-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathCommon.hs
More file actions
1558 lines (1376 loc) · 50.4 KB
/
Common.hs
File metadata and controls
1558 lines (1376 loc) · 50.4 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
{-# LANGUAGE UnliftedFFITypes #-}
-- |
-- Module : Streamly.Internal.FileSystem.Path.Common
-- Copyright : (c) 2023 Composewell Technologies
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Portability : GHC
--
module Streamly.Internal.FileSystem.Path.Common
(
-- * Types
OS (..)
-- * Validation
, isValidPath
, isValidPath'
, validatePath
, validatePath'
, validateFile
-- * Construction
, fromChunk
, unsafeFromChunk
, fromChars
, unsafeFromChars
-- * Quasiquoters
, mkQ
-- * Elimination
, toString
, toChars
-- * Separators
, primarySeparator
, isSeparator
, dropTrailingSeparators
, hasTrailingSeparator
, hasLeadingSeparator
-- * Tests
, isBranch
, isRooted
, isAbsolute
-- , isRelative -- not isAbsolute
, isRootRelative -- XXX hasRelativeRoot
, isRelativeWithDrive -- XXX hasRelativeDriveRoot
, hasDrive
-- * Joining
, append
, append'
, unsafeAppend
, appendCString
, appendCString'
, unsafeJoinPaths
-- , joinRoot -- XXX append should be enough
-- * Splitting
-- Note: splitting the search path does not belong here, it is shell aware
-- operation. search path is separated by : and : is allowed in paths on
-- posix. Shell would escape it which needs to be handled.
, splitRoot
-- , dropRoot
-- , dropRelRoot -- if relative then dropRoot
, splitHead
, splitTail
, splitPath
, splitPath_
-- * Dir and File
, splitFile
, splitDir
-- * Extensions
, extensionWord
, splitExtension
, splitExtensionBy
-- , addExtension
-- * Equality
-- , processParentRefs
, normalizeSeparators
-- , normalize -- separators and /./ components (split/combine)
, eqPathBytes
, EqCfg(..)
, eqCfg
, eqPathWith
, eqPath
-- , commonPrefix -- common prefix of two paths
-- , eqPrefix -- common prefix is equal to first path
-- , dropPrefix
-- * Utilities
, wordToChar
, charToWord
, unsafeIndexChar
-- * Internal
, unsafeSplitTopLevel
, unsafeSplitDrive
, unsafeSplitUNC
, splitCompact
, splitWithFilter
)
where
#include "assert.hs"
import Control.Monad (when)
import Control.Monad.Catch (MonadThrow(..))
import Control.Monad.IO.Class (MonadIO(..))
import Data.Char (chr, ord, isAlpha, toUpper)
import Data.Function ((&))
import Data.Functor.Identity (Identity(..))
import Data.Word (Word8, Word16)
import Foreign (castPtr)
import Foreign.C (CString, CSize(..))
import GHC.Base (unsafeChr, Addr#)
import GHC.Ptr (Ptr(..))
import Language.Haskell.TH (Q, Exp)
import Language.Haskell.TH.Quote (QuasiQuoter (..))
import Streamly.Internal.Data.Array (Array(..))
import Streamly.Internal.Data.MutArray (MutArray)
import Streamly.Internal.Data.MutByteArray (Unbox(..))
import Streamly.Internal.Data.Path (PathException(..))
import Streamly.Internal.Data.Stream (Stream)
import System.IO.Unsafe (unsafePerformIO)
import qualified Data.List as List
import qualified Streamly.Internal.Data.Array as Array
import qualified Streamly.Internal.Data.Fold as Fold
import qualified Streamly.Internal.Data.MutArray as MutArray
import qualified Streamly.Internal.Data.Stream as Stream
import qualified Streamly.Internal.Unicode.Stream as Unicode
{- $setup
>>> :m
>>> import Data.Functor.Identity (runIdentity)
>>> import System.IO.Unsafe (unsafePerformIO)
>>> import qualified Streamly.Data.Stream as Stream
>>> import qualified Streamly.Unicode.Stream as Unicode
>>> import qualified Streamly.Internal.Data.Array as Array
>>> import qualified Streamly.Internal.FileSystem.Path.Common as Common
>>> import qualified Streamly.Internal.Unicode.Stream as Unicode
>>> packPosix = unsafePerformIO . Stream.fold Array.create . Unicode.encodeUtf8' . Stream.fromList
>>> unpackPosix = runIdentity . Stream.toList . Unicode.decodeUtf8' . Array.read
>>> packWindows = unsafePerformIO . Stream.fold Array.create . Unicode.encodeUtf16le' . Stream.fromList
>>> unpackWindows = runIdentity . Stream.toList . Unicode.decodeUtf16le' . Array.read
-}
data OS = Windows | Posix deriving Eq
------------------------------------------------------------------------------
-- Parsing Operations
------------------------------------------------------------------------------
-- XXX We can use Enum type class to include the Char type as well so that the
-- functions can work on Array Word8/Word16/Char but that may be slow.
-- | Unsafe, may tructate to shorter word types, can only be used safely for
-- characters that fit in the given word size.
charToWord :: Integral a => Char -> a
charToWord c =
let n = ord c
in assert (n <= 255) (fromIntegral n)
-- | Unsafe, should be a valid character.
wordToChar :: Integral a => a -> Char
wordToChar = unsafeChr . fromIntegral
------------------------------------------------------------------------------
-- Array utils
------------------------------------------------------------------------------
-- | Index a word in an array and convert it to Char.
unsafeIndexChar :: (Unbox a, Integral a) => Int -> Array a -> Char
unsafeIndexChar i a = wordToChar (Array.unsafeGetIndex i a)
-- XXX put this in array module, we can have Array.fold and Array.foldM
foldArr :: Unbox a => Fold.Fold Identity a b -> Array a -> b
foldArr f arr = runIdentity $ Array.foldM f arr
{-# INLINE countLeadingBy #-}
countLeadingBy :: Unbox a => (a -> Bool) -> Array a -> Int
countLeadingBy p = foldArr (Fold.takeEndBy_ (not . p) Fold.length)
countTrailingBy :: Unbox a => (a -> Bool) -> Array a -> Int
countTrailingBy p = Array.foldRev (Fold.takeEndBy_ (not . p) Fold.length)
------------------------------------------------------------------------------
-- Separator parsing
------------------------------------------------------------------------------
extensionWord :: Integral a => a
extensionWord = charToWord '.'
posixSeparator :: Char
posixSeparator = '/'
windowsSeparator :: Char
windowsSeparator = '\\'
-- | Primary path separator character, @/@ on Posix and @\\@ on Windows.
-- Windows supports @/@ too as a separator. Please use 'isSeparator' for
-- testing if a char is a separator char.
{-# INLINE primarySeparator #-}
primarySeparator :: OS -> Char
primarySeparator Posix = posixSeparator
primarySeparator Windows = windowsSeparator
-- | On Posix only @/@ is a path separator but in windows it could be either
-- @/@ or @\\@.
{-# INLINE isSeparator #-}
isSeparator :: OS -> Char -> Bool
isSeparator Posix c = c == posixSeparator
isSeparator Windows c = (c == windowsSeparator) || (c == posixSeparator)
{-# INLINE isSeparatorWord #-}
isSeparatorWord :: Integral a => OS -> a -> Bool
isSeparatorWord os = isSeparator os . wordToChar
------------------------------------------------------------------------------
-- Separator normalization
------------------------------------------------------------------------------
-- | If the path is @//@ the result is @/@. If it is @a//@ then the result is
-- @a@. On Windows "c:" and "c:/" are different paths, therefore, we do not
-- drop the trailing separator from "c:/" or for that matter a separator
-- preceded by a ':'.
{-# INLINE dropTrailingBy #-}
dropTrailingBy :: (Unbox a, Integral a) =>
OS -> (a -> Bool) -> Array a -> Array a
dropTrailingBy os p arr =
let len = Array.length arr
n = countTrailingBy p arr
arr1 = fst $ Array.unsafeBreakAt (len - n) arr
in if n == 0
then arr
else if n == len -- "////"
then fst $ Array.unsafeBreakAt 1 arr
-- "c:////"
else if (os == Windows)
&& (Array.unsafeGetIndex (len - n - 1) arr == charToWord ':')
then fst $ Array.unsafeBreakAt (len - n + 1) arr
else arr1
{-# INLINE compactTrailingBy #-}
compactTrailingBy :: Unbox a => (a -> Bool) -> Array a -> Array a
compactTrailingBy p arr =
let len = Array.length arr
n = countTrailingBy p arr
in if n <= 1
then arr
else fst $ Array.unsafeBreakAt (len - n + 1) arr
{-# INLINE dropTrailingSeparators #-}
dropTrailingSeparators :: (Unbox a, Integral a) => OS -> Array a -> Array a
dropTrailingSeparators os =
dropTrailingBy os (isSeparator os . wordToChar)
-- | A path starting with a separator.
hasLeadingSeparator :: (Unbox a, Integral a) => OS -> Array a -> Bool
hasLeadingSeparator os a
| Array.null a = False -- empty path should not occur
| isSeparatorWord os (Array.unsafeGetIndex 0 a) = True
| otherwise = False
{-# INLINE hasTrailingSeparator #-}
hasTrailingSeparator :: (Integral a, Unbox a) => OS -> Array a -> Bool
hasTrailingSeparator os path =
let e = Array.getIndexRev 0 path
in case e of
Nothing -> False
Just x -> isSeparatorWord os x
{-# INLINE toDefaultSeparator #-}
toDefaultSeparator :: Integral a => a -> a
toDefaultSeparator x =
if isSeparatorWord Windows x
then charToWord (primarySeparator Windows)
else x
-- | Change all separators in the path to default separator on windows.
{-# INLINE normalizeSeparators #-}
normalizeSeparators :: (Integral a, Unbox a) => Array a -> Array a
normalizeSeparators a =
-- XXX We can check and return the original array if no change is needed.
Array.fromPureStreamN (Array.length a)
$ fmap toDefaultSeparator
$ Array.read a
------------------------------------------------------------------------------
-- Windows drive parsing
------------------------------------------------------------------------------
-- | @C:...@, does not check array length.
{-# INLINE unsafeHasDrive #-}
unsafeHasDrive :: (Unbox a, Integral a) => Array a -> Bool
unsafeHasDrive a
-- Check colon first for quicker return
| unsafeIndexChar 1 a /= ':' = False
-- XXX If we found a colon anyway this cannot be a valid path unless it has
-- a drive prefix. colon is not a valid path character.
-- XXX check isAlpha perf
| not (isAlpha (unsafeIndexChar 0 a)) = False
| otherwise = True
-- | A path that starts with a alphabet followed by a colon e.g. @C:...@.
hasDrive :: (Unbox a, Integral a) => Array a -> Bool
hasDrive a = Array.length a >= 2 && unsafeHasDrive a
-- | A path that contains only an alphabet followed by a colon e.g. @C:@.
isDrive :: (Unbox a, Integral a) => Array a -> Bool
isDrive a = Array.length a == 2 && unsafeHasDrive a
------------------------------------------------------------------------------
-- Relative or Absolute
------------------------------------------------------------------------------
-- | A path relative to cur dir it is either @.@ or starts with @./@.
isRelativeCurDir :: (Unbox a, Integral a) => OS -> Array a -> Bool
isRelativeCurDir os a
| len == 0 = False -- empty path should not occur
| wordToChar (Array.unsafeGetIndex 0 a) /= '.' = False
| len < 2 = True
| otherwise = isSeparatorWord os (Array.unsafeGetIndex 1 a)
where
len = Array.length a
-- | A non-UNC path starting with a separator.
-- Note that "\\/share/x" is treated as "C:/share/x".
isRelativeCurDriveRoot :: (Unbox a, Integral a) => Array a -> Bool
isRelativeCurDriveRoot a
| len == 0 = False -- empty path should not occur
| len == 1 && sep0 = True
| sep0 && c0 /= c1 = True -- "\\/share/x" is treated as "C:/share/x".
| otherwise = False
where
len = Array.length a
c0 = Array.unsafeGetIndex 0 a
c1 = Array.unsafeGetIndex 1 a
sep0 = isSeparatorWord Windows c0
-- | @C:@ or @C:a...@.
isRelativeWithDrive :: (Unbox a, Integral a) => Array a -> Bool
isRelativeWithDrive a =
hasDrive a
&& ( Array.length a < 3
|| not (isSeparator Windows (unsafeIndexChar 2 a))
)
isRootRelative :: (Unbox a, Integral a) => OS -> Array a -> Bool
isRootRelative Posix a = isRelativeCurDir Posix a
isRootRelative Windows a =
isRelativeCurDir Windows a
|| isRelativeCurDriveRoot a
|| isRelativeWithDrive a
-- | @C:\...@. Note that "C:" or "C:a" is not absolute.
isAbsoluteWithDrive :: (Unbox a, Integral a) => Array a -> Bool
isAbsoluteWithDrive a =
Array.length a >= 3
&& unsafeHasDrive a
&& isSeparator Windows (unsafeIndexChar 2 a)
-- | @\\\\...@ or @//...@
isAbsoluteUNC :: (Unbox a, Integral a) => Array a -> Bool
isAbsoluteUNC a
| Array.length a < 2 = False
| isSeparatorWord Windows c0 && c0 == c1 = True
| otherwise = False
where
c0 = Array.unsafeGetIndex 0 a
c1 = Array.unsafeGetIndex 1 a
-- XXX rename to isRootAbsolute
-- | Note that on Windows a path starting with a separator is relative to
-- current drive while on Posix this is absolute path as there is only one
-- drive.
isAbsolute :: (Unbox a, Integral a) => OS -> Array a -> Bool
isAbsolute Posix arr =
hasLeadingSeparator Posix arr
isAbsolute Windows arr =
isAbsoluteWithDrive arr || isAbsoluteUNC arr
------------------------------------------------------------------------------
-- Location or Segment
------------------------------------------------------------------------------
-- XXX API for static processing of .. (normalizeParentRefs)
--
-- Note: paths starting with . or .. are ambiguous and can be considered
-- segments or rooted. We consider a path starting with "." as rooted, when
-- someone uses "./x" they explicitly mean x in the current directory whereas
-- just "x" can be taken to mean a path segment without any specific root.
-- However, in typed paths the programmer can convey the meaning whether they
-- mean it as a segment or a rooted path. So even "./x" can potentially be used
-- as a segment which can just mean "x".
--
-- XXX For the untyped Path we can allow appending "./x" to other paths. We can
-- leave this to the programmer. In typed paths we can allow "./x" in segments.
-- XXX Empty path can be taken to mean "." except in case of UNC paths
isRooted :: (Unbox a, Integral a) => OS -> Array a -> Bool
isRooted Posix a =
hasLeadingSeparator Posix a
|| isRelativeCurDir Posix a
isRooted Windows a =
hasLeadingSeparator Windows a
|| isRelativeCurDir Windows a
|| hasDrive a -- curdir-in-drive relative, drive absolute
isBranch :: (Unbox a, Integral a) => OS -> Array a -> Bool
isBranch os = not . isRooted os
------------------------------------------------------------------------------
-- Split root
------------------------------------------------------------------------------
unsafeSplitPrefix :: (Unbox a, Integral a) =>
OS -> Int -> Array a -> (Array a, Array a)
unsafeSplitPrefix os prefixLen arr =
Array.unsafeBreakAt cnt arr
where
afterDrive = snd $ Array.unsafeBreakAt prefixLen arr
n = countLeadingBy (isSeparatorWord os) afterDrive
cnt = prefixLen + n
-- Note: We can have normalized splitting functions to normalize as we split
-- for efficiency. But then we will have to allocate new arrays instead of
-- slicing which can make it inefficient.
-- | Split a path prefixed with a separator into (drive, path) tuple.
--
-- >>> toListPosix (a,b) = (unpackPosix a, unpackPosix b)
-- >>> splitPosix = toListPosix . Common.unsafeSplitTopLevel Common.Posix . packPosix
--
-- >>> toListWin (a,b) = (unpackWindows a, unpackWindows b)
-- >>> splitWin = toListWin . Common.unsafeSplitTopLevel Common.Windows . packWindows
--
-- >>> splitPosix "/"
-- ("/","")
--
-- >>> splitPosix "//"
-- ("//","")
--
-- >>> splitPosix "/home"
-- ("/","home")
--
-- >>> splitPosix "/home/user"
-- ("/","home/user")
--
-- >>> splitWin "\\"
-- ("\\","")
--
-- >>> splitWin "\\home"
-- ("\\","home")
unsafeSplitTopLevel :: (Unbox a, Integral a) =>
OS -> Array a -> (Array a, Array a)
-- Note on Windows we should be here only when the path starts with exactly one
-- separator, otherwise it would be UNC path. But on posix multiple separators
-- are valid.
unsafeSplitTopLevel os = unsafeSplitPrefix os 1
-- In some cases there is no valid drive component e.g. "\\a\\b", though if we
-- consider relative roots then we could use "\\" as the root in this case. In
-- other cases there is no valid path component e.g. "C:" or "\\share\\" though
-- the latter is not a valid path and in the former case we can use "." as the
-- path component.
-- | Split a path prefixed with drive into (drive, path) tuple.
--
-- >>> toList (a,b) = (unpackPosix a, unpackPosix b)
-- >>> split = toList . Common.unsafeSplitDrive . packPosix
--
-- >>> split "C:"
-- ("C:","")
--
-- >>> split "C:a"
-- ("C:","a")
--
-- >>> split "C:\\"
-- ("C:\\","")
--
-- >>> split "C:\\\\" -- this is invalid path
-- ("C:\\\\","")
--
-- >>> split "C:\\\\a" -- this is invalid path
-- ("C:\\\\","a")
--
-- >>> split "C:\\/a/b" -- is this valid path?
-- ("C:\\/","a/b")
unsafeSplitDrive :: (Unbox a, Integral a) => Array a -> (Array a, Array a)
unsafeSplitDrive = unsafeSplitPrefix Windows 2
-- | Skip separators and then parse the next path segment.
-- Return (segment offset, segment length).
parseSegment :: (Unbox a, Integral a) => Array a -> Int -> (Int, Int)
parseSegment arr sepOff = (segOff, segCnt)
where
arr1 = snd $ Array.unsafeBreakAt sepOff arr
sepCnt = countLeadingBy (isSeparatorWord Windows) arr1
segOff = sepOff + sepCnt
arr2 = snd $ Array.unsafeBreakAt segOff arr
segCnt = countLeadingBy (not . isSeparatorWord Windows) arr2
-- XXX We can split a path as "root, . , rest" or "root, /, rest".
-- XXX We can remove the redundant path separator after the root. With that
-- joining root vs other paths will become similar. But there are some special
-- cases e.g. (1) "C:a" does not have a separator, can we make this "C:.\\a"?
-- (2) In case of "/home" we have "/" as root - while joining root and path we
-- should not add another separator between root and path - thus joining root
-- and path in this case is anyway special.
-- | Split a path prefixed with "\\" into (drive, path) tuple.
--
-- >>> toList (a,b) = (unpackPosix a, unpackPosix b)
-- >>> split = toList . Common.unsafeSplitUNC . packPosix
--
-- >> split ""
-- ("","")
--
-- >>> split "\\\\"
-- ("\\\\","")
--
-- >>> split "\\\\server"
-- ("\\\\server","")
--
-- >>> split "\\\\server\\"
-- ("\\\\server\\","")
--
-- >>> split "\\\\server\\home"
-- ("\\\\server\\","home")
--
-- >>> split "\\\\?\\c:"
-- ("\\\\?\\c:","")
--
-- >>> split "\\\\?\\c:/"
-- ("\\\\?\\c:/","")
--
-- >>> split "\\\\?\\c:\\home"
-- ("\\\\?\\c:\\","home")
--
-- >>> split "\\\\?\\UNC/"
-- ("\\\\?\\UNC/","")
--
-- >>> split "\\\\?\\UNC\\server"
-- ("\\\\?\\UNC\\server","")
--
-- >>> split "\\\\?\\UNC/server\\home"
-- ("\\\\?\\UNC/server\\","home")
--
unsafeSplitUNC :: (Unbox a, Integral a) => Array a -> (Array a, Array a)
unsafeSplitUNC arr =
if cnt1 == 1 && unsafeIndexChar 2 arr == '?'
then do
if uncLen == 3
&& unsafeIndexChar uncOff arr == 'U'
&& unsafeIndexChar (uncOff + 1) arr == 'N'
&& unsafeIndexChar (uncOff + 2) arr == 'C'
then unsafeSplitPrefix Windows (serverOff + serverLen) arr
else unsafeSplitPrefix Windows sepOff1 arr
else unsafeSplitPrefix Windows sepOff arr
where
arr1 = snd $ Array.unsafeBreakAt 2 arr
cnt1 = countLeadingBy (not . isSeparatorWord Windows) arr1
sepOff = 2 + cnt1
-- XXX there should be only one separator in a valid path?
-- XXX it should either be UNC or two letter drive in a valid path
(uncOff, uncLen) = parseSegment arr sepOff
sepOff1 = uncOff + uncLen
(serverOff, serverLen) = parseSegment arr sepOff1
-- XXX should we make the root Maybe? Both components will have to be Maybe to
-- avoid an empty path.
-- XXX Should we keep the trailing separator in the directory components?
{-# INLINE splitRoot #-}
splitRoot :: (Unbox a, Integral a) => OS -> Array a -> (Array a, Array a)
-- NOTE: validatePath depends on splitRoot splitting the path without removing
-- any redundant chars etc. It should just split and do nothing else.
-- XXX We can put an assert here "arrLen == rootLen + stemLen".
-- XXX assert (isValidPath path == isValidPath root)
--
-- NOTE: we cannot drop the trailing "/" on the root even if we want to -
-- because "c:/" will become "c:" and the two are not equivalent.
splitRoot Posix arr
| isRooted Posix arr
= unsafeSplitTopLevel Posix arr
| otherwise = (Array.empty, arr)
splitRoot Windows arr
| isRelativeCurDriveRoot arr || isRelativeCurDir Windows arr
= unsafeSplitTopLevel Windows arr
| hasDrive arr = unsafeSplitDrive arr
| isAbsoluteUNC arr = unsafeSplitUNC arr
| otherwise = (Array.empty, arr)
------------------------------------------------------------------------------
-- Split path
------------------------------------------------------------------------------
-- | Raw split an array on path separartor word using a filter to filter out
-- some splits.
{-# INLINE splitWithFilter #-}
splitWithFilter
:: (Unbox a, Integral a, Monad m)
=> ((Int, Int) -> Bool)
-> Bool
-> OS
-> Array a
-> Stream m (Array a)
splitWithFilter filt withSep os arr =
f (isSeparatorWord os) (Array.read arr)
& Stream.filter filt
& fmap (\(i, len) -> Array.unsafeSliceOffLen i len arr)
where
f = if withSep then Stream.indexEndBy else Stream.indexEndBy_
-- | Split a path on separator chars and compact contiguous separators and
-- remove /./ components. Note this does not treat the path root in a special
-- way.
{-# INLINE splitCompact #-}
splitCompact
:: (Unbox a, Integral a, Monad m)
=> Bool
-> OS
-> Array a
-> Stream m (Array a)
splitCompact withSep os arr =
splitWithFilter (not . shouldFilterOut) withSep os arr
where
sepFilter (off, len) =
( len == 1
&& isSeparator os (unsafeIndexChar off arr)
)
||
-- Note, last component may have len == 2 but second char may not
-- be slash, so we need to check for slash explicitly.
--
( len == 2
&& unsafeIndexChar off arr == '.'
&& isSeparator os (unsafeIndexChar (off + 1) arr)
)
{-# INLINE shouldFilterOut #-}
shouldFilterOut (off, len) =
len == 0
-- Note this is needed even when withSep is true - for the last
-- component case.
|| (len == 1 && unsafeIndexChar off arr == '.')
-- XXX Ensure that these are statically removed by GHC when withSep
-- is False.
|| (withSep && sepFilter (off, len))
{-# INLINE splitPathUsing #-}
splitPathUsing
:: (Unbox a, Integral a, Monad m)
=> Bool
-> OS
-> Array a
-> Stream m (Array a)
splitPathUsing withSep os arr =
let stream = splitCompact withSep os rest
in if Array.null root
then stream
else Stream.cons root1 stream
where
-- We should not filter out a leading '.' on Posix or Windows.
-- We should not filter out a '.' in the middle of a UNC root on windows.
-- Therefore, we split the root and treat it in a special way.
(root, rest) = splitRoot os arr
root1 =
if withSep
then compactTrailingBy (isSeparator os . wordToChar) root
else dropTrailingSeparators os root
{-# INLINE splitPath_ #-}
splitPath_
:: (Unbox a, Integral a, Monad m)
=> OS -> Array a -> Stream m (Array a)
splitPath_ = splitPathUsing False
{-# INLINE splitPath #-}
splitPath
:: (Unbox a, Integral a, Monad m)
=> OS -> Array a -> Stream m (Array a)
splitPath = splitPathUsing True
-- | Split the first non-empty path component.
--
-- /Unimplemented/
{-# INLINE splitHead #-}
splitHead :: -- (Unbox a, Integral a) =>
OS -> Array a -> (Array a, Maybe (Array a))
splitHead _os _arr = undefined
-- | Split the last non-empty path component.
--
-- /Unimplemented/
{-# INLINE splitTail #-}
splitTail :: -- (Unbox a, Integral a) =>
OS -> Array a -> (Maybe (Array a), Array a)
splitTail _os _arr = undefined
------------------------------------------------------------------------------
-- File or Dir
------------------------------------------------------------------------------
-- | Returns () if the path can be a valid file, otherwise throws an
-- exception.
validateFile :: (MonadThrow m, Unbox a, Integral a) => OS -> Array a -> m ()
validateFile os arr = do
s1 <-
Stream.toList
$ Stream.take 3
$ Stream.takeWhile (not . isSeparator os)
$ fmap wordToChar
$ Array.readRev arr
-- XXX On posix we just need to check last 3 bytes of the array
-- XXX Display the path in the exception messages.
case s1 of
[] -> throwM $ InvalidPath "A file name cannot have a trailing separator"
'.' : xs ->
case xs of
[] -> throwM $ InvalidPath "A file name cannot have a trailing \".\""
'.' : [] ->
throwM $ InvalidPath "A file name cannot have a trailing \"..\""
_ -> pure ()
_ -> pure ()
case os of
Windows ->
-- XXX We can exclude a UNC root as well but just the UNC root is
-- not even a valid path.
when (isDrive arr)
$ throwM $ InvalidPath "A drive root is not a valid file name"
Posix -> pure ()
{-# INLINE splitFile #-}
splitFile :: (Unbox a, Integral a) =>
OS -> Array a -> Maybe (Maybe (Array a), Array a)
splitFile os arr =
let p x =
if os == Windows
then x == charToWord ':' || isSeparatorWord os x
else isSeparatorWord os x
-- XXX Use Array.revBreakEndBy?
fileLen = runIdentity
$ Stream.fold (Fold.takeEndBy_ p Fold.length)
$ Array.readRev arr
arrLen = Array.length arr
baseLen = arrLen - fileLen
(base, file) = Array.unsafeBreakAt baseLen arr
fileFirst = Array.unsafeGetIndex 0 file
fileSecond = Array.unsafeGetIndex 1 file
in
if fileLen > 0
-- exclude the file == '.' case
&& not (fileLen == 1 && fileFirst == charToWord '.')
-- exclude the file == '..' case
&& not (fileLen == 2
&& fileFirst == charToWord '.'
&& fileSecond == charToWord '.')
then
if baseLen <= 0
then Just (Nothing, arr)
else Just (Just $ Array.unsafeSliceOffLen 0 baseLen base, file) -- "/"
else Nothing
-- | Split a multi-component path into (dir, last component). If the path has a
-- single component and it is a root then return (path, "") otherwise return
-- ("", path).
--
-- Split a single component into (dir, "") if it can be a dir i.e. it is either
-- a path root, "." or ".." or has a trailing separator.
--
-- The only difference between splitFile and splitDir:
--
-- >> splitFile "a/b/"
-- ("a/b/", "")
-- >> splitDir "a/b/"
-- ("a/", "b/")
--
-- This is equivalent to splitPath and keeping the last component but is usually
-- faster.
--
-- >>> toList (a,b) = (unpackPosix a, unpackPosix b)
-- >>> splitPosix = toList . Common.splitDir Common.Posix . packPosix
--
-- >> splitPosix "/"
-- ("/","")
--
-- >> splitPosix "."
-- (".","")
--
-- >> splitPosix "/."
-- ("/.","")
--
-- >> splitPosix "/x"
-- ("/","x")
--
-- >> splitPosix "/x/"
-- ("/","x/")
--
-- >> splitPosix "//"
-- ("//","")
--
-- >> splitPosix "./x"
-- ("./","x")
--
-- >> splitPosix "x"
-- ("","x")
--
-- >> splitPosix "x/"
-- ("x/","")
--
-- >> splitPosix "x/y"
-- ("x/","y")
--
-- >> splitPosix "x/y/"
-- ("x/","y/")
--
-- >> splitPosix "x/y//"
-- ("x/","y//")
--
-- >> splitPosix "x//y"
-- ("x//","y")
--
-- >> splitPosix "x/./y"
-- ("x/./","y")
--
-- /Unimplemented/
{-# INLINE splitDir #-}
splitDir :: -- (Unbox a, Integral a) =>
OS -> Array a -> (Array a, Array a)
splitDir _os _arr = undefined
------------------------------------------------------------------------------
-- Split extensions
------------------------------------------------------------------------------
-- | Like split extension but we can specify the extension char to be used.
{-# INLINE splitExtensionBy #-}
splitExtensionBy :: (Unbox a, Integral a) =>
a -> OS -> Array a -> Maybe (Array a, Array a)
splitExtensionBy c os arr =
let p x = x == c || isSeparatorWord os x
-- XXX Use Array.revBreakEndBy_
extLen = runIdentity
$ Stream.fold (Fold.takeEndBy p Fold.length)
$ Array.readRev arr
arrLen = Array.length arr
baseLen = arrLen - extLen
-- XXX We can use reverse split operation on the array
res@(base, ext) = Array.unsafeBreakAt baseLen arr
baseLast = Array.unsafeGetIndexRev 0 base
extFirst = Array.unsafeGetIndex 0 ext
in
-- For an extension to be present the path must be at least 3 chars.
-- non-empty base followed by extension char followed by non-empty
-- extension.
if arrLen > 2
-- If ext is empty, then there is no extension and we should not
-- strip an extension char if any at the end of base.
&& extLen > 1
&& extFirst == c
-- baseLast is always either base name char or '/' unless empty
-- if baseLen is 0 then we have not found an extension.
&& baseLen > 0
-- If baseLast is '/' then base name is empty which means it is a
-- dot file and there is no extension.
&& not (isSeparatorWord os baseLast)
-- On Windows if base is 'c:.' or a UNC path ending in '/c:.' then
-- it is a dot file, no extension.
&& not (os == Windows && baseLast == charToWord ':')
then Just res
else Nothing
{-# INLINE splitExtension #-}
splitExtension :: (Unbox a, Integral a) => OS -> Array a -> Maybe (Array a, Array a)
splitExtension = splitExtensionBy extensionWord
{-
-- Instead of this keep calling splitExtension until there is no more extension
-- returned.
{-# INLINE splitAllExtensionsBy #-}
splitAllExtensionsBy :: (Unbox a, Integral a) =>
Bool -> a -> OS -> Array a -> (Array a, Array a)
-- If the isFileName arg is true, it means that the path supplied does not have
-- any separator chars, so we can do it more efficiently.
splitAllExtensionsBy isFileName extChar os arr =
let file =
if isFileName
then arr
else snd $ splitFile os arr
fileLen = Array.length file
arrLen = Array.length arr
baseLen = foldArr (Fold.takeEndBy_ (== extChar) Fold.length) file
extLen = fileLen - baseLen
in
-- XXX unsafeBreakAt itself should use Array.empty in case of no split
if fileLen > 0 && extLen > 1 && extLen /= fileLen
then (Array.unsafeBreakAt (arrLen - extLen) arr)
else (arr, Array.empty)
-- |
--
-- TODO: This function needs to be consistent with splitExtension. It should
-- strip all valid extensions by that definition.
--
-- splitAllExtensions "x/y.tar.gz" gives ("x/y", ".tar.gz")
--
-- >>> toList (a,b) = (unpackPosix a, unpackPosix b)
-- >>> splitPosix = toList . Common.splitAllExtensions Common.Posix . packPosix
--
-- >>> toListWin (a,b) = (unpackWindows a, unpackWindows b)
-- >>> splitWin = toListWin . Common.splitAllExtensions Common.Windows . packWindows
--
-- >>> splitPosix "/"
-- ("/","")
--
-- >>> splitPosix "."
-- (".","")
--
-- >>> splitPosix "x"
-- ("x","")
--
-- >>> splitPosix "/x"
-- ("/x","")
--
-- >>> splitPosix "x/"
-- ("x/","")
--
-- >>> splitPosix "./x"
-- ("./x","")
--
-- >>> splitPosix "x/."
-- ("x/.","")
--
-- >>> splitPosix "x/y."
-- ("x/y.","")
--
-- >>> splitPosix "/x.y"
-- ("/x",".y")
--
-- >>> splitPosix "x/.y"
-- ("x/.y","")
--
-- >>> splitPosix ".x"
-- (".x","")
--
-- >>> splitPosix "x."
-- ("x.","")
--
-- >>> splitPosix ".x.y"
-- (".x",".y")
--
-- >>> splitPosix "x/y.z"
-- ("x/y",".z")
--
-- >>> splitPosix "x.y.z"
-- ("x",".y.z")
--
-- >>> splitPosix "x..y" -- ??
-- ("x.",".y")
--
-- >>> splitPosix ".."
-- ("..","")
--
-- >>> splitPosix "..."
-- ("...","")
--
-- >>> splitPosix "...x"