os: implement cp for nix

pull/5162/head
Naheel 2020-06-01 22:11:40 +03:00 committed by GitHub
parent a24bf80228
commit 4fcabb71c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 31 additions and 9 deletions

View File

@ -411,3 +411,6 @@ fn C.pthread_mutex_init(voidptr, voidptr) int
fn C.pthread_mutex_lock(voidptr) int
fn C.pthread_mutex_unlock(voidptr) int
fn C.read(fd int, buf voidptr, count size_t) int
fn C.write(fd int, buf voidptr, count size_t) int
fn C.close(fd int) int

View File

@ -62,12 +62,8 @@ fn C.send() int
fn C.recv() int
fn C.read() int
fn C.shutdown() int
fn C.close() int
fn C.ntohs() int
fn C.getsockname() int

View File

@ -1,7 +1,5 @@
module websocket
fn C.write() int
fn (mut ws Client) write_to_server(buf voidptr, len int) int {
mut bytes_written := 0
ws.write_lock.lock()

View File

@ -207,7 +207,6 @@ pub fn mv(old, new string) {
}
fn C.CopyFile(&u32, &u32, int) int
// TODO implement actual cp for linux
pub fn cp(old, new string) ?bool {
$if windows {
w_old := old.replace('/', '\\')
@ -221,8 +220,34 @@ pub fn cp(old, new string) ?bool {
return error_with_code('failed to copy $old to $new', int(result))
}
} $else {
os.system('cp "$old" "$new"')
return true // TODO make it return true or error when cp for linux is implemented
fp_from := C.open(old.str, C.O_RDONLY)
if fp_from < 0 { // Check if file opened
return error_with_code('cp: failed to open $old', int(fp_from))
}
fp_to := C.open(new.str, C.O_WRONLY | C.O_CREAT | C.O_TRUNC)
if fp_to < 0 { // Check if file opened (permissions problems ...)
C.close(fp_from)
return error_with_code('cp: failed to write to $new', int(fp_to))
}
mut buf := [1024]byte
mut count := 0
for {
// FIXME: use sizeof, bug: 'os__buf' undeclared
//count = C.read(fp_from, buf, sizeof(buf))
count = C.read(fp_from, buf, 1024)
if count == 0 {
break
}
if C.write(fp_to, buf, count) < 0 {
return error_with_code('cp: failed to write to $new', int(-1))
}
}
from_attr := C.stat{}
C.stat(old.str, &from_attr)
if C.chmod(new.str, from_attr.st_mode) < 0 {
return error_with_code('failed to set permissions for $new', int(-1))
}
return true
}
}