-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathPosixPath.hs
More file actions
1615 lines (1492 loc) · 45.4 KB
/
PosixPath.hs
File metadata and controls
1615 lines (1492 loc) · 45.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 CPP #-}
{-# LANGUAGE TemplateHaskell #-}
#if defined(IS_PORTABLE)
#define OS_PATH_TYPE Path
#define OS_WORD_TYPE OsWord
#define OS_CSTRING_TYPE OsCString
#define AS_OS_CSTRING asOsCString
#elif defined(IS_WINDOWS)
#define OS_PATH_TYPE WindowsPath
#define OS_WORD_TYPE Word16
#define OS_CSTRING_TYPE CWString
#define AS_OS_CSTRING asCWString
#else
#define OS_PATH_TYPE PosixPath
#define OS_WORD_TYPE Word8
#define OS_CSTRING_TYPE CString
#define AS_OS_CSTRING asCString
#endif
-- Anything other than windows (Linux/macOS/FreeBSD) is Posix
#if defined(IS_WINDOWS)
#define OS_NAME Windows
#define OS_PATH WindowsPath
#define OS_WORD Word16
#define OS_CSTRING CWString
#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 OS_WORD Word8
#define OS_CSTRING CString
#define UNICODE_ENCODER encodeUtf8'
#define UNICODE_DECODER decodeUtf8'
#define UNICODE_DECODER_LAX decodeUtf8
#define CODEC_NAME UTF-8
#define SEPARATORS @/@
#endif
-- XXX Do not start a module haddock comment here as this file gets included in
-- Path.hs and then we have duplicate module level comment in that file,
-- generating a haddock warning.
-- Module : Streamly.Internal.FileSystem.OS_PATH_TYPE
-- Copyright : (c) 2023 Composewell Technologies
-- License : BSD3
-- Maintainer : streamly@composewell.com
-- Portability : GHC
--
-- This module implements a OS_PATH_TYPE 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 OS_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:
--
-- 1. Empty paths are not allowed. Paths are validated before construction.
-- 2. The default Path type itself affords considerable safety regarding the
-- distinction of rooted or non-rooted paths, it also allows distinguishing
-- directory and file paths.
-- 3. 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.
-- 4. 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
(
-- * Setup
-- | To execute the code examples provided in this module in ghci, please
-- run the following commands first.
--
-- $setup
-- * Type
#if defined(IS_PORTABLE)
OS_WORD_TYPE
, OS_CSTRING_TYPE
, OS_PATH_TYPE
#else
OS_PATH_TYPE (..)
#endif
-- * Conversions
, IsPath (..)
, adapt
-- * Conversion to OsWord
, charToWord
, wordToChar
-- * Validation
, validatePath
, isValidPath
#ifdef IS_WINDOWS
, validatePath'
, isValidPath'
#endif
-- * Construction
, fromArray
, unsafeFromArray
, fromChars
, fromString
, fromString_
, encodeString
, unsafeFromString
-- , fromCString#
-- , fromCWString#
, readArray
-- * 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
, toArray
, toChars
, toChars_
, toString
, AS_OS_CSTRING
, toString_
, showArray
-- * 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. We should export the OsWord based operations to work with arrays.
, separator
, isSeparator
, extSeparator
-- * Dir or non-dir paths
-- You do not need these, instead use eqPath with ignoreTrailingSeparators.
, dropTrailingSeparators
, hasTrailingSeparator
, addTrailingSeparator
-- * Path Segment Types
, isRooted
, isUnrooted
-- * Joining
, joinStr
-- , concat
, unsafeJoin
#ifndef IS_WINDOWS
, joinCStr
, joinCStr'
#endif
, join
, joinDir
, unsafeJoinPaths
-- * Splitting
-- | Note: you can use 'unsafeJoin' as a replacement for the joinDrive
-- function in the filepath package.
, splitRoot
, splitPath
, splitPath_
, splitFile
, splitFirst
, splitLast
-- ** Extension
, splitExtension
, dropExtension
, addExtension
, replaceExtension
-- ** Path View
, takeFileName
, takeDirectory
-- , takeDirectory_ -- drops the trailing /
, takeExtension
, takeFileBase
-- * Equality
, EqCfg
, ignoreTrailingSeparators
, ignoreCase
, allowRelativeEquality
, eqPath
, eqPathBytes
, normalize
)
where
import Control.Exception (throw)
import Control.Monad.Catch (MonadThrow(..))
import Data.Bifunctor (bimap)
import Data.Functor.Identity (Identity(..))
import Data.Maybe (fromJust, isJust)
#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(..))
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
#if defined(IS_PORTABLE)
import Streamly.Internal.FileSystem.OS_PATH (OS_PATH(..))
#endif
-- NOTES about C preprocessor use.
--
-- docspec comment lines cannot use CPP macros, docspec does not expand them
-- before running tests.
--
-- We cannot use a CPP conditional inside haddock comments because the
-- conditional line replaced by a blank line by CPP and this breaks the haddock
-- comment. Therefore if the comment is slightly different on a different
-- platform we duplicate the entire comment inside a conditional.
#ifdef IS_PORTABLE
#include "DocTestFileSystemPath.hs"
#elif defined(IS_WINDOWS)
#include "DocTestFileSystemWindowsPath.hs"
#else
#include "DocTestFileSystemPosixPath.hs"
#endif
#if defined(IS_PORTABLE)
type OS_PATH_TYPE = OS_PATH
type OS_WORD_TYPE = OS_WORD
type OS_CSTRING_TYPE = OS_CSTRING
#else
-- | A type representing file system paths on OS_NAME.
--
-- A OS_PATH_TYPE 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 OS_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
#endif
-- 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_TYPE a, IsPath OS_PATH_TYPE b) => a -> m b
adapt p = fromPath (toPath p :: OS_PATH_TYPE)
------------------------------------------------------------------------------
-- Char to word
------------------------------------------------------------------------------
-- | Unsafe, truncates the Char to Word8 on Posix and Word16 on Windows.
charToWord :: Char -> OS_WORD_TYPE
charToWord = Common.charToWord
-- | Unsafe, should be a valid character.
wordToChar :: OS_WORD_TYPE -> Char
wordToChar = Common.wordToChar
------------------------------------------------------------------------------
-- Separators
------------------------------------------------------------------------------
-- | The primary path separator word: @/@ on POSIX and @\\@ on Windows.
-- Windows also supports @/@ as a valid separator. Use 'isSeparator' to check
-- for any valid path separator.
{-# INLINE separator #-}
separator :: OS_WORD_TYPE
separator = charToWord $ Common.primarySeparator Common.OS_NAME
-- | On POSIX, only @/@ is a path separator, whereas on Windows both @/@ and
-- @\\@ are valid separators.
{-# INLINE isSeparator #-}
isSeparator :: OS_WORD_TYPE -> Bool
isSeparator = Common.isSeparatorWord Common.OS_NAME
-- | File extension separator word.
{-# INLINE extSeparator #-}
extSeparator :: OS_WORD_TYPE
extSeparator = Common.extensionWord
------------------------------------------------------------------------------
-- Path parsing utilities
------------------------------------------------------------------------------
-- XXX We can have prime suffixed versions where it drops or adds separator
-- unconditionally. Alternatively, we can convert the path to array and use
-- array operations instead.
-- | Remove all trailing path separators from the given 'Path'.
--
-- Instead of this operation you may want to use 'eqPath' with
-- 'ignoreTrailingSeparators' option.
--
-- This operation is careful not to alter the semantic meaning of the path.
-- For example, on Windows:
--
-- * Dropping the separator from "C:/" would change the meaning of the path
-- from referring to the root of the C: drive to the current directory on C:.
-- * If a path ends with a separator immediately after a colon (e.g., "C:/"),
-- the separator will not be removed.
--
-- If the input path is invalid, the behavior is not fully guaranteed:
--
-- * The separator may still be dropped.
-- * In some cases, dropping the separator may make an invalid path valid
-- (e.g., "C:\\\\" or "C:\\/").
--
-- This operation may convert a path that implicitly refers to a directory
-- into one that does not.
--
-- Typically, if the path is @dir//@, the result is @dir@. Special cases include:
--
-- * On POSIX: dropping from @"//"@ yields @"/"@.
-- * On Windows: dropping from @"C://"@ results in @"C:/"@.
--
-- Examples:
--
-- >>> f = Path.toString . Path.dropTrailingSeparators . Path.fromString_
-- >>> f "./"
-- "."
--
-- >> f "//" -- On POSIX
-- "/"
--
{-# INLINE dropTrailingSeparators #-}
dropTrailingSeparators :: OS_PATH_TYPE -> OS_PATH_TYPE
dropTrailingSeparators (OS_PATH arr) =
OS_PATH (Common.dropTrailingSeparators Common.OS_NAME arr)
-- On windows a share name can also be reported to have a trailing separator,
-- but that is not a valid Path.
-- | Returns 'True' if the path ends with a trailing separator.
--
-- This typically indicates that the path is a directory, though this is not
-- guaranteed in all cases.
--
-- Example:
--
-- >>> Path.hasTrailingSeparator (Path.fromString_ "foo/")
-- True
--
-- >>> Path.hasTrailingSeparator (Path.fromString_ "foo")
-- False
{-# INLINE hasTrailingSeparator #-}
hasTrailingSeparator :: OS_PATH_TYPE -> Bool
hasTrailingSeparator (OS_PATH arr) =
Common.hasTrailingSeparator Common.OS_NAME arr
-- | Add a trailing path separator to a path if it doesn't already have one.
--
-- Instead of this operation you may want to use 'eqPath' with
-- 'ignoreTrailingSeparators' option.
--
-- This function avoids modifying the path if doing so would change its meaning
-- or make it invalid. For example, on Windows:
--
-- * Adding a separator to "C:" would change it from referring to the current
-- directory on the C: drive to the root directory.
-- * Adding a separator to "\\" could turn it into a UNC share path, which may
-- not be intended.
-- * If the path ends with a colon (e.g., "C:"), a separator is not added.
--
-- This operation typically makes the path behave like an implicit directory path.
{-# INLINE addTrailingSeparator #-}
addTrailingSeparator :: OS_PATH_TYPE -> OS_PATH_TYPE
addTrailingSeparator p@(OS_PATH _arr) =
#ifdef IS_WINDOWS
if Array.unsafeGetIndexRev 0 _arr == Common.charToWord ':'
then p
else unsafeJoin p sep
#else
unsafeJoin p sep
#endif
where
sep = fromJust $ fromString [Common.primarySeparator Common.OS_NAME]
-- 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.
#ifndef IS_WINDOWS
-- | Checks whether the filepath is valid; i.e., whether the operating system
-- permits such a path for listing or creating files. These validations are
-- operating system specific and file system independent. Throws an exception
-- with a detailed explanation if the path is invalid.
--
-- >>> isValid = isJust . Path.validatePath . Path.encodeString
--
-- Validations:
--
-- >>> isValid ""
-- False
-- >>> isValid "\0"
-- False
--
-- Other than these there may be maximum path component length and maximum path
-- length restrictions enforced by the OS as well as the filesystem which we do
-- not validate.
--
#else
-- | Checks whether the filepath is valid; i.e., whether the operating system
-- permits such a path for listing or creating files. These validations are
-- operating system specific and file system independent. Throws an exception
-- with a detailed explanation if the path is invalid.
--
-- >>> isValid = isJust . Path.validatePath . Path.encodeString
--
-- General validations:
--
-- >>> isValid ""
-- False
-- >>> isValid "\0"
-- False
--
-- Windows invalid characters:
--
-- >>> isValid "c::"
-- False
-- >>> isValid "c:\\x:y"
-- False
-- >>> isValid "x*"
-- False
-- >>> isValid "x\ty" -- control characters
-- False
--
-- Windows invalid path components:
--
-- >>> isValid "pRn.txt"
-- False
-- >>> isValid " pRn .txt"
-- False
-- >>> isValid "c:\\x\\pRn"
-- False
-- >>> isValid "c:\\x\\pRn.txt"
-- False
-- >>> isValid "c:\\pRn\\x"
-- False
-- >>> isValid "c:\\ pRn \\x"
-- False
-- >>> isValid "pRn.x.txt"
-- False
--
-- Windows drive root validations:
--
-- >>> isValid "c:"
-- True
-- >>> isValid "c:a\\b"
-- True
-- >>> isValid "c:\\"
-- True
-- >>> isValid "c:\\\\"
-- False
-- >>> isValid "c:\\/"
-- False
-- >>> isValid "c:\\\\x"
-- False
-- >>> isValid "c:\\/x"
-- False
--
-- Mixing path separators:
-- >>> isValid "/x\\y"
-- True
-- >>> isValid "\\/" -- ?
-- True
-- >>> isValid "/\\" -- ?
-- True
-- >>> isValid "\\/x/y" -- ?
-- True
-- >>> isValid "/x/\\y" -- ?
-- True
-- >>> isValid "/x\\/y" -- ?
-- True
--
-- Windows share path validations:
--
-- >>> isValid "\\"
-- True
-- >>> isValid "\\\\"
-- False
-- >>> isValid "\\\\\\"
-- False
-- >>> isValid "\\\\x"
-- False
-- >>> isValid "\\\\x\\"
-- True
-- >>> isValid "\\\\x\\y"
-- True
-- >>> isValid "//x/y"
-- True
-- >>> isValid "\\\\prn\\y"
-- False
-- >>> isValid "\\\\x\\\\"
-- False
-- >>> isValid "\\\\x\\\\x"
-- False
-- >>> isValid "\\\\\\x"
-- False
--
-- Windows short UNC path validations:
--
-- >>> isValid "\\\\?\\c:"
-- False
-- >>> isValid "\\\\?\\c:\\"
-- True
-- >>> isValid "\\\\?\\c:x"
-- False
-- >>> isValid "\\\\?\\c:\\\\" -- XXX validate this
-- False
-- >>> isValid "\\\\?\\c:\\x"
-- True
-- >>> isValid "\\\\?\\c:\\\\\\"
-- False
-- >>> isValid "\\\\?\\c:\\\\x"
-- False
--
-- Windows long UNC path validations:
--
-- >>> isValid "\\\\?\\UnC\\x" -- UnC treated as share name
-- True
-- >>> isValid "\\\\?\\UNC\\x" -- XXX fix
-- False
-- >>> isValid "\\\\?\\UNC\\c:\\x"
-- True
--
-- DOS local/global device namespace
--
-- >>> isValid "\\\\.\\x"
-- True
-- >>> isValid "\\\\??\\x"
-- True
--
-- Other than these there may be maximum path component length and maximum path
-- length restrictions enforced by the OS as well as the filesystem which we do
-- not validate.
--
#endif
validatePath :: MonadThrow m => Array OS_WORD_TYPE -> m ()
validatePath = Common.validatePath Common.OS_NAME
-- | Returns 'True' if the filepath is valid:
--
-- >>> isValidPath = isJust . Path.validatePath
--
isValidPath :: Array OS_WORD_TYPE -> Bool
isValidPath = isJust . validatePath
-- 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 'validatePath'.
--
{-# INLINE unsafeFromArray #-}
unsafeFromArray :: Array OS_WORD_TYPE -> OS_PATH_TYPE
unsafeFromArray =
#ifndef DEBUG
OS_PATH . Common.unsafeFromArray
#else
fromJust . fromArray
#endif
#ifndef IS_WINDOWS
-- | Convert an encoded array of OS_WORD_TYPE into a value of type
-- OS_PATH_TYPE. The path is validated using 'validatePath'.
--
-- Each OS_WORD_TYPE should be encoded such that:
--
-- * The input does not contain a NUL word.
-- * Values from 1-128 are assumed to be ASCII characters.
--
-- Apart from the above, there are no restrictions on the encoding.
--
-- To bypass path validation checks, use 'unsafeFromArray'.
--
-- Throws 'InvalidPath' if 'validatePath' fails on the resulting path.
--
#else
-- | Convert an encoded array of OS_WORD_TYPE into a value of type
-- OS_PATH_TYPE. The path is validated using 'validatePath'.
--
-- Each OS_WORD_TYPE should be encoded such that:
--
-- * The input does not contain a NUL word.
-- * The OS_WORD_TYPE is encoded with little-endian ordering.
-- * Values from 1-128 are assumed to be ASCII characters.
--
-- Apart from the above, there are no restrictions on the encoding.
--
-- To bypass path validation checks, use 'unsafeFromArray'.
--
-- Throws 'InvalidPath' if 'validatePath' fails on the resulting path.
--
#endif
fromArray :: MonadThrow m => Array OS_WORD_TYPE -> m OS_PATH_TYPE
fromArray arr = OS_PATH <$> Common.fromArray Common.OS_NAME arr
-- XXX Should be a Fold instead?
-- | Like 'fromString' but a streaming operation.
--
-- >>> fromString = Path.fromChars . Stream.fromList
--
-- 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.
--
-- Unicode normalization is not done. If normalization is needed the user can
-- normalize it and then use the 'fromArray' API.
{-# INLINE fromChars #-}
fromChars :: MonadThrow m => Stream Identity Char -> m OS_PATH_TYPE
fromChars s =
OS_PATH <$> Common.fromChars Common.OS_NAME Unicode.UNICODE_ENCODER s
-- | Create an array from a path string using strict CODEC_NAME encoding. The
-- path is not validated, therefore, it may not be valid according to
-- 'validatePath'.
--
-- Same as @toArray . unsafeFromString@.
encodeString :: [Char] -> Array OS_WORD_TYPE
encodeString =
Common.unsafeFromChars Unicode.UNICODE_ENCODER
. Stream.fromList
-- | Like 'fromString' but does not perform any validations mentioned under
-- 'validatePath'. Fails only if unicode encoding fails.
unsafeFromString :: [Char] -> OS_PATH_TYPE
unsafeFromString =
#ifndef DEBUG
OS_PATH
. encodeString
#else
fromJust . fromString
#endif
-- | Encode a Unicode character string to OS_PATH_TYPE using strict CODEC_NAME
-- encoding. The path is validated using 'validatePath'.
--
-- * Throws 'InvalidPath' if 'validatePath' fails on the path
-- * Fails if the stream contains invalid unicode characters
--
fromString :: MonadThrow m => [Char] -> m OS_PATH_TYPE
fromString = fromChars . Stream.fromList
-- | Like fromString but a pure and partial function that throws an
-- 'InvalidPath' exception.
fromString_ :: [Char] -> OS_PATH_TYPE
fromString_ x =
case fromString x of
Left e -> throw e
Right v -> v
-- | Append a separator followed by the supplied string to a path.
--
-- Throws 'InvalidPath' if the resulting path is not a valid path as per
-- 'validatePath'.
--
joinStr :: OS_PATH_TYPE -> [Char] -> OS_PATH_TYPE
joinStr (OS_PATH a) b =
OS_PATH $
Common.append Common.OS_NAME
(Common.toString Unicode.UNICODE_DECODER) a (encodeString b)
------------------------------------------------------------------------------
-- 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_TYPE -> Q Exp
liftPath p =
[| unsafeFromString $(lift $ toString p) :: OS_PATH |]
-- | Generates a Haskell expression of type OS_PATH_TYPE 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.
#ifdef IS_PORTABLE
-- | Generates a OS_PATH_TYPE type from a quoted literal. Equivalent to using
-- 'fromString' on the static literal.
--
-- >>> Path.toString ([path|/usr/bin|] :: Path)
-- "/usr/bin"
--
#endif
path :: QuasiQuoter
path = mkQ pathE
------------------------------------------------------------------------------
-- Eimination
------------------------------------------------------------------------------
-- | Convert the path to an array.
toArray :: OS_PATH_TYPE -> Array OS_WORD_TYPE
toArray (OS_PATH arr) = arr
-- | Decode the path to a stream of Unicode chars using strict CODEC_NAME decoding.
{-# INLINE toChars #-}
toChars :: Monad m => OS_PATH_TYPE -> Stream m Char
toChars (OS_PATH arr) = Common.toChars Unicode.UNICODE_DECODER arr
-- | Decode the path to a stream of Unicode chars using lax CODEC_NAME decoding.
toChars_ :: Monad m => OS_PATH_TYPE -> Stream m Char
toChars_ (OS_PATH arr) = 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 :: OS_PATH_TYPE -> [Char]
toString = runIdentity . Stream.toList . toChars
-- | Decode the path to a Unicode string using lax CODEC_NAME decoding.
toString_ :: OS_PATH_TYPE -> [Char]
toString_ = runIdentity . Stream.toList . toChars_
-- | Show the path as raw characters without any specific decoding.
--
-- See also: 'readArray'.
--
showArray :: OS_PATH_TYPE -> [Char]
showArray (OS_PATH arr) = show arr
#ifndef IS_WINDOWS
#ifdef IS_PORTABLE
-- | Parse a raw array of bytes as a path type.
--
-- >>> readArray = fromJust . Path.fromArray . read
--
-- >>> arr = Path.encodeString "hello"
-- >>> Path.showArray $ (Path.readArray $ show arr :: Path.Path)
-- "fromList [104,101,108,108,111]"
--
-- See also: 'showArray'.
#endif
readArray :: [Char] -> OS_PATH_TYPE
readArray = fromJust . fromArray . 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 AS_OS_CSTRING #-}
AS_OS_CSTRING :: OS_PATH_TYPE -> (OS_CSTRING_TYPE -> IO a) -> IO a
AS_OS_CSTRING p = Array.asCStringUnsafe (toArray p)
#else
-- | Use the path as a pinned CWString. Useful for using a WindowsPath in
-- system calls on Windows.
{-# INLINE AS_OS_CSTRING #-}
AS_OS_CSTRING :: OS_PATH_TYPE -> (OS_CSTRING_TYPE -> IO a) -> IO a
AS_OS_CSTRING p = Array.asCWString (toArray 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 . Path.fromString_
--
-- >>> isRooted "/"
-- True
-- >>> isRooted "/x"
-- True
-- >>> isRooted "."
-- True
-- >>> isRooted "./x"
-- True
--
isRooted :: OS_PATH_TYPE -> 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@.
--
-- >>> isUnrooted = not . Path.isRooted
--
-- >>> isUnrooted = Path.isUnrooted . Path.fromString_
--
-- >>> isUnrooted "x"
-- True
-- >>> isUnrooted "x/y"
-- True
-- >>> isUnrooted ".."
-- True
-- >>> isUnrooted "../x"
-- True
--
isUnrooted :: OS_PATH_TYPE -> Bool
isUnrooted = not . isRooted
#ifndef IS_WINDOWS
-- | Like 'join' but does not check if the second path is rooted.
--
-- >>> f a b = Path.toString $ Path.unsafeJoin (Path.fromString_ a) (Path.fromString_ b)
--
-- >>> f "x" "y"
-- "x/y"
-- >>> f "x/" "y"
-- "x/y"
-- >>> f "x" "/y"
-- "x/y"
-- >>> f "x/" "/y"
-- "x/y"
--
{-# INLINE unsafeJoin #-}
unsafeJoin :: OS_PATH_TYPE -> OS_PATH_TYPE -> OS_PATH_TYPE
unsafeJoin (OS_PATH a) (OS_PATH b) =
OS_PATH
$ Common.unsafeAppend
Common.OS_NAME (Common.toString Unicode.UNICODE_DECODER) a b
-- If you want to avoid runtime failure use the typesafe
-- Streamly.FileSystem.OS_PATH_TYPE.Seg module.
-- | Append a separator followed by another path to a OS_PATH_TYPE. Fails if
-- the second path is a rooted path. Use 'unsafeJoin' to avoid failure if you
-- know it is ok to append the rooted path.
--
-- >>> f a b = Path.toString $ Path.join a b
--
-- >>> f [path|/usr|] [path|bin|]
-- "/usr/bin"
-- >>> f [path|/usr/|] [path|bin|]
-- "/usr/bin"
-- >>> fails (f [path|/usr|] [path|/bin|])
-- True
--
join :: OS_PATH_TYPE -> OS_PATH_TYPE -> OS_PATH_TYPE
join (OS_PATH a) (OS_PATH b) =
OS_PATH
$ Common.append
Common.OS_NAME (Common.toString Unicode.UNICODE_DECODER) a b
-- | A stricter version of 'join' which requires the first path to be a
-- directory like path i.e. having a trailing separator.
--
-- >>> f a b = Path.toString $ Path.joinDir a b
--
-- >>> fails $ f [path|/usr|] [path|bin|]
-- True
--
joinDir ::
OS_PATH_TYPE -> OS_PATH_TYPE -> OS_PATH_TYPE
joinDir
(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 'unsafeJoin'
-- 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.
--
joinCStr :: OS_PATH_TYPE -> CString -> IO OS_PATH_TYPE
joinCStr (OS_PATH a) str =
fmap OS_PATH
$ Common.appendCString
Common.OS_NAME a str
-- | Like 'joinCStr' but creates a pinned path.
--
joinCStr' ::
OS_PATH_TYPE -> CString -> IO OS_PATH_TYPE
joinCStr'
(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_TYPE] -> OS_PATH_TYPE
unsafeJoinPaths = undefined
------------------------------------------------------------------------------
-- Splitting path
------------------------------------------------------------------------------
#ifndef IS_WINDOWS
-- | If a path is rooted then separate the root and the remaining path,
-- otherwise return 'Nothing'. The non-root
-- part is guaranteed to NOT start with a separator.
--
-- Some filepath package equivalent idioms:
--
-- >>> splitDrive = Path.splitRoot
-- >>> joinDrive = Path.unsafeJoin
-- >>> takeDrive = fmap fst . Path.splitRoot
-- >>> dropDrive x = Path.splitRoot x >>= snd
-- >>> hasDrive = isJust . Path.splitRoot