Skip to content

Commit

Permalink
better c interop error checking
Browse files Browse the repository at this point in the history
  • Loading branch information
mike-ward committed Jun 15, 2024
1 parent ec2d899 commit 5ddb0f6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/ls/ls.v
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ fn ls(args Args) {
if print_dir_names {
print_dir_name(dir, args)
}

print_listing(listing, args)
}
}
29 changes: 26 additions & 3 deletions src/ls/ls_nix.c.v
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import os

#include <pwd.h>
#include <grp.h>
#include <unistd.h>
Expand All @@ -21,18 +23,39 @@ fn C.getgrgid(uid usize) &Group
fn C.readlink(file &char, buf &char, buf_size usize)

fn get_owner_name(uid usize) string {
p := C.getpwuid(uid)
return unsafe { cstring_to_vstring(p.pw_name) }
pwd := C.getpwuid(uid)
unsafe {
if isnil(pwd) {
// Call succeeded but user not found
if C.errno == 0 {
return ''
}
return os.error_posix().msg()
}
return cstring_to_vstring(pwd.pw_name)
}
}

fn get_group_name(uid usize) string {
grp := C.getgrgid(uid)
return unsafe { cstring_to_vstring(grp.gr_name) }
unsafe {
if isnil(grp) {
// Call succeeded but user not found
if C.errno == 0 {
return ''
}
return os.error_posix().msg()
}
return cstring_to_vstring(grp.gr_name)
}
}

fn read_link(file string) string {
buf_size := 2048
buf := '\0'.repeat(buf_size)
len := C.readlink(file.str, buf.str, usize(buf_size))
if len == -1 {
return os.error_posix().msg()
}
return buf.substr(0, len)
}

0 comments on commit 5ddb0f6

Please sign in to comment.