-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathPosixPath.hs
More file actions
1180 lines (1079 loc) · 33 KB
/
PosixPath.hs
File metadata and controls
1180 lines (1079 loc) · 33 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 TemplateHaskell #-}
-- Anything other than windows (Linux/macOS/FreeBSD) is Posix
#if defined(IS_WINDOWS)
#define OS_NAME Windows
#define OS_PATH WindowsPath
#define WORD_TYPE Word16
#define UNICODE_ENCODER encodeUtf16le'
#define UNICODE_DECODER decodeUtf16le'
#define UNICODE_DECODER_LAX decodeUtf16le
#define CODEC_NAME UTF-16LE
#define SEPARATORS @/, \\@
#else
#define OS_NAME Posix
#define OS_PATH PosixPath
#define WORD_TYPE Word8
#define UNICODE_ENCODER encodeUtf8'
#define UNICODE_DECODER decodeUtf8'
#define UNICODE_DECODER_LAX decodeUtf8
#define CODEC_NAME UTF-8
#define SEPARATORS @/@
#endif
-- |
-- Module : Streamly.Internal.FileSystem.OS_PATH
-- Copyright : (c) 2023 Composewell Technologies
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Portability : GHC
--
-- This module implements a OS_PATH type representing a file system path for
-- OS_NAME operating systems. The only assumption about the encoding of the
-- path is that it maps the characters SEPARATORS and @.@ to WORD_TYPE
-- representing their ASCII values. Operations are provided to encode and
-- decode using CODEC_NAME encoding.
--
-- This module has APIs that are equivalent to or can emulate all or most of
-- the filepath package APIs. It has some differences from the filepath
-- package:
--
-- * The default Path type it self affords considerable safety regarding the
-- distinction of rooted or non-rooted paths, it also allows distinguishing
-- directory and file paths.
-- * It is designed to provide flexible typing to provide compile time safety
-- for rooted/non-rooted paths and file/dir paths. The Path type is just part
-- of that typed path ecosystem. Though the default Path type itself should be
-- enough for most cases.
-- * It leverages the streamly array module for most of the heavy lifting,
-- it is a thin wrapper on top of that, improving maintainability as well as
-- providing better performance. We can have pinned and unpinned paths, also
-- provide lower level operations for certain cases to interact more
-- efficinetly with low level code.
module Streamly.Internal.FileSystem.OS_PATH
(
-- * Type
OS_PATH (..)
-- * Conversions
, IsPath (..)
, adapt
-- * Validation
, validatePath
, isValidPath
#ifdef IS_WINDOWS
, validatePath'
, isValidPath'
#endif
-- * Construction
, fromChunk
, unsafeFromChunk
, fromChars
, fromString
, rawFromString
, unsafeFromString
-- , fromCString#
-- , fromCWString#
, readRaw
-- * Statically Verified String Literals
-- | Quasiquoters.
, path
-- * Statically Verified Strings
-- | Template Haskell expression splices.
-- Note: We expose these even though we have quasiquoters as these TH
-- helpers are more powerful. They are useful if we are generating strings
-- statically using methods other than literals or if we are doing some
-- text processing on strings before using them.
, pathE
-- * Elimination
, toChunk
, toChars
, toChars_
, toString
#ifndef IS_WINDOWS
, asCString
#else
, asCWString
#endif
, toString_
, showRaw
-- -- * Separators
-- Do we need to export the separator char functions? They are not
-- essential if operations to split and combine paths are provided. If
-- someone wants to work on paths at low level then they know what they
-- are.
-- , isPrimarySeparator
-- , isSeparator
-- * Dir or non-dir paths
--
-- XXX These are unstable APIs. We may change them such that the trailing
-- separators are not removed or added if the path is a root/drive.
-- Therefore, the meaning of these would be just to change the directory
-- status of the path, if any, and nothing else. We may want to change the
-- names accordingly. Also see the Node module implementation for code
-- reuse.
, dropTrailingSeparators
, hasTrailingSeparator
, addTrailingSeparator
-- * Path Segment Types
, isRooted
, isBranch
-- * Joining
, addString
-- , concat
, unsafeExtend
#ifndef IS_WINDOWS
, extendByCString
, extendByCString'
#endif
, extend
, extendDir
, unsafeJoinPaths
-- * Splitting
-- | Note: you can use 'unsafeExtend' as a replacement for the joinDrive
-- function in the filepath package.
, splitRoot
, splitPath
, splitPath_
, splitFile
, splitFirst
, splitLast
, splitExtension
, dropExtension
, addExtension
-- * Equality
, eqPath
, EqCfg(..)
, eqCfg
, eqPathWith
, eqPathBytes
, normalize
)
where
import Control.Monad.Catch (MonadThrow(..))
import Data.Bifunctor (bimap)
import Data.Functor.Identity (Identity(..))
import Data.Maybe (fromJust)
#ifndef IS_WINDOWS
import Data.Word (Word8)
import Foreign.C (CString)
#else
import Data.Word (Word16)
import Foreign.C (CWString)
#endif
import Language.Haskell.TH.Syntax (lift)
import Streamly.Internal.Data.Array (Array(..))
import Streamly.Internal.Data.Stream (Stream)
import Streamly.Internal.FileSystem.Path.Common (mkQ, EqCfg(..), eqCfg)
import qualified Streamly.Internal.Data.Array as Array
import qualified Streamly.Internal.Data.Stream as Stream
import qualified Streamly.Internal.FileSystem.Path.Common as Common
import qualified Streamly.Internal.Unicode.Stream as Unicode
import Language.Haskell.TH
import Language.Haskell.TH.Quote
import Streamly.Internal.Data.Path
-- XXX docspec does not process CPP
{- $setup
>>> :m
>>> :set -XQuasiQuotes
>>> import Data.Maybe (fromJust, isNothing, isJust)
>>> import qualified Streamly.Data.Stream as Stream
For APIs that have not been released yet.
>>> import Streamly.Internal.FileSystem.PosixPath (PosixPath, path)
>>> import qualified Streamly.Internal.Data.Array as Array
>>> import qualified Streamly.Internal.FileSystem.PosixPath as Path
>>> import qualified Streamly.Unicode.Stream as Unicode
>>> import Data.Either (Either, isLeft)
>>> import Control.Exception (SomeException, evaluate, try)
>>> pack = fromJust . Path.fromString
>>> fails action = (try (evaluate action) :: IO (Either SomeException String)) >>= return . isLeft
-}
-- Path must not contain null char as system calls treat the path as a null
-- terminated C string. Also, they return null terminated strings as paths.
-- XXX Maintain the Array with null termination? To avoid copying the path for
-- null termination when passing to system calls. Path appends will have to
-- handle the null termination.
--
-- XXX On Windows several characters other than null are not allowed but we do
-- not validate that yet when parsing a path.
-- Path components may have limits.
-- Total path length may have a limit.
-- | A type representing file system paths on OS_NAME.
--
-- A OS_PATH is validated before construction unless unsafe constructors are
-- used to create it. For validations performed by the safe construction
-- methods see the 'fromChars' function.
--
-- Note that in some cases the file system may perform unicode normalization on
-- paths (e.g. Apple HFS), it may cause surprising results as the path used by
-- the user may not have the same bytes as later returned by the file system.
newtype OS_PATH = OS_PATH (Array WORD_TYPE)
-- XXX The Eq instance may be provided but it will require some sensible
-- defaults for comparison. For example, should we use case sensitive or
-- insensitive comparison? It depends on the underlying file system. For now
-- now we have eqPath operations for equality comparison.
instance IsPath OS_PATH OS_PATH where
unsafeFromPath = id
fromPath = pure
toPath = id
-- XXX Use rewrite rules to eliminate intermediate conversions for better
-- efficiency. If the argument path is already verfied for a property, we
-- should not verify it again e.g. if we adapt (Rooted path) as (Rooted (Dir
-- path)) then we should not verify it to be Rooted again.
-- XXX castPath?
-- | Convert a path type to another path type. This operation may fail with a
-- 'PathException' when converting a less restrictive path type to a more
-- restrictive one. This can be used to upgrade or downgrade type safety.
adapt :: (MonadThrow m, IsPath OS_PATH a, IsPath OS_PATH b) => a -> m b
adapt p = fromPath (toPath p :: OS_PATH)
------------------------------------------------------------------------------
-- Path parsing utilities
------------------------------------------------------------------------------
-- | Drop all trailing separators from a path. This can potentially convert an
-- implicit dir path to a non-dir.
--
-- Normally, if the path is @dir//@ then the result is @dir@; there are a few
-- special cases though:
--
-- * If the path is @\/\/@ then the result is @\/@.
-- * On Windows, if the path is "C:\/\/" then the result is "C:\/" because "C:"
-- has a different meaning.
--
-- >>> f a = Path.toString $ Path.dropTrailingSeparators (pack a)
-- >>> f "./"
-- "."
-- >>> f "//"
-- "/"
--
{-# INLINE dropTrailingSeparators #-}
dropTrailingSeparators :: OS_PATH -> OS_PATH
dropTrailingSeparators (OS_PATH arr) =
OS_PATH (Common.dropTrailingSeparators Common.OS_NAME arr)
-- | Returns True if the path has a trailing separator. This means the path is
-- implicitly a dir type path.
{-# INLINE hasTrailingSeparator #-}
hasTrailingSeparator :: OS_PATH -> Bool
hasTrailingSeparator (OS_PATH arr) =
Common.hasTrailingSeparator Common.OS_NAME arr
-- | Add a trailing path separator if it does not have one.
-- Note that this will make it an implicit dir type path.
--
-- Note that on Windows adding a separator to "C:" makes it "C:\\" which has a
-- different meaning.
--
{-# INLINE addTrailingSeparator #-}
addTrailingSeparator :: OS_PATH -> OS_PATH
addTrailingSeparator p = unsafeExtend p sep
where
sep = fromJust $ fromString [Common.primarySeparator Common.OS_NAME]
-- | Throws an exception if the path is not valid. See 'isValidPath' for the
-- list of validations.
validatePath :: MonadThrow m => Array WORD_TYPE -> m ()
validatePath = Common.validatePath Common.OS_NAME
#ifndef IS_WINDOWS
-- | Check if the filepath is valid i.e. does the operating system or the file
-- system allow such a path in listing or creating files?
--
-- >>> isValid = Path.isValidPath . Path.rawFromString
--
-- >>> isValid ""
-- False
-- >>> isValid "\0"
-- False
--
isValidPath :: Array WORD_TYPE -> Bool
isValidPath = Common.isValidPath Common.OS_NAME
#endif
-- Note: CPP gets confused by the prime suffix, so we have to put the CPP
-- macros on the next line to get it to work.
------------------------------------------------------------------------------
-- Construction
------------------------------------------------------------------------------
-- A chunk is essentially an untyped Array i.e. Array Word8. We can either use
-- the term ByteArray for that or just Chunk. The latter is shorter and we have
-- been using it consistently in streamly. We use "bytes" for a stream of
-- bytes.
-- | /Unsafe/: The user is responsible to make sure that the path is valid as
-- per 'isValidPath'.
--
{-# INLINE unsafeFromChunk #-}
unsafeFromChunk :: IsPath OS_PATH a => Array WORD_TYPE -> a
unsafeFromChunk =
#ifndef DEBUG
unsafeFromPath . OS_PATH . Common.unsafeFromChunk
#else
fromJust . fromChunk
#endif
-- XXX mkPath?
-- | Convert a byte array into a Path.
-- Throws 'InvalidPath' if 'isValidPath' fails on the path.
--
fromChunk :: (MonadThrow m, IsPath OS_PATH a) => Array WORD_TYPE -> m a
fromChunk arr = Common.fromChunk Common.OS_NAME arr >>= fromPath . OS_PATH
-- XXX Should be a Fold instead?
-- | Encode a Unicode character stream to OS_PATH using strict CODEC_NAME encoding.
--
-- * Throws 'InvalidPath' if 'isValidPath' fails on the path
-- * Fails if the stream contains invalid unicode characters
--
-- We do not sanitize the path i.e. we do not remove duplicate separators,
-- redundant @.@ segments, trailing separators etc because that would require
-- unnecessary checks and modifications to the path which may not be used ever
-- for any useful purpose, it is only needed for path equality and can be done
-- during the equality check.
--
-- On Windows it accepts a share root even if a path does not follow it.
--
-- Unicode normalization is not done. If normalization is needed the user can
-- normalize it and then use the 'fromChunk' API.
{-# INLINE fromChars #-}
fromChars :: (MonadThrow m, IsPath OS_PATH a) => Stream Identity Char -> m a
fromChars s =
Common.fromChars Common.OS_NAME Unicode.UNICODE_ENCODER s
>>= fromPath . OS_PATH
-- | Create a raw path i.e. an array representing the path. Note that the path
-- is not validated, therefore, it may not be valid according to 'isValidPath'.
rawFromString :: [Char] -> Array WORD_TYPE
rawFromString =
Common.unsafeFromChars Unicode.UNICODE_ENCODER
. Stream.fromList
-- | Like 'fromString' but does not perform any validations mentioned under
-- 'isValidPath'. Fails only if unicode encoding fails.
unsafeFromString :: IsPath OS_PATH a => [Char] -> a
unsafeFromString =
#ifndef DEBUG
unsafeFromPath
. OS_PATH
. rawFromString
#else
fromJust . fromString
#endif
-- | Convert a string to OS_PATH. See 'fromChars' for failure cases and
-- semantics.
--
-- >>> fromString = Path.fromChars . Stream.fromList
--
fromString :: (MonadThrow m, IsPath OS_PATH a) => [Char] -> m a
fromString = fromChars . Stream.fromList
-- | Concatenate a string to an existing path.
--
-- Throws an error if the resulting path is not a valid path as per
-- 'isValidPath'.
--
-- /Unimplemented/
addString :: OS_PATH -> [Char] -> OS_PATH
addString (OS_PATH _a) = undefined
------------------------------------------------------------------------------
-- Statically Verified Strings
------------------------------------------------------------------------------
-- XXX We can lift the array directly, ByteArray has a lift instance. Does that
-- work better?
--
-- XXX Make this polymorphic and reusable in other modules.
liftPath :: OS_PATH -> Q Exp
liftPath p =
[| unsafeFromString $(lift $ toString p) :: OS_PATH |]
-- | Generates a Haskell expression of type OS_PATH from a String. Equivalent
-- to using 'fromString' on the string passed.
--
pathE :: String -> Q Exp
pathE = either (error . show) liftPath . fromString
------------------------------------------------------------------------------
-- Statically Verified Literals
------------------------------------------------------------------------------
-- XXX Define folds or parsers to parse the paths.
-- XXX Build these on top of the str quasiquoter so that we get interpolation
-- for free. Interpolated vars if any have to be of appropriate type depending
-- on the context so that we can splice them safely.
-- | Generates a OS_PATH type from a quoted literal. Equivalent to using
-- 'fromString' on the static literal.
--
-- >>> Path.toString ([path|/usr/bin|] :: PosixPath)
-- "/usr/bin"
--
path :: QuasiQuoter
path = mkQ pathE
------------------------------------------------------------------------------
-- Eimination
------------------------------------------------------------------------------
-- XXX unPath?
-- | Convert the path to an array.
toChunk :: IsPath OS_PATH a => a -> Array WORD_TYPE
toChunk p = let OS_PATH arr = toPath p in arr
-- | Decode the path to a stream of Unicode chars using strict CODEC_NAME decoding.
{-# INLINE toChars #-}
toChars :: (Monad m, IsPath OS_PATH a) => a -> Stream m Char
toChars p =
let (OS_PATH arr) =
toPath p in Common.toChars Unicode.UNICODE_DECODER arr
-- | Decode the path to a stream of Unicode chars using lax CODEC_NAME decoding.
toChars_ :: (Monad m, IsPath OS_PATH a) => a -> Stream m Char
toChars_ p =
let (OS_PATH arr) =
toPath p in Common.toChars Unicode.UNICODE_DECODER_LAX arr
-- XXX When showing, append a "/" to dir types?
-- | Decode the path to a Unicode string using strict CODEC_NAME decoding.
toString :: IsPath OS_PATH a => a -> [Char]
toString = runIdentity . Stream.toList . toChars
-- | Decode the path to a Unicode string using lax CODEC_NAME decoding.
toString_ :: IsPath OS_PATH a => a -> [Char]
toString_ = runIdentity . Stream.toList . toChars_
-- | Show the path as raw characters without any specific decoding.
--
-- See also: 'readRaw'.
--
showRaw :: IsPath OS_PATH a => a -> [Char]
showRaw p =
let (OS_PATH arr) =
toPath p in show arr
#ifndef IS_WINDOWS
-- | Parse a raw array of bytes as a path type.
--
-- >>> readRaw = fromJust . Path.fromChunk . read
--
-- >>> arr = Path.rawFromString "hello"
-- >>> Path.showRaw $ (Path.readRaw $ show arr :: Path.PosixPath)
-- "fromList [104,101,108,108,111]"
--
-- See also: 'showRaw'.
readRaw :: IsPath OS_PATH a => [Char] -> a
readRaw = fromJust . fromChunk . read
#endif
-- We cannot show decoded path in the Show instance as it may not always
-- succeed and it depends on the encoding which we may not even know. The
-- encoding may depend on the OS and the file system. Also we need Show and
-- Read to be inverses. The best we can provide is to show the bytes as
-- Hex or decimal values.
{-
instance Show OS_PATH where
show (OS_PATH x) = show x
-}
#ifndef IS_WINDOWS
-- | Use the path as a pinned CString. Useful for using a PosixPath in
-- system calls on Posix.
{-# INLINE asCString #-}
asCString :: OS_PATH -> (CString -> IO a) -> IO a
asCString p = Array.asCStringUnsafe (toChunk p)
#else
-- | Use the path as a pinned CWString. Useful for using a WindowsPath in
-- system calls on Windows.
{-# INLINE asCWString #-}
asCWString :: OS_PATH -> (CWString -> IO a) -> IO a
asCWString p = Array.asCWString (toChunk p)
#endif
------------------------------------------------------------------------------
-- Operations on Path
------------------------------------------------------------------------------
#ifndef IS_WINDOWS
-- | A path that is attached to a root e.g. "\/x" or ".\/x" are rooted paths.
-- "\/" is considered an absolute root and "." as a dynamic root. ".." is not
-- considered a root, "..\/x" or "x\/y" are not rooted paths.
--
-- >>> isRooted = Path.isRooted . pack
--
-- >>> isRooted "/"
-- True
-- >>> isRooted "/x"
-- True
-- >>> isRooted "."
-- True
-- >>> isRooted "./x"
-- True
--
isRooted :: OS_PATH -> Bool
isRooted (OS_PATH arr) = Common.isRooted Common.OS_NAME arr
#endif
-- | A path that is not attached to a root e.g. @a\/b\/c@ or @..\/b\/c@.
--
-- >>> isBranch = not . Path.isRooted
--
-- >>> isBranch = Path.isBranch . pack
--
-- >>> isBranch "x"
-- True
-- >>> isBranch "x/y"
-- True
-- >>> isBranch ".."
-- True
-- >>> isBranch "../x"
-- True
--
isBranch :: OS_PATH -> Bool
isBranch = not . isRooted
#ifndef IS_WINDOWS
-- | Like 'extend' but does not check if the second path is rooted.
--
-- >>> f a b = Path.toString $ Path.unsafeExtend (pack a) (pack b)
--
-- >>> f "x" "y"
-- "x/y"
-- >>> f "x/" "y"
-- "x/y"
-- >>> f "x" "/y"
-- "x/y"
-- >>> f "x/" "/y"
-- "x/y"
--
{-# INLINE unsafeExtend #-}
unsafeExtend :: OS_PATH -> OS_PATH -> OS_PATH
unsafeExtend (OS_PATH a) (OS_PATH b) =
OS_PATH
$ Common.unsafeAppend
Common.OS_NAME (Common.toString Unicode.UNICODE_DECODER) a b
-- | Extend an OS_PATH by appending another one to it. Fails if the second path
-- refers to a rooted path. If you want to avoid runtime failure use the
-- typesafe Streamly.FileSystem.OS_PATH.Seg module. Use 'unsafeExtend' to avoid
-- failure if you know it is ok to append the path.
--
-- >>> f a b = Path.toString $ Path.extend a b
--
-- >>> f [path|/usr|] [path|bin|]
-- "/usr/bin"
-- >>> f [path|/usr/|] [path|bin|]
-- "/usr/bin"
-- >>> fails (f [path|/usr|] [path|/bin|])
-- True
--
extend :: OS_PATH -> OS_PATH -> OS_PATH
extend (OS_PATH a) (OS_PATH b) =
OS_PATH
$ Common.append
Common.OS_NAME (Common.toString Unicode.UNICODE_DECODER) a b
-- | A stricter version of 'extend' which requires the first path to be a
-- directory like path i.e. with a trailing separator.
--
-- >>> f a b = Path.toString $ Path.extendDir a b
--
-- >>> fails $ f [path|/usr|] [path|bin|]
-- True
--
extendDir ::
OS_PATH -> OS_PATH -> OS_PATH
extendDir
(OS_PATH a) (OS_PATH b) =
OS_PATH
$ Common.append'
Common.OS_NAME (Common.toString Unicode.UNICODE_DECODER) a b
#endif
-- XXX This can be pure, like append.
-- XXX add appendCWString for Windows?
#ifndef IS_WINDOWS
-- | Append a separator and a CString to the Array. This is like 'unsafeExtend'
-- but always inserts a separator between the two paths even if the first path
-- has a trailing separator or second path has a leading separator.
--
extendByCString :: OS_PATH -> CString -> IO OS_PATH
extendByCString (OS_PATH a) str =
fmap OS_PATH
$ Common.appendCString
Common.OS_NAME a str
-- | Like 'appendCString' but creates a pinned path.
--
extendByCString' ::
OS_PATH -> CString -> IO OS_PATH
extendByCString'
(OS_PATH a) str =
fmap OS_PATH
$ Common.appendCString'
Common.OS_NAME a str
#endif
-- See unsafeJoinPaths in the Common path module, we need to avoid MonadIo from
-- that to implement this.
-- | Join paths by path separator. Does not check if the paths being appended
-- are rooted or branches. Note that splitting and joining may not give exactly
-- the original path but an equivalent path.
--
-- /Unimplemented/
unsafeJoinPaths :: [OS_PATH] -> OS_PATH
unsafeJoinPaths = undefined
------------------------------------------------------------------------------
-- Splitting path
------------------------------------------------------------------------------
#ifndef IS_WINDOWS
-- | If a path is rooted then separate the root and the remaining path,
-- otherwise return 'Nothing'. If the path is rooted then the non-root
-- part is guaranteed to NOT start with a separator.
--
-- Some filepath package equivalent idioms:
--
-- >>> splitDrive = Path.splitRoot
-- >>> joinDrive = Path.unsafeExtend
-- >>> takeDrive = fmap fst . Path.splitRoot
-- >>> dropDrive x = Path.splitRoot x >>= snd
-- >>> hasDrive = isJust . Path.splitRoot
-- >>> isDrive = isNothing . dropDrive
--
-- >>> toList (a,b) = (Path.toString a, fmap Path.toString b)
-- >>> split = fmap toList . Path.splitRoot . pack
--
-- >>> split "/"
-- Just ("/",Nothing)
--
-- >>> split "."
-- Just (".",Nothing)
--
-- >>> split "./"
-- Just ("./",Nothing)
--
-- >>> split "/home"
-- Just ("/",Just "home")
--
-- >>> split "//"
-- Just ("//",Nothing)
--
-- >>> split "./home"
-- Just ("./",Just "home")
--
-- >>> split "home"
-- Nothing
--
splitRoot :: OS_PATH -> Maybe (OS_PATH, Maybe OS_PATH)
splitRoot (OS_PATH x) =
let (a,b) = Common.splitRoot Common.OS_NAME x
in if Array.null a
then Nothing
else if Array.null b
then Just (OS_PATH a, Nothing)
else Just (OS_PATH a, Just (OS_PATH b))
-- | Split the path components keeping separators between path components
-- attached to the dir part. Redundant separators are removed, only the first
-- one is kept. Separators are not added either e.g. "." and ".." may not have
-- trailing separators if the original path does not.
--
-- >>> split = Stream.toList . fmap Path.toString . Path.splitPath . pack
--
-- >>> split "."
-- ["."]
--
-- >>> split "././"
-- ["./"]
--
-- >>> split "./a/b/."
-- ["./","a/","b/"]
--
-- >>> split ".."
-- [".."]
--
-- >>> split "../"
-- ["../"]
--
-- >>> split "a/.."
-- ["a/",".."]
--
-- >>> split "/"
-- ["/"]
--
-- >>> split "//"
-- ["/"]
--
-- >>> split "/x"
-- ["/","x"]
--
-- >>> split "/./x/"
-- ["/","x/"]
--
-- >>> split "/x/./y"
-- ["/","x/","y"]
--
-- >>> split "/x/../y"
-- ["/","x/","../","y"]
--
-- >>> split "/x///y"
-- ["/","x/","y"]
--
-- >>> split "/x/\\y"
-- ["/","x/","\\y"]
--
{-# INLINE splitPath #-}
splitPath :: Monad m => OS_PATH -> Stream m OS_PATH
splitPath (OS_PATH a) = fmap OS_PATH $ Common.splitPath Common.OS_NAME a
-- | Split a path into components separated by the path separator. "."
-- components in the path are ignored except when in the leading position.
-- Trailing separators in non-root components are dropped.
--
-- >>> split = Stream.toList . fmap Path.toString . Path.splitPath_ . pack
--
-- >>> split "."
-- ["."]
--
-- >>> split "././"
-- ["."]
--
-- >>> split ".//"
-- ["."]
--
-- >>> split "//"
-- ["/"]
--
-- >>> split "//x/y/"
-- ["/","x","y"]
--
-- >>> split "./a"
-- [".","a"]
--
-- >>> split "a/."
-- ["a"]
--
-- >>> split "/"
-- ["/"]
--
-- >>> split "/x"
-- ["/","x"]
--
-- >>> split "/./x/"
-- ["/","x"]
--
-- >>> split "/x/./y"
-- ["/","x","y"]
--
-- >>> split "/x/../y"
-- ["/","x","..","y"]
--
-- >>> split "/x///y"
-- ["/","x","y"]
--
-- >>> split "/x/\\y"
-- ["/","x","\\y"]
--
{-# INLINE splitPath_ #-}
splitPath_ :: Monad m => OS_PATH -> Stream m OS_PATH
splitPath_ (OS_PATH a) = fmap OS_PATH $ Common.splitPath_ Common.OS_NAME a
#endif
-- | If the path does not look like a directory then return @Just (Maybe dir,
-- file)@ otherwise return 'Nothing'. The path is not a directory if:
--
-- * the path does not end with a separator
-- * the path does not end with a . or .. component
--
-- Splits a single component path into @Just (Nothing, path)@ if it does not
-- look like a dir.
--
-- Some filepath package equivalent idioms:
--
-- >>> takeFileName = fmap snd . Path.splitFile
-- >>> takeBaseName = fmap Path.dropExtension . takeFileName
-- >>> dropFileName x = Path.splitFile x >>= fst
-- >>> takeDirectory x = Path.splitFile x >>= fst
-- >>> replaceFileName p x = fmap (flip Path.extend x) (takeDirectory p)
-- >>> replaceDirectory p x = fmap (flip Path.extend x) (takeFileName p)
--
-- >>> toList (a,b) = (fmap Path.toString a, Path.toString b)
-- >>> split = fmap toList . Path.splitFile . pack
--
-- >>> split "/"
-- Nothing
--
-- >>> split "."
-- Nothing
--
-- >>> split "/."
-- Nothing
--
-- >>> split ".."
-- Nothing
--
-- >>> split "//"
-- Nothing
--
-- >>> split "/home"
-- Just (Just "/","home")
--
-- >>> split "./home"
-- Just (Just "./","home")
--
-- >>> split "home"
-- Just (Nothing,"home")
--
-- >>> split "x/"
-- Nothing
--
-- >>> split "x/y"
-- Just (Just "x/","y")
--
-- >>> split "x//y"
-- Just (Just "x//","y")
--
-- >>> split "x/./y"
-- Just (Just "x/./","y")
splitFile :: OS_PATH -> Maybe (Maybe OS_PATH, OS_PATH)
splitFile (OS_PATH a) =
fmap (bimap (fmap OS_PATH) OS_PATH) $ Common.splitFile Common.OS_NAME a
-- | Split the path into the first component and rest of the path. Treats the
-- entire root or share name, if present, as the first component.
--
-- /Unimplemented/
splitFirst :: OS_PATH -> (OS_PATH, Maybe OS_PATH)
splitFirst (OS_PATH a) =
bimap OS_PATH (fmap OS_PATH) $ Common.splitHead Common.OS_NAME a
-- | Split the path into the last component and rest of the path. Treats the
-- entire root or share name, if present, as the first component.
--
-- >>> basename = snd . Path.splitLast -- Posix basename
-- >>> dirname = fst . Path.splitLast -- Posix dirname
--
-- /Unimplemented/
splitLast :: OS_PATH -> (Maybe OS_PATH, OS_PATH)
splitLast (OS_PATH a) =
bimap (fmap OS_PATH) OS_PATH $ Common.splitTail Common.OS_NAME a
#ifndef IS_WINDOWS
-- Note: In the cases of "x.y." and "x.y.." we return no extension rather
-- than ".y." or ".y.." as extensions. That is they considered to have no
-- extension.
-- | Returns @Just(filename, extension)@ if an extension is present otherwise
-- returns 'Nothing'.
--
-- A file name is considered to have an extension if the file name can be
-- split into a non-empty filename followed by the extension separator "."
-- followed by a non-empty extension with at least one character in addition to
-- the extension separator.
-- The shortest suffix obtained by this rule, starting with the
-- extension separator, is returned as the extension and the remaining prefix
-- part as the filename.
--
-- A directory name does not have an extension.
--
-- Other extension related operations can be implemented using this API:
--
-- >>> takeExtension = fmap snd . Path.splitExtension
-- >>> hasExtension = isJust . Path.splitExtension
--
-- If you want a @splitExtensions@, you can use splitExtension until the
-- extension returned is Nothing. @dropExtensions@, @isExtensionOf@ can be
-- implemented similarly.
--
-- >>> toList (a,b) = (Path.toString a, Path.toString b)
-- >>> split = fmap toList . Path.splitExtension . pack
--
-- >>> split "/"
-- Nothing
--
-- >>> split "."
-- Nothing
--
-- >>> split ".."
-- Nothing
--
-- >>> split "x"
-- Nothing
--
-- >>> split "/x"
-- Nothing
--
-- >>> split "x/"
-- Nothing
--
-- >>> split "./x"
-- Nothing
--
-- >>> split "x/."
-- Nothing
--
-- >>> split "x/y."
-- Nothing
--
-- >>> split "/x.y"
-- Just ("/x",".y")
--
-- >>> split "/x.y."
-- Nothing
--
-- >>> split "/x.y.."
-- Nothing
--
-- >>> split "x/.y"
-- Nothing
--
-- >>> split ".x"
-- Nothing
--
-- >>> split "x."
-- Nothing
--
-- >>> split ".x.y"
-- Just (".x",".y")
--
-- >>> split "x/y.z"
-- Just ("x/y",".z")
--
-- >>> split "x.y.z"
-- Just ("x.y",".z")
--
-- >>> split "x..y"
-- Just ("x.",".y")
--
-- >>> split "..."
-- Nothing
--
-- >>> split "..x"
-- Just (".",".x")
--