v2 / vlib / os / inode.c.v
74 lines · 67 sloc · 1.69 KB · 37255767290c243b71f0e78d77c3bd5e875748e6
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module os
5
6pub struct FileMode {
7pub:
8 typ FileType
9 owner FilePermission
10 group FilePermission
11 others FilePermission
12}
13
14pub struct FileInfo {
15 FileMode
16pub:
17 size u64 // size of the file in bytes
18 mtime i64 // last modification time in seconds after the Unix epoch
19}
20
21pub enum FileType {
22 unknown
23 regular
24 directory
25 character_device
26 block_device
27 fifo
28 symbolic_link
29 socket
30}
31
32pub struct FilePermission {
33pub:
34 read bool
35 write bool
36 execute bool
37}
38
39// bitmask returns a 3 bit sequence in the order RWE, where the bit is set to 1 if the value is true or 0 otherwise.
40pub fn (p FilePermission) bitmask() u32 {
41 mut mask := u32(0)
42 if p.read {
43 mask |= 4
44 }
45 if p.write {
46 mask |= 2
47 }
48 if p.execute {
49 mask |= 1
50 }
51 return mask
52}
53
54// bitmask returns a 9 bit sequence in the order owner + group + others.
55// This is a valid bitmask to use with `os.chmod`.
56pub fn (m FileMode) bitmask() u32 {
57 return m.owner.bitmask() << 6 | m.group.bitmask() << 3 | m.others.bitmask()
58}
59
60// inode returns the metadata of the file/inode, containing inode type, permission information, size and modification time.
61// It supports Windows for regular files, but it doesn't matter if you use owner, group or others when checking permissions on Windows.
62// if a symlink is targeted, it returns info on the link, not the target.
63pub fn inode(path string) FileInfo {
64 attr := lstat(path) or { Stat{} }
65 fm := attr.get_mode()
66 return FileInfo{
67 typ: fm.typ
68 owner: fm.owner
69 group: fm.group
70 others: fm.others
71 size: attr.size
72 mtime: attr.mtime
73 }
74}
75