1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/os/os_nix.v

97 lines
1.9 KiB
V
Raw Normal View History

module os
2019-07-01 18:04:09 +03:00
#include <dirent.h>
#include <unistd.h>
2019-07-16 02:57:03 +03:00
2019-10-24 12:36:57 +03:00
pub const (
2019-10-12 22:18:19 +03:00
path_separator = '/'
)
2019-10-31 13:08:01 +03:00
pub fn init_os_args(argc int, argv &byteptr) []string {
2019-09-14 23:48:30 +03:00
mut args := []string
2019-10-13 01:50:15 +03:00
for i in 0 .. argc {
2019-09-14 23:48:30 +03:00
args << string(argv[i])
}
return args
}
2019-08-16 15:05:11 +03:00
// get_error_msg return error code representation in string.
pub fn get_error_msg(code int) string {
_ptr_text := C.strerror(code) // voidptr?
if _ptr_text == 0 {
return ''
}
2019-09-15 15:36:05 +03:00
return tos(_ptr_text, vstrlen(_ptr_text))
2019-07-29 19:21:36 +03:00
}
2019-08-16 15:05:11 +03:00
2019-10-17 14:30:05 +03:00
pub fn ls(path string) ?[]string {
2019-08-16 15:05:11 +03:00
mut res := []string
dir := C.opendir(path.str)
2019-08-16 15:05:11 +03:00
if isnil(dir) {
2019-10-17 14:30:05 +03:00
return error('ls() couldnt open dir "$path"')
2019-08-16 15:05:11 +03:00
}
mut ent := &C.dirent{!}
for {
ent = C.readdir(dir)
if isnil(ent) {
break
}
2019-09-15 19:07:40 +03:00
name := tos_clone(byteptr(ent.d_name))
2019-08-16 15:05:11 +03:00
if name != '.' && name != '..' && name != '' {
res << name
}
}
C.closedir(dir)
return res
}
2019-08-17 16:17:43 +03:00
pub fn dir_exists(path string) bool {
2019-11-15 00:46:40 +03:00
/*
$if linux {
C.syscall(4, path.str) // sys_newstat
}
*/
2019-08-17 16:17:43 +03:00
dir := C.opendir(path.str)
res := !isnil(dir)
if res {
C.closedir(dir)
}
return res
}
// mkdir creates a new directory with the specified path.
pub fn mkdir(path string) {
2019-11-11 17:18:32 +03:00
$if linux {
2019-11-15 00:15:23 +03:00
C.syscall(83, path.str, 511) // sys_mkdir
2019-11-11 17:18:32 +03:00
} $else {
C.mkdir(path.str, 511)// S_IRWXU | S_IRWXG | S_IRWXO
2019-11-15 00:15:23 +03:00
}
2019-08-17 16:17:43 +03:00
}
2019-11-07 16:01:17 +03:00
// exec starts the specified command, waits for it to complete, and returns its output.
pub fn exec(cmd string) ?Result {
if cmd.contains(';') || cmd.contains('&&') || cmd.contains('||') || cmd.contains('\n') {
return error(';, &&, || and \\n are not allowed in shell commands')
}
pcmd := '$cmd 2>&1'
f := vpopen(pcmd)
if isnil(f) {
return error('exec("$cmd") failed')
}
buf := [1000]byte
mut res := ''
for C.fgets(*char(buf), 1000, f) != 0 {
res += tos(buf, vstrlen(buf))
}
res = res.trim_space()
exit_code := vpclose(f)
//if exit_code != 0 {
//return error(res)
//}
return Result {
output: res
exit_code: exit_code
}
}