-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
fs.cljc
1325 lines (1161 loc) · 47.9 KB
/
fs.cljc
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
(ns babashka.fs
(:require [clojure.java.io :as io]
[clojure.string :as str]
[clojure.walk :as walk])
(:import [java.io File InputStream]
[java.net URI]
[java.nio.file StandardOpenOption CopyOption
#?@(:bb [] :clj [DirectoryStream]) #?@(:bb [] :clj [DirectoryStream$Filter])
Files
FileSystems
FileVisitOption
FileVisitResult
StandardCopyOption
LinkOption Path
FileVisitor]
[java.nio.file.attribute BasicFileAttributes FileAttribute FileTime PosixFilePermissions PosixFilePermission]
[java.nio.charset Charset]
[java.util HashSet]
[java.util.zip GZIPInputStream GZIPOutputStream ZipInputStream ZipOutputStream ZipEntry]
[java.io File BufferedInputStream FileInputStream FileOutputStream]))
(set! *warn-on-reflection* true)
(def ^:private fvr-lookup
{:continue FileVisitResult/CONTINUE
:skip-subtree FileVisitResult/SKIP_SUBTREE
:skip-siblings FileVisitResult/SKIP_SIBLINGS
:terminate FileVisitResult/TERMINATE})
(defn- file-visit-result
[x]
(if (instance? FileVisitResult x) x
(or (fvr-lookup x)
(throw (Exception. "Expected: one of :continue, :skip-subtree, :skip-siblings, :terminate.")))))
(defn- as-path
^Path [path]
(if (instance? Path path) path
(if (instance? URI path)
(java.nio.file.Paths/get ^URI path)
(.toPath (io/file path)))))
(defn- as-file
"Coerces a path into a file if it isn't already one."
^java.io.File [path]
(if (instance? Path path) (.toFile ^Path path)
(io/file path)))
(defn- get-env [k]
(System/getenv k))
(defn path
"Coerces f into a Path. Multiple-arg versions treat the first argument as
parent and subsequent args as children relative to the parent."
(^Path [f]
(as-path f))
(^Path [parent child]
(as-path (io/file (as-file parent) (as-file child))))
(^Path [parent child & more]
(reduce path (path parent child) more)))
(defn file
"Coerces f into a File. Multiple-arg versions treat the first argument
as parent and subsequent args as children relative to the parent."
(^File [f] (as-file f))
(^File [f & fs]
(apply io/file (map as-file (cons f fs)))))
(defn- ->link-opts ^"[Ljava.nio.file.LinkOption;"
[nofollow-links]
(into-array LinkOption
(cond-> []
nofollow-links
(conj LinkOption/NOFOLLOW_LINKS))))
(defn real-path
"Converts f into real path via Path#toRealPath."
(^Path [f] (real-path f nil))
(^Path [f {:keys [:nofollow-links]}]
(.toRealPath (as-path f) (->link-opts nofollow-links))))
(defn owner
"Returns the owner of a file. Call `str` on it to get the owner name
as a string."
([f] (owner f nil))
([f {:keys [:nofollow-links]}]
(Files/getOwner (as-path f) (->link-opts nofollow-links))))
;;;; Predicates
(defn regular-file?
"Returns true if f is a regular file, using Files/isRegularFile."
([f] (regular-file? f nil))
([f {:keys [:nofollow-links]}]
(Files/isRegularFile (as-path f)
(->link-opts nofollow-links))))
(defn directory?
"Returns true if f is a directory, using Files/isDirectory."
([f] (directory? f nil))
([f {:keys [:nofollow-links]}]
(Files/isDirectory (as-path f)
(->link-opts nofollow-links))))
(def ^:private simple-link-opts
(into-array LinkOption []))
(defn- directory-simple?
[^Path f] (Files/isDirectory f simple-link-opts))
(defn hidden?
"Returns true if f is hidden."
[f] (Files/isHidden (as-path f)))
(defn absolute?
"Returns true if f represents an absolute path."
[f] (.isAbsolute (as-path f)))
(defn executable?
"Returns true if f is executable."
[f] (Files/isExecutable (as-path f)))
(defn readable?
"Returns true if f is readable"
[f] (Files/isReadable (as-path f)))
(defn writable?
"Returns true if f is writable"
[f] (Files/isWritable (as-path f)))
(defn relative?
"Returns true if f represents a relative path."
[f] (not (absolute? f)))
(defn exists?
"Returns true if f exists."
([f] (exists? f nil))
([f {:keys [:nofollow-links]}]
(try
(Files/exists
(as-path f)
(->link-opts nofollow-links))
(catch Exception _e
false))))
;;;; End predicates
(defn components
"Returns a seq of all components of f as paths, i.e. split on the file
separator."
[f]
(seq (as-path f)))
(defn absolutize
"Converts f into an absolute path via Path#toAbsolutePath."
[f] (.toAbsolutePath (as-path f)))
(defn relativize
"Returns relative path by comparing this with other."
^Path [this other]
(.relativize (as-path this) (as-path other)))
(defn normalize
"Normalizes f via Path#normalize."
[f]
(.normalize (as-path f)))
(defn canonicalize
"Returns the canonical path via
java.io.File#getCanonicalPath. If `:nofollow-links` is set, then it
will fall back on `absolutize` + `normalize.` This function can be used
as an alternative to `real-path` which requires files to exist."
(^Path [f] (canonicalize f nil))
(^Path [f {:keys [:nofollow-links]}]
(if nofollow-links
(-> f absolutize normalize)
(as-path (.getCanonicalPath (as-file f))))))
(defn file-name
"Returns the name of the file or directory. E.g. (file-name \"foo/bar/baz\") returns \"baz\"."
[x]
(.getName (as-file x)))
(def ^:private continue (constantly :continue))
(defn walk-file-tree
"Walks f using Files/walkFileTree. Visitor functions: :pre-visit-dir,
:post-visit-dir, :visit-file, :visit-file-failed. All visitor functions
default to (constantly :continue). Supported return
values: :continue, :skip-subtree, :skip-siblings, :terminate. A
different return value will throw."
[f
{:keys [:pre-visit-dir :post-visit-dir
:visit-file :visit-file-failed
:follow-links :max-depth]}]
(let [pre-visit-dir (or pre-visit-dir continue)
post-visit-dir (or post-visit-dir continue)
visit-file (or visit-file continue)
max-depth (or max-depth Integer/MAX_VALUE)
visit-opts (set (cond-> []
follow-links (conj FileVisitOption/FOLLOW_LINKS)))
visit-file-failed (or visit-file-failed
(fn [_path _attrs]
:continue))]
(Files/walkFileTree (as-path f)
visit-opts
max-depth
(reify FileVisitor
(preVisitDirectory [_ dir attrs]
(-> (pre-visit-dir dir attrs)
file-visit-result))
(postVisitDirectory [_ dir ex]
(-> (post-visit-dir dir ex)
file-visit-result))
(visitFile [_ path attrs]
(-> (visit-file path attrs)
file-visit-result))
(visitFileFailed [_ path ex]
(-> (visit-file-failed path ex)
file-visit-result))))))
#?(:bb nil :clj
(defn- directory-stream
"Returns a stream of all files in dir. The caller of this function is
responsible for closing the stream, e.g. using with-open. The stream
can consumed as a seq by calling seq on it. Accepts optional glob or
accept function of one argument."
(^DirectoryStream [dir]
(Files/newDirectoryStream (as-path dir)))
(^DirectoryStream [dir glob-or-accept]
(if (string? glob-or-accept)
(Files/newDirectoryStream (as-path dir) (str glob-or-accept))
(let [accept* glob-or-accept]
(Files/newDirectoryStream (as-path dir)
(reify DirectoryStream$Filter
(accept [_ entry]
(boolean (accept* entry))))))))))
#?(:bb nil :clj
(defn list-dir
"Returns all paths in dir as vector. For descending into subdirectories use `glob.`
- `glob-or-accept` - a glob string such as \"*.edn\" or a (fn accept [^java.nio.file.Path p]) -> truthy"
([dir]
(with-open [stream (directory-stream dir)]
(vec stream)))
([dir glob-or-accept]
(with-open [stream (directory-stream dir glob-or-accept)]
(vec stream)))))
(def file-separator File/separator)
(def path-separator File/pathSeparator)
(def ^:private win?
(-> (System/getProperty "os.name")
(str/lower-case)
(str/includes? "win")))
(defn match
"Given a file and match pattern, returns matches as vector of
paths. Pattern interpretation is done using the rules described in
https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String).
Options:
* `:hidden` - match hidden paths - note: on Windows paths starting with
a dot are not hidden, unless their hidden attribute is set.
* `:follow-links` - follow symlinks.
* `:recursive` - match recursively.
* `:max-depth` - max depth to descend into directory structure.
Examples:
`(fs/match \".\" \"regex:.*\\\\.clj\" {:recursive true})`"
([root pattern] (match root pattern nil))
([root pattern {:keys [hidden follow-links max-depth recursive]}]
(let [base-path (-> root absolutize normalize)
base-path (if win?
(str/replace base-path file-separator (str "\\" file-separator))
(str base-path))
skip-hidden? (not hidden)
results (atom (transient []))
past-root? (volatile! nil)
[prefix pattern] (str/split pattern #":")
pattern (let [separator (when-not (str/ends-with? base-path file-separator)
;; we need to escape the file separator on Windows
(str (when win? "\\")
file-separator))]
(str base-path
separator
(if win?
(str/replace pattern "/" "\\\\")
pattern)))
pattern (str prefix ":" pattern)
matcher (.getPathMatcher
(FileSystems/getDefault)
pattern)
match (fn [^Path path]
(when (.matches matcher path)
(swap! results conj! path))
nil)]
(walk-file-tree
base-path
{:max-depth max-depth
:follow-links follow-links
:pre-visit-dir (fn [dir _attrs]
(if (and @past-root?
(or (not recursive)
(and skip-hidden?
(hidden? dir))))
:skip-subtree
(do
(if @past-root? (match dir)
(vreset! past-root? true))
:continue)))
:visit-file (fn [path _attrs]
(when-not (and skip-hidden?
(hidden? path))
(match path))
:continue)})
(let [results (persistent! @results)
absolute-cwd (absolutize "")]
(if (relative? root)
(mapv #(relativize absolute-cwd %)
results)
results)))))
(defn glob
"Given a file and glob pattern, returns matches as vector of
paths. Patterns containing `**` or `/` will cause a recursive walk over
path, unless overriden with :recursive. Similarly: :hidden will be enabled (when not set)
when `pattern` starts with a dot.
Glob interpretation is done using the rules described in
https://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String).
Options:
* `:hidden` - match hidden paths. Implied when `pattern` starts with a dot. Note: on Windows files starting with a dot are not hidden, unless their hidden attribute is set.
* `:follow-links` - follow symlinks.
* `:recursive` - force recursive search. Implied when `pattern` contains `**` or `/`.
* `:max-depth` - max depth to descend into directory structure.
Examples:
`(fs/glob \".\" \"**.clj\")`"
([root pattern] (glob root pattern nil))
([root pattern opts]
(let [recursive (:recursive opts
(or (str/includes? pattern "**")
(str/includes? pattern file-separator)
(when win?
(str/includes? pattern "/"))))
hidden (:hidden opts (str/starts-with? pattern "."))]
(match root (str "glob:" pattern) (assoc opts :recursive recursive :hidden hidden)))))
(defn- ->copy-opts ^"[Ljava.nio.file.CopyOption;"
[replace-existing copy-attributes atomic-move nofollow-links]
(into-array CopyOption
(cond-> []
replace-existing (conj StandardCopyOption/REPLACE_EXISTING)
copy-attributes (conj StandardCopyOption/COPY_ATTRIBUTES)
atomic-move (conj StandardCopyOption/ATOMIC_MOVE)
nofollow-links (conj LinkOption/NOFOLLOW_LINKS))))
(defn copy
"Copies src file to dest dir or file.
Options:
* `:replace-existing`
* `:copy-attributes`
* `:nofollow-links` (used to determine to copy symbolic link itself or not)."
([src dest] (copy src dest nil))
([src dest {:keys [replace-existing
copy-attributes
nofollow-links]}]
(let [copy-options (->copy-opts replace-existing copy-attributes false nofollow-links)
dest (as-path dest)
dest (if (directory-simple? dest)
(path dest (file-name src))
dest)
input-stream? (instance? java.io.InputStream src)]
(if input-stream?
(Files/copy ^java.io.InputStream src dest copy-options)
(Files/copy (as-path src) dest copy-options)))))
(defn posix->str
"Converts a set of PosixFilePermission to a string."
[p]
(PosixFilePermissions/toString p))
(defn str->posix
"Converts a string to a set of PosixFilePermission.
`s` is a string like `\"rwx------\"`."
[s]
(PosixFilePermissions/fromString s))
(defn- ->posix-file-permissions [s]
(cond (string? s)
(str->posix s)
;; (set? s)
;; (into #{} (map keyword->posix-file-permission) s)
:else
s))
(defn- posix->file-attribute [x]
(PosixFilePermissions/asFileAttribute x))
(defn- posix->attrs
^"[Ljava.nio.file.attribute.FileAttribute;" [posix-file-permissions]
(let [attrs (if posix-file-permissions
(-> posix-file-permissions
(->posix-file-permissions)
(posix->file-attribute)
vector)
[])]
(into-array FileAttribute attrs)))
(defn create-dir
"Creates dir using `Files#createDirectory`. Does not create parents."
([path]
(create-dir path nil))
([path {:keys [:posix-file-permissions]}]
(let [attrs (posix->attrs posix-file-permissions)]
(Files/createDirectory (as-path path) attrs))))
(defn create-dirs
"Creates directories using `Files#createDirectories`. Also creates parents if needed.
Doesn't throw an exception if the dirs exist already. Similar to `mkdir -p`"
([path] (create-dirs path nil))
([path {:keys [:posix-file-permissions]}]
(Files/createDirectories (as-path path) (posix->attrs posix-file-permissions))))
(defn set-posix-file-permissions
"Sets posix file permissions on f. Accepts a string like `\"rwx------\"` or a set of PosixFilePermission."
[f posix-file-permissions]
(Files/setPosixFilePermissions (as-path f) (->posix-file-permissions posix-file-permissions)))
(defn posix-file-permissions
"Gets f's posix file permissions. Use posix->str to view as a string."
([f] (posix-file-permissions f nil))
([f {:keys [:nofollow-links]}]
(Files/getPosixFilePermissions (as-path f) (->link-opts nofollow-links))))
(defn- u+wx
[f]
(if win?
(.setWritable (file f) true)
(let [^HashSet perms (posix-file-permissions f)
p1 (.add perms PosixFilePermission/OWNER_WRITE)
p2 (.add perms PosixFilePermission/OWNER_EXECUTE)]
(when (or p1 p2)
(set-posix-file-permissions f perms)))))
(defn copy-tree
"Copies entire file tree from src to dest. Creates dest if needed
using `create-dirs`, passing it the `:posix-file-permissions`
option. Supports same options as copy."
([src dest] (copy-tree src dest nil))
([src dest {:keys [:replace-existing
:copy-attributes
:nofollow-links]
:as opts}]
;; cf. Python
(when-not (directory? src)
(throw (IllegalArgumentException. (str "Not a directory: " src))))
;; cf. Python
(when (and (exists? dest)
(not (directory? dest)))
(throw (IllegalArgumentException. (str "Not a directory: " dest))))
;; cf. Python
(create-dirs dest opts)
(let [copy-options (->copy-opts replace-existing copy-attributes false nofollow-links)
link-options (->link-opts nofollow-links)
from (real-path src {:nofollow-links nofollow-links})
;; using canonicalize here because real-path requires the path to exist
to (canonicalize dest {:nofollow-links nofollow-links})]
(walk-file-tree from {:pre-visit-dir (fn [dir _attrs]
(let [rel (relativize from dir)
to-dir (path to rel)]
(when-not (Files/exists to-dir link-options)
(Files/copy ^Path dir to-dir
^"[Ljava.nio.file.CopyOption;"
copy-options)
(when-not win?
(u+wx to-dir))))
:continue)
:visit-file (fn [from-path _attrs]
(let [rel (relativize from from-path)
to-file (path to rel)]
(Files/copy ^Path from-path to-file
^"[Ljava.nio.file.CopyOption;"
copy-options)
:continue)
:continue)
:post-visit-dir (fn [dir _ex]
(let [rel (relativize from dir)
to-dir (path to rel)]
(when-not win?
(let [perms (posix-file-permissions (file dir))]
(Files/setPosixFilePermissions to-dir perms)))
:continue))}))))
(declare posix-file-permissions)
(declare set-posix-file-permissions)
(defn temp-dir
"Returns `java.io.tmpdir` property as path."
[]
(as-path (System/getProperty "java.io.tmpdir")))
(defn create-temp-dir
"Creates a temporary directory using Files#createDirectories.
- `(create-temp-dir)`: creates temp dir with random prefix.
- `(create-temp-dir {:keys [:dir :prefix :posix-file-permissions]})`:
create temp dir in dir with prefix. If prefix is not provided, a random one
is generated. If path is not provided, the directory is created as if called with `(create-temp-dir)`.
File permissions can be specified with an `:posix-file-permissions` option.
String format for posix file permissions is described in the `str->posix` docstring."
([]
(Files/createTempDirectory
(str (java.util.UUID/randomUUID))
(make-array FileAttribute 0)))
([{:keys [:dir :prefix :posix-file-permissions] :as opts}]
(let [attrs (posix->attrs posix-file-permissions)
prefix (or prefix (str (java.util.UUID/randomUUID)))
dir (or dir (:path opts))]
(if dir
(Files/createTempDirectory
(as-path dir)
prefix
attrs)
(Files/createTempDirectory
prefix
attrs)))))
(defn create-temp-file
"Creates an empty temporary file using Files#createTempFile.
- `(create-temp-file)`: creates temp file with random prefix and suffix.
- `(create-temp-dir {:keys [:dir :prefix :suffix :posix-file-permissions]})`:
create temp file in dir with prefix. If prefix and suffix are not provided,
random ones are generated.
File permissions can be specified with an `:posix-file-permissions` option.
String format for posix file permissions is described in the `str->posix` docstring."
([]
(Files/createTempFile
(str (java.util.UUID/randomUUID))
(str (java.util.UUID/randomUUID))
(make-array FileAttribute 0)))
([{:keys [:dir :prefix :suffix :posix-file-permissions] :as opts}]
(let [attrs (posix->attrs posix-file-permissions)
prefix (or prefix (str (java.util.UUID/randomUUID)))
suffix (or suffix (str (java.util.UUID/randomUUID)))
dir (or dir
;; backwards compat
(:path opts))]
(if dir
(Files/createTempFile
(as-path dir)
prefix
suffix
attrs)
(Files/createTempFile
prefix
suffix
attrs)))))
(defn create-sym-link
"Create a soft link from path to target."
[path target]
(Files/createSymbolicLink
(as-path path)
(as-path target)
(make-array FileAttribute 0)))
(defn create-link
"Create a hard link from path to target."
[path target]
(Files/createLink
(as-path path)
(as-path target)))
(defn read-link
"Reads the target of a symbolic link. The target need not exist."
[path]
(java.nio.file.Files/readSymbolicLink (as-path path)))
(defn delete
"Deletes f. Returns nil if the delete was successful,
throws otherwise. Does not follow symlinks."
;; We don't follow symlinks, since the link can target a dir and you should be
;; using delete-tree to delete that.
[f]
(Files/delete (as-path f)))
(defn delete-if-exists
"Deletes f if it exists. Returns true if the delete was successful,
false if f didn't exist. Does not follow symlinks."
[f]
(Files/deleteIfExists (as-path f)))
(defn sym-link?
"Determines if `f` is a symbolic link via `java.nio.file.Files/isSymbolicLink`."
[f]
(Files/isSymbolicLink (as-path f)))
(defn delete-tree
"Deletes a file tree using `walk-file-tree`. Similar to `rm -rf`. Does not follow symlinks.
`force` ensures read-only directories/files are deleted. Similar to `chmod -R +wx` + `rm -rf`"
;; See delete-permission-assumptions-test
;; Implementation with the force flag is based on those assumptions
([root] (delete-tree root nil))
([root {:keys [force]}]
(when (exists? root)
(walk-file-tree root
{:visit-file (fn [path _]
(when (and win? force)
(.setWritable (file path) true))
(delete path)
:continue)
:pre-visit-dir (fn [path _]
(when force
(u+wx path))
:continue)
:post-visit-dir (fn [path _]
(delete path)
:continue)}))))
(defn create-file
"Creates empty file using `Files#createFile`.
File permissions can be specified with an `:posix-file-permissions` option.
String format for posix file permissions is described in the `str->posix` docstring."
([path]
(create-file path nil))
([path {:keys [:posix-file-permissions]}]
(let [attrs (posix->attrs posix-file-permissions)]
(Files/createFile (as-path path) attrs))))
(defn move
"Move or rename a file to a target dir or file via `Files/move`."
([source target] (move source target nil))
([source target {:keys [:replace-existing
:atomic-move
:nofollow-links]}]
(let [target (as-path target)]
(if (directory-simple? target)
(Files/move (as-path source)
(path target (file-name source))
(->copy-opts replace-existing false atomic-move nofollow-links))
(Files/move (as-path source)
target
(->copy-opts replace-existing false atomic-move nofollow-links))))))
(defn parent
"Returns parent of f. Akin to `dirname` in bash."
[f]
(.getParent (as-path f)))
(defn size
"Returns the size of a file (in bytes)."
[f]
(Files/size (as-path f)))
(defn delete-on-exit
"Requests delete on exit via `File#deleteOnExit`. Returns f."
[f]
(.deleteOnExit (as-file f))
f)
(defn same-file?
"Returns true if this is the same file as other."
[this other]
(Files/isSameFile (as-path this) (as-path other)))
(defn read-all-bytes
"Returns contents of file as byte array."
[f]
(Files/readAllBytes (as-path f)))
(defn- ->charset ^Charset [charset]
(if (string? charset)
(Charset/forName charset)
charset))
(defn read-all-lines
"Read all lines from a file."
([f]
(vec (Files/readAllLines (as-path f))))
([f {:keys [charset]
:or {charset "utf-8"}}]
(vec (Files/readAllLines
(as-path f)
(->charset charset)))))
;;;; Attributes, from github.com/corasaurus-hex/fs
(defn get-attribute
([path attribute]
(get-attribute path attribute nil))
([path attribute {:keys [:nofollow-links]}]
(Files/getAttribute (as-path path)
attribute
(->link-opts {:nofollow-links nofollow-links}))))
(defn- keyize
[key-fn m]
(let [f (fn [[k v]] (if (string? k) [(key-fn k) v] [k v]))]
(walk/postwalk (fn [x] (if (map? x) (into {} (map f x)) x)) m)))
(defn read-attributes*
"Reads attributes via Files/readAttributes."
([path attributes]
(read-attributes* path attributes nil))
([path attributes {:keys [:nofollow-links]}]
(let [p (as-path path)
link-opts (->link-opts {:nofollow-links nofollow-links})
attrs
;; prevent reflection warning
(if (instance? String attributes)
(Files/readAttributes p
^String attributes
link-opts)
(Files/readAttributes p
^Class attributes
link-opts))]
attrs)))
(defn read-attributes
"Same as `read-attributes*` but turns attributes into a map and keywordizes keys.
Keywordizing can be changed by passing a :key-fn in the options map."
([path attributes]
(read-attributes path attributes nil))
([path attributes {:keys [:nofollow-links :key-fn] :as opts}]
(->> (read-attributes* path attributes opts)
(into {})
(keyize (or key-fn keyword)))))
(defn set-attribute
([path attribute value]
(set-attribute path attribute value nil))
([path attribute value {:keys [:nofollow-links]}]
(Files/setAttribute (as-path path)
attribute
value
(->link-opts {:nofollow-links nofollow-links}))))
(defn file-time->instant
"Converts a java.nio.file.attribute.FileTime to a java.time.Instant."
[^FileTime ft]
(.toInstant ft))
(defn instant->file-time
"Converts a java.time.Instant to a java.nio.file.attribute.FileTime."
[instant]
(FileTime/from instant))
(defn file-time->millis
"Converts a java.nio.file.attribute.FileTime to epoch millis (long)."
[^FileTime ft]
(.toMillis ft))
(defn millis->file-time
"Converts epoch millis (long) to a java.nio.file.attribute.FileTime."
[millis]
(FileTime/fromMillis millis))
(defn- ->file-time [x]
(cond (int? x) (millis->file-time x)
(instance? java.time.Instant x) (instant->file-time x)
:else x))
(defn last-modified-time
"Returns last modified time as a java.nio.file.attribute.FileTime."
([f]
(last-modified-time f nil))
([f {:keys [nofollow-links] :as opts}]
(get-attribute f "basic:lastModifiedTime" opts)))
(defn set-last-modified-time
"Sets last modified time of f to time (millis, java.time.Instant or java.nio.file.attribute.FileTime)."
([f time]
(set-last-modified-time f time nil))
([f time {:keys [nofollow-links] :as opts}]
(set-attribute f "basic:lastModifiedTime" (->file-time time) opts)))
(defn creation-time
"Returns creation time as FileTime."
([f]
(creation-time f nil))
([f {:keys [nofollow-links] :as opts}]
(get-attribute f "basic:creationTime" opts)))
(defn set-creation-time
"Sets creation time of f to time (millis, java.time.Instant or java.nio.file.attribute.FileTime)."
([f time]
(set-creation-time f time nil))
([f time {:keys [nofollow-links] :as opts}]
(set-attribute f "basic:creationTime" (->file-time time) opts)))
(defn list-dirs
"Similar to list-dir but accepts multiple roots and returns the concatenated results.
- `glob-or-accept` - a glob string such as \"*.edn\" or a (fn accept [^java.nio.file.Path p]) -> truthy"
[dirs glob-or-accept]
(mapcat #(list-dir % glob-or-accept) dirs))
(defn split-ext
"Splits path on extension If provided, a specific extension `ext`, the
extension (without dot), will be used for splitting. Directories
are not processed."
([path] (split-ext path nil))
([path {:keys [ext]}]
(let [path-str (str path)
file-name (file-name path)]
(let [ext (if ext
(str "." ext)
(when-let [last-dot (str/last-index-of file-name ".")]
(subs file-name last-dot)))]
(if (and ext
(str/ends-with? path-str ext)
(not= path-str ext))
(let [loc (str/last-index-of path-str ext)]
[(subs path-str 0 loc)
(subs path-str (inc loc))])
[path-str nil])))))
(defn strip-ext
"Strips extension via `split-ext`."
([path]
(strip-ext path nil))
([path {:keys [ext] :as opts}]
(first (split-ext path opts))))
(defn extension
"Returns the extension of a file via `split-ext`."
[path]
(-> path split-ext last))
(defn split-paths
"Splits a path list given as a string joined by the OS-specific path-separator into a vec of paths.
On UNIX systems, the separator is ':', on Microsoft Windows systems it is ';'."
[^String joined-paths]
(mapv path (.split joined-paths path-separator)))
(defn exec-paths
"Returns executable paths (using the PATH environment variable). Same
as `(split-paths (System/getenv \"PATH\"))`."
[]
(split-paths (System/getenv "PATH")))
(defn- filename-only?
"Returns true if `f` is exactly a file name (i.e. with no absolute or
relative path information."
[f]
(let [f-as-path (as-path f)]
(= f-as-path (.getFileName f-as-path))))
(defn which
"Returns Path to first executable `program` found in `:paths` `opt`, similar to the which Unix command.
Default for `:paths` is `(exec-paths)`.
On Windows, searches for `program` with filename extensions specified in `:win-exts` `opt`.
Default is `[\"com\" \"exe\" \"bat\" \"cmd\"]`.
If `program` already includes an extension from `:win-exts`, it will be searched as-is first.
When `program` is a relative or absolute path, `:paths` is not consulted. On Windows, the `:win-exts`
variants are still searched. On other OSes, the path for `program` will be returned if executable,
else nil."
([program] (which program nil))
([program opts]
(let [exts (if win?
(let [exts (or (:win-exts opts)
["com" "exe" "bat" "cmd"])
ext (extension program)]
(if (and ext (contains? (set exts) ext))
;; this program name already contains the expected extension so we
;; first search with that and then try the others to find e.g. foo.bat.cmd
(into [nil] exts)
exts))
[nil])
paths (or (:paths opts) (babashka.fs/exec-paths))
;; if program is exactly a file name, then search all the path entries
;; otherwise, only search relative to current directory (absolute paths will throw)
candidate-paths (if (filename-only? program)
paths
[nil])]
(loop [paths candidate-paths
results []]
(if (seq paths)
(let [p (first paths)
fs (loop [exts exts
candidates []]
(if (seq exts)
(let [ext (first exts)
program (str program (when ext (str "." ext)))
f (if (babashka.fs/relative? program)
(babashka.fs/path p program)
(babashka.fs/path program))]
(if (and (executable? f) (not (directory? f)))
(recur (rest exts)
(conj candidates f))
(recur (rest exts)
candidates)))
candidates))]
(if (seq fs)
(if (:all opts)
(recur (rest paths) (into results fs))
(first fs))
(recur (rest paths) results)))
(if (:all opts) results (first results)))))))
(defn which-all
"Returns every Path to `program` found in (`exec-paths`). See `which`."
([program] (which-all program nil))
([program opts]
(which program (assoc opts :all true))))
;; the above can be implemented using:
;; user=> (first (filter fs/executable? (fs/list-dirs (filter fs/exists? (fs/exec-path)) "java")))
;; #object[sun.nio.fs.UnixPath 0x1dd74143 "/Users/borkdude/.jenv/versions/11.0/bin/java"]
;; although the which impl is faster
(defn starts-with?
"Returns true if path this starts with path other."
[this other]
(.startsWith (as-path this) (as-path other)))
(defn ends-with?
"Returns true if path this ends with path other."
[this other]
(.endsWith (as-path this) (as-path other)))
;;;; Modified since
(defn- last-modified-1
"Returns max last-modified of regular file f. Returns 0 if file does not exist."
[f]
(if (exists? f)
(file-time->millis
(last-modified-time f))
0))
(defn- last-modified
"Returns max last-modified of f or of all files within f"
[f]
(if (exists? f)
(if (regular-file? f)
(last-modified-1 f)
(apply max 0
(map last-modified-1
(filter regular-file? (file-seq (file f))))))
0))
(defn- expand-file-set
[file-set]
(if (coll? file-set)
(mapcat expand-file-set file-set)
(filter regular-file? (file-seq (file file-set)))))
(defn modified-since
"Returns seq of regular files (non-directories, non-symlinks) from file-set that were modified since the anchor path.
The anchor path can be a regular file or directory, in which case
the recursive max last modified time stamp is used as the timestamp
to compare with. The file-set may be a regular file, directory or
collection of files (e.g. returned by glob). Directories are
searched recursively."
[anchor file-set]
(let [lm (last-modified anchor)]
(map path (filter #(> (last-modified-1 %) lm) (expand-file-set file-set)))))
;;;; End modified since
;;;; Zip
(defn unzip
"Unzips `zip-file` to `dest` directory (default `\".\"`).
Options:
* `:replace-existing` - `true` / `false`: overwrite existing files"
([zip-file] (unzip zip-file "."))
([zip-file dest] (unzip zip-file dest nil))
([zip-file dest {:keys [replace-existing]}]
(let [output-path (as-path dest)
_ (create-dirs dest)
cp-opts (->copy-opts replace-existing nil nil nil)]
(with-open
[^InputStream fis
(if (instance? InputStream zip-file) zip-file
(Files/newInputStream (as-path zip-file) (into-array java.nio.file.OpenOption [])))
zis (ZipInputStream. fis)]
(loop []
(let [entry (.getNextEntry zis)]
(when entry
(let [entry-name (.getName entry)
new-path (.resolve output-path entry-name)]
(if (.isDirectory entry)
(create-dirs new-path)
(do
(create-dirs (parent new-path))
(Files/copy ^java.io.InputStream zis