os: format os.v (#7334)

pull/7342/head
yuyi 2020-12-15 15:33:31 +08:00 committed by GitHub
parent 3064fff95b
commit 947ceb1595
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 214 additions and 284 deletions

View File

@ -10,7 +10,7 @@ pub const (
// read_bytes returns all bytes read from file in `path`. // read_bytes returns all bytes read from file in `path`.
pub fn read_bytes(path string) ?[]byte { pub fn read_bytes(path string) ?[]byte {
mut fp := vfopen(path, 'rb')? mut fp := vfopen(path, 'rb') ?
cseek := C.fseek(fp, 0, C.SEEK_END) cseek := C.fseek(fp, 0, C.SEEK_END)
if cseek != 0 { if cseek != 0 {
return error('fseek failed') return error('fseek failed')
@ -29,12 +29,13 @@ pub fn read_bytes(path string) ?[]byte {
return res[0..nr_read_elements * fsize] return res[0..nr_read_elements * fsize]
} }
// read_file reads the file in `path` and returns the contents. // read_file reads the file in `path` and returns the contents.
pub fn read_file(path string) ?string { pub fn read_file(path string) ?string {
mode := 'rb' mode := 'rb'
mut fp := vfopen(path, mode)? mut fp := vfopen(path, mode) ?
defer { C.fclose(fp) } defer {
C.fclose(fp)
}
cseek := C.fseek(fp, 0, C.SEEK_END) cseek := C.fseek(fp, 0, C.SEEK_END)
if cseek != 0 { if cseek != 0 {
return error('fseek failed') return error('fseek failed')
@ -57,7 +58,7 @@ pub fn read_file(path string) ?string {
} }
} }
//***************************** OS ops ************************ // ***************************** OS ops ************************
// file_size returns the size of the file located in `path`. // file_size returns the size of the file located in `path`.
pub fn file_size(path string) int { pub fn file_size(path string) int {
mut s := C.stat{} mut s := C.stat{}
@ -79,7 +80,7 @@ pub fn file_size(path string) int {
pub fn mv(src string, dst string) { pub fn mv(src string, dst string) {
mut rdst := dst mut rdst := dst
if is_dir(rdst) { if is_dir(rdst) {
rdst = join_path(rdst.trim_right(path_separator),file_name(src.trim_right(path_separator))) rdst = join_path(rdst.trim_right(path_separator), file_name(src.trim_right(path_separator)))
} }
$if windows { $if windows {
w_src := src.replace('/', '\\') w_src := src.replace('/', '\\')
@ -107,13 +108,14 @@ pub fn cp(src string, dst string) ? {
fp_to := C.open(charptr(dst.str), C.O_WRONLY | C.O_CREAT | C.O_TRUNC, C.S_IWUSR | C.S_IRUSR) fp_to := C.open(charptr(dst.str), C.O_WRONLY | C.O_CREAT | C.O_TRUNC, C.S_IWUSR | C.S_IRUSR)
if fp_to < 0 { // Check if file opened (permissions problems ...) if fp_to < 0 { // Check if file opened (permissions problems ...)
C.close(fp_from) C.close(fp_from)
return error_with_code('cp (permission): failed to write to $dst (fp_to: $fp_to)', int(fp_to)) return error_with_code('cp (permission): failed to write to $dst (fp_to: $fp_to)',
int(fp_to))
} }
mut buf := [1024]byte{} mut buf := [1024]byte{}
mut count := 0 mut count := 0
for { for {
// FIXME: use sizeof, bug: 'os__buf' undeclared // FIXME: use sizeof, bug: 'os__buf' undeclared
//count = C.read(fp_from, buf, sizeof(buf)) // count = C.read(fp_from, buf, sizeof(buf))
count = C.read(fp_from, buf, 1024) count = C.read(fp_from, buf, 1024)
if count == 0 { if count == 0 {
break break
@ -123,9 +125,7 @@ pub fn cp(src string, dst string) ? {
} }
} }
from_attr := C.stat{} from_attr := C.stat{}
unsafe { unsafe {C.stat(charptr(src.str), &from_attr)}
C.stat(charptr(src.str), &from_attr)
}
if C.chmod(charptr(dst.str), from_attr.st_mode) < 0 { if C.chmod(charptr(dst.str), from_attr.st_mode) < 0 {
return error_with_code('failed to set permissions for $dst', int(-1)) return error_with_code('failed to set permissions for $dst', int(-1))
} }
@ -143,38 +143,36 @@ pub fn cp_r(osource_path string, odest_path string, overwrite bool) ? {
// cp_all will recursively copy `src` to `dst`, // cp_all will recursively copy `src` to `dst`,
// optionally overwriting files or dirs in `dst`. // optionally overwriting files or dirs in `dst`.
pub fn cp_all(src string, dst string, overwrite bool) ? { pub fn cp_all(src string, dst string, overwrite bool) ? {
source_path := os.real_path(src) source_path := real_path(src)
dest_path := os.real_path(dst) dest_path := real_path(dst)
if !os.exists(source_path) { if !exists(source_path) {
return error("Source path doesn\'t exist") return error("Source path doesn\'t exist")
} }
// single file copy // single file copy
if !os.is_dir(source_path) { if !is_dir(source_path) {
adjusted_path := if os.is_dir(dest_path) { adjusted_path := if is_dir(dest_path) { join_path(dest_path, file_name(source_path)) } else { dest_path }
os.join_path(dest_path,os.file_name(source_path)) } else { dest_path } if exists(adjusted_path) {
if os.exists(adjusted_path) {
if overwrite { if overwrite {
os.rm(adjusted_path) rm(adjusted_path)
} } else {
else {
return error('Destination file path already exist') return error('Destination file path already exist')
} }
} }
os.cp(source_path, adjusted_path)? cp(source_path, adjusted_path) ?
return return
} }
if !os.is_dir(dest_path) { if !is_dir(dest_path) {
return error('Destination path is not a valid directory') return error('Destination path is not a valid directory')
} }
files := os.ls(source_path)? files := ls(source_path) ?
for file in files { for file in files {
sp := os.join_path(source_path, file) sp := join_path(source_path, file)
dp := os.join_path(dest_path, file) dp := join_path(dest_path, file)
if os.is_dir(sp) { if is_dir(sp) {
os.mkdir(dp)? mkdir(dp) ?
} }
cp_all(sp, dp, overwrite) or { cp_all(sp, dp, overwrite) or {
os.rmdir(dp) rmdir(dp)
return error(err) return error(err)
} }
} }
@ -183,8 +181,8 @@ os.join_path(dest_path,os.file_name(source_path)) } else { dest_path }
// mv_by_cp first copies the source file, and if it is copied successfully, deletes the source file. // mv_by_cp first copies the source file, and if it is copied successfully, deletes the source file.
// may be used when you are not sure that the source and target are on the same mount/partition. // may be used when you are not sure that the source and target are on the same mount/partition.
pub fn mv_by_cp(source string, target string) ? { pub fn mv_by_cp(source string, target string) ? {
os.cp(source, target)? cp(source, target) ?
os.rm(source)? rm(source) ?
} }
// vfopen returns an opened C file, given its path and open mode. // vfopen returns an opened C file, given its path and open mode.
@ -222,13 +220,13 @@ pub fn fileno(cfile voidptr) int {
// read_lines reads the file in `path` into an array of lines. // read_lines reads the file in `path` into an array of lines.
pub fn read_lines(path string) ?[]string { pub fn read_lines(path string) ?[]string {
buf := read_file(path)? buf := read_file(path) ?
return buf.split_into_lines() return buf.split_into_lines()
} }
// read_ulines reads the file in `path` into an array of ustring lines. // read_ulines reads the file in `path` into an array of ustring lines.
fn read_ulines(path string) ?[]ustring { fn read_ulines(path string) ?[]ustring {
lines := read_lines(path)? lines := read_lines(path) ?
// mut ulines := new_array(0, lines.len, sizeof(ustring)) // mut ulines := new_array(0, lines.len, sizeof(ustring))
mut ulines := []ustring{} mut ulines := []ustring{}
for myline in lines { for myline in lines {
@ -276,36 +274,29 @@ pub fn open_file(path string, mode string, options ...int) ?File {
else {} else {}
} }
} }
mut permission := 0o666 mut permission := 0o666
if options.len > 0 { if options.len > 0 {
permission = options[0] permission = options[0]
} }
$if windows { $if windows {
if permission < 0o600 { if permission < 0o600 {
permission = 0x0100 permission = 0x0100
} } else {
else {
permission = 0x0100 | 0x0080 permission = 0x0100 | 0x0080
} }
} }
mut p := path mut p := path
$if windows { $if windows {
p = path.replace('/', '\\') p = path.replace('/', '\\')
} }
fd := C.open(charptr(p.str), flags, permission) fd := C.open(charptr(p.str), flags, permission)
if fd == -1 { if fd == -1 {
return error(posix_get_error_msg(C.errno)) return error(posix_get_error_msg(C.errno))
} }
cfile := C.fdopen(fd, charptr(mode.str)) cfile := C.fdopen(fd, charptr(mode.str))
if isnil(cfile) { if isnil(cfile) {
return error('Failed to open or create file "$path"') return error('Failed to open or create file "$path"')
} }
return File{ return File{
cfile: cfile cfile: cfile
fd: fd fd: fd
@ -326,9 +317,9 @@ fn vpopen(path string) voidptr {
} }
} }
fn posix_wait4_to_exit_status(waitret int) (int,bool) { fn posix_wait4_to_exit_status(waitret int) (int, bool) {
$if windows { $if windows {
return waitret,false return waitret, false
} $else { } $else {
mut ret := 0 mut ret := 0
mut is_signaled := true mut is_signaled := true
@ -336,12 +327,11 @@ fn posix_wait4_to_exit_status(waitret int) (int,bool) {
if C.WIFEXITED(waitret) { if C.WIFEXITED(waitret) {
ret = C.WEXITSTATUS(waitret) ret = C.WEXITSTATUS(waitret)
is_signaled = false is_signaled = false
} } else if C.WIFSIGNALED(waitret) {
else if C.WIFSIGNALED(waitret) {
ret = C.WTERMSIG(waitret) ret = C.WTERMSIG(waitret)
is_signaled = true is_signaled = true
} }
return ret,is_signaled return ret, is_signaled
} }
} }
@ -359,7 +349,7 @@ fn vpclose(f voidptr) int {
$if windows { $if windows {
return C._pclose(f) return C._pclose(f)
} $else { } $else {
ret,_ := posix_wait4_to_exit_status(C.pclose(f)) ret, _ := posix_wait4_to_exit_status(C.pclose(f))
return ret return ret
} }
} }
@ -387,7 +377,7 @@ pub fn system(cmd string) int {
} $else { } $else {
$if ios { $if ios {
unsafe { unsafe {
arg := [ c'/bin/sh', c'-c', byteptr(cmd.str), 0 ] arg := [c'/bin/sh', c'-c', byteptr(cmd.str), 0]
pid := 0 pid := 0
ret = C.posix_spawn(&pid, '/bin/sh', 0, 0, arg.data, 0) ret = C.posix_spawn(&pid, '/bin/sh', 0, 0, arg.data, 0)
status := 0 status := 0
@ -406,7 +396,7 @@ pub fn system(cmd string) int {
print_c_errno() print_c_errno()
} }
$if !windows { $if !windows {
pret,is_signaled := posix_wait4_to_exit_status(ret) pret, is_signaled := posix_wait4_to_exit_status(ret)
if is_signaled { if is_signaled {
println('Terminated by signal ${ret:2d} (' + sigint_to_signal_name(pret) + ')') println('Terminated by signal ${ret:2d} (' + sigint_to_signal_name(pret) + ')')
} }
@ -419,39 +409,17 @@ pub fn system(cmd string) int {
pub fn sigint_to_signal_name(si int) string { pub fn sigint_to_signal_name(si int) string {
// POSIX signals: // POSIX signals:
match si { match si {
1 { 1 { return 'SIGHUP' }
return 'SIGHUP' 2 { return 'SIGINT' }
} 3 { return 'SIGQUIT' }
2 { 4 { return 'SIGILL' }
return 'SIGINT' 6 { return 'SIGABRT' }
} 8 { return 'SIGFPE' }
3 { 9 { return 'SIGKILL' }
return 'SIGQUIT' 11 { return 'SIGSEGV' }
} 13 { return 'SIGPIPE' }
4 { 14 { return 'SIGALRM' }
return 'SIGILL' 15 { return 'SIGTERM' }
}
6 {
return 'SIGABRT'
}
8 {
return 'SIGFPE'
}
9 {
return 'SIGKILL'
}
11 {
return 'SIGSEGV'
}
13 {
return 'SIGPIPE'
}
14 {
return 'SIGALRM'
}
15 {
return 'SIGTERM'
}
else {} else {}
} }
$if linux { $if linux {
@ -459,37 +427,17 @@ pub fn sigint_to_signal_name(si int) string {
match si { match si {
// TODO dependent on platform // TODO dependent on platform
// works only on x86/ARM/most others // works only on x86/ARM/most others
10 /*, 30, 16 */ { 10 /* , 30, 16 */ { return 'SIGUSR1' }
return 'SIGUSR1' 12 /* , 31, 17 */ { return 'SIGUSR2' }
} 17 /* , 20, 18 */ { return 'SIGCHLD' }
12 /*, 31, 17 */ { 18 /* , 19, 25 */ { return 'SIGCONT' }
return 'SIGUSR2' 19 /* , 17, 23 */ { return 'SIGSTOP' }
} 20 /* , 18, 24 */ { return 'SIGTSTP' }
17 /*, 20, 18 */ { 21 /* , 26 */ { return 'SIGTTIN' }
return 'SIGCHLD' 22 /* , 27 */ { return 'SIGTTOU' }
}
18 /*, 19, 25 */ {
return 'SIGCONT'
}
19 /*, 17, 23 */ {
return 'SIGSTOP'
}
20 /*, 18, 24 */ {
return 'SIGTSTP'
}
21 /*, 26 */ {
return 'SIGTTIN'
}
22 /*, 27 */ {
return 'SIGTTOU'
}
// ///////////////////////////// // /////////////////////////////
5 { 5 { return 'SIGTRAP' }
return 'SIGTRAP' 7 { return 'SIGBUS' }
}
7 {
return 'SIGBUS'
}
else {} else {}
} }
} }
@ -522,8 +470,8 @@ pub fn is_executable(path string) bool {
// 02 Write-only // 02 Write-only
// 04 Read-only // 04 Read-only
// 06 Read and write // 06 Read and write
p := os.real_path( path ) p := real_path(path)
return ( os.exists( p ) && p.ends_with('.exe') ) return (exists(p) && p.ends_with('.exe'))
} }
$if solaris { $if solaris {
statbuf := C.stat{} statbuf := C.stat{}
@ -532,7 +480,7 @@ pub fn is_executable(path string) bool {
return false return false
} }
} }
return (int(statbuf.st_mode) & ( s_ixusr | s_ixgrp | s_ixoth )) != 0 return (int(statbuf.st_mode) & (s_ixusr | s_ixgrp | s_ixoth)) != 0
} }
return C.access(charptr(path.str), x_ok) != -1 return C.access(charptr(path.str), x_ok) != -1
} }
@ -568,7 +516,7 @@ pub fn rm(path string) ? {
$if windows { $if windows {
rc := C._wremove(path.to_wide()) rc := C._wremove(path.to_wide())
if rc == -1 { if rc == -1 {
//TODO: proper error as soon as it's supported on windows // TODO: proper error as soon as it's supported on windows
return error('Failed to remove "$path"') return error('Failed to remove "$path"')
} }
} $else { } $else {
@ -605,14 +553,14 @@ pub fn rmdir_recursive(path string) {
// rmdir_all recursively removes the specified directory. // rmdir_all recursively removes the specified directory.
pub fn rmdir_all(path string) ? { pub fn rmdir_all(path string) ? {
mut ret_err := '' mut ret_err := ''
items := os.ls(path)? items := ls(path) ?
for item in items { for item in items {
if os.is_dir(os.join_path(path, item)) { if is_dir(join_path(path, item)) {
rmdir_all(os.join_path(path, item)) rmdir_all(join_path(path, item))
} }
os.rm(os.join_path(path, item)) or { ret_err = err } rm(join_path(path, item)) or { ret_err = err }
} }
os.rmdir(path) or { ret_err = err } rmdir(path) or { ret_err = err }
if ret_err.len > 0 { if ret_err.len > 0 {
return error(ret_err) return error(ret_err)
} }
@ -620,9 +568,7 @@ pub fn rmdir_all(path string) ? {
// is_dir_empty will return a `bool` whether or not `path` is empty. // is_dir_empty will return a `bool` whether or not `path` is empty.
pub fn is_dir_empty(path string) bool { pub fn is_dir_empty(path string) bool {
items := os.ls(path) or { items := ls(path) or { return true }
return true
}
return items.len == 0 return items.len == 0
} }
@ -636,9 +582,7 @@ fn print_c_errno() {
// file_ext will return the part after the last occurence of `.` in `path`. // file_ext will return the part after the last occurence of `.` in `path`.
// The `.` is included. // The `.` is included.
pub fn file_ext(path string) string { pub fn file_ext(path string) string {
pos := path.last_index('.') or { pos := path.last_index('.') or { return '' }
return ''
}
return path[pos..] return path[pos..]
} }
@ -651,9 +595,7 @@ pub fn dir(path string) string {
if path == '' { if path == '' {
return '.' return '.'
} }
pos := path.last_index(path_separator) or { pos := path.last_index(path_separator) or { return '.' }
return '.'
}
return path[..pos] return path[..pos]
} }
@ -669,16 +611,12 @@ pub fn base(path string) string {
return path_separator return path_separator
} }
if path.ends_with(path_separator) { if path.ends_with(path_separator) {
path2 := path[..path.len-1] path2 := path[..path.len - 1]
pos := path2.last_index(path_separator) or { pos := path2.last_index(path_separator) or { return path2.clone() }
return path2.clone() return path2[pos + 1..]
} }
return path2[pos+1..] pos := path.last_index(path_separator) or { return path.clone() }
} return path[pos + 1..]
pos := path.last_index(path_separator) or {
return path.clone()
}
return path[pos+1..]
} }
// file_name will return all characters found after the last occurence of `path_separator`. // file_name will return all characters found after the last occurence of `path_separator`.
@ -713,7 +651,8 @@ pub fn get_raw_line() string {
h_input := C.GetStdHandle(std_input_handle) h_input := C.GetStdHandle(std_input_handle)
mut bytes_read := 0 mut bytes_read := 0
if is_atty(0) > 0 { if is_atty(0) > 0 {
C.ReadConsole(h_input, buf, max_line_chars * 2, C.LPDWORD(&bytes_read), 0) C.ReadConsole(h_input, buf, max_line_chars * 2, C.LPDWORD(&bytes_read),
0)
return string_from_wide2(&u16(buf), bytes_read) return string_from_wide2(&u16(buf), bytes_read)
} }
mut offset := 0 mut offset := 0
@ -735,13 +674,13 @@ pub fn get_raw_line() string {
max := size_t(0) max := size_t(0)
mut buf := charptr(0) mut buf := charptr(0)
nr_chars := C.getline(&buf, &max, C.stdin) nr_chars := C.getline(&buf, &max, C.stdin)
//defer { unsafe{ free(buf) } } // defer { unsafe{ free(buf) } }
if nr_chars == 0 || nr_chars == -1 { if nr_chars == 0 || nr_chars == -1 {
return '' return ''
} }
return tos3(buf) return tos3(buf)
//res := tos_clone(buf) // res := tos_clone(buf)
//return res // return res
} }
} }
@ -758,17 +697,18 @@ pub fn get_raw_stdin() []byte {
pos := buf + offset pos := buf + offset
res := C.ReadFile(h_input, pos, block_bytes, C.LPDWORD(&bytes_read), 0) res := C.ReadFile(h_input, pos, block_bytes, C.LPDWORD(&bytes_read), 0)
offset += bytes_read offset += bytes_read
if !res { if !res {
break break
} }
buf = v_realloc(buf, offset + block_bytes + (block_bytes - bytes_read))
buf = v_realloc(buf, offset + block_bytes + (block_bytes-bytes_read))
} }
C.CloseHandle(h_input) C.CloseHandle(h_input)
return array{
return array{element_size: 1 data: voidptr(buf) len: offset cap: offset } element_size: 1
data: voidptr(buf)
len: offset
cap: offset
}
} }
} $else { } $else {
panic('get_raw_stdin not implemented on this platform...') panic('get_raw_stdin not implemented on this platform...')
@ -845,25 +785,25 @@ pub fn user_os() string {
// home_dir returns path to user's home directory. // home_dir returns path to user's home directory.
pub fn home_dir() string { pub fn home_dir() string {
$if windows { $if windows {
return os.getenv('USERPROFILE') return getenv('USERPROFILE')
} $else { } $else {
//println('home_dir() call') // println('home_dir() call')
//res:= os.getenv('HOME') // res:= os.getenv('HOME')
//println('res="$res"') // println('res="$res"')
return os.getenv('HOME') return getenv('HOME')
} }
} }
// write_file writes `text` data to a file in `path`. // write_file writes `text` data to a file in `path`.
pub fn write_file(path string, text string) ? { pub fn write_file(path string, text string) ? {
mut f := os.create(path)? mut f := create(path) ?
f.write(text.bytes()) f.write(text.bytes())
f.close() f.close()
} }
// write_file_array writes the data in `buffer` to a file in `path`. // write_file_array writes the data in `buffer` to a file in `path`.
pub fn write_file_array(path string, buffer array) ? { pub fn write_file_array(path string, buffer array) ? {
mut f := os.create(path)? mut f := create(path) ?
f.write_bytes_at(buffer.data, (buffer.len * buffer.element_size), 0) f.write_bytes_at(buffer.data, (buffer.len * buffer.element_size), 0)
f.close() f.close()
} }
@ -882,7 +822,12 @@ pub fn read_file_array<T>(path string) []T {
buf := malloc(fsize) buf := malloc(fsize)
C.fread(buf, fsize, 1, fp) C.fread(buf, fsize, 1, fp)
C.fclose(fp) C.fclose(fp)
return array{element_size: tsize data: buf len: len cap: len } return array{
element_size: tsize
data: buf
len: len
cap: len
}
} }
pub fn on_segfault(f voidptr) { pub fn on_segfault(f voidptr) {
@ -890,7 +835,7 @@ pub fn on_segfault(f voidptr) {
return return
} }
$if macos { $if macos {
C.printf("TODO") C.printf('TODO')
/* /*
mut sa := C.sigaction{} mut sa := C.sigaction{}
C.memset(&sa, 0, sizeof(C.sigaction_size)) C.memset(&sa, 0, sizeof(C.sigaction_size))
@ -912,7 +857,7 @@ pub fn executable() string {
eprintln('os.executable() failed at reading /proc/self/exe to get exe path') eprintln('os.executable() failed at reading /proc/self/exe to get exe path')
return executable_fallback() return executable_fallback()
} }
return unsafe { result.vstring() } return unsafe {result.vstring()}
} }
$if windows { $if windows {
max := 512 max := 512
@ -933,8 +878,7 @@ pub fn executable() string {
ret := string_from_wide2(final_path, final_len) ret := string_from_wide2(final_path, final_len)
// remove '\\?\' from beginning (see link above) // remove '\\?\' from beginning (see link above)
return ret[4..] return ret[4..]
} } else {
else {
eprintln('os.executable() saw that the executable file path was too long') eprintln('os.executable() saw that the executable file path was too long')
} }
} }
@ -950,21 +894,22 @@ pub fn executable() string {
eprintln('os.executable() failed at calling proc_pidpath with pid: $pid . proc_pidpath returned $ret ') eprintln('os.executable() failed at calling proc_pidpath with pid: $pid . proc_pidpath returned $ret ')
return executable_fallback() return executable_fallback()
} }
return unsafe { result.vstring() } return unsafe {result.vstring()}
} }
$if freebsd { $if freebsd {
mut result := vcalloc(max_path_len) mut result := vcalloc(max_path_len)
mib := [1/* CTL_KERN */, 14/* KERN_PROC */, 12/* KERN_PROC_PATHNAME */, -1] mib := [1 /* CTL_KERN */, 14 /* KERN_PROC */, 12 /* KERN_PROC_PATHNAME */, -1]
size := max_path_len size := max_path_len
unsafe { unsafe {C.sysctl(mib.data, 4, result, &size, 0, 0)}
C.sysctl(mib.data, 4, result, &size, 0, 0) return unsafe {result.vstring()}
}
return unsafe { result.vstring() }
} }
// "Sadly there is no way to get the full path of the executed file in OpenBSD." // "Sadly there is no way to get the full path of the executed file in OpenBSD."
$if openbsd {} $if openbsd {
$if solaris {} }
$if haiku {} $if solaris {
}
$if haiku {
}
$if netbsd { $if netbsd {
mut result := vcalloc(max_path_len) mut result := vcalloc(max_path_len)
count := C.readlink('/proc/curproc/exe', charptr(result), max_path_len) count := C.readlink('/proc/curproc/exe', charptr(result), max_path_len)
@ -972,7 +917,7 @@ pub fn executable() string {
eprintln('os.executable() failed at reading /proc/curproc/exe to get exe path') eprintln('os.executable() failed at reading /proc/curproc/exe to get exe path')
return executable_fallback() return executable_fallback()
} }
return unsafe { result.vstring_with_len(count) } return unsafe {result.vstring_with_len(count)}
} }
$if dragonfly { $if dragonfly {
mut result := vcalloc(max_path_len) mut result := vcalloc(max_path_len)
@ -981,7 +926,7 @@ pub fn executable() string {
eprintln('os.executable() failed at reading /proc/curproc/file to get exe path') eprintln('os.executable() failed at reading /proc/curproc/file to get exe path')
return executable_fallback() return executable_fallback()
} }
return unsafe { result.vstring_with_len(count) } return unsafe {result.vstring_with_len(count)}
} }
return executable_fallback() return executable_fallback()
} }
@ -990,57 +935,55 @@ pub fn executable() string {
// It relies on path manipulation of os.args[0] and os.wd_at_startup, so it may not work properly in // It relies on path manipulation of os.args[0] and os.wd_at_startup, so it may not work properly in
// all cases, but it should be better, than just using os.args[0] directly. // all cases, but it should be better, than just using os.args[0] directly.
fn executable_fallback() string { fn executable_fallback() string {
if os.args.len == 0 { if args.len == 0 {
// we are early in the bootstrap, os.args has not been initialized yet :-| // we are early in the bootstrap, os.args has not been initialized yet :-|
return '' return ''
} }
mut exepath := os.args[0] mut exepath := args[0]
$if windows { $if windows {
if !exepath.contains('.exe') { if !exepath.contains('.exe') {
exepath += '.exe' exepath += '.exe'
} }
} }
if !os.is_abs_path(exepath) { if !is_abs_path(exepath) {
if exepath.contains( os.path_separator ) { if exepath.contains(path_separator) {
exepath = os.join_path(os.wd_at_startup, exepath) exepath = join_path(wd_at_startup, exepath)
}else{ } else {
// no choice but to try to walk the PATH folders :-| ... // no choice but to try to walk the PATH folders :-| ...
foundpath := os.find_abs_path_of_executable(exepath) or { '' } foundpath := find_abs_path_of_executable(exepath) or { '' }
if foundpath.len > 0 { if foundpath.len > 0 {
exepath = foundpath exepath = foundpath
} }
} }
} }
exepath = os.real_path(exepath) exepath = real_path(exepath)
return exepath return exepath
} }
// find_exe_path walks the environment PATH, just like most shell do, it returns // find_exe_path walks the environment PATH, just like most shell do, it returns
// the absolute path of the executable if found // the absolute path of the executable if found
pub fn find_abs_path_of_executable(exepath string) ?string { pub fn find_abs_path_of_executable(exepath string) ?string {
if os.is_abs_path(exepath) { if is_abs_path(exepath) {
return os.real_path(exepath) return real_path(exepath)
} }
mut res := '' mut res := ''
paths := os.getenv('PATH').split(path_delimiter) paths := getenv('PATH').split(path_delimiter)
for p in paths { for p in paths {
found_abs_path := os.join_path( p, exepath ) found_abs_path := join_path(p, exepath)
if os.exists( found_abs_path ) && os.is_executable( found_abs_path ) { if exists(found_abs_path) && is_executable(found_abs_path) {
res = found_abs_path res = found_abs_path
break break
} }
} }
if res.len>0 { if res.len > 0 {
return os.real_path(res) return real_path(res)
} }
return error('failed to find executable') return error('failed to find executable')
} }
// exists_in_system_path returns `true` if `prog` exists in the system's PATH // exists_in_system_path returns `true` if `prog` exists in the system's PATH
pub fn exists_in_system_path(prog string) bool { pub fn exists_in_system_path(prog string) bool {
os.find_abs_path_of_executable(prog) or { find_abs_path_of_executable(prog) or { return false }
return false
}
return true return true
} }
@ -1068,7 +1011,7 @@ pub fn is_dir(path string) bool {
return false return false
} }
// ref: https://code.woboq.org/gcc/include/sys/stat.h.html // ref: https://code.woboq.org/gcc/include/sys/stat.h.html
val:= int(statbuf.st_mode) & os.s_ifmt val := int(statbuf.st_mode) & s_ifmt
return val == s_ifdir return val == s_ifdir
} }
} }
@ -1114,7 +1057,7 @@ pub fn getwd() string {
if C.getcwd(charptr(buf), 512) == 0 { if C.getcwd(charptr(buf), 512) == 0 {
return '' return ''
} }
return unsafe { buf.vstring() } return unsafe {buf.vstring()}
} }
} }
@ -1137,7 +1080,7 @@ pub fn real_path(fpath string) string {
return fpath return fpath
} }
} }
res := unsafe { fullpath.vstring() } res := unsafe {fullpath.vstring()}
return normalize_drive_letter(res) return normalize_drive_letter(res)
} }
@ -1148,7 +1091,8 @@ fn normalize_drive_letter(path string) string {
$if !windows { $if !windows {
return path return path
} }
if path.len > 2 && path[0] >= `a` && path[0] <= `z` && path[1] == `:` && path[2] == os.path_separator[0] { if path.len > 2 &&
path[0] >= `a` && path[0] <= `z` && path[1] == `:` && path[2] == path_separator[0] {
unsafe { unsafe {
x := &path.str[0] x := &path.str[0]
(*x) = *x - 32 (*x) = *x - 32
@ -1157,7 +1101,6 @@ fn normalize_drive_letter(path string) string {
return path return path
} }
// is_abs_path returns `true` if `path` is absolute. // is_abs_path returns `true` if `path` is absolute.
pub fn is_abs_path(path string) bool { pub fn is_abs_path(path string) bool {
$if windows { $if windows {
@ -1179,23 +1122,20 @@ pub fn join_path(base string, dirs ...string) string {
// walk_ext returns a recursive list of all files in `path` ending with `ext`. // walk_ext returns a recursive list of all files in `path` ending with `ext`.
pub fn walk_ext(path string, ext string) []string { pub fn walk_ext(path string, ext string) []string {
if !os.is_dir(path) { if !is_dir(path) {
return []
}
mut files := os.ls(path) or {
return [] return []
} }
mut files := ls(path) or { return [] }
mut res := []string{} mut res := []string{}
separator := if path.ends_with(os.path_separator) { '' } else { os.path_separator } separator := if path.ends_with(path_separator) { '' } else { path_separator }
for file in files { for file in files {
if file.starts_with('.') { if file.starts_with('.') {
continue continue
} }
p := path + separator + file p := path + separator + file
if os.is_dir(p) && !os.is_link(p) { if is_dir(p) && !is_link(p) {
res << walk_ext(p, ext) res << walk_ext(p, ext)
} } else if file.ends_with(ext) {
else if file.ends_with(ext) {
res << p res << p
} }
} }
@ -1204,30 +1144,25 @@ pub fn walk_ext(path string, ext string) []string {
// walk recursively traverses the given directory `path`. // walk recursively traverses the given directory `path`.
// When a file is encountred it will call the callback function with current file as argument. // When a file is encountred it will call the callback function with current file as argument.
pub fn walk(path string, f fn(path string)) { pub fn walk(path string, f fn (string)) {
if !os.is_dir(path) { if !is_dir(path) {
return
}
mut files := os.ls(path) or {
return return
} }
mut files := ls(path) or { return }
for file in files { for file in files {
p := path + os.path_separator + file p := path + path_separator + file
if os.is_dir(p) && !os.is_link(p) { if is_dir(p) && !is_link(p) {
walk(p, f) walk(p, f)
} } else if exists(p) {
else if os.exists(p) {
f(p) f(p)
} }
} }
return return
} }
[unsafe] // signal will assign `handler` callback to be called when `signum` signal is recieved. // signal will assign `handler` callback to be called when `signum` signal is recieved.
pub fn signal(signum int, handler voidptr) { pub fn signal(signum int, handler voidptr) {
unsafe { unsafe {C.signal(signum, handler)}
C.signal(signum, handler)
}
} }
// fork will fork the current system process and return the pid of the fork. // fork will fork the current system process and return the pid of the fork.
@ -1259,9 +1194,7 @@ pub fn wait() int {
pub fn file_last_mod_unix(path string) int { pub fn file_last_mod_unix(path string) int {
attr := C.stat{} attr := C.stat{}
// # struct stat attr; // # struct stat attr;
unsafe { unsafe {C.stat(charptr(path.str), &attr)}
C.stat(charptr(path.str), &attr)
}
// # stat(path.str, &attr); // # stat(path.str, &attr);
return attr.st_mtime return attr.st_mtime
// # return attr.st_mtime ; // # return attr.st_mtime ;
@ -1285,16 +1218,14 @@ pub fn flush() {
// mkdir_all will create a valid full path of all directories given in `path`. // mkdir_all will create a valid full path of all directories given in `path`.
pub fn mkdir_all(path string) ? { pub fn mkdir_all(path string) ? {
mut p := if path.starts_with(os.path_separator) { os.path_separator } else { '' } mut p := if path.starts_with(path_separator) { path_separator } else { '' }
path_parts := path.trim_left(os.path_separator).split(os.path_separator) path_parts := path.trim_left(path_separator).split(path_separator)
for subdir in path_parts { for subdir in path_parts {
p += subdir + os.path_separator p += subdir + path_separator
if os.exists(p) && os.is_dir(p) { if exists(p) && is_dir(p) {
continue continue
} }
os.mkdir(p) or { mkdir(p) or { return error('folder: $p, error: $err') }
return error('folder: $p, error: $err')
}
} }
} }
@ -1308,31 +1239,29 @@ pub fn cache_dir() string {
// non-essential data files should be stored. If $XDG_CACHE_HOME is either not set // non-essential data files should be stored. If $XDG_CACHE_HOME is either not set
// or empty, a default equal to $HOME/.cache should be used. // or empty, a default equal to $HOME/.cache should be used.
$if !windows { $if !windows {
xdg_cache_home := os.getenv('XDG_CACHE_HOME') xdg_cache_home := getenv('XDG_CACHE_HOME')
if xdg_cache_home != '' { if xdg_cache_home != '' {
return xdg_cache_home return xdg_cache_home
} }
} }
cdir := os.join_path(os.home_dir(), '.cache') cdir := join_path(home_dir(), '.cache')
if !os.is_dir(cdir) && !os.is_link(cdir) { if !is_dir(cdir) && !is_link(cdir) {
os.mkdir(cdir) or { mkdir(cdir) or { panic(err) }
panic(err)
}
} }
return cdir return cdir
} }
// temp_dir returns the path to a folder, that is suitable for storing temporary files. // temp_dir returns the path to a folder, that is suitable for storing temporary files.
pub fn temp_dir() string { pub fn temp_dir() string {
mut path := os.getenv('TMPDIR') mut path := getenv('TMPDIR')
$if windows { $if windows {
if path == '' { if path == '' {
// TODO see Qt's implementation? // TODO see Qt's implementation?
// https://doc.qt.io/qt-5/qdir.html#tempPath // https://doc.qt.io/qt-5/qdir.html#tempPath
// https://github.com/qt/qtbase/blob/e164d61ca8263fc4b46fdd916e1ea77c7dd2b735/src/corelib/io/qfilesystemengine_win.cpp#L1275 // https://github.com/qt/qtbase/blob/e164d61ca8263fc4b46fdd916e1ea77c7dd2b735/src/corelib/io/qfilesystemengine_win.cpp#L1275
path = os.getenv('TEMP') path = getenv('TEMP')
if path == '' { if path == '' {
path = os.getenv('TMP') path = getenv('TMP')
} }
if path == '' { if path == '' {
path = 'C:/tmp' path = 'C:/tmp'
@ -1342,7 +1271,7 @@ pub fn temp_dir() string {
$if android { $if android {
// TODO test+use '/data/local/tmp' on Android before using cache_dir() // TODO test+use '/data/local/tmp' on Android before using cache_dir()
if path == '' { if path == '' {
path = os.cache_dir() path = cache_dir()
} }
} }
if path == '' { if path == '' {
@ -1352,25 +1281,26 @@ pub fn temp_dir() string {
} }
fn default_vmodules_path() string { fn default_vmodules_path() string {
return os.join_path(os.home_dir(), '.vmodules') return join_path(home_dir(), '.vmodules')
} }
// vmodules_dir returns the path to a folder, where v stores its global modules. // vmodules_dir returns the path to a folder, where v stores its global modules.
pub fn vmodules_dir() string { pub fn vmodules_dir() string {
paths := vmodules_paths() paths := vmodules_paths()
if paths.len > 0 { if paths.len > 0 {
return paths[0] return paths[0]
} }
return os.default_vmodules_path() return default_vmodules_path()
} }
// vmodules_paths returns a list of paths, where v looks up for modules. // vmodules_paths returns a list of paths, where v looks up for modules.
// You can customize it through setting the environment variable VMODULES // You can customize it through setting the environment variable VMODULES
pub fn vmodules_paths() []string { pub fn vmodules_paths() []string {
mut path := os.getenv('VMODULES') mut path := getenv('VMODULES')
if path == '' { if path == '' {
path = os.default_vmodules_path() path = default_vmodules_path()
} }
list := path.split(os.path_delimiter).map(it.trim_right(os.path_separator)) list := path.split(path_delimiter).map(it.trim_right(path_separator))
return list return list
} }
@ -1390,12 +1320,12 @@ pub const (
// It gives a convenient way to access program resources like images, fonts, sounds and so on, // It gives a convenient way to access program resources like images, fonts, sounds and so on,
// *no matter* how the program was started, and what is the current working directory. // *no matter* how the program was started, and what is the current working directory.
pub fn resource_abs_path(path string) string { pub fn resource_abs_path(path string) string {
mut base_path := os.real_path(os.dir(os.executable())) mut base_path := real_path(dir(executable()))
vresource := os.getenv('V_RESOURCE_PATH') vresource := getenv('V_RESOURCE_PATH')
if vresource.len != 0 { if vresource.len != 0 {
base_path = vresource base_path = vresource
} }
return os.real_path(os.join_path(base_path, path)) return real_path(join_path(base_path, path))
} }
// open tries to open a file for reading and returns back a read-only `File` object. // open tries to open a file for reading and returns back a read-only `File` object.
@ -1414,9 +1344,9 @@ pub fn open(path string) ?File {
} }
} }
*/ */
cfile := vfopen(path, 'rb')? cfile := vfopen(path, 'rb') ?
fd := fileno(cfile) fd := fileno(cfile)
return File { return File{
cfile: cfile cfile: cfile
fd: fd fd: fd
is_opened: true is_opened: true
@ -1448,9 +1378,9 @@ pub fn create(path string) ?File {
} }
} }
*/ */
cfile := vfopen(path, 'wb')? cfile := vfopen(path, 'wb') ?
fd := fileno(cfile) fd := fileno(cfile)
return File { return File{
cfile: cfile cfile: cfile
fd: fd fd: fd
is_opened: true is_opened: true