Repository navigation
Expand file tree
/
Copy pathos.v
More file actions
1223 lines (1112 loc) · 26 KB
/
Copy pathos.v
File metadata and controls
1223 lines (1112 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019-2020 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module os
#include <sys/stat.h> // #include <signal.h>
#include <errno.h>
/*
struct dirent {
d_ino int
d_off int
d_reclen u16
d_type byte
d_name [256]byte
}
*/
struct C.dirent {
d_name byteptr
}
fn C.readdir(voidptr) C.dirent
pub const (
args = []string
MAX_PATH = 4096
)
pub struct File {
cfile voidptr // Using void* instead of FILE*
pub:
fd int
mut:
opened bool
}
struct FileInfo {
name string
size int
}
struct C.stat {
st_size int
st_mode u32
st_mtime int
}
struct C.DIR {}
// struct C.dirent {
// d_name byteptr
// }
struct C.sigaction {
mut:
sa_mask int
sa_sigaction int
sa_flags int
}
fn C.getline(voidptr, voidptr, voidptr) int
fn C.ftell(fp voidptr) int
fn C.sigaction(int, voidptr, int)
fn C.open(charptr, int, int) int
fn C.fdopen(int, string) voidptr
pub fn (f File) is_opened() bool {
return f.opened
}
// read_bytes reads an amount of bytes from the beginning of the file
pub fn (f &File) read_bytes(size int) []byte {
return f.read_bytes_at(size, 0)
}
// read_bytes_at reads an amount of bytes at the given position in the file
pub fn (f &File) read_bytes_at(size, pos int) []byte {
mut arr := [`0`].repeat(size)
C.fseek(f.cfile, pos, C.SEEK_SET)
nreadbytes := C.fread(arr.data, 1, size, f.cfile)
C.fseek(f.cfile, 0, C.SEEK_SET)
return arr[0..nreadbytes]
}
pub fn read_bytes(path string) ?[]byte {
mut fp := vfopen(path, 'rb')
if isnil(fp) {
return error('failed to open file "$path"')
}
C.fseek(fp, 0, C.SEEK_END)
fsize := C.ftell(fp)
C.rewind(fp)
mut res := [`0`].repeat(fsize)
nr_read_elements := C.fread(res.data, fsize, 1, fp)
C.fclose(fp)
return res[0..nr_read_elements * fsize]
}
// read_file reads the file in `path` and returns the contents.
pub fn read_file(path string) ?string {
mode := 'rb'
mut fp := vfopen(path, mode)
if isnil(fp) {
return error('failed to open file "$path"')
}
defer { C.fclose(fp) }
C.fseek(fp, 0, C.SEEK_END)
fsize := C.ftell(fp)
// C.fseek(fp, 0, SEEK_SET) // same as `C.rewind(fp)` below
C.rewind(fp)
mut str := &byte(0)
unsafe { str = malloc(fsize + 1) }
C.fread(str, fsize, 1, fp)
str[fsize] = 0
return string(str,fsize)
}
// file_size returns the size of the file located in `path`.
pub fn file_size(path string) int {
mut s := C.stat{}
$if windows {
C._wstat(path.to_wide(), voidptr(&s))
} $else {
C.stat(charptr(path.str), &s)
}
return s.st_size
}
pub fn mv(old, new string) {
$if windows {
C._wrename(old.to_wide(), new.to_wide())
} $else {
C.rename(charptr(old.str), charptr(new.str))
}
}
fn C.CopyFile(&u32, &u32, int) int
// TODO implement actual cp for linux
pub fn cp(old, new string) ?bool {
$if windows {
_old := old.replace('/', '\\')
_new := new.replace('/', '\\')
C.CopyFile(_old.to_wide(), _new.to_wide(), false)
result := C.GetLastError()
if result == 0 {
return true
}
else {
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
}
}
[deprecated]
pub fn cp_r(osource_path, odest_path string, overwrite bool) ?bool {
panic('Use `os.cp_all` instead of `os.cp_r`')
}
pub fn cp_all(osource_path, odest_path string, overwrite bool) ?bool {
source_path := os.real_path(osource_path)
dest_path := os.real_path(odest_path)
if !os.exists(source_path) {
return error("Source path doesn\'t exist")
}
// single file copy
if !os.is_dir(source_path) {
adjusted_path := if os.is_dir(dest_path) {os.join_path(dest_path,os.file_name(source_path)) } else { dest_path }
if os.exists(adjusted_path) {
if overwrite {
os.rm(adjusted_path)
}
else {
return error('Destination file path already exist')
}
}
os.cp(source_path, adjusted_path) or {
return error(err)
}
return true
}
if !os.is_dir(dest_path) {
return error('Destination path is not a valid directory')
}
files := os.ls(source_path) or {
return error(err)
}
for file in files {
sp := os.join_path(source_path, file)
dp := os.join_path(dest_path, file)
if os.is_dir(sp) {
os.mkdir(dp) or {
panic(err)
}
}
cp_all(sp, dp, overwrite) or {
os.rmdir(dp)
panic(err)
}
}
return true
}
// mv_by_cp first copies the source file, and if it is copied successfully, deletes the source file.
// mv_by_cp 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) ?bool {
os.cp(source, target) or {
return error(err)
}
os.rm(source)
return true
}
fn vfopen(path, mode string) &C.FILE {
$if windows {
return C._wfopen(path.to_wide(), mode.to_wide())
} $else {
return C.fopen(charptr(path.str), charptr(mode.str))
}
}
// read_lines reads the file in `path` into an array of lines.
pub fn read_lines(path string) ?[]string {
buf := read_file(path) or {
return error(err)
}
return buf.split_into_lines()
}
fn read_ulines(path string) ?[]ustring {
lines := read_lines(path) or {
return error(err)
}
// mut ulines := new_array(0, lines.len, sizeof(ustring))
mut ulines := []ustring
for myline in lines {
// ulines[i] = ustr
ulines << myline.ustring()
}
return ulines
}
pub fn open_append(path string) ?File {
mut file := File{}
$if windows {
wpath := path.replace('/', '\\').to_wide()
mode := 'ab'
file = File{
cfile: C._wfopen(wpath, mode.to_wide())
}
} $else {
cpath := path.str
file = File{
cfile: C.fopen(charptr(cpath), 'ab')
}
}
if isnil(file.cfile) {
return error('failed to create(append) file "$path"')
}
file.opened = true
return file
}
// open_file can be used to open or create a file with custom flags and permissions and returns a `File` object
pub fn open_file(path string, mode string, options ...int) ?File {
mut flags := 0
for m in mode {
match m {
`r` { flags |= O_RDONLY }
`w` { flags |= O_CREATE | O_TRUNC }
`a` { flags |= O_CREATE | O_APPEND }
`s` { flags |= O_SYNC }
`n` { flags |= O_NONBLOCK }
`c` { flags |= O_NOCTTY }
`+` { flags |= O_RDWR }
else {}
}
}
mut permission := 0o666
if options.len > 0 {
permission = options[0]
}
$if windows {
if permission < 0o600 {
permission = 0x0100
}
else {
permission = 0x0100 | 0x0080
}
}
mut p := path
$if windows {
p = path.replace('/', '\\')
}
fd := C.open(charptr(p.str), flags, permission)
if fd == -1 {
return error(posix_get_error_msg(C.errno))
}
cfile := C.fdopen(fd, charptr(mode.str))
if isnil(cfile) {
return error('Failed to open or create file "$path"')
}
return File{
cfile: cfile
fd: fd
opened: true
}
}
pub fn (f mut File) write_bytes_at(data voidptr, size, pos int) {
//$if linux {
//}
//$else {
C.fseek(f.cfile, pos, C.SEEK_SET)
C.fwrite(data, 1, size, f.cfile)
C.fseek(f.cfile, 0, C.SEEK_END)
//}
}
pub fn (f mut File) flush() {
if !f.opened {
return
}
C.fflush(f.cfile)
}
// system starts the specified command, waits for it to complete, and returns its code.
fn vpopen(path string) voidptr {
// *C.FILE {
$if windows {
mode := 'rb'
wpath := path.to_wide()
return C._wpopen(wpath, mode.to_wide())
} $else {
cpath := path.str
return C.popen(cpath, 'r')
}
}
fn posix_wait4_to_exit_status(waitret int) (int,bool) {
$if windows {
return waitret,false
} $else {
mut ret := 0
mut is_signaled := true
// (see man system, man 2 waitpid: C macro WEXITSTATUS section)
if C.WIFEXITED(waitret) {
ret = C.WEXITSTATUS(waitret)
is_signaled = false
}
else if C.WIFSIGNALED(waitret) {
ret = C.WTERMSIG(waitret)
is_signaled = true
}
return ret,is_signaled
}
}
// posix_get_error_msg return error code representation in string.
pub fn posix_get_error_msg(code int) string {
ptr_text := C.strerror(code) // voidptr?
if ptr_text == 0 {
return ''
}
return tos3(ptr_text)
}
fn vpclose(f voidptr) int {
$if windows {
return C._pclose(f)
} $else {
ret,_ := posix_wait4_to_exit_status(C.pclose(f))
return ret
}
}
pub struct Result {
pub:
exit_code int
output string
// stderr string // TODO
}
// `system` works like `exec()`, but only returns a return code.
pub fn system(cmd string) int {
// if cmd.contains(';') || cmd.contains('&&') || cmd.contains('||') || cmd.contains('\n') {
// TODO remove panic
// panic(';, &&, || and \\n are not allowed in shell commands')
// }
mut ret := 0
$if windows {
// overcome bug in system & _wsystem (cmd) when first char is quote `"`
wcmd := if cmd.len > 1 && cmd[0] == `"` && cmd[1] != `"` { '"$cmd"' } else { cmd }
ret = C._wsystem(wcmd.to_wide())
} $else {
ret = C.system(cmd.str)
}
if ret == -1 {
print_c_errno()
}
$if !windows {
pret,is_signaled := posix_wait4_to_exit_status(ret)
if is_signaled {
println('Terminated by signal ${ret:2d} (' + sigint_to_signal_name(pret) + ')')
}
ret = pret
}
return ret
}
pub fn sigint_to_signal_name(si int) string {
// POSIX signals:
match si {
1 {
return 'SIGHUP'
}
2 {
return 'SIGINT'
}
3 {
return 'SIGQUIT'
}
4 {
return 'SIGILL'
}
6 {
return 'SIGABRT'
}
8 {
return 'SIGFPE'
}
9 {
return 'SIGKILL'
}
11 {
return 'SIGSEGV'
}
13 {
return 'SIGPIPE'
}
14 {
return 'SIGALRM'
}
15 {
return 'SIGTERM'
}
else {}
}
$if linux {
// From `man 7 signal` on linux:
match si {
30, 10, 16 {
return 'SIGUSR1'
}
31, 12, 17 {
return 'SIGUSR2'
}
20, 17, 18 {
return 'SIGCHLD'
}
19, 18, 25 {
return 'SIGCONT'
}
17, 19, 23 {
return 'SIGSTOP'
}
18, 20, 24 {
return 'SIGTSTP'
}
21, 21, 26 {
return 'SIGTTIN'
}
22, 22, 27 {
return 'SIGTTOU'
}
// /////////////////////////////
5 {
return 'SIGTRAP'
}
7 {
return 'SIGBUS'
}
else {}
}
}
return 'unknown'
}
const (
F_OK = 0
X_OK = 1
W_OK = 2
R_OK = 4
)
// exists returns true if `path` exists.
pub fn exists(path string) bool {
$if windows {
p := path.replace('/', '\\')
return C._waccess(p.to_wide(), F_OK) != -1
} $else {
return C.access(path.str, F_OK) != -1
}
}
// `is_executable` returns `true` if `path` is executable.
pub fn is_executable(path string) bool {
$if windows {
// NB: https://docs.microsoft.com/en-us/cpp/c-runtime-library/reference/access-waccess?view=vs-2019
// i.e. there is no X bit there, the modes can be:
// 00 Existence only
// 02 Write-only
// 04 Read-only
// 06 Read and write
p := os.real_path( path )
return ( os.exists( p ) && p.ends_with('.exe') )
}
$if solaris {
statbuf := C.stat{}
if C.stat(path.str, &statbuf) != 0 {
return false
}
return (int(statbuf.st_mode) & ( S_IXUSR | S_IXGRP | S_IXOTH )) != 0
}
return C.access(path.str, X_OK) != -1
}
// `is_writable_folder` - `folder` exists and is writable to the process
pub fn is_writable_folder(folder string) ?bool {
if !os.exists(folder) {
return error('`$folder` does not exist')
}
if !os.is_dir(folder) {
return error('`folder` is not a folder')
}
tmp_perm_check := os.join_path(folder, 'tmp_perm_check')
f := os.open_file(tmp_perm_check, 'w+', 0o700) or {
return error('cannot write to folder `$folder`: $err')
}
f.close()
os.rm(tmp_perm_check)
return true
}
// `is_writable` returns `true` if `path` is writable.
pub fn is_writable(path string) bool {
$if windows {
p := path.replace('/', '\\')
return C._waccess(p.to_wide(), W_OK) != -1
} $else {
return C.access(path.str, W_OK) != -1
}
}
// `is_readable` returns `true` if `path` is readable.
pub fn is_readable(path string) bool {
$if windows {
p := path.replace('/', '\\')
return C._waccess(p.to_wide(), R_OK) != -1
} $else {
return C.access(path.str, R_OK) != -1
}
}
[deprecated]
pub fn file_exists(_path string) bool {
panic('Use `os.exists` instead of `os.file_exists`')
}
// rm removes file in `path`.
pub fn rm(path string) {
$if windows {
C._wremove(path.to_wide())
} $else {
C.remove(path.str)
}
// C.unlink(path.cstr())
}
// rmdir removes a specified directory.
pub fn rmdir(path string) {
$if !windows {
C.rmdir(path.str)
} $else {
C.RemoveDirectory(path.to_wide())
}
}
[deprecated]
pub fn rmdir_recursive(path string) {
panic('Use `os.rmdir_all` instead of `os.rmdir_recursive`')
}
pub fn rmdir_all(path string) {
items := os.ls(path) or {
return
}
for item in items {
if os.is_dir(os.join_path(path, item)) {
rmdir_all(os.join_path(path, item))
}
os.rm(os.join_path(path, item))
}
os.rmdir(path)
}
pub fn is_dir_empty(path string) bool {
items := os.ls(path) or {
return true
}
return items.len == 0
}
fn print_c_errno() {
e := C.errno
se := tos_clone(byteptr(C.strerror(C.errno)))
println('errno=$e err=$se')
}
pub fn file_ext(path string) string {
pos := path.last_index('.') or {
return ''
}
return path[pos..]
}
pub fn dir(path string) string {
pos := path.last_index(path_separator) or {
return '.'
}
return path[..pos]
}
pub fn base_dir(path string) string {
posx := path.last_index(path_separator) or {
return path
}
// NB: *without* terminating /
return path[..posx]
}
pub fn file_name(path string) string {
return path.all_after(path_separator)
}
// get_line returns a one-line string from stdin
pub fn get_line() string {
str := get_raw_line()
$if windows {
return str.trim_right('\r\n')
} $else {
return str.trim_right('\n')
}
}
// get_raw_line returns a one-line string from stdin along with '\n' if there is any
pub fn get_raw_line() string {
$if windows {
unsafe {
max_line_chars := 256
buf := malloc(max_line_chars * 2)
h_input := C.GetStdHandle(STD_INPUT_HANDLE)
mut bytes_read := 0
if is_atty(0) > 0 {
C.ReadConsole(h_input, buf, max_line_chars * 2, &bytes_read, 0)
return string_from_wide2(&u16(buf), bytes_read)
}
mut offset := 0
for {
pos := buf + offset
res := C.ReadFile(h_input, pos, 1, &bytes_read, 0)
if !res || bytes_read == 0 {
break
}
if *pos == `\n` || *pos == `\r` {
offset++
break
}
offset++
}
return string(buf, offset)
}
} $else {
max := size_t(0)
mut buf := charptr(0)
nr_chars := C.getline(&buf, &max, C.stdin)
//defer { unsafe{ free(buf) } }
if nr_chars == 0 || nr_chars == -1 {
return ''
}
return tos3(buf)
//res := tos_clone(buf)
//return res
}
}
pub fn get_lines() []string {
mut line := ''
mut inputstr := []string
for {
line = get_line()
if line.len <= 0 {
break
}
line = line.trim_space()
inputstr << line
}
return inputstr
}
pub fn get_lines_joined() string {
mut line := ''
mut inputstr := ''
for {
line = get_line()
if line.len <= 0 {
break
}
line = line.trim_space()
inputstr += line
}
return inputstr
}
// user_os returns current user operating system name.
pub fn user_os() string {
$if linux {
return 'linux'
}
$if macos {
return 'mac'
}
$if windows {
return 'windows'
}
$if freebsd {
return 'freebsd'
}
$if openbsd {
return 'openbsd'
}
$if netbsd {
return 'netbsd'
}
$if dragonfly {
return 'dragonfly'
}
$if android {
return 'android'
}
$if solaris {
return 'solaris'
}
$if haiku {
return 'haiku'
}
return 'unknown'
}
// home_dir returns path to user's home directory.
pub fn home_dir() string {
$if windows {
return os.getenv('USERPROFILE') + os.path_separator
} $else {
//println('home_dir() call')
//res:= os.getenv('HOME') + os.path_separator
//println('res="$res"')
return os.getenv('HOME') + os.path_separator
}
}
// write_file writes `text` data to a file in `path`.
pub fn write_file(path, text string) {
mut f := os.create(path) or {
return
}
f.write(text)
f.close()
}
// clear clears current terminal screen.
pub fn clear() {
$if !windows {
C.printf('\x1b[2J')
C.printf('\x1b[H')
}
}
pub fn on_segfault(f voidptr) {
$if windows {
return
}
$if macos {
C.printf("TODO")
/*
mut sa := C.sigaction{}
C.memset(&sa, 0, sizeof(C.sigaction_size))
C.sigemptyset(&sa.sa_mask)
sa.sa_sigaction = f
sa.sa_flags = C.SA_SIGINFO
C.sigaction(C.SIGSEGV, &sa, 0)
*/
}
}
fn C.getpid() int
fn C.proc_pidpath(int, byteptr, int) int
fn C.readlink() int
// executable returns the path name of the executable that started the current
// process.
pub fn executable() string {
$if linux {
mut result := vcalloc(MAX_PATH)
count := C.readlink('/proc/self/exe', result, MAX_PATH)
if count < 0 {
eprintln('os.executable() failed at reading /proc/self/exe to get exe path')
return executable_fallback()
}
return string(result)
}
$if windows {
max := 512
mut result := &u16(vcalloc(max * 2)) // MAX_PATH * sizeof(wchar_t)
len := C.GetModuleFileName(0, result, max)
return string_from_wide2(result, len)
}
$if macos {
mut result := vcalloc(MAX_PATH)
pid := C.getpid()
ret := proc_pidpath(pid, result, MAX_PATH)
if ret <= 0 {
eprintln('os.executable() failed at calling proc_pidpath with pid: $pid . proc_pidpath returned $ret ')
return executable_fallback()
}
return string(result)
}
$if freebsd {
mut result := vcalloc(MAX_PATH)
mib := [1/* CTL_KERN */, 14/* KERN_PROC */, 12/* KERN_PROC_PATHNAME */, -1]
size := MAX_PATH
C.sysctl(mib.data, 4, result, &size, 0, 0)
return string(result)
}
// "Sadly there is no way to get the full path of the executed file in OpenBSD."
$if openbsd {}
$if solaris {}
$if haiku {}
$if netbsd {
mut result := vcalloc(MAX_PATH)
count := C.readlink('/proc/curproc/exe', result, MAX_PATH)
if count < 0 {
eprintln('os.executable() failed at reading /proc/curproc/exe to get exe path')
return executable_fallback()
}
return string(result,count)
}
$if dragonfly {
mut result := vcalloc(MAX_PATH)
count := C.readlink('/proc/curproc/file', result, MAX_PATH)
if count < 0 {
eprintln('os.executable() failed at reading /proc/curproc/file to get exe path')
return executable_fallback()
}
return string(result,count)
}
return executable_fallback()
}
// executable_fallback is used when there is not a more platform specific and accurate implementation
// 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.
fn executable_fallback() string {
mut exepath := os.args[0]
if !os.is_abs_path(exepath) {
if exepath.contains( os.path_separator ) {
exepath = os.join_path(os.wd_at_startup, exepath)
}else{
// no choice but to try to walk the PATH folders :-| ...
foundpath := os.find_abs_path_of_executable(exepath) or { '' }
if foundpath.len > 0 {
exepath = foundpath
}
}
}
exepath = os.real_path(exepath)
return exepath
}
// find_exe_path walks the environment PATH, just like most shell do, it returns
// the absolute path of the executable if found
pub fn find_abs_path_of_executable(exepath string) ?string {
if os.is_abs_path(exepath) {
return exepath
}
mut res := ''
env_path_delimiter := if os.user_os() == 'windows' { ';' } else { ':' }
paths := os.getenv('PATH').split(env_path_delimiter)
for p in paths {
found_abs_path := os.join_path( p, exepath )
if os.exists( found_abs_path ) && os.is_executable( found_abs_path ) {
res = found_abs_path
break
}
}
if res.len>0 {
return res
}
return error('failed to find executable')
}
[deprecated]
pub fn dir_exists(path string) bool {
panic('Use `os.is_dir` instead of `os.dir_exists`')
}
// is_dir returns a boolean indicating whether the given path is a directory.
pub fn is_dir(path string) bool {
$if windows {
_path := path.replace('/', '\\')
attr := C.GetFileAttributesW(_path.to_wide())
if attr == u32(C.INVALID_FILE_ATTRIBUTES) {
return false
}
if int(attr) & C.FILE_ATTRIBUTE_DIRECTORY != 0 {
return true
}
return false
} $else {
statbuf := C.stat{}
if C.stat(path.str, &statbuf) != 0 {
return false
}
// ref: https://code.woboq.org/gcc/include/sys/stat.h.html
val:= int(statbuf.st_mode) & S_IFMT
return val == S_IFDIR
}
}
// is_link returns a boolean indicating whether the given path is a link.
pub fn is_link(path string) bool {
$if windows {
return false // TODO
} $else {
statbuf := C.stat{}
if C.lstat(path.str, &statbuf) != 0 {
return false
}
return int(statbuf.st_mode) & S_IFMT == S_IFLNK
}
}
// chdir changes the current working directory to the new directory path.
pub fn chdir(path string) {
$if windows {
C._wchdir(path.to_wide())
} $else {
C.chdir(path.str)
}
}
// getwd returns the absolute path name of the current directory.
pub fn getwd() string {
$if windows {
max := 512 // MAX_PATH * sizeof(wchar_t)
buf := &u16(vcalloc(max * 2))
if C._wgetcwd(buf, max) == 0 {
return ''
}
return string_from_wide(buf)
} $else {
buf := vcalloc(512)
if C.getcwd(buf, 512) == 0 {
return ''
}
return string(buf)
}
}
// Returns the full absolute path for fpath, with all relative ../../, symlinks and so on resolved.