nspkg / engine / filesystem.v
48 lines · 43 sloc · 1.51 KB · c01b0795d1db56c7bce2539b2c46b110637fdc1a
Raw
1// directory modes follow pacman util.c, independent of the caller's umask.
2// SPDX-License-Identifier: GPL-2.0-or-later
3module engine
4
5import os
6
7fn C.umask(u32) u32
8fn C.fchmod(i32, u32) i32
9
10fn make_directory_mode(path string, mode u32) ! {
11 old_mask := C.umask(0)
12 defer { C.umask(old_mask) }
13 mut current := if path.starts_with('/') { '/' } else { '' }
14 for component in path.split('/') {
15 if component == '' { continue }
16 current += component
17 status := unsafe { C.mkdir(&char(current.str), mode) }
18 if status != 0 && C.errno != C.EEXIST { return os.last_error() }
19 current += '/'
20 }
21}
22
23fn (mut handle Handle) remove_temporary_file(path string) {
24 if C.unlink(unsafe { &char(path.str) }) != 0 && C.errno != C.ENOENT {
25 handle.diagnostics << 'could not remove ${path}: ${os.last_error().msg()}'
26 }
27}
28
29fn (mut handle Handle) temporary_download_name(directory string) !string {
30 mut pattern := (directory + 'alpmtmp.XXXXXX\x00').bytes()
31 fd := C.mkstemp(pattern.data)
32 if fd < 0 { return handle.fail(.retrieve, os.last_error().msg()) }
33 path := pattern[..pattern.len - 1].bytestr()
34 mut keep := false
35 defer { if !keep { handle.remove_temporary_file(path) } }
36 mask := C.umask(0)
37 C.umask(mask)
38 if C.fchmod(fd, ~mask & u32(0o666)) != 0 {
39 problem := os.last_error()
40 if C.close(fd) != 0 {
41 handle.diagnostics << 'could not close temporary download: ${os.last_error().msg()}'
42 }
43 return handle.fail(.retrieve, problem.msg())
44 }
45 if C.close(fd) != 0 { return handle.fail(.retrieve, os.last_error().msg()) }
46 keep = true
47 return path
48}
49