-
Notifications
You must be signed in to change notification settings - Fork 47
/
Common.hs
340 lines (304 loc) · 11.6 KB
/
Common.hs
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
module System.Directory.Internal.Common
( module System.Directory.Internal.Common
, OsPath
, OsString
) where
import Prelude ()
import System.Directory.Internal.Prelude
import GHC.IO.Encoding.Failure (CodingFailureMode(TransliterateCodingFailure))
import GHC.IO.Encoding.UTF16 (mkUTF16le)
import GHC.IO.Encoding.UTF8 (mkUTF8)
import System.File.OsPath.Internal (openFileWithCloseOnExec)
import System.OsPath
( OsPath
, OsString
, addTrailingPathSeparator
, decodeUtf
, decodeWith
, encodeUtf
, hasTrailingPathSeparator
, isPathSeparator
, isRelative
, joinDrive
, joinPath
, normalise
, pack
, pathSeparator
, pathSeparators
, splitDirectories
, splitDrive
, toChar
, unpack
, unsafeFromChar
)
-- | A generator with side-effects.
newtype ListT m a = ListT { unListT :: m (Maybe (a, ListT m a)) }
emptyListT :: Applicative m => ListT m a
emptyListT = ListT (pure Nothing)
maybeToListT :: Applicative m => m (Maybe a) -> ListT m a
maybeToListT m = ListT (((\ x -> (x, emptyListT)) <$>) <$> m)
listToListT :: Applicative m => [a] -> ListT m a
listToListT [] = emptyListT
listToListT (x : xs) = ListT (pure (Just (x, listToListT xs)))
liftJoinListT :: Monad m => m (ListT m a) -> ListT m a
liftJoinListT m = ListT (m >>= unListT)
listTHead :: Functor m => ListT m a -> m (Maybe a)
listTHead (ListT m) = (fst <$>) <$> m
listTToList :: Monad m => ListT m a -> m [a]
listTToList (ListT m) = do
mx <- m
case mx of
Nothing -> return []
Just (x, m') -> do
xs <- listTToList m'
return (x : xs)
andM :: Monad m => m Bool -> m Bool -> m Bool
andM mx my = do
x <- mx
if x
then my
else return x
sequenceWithIOErrors_ :: [IO ()] -> IO ()
sequenceWithIOErrors_ actions = go (Right ()) actions
where
go :: Either IOError () -> [IO ()] -> IO ()
go (Left e) [] = ioError e
go (Right ()) [] = pure ()
go s (m : ms) = s `seq` do
r <- tryIOError m
go (s *> r) ms
-- | Similar to 'try' but only catches a specify kind of 'IOError' as
-- specified by the predicate.
tryIOErrorType :: (IOError -> Bool) -> IO a -> IO (Either IOError a)
tryIOErrorType check action = do
result <- tryIOError action
case result of
Left err -> if check err then pure (Left err) else throwIO err
Right val -> pure (Right val)
-- | Attempt to perform the given action, silencing any IO exception thrown by
-- it.
ignoreIOExceptions :: IO () -> IO ()
ignoreIOExceptions io = io `catchIOError` (\_ -> pure ())
specializeErrorString :: String -> (IOError -> Bool) -> IO a -> IO a
specializeErrorString str errType action = do
mx <- tryIOErrorType errType action
case mx of
Left e -> throwIO (ioeSetErrorString e str)
Right x -> pure x
ioeAddLocation :: IOError -> String -> IOError
ioeAddLocation e loc = do
ioeSetLocation e newLoc
where
newLoc = loc <> if null oldLoc then "" else ":" <> oldLoc
oldLoc = ioeGetLocation e
rightOrError :: Exception e => Either e a -> a
rightOrError (Left e) = error (displayException e)
rightOrError (Right a) = a
-- | Fallibly converts String to OsString. Only intended to be used on literals.
os :: String -> OsString
os = rightOrError . encodeUtf
-- | Fallibly converts OsString to String. Only intended to be used on literals.
so :: OsString -> String
so = rightOrError . decodeUtf
ioeSetOsPath :: IOError -> OsPath -> IOError
ioeSetOsPath err =
ioeSetFileName err .
rightOrError .
decodeWith
(mkUTF8 TransliterateCodingFailure)
(mkUTF16le TransliterateCodingFailure)
dropSpecialDotDirs :: [OsPath] -> [OsPath]
dropSpecialDotDirs = filter f
where f filename = filename /= os "." && filename /= os ".."
-- | Given a list of path segments, expand @.@ and @..@. The path segments
-- must not contain path separators.
expandDots :: [OsPath] -> [OsPath]
expandDots = reverse . go []
where
go ys' xs' =
case xs' of
[] -> ys'
x : xs
| x == os "." -> go ys' xs
| x == os ".." ->
case ys' of
[] -> go (x : ys') xs
y : ys
| y == os ".." -> go (x : ys') xs
| otherwise -> go ys xs
| otherwise -> go (x : ys') xs
-- | Convert to the right kind of slashes.
normalisePathSeps :: OsPath -> OsPath
normalisePathSeps p = pack (normaliseChar <$> unpack p)
where normaliseChar c = if isPathSeparator c then pathSeparator else c
-- | Remove redundant trailing slashes and pick the right kind of slash.
normaliseTrailingSep :: OsPath -> OsPath
normaliseTrailingSep path = do
let path' = reverse (unpack path)
let (sep, path'') = span isPathSeparator path'
let addSep = if null sep then id else (pathSeparator :)
pack (reverse (addSep path''))
-- | Convert empty paths to the current directory, otherwise leave it
-- unchanged.
emptyToCurDir :: OsPath -> OsPath
emptyToCurDir path
| path == mempty = os "."
| otherwise = path
-- | Similar to 'normalise' but empty paths stay empty.
simplifyPosix :: OsPath -> OsPath
simplifyPosix path
| path == mempty = mempty
| otherwise = normalise path
-- | Similar to 'normalise' but:
--
-- * empty paths stay empty,
-- * parent dirs (@..@) are expanded, and
-- * paths starting with @\\\\?\\@ are preserved.
--
-- The goal is to preserve the meaning of paths better than 'normalise'.
simplifyWindows :: OsPath -> OsPath
simplifyWindows path
| path == mempty = mempty
| drive' == os "\\\\?\\" = drive' <> subpath
| otherwise = simplifiedPath
where
simplifiedPath = joinDrive drive' subpath'
(drive, subpath) = splitDrive path
drive' = upperDrive (normaliseTrailingSep (normalisePathSeps drive))
subpath' = appendSep . avoidEmpty . prependSep . joinPath .
stripPardirs . expandDots . skipSeps .
splitDirectories $ subpath
upperDrive d = case unpack d of
c : k : s
| isAlpha (toChar c), toChar k == ':', all isPathSeparator s ->
-- unsafeFromChar is safe here since all characters are ASCII.
pack (unsafeFromChar (toUpper (toChar c)) : unsafeFromChar ':' : s)
_ -> d
skipSeps =
(pack <$>) .
filter (not . (`elem` (pure <$> pathSeparators))) .
(unpack <$>)
stripPardirs | pathIsAbsolute || subpathIsAbsolute = dropWhile (== os "..")
| otherwise = id
prependSep | subpathIsAbsolute = (pack [pathSeparator] <>)
| otherwise = id
avoidEmpty | not pathIsAbsolute
, drive == mempty || hasTrailingPathSep -- prefer "C:" over "C:."
= emptyToCurDir
| otherwise = id
appendSep p | hasTrailingPathSep, not (pathIsAbsolute && p == mempty)
= addTrailingPathSeparator p
| otherwise = p
pathIsAbsolute = not (isRelative path)
subpathIsAbsolute = any isPathSeparator (take 1 (unpack subpath))
hasTrailingPathSep = hasTrailingPathSeparator subpath
data WhetherFollow = NoFollow | FollowLinks deriving (Show)
isNoFollow :: WhetherFollow -> Bool
isNoFollow NoFollow = True
isNoFollow FollowLinks = False
data FileType = File
| SymbolicLink -- ^ POSIX: either file or directory link; Windows: file link
| Directory
| DirectoryLink -- ^ Windows only: directory link
deriving (Bounded, Enum, Eq, Ord, Read, Show)
-- | Check whether the given 'FileType' is considered a directory by the
-- operating system. This affects the choice of certain functions
-- e.g. 'System.Directory.removeDirectory' vs 'System.Directory.removeFile'.
fileTypeIsDirectory :: FileType -> Bool
fileTypeIsDirectory Directory = True
fileTypeIsDirectory DirectoryLink = True
fileTypeIsDirectory _ = False
-- | Return whether the given 'FileType' is a link.
fileTypeIsLink :: FileType -> Bool
fileTypeIsLink SymbolicLink = True
fileTypeIsLink DirectoryLink = True
fileTypeIsLink _ = False
data Permissions
= Permissions
{ readable :: Bool
, writable :: Bool
, executable :: Bool
, searchable :: Bool
} deriving (Eq, Ord, Read, Show)
withBinaryFile :: OsPath -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile path mode = bracket (openFileWithCloseOnExec path mode) hClose
-- | Copy data from one handle to another until end of file.
copyHandleData :: Handle -- ^ Source handle
-> Handle -- ^ Destination handle
-> IO ()
copyHandleData hFrom hTo =
(`ioeAddLocation` "copyData") `modifyIOError` do
allocaBytes bufferSize go
where
bufferSize = 131072 -- 128 KiB, as coreutils `cp` uses as of May 2014 (see ioblksize.h)
go buffer = do
count <- hGetBuf hFrom buffer bufferSize
when (count > 0) $ do
hPutBuf hTo buffer count
go buffer
-- | Special directories for storing user-specific application data,
-- configuration, and cache files, as specified by the
-- <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html XDG Base Directory Specification>.
--
-- Note: On Windows, 'XdgData' and 'XdgConfig' usually map to the same
-- directory.
--
-- @since 1.2.3.0
data XdgDirectory
= XdgData
-- ^ For data files (e.g. images).
-- It uses the @XDG_DATA_HOME@ environment variable.
-- On non-Windows systems, the default is @~\/.local\/share@.
-- On Windows, the default is @%APPDATA%@
-- (e.g. @C:\/Users\//\<user\>/\/AppData\/Roaming@).
-- Can be considered as the user-specific equivalent of @\/usr\/share@.
| XdgConfig
-- ^ For configuration files.
-- It uses the @XDG_CONFIG_HOME@ environment variable.
-- On non-Windows systems, the default is @~\/.config@.
-- On Windows, the default is @%APPDATA%@
-- (e.g. @C:\/Users\//\<user\>/\/AppData\/Roaming@).
-- Can be considered as the user-specific equivalent of @\/etc@.
| XdgCache
-- ^ For non-essential files (e.g. cache).
-- It uses the @XDG_CACHE_HOME@ environment variable.
-- On non-Windows systems, the default is @~\/.cache@.
-- On Windows, the default is @%LOCALAPPDATA%@
-- (e.g. @C:\/Users\//\<user\>/\/AppData\/Local@).
-- Can be considered as the user-specific equivalent of @\/var\/cache@.
| XdgState
-- ^ For data that should persist between (application) restarts,
-- but that is not important or portable enough to the user that it
-- should be stored in 'XdgData'.
-- It uses the @XDG_STATE_HOME@ environment variable.
-- On non-Windows sytems, the default is @~\/.local\/state@. On
-- Windows, the default is @%LOCALAPPDATA%@
-- (e.g. @C:\/Users\//\<user\>/\/AppData\/Local@).
--
-- @since 1.3.7.0
deriving (Bounded, Enum, Eq, Ord, Read, Show)
-- | Search paths for various application data, as specified by the
-- <http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html XDG Base Directory Specification>.
--
-- The list of paths is split using 'System.FilePath.searchPathSeparator',
-- which on Windows is a semicolon.
--
-- Note: On Windows, 'XdgDataDirs' and 'XdgConfigDirs' usually yield the same
-- result.
--
-- @since 1.3.2.0
data XdgDirectoryList
= XdgDataDirs
-- ^ For data files (e.g. images).
-- It uses the @XDG_DATA_DIRS@ environment variable.
-- On non-Windows systems, the default is @\/usr\/local\/share\/@ and
-- @\/usr\/share\/@.
-- On Windows, the default is @%PROGRAMDATA%@ or @%ALLUSERSPROFILE%@
-- (e.g. @C:\/ProgramData@).
| XdgConfigDirs
-- ^ For configuration files.
-- It uses the @XDG_CONFIG_DIRS@ environment variable.
-- On non-Windows systems, the default is @\/etc\/xdg@.
-- On Windows, the default is @%PROGRAMDATA%@ or @%ALLUSERSPROFILE%@
-- (e.g. @C:\/ProgramData@).
deriving (Bounded, Enum, Eq, Ord, Read, Show)