Make some utils -Wall clean
[ghc.git] / utils / ghc-pkg / Main.hs
1 {-# OPTIONS -fglasgow-exts -cpp #-}
2 -----------------------------------------------------------------------------
3 --
4 -- (c) The University of Glasgow 2004.
5 --
6 -- Package management tool
7 --
8 -----------------------------------------------------------------------------
9
10 -- TODO:
11 -- * validate modules
12 -- * expanding of variables in new-style package conf
13 -- * version manipulation (checking whether old version exists,
14 -- hiding old version?)
15
16 module Main (main) where
17
18 import Version ( version, targetOS, targetARCH )
19 import Distribution.InstalledPackageInfo hiding (depends)
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils
22 import Distribution.Package
23 import Distribution.Text
24 import Distribution.Version
25 import System.FilePath
26 import System.Cmd ( rawSystem )
27 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
28
29 import Prelude
30
31 #include "../../includes/ghcconfig.h"
32
33 import System.Console.GetOpt
34 import Text.PrettyPrint
35 import qualified Control.Exception as Exception
36 import Data.Maybe
37
38 import Data.Char ( isSpace, toLower )
39 import Control.Monad
40 import System.Directory ( doesDirectoryExist, getDirectoryContents,
41 doesFileExist, renameFile, removeFile )
42 import System.Exit ( exitWith, ExitCode(..) )
43 import System.Environment ( getArgs, getProgName, getEnv )
44 import System.IO
45 import System.IO.Error (try)
46 import Data.List
47 import Control.Concurrent
48
49 #ifdef mingw32_HOST_OS
50 import Foreign
51 import Foreign.C.String
52 import GHC.ConsoleHandler
53 #else
54 import System.Posix
55 #endif
56
57 import IO ( isPermissionError )
58
59 #if defined(GLOB)
60 import System.Process(runInteractiveCommand)
61 import qualified System.Info(os)
62 #endif
63
64 -- -----------------------------------------------------------------------------
65 -- Entry point
66
67 main :: IO ()
68 main = do
69 args <- getArgs
70
71 case getOpt Permute (flags ++ deprecFlags) args of
72 (cli,_,[]) | FlagHelp `elem` cli -> do
73 prog <- getProgramName
74 bye (usageInfo (usageHeader prog) flags)
75 (cli,_,[]) | FlagVersion `elem` cli ->
76 bye ourCopyright
77 (cli,nonopts,[]) ->
78 runit cli nonopts
79 (_,_,errors) -> do
80 prog <- getProgramName
81 die (concat errors ++ usageInfo (usageHeader prog) flags)
82
83 -- -----------------------------------------------------------------------------
84 -- Command-line syntax
85
86 data Flag
87 = FlagUser
88 | FlagGlobal
89 | FlagHelp
90 | FlagVersion
91 | FlagConfig FilePath
92 | FlagGlobalConfig FilePath
93 | FlagForce
94 | FlagForceFiles
95 | FlagAutoGHCiLibs
96 | FlagSimpleOutput
97 | FlagNamesOnly
98 | FlagIgnoreCase
99 | FlagNoUserDb
100 deriving Eq
101
102 flags :: [OptDescr Flag]
103 flags = [
104 Option [] ["user"] (NoArg FlagUser)
105 "use the current user's package database",
106 Option [] ["global"] (NoArg FlagGlobal)
107 "use the global package database",
108 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
109 "use the specified package config file",
110 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
111 "location of the global package config",
112 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
113 "never read the user package database",
114 Option [] ["force"] (NoArg FlagForce)
115 "ignore missing dependencies, directories, and libraries",
116 Option [] ["force-files"] (NoArg FlagForceFiles)
117 "ignore missing directories and libraries only",
118 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
119 "automatically build libs for GHCi (with register)",
120 Option ['?'] ["help"] (NoArg FlagHelp)
121 "display this help and exit",
122 Option ['V'] ["version"] (NoArg FlagVersion)
123 "output version information and exit",
124 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
125 "print output in easy-to-parse format for some commands",
126 Option [] ["names-only"] (NoArg FlagNamesOnly)
127 "only print package names, not versions; can only be used with list --simple-output",
128 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
129 "ignore case for substring matching"
130 ]
131
132 deprecFlags :: [OptDescr Flag]
133 deprecFlags = [
134 -- put deprecated flags here
135 ]
136
137 ourCopyright :: String
138 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
139
140 usageHeader :: String -> String
141 usageHeader prog = substProg prog $
142 "Usage:\n" ++
143 " $p register {filename | -}\n" ++
144 " Register the package using the specified installed package\n" ++
145 " description. The syntax for the latter is given in the $p\n" ++
146 " documentation.\n" ++
147 "\n" ++
148 " $p update {filename | -}\n" ++
149 " Register the package, overwriting any other package with the\n" ++
150 " same name.\n" ++
151 "\n" ++
152 " $p unregister {pkg-id}\n" ++
153 " Unregister the specified package.\n" ++
154 "\n" ++
155 " $p expose {pkg-id}\n" ++
156 " Expose the specified package.\n" ++
157 "\n" ++
158 " $p hide {pkg-id}\n" ++
159 " Hide the specified package.\n" ++
160 "\n" ++
161 " $p list [pkg]\n" ++
162 " List registered packages in the global database, and also the\n" ++
163 " user database if --user is given. If a package name is given\n" ++
164 " all the registered versions will be listed in ascending order.\n" ++
165 " Accepts the --simple-output flag.\n" ++
166 "\n" ++
167 " $p find-module {module}\n" ++
168 " List registered packages exposing module {module} in the global\n" ++
169 " database, and also the user database if --user is given.\n" ++
170 " All the registered versions will be listed in ascending order.\n" ++
171 " Accepts the --simple-output flag.\n" ++
172 "\n" ++
173 " $p latest {pkg-id}\n" ++
174 " Prints the highest registered version of a package.\n" ++
175 "\n" ++
176 " $p check\n" ++
177 " Check the consistency of package depenencies and list broken packages.\n" ++
178 " Accepts the --simple-output flag.\n" ++
179 "\n" ++
180 " $p describe {pkg}\n" ++
181 " Give the registered description for the specified package. The\n" ++
182 " description is returned in precisely the syntax required by $p\n" ++
183 " register.\n" ++
184 "\n" ++
185 " $p field {pkg} {field}\n" ++
186 " Extract the specified field of the package description for the\n" ++
187 " specified package. Accepts comma-separated multiple fields.\n" ++
188 "\n" ++
189 " $p dump\n" ++
190 " Dump the registered description for every package. This is like\n" ++
191 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
192 " by tools that parse the results, rather than humans.\n" ++
193 "\n" ++
194 " Substring matching is supported for {module} in find-module and\n" ++
195 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
196 " open substring ends (prefix*, *suffix, *infix*).\n" ++
197 "\n" ++
198 " When asked to modify a database (register, unregister, update,\n"++
199 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
200 " default. Specifying --user causes it to act on the user database,\n"++
201 " or --package-conf can be used to act on another database\n"++
202 " entirely. When multiple of these options are given, the rightmost\n"++
203 " one is used as the database to act upon.\n"++
204 "\n"++
205 " Commands that query the package database (list, latest, describe,\n"++
206 " field) operate on the list of databases specified by the flags\n"++
207 " --user, --global, and --package-conf. If none of these flags are\n"++
208 " given, the default is --global --user.\n"++
209 "\n" ++
210 " The following optional flags are also accepted:\n"
211
212 substProg :: String -> String -> String
213 substProg _ [] = []
214 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
215 substProg prog (c:xs) = c : substProg prog xs
216
217 -- -----------------------------------------------------------------------------
218 -- Do the business
219
220 data Force = ForceAll | ForceFiles | NoForce
221
222 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
223
224 runit :: [Flag] -> [String] -> IO ()
225 runit cli nonopts = do
226 installSignalHandlers -- catch ^C and clean up
227 prog <- getProgramName
228 let
229 force
230 | FlagForce `elem` cli = ForceAll
231 | FlagForceFiles `elem` cli = ForceFiles
232 | otherwise = NoForce
233 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
234 splitFields fields = unfoldr splitComma (',':fields)
235 where splitComma "" = Nothing
236 splitComma fs = Just $ break (==',') (tail fs)
237
238 substringCheck :: String -> Maybe (String -> Bool)
239 substringCheck "" = Nothing
240 substringCheck "*" = Just (const True)
241 substringCheck [_] = Nothing
242 substringCheck (h:t) =
243 case (h, init t, last t) of
244 ('*',s,'*') -> Just (isInfixOf (f s) . f)
245 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
246 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
247 _ -> Nothing
248 where f | FlagIgnoreCase `elem` cli = map toLower
249 | otherwise = id
250 #if defined(GLOB)
251 glob x | System.Info.os=="mingw32" = do
252 -- glob echoes its argument, after win32 filename globbing
253 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
254 txt <- hGetContents o
255 return (read txt)
256 glob x | otherwise = return [x]
257 #endif
258 --
259 -- first, parse the command
260 case nonopts of
261 #if defined(GLOB)
262 -- dummy command to demonstrate usage and permit testing
263 -- without messing things up; use glob to selectively enable
264 -- windows filename globbing for file parameters
265 -- register, update, FlagGlobalConfig, FlagConfig; others?
266 ["glob", filename] -> do
267 print filename
268 glob filename >>= print
269 #endif
270 ["register", filename] ->
271 registerPackage filename cli auto_ghci_libs False force
272 ["update", filename] ->
273 registerPackage filename cli auto_ghci_libs True force
274 ["unregister", pkgid_str] -> do
275 pkgid <- readGlobPkgId pkgid_str
276 unregisterPackage pkgid cli force
277 ["expose", pkgid_str] -> do
278 pkgid <- readGlobPkgId pkgid_str
279 exposePackage pkgid cli force
280 ["hide", pkgid_str] -> do
281 pkgid <- readGlobPkgId pkgid_str
282 hidePackage pkgid cli force
283 ["list"] -> do
284 listPackages cli Nothing Nothing
285 ["list", pkgid_str] ->
286 case substringCheck pkgid_str of
287 Nothing -> do pkgid <- readGlobPkgId pkgid_str
288 listPackages cli (Just (Id pkgid)) Nothing
289 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
290 ["find-module", moduleName] -> do
291 let match = maybe (==moduleName) id (substringCheck moduleName)
292 listPackages cli Nothing (Just match)
293 ["latest", pkgid_str] -> do
294 pkgid <- readGlobPkgId pkgid_str
295 latestPackage cli pkgid
296 ["describe", pkgid_str] ->
297 case substringCheck pkgid_str of
298 Nothing -> do pkgid <- readGlobPkgId pkgid_str
299 describePackage cli (Id pkgid)
300 Just m -> describePackage cli (Substring pkgid_str m)
301 ["field", pkgid_str, fields] ->
302 case substringCheck pkgid_str of
303 Nothing -> do pkgid <- readGlobPkgId pkgid_str
304 describeField cli (Id pkgid) (splitFields fields)
305 Just m -> describeField cli (Substring pkgid_str m)
306 (splitFields fields)
307 ["check"] -> do
308 checkConsistency cli
309
310 ["dump"] -> do
311 dumpPackages cli
312
313 [] -> do
314 die ("missing command\n" ++
315 usageInfo (usageHeader prog) flags)
316 (_cmd:_) -> do
317 die ("command-line syntax error\n" ++
318 usageInfo (usageHeader prog) flags)
319
320 parseCheck :: ReadP a a -> String -> String -> IO a
321 parseCheck parser str what =
322 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
323 [x] -> return x
324 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
325
326 readGlobPkgId :: String -> IO PackageIdentifier
327 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
328
329 parseGlobPackageId :: ReadP r PackageIdentifier
330 parseGlobPackageId =
331 parse
332 +++
333 (do n <- parse
334 string "-*"
335 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
336
337 -- globVersion means "all versions"
338 globVersion :: Version
339 globVersion = Version{ versionBranch=[], versionTags=["*"] }
340
341 -- -----------------------------------------------------------------------------
342 -- Package databases
343
344 -- Some commands operate on a single database:
345 -- register, unregister, expose, hide
346 -- however these commands also check the union of the available databases
347 -- in order to check consistency. For example, register will check that
348 -- dependencies exist before registering a package.
349 --
350 -- Some commands operate on multiple databases, with overlapping semantics:
351 -- list, describe, field
352
353 type PackageDBName = FilePath
354 type PackageDB = [InstalledPackageInfo]
355
356 type NamedPackageDB = (PackageDBName, PackageDB)
357 type PackageDBStack = [NamedPackageDB]
358 -- A stack of package databases. Convention: head is the topmost
359 -- in the stack. Earlier entries override later one.
360
361 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
362 allPackagesInStack = concatMap snd
363
364 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
365 getPkgDatabases modify my_flags = do
366 -- first we determine the location of the global package config. On Windows,
367 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
368 -- location is passed to the binary using the --global-config flag by the
369 -- wrapper script.
370 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
371 global_conf <-
372 case [ f | FlagGlobalConfig f <- my_flags ] of
373 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
374 case mb_dir of
375 Nothing -> die err_msg
376 Just dir ->
377 do let path1 = dir </> "package.conf"
378 path2 = dir </> ".." </> ".." </> ".."
379 </> "inplace-datadir"
380 </> "package.conf"
381 exists1 <- doesFileExist path1
382 exists2 <- doesFileExist path2
383 if exists1 then return path1
384 else if exists2 then return path2
385 else die "Can't find package.conf"
386 fs -> return (last fs)
387
388 let global_conf_dir = global_conf ++ ".d"
389 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
390 global_confs <-
391 if global_conf_dir_exists
392 then do files <- getDirectoryContents global_conf_dir
393 return [ global_conf_dir ++ '/' : file
394 | file <- files
395 , isSuffixOf ".conf" file]
396 else return []
397
398 let no_user_db = FlagNoUserDb `elem` my_flags
399
400 -- get the location of the user package database, and create it if necessary
401 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
402 appdir <- try $ getAppUserDataDirectory "ghc"
403
404 mb_user_conf <-
405 if no_user_db then return Nothing else
406 case appdir of
407 Right dir -> do
408 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
409 user_conf = dir </> subdir </> "package.conf"
410 user_exists <- doesFileExist user_conf
411 return (Just (user_conf,user_exists))
412 Left _ ->
413 return Nothing
414
415 -- If the user database doesn't exist, and this command isn't a
416 -- "modify" command, then we won't attempt to create or use it.
417 let sys_databases
418 | Just (user_conf,user_exists) <- mb_user_conf,
419 modify || user_exists = user_conf : global_confs ++ [global_conf]
420 | otherwise = global_confs ++ [global_conf]
421
422 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
423 let env_stack =
424 case e_pkg_path of
425 Left _ -> sys_databases
426 Right path
427 | last cs == "" -> init cs ++ sys_databases
428 | otherwise -> cs
429 where cs = parseSearchPath path
430
431 -- The "global" database is always the one at the bottom of the stack.
432 -- This is the database we modify by default.
433 virt_global_conf = last env_stack
434
435 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
436 where is_db_flag FlagUser
437 | Just (user_conf, _user_exists) <- mb_user_conf
438 = Just user_conf
439 is_db_flag FlagGlobal = Just virt_global_conf
440 is_db_flag (FlagConfig f) = Just f
441 is_db_flag _ = Nothing
442
443 (final_stack, to_modify) <-
444 if not modify
445 then -- For a "read" command, we use all the databases
446 -- specified on the command line. If there are no
447 -- command-line flags specifying databases, the default
448 -- is to use all the ones we know about.
449 if null db_flags then return (env_stack, Nothing)
450 else return (reverse (nub db_flags), Nothing)
451 else let
452 -- For a "modify" command, treat all the databases as
453 -- a stack, where we are modifying the top one, but it
454 -- can refer to packages in databases further down the
455 -- stack.
456
457 -- -f flags on the command line add to the database
458 -- stack, unless any of them are present in the stack
459 -- already.
460 flag_stack = filter (`notElem` env_stack)
461 [ f | FlagConfig f <- reverse my_flags ]
462 ++ env_stack
463
464 -- the database we actually modify is the one mentioned
465 -- rightmost on the command-line.
466 to_modify = if null db_flags
467 then Just virt_global_conf
468 else Just (last db_flags)
469 in
470 return (flag_stack, to_modify)
471
472 db_stack <- mapM readParseDatabase final_stack
473 return (db_stack, to_modify)
474
475 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
476 readParseDatabase filename = do
477 str <- readFile filename `catchIO` \_ -> return emptyPackageConfig
478 let packages = map convertPackageInfoIn $ read str
479 Exception.evaluate packages
480 `catchError` \e->
481 die ("error while parsing " ++ filename ++ ": " ++ show e)
482 return (filename,packages)
483
484 emptyPackageConfig :: String
485 emptyPackageConfig = "[]"
486
487 -- -----------------------------------------------------------------------------
488 -- Registering
489
490 registerPackage :: FilePath
491 -> [Flag]
492 -> Bool -- auto_ghci_libs
493 -> Bool -- update
494 -> Force
495 -> IO ()
496 registerPackage input my_flags auto_ghci_libs update force = do
497 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
498 let
499 db_to_operate_on = my_head "register" $
500 filter ((== to_modify).fst) db_stack
501 --
502 s <-
503 case input of
504 "-" -> do
505 putStr "Reading package info from stdin ... "
506 getContents
507 f -> do
508 putStr ("Reading package info from " ++ show f ++ " ... ")
509 readFile f
510
511 expanded <- expandEnvVars s force
512
513 pkg <- parsePackageInfo expanded
514 putStrLn "done."
515
516 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
517 -- truncate the stack for validation, because we don't allow
518 -- packages lower in the stack to refer to those higher up.
519 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
520 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
521 not_this p = package p /= package pkg
522 writeNewConfig to_modify new_details
523
524 parsePackageInfo
525 :: String
526 -> IO InstalledPackageInfo
527 parsePackageInfo str =
528 case parseInstalledPackageInfo str of
529 ParseOk _warns ok -> return ok
530 ParseFailed err -> case locatedErrorMsg err of
531 (Nothing, s) -> die s
532 (Just l, s) -> die (show l ++ ": " ++ s)
533
534 -- -----------------------------------------------------------------------------
535 -- Exposing, Hiding, Unregistering are all similar
536
537 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
538 exposePackage = modifyPackage (\p -> [p{exposed=True}])
539
540 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
541 hidePackage = modifyPackage (\p -> [p{exposed=False}])
542
543 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
544 unregisterPackage = modifyPackage (\_ -> [])
545
546 modifyPackage
547 :: (InstalledPackageInfo -> [InstalledPackageInfo])
548 -> PackageIdentifier
549 -> [Flag]
550 -> Force
551 -> IO ()
552 modifyPackage fn pkgid my_flags force = do
553 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
554 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
555 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
556 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
557 let
558 pids = map package ps
559 modify pkg
560 | package pkg `elem` pids = fn pkg
561 | otherwise = [pkg]
562 new_config = concat (map modify pkgs)
563
564 let
565 old_broken = brokenPackages (allPackagesInStack db_stack)
566 rest_of_stack = [ (nm, mypkgs)
567 | (nm, mypkgs) <- db_stack, nm /= db_name ]
568 new_stack = (db_name,new_config) : rest_of_stack
569 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
570 newly_broken = filter (`notElem` map package old_broken) new_broken
571 --
572 when (not (null newly_broken)) $
573 dieOrForceAll force ("unregistering " ++ display pkgid ++
574 " would break the following packages: "
575 ++ unwords (map display newly_broken))
576
577 writeNewConfig db_name new_config
578
579 -- -----------------------------------------------------------------------------
580 -- Listing packages
581
582 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
583 listPackages my_flags mPackageName mModuleName = do
584 let simple_output = FlagSimpleOutput `elem` my_flags
585 (db_stack, _) <- getPkgDatabases False my_flags
586 let db_stack_filtered -- if a package is given, filter out all other packages
587 | Just this <- mPackageName =
588 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
589 db_stack
590 | Just match <- mModuleName = -- packages which expose mModuleName
591 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
592 db_stack
593 | otherwise = db_stack
594
595 db_stack_sorted
596 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
597 where sort_pkgs = sortBy cmpPkgIds
598 cmpPkgIds pkg1 pkg2 =
599 case pkgName p1 `compare` pkgName p2 of
600 LT -> LT
601 GT -> GT
602 EQ -> pkgVersion p1 `compare` pkgVersion p2
603 where (p1,p2) = (package pkg1, package pkg2)
604
605 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
606
607 pkg_map = allPackagesInStack db_stack
608 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
609
610 show_func (reverse db_stack_sorted)
611
612 where show_normal pkg_map (db_name,pkg_confs) =
613 hPutStrLn stdout (render $
614 text db_name <> colon $$ nest 4 packages
615 )
616 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
617 broken = map package (brokenPackages pkg_map)
618 pp_pkg p
619 | package p `elem` broken = braces doc
620 | exposed p = doc
621 | otherwise = parens doc
622 where doc = text (display (package p))
623
624 show_simple db_stack = do
625 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
626 else display
627 pkgs = map showPkg $ sortBy compPkgIdVer $
628 map package (allPackagesInStack db_stack)
629 when (not (null pkgs)) $
630 hPutStrLn stdout $ concat $ intersperse " " pkgs
631
632 -- -----------------------------------------------------------------------------
633 -- Prints the highest (hidden or exposed) version of a package
634
635 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
636 latestPackage my_flags pkgid = do
637 (db_stack, _) <- getPkgDatabases False my_flags
638 ps <- findPackages db_stack (Id pkgid)
639 show_pkg (sortBy compPkgIdVer (map package ps))
640 where
641 show_pkg [] = die "no matches"
642 show_pkg pids = hPutStrLn stdout (display (last pids))
643
644 -- -----------------------------------------------------------------------------
645 -- Describe
646
647 describePackage :: [Flag] -> PackageArg -> IO ()
648 describePackage my_flags pkgarg = do
649 (db_stack, _) <- getPkgDatabases False my_flags
650 ps <- findPackages db_stack pkgarg
651 doDump ps
652
653 dumpPackages :: [Flag] -> IO ()
654 dumpPackages my_flags = do
655 (db_stack, _) <- getPkgDatabases False my_flags
656 doDump (allPackagesInStack db_stack)
657
658 doDump :: [InstalledPackageInfo] -> IO ()
659 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
660
661 -- PackageId is can have globVersion for the version
662 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
663 findPackages db_stack pkgarg
664 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
665
666 findPackagesByDB :: PackageDBStack -> PackageArg
667 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
668 findPackagesByDB db_stack pkgarg
669 = case [ (db, matched)
670 | db@(_, pkgs) <- db_stack,
671 let matched = filter (pkgarg `matchesPkg`) pkgs,
672 not (null matched) ] of
673 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
674 ps -> return ps
675 where
676 pkg_msg (Id pkgid) = display pkgid
677 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
678
679 matches :: PackageIdentifier -> PackageIdentifier -> Bool
680 pid `matches` pid'
681 = (pkgName pid == pkgName pid')
682 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
683
684 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
685 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
686 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
687
688 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
689 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
690
691 -- -----------------------------------------------------------------------------
692 -- Field
693
694 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
695 describeField my_flags pkgarg fields = do
696 (db_stack, _) <- getPkgDatabases False my_flags
697 fns <- toFields fields
698 ps <- findPackages db_stack pkgarg
699 let top_dir = takeDirectory (fst (last db_stack))
700 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
701 where toFields [] = return []
702 toFields (f:fs) = case toField f of
703 Nothing -> die ("unknown field: " ++ f)
704 Just fn -> do fns <- toFields fs
705 return (fn:fns)
706 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
707
708 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
709 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
710 -- with the current topdir (obtained from the -B option).
711 mungePackagePaths top_dir ps = map munge_pkg ps
712 where
713 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
714 includeDirs = munge_paths (includeDirs p),
715 libraryDirs = munge_paths (libraryDirs p),
716 frameworkDirs = munge_paths (frameworkDirs p),
717 haddockInterfaces = munge_paths (haddockInterfaces p),
718 haddockHTMLs = munge_paths (haddockHTMLs p)
719 }
720
721 munge_paths = map munge_path
722
723 munge_path p
724 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
725 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
726 | otherwise = p
727
728 toHttpPath p = "file:///" ++ p
729
730 maybePrefixMatch :: String -> String -> Maybe String
731 maybePrefixMatch [] rest = Just rest
732 maybePrefixMatch (_:_) [] = Nothing
733 maybePrefixMatch (p:pat) (r:rest)
734 | p == r = maybePrefixMatch pat rest
735 | otherwise = Nothing
736
737 toField :: String -> Maybe (InstalledPackageInfo -> String)
738 -- backwards compatibility:
739 toField "import_dirs" = Just $ strList . importDirs
740 toField "source_dirs" = Just $ strList . importDirs
741 toField "library_dirs" = Just $ strList . libraryDirs
742 toField "hs_libraries" = Just $ strList . hsLibraries
743 toField "extra_libraries" = Just $ strList . extraLibraries
744 toField "include_dirs" = Just $ strList . includeDirs
745 toField "c_includes" = Just $ strList . includes
746 toField "package_deps" = Just $ strList . map display. depends
747 toField "extra_cc_opts" = Just $ strList . ccOptions
748 toField "extra_ld_opts" = Just $ strList . ldOptions
749 toField "framework_dirs" = Just $ strList . frameworkDirs
750 toField "extra_frameworks"= Just $ strList . frameworks
751 toField s = showInstalledPackageInfoField s
752
753 strList :: [String] -> String
754 strList = show
755
756
757 -- -----------------------------------------------------------------------------
758 -- Check: Check consistency of installed packages
759
760 checkConsistency :: [Flag] -> IO ()
761 checkConsistency my_flags = do
762 (db_stack, _) <- getPkgDatabases True my_flags
763 -- check behaves like modify for the purposes of deciding which
764 -- databases to use, because ordering is important.
765 let pkgs = allPackagesInStack db_stack
766 broken_pkgs = brokenPackages pkgs
767 broken_ids = map package broken_pkgs
768 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
769 | p <- broken_pkgs ]
770 mapM_ (putStrLn . render . show_func) broken_why
771 where
772 show_func | FlagSimpleOutput `elem` my_flags = show_simple
773 | otherwise = show_normal
774 show_simple (pid,deps) =
775 text (display pid) <> colon
776 <+> fsep (punctuate comma (map (text . display) deps))
777 show_normal (pid,deps) =
778 text "package" <+> text (display pid) <+> text "has missing dependencies:"
779 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
780
781
782 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
783 brokenPackages pkgs = go [] pkgs
784 where
785 go avail not_avail =
786 case partition (depsAvailable avail) not_avail of
787 ([], not_avail') -> not_avail'
788 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
789
790 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
791 -> Bool
792 depsAvailable pkgs_ok pkg = null dangling
793 where dangling = filter (`notElem` pids) (depends pkg)
794 pids = map package pkgs_ok
795
796 -- we want mutually recursive groups of package to show up
797 -- as broken. (#1750)
798
799 -- -----------------------------------------------------------------------------
800 -- Manipulating package.conf files
801
802 type InstalledPackageInfoString = InstalledPackageInfo_ String
803
804 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
805 convertPackageInfoOut
806 (pkgconf@(InstalledPackageInfo { exposedModules = e,
807 hiddenModules = h })) =
808 pkgconf{ exposedModules = map display e,
809 hiddenModules = map display h }
810
811 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
812 convertPackageInfoIn
813 (pkgconf@(InstalledPackageInfo { exposedModules = e,
814 hiddenModules = h })) =
815 pkgconf{ exposedModules = map convert e,
816 hiddenModules = map convert h }
817 where convert = fromJust . simpleParse
818
819 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
820 writeNewConfig filename packages = do
821 hPutStr stdout "Writing new package config file... "
822 createDirectoryIfMissing True $ takeDirectory filename
823 let shown = concat $ intersperse ",\n "
824 $ map (show . convertPackageInfoOut) packages
825 fileContents = "[" ++ shown ++ "\n]"
826 writeFileAtomic filename fileContents
827 `catch` \e ->
828 if isPermissionError e
829 then die (filename ++ ": you don't have permission to modify this file")
830 else ioError e
831 hPutStrLn stdout "done."
832
833 -----------------------------------------------------------------------------
834 -- Sanity-check a new package config, and automatically build GHCi libs
835 -- if requested.
836
837 validatePackageConfig :: InstalledPackageInfo
838 -> PackageDBStack
839 -> Bool -- auto-ghc-libs
840 -> Bool -- update
841 -> Force
842 -> IO ()
843 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
844 checkPackageId pkg
845 checkDuplicates db_stack pkg update force
846 mapM_ (checkDep db_stack force) (depends pkg)
847 checkDuplicateDepends force (depends pkg)
848 mapM_ (checkDir force) (importDirs pkg)
849 mapM_ (checkDir force) (libraryDirs pkg)
850 mapM_ (checkDir force) (includeDirs pkg)
851 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
852 -- ToDo: check these somehow?
853 -- extra_libraries :: [String],
854 -- c_includes :: [String],
855
856 -- When the package name and version are put together, sometimes we can
857 -- end up with a package id that cannot be parsed. This will lead to
858 -- difficulties when the user wants to refer to the package later, so
859 -- we check that the package id can be parsed properly here.
860 checkPackageId :: InstalledPackageInfo -> IO ()
861 checkPackageId ipi =
862 let str = display (package ipi) in
863 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
864 [_] -> return ()
865 [] -> die ("invalid package identifier: " ++ str)
866 _ -> die ("ambiguous package identifier: " ++ str)
867
868 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
869 checkDuplicates db_stack pkg update force = do
870 let
871 pkgid = package pkg
872 (_top_db_name, pkgs) : _ = db_stack
873 --
874 -- Check whether this package id already exists in this DB
875 --
876 when (not update && (pkgid `elem` map package pkgs)) $
877 die ("package " ++ display pkgid ++ " is already installed")
878
879 let
880 uncasep = map toLower . display
881 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
882
883 when (not update && not (null dups)) $ dieOrForceAll force $
884 "Package names may be treated case-insensitively in the future.\n"++
885 "Package " ++ display pkgid ++
886 " overlaps with: " ++ unwords (map display dups)
887
888
889 checkDir :: Force -> String -> IO ()
890 checkDir force d
891 | "$topdir" `isPrefixOf` d = return ()
892 | "$httptopdir" `isPrefixOf` d = return ()
893 -- can't check these, because we don't know what $(http)topdir is
894 | otherwise = do
895 there <- doesDirectoryExist d
896 when (not there)
897 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
898
899 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
900 checkDep db_stack force pkgid
901 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
902 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
903 ++ " doesn't exist")
904 where
905 -- for backwards compat, we treat 0.0 as a special version,
906 -- and don't check that it actually exists.
907 real_version = realVersion pkgid
908
909 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
910 name = pkgName pkgid
911
912 all_pkgs = allPackagesInStack db_stack
913 pkgids = map package all_pkgs
914
915 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
916 checkDuplicateDepends force deps
917 | null dups = return ()
918 | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
919 unwords (map display dups))
920 where
921 dups = [ p | (p:_:_) <- group (sort deps) ]
922
923 realVersion :: PackageIdentifier -> Bool
924 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
925
926 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
927 checkHSLib dirs auto_ghci_libs force lib = do
928 let batch_lib_file = "lib" ++ lib ++ ".a"
929 bs <- mapM (doesLibExistIn batch_lib_file) dirs
930 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
931 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
932 " on library path")
933 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
934
935 doesLibExistIn :: String -> String -> IO Bool
936 doesLibExistIn lib d
937 | "$topdir" `isPrefixOf` d = return True
938 | "$httptopdir" `isPrefixOf` d = return True
939 | otherwise = doesFileExist (d ++ '/':lib)
940
941 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
942 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
943 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
944 | otherwise = do
945 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
946 case [dir | (exists,dir) <- zip bs dirs, exists] of
947 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
948 (_:_) -> return ()
949 where
950 ghci_lib_file = lib ++ ".o"
951
952 -- automatically build the GHCi version of a batch lib,
953 -- using ld --whole-archive.
954
955 autoBuildGHCiLib :: String -> String -> String -> IO ()
956 autoBuildGHCiLib dir batch_file ghci_file = do
957 let ghci_lib_file = dir ++ '/':ghci_file
958 batch_lib_file = dir ++ '/':batch_file
959 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
960 #if defined(darwin_HOST_OS)
961 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
962 #elif defined(mingw32_HOST_OS)
963 execDir <- getExecDir "/bin/ghc-pkg.exe"
964 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
965 #else
966 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
967 #endif
968 when (r /= ExitSuccess) $ exitWith r
969 hPutStrLn stderr (" done.")
970
971 -- -----------------------------------------------------------------------------
972 -- Searching for modules
973
974 #if not_yet
975
976 findModules :: [FilePath] -> IO [String]
977 findModules paths =
978 mms <- mapM searchDir paths
979 return (concat mms)
980
981 searchDir path prefix = do
982 fs <- getDirectoryEntries path `catch` \_ -> return []
983 searchEntries path prefix fs
984
985 searchEntries path prefix [] = return []
986 searchEntries path prefix (f:fs)
987 | looks_like_a_module = do
988 ms <- searchEntries path prefix fs
989 return (prefix `joinModule` f : ms)
990 | looks_like_a_component = do
991 ms <- searchDir (path </> f) (prefix `joinModule` f)
992 ms' <- searchEntries path prefix fs
993 return (ms ++ ms')
994 | otherwise
995 searchEntries path prefix fs
996
997 where
998 (base,suffix) = splitFileExt f
999 looks_like_a_module =
1000 suffix `elem` haskell_suffixes &&
1001 all okInModuleName base
1002 looks_like_a_component =
1003 null suffix && all okInModuleName base
1004
1005 okInModuleName c
1006
1007 #endif
1008
1009 -- ---------------------------------------------------------------------------
1010 -- expanding environment variables in the package configuration
1011
1012 expandEnvVars :: String -> Force -> IO String
1013 expandEnvVars str0 force = go str0 ""
1014 where
1015 go "" acc = return $! reverse acc
1016 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1017 = do value <- lookupEnvVar var
1018 go rest (reverse value ++ acc)
1019 where close c = c == '}' || c == '\n' -- don't span newlines
1020 go (c:str) acc
1021 = go str (c:acc)
1022
1023 lookupEnvVar :: String -> IO String
1024 lookupEnvVar nm =
1025 catch (System.Environment.getEnv nm)
1026 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1027 show nm)
1028 return "")
1029
1030 -----------------------------------------------------------------------------
1031
1032 getProgramName :: IO String
1033 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1034 where str `withoutSuffix` suff
1035 | suff `isSuffixOf` str = take (length str - length suff) str
1036 | otherwise = str
1037
1038 bye :: String -> IO a
1039 bye s = putStr s >> exitWith ExitSuccess
1040
1041 die :: String -> IO a
1042 die = dieWith 1
1043
1044 dieWith :: Int -> String -> IO a
1045 dieWith ec s = do
1046 hFlush stdout
1047 prog <- getProgramName
1048 hPutStrLn stderr (prog ++ ": " ++ s)
1049 exitWith (ExitFailure ec)
1050
1051 dieOrForceAll :: Force -> String -> IO ()
1052 dieOrForceAll ForceAll s = ignoreError s
1053 dieOrForceAll _other s = dieForcible s
1054
1055 dieOrForceFile :: Force -> String -> IO ()
1056 dieOrForceFile ForceAll s = ignoreError s
1057 dieOrForceFile ForceFiles s = ignoreError s
1058 dieOrForceFile _other s = dieForcible s
1059
1060 ignoreError :: String -> IO ()
1061 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1062
1063 dieForcible :: String -> IO ()
1064 dieForcible s = die (s ++ " (use --force to override)")
1065
1066 my_head :: String -> [a] -> a
1067 my_head s [] = error s
1068 my_head _ (x : _) = x
1069
1070 -----------------------------------------
1071 -- Cut and pasted from ghc/compiler/main/SysTools
1072
1073 #if defined(mingw32_HOST_OS)
1074 subst :: Char -> Char -> String -> String
1075 subst a b ls = map (\ x -> if x == a then b else x) ls
1076
1077 unDosifyPath :: FilePath -> FilePath
1078 unDosifyPath xs = subst '\\' '/' xs
1079
1080 getExecDir :: String -> IO (Maybe String)
1081 -- (getExecDir cmd) returns the directory in which the current
1082 -- executable, which should be called 'cmd', is running
1083 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1084 -- you'll get "/a/b/c" back as the result
1085 getExecDir cmd
1086 = allocaArray len $ \buf -> do
1087 ret <- getModuleFileName nullPtr buf len
1088 if ret == 0 then return Nothing
1089 else do s <- peekCString buf
1090 return (Just (reverse (drop (length cmd)
1091 (reverse (unDosifyPath s)))))
1092 where
1093 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1094
1095 foreign import stdcall unsafe "GetModuleFileNameA"
1096 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1097 #else
1098 getExecDir :: String -> IO (Maybe String)
1099 getExecDir _ = return Nothing
1100 #endif
1101
1102 -----------------------------------------
1103 -- Adapted from ghc/compiler/utils/Panic
1104
1105 installSignalHandlers :: IO ()
1106 installSignalHandlers = do
1107 threadid <- myThreadId
1108 let
1109 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1110 --
1111 #if !defined(mingw32_HOST_OS)
1112 installHandler sigQUIT (Catch interrupt) Nothing
1113 installHandler sigINT (Catch interrupt) Nothing
1114 return ()
1115 #elif __GLASGOW_HASKELL__ >= 603
1116 -- GHC 6.3+ has support for console events on Windows
1117 -- NOTE: running GHCi under a bash shell for some reason requires
1118 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1119 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1120 -- why --SDM 17/12/2004
1121 let sig_handler ControlC = interrupt
1122 sig_handler Break = interrupt
1123 sig_handler _ = return ()
1124
1125 installHandler (Catch sig_handler)
1126 return ()
1127 #else
1128 return () -- nothing
1129 #endif
1130
1131 #if __GLASGOW_HASKELL__ <= 604
1132 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1133 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1134 #endif
1135
1136 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1137 #if __GLASGOW_HASKELL__ >= 609
1138 catchIO = Exception.catch
1139 #else
1140 catchIO io handler = io `Exception.catch` handler'
1141 where handler' (Exception.IOException ioe) = handler ioe
1142 handler' e = Exception.throw e
1143 #endif
1144
1145 #if mingw32_HOST_OS || mingw32_TARGET_OS
1146 throwIOIO :: Exception.IOException -> IO a
1147 #if __GLASGOW_HASKELL__ >= 609
1148 throwIOIO = Exception.throwIO
1149 #else
1150 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1151 #endif
1152 #endif
1153
1154 catchError :: IO a -> (String -> IO a) -> IO a
1155 #if __GLASGOW_HASKELL__ >= 609
1156 catchError io handler = io `Exception.catch` handler'
1157 where handler' (Exception.ErrorCall err) = handler err
1158 #else
1159 catchError io handler = io `Exception.catch` handler'
1160 where handler' (Exception.ErrorCall err) = handler err
1161 handler' e = Exception.throw e
1162 #endif
1163
1164 onException :: IO a -> IO () -> IO a
1165 #if __GLASGOW_HASKELL__ >= 609
1166 onException = Exception.onException
1167 #else
1168 onException io what = io `Exception.catch` \e -> do what
1169 Exception.throw e
1170 #endif
1171
1172
1173 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1174 -- to use text files here, rather than binary files.
1175 writeFileAtomic :: FilePath -> String -> IO ()
1176 writeFileAtomic targetFile content = do
1177 (tmpFile, tmpHandle) <- openTempFile targetDir template
1178 do hPutStr tmpHandle content
1179 hClose tmpHandle
1180 #if mingw32_HOST_OS || mingw32_TARGET_OS
1181 renameFile tmpFile targetFile
1182 -- If the targetFile exists then renameFile will fail
1183 `catchIO` \err -> do
1184 exists <- doesFileExist targetFile
1185 if exists
1186 then do removeFile targetFile
1187 -- Big fat hairy race condition
1188 renameFile tmpFile targetFile
1189 -- If the removeFile succeeds and the renameFile fails
1190 -- then we've lost the atomic property.
1191 else throwIOIO err
1192 #else
1193 renameFile tmpFile targetFile
1194 #endif
1195 `onException` do hClose tmpHandle
1196 removeFile tmpFile
1197 where
1198 template = targetName <.> "tmp"
1199 targetDir | null targetDir_ = "."
1200 | otherwise = targetDir_
1201 --TODO: remove this when takeDirectory/splitFileName is fixed
1202 -- to always return a valid dir
1203 (targetDir_,targetName) = splitFileName targetFile
1204
1205 -- | The function splits the given string to substrings
1206 -- using 'isSearchPathSeparator'.
1207 parseSearchPath :: String -> [FilePath]
1208 parseSearchPath path = split path
1209 where
1210 split :: String -> [String]
1211 split s =
1212 case rest' of
1213 [] -> [chunk]
1214 _:rest -> chunk : split rest
1215 where
1216 chunk =
1217 case chunk' of
1218 #ifdef mingw32_HOST_OS
1219 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1220 #endif
1221 _ -> chunk'
1222
1223 (chunk', rest') = break isSearchPathSeparator s