Repository navigation
Expand file tree
/
Copy pathos.nim
More file actions
2466 lines (2269 loc) · 87.7 KB
/
Copy pathos.nim
File metadata and controls
2466 lines (2269 loc) · 87.7 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
#
#
# Nim's Runtime Library
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## This module contains basic operating system facilities like
## retrieving environment variables, reading command line arguments,
## working with directories, running shell commands, etc.
{.deadCodeElim: on.} # dce option deprecated
{.push debugger: off.}
include "system/inclrtl"
import
strutils, pathnorm
const weirdTarget = defined(nimscript) or defined(js)
when weirdTarget:
discard
elif defined(windows):
import winlean, times
elif defined(posix):
import posix, times
proc toTime(ts: Timespec): times.Time {.inline.} =
result = initTime(ts.tv_sec.int64, ts.tv_nsec.int)
else:
{.error: "OS module not ported to your operating system!".}
when weirdTarget and defined(nimErrorProcCanHaveBody):
{.pragma: noNimScript, error: "this proc is not available on the NimScript target".}
else:
{.pragma: noNimScript.}
type
ReadEnvEffect* = object of ReadIOEffect ## effect that denotes a read
## from an environment variable
WriteEnvEffect* = object of WriteIOEffect ## effect that denotes a write
## to an environment variable
ReadDirEffect* = object of ReadIOEffect ## effect that denotes a read
## operation from the directory
## structure
WriteDirEffect* = object of WriteIOEffect ## effect that denotes a write
## operation to
## the directory structure
OSErrorCode* = distinct int32 ## Specifies an OS Error Code.
include "includes/osseps"
proc normalizePathEnd(path: var string, trailingSep = false) =
## ensures ``path`` has exactly 0 or 1 trailing `DirSep`, depending on
## ``trailingSep``, and taking care of edge cases: it preservers whether
## a path is absolute or relative, and makes sure trailing sep is `DirSep`,
## not `AltSep`.
if path.len == 0: return
var i = path.len
while i >= 1 and path[i-1] in {DirSep, AltSep}: dec(i)
if trailingSep:
# foo// => foo
path.setLen(i)
# foo => foo/
path.add DirSep
elif i > 0:
# foo// => foo
path.setLen(i)
else:
# // => / (empty case was already taken care of)
path = $DirSep
proc normalizePathEnd(path: string, trailingSep = false): string =
result = path
result.normalizePathEnd(trailingSep)
proc joinPath*(head, tail: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Joins two directory names to one.
##
## For example on Unix:
##
## .. code-block:: nim
## joinPath("usr", "lib")
##
## results in:
##
## .. code-block:: nim
## "usr/lib"
##
## If head is the empty string, tail is returned. If tail is the empty
## string, head is returned with a trailing path separator. If tail starts
## with a path separator it will be removed when concatenated to head. Other
## path separators not located on boundaries won't be modified. More
## examples on Unix:
##
## .. code-block:: nim
## assert joinPath("usr", "") == "usr/"
## assert joinPath("", "lib") == "lib"
## assert joinPath("", "/lib") == "/lib"
## assert joinPath("usr/", "/lib") == "usr/lib"
result = newStringOfCap(head.len + tail.len)
var state = 0
addNormalizePath(head, result, state, DirSep)
if tail.len == 0:
result.add DirSep
else:
addNormalizePath(tail, result, state, DirSep)
when false:
if len(head) == 0:
result = tail
elif head[len(head)-1] in {DirSep, AltSep}:
if tail.len > 0 and tail[0] in {DirSep, AltSep}:
result = head & substr(tail, 1)
else:
result = head & tail
else:
if tail.len > 0 and tail[0] in {DirSep, AltSep}:
result = head & tail
else:
result = head & DirSep & tail
proc joinPath*(parts: varargs[string]): string {.noSideEffect,
rtl, extern: "nos$1OpenArray".} =
## The same as `joinPath(head, tail)`, but works with any number of
## directory parts. You need to pass at least one element or the proc
## will assert in debug builds and crash on release builds.
var estimatedLen = 0
for p in parts: estimatedLen += p.len
result = newStringOfCap(estimatedLen)
var state = 0
for i in 0..high(parts):
addNormalizePath(parts[i], result, state, DirSep)
proc `/`*(head, tail: string): string {.noSideEffect.} =
## The same as ``joinPath(head, tail)``
##
## Here are some examples for Unix:
##
## .. code-block:: nim
## assert "usr" / "" == "usr/"
## assert "" / "lib" == "lib"
## assert "" / "/lib" == "/lib"
## assert "usr/" / "/lib" == "usr/lib"
return joinPath(head, tail)
proc splitPath*(path: string): tuple[head, tail: string] {.
noSideEffect, rtl, extern: "nos$1".} =
## Splits a directory into (head, tail), so that
## ``head / tail == path`` (except for edge cases like "/usr").
##
## Examples:
##
## .. code-block:: nim
## splitPath("usr/local/bin") -> ("usr/local", "bin")
## splitPath("usr/local/bin/") -> ("usr/local/bin", "")
## splitPath("bin") -> ("", "bin")
## splitPath("/bin") -> ("", "bin")
## splitPath("") -> ("", "")
var sepPos = -1
for i in countdown(len(path)-1, 0):
if path[i] in {DirSep, AltSep}:
sepPos = i
break
if sepPos >= 0:
result.head = substr(path, 0, sepPos-1)
result.tail = substr(path, sepPos+1)
else:
result.head = ""
result.tail = path
when FileSystemCaseSensitive:
template `!=?`(a, b: char): bool = toLowerAscii(a) != toLowerAscii(b)
else:
template `!=?`(a, b: char): bool = a != b
proc relativePath*(path, base: string; sep = DirSep): string {.
noSideEffect, rtl, extern: "nos$1", raises: [].} =
## Converts `path` to a path relative to `base`.
## The `sep` is used for the path normalizations, this can be useful to
## ensure the relative path only contains '/' so that it can be used for
## URL constructions.
runnableExamples:
doAssert relativePath("/Users/me/bar/z.nim", "/Users/other/bad", '/') == "../../me/bar/z.nim"
doAssert relativePath("/Users/me/bar/z.nim", "/Users/other", '/') == "../me/bar/z.nim"
doAssert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
doAssert relativePath("/Users/me/bar/z.nim", "/Users/me", '/') == "bar/z.nim"
doAssert relativePath("", "/users/moo", '/') == ""
# Todo: If on Windows, path and base do not agree on the drive letter,
# return `path` as is.
if path.len == 0: return ""
var f, b: PathIter
var ff = (0, -1)
var bb = (0, -1) # (int, int)
result = newStringOfCap(path.len)
# skip the common prefix:
while f.hasNext(path) and b.hasNext(base):
ff = next(f, path)
bb = next(b, base)
let diff = ff[1] - ff[0]
if diff != bb[1] - bb[0]: break
var same = true
for i in 0..diff:
if path[i + ff[0]] !=? base[i + bb[0]]:
same = false
break
if not same: break
ff = (0, -1)
bb = (0, -1)
# for i in 0..diff:
# result.add base[i + bb[0]]
# /foo/bar/xxx/ -- base
# /foo/bar/baz -- path path
# ../baz
# every directory that is in 'base', needs to add '..'
while true:
if bb[1] >= bb[0]:
if result.len > 0 and result[^1] != sep:
result.add sep
result.add ".."
if not b.hasNext(base): break
bb = b.next(base)
# add the rest of 'path':
while true:
if ff[1] >= ff[0]:
if result.len > 0 and result[^1] != sep:
result.add sep
for i in 0..ff[1] - ff[0]:
r
10000
esult.add path[i + ff[0]]
if not f.hasNext(path): break
ff = f.next(path)
proc parentDirPos(path: string): int =
var q = 1
if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2
for i in countdown(len(path)-q, 0):
if path[i] in {DirSep, AltSep}: return i
result = -1
proc parentDir*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Returns the parent directory of `path`.
##
## This is the same as ``splitPath(path).head`` when ``path`` doesn't end
## in a dir separator.
## The remainder can be obtained with ``lastPathPart(path)``
runnableExamples:
doAssert parentDir("") == ""
when defined(posix):
doAssert parentDir("/usr/local/bin") == "/usr/local"
doAssert parentDir("foo/bar/") == "foo"
let sepPos = parentDirPos(path)
if sepPos >= 0:
result = substr(path, 0, sepPos-1)
else:
result = ""
proc tailDir*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Returns the tail part of `path`..
##
## | Example: ``tailDir("/usr/local/bin") == "local/bin"``.
## | Example: ``tailDir("usr/local/bin/") == "local/bin"``.
## | Example: ``tailDir("bin") == ""``.
var q = 1
if len(path) >= 1 and path[len(path)-1] in {DirSep, AltSep}: q = 2
for i in 0..len(path)-q:
if path[i] in {DirSep, AltSep}:
return substr(path, i+1)
result = ""
proc isRootDir*(path: string): bool {.
noSideEffect, rtl, extern: "nos$1".} =
## Checks whether a given `path` is a root directory
result = parentDirPos(path) < 0
iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string =
## Walks over all parent directories of a given `path`
##
## If `fromRoot` is set, the traversal will start from the file system root
## diretory. If `inclusive` is set, the original argument will be included
## in the traversal.
##
## Relative paths won't be expanded by this proc. Instead, it will traverse
## only the directories appearing in the relative path.
if not fromRoot:
var current = path
if inclusive: yield path
while true:
if current.isRootDir: break
current = current.parentDir
yield current
else:
for i in countup(0, path.len - 2): # ignore the last /
# deal with non-normalized paths such as /foo//bar//baz
if path[i] in {DirSep, AltSep} and
(i == 0 or path[i-1] notin {DirSep, AltSep}):
yield path.substr(0, i)
if inclusive: yield path
proc `/../`*(head, tail: string): string {.noSideEffect.} =
## The same as ``parentDir(head) / tail`` unless there is no parent
## directory. Then ``head / tail`` is performed instead.
let sepPos = parentDirPos(head)
if sepPos >= 0:
result = substr(head, 0, sepPos-1) / tail
else:
result = head / tail
proc normExt(ext: string): string =
if ext == "" or ext[0] == ExtSep: result = ext # no copy needed here
else: result = ExtSep & ext
proc searchExtPos*(path: string): int =
## Returns index of the '.' char in `path` if it signifies the beginning
## of extension. Returns -1 otherwise.
# BUGFIX: do not search until 0! .DS_Store is no file extension!
result = -1
for i in countdown(len(path)-1, 1):
if path[i] == ExtSep:
result = i
break
elif path[i] in {DirSep, AltSep}:
break # do not skip over path
proc splitFile*(path: string): tuple[dir, name, ext: string] {.
noSideEffect, rtl, extern: "nos$1".} =
## Splits a filename into (dir, filename, extension).
## `dir` does not end in `DirSep`.
## `extension` includes the leading dot.
##
## Example:
##
## .. code-block:: nim
## var (dir, name, ext) = splitFile("usr/local/nimc.html")
## assert dir == "usr/local"
## assert name == "nimc"
## assert ext == ".html"
##
## If `path` has no extension, `ext` is the empty string.
## If `path` has no directory component, `dir` is the empty string.
## If `path` has no filename component, `name` and `ext` are empty strings.
if path.len == 0:
result = ("", "", "")
elif path[^1] in {DirSep, AltSep}:
if path.len == 1:
# issue #8255
result = ($path[0], "", "")
else:
result = (path[0 ..< ^1], "", "")
else:
var sepPos = -1
var dotPos = path.len
for i in countdown(len(path)-1, 0):
if path[i] == ExtSep:
if dotPos == path.len and i > 0 and
path[i-1] notin {DirSep, AltSep, ExtSep}: dotPos = i
elif path[i] in {DirSep, AltSep}:
sepPos = i
break
if sepPos-1 >= 0:
result.dir = substr(path, 0, sepPos-1)
elif path[0] in {DirSep, AltSep}:
# issue #8255
result.dir = $path[0]
result.name = substr(path, sepPos+1, dotPos-1)
result.ext = substr(path, dotPos)
proc extractFilename*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Extracts the filename of a given `path`. This is the same as
## ``name & ext`` from ``splitFile(path)``. See also ``lastPathPart``.
runnableExamples:
when defined(posix):
doAssert extractFilename("foo/bar/") == ""
doAssert extractFilename("foo/bar") == "bar"
if path.len == 0 or path[path.len-1] in {DirSep, AltSep}:
result = ""
else:
result = splitPath(path).tail
proc lastPathPart*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## like ``extractFilename``, but ignores trailing dir separator; aka: `baseName`:idx:
## in some other languages.
runnableExamples:
when defined(posix):
doAssert lastPathPart("foo/bar/") == "bar"
let path = path.normalizePathEnd(trailingSep = false)
result = extractFilename(path)
proc changeFileExt*(filename, ext: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Changes the file extension to `ext`.
##
## If the `filename` has no extension, `ext` will be added.
## If `ext` == "" then any extension is removed.
## `Ext` should be given without the leading '.', because some
## filesystems may use a different character. (Although I know
## of none such beast.)
var extPos = searchExtPos(filename)
if extPos < 0: result = filename & normExt(ext)
else: result = substr(filename, 0, extPos-1) & normExt(ext)
proc addFileExt*(filename, ext: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Adds the file extension `ext` to `filename`, unless
## `filename` already has an extension.
##
## `Ext` should be given without the leading '.', because some
## filesystems may use a different character.
## (Although I know of none such beast.)
var extPos = searchExtPos(filename)
if extPos < 0: result = filename & normExt(ext)
else: result = filename
proc cmpPaths*(pathA, pathB: string): int {.
noSideEffect, rtl, extern: "nos$1".} =
## Compares two paths.
##
## On a case-sensitive filesystem this is done
## case-sensitively otherwise case-insensitively. Returns:
##
## | 0 iff pathA == pathB
## | < 0 iff pathA < pathB
## | > 0 iff pathA > pathB
runnableExamples:
when defined(macosx):
doAssert cmpPaths("foo", "Foo") == 0
elif defined(posix):
doAssert cmpPaths("foo", "Foo") > 0
let a = normalizePath(pathA)
let b = normalizePath(pathB)
if FileSystemCaseSensitive:
result = cmp(a, b)
else:
when defined(nimscript):
result = cmpic(a, b)
elif defined(nimdoc): discard
else:
result = cmpIgnoreCase(a, b)
proc isAbsolute*(path: string): bool {.rtl, noSideEffect, extern: "nos$1".} =
## Checks whether a given `path` is absolute.
##
## On Windows, network paths are considered absolute too.
runnableExamples:
doAssert(not "".isAbsolute)
doAssert(not ".".isAbsolute)
when defined(posix):
doAssert "/".isAbsolute
doAssert(not "a/".isAbsolute)
if len(path) == 0: return false
when doslikeFileSystem:
var len = len(path)
result = (path[0] in {'/', '\\'}) or
(len > 1 and path[0] in {'a'..'z', 'A'..'Z'} and path[1] == ':')
elif defined(macos):
# according to https://perldoc.perl.org/File/Spec/Mac.html `:a` is a relative path
result = path[0] != ':'
elif defined(RISCOS):
result = path[0] == '$'
elif defined(posix):
result = path[0] == '/'
proc unixToNativePath*(path: string, drive=""): string {.
noSideEffect, rtl, extern: "nos$1".} =
## Converts an UNIX-like path to a native one.
##
## On an UNIX system this does nothing. Else it converts
## '/', '.', '..' to the appropriate things.
##
## On systems with a concept of "drives", `drive` is used to determine
## which drive label to use during absolute path conversion.
## `drive` defaults to the drive of the current working directory, and is
when defined(unix):
result = path
else:
if path.len == 0: return ""
var start: int
if path[0] == '/':
# an absolute path
when doslikeFileSystem:
if drive != "":
result = drive & ":" & DirSep
else:
result = $DirSep
elif defined(macos):
result = "" # must not start with ':'
else:
result = $DirSep
start = 1
elif path[0] == '.' and (path.len == 1 or path[1] == '/'):
# current directory
result = $CurDir
start = when doslikeFileSystem: 1 else: 2
else:
result = ""
start = 0
var i = start
while i < len(path): # ../../../ --> ::::
if i+2 < path.len and path[i] == '.' and path[i+1] == '.' and path[i+2] == '/':
# parent directory
when defined(macos):
if result[high(result)] == ':':
add result, ':'
else:
add result, ParDir
else:
add result, ParDir & DirSep
inc(i, 3)
elif path[i] == '/':
add result, DirSep
inc(i)
else:
add result, path[i]
inc(i)
include "includes/oserr"
when not defined(nimscript):
include "includes/osenv"
proc getHomeDir*(): string {.rtl, extern: "nos$1",
tags: [ReadEnvEffect, ReadIOEffect].} =
## Returns the home directory of the current user.
##
## This proc is wrapped by the expandTilde proc for the convenience of
## processing paths coming from user configuration files.
when defined(windows): return string(getEnv("USERPROFILE")) & "\\"
else: return string(getEnv("HOME")) & "/"
proc getConfigDir*(): string {.rtl, extern: "nos$1",
tags: [ReadEnvEffect, ReadIOEffect].} =
## Returns the config directory of the current user for applications.
##
## On non-Windows OSs, this proc conforms to the XDG Base Directory
## spec. Thus, this proc returns the value of the XDG_CONFIG_HOME environment
## variable if it is set, and returns the default configuration directory,
## "~/.config/", otherwise.
##
## An OS-dependent trailing slash is always present at the end of the
## returned string; `\` on Windows and `/` on all other OSs.
when defined(windows):
result = getEnv("APPDATA").string
else:
result = getEnv("XDG_CONFIG_HOME", getEnv("HOME").string / ".config").string
result.normalizePathEnd(trailingSep = true)
proc getTempDir*(): string {.rtl, extern: "nos$1",
tags: [ReadEnvEffect, ReadIOEffect].} =
## Returns the temporary directory of the current user for applications to
## save temporary files in.
##
## **Please do not use this**: On Android, it currently
## returns ``getHomeDir()``, and on other Unix based systems it can cause
## security problems too. That said, you can override this implementation
## by adding ``-d:tempDir=mytempname`` to your compiler invokation.
when defined(tempDir):
const tempDir {.strdefine.}: string = nil
return tempDir
elif defined(windows): return string(getEnv("TEMP")) & "\\"
elif defined(android): return getHomeDir()
else: return "/tmp/"
proc expandTilde*(path: string): string {.
tags: [ReadEnvEffect, ReadIOEffect].} =
## Expands ``~`` or a path starting with ``~/`` to a full path, replacing
## ``~`` with ``getHomeDir()`` (otherwise returns ``path`` unmodified).
##
## Windows: this is still supported despite Windows platform not having this
## convention; also, both ``~/`` and ``~\`` are handled.
runnableExamples:
doAssert expandTilde("~" / "appname.cfg") == getHomeDir() / "appname.cfg"
if len(path) == 0 or path[0] != '~':
result = path
elif len(path) == 1:
result = getHomeDir()
elif (path[1] in {DirSep, AltSep}):
result = getHomeDir() / path.substr(2)
else:
# TODO: handle `~bob` and `~bob/` which means home of bob
result = path
# TODO: consider whether quoteShellPosix, quoteShellWindows, quoteShell, quoteShellCommand
# belong in `strutils` instead; they are not specific to paths
proc quoteShellWindows*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
## Quote s, so it can be safely passed to Windows API.
## Based on Python's subprocess.list2cmdline
## See http://msdn.microsoft.com/en-us/library/17w5ykft.aspx
let needQuote = {' ', '\t'} in s or s.len == 0
result = ""
var backslashBuff = ""
if needQuote:
result.add("\"")
for c in s:
if c == '\\':
backslashBuff.add(c)
elif c == '\"':
result.add(backslashBuff)
result.add(backslashBuff)
backslashBuff.setLen(0)
result.add("\\\"")
else:
if backslashBuff.len != 0:
result.add(backslashBuff)
backslashBuff.setLen(0)
result.add(c)
if needQuote:
result.add("\"")
proc quoteShellPosix*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
## Quote ``s``, so it can be safely passed to POSIX shell.
## Based on Python's pipes.quote
const safeUnixChars = {'%', '+', '-', '.', '/', '_', ':', '=', '@',
'0'..'9', 'A'..'Z', 'a'..'z'}
if s.len == 0:
return "''"
let safe = s.allCharsInSet(safeUnixChars)
if safe:
return s
else:
return "'" & s.replace("'", "'\"'\"'") & "'"
when defined(windows) or defined(posix) or defined(nintendoswitch):
proc quoteShell*(s: string): string {.noSideEffect, rtl, extern: "nosp$1".} =
## Quote ``s``, so it can be safely passed to shell.
when defined(windows):
return quoteShellWindows(s)
else:
return quoteShellPosix(s)
proc quoteShellCommand*(args: openArray[string]): string =
## Concatenates and quotes shell arguments `args`
runnableExamples:
when defined(posix):
assert quoteShellCommand(["aaa", "", "c d"]) == "aaa '' 'c d'"
when defined(windows):
assert quoteShellCommand(["aaa", "", "c d"]) == "aaa \"\" \"c d\""
# can't use `map` pending https://github.com/nim-lang/Nim/issues/8303
for i in 0..<args.len:
if i > 0: result.add " "
result.add quoteShell(args[i])
when not weirdTarget:
proc c_rename(oldname, newname: cstring): cint {.
importc: "rename", header: "<stdio.h>".}
proc c_system(cmd: cstring): cint {.
importc: "system", header: "<stdlib.h>".}
proc c_strlen(a: cstring): cint {.
importc: "strlen", header: "<string.h>", noSideEffect.}
proc c_free(p: pointer) {.
importc: "free", header: "<stdlib.h>".}
when defined(windows) and not weirdTarget:
when useWinUnicode:
template wrapUnary(varname, winApiProc, arg: untyped) =
var varname = winApiProc(newWideCString(arg))
template wrapBinary(varname, winApiProc, arg, arg2: untyped) =
var varname = winApiProc(newWideCString(arg), arg2)
proc findFirstFile(a: string, b: var WIN32_FIND_DATA): Handle =
result = findFirstFileW(newWideCString(a), b)
template findNextFile(a, b: untyped): untyped = findNextFileW(a, b)
template getCommandLine(): untyped = getCommandLineW()
template getFilename(f: untyped): untyped =
$cast[WideCString](addr(f.cFilename[0]))
else:
template findFirstFile(a, b: untyped): untyped = findFirstFileA(a, b)
template findNextFile(a, b: untyped): untyped = findNextFileA(a, b)
template getCommandLine(): untyped = getCommandLineA()
template getFilename(f: untyped): untyped = $f.cFilename
proc skipFindData(f: WIN32_FIND_DATA): bool {.inline.} =
# Note - takes advantage of null delimiter in the cstring
const dot = ord('.')
result = f.cFileName[0].int == dot and (f.cFileName[1].int == 0 or
f.cFileName[1].int == dot and f.cFileName[2].int == 0)
proc existsFile*(filename: string): bool {.rtl, extern: "nos$1",
tags: [ReadDirEffect], noNimScript.} =
## Returns true if `filename` exists and is a regular file or symlink.
## (directories, device files, named pipes and sockets return false)
## This proc is not available for NimScript.
when defined(windows):
when useWinUnicode:
wrapUnary(a, getFileAttributesW, filename)
else:
var a = getFileAttributesA(filename)
if a != -1'i32:
result = (a and FILE_ATTRIBUTE_DIRECTORY) == 0'i32
else:
var res: Stat
return stat(filename, res) >= 0'i32 and S_ISREG(res.st_mode)
proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect],
noNimScript.} =
## Returns true iff the directory `dir` exists. If `dir` is a file, false
## is returned. Follows symlinks.
when defined(windows):
when useWinUnicode:
wrapUnary(a, getFileAttributesW, dir)
else:
var a = getFileAttributesA(dir)
if a != -1'i32:
result = (a and FILE_ATTRIBUTE_DIRECTORY) != 0'i32
else:
var res: Stat
return stat(dir, res) >= 0'i32 and S_ISDIR(res.st_mode)
proc symlinkExists*(link: string): bool {.rtl, extern: "nos$1",
tags: [ReadDirEffect],
noNimScript.} =
## Returns true iff the symlink `link` exists. Will return true
## regardless of whether the link points to a directory or file.
when defined(windows):
when useWinUnicode:
wrapUnary(a, getFileAttributesW, link)
else:
var a = getFileAttributesA(link)
if a != -1'i32:
result = (a and FILE_ATTRIBUTE_REPARSE_POINT) != 0'i32
else:
var res: Stat
return lstat(link, res) >= 0'i32 and S_ISLNK(res.st_mode)
proc fileExists*(filename: string): bool {.inline, noNimScript.} =
## Synonym for existsFile
existsFile(filename)
proc dirExists*(dir: string): bool {.inline, noNimScript.} =
## Synonym for existsDir
existsDir(dir)
when not defined(windows) and not weirdTarget:
proc checkSymlink(path: string): bool =
var rawInfo: Stat
if lstat(path, rawInfo) < 0'i32: result = false
else: result = S_ISLNK(rawInfo.st_mode)
const
ExeExts* = when defined(windows): ["exe", "cmd", "bat"] else: [""] ## \
## platform specific file extension for executables. On Windows
## ``["exe", "cmd", "bat"]``, on Posix ``[""]``.
proc findExe*(exe: string, followSymlinks: bool = true;
extensions: openarray[string]=ExeExts): string {.
tags: [ReadDirEffect, ReadEnvEffect, ReadIOEffect], noNimScript.} =
## Searches for `exe` in the current working directory and then
## in directories listed in the ``PATH`` environment variable.
## Returns "" if the `exe` cannot be found. `exe`
## is added the `ExeExts <#ExeExts>`_ file extensions if it has none.
## If the system supports symlinks it also resolves them until it
## meets the actual file. This behavior can be disabled if desired.
if exe.len == 0: return
template checkCurrentDir() =
for ext in extensions:
result = addFileExt(exe, ext)
if existsFile(result): return
when defined(posix):
if '/' in exe: checkCurrentDir()
else:
checkCurrentDir()
let path = string(getEnv("PATH"))
for candidate in split(path, PathSep):
if candidate.len == 0: continue
when defined(windows):
var x = (if candidate[0] == '"' and candidate[^1] == '"':
substr(candidate, 1, candidate.len-2) else: candidate) /
exe
else:
var x = expandTilde(candidate) / exe
for ext in extensions:
var x = addFileExt(x, ext)
if existsFile(x):
when not defined(windows):
while followSymlinks: # doubles as if here
if x.checkSymlink:
var r = newString(256)
var len = readlink(x, r, 256)
if len < 0:
raiseOSError(osLastError())
if len > 256:
r = newString(len+1)
len = readlink(x, r, len)
setLen(r, len)
if isAbsolute(r):
x = r
else:
x = parentDir(x) / r
else:
break
return x
result = ""
when weirdTarget:
const times = "fake const"
template Time(x: untyped): untyped = string
proc getLastModificationTime*(file: string): times.Time {.rtl, extern: "nos$1", noNimScript.} =
## Returns the `file`'s last modification time.
when defined(posix):
var res: Stat
if stat(file, res) < 0'i32: raiseOSError(osLastError())
result = res.st_mtim.toTime
else:
var f: WIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: raiseOSError(osLastError())
result = fromWinTime(rdFileTime(f.ftLastWriteTime))
findClose(h)
proc getLastAccessTime*(file: string): times.Time {.rtl, extern: "nos$1", noNimScript.} =
## Returns the `file`'s last read or write access time.
when defined(posix):
var res: Stat
if stat(file, res) < 0'i32: raiseOSError(osLastError())
result = res.st_atim.toTime
else:
var f: WIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: raiseOSError(osLastError())
result = fromWinTime(rdFileTime(f.ftLastAccessTime))
findClose(h)
proc getCreationTime*(file: string): times.Time {.rtl, extern: "nos$1", noNimScript.} =
## Returns the `file`'s creation time.
##
## **Note:** Under POSIX OS's, the returned time may actually be the time at
## which the file's attribute's were last modified. See
## `here <https://github.com/nim-lang/Nim/issues/1058>`_ for details.
when defined(posix):
var res: Stat
if stat(file, res) < 0'i32: raiseOSError(osLastError())
result = res.st_ctim.toTime
else:
var f: WIN32_FIND_DATA
var h = findFirstFile(file, f)
if h == -1'i32: raiseOSError(osLastError())
result = fromWinTime(rdFileTime(f.ftCreationTime))
findClose(h)
proc fileNewer*(a, b: string): bool {.rtl, extern: "nos$1", noNimScript.} =
## Returns true if the file `a` is newer than file `b`, i.e. if `a`'s
## modification time is later than `b`'s.
when defined(posix):
# If we don't have access to nanosecond resolution, use '>='
when not StatHasNanoseconds:
result = getLastModificationTime(a) >= getLastModificationTime(b)
else:
result = getLastModificationTime(a) > getLastModificationTime(b)
else:
result = getLastModificationTime(a) > getLastModificationTime(b)
proc getCurrentDir*(): string {.rtl, extern: "nos$1", tags: [], noNimScript.} =
## Returns the `current working directory`:idx:.
when defined(windows):
var bufsize = MAX_PATH.int32
when useWinUnicode:
var res = newWideCString("", bufsize)
while true:
var L = getCurrentDirectoryW(bufsize, res)
if L == 0'i32:
raiseOSError(osLastError())
elif L > bufsize:
res = newWideCString("", L)
bufsize = L
else:
result = res$L
break
else:
result = newString(bufsize)
while true:
var L = getCurrentDirectoryA(bufsize, result)
if L == 0'i32:
raiseOSError(osLastError())
elif L > bufsize:
result = newString(L)
bufsize = L
else:
setLen(result, L)
break
else:
var bufsize = 1024 # should be enough
result = newString(bufsize)
while true:
if getcwd(result, bufsize) != nil:
setLen(result, c_strlen(result))
break
else:
let err = osLastError()
if err.int32 == ERANGE:
bufsize = bufsize shl 1
doAssert(bufsize >= 0)
result = newString(bufsize)
else:
raiseOSError(osLastError())
proc setCurrentDir*(newDir: string) {.inline, tags: [], noNimScript.} =
## Sets the `current working directory`:idx:; `OSError` is raised if
## `newDir` cannot been set.
when defined(Windows):
when useWinUnicode:
if setCurrentDirectoryW(newWideCString(newDir)) == 0'i32:
raiseOSError(osLastError())
else:
if setCurrentDirectoryA(newDir) == 0'i32: raiseOSError(osLastError())
else:
if chdir(newDir) != 0'i32: raiseOSError(osLastError())
when not weirdTarget:
proc absolutePath*(path: string, root = getCurrentDir()): string {.noNimScript.} =
## Returns the absolute path of `path`, rooted at `root` (which must be absolute)
## if `path` is absolute, return it, ignoring `root`
runnableExamples:
doAssert absolutePath("a") == getCurrentDir() / "a"
if isAbsolute(path): path
else:
if not root.isAbsolute:
raise newException(ValueError, "The specified root is not absolute: " & root)
joinPath(root, path)
proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
tags: [ReadDirEffect], noNimScript.} =
## Returns the full (`absolute`:idx:) path of an existing file `filename`,
## raises OSError in case of an error. Follows symlinks.
when defined(windows):
var bufsize = MAX_PATH.int32
when useWinUnicode:
var unused: WideCString = nil
var res = newWideCString("", bufsize)
while true:
var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused)
if L == 0'i32:
raiseOSError(osLastError())
elif L > bufsize:
res = newWideCString("", L)
bufsize = L
else:
result = res$L
break
else:
var unused: cstring = nil
result = newString(bufsize)
while true:
var L = getFullPathNameA(filename, bufsize, result, unused)
if L == 0'i32:
raiseOSError(osLastError())
elif L > bufsize:
result = newString(L)
bufsize = L
else:
setLen(result, L)
break
else:
# according to Posix we don't need to allocate space for result pathname.
# But we need to free return value with free(3).
var r = realpath(filename, nil)
if r.isNil:
raiseOSError(osLastError())
else:
result = $r
c_free(cast[pointer](r))
proc normalizePath*(path: var string) {.rtl, extern: "nos$1", tags: [], noNimScript.} =
## Normalize a path.
##
## Consecutive directory separators are collapsed, including an initial double slash.
##
## On relative paths, double dot (..) sequences are collapsed if possible.
## On absolute paths they are always collapsed.
##
## Warning: URL-encoded and Unicode attempts at directory traversal are not detected.
## Triple dot is not handled.
path = pathnorm.normalizePath(path)