[project @ 2004-11-13 14:37:18 by panne]
[ghc-base.git] / System / FilePath.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  System.FilePath
4 -- Copyright   :  (c) The University of Glasgow 2004
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  stable
9 -- Portability :  portable
10 --
11 -- System-independent pathname manipulations.
12 --
13 -----------------------------------------------------------------------------
14
15 module System.FilePath
16          ( -- * File path
17            FilePath
18          , splitFileName
19          , splitFileExt
20          , splitFilePath
21          , joinFileName
22          , joinFileExt
23          , joinPaths         
24          , changeFileExt
25          , isRootedPath
26          , isAbsolutePath
27
28          , pathParents
29          , commonParent
30
31          -- * Search path
32          , parseSearchPath
33          , mkSearchPath
34
35          -- * Separators
36          , isPathSeparator
37          , pathSeparator
38          , searchPathSeparator
39          ) where
40
41 import Data.List(intersperse)
42
43 --------------------------------------------------------------
44 -- * FilePath
45 --------------------------------------------------------------
46
47 -- | Split the path into directory and file name
48 --
49 -- Examples:
50 --
51 -- \[Posix\]
52 --
53 -- > splitFileName "/"            == ("/",    "")
54 -- > splitFileName "/foo/bar.ext" == ("/foo", "bar.ext")
55 -- > splitFileName "bar.ext"      == (".",    "bar.ext")
56 -- > splitFileName "/foo/."       == ("/foo", ".")
57 -- > splitFileName "/foo/.."      == ("/foo", "..")
58 --
59 -- \[Windows\]
60 --
61 -- > splitFileName "\\"               == ("\\",      "")
62 -- > splitFileName "c:\\foo\\bar.ext" == ("c:\\foo", "bar.ext")
63 -- > splitFileName "bar.ext"          == (".",       "bar.ext")
64 -- > splitFileName "c:\\foo\\."       == ("c:\\foo", ".")
65 -- > splitFileName "c:\\foo\\.."      == ("c:\\foo", "..")
66 --
67 -- The first case in the above examples returns an empty file name.
68 -- This is a special case because the \"\/\" (\"\\\\\" on Windows) 
69 -- path doesn\'t refer to an object (file or directory) which resides 
70 -- within a directory.
71 splitFileName :: FilePath -> (String, String)
72 splitFileName p = (reverse (path2++drive), reverse fname)
73   where
74 #ifdef mingw32_TARGET_OS
75     (path,drive) = break (== ':') (reverse p)
76 #else
77     (path,drive) = (reverse p,"")
78 #endif
79     (fname,path1) = break isPathSeparator path
80     path2 = case path1 of
81       []                           -> "."
82       [_]                          -> path1   -- don't remove the trailing slash if 
83                                               -- there is only one character
84       (c:path) | isPathSeparator c -> path
85       _                            -> path1
86
87 -- | Split the path into file name and extension. If the file doesn\'t have extension,
88 -- the function will return empty string. The extension doesn\'t include a leading period.
89 --
90 -- Examples:
91 --
92 -- > splitFileExt "foo.ext" == ("foo", "ext")
93 -- > splitFileExt "foo"     == ("foo", "")
94 -- > splitFileExt "."       == (".",   "")
95 -- > splitFileExt ".."      == ("..",  "")
96 splitFileExt :: FilePath -> (String, String)
97 splitFileExt p =
98   case pre of
99         []      -> (p, [])
100         (_:pre) -> (reverse (pre++path), reverse suf)
101   where
102     (fname,path) = break isPathSeparator (reverse p)
103     (suf,pre) | fname == "." || fname == ".." = (fname,"")
104               | otherwise                     = break (== '.') fname
105
106 -- | Split the path into directory, file name and extension. 
107 -- The function is an optimized version of the following equation:
108 --
109 -- > splitFilePath path = (dir,name,ext)
110 -- >   where
111 -- >     (dir,basename) = splitFileName path
112 -- >     (name,ext)     = splitFileExt  basename
113 splitFilePath :: FilePath -> (String, String, String)
114 splitFilePath p =
115   case pre of
116     []      -> (reverse real_dir, reverse suf, [])
117     (_:pre) -> (reverse real_dir, reverse pre, reverse suf)
118   where
119 #ifdef mingw32_TARGET_OS
120     (path,drive) = break (== ':') (reverse p)
121 #else
122     (path,drive) = (reverse p,"")
123 #endif
124     (file,dir)   = break isPathSeparator path
125     (suf,pre)    = case file of
126                      ".." -> ("..", "")
127                      _    -> break (== '.') file
128     
129     real_dir = case dir of
130       []      -> '.':drive
131       [_]     -> pathSeparator:drive
132       (_:dir) -> dir++drive
133
134 -- | The 'joinFileName' function is the opposite of 'splitFileName'. 
135 -- It joins directory and file names to form complete file path.
136 --
137 -- The general rule is:
138 --
139 -- > dir `joinFileName` basename == path
140 -- >   where
141 -- >     (dir,basename) = splitFileName path
142 --
143 -- There might be an exeptions to the rule but in any case the
144 -- reconstructed path will refer to the same object (file or directory).
145 -- An example exception is that on Windows some slashes might be converted
146 -- to backslashes.
147 joinFileName :: String -> String -> FilePath
148 joinFileName ""  fname = fname
149 joinFileName "." fname = fname
150 joinFileName dir ""    = dir
151 joinFileName dir fname
152   | isPathSeparator (last dir) = dir++fname
153   | otherwise                  = dir++pathSeparator:fname
154
155 -- | The 'joinFileExt' function is the opposite of 'splitFileExt'.
156 -- It joins file name and extension to form complete file path.
157 --
158 -- The general rule is:
159 --
160 -- > filename `joinFileExt` ext == path
161 -- >   where
162 -- >     (filename,ext) = splitFileExt path
163 joinFileExt :: String -> String -> FilePath
164 joinFileExt path ""  = path
165 joinFileExt path ext = path ++ '.':ext
166
167 -- | Given a directory path \"dir\" and a file\/directory path \"rel\",
168 -- returns a merged path \"full\" with the property that
169 -- (cd dir; do_something_with rel) is equivalent to
170 -- (do_something_with full). If the \"rel\" path is an absolute path
171 -- then the returned path is equal to \"rel\"
172 joinPaths :: FilePath -> FilePath -> FilePath
173 joinPaths path1 path2
174   | isRootedPath path2 = path2
175   | otherwise          = 
176 #ifdef mingw32_TARGET_OS
177         case path2 of
178           d:':':path2' | take 2 path1 == [d,':'] -> path1 `joinFileName` path2'
179                        | otherwise               -> path2
180           _                                      -> path1 `joinFileName` path2
181 #else
182         path1 `joinFileName` path2
183 #endif
184   
185 -- | Changes the extension of a file path.
186 changeFileExt :: FilePath           -- ^ The path information to modify.
187           -> String                 -- ^ The new extension (without a leading period).
188                                     -- Specify an empty string to remove an existing 
189                                     -- extension from path.
190           -> FilePath               -- ^ A string containing the modified path information.
191 changeFileExt path ext = joinFileExt name ext
192   where
193     (name,_) = splitFileExt path
194
195 -- | On Unix and Macintosh the 'isRootedPath' function is a synonym to 'isAbsolutePath'.
196 -- The difference is important only on Windows. The rooted path must start from the root
197 -- directory but may not include the drive letter while the absolute path always includes
198 -- the drive letter and the full file path.
199 isRootedPath :: FilePath -> Bool
200 isRootedPath (c:_) | isPathSeparator c = True
201 #ifdef mingw32_TARGET_OS
202 isRootedPath (_:':':c:_) | isPathSeparator c = True  -- path with drive letter
203 #endif
204 isRootedPath _ = False
205
206 -- | Returns True if this path\'s meaning is independent of any OS
207 -- "working directory", False if it isn\'t.
208 isAbsolutePath :: FilePath -> Bool
209 #ifdef mingw32_TARGET_OS
210 isAbsolutePath (_:':':c:_) | isPathSeparator c = True
211 #else
212 isAbsolutePath (c:_)       | isPathSeparator c = True
213 #endif
214 isAbsolutePath _ = False
215
216 -- | Gets this path and all its parents.
217 -- The function is useful in case if you want to create 
218 -- some file but you aren\'t sure whether all directories 
219 -- in the path exists or if you want to search upward for some file.
220 -- 
221 -- Some examples:
222 --
223 -- \[Posix\]
224 --
225 -- >  pathParents "/"          == ["/"]
226 -- >  pathParents "/dir1"      == ["/", "/dir1"]
227 -- >  pathParents "/dir1/dir2" == ["/", "/dir1", "/dir1/dir2"]
228 -- >  pathParents "dir1"       == [".", "dir1"]
229 -- >  pathParents "dir1/dir2"  == [".", "dir1", "dir1/dir2"]
230 --
231 -- In the above examples \"\/\" isn\'t included in the list 
232 -- because you can\'t create root directory.
233 --
234 -- \[Windows\]
235 --
236 -- >  pathParents "c:"             == ["c:."]
237 -- >  pathParents "c:\\"           == ["c:\\"]
238 -- >  pathParents "c:\\dir1"       == ["c:\\", "c:\\dir1"]
239 -- >  pathParents "c:\\dir1\\dir2" == ["c:\\", "c:\\dir1", "c:\\dir1\\dir2"]
240 -- >  pathParents "c:dir1"         == ["c:.","c:dir1"]
241 -- >  pathParents "dir1\\dir2"     == [".", "dir1", "dir1\\dir2"]
242 --
243 -- Note that if the file is relative then the the current directory (\".\") 
244 -- will be explicitly listed.
245 pathParents :: FilePath -> [FilePath]
246 pathParents p =
247     root'' : map ((++) root') (dropEmptyPath $ inits path')
248     where
249 #ifdef mingw32_TARGET_OS
250        (root,path) = case break (== ':') p of
251           (path,    "") -> ("",path)
252           (root,_:path) -> (root++":",path)
253 #else
254        (root,path) = ("",p)
255 #endif
256        (root',root'',path') = case path of
257          (c:path) | isPathSeparator c -> (root++[pathSeparator],root++[pathSeparator],path)
258          _                            -> (root                 ,root++"."            ,path)
259
260        dropEmptyPath ("":paths) = paths
261        dropEmptyPath paths      = paths
262
263        inits :: String -> [String]
264        inits [] =  [""]
265        inits cs = 
266          case pre of
267            "."  -> inits suf
268            ".." -> map (joinFileName pre) (dropEmptyPath $ inits suf)
269            _    -> "" : map (joinFileName pre) (inits suf)
270          where
271            (pre,suf) = case break isPathSeparator cs of
272               (pre,"")    -> (pre, "")
273               (pre,_:suf) -> (pre,suf)
274
275 -- | Given a list of file paths, returns the longest common parent.
276 commonParent :: [FilePath] -> Maybe FilePath
277 commonParent []           = Nothing
278 commonParent paths@(p:ps) = 
279   case common Nothing "" p ps of
280 #ifdef mingw32_TARGET_OS
281     Nothing | all (not . isAbsolutePath) paths -> 
282       case foldr getDrive [] paths of
283         []  -> Just "."
284         [d] -> Just [d,':']
285         _   -> Nothing
286 #else
287     Nothing | all (not . isAbsolutePath) paths -> Just "."
288 #endif
289     mb_path   -> mb_path
290   where
291     getDrive (d:':':_) ds 
292       | not (d `elem` ds) = d:ds
293     getDrive _         ds = ds
294
295     common i acc []     ps = checkSep   i acc         ps
296     common i acc (c:cs) ps
297       | isPathSeparator c  = removeSep  i acc   cs [] ps
298       | otherwise          = removeChar i acc c cs [] ps
299
300     checkSep i acc []      = Just (reverse acc)
301     checkSep i acc ([]:ps) = Just (reverse acc)
302     checkSep i acc ((c1:p):ps)
303       | isPathSeparator c1 = checkSep i acc ps
304     checkSep i acc ps      = i
305
306     removeSep i acc cs pacc []          = 
307       common (Just (reverse (pathSeparator:acc))) (pathSeparator:acc) cs pacc
308     removeSep i acc cs pacc ([]    :ps) = Just (reverse acc)
309     removeSep i acc cs pacc ((c1:p):ps)
310       | isPathSeparator c1              = removeSep i acc cs (p:pacc) ps
311     removeSep i acc cs pacc ps          = i
312
313     removeChar i acc c cs pacc []          = common i (c:acc) cs pacc
314     removeChar i acc c cs pacc ([]    :ps) = i
315     removeChar i acc c cs pacc ((c1:p):ps)
316       | c == c1                            = removeChar i acc c cs (p:pacc) ps
317     removeChar i acc c cs pacc ps          = i
318
319 --------------------------------------------------------------
320 -- * Search path
321 --------------------------------------------------------------
322
323 -- | The function splits the given string to substrings
324 -- using the 'searchPathSeparator'.
325 parseSearchPath :: String -> [FilePath]
326 parseSearchPath path = split searchPathSeparator path
327   where
328     split :: Char -> String -> [String]
329     split c s =
330       case rest of
331         []      -> [chunk] 
332         _:rest' -> chunk : split c rest'
333       where
334         (chunk, rest) = break (==c) s
335
336 -- | The function concatenates the given paths to form a
337 -- single string where the paths are separated with 'searchPathSeparator'.
338 mkSearchPath :: [FilePath] -> String
339 mkSearchPath paths = concat (intersperse [searchPathSeparator] paths)
340
341
342 --------------------------------------------------------------
343 -- * Separators
344 --------------------------------------------------------------
345
346 -- | Checks whether the character is a valid path separator for the host platform.
347 -- The valid character is a 'pathSeparator' but since the Windows operating system 
348 -- also accepts a backslash (\"\\\") the function also checks for \"\/\" on this platform.
349 isPathSeparator :: Char -> Bool
350 isPathSeparator ch =
351 #ifdef mingw32_TARGET_OS
352   ch == '/' || ch == '\\'
353 #else
354   ch == '/'
355 #endif
356
357 -- | Provides a platform-specific character used to separate directory levels in a 
358 -- path string that reflects a hierarchical file system organization.
359 -- The separator is a slash (\"\/\") on Unix and Macintosh, and a backslash (\"\\\") on the 
360 -- Windows operating system.
361 pathSeparator :: Char
362 #ifdef mingw32_TARGET_OS
363 pathSeparator = '\\'
364 #else
365 pathSeparator = '/'
366 #endif
367
368 -- | A platform-specific character used to separate search path strings in 
369 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh, 
370 -- and a semicolon (\";\") on the Windows operating system.
371 searchPathSeparator :: Char
372 #ifdef mingw32_TARGET_OS
373 searchPathSeparator = ';'
374 #else
375 searchPathSeparator = ':'
376 #endif