os: add new function os.loginname(), improve some error messages (#9794)

pull/9814/head
Bastian Buck 2021-04-19 13:57:25 +02:00 committed by GitHub
parent 3158617ce2
commit 9ec91f4d58
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 41 additions and 6 deletions

View File

@ -267,7 +267,7 @@ fn C.wcslen(str &u16) int
fn C.WideCharToMultiByte(codePage u32, dwFlags u32, lpWideCharStr &u16, cchWideChar int, lpMultiByteStr &char, cbMultiByte int, lpDefaultChar &char, lpUsedDefaultChar &int) int
fn C._wstat(path &u16, buffer &C._stat)
fn C._wstat(path &u16, buffer &C._stat) int
fn C._wrename(oldname &u16, newname &u16) int

View File

@ -143,7 +143,7 @@ pub fn truncate(path string, len u64) ? {
C.close(fp)
}
if fp < 0 {
return error('open file failed')
return error_with_code(posix_get_error_msg(C.errno), C.errno)
}
$if windows {
if C._chsize_s(fp, len) != 0 {
@ -165,10 +165,18 @@ pub fn file_size(path string) u64 {
$if x64 {
$if windows {
mut swin := C.__stat64{}
C._wstat64(&char(path.to_wide()), voidptr(&swin))
if C._wstat64(&char(path.to_wide()), voidptr(&swin)) != 0 {
eprintln('os.file_size() Cannot determine file-size: ' +
posix_get_error_msg(C.errno))
return 0
}
return swin.st_size
} $else {
C.stat(&char(path.str), &s)
if C.stat(&char(path.str), &s) != 0 {
eprintln('os.file_size() Cannot determine file-size: ' +
posix_get_error_msg(C.errno))
return 0
}
return u64(s.st_size)
}
}
@ -177,10 +185,18 @@ pub fn file_size(path string) u64 {
println('Using os.file_size() on 32bit systems may not work on big files.')
}
$if windows {
C._wstat(path.to_wide(), voidptr(&s))
if C._wstat(path.to_wide(), voidptr(&s)) != 0 {
eprintln('os.file_size() Cannot determine file-size: ' +
posix_get_error_msg(C.errno))
return 0
}
return u64(s.st_size)
} $else {
C.stat(&char(path.str), &s)
if C.stat(&char(path.str), &s) != 0 {
eprintln('os.file_size() Cannot determine file-size: ' +
posix_get_error_msg(C.errno))
return 0
}
return u64(s.st_size)
}
}

View File

@ -53,6 +53,8 @@ fn C.symlink(&char, &char) int
fn C.gethostname(&char, int) int
fn C.getlogin_r(&char, int) int
pub fn uname() Uname {
mut u := Uname{}
utsize := sizeof(C.utsname)
@ -83,6 +85,18 @@ pub fn hostname() string {
return ''
}
pub fn loginname() string {
mut lgnname := ''
size := 256
mut buf := unsafe { &char(malloc(size)) }
if C.getlogin_r(buf, size) == 0 {
lgnname = unsafe { cstring_to_vstring(buf) }
unsafe { free(buf) }
return lgnname
}
return ''
}
fn init_os_args(argc int, argv &&byte) []string {
mut args_ := []string{}
// mut args := []string(make(0, argc, sizeof(string)))

View File

@ -394,6 +394,11 @@ pub fn hostname() string {
return execute('cmd /c hostname').output
}
pub fn loginname() string {
// TODO: use C.GetUserName(&char, u32) bool instead
return execute('cmd /c echo %USERNAME%').output
}
// `is_writable_folder` - `folder` exists and is writable to the process
pub fn is_writable_folder(folder string) ?bool {
if !exists(folder) {