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