Test for and reject duplicate dependencies (#2330)
[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
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, isDoesNotExistError )
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 ex ->
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 = splitSearchPath 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,pkgs) | (nm,pkgs) <- db_stack, nm /= db_name ]
567       new_stack = (db_name,new_config) : rest_of_stack
568       new_broken = map package (brokenPackages (allPackagesInStack new_stack))
569       newly_broken = filter (`notElem` map package old_broken) new_broken
570   --
571   when (not (null newly_broken)) $
572       dieOrForceAll force ("unregistering " ++ display pkgid ++
573            " would break the following packages: "
574               ++ unwords (map display newly_broken))
575
576   writeNewConfig db_name new_config
577
578 -- -----------------------------------------------------------------------------
579 -- Listing packages
580
581 listPackages ::  [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
582 listPackages my_flags mPackageName mModuleName = do
583   let simple_output = FlagSimpleOutput `elem` my_flags
584   (db_stack, _) <- getPkgDatabases False my_flags
585   let db_stack_filtered -- if a package is given, filter out all other packages
586         | Just this <- mPackageName =
587             map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
588                 db_stack
589         | Just match <- mModuleName = -- packages which expose mModuleName
590             map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
591                 db_stack
592         | otherwise = db_stack
593
594       db_stack_sorted
595           = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
596           where sort_pkgs = sortBy cmpPkgIds
597                 cmpPkgIds pkg1 pkg2 =
598                    case pkgName p1 `compare` pkgName p2 of
599                         LT -> LT
600                         GT -> GT
601                         EQ -> pkgVersion p1 `compare` pkgVersion p2
602                    where (p1,p2) = (package pkg1, package pkg2)
603
604       match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
605
606       pkg_map = allPackagesInStack db_stack
607       show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
608
609   show_func (reverse db_stack_sorted)
610
611   where show_normal pkg_map (db_name,pkg_confs) =
612           hPutStrLn stdout (render $
613                 text db_name <> colon $$ nest 4 packages
614                 )
615            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
616                  broken = map package (brokenPackages pkg_map)
617                  pp_pkg p
618                    | package p `elem` broken = braces doc
619                    | exposed p = doc
620                    | otherwise = parens doc
621                    where doc = text (display (package p))
622
623         show_simple db_stack = do
624           let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
625                                                          else display
626               pkgs = map showPkg $ sortBy compPkgIdVer $
627                           map package (allPackagesInStack db_stack)
628           when (not (null pkgs)) $ 
629              hPutStrLn stdout $ concat $ intersperse " " pkgs
630
631 -- -----------------------------------------------------------------------------
632 -- Prints the highest (hidden or exposed) version of a package
633
634 latestPackage ::  [Flag] -> PackageIdentifier -> IO ()
635 latestPackage my_flags pkgid = do
636   (db_stack, _) <- getPkgDatabases False my_flags
637   ps <- findPackages db_stack (Id pkgid)
638   show_pkg (sortBy compPkgIdVer (map package ps))
639   where
640     show_pkg [] = die "no matches"
641     show_pkg pids = hPutStrLn stdout (display (last pids))
642
643 -- -----------------------------------------------------------------------------
644 -- Describe
645
646 describePackage :: [Flag] -> PackageArg -> IO ()
647 describePackage my_flags pkgarg = do
648   (db_stack, _) <- getPkgDatabases False my_flags
649   ps <- findPackages db_stack pkgarg
650   doDump ps
651
652 dumpPackages :: [Flag] -> IO ()
653 dumpPackages my_flags = do
654   (db_stack, _) <- getPkgDatabases False my_flags
655   doDump (allPackagesInStack db_stack)
656
657 doDump :: [InstalledPackageInfo] -> IO ()
658 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
659
660 -- PackageId is can have globVersion for the version
661 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
662 findPackages db_stack pkgarg
663   = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
664
665 findPackagesByDB :: PackageDBStack -> PackageArg
666                  -> IO [(NamedPackageDB, [InstalledPackageInfo])]
667 findPackagesByDB db_stack pkgarg
668   = case [ (db, matched)
669          | db@(db_name,pkgs) <- db_stack,
670            let matched = filter (pkgarg `matchesPkg`) pkgs,
671            not (null matched) ] of
672         [] -> die ("cannot find package " ++ pkg_msg pkgarg)
673         ps -> return ps
674   where
675         pkg_msg (Id pkgid)           = display pkgid
676         pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
677
678 matches :: PackageIdentifier -> PackageIdentifier -> Bool
679 pid `matches` pid'
680   = (pkgName pid == pkgName pid')
681     && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
682
683 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
684 (Id pid)        `matchesPkg` pkg = pid `matches` package pkg
685 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
686
687 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
688 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
689
690 -- -----------------------------------------------------------------------------
691 -- Field
692
693 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
694 describeField my_flags pkgarg fields = do
695   (db_stack, _) <- getPkgDatabases False my_flags
696   fns <- toFields fields
697   ps <- findPackages db_stack pkgarg
698   let top_dir = takeDirectory (fst (last db_stack))
699   mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
700   where toFields [] = return []
701         toFields (f:fs) = case toField f of
702             Nothing -> die ("unknown field: " ++ f)
703             Just fn -> do fns <- toFields fs
704                           return (fn:fns)
705         selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
706
707 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
708 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
709 -- with the current topdir (obtained from the -B option).
710 mungePackagePaths top_dir ps = map munge_pkg ps
711   where
712   munge_pkg p = p{ importDirs        = munge_paths (importDirs p),
713                    includeDirs       = munge_paths (includeDirs p),
714                    libraryDirs       = munge_paths (libraryDirs p),
715                    frameworkDirs     = munge_paths (frameworkDirs p),
716                    haddockInterfaces = munge_paths (haddockInterfaces p),
717                    haddockHTMLs      = munge_paths (haddockHTMLs p)
718                  }
719
720   munge_paths = map munge_path
721
722   munge_path p
723    | Just p' <- maybePrefixMatch "$topdir"     p =            top_dir ++ p'
724    | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
725    | otherwise                               = p
726
727   toHttpPath p = "file:///" ++ p
728
729 maybePrefixMatch :: String -> String -> Maybe String
730 maybePrefixMatch []    rest = Just rest
731 maybePrefixMatch (_:_) []   = Nothing
732 maybePrefixMatch (p:pat) (r:rest)
733   | p == r    = maybePrefixMatch pat rest
734   | otherwise = Nothing
735
736 toField :: String -> Maybe (InstalledPackageInfo -> String)
737 -- backwards compatibility:
738 toField "import_dirs"     = Just $ strList . importDirs
739 toField "source_dirs"     = Just $ strList . importDirs
740 toField "library_dirs"    = Just $ strList . libraryDirs
741 toField "hs_libraries"    = Just $ strList . hsLibraries
742 toField "extra_libraries" = Just $ strList . extraLibraries
743 toField "include_dirs"    = Just $ strList . includeDirs
744 toField "c_includes"      = Just $ strList . includes
745 toField "package_deps"    = Just $ strList . map display. depends
746 toField "extra_cc_opts"   = Just $ strList . ccOptions
747 toField "extra_ld_opts"   = Just $ strList . ldOptions
748 toField "framework_dirs"  = Just $ strList . frameworkDirs
749 toField "extra_frameworks"= Just $ strList . frameworks
750 toField s                 = showInstalledPackageInfoField s
751
752 strList :: [String] -> String
753 strList = show
754
755
756 -- -----------------------------------------------------------------------------
757 -- Check: Check consistency of installed packages
758
759 checkConsistency :: [Flag] -> IO ()
760 checkConsistency my_flags = do
761   (db_stack, _) <- getPkgDatabases True my_flags
762          -- check behaves like modify for the purposes of deciding which
763          -- databases to use, because ordering is important.
764   let pkgs = allPackagesInStack db_stack
765       broken_pkgs = brokenPackages pkgs
766       broken_ids = map package broken_pkgs
767       broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
768                    | p <- broken_pkgs ]
769   mapM_ (putStrLn . render . show_func) broken_why
770   where
771   show_func | FlagSimpleOutput `elem` my_flags = show_simple
772             | otherwise = show_normal
773   show_simple (pid,deps) =
774     text (display pid) <> colon
775       <+> fsep (punctuate comma (map (text . display) deps))
776   show_normal (pid,deps) =
777     text "package" <+> text (display pid) <+> text "has missing dependencies:"
778       $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
779
780
781 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
782 brokenPackages pkgs = go [] pkgs
783  where
784    go avail not_avail =
785      case partition (depsAvailable avail) not_avail of
786         ([],        not_avail) -> not_avail
787         (new_avail, not_avail) -> go (new_avail ++ avail) not_avail
788
789    depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
790                  -> Bool
791    depsAvailable pkgs_ok pkg = null dangling
792         where dangling = filter (`notElem` pids) (depends pkg)
793               pids = map package pkgs_ok
794
795         -- we want mutually recursive groups of package to show up
796         -- as broken. (#1750)
797
798 -- -----------------------------------------------------------------------------
799 -- Manipulating package.conf files
800
801 type InstalledPackageInfoString = InstalledPackageInfo_ String
802
803 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
804 convertPackageInfoOut
805     (pkgconf@(InstalledPackageInfo { exposedModules = e,
806                                      hiddenModules = h })) =
807         pkgconf{ exposedModules = map display e,
808                  hiddenModules  = map display h }
809
810 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
811 convertPackageInfoIn
812     (pkgconf@(InstalledPackageInfo { exposedModules = e,
813                                      hiddenModules = h })) =
814         pkgconf{ exposedModules = map convert e,
815                  hiddenModules  = map convert h }
816     where convert = fromJust . simpleParse
817
818 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
819 writeNewConfig filename packages = do
820   hPutStr stdout "Writing new package config file... "
821   createDirectoryIfMissing True $ takeDirectory filename
822   let shown = concat $ intersperse ",\n "
823                      $ map (show . convertPackageInfoOut) packages
824       fileContents = "[" ++ shown ++ "\n]"
825   writeFileAtomic filename fileContents
826     `catch` \e ->
827       if isPermissionError e
828       then die (filename ++ ": you don't have permission to modify this file")
829       else ioError e
830   hPutStrLn stdout "done."
831
832 -----------------------------------------------------------------------------
833 -- Sanity-check a new package config, and automatically build GHCi libs
834 -- if requested.
835
836 validatePackageConfig :: InstalledPackageInfo
837                       -> PackageDBStack
838                       -> Bool   -- auto-ghc-libs
839                       -> Bool   -- update
840                       -> Force
841                       -> IO ()
842 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
843   checkPackageId pkg
844   checkDuplicates db_stack pkg update force
845   mapM_ (checkDep db_stack force) (depends pkg)
846   checkDuplicateDepends force (depends pkg)
847   mapM_ (checkDir force) (importDirs pkg)
848   mapM_ (checkDir force) (libraryDirs pkg)
849   mapM_ (checkDir force) (includeDirs pkg)
850   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
851   -- ToDo: check these somehow?
852   --    extra_libraries :: [String],
853   --    c_includes      :: [String],
854
855 -- When the package name and version are put together, sometimes we can
856 -- end up with a package id that cannot be parsed.  This will lead to
857 -- difficulties when the user wants to refer to the package later, so
858 -- we check that the package id can be parsed properly here.
859 checkPackageId :: InstalledPackageInfo -> IO ()
860 checkPackageId ipi =
861   let str = display (package ipi) in
862   case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
863     [_] -> return ()
864     []  -> die ("invalid package identifier: " ++ str)
865     _   -> die ("ambiguous package identifier: " ++ str)
866
867 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
868 checkDuplicates db_stack pkg update force = do
869   let
870         pkgid = package pkg
871         (_top_db_name, pkgs) : _  = db_stack
872   --
873   -- Check whether this package id already exists in this DB
874   --
875   when (not update && (pkgid `elem` map package pkgs)) $
876        die ("package " ++ display pkgid ++ " is already installed")
877
878   let
879         uncasep = map toLower . display
880         dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
881
882   when (not update && not (null dups)) $ dieOrForceAll force $
883         "Package names may be treated case-insensitively in the future.\n"++
884         "Package " ++ display pkgid ++
885         " overlaps with: " ++ unwords (map display dups)
886
887
888 checkDir :: Force -> String -> IO ()
889 checkDir force d
890  | "$topdir"     `isPrefixOf` d = return ()
891  | "$httptopdir" `isPrefixOf` d = return ()
892         -- can't check these, because we don't know what $(http)topdir is
893  | otherwise = do
894    there <- doesDirectoryExist d
895    when (not there)
896        (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
897
898 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
899 checkDep db_stack force pkgid
900   | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
901   | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
902                                         ++ " doesn't exist")
903   where
904         -- for backwards compat, we treat 0.0 as a special version,
905         -- and don't check that it actually exists.
906         real_version = realVersion pkgid
907
908         name_exists = any (\p -> pkgName (package p) == name) all_pkgs
909         name = pkgName pkgid
910
911         all_pkgs = allPackagesInStack db_stack
912         pkgids = map package all_pkgs
913
914 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
915 checkDuplicateDepends force deps
916   | null dups = return ()
917   | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
918                                      unwords (map display dups))
919   where
920        dups = [ p | (p:_:_) <- group (sort deps) ]
921
922 realVersion :: PackageIdentifier -> Bool
923 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
924
925 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
926 checkHSLib dirs auto_ghci_libs force lib = do
927   let batch_lib_file = "lib" ++ lib ++ ".a"
928   bs <- mapM (doesLibExistIn batch_lib_file) dirs
929   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
930         [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
931                                     " on library path")
932         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
933
934 doesLibExistIn :: String -> String -> IO Bool
935 doesLibExistIn lib d
936  | "$topdir"     `isPrefixOf` d = return True
937  | "$httptopdir" `isPrefixOf` d = return True
938  | otherwise                = doesFileExist (d ++ '/':lib)
939
940 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
941 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
942   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
943   | otherwise  = do
944       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
945       case [dir | (exists,dir) <- zip bs dirs, exists] of
946         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
947         (_:_) -> return ()
948   where
949     ghci_lib_file = lib ++ ".o"
950
951 -- automatically build the GHCi version of a batch lib,
952 -- using ld --whole-archive.
953
954 autoBuildGHCiLib :: String -> String -> String -> IO ()
955 autoBuildGHCiLib dir batch_file ghci_file = do
956   let ghci_lib_file  = dir ++ '/':ghci_file
957       batch_lib_file = dir ++ '/':batch_file
958   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
959 #if defined(darwin_HOST_OS)
960   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
961 #elif defined(mingw32_HOST_OS)
962   execDir <- getExecDir "/bin/ghc-pkg.exe"
963   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
964 #else
965   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
966 #endif
967   when (r /= ExitSuccess) $ exitWith r
968   hPutStrLn stderr (" done.")
969
970 -- -----------------------------------------------------------------------------
971 -- Searching for modules
972
973 #if not_yet
974
975 findModules :: [FilePath] -> IO [String]
976 findModules paths =
977   mms <- mapM searchDir paths
978   return (concat mms)
979
980 searchDir path prefix = do
981   fs <- getDirectoryEntries path `catch` \_ -> return []
982   searchEntries path prefix fs
983
984 searchEntries path prefix [] = return []
985 searchEntries path prefix (f:fs)
986   | looks_like_a_module  =  do
987         ms <- searchEntries path prefix fs
988         return (prefix `joinModule` f : ms)
989   | looks_like_a_component  =  do
990         ms <- searchDir (path </> f) (prefix `joinModule` f)
991         ms' <- searchEntries path prefix fs
992         return (ms ++ ms')
993   | otherwise
994         searchEntries path prefix fs
995
996   where
997         (base,suffix) = splitFileExt f
998         looks_like_a_module =
999                 suffix `elem` haskell_suffixes &&
1000                 all okInModuleName base
1001         looks_like_a_component =
1002                 null suffix && all okInModuleName base
1003
1004 okInModuleName c
1005
1006 #endif
1007
1008 -- ---------------------------------------------------------------------------
1009 -- expanding environment variables in the package configuration
1010
1011 expandEnvVars :: String -> Force -> IO String
1012 expandEnvVars str0 force = go str0 ""
1013  where
1014    go "" acc = return $! reverse acc
1015    go ('$':'{':str) acc | (var, '}':rest) <- break close str
1016         = do value <- lookupEnvVar var
1017              go rest (reverse value ++ acc)
1018         where close c = c == '}' || c == '\n' -- don't span newlines
1019    go (c:str) acc
1020         = go str (c:acc)
1021
1022    lookupEnvVar :: String -> IO String
1023    lookupEnvVar nm =
1024         catch (System.Environment.getEnv nm)
1025            (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1026                                         show nm)
1027                       return "")
1028
1029 -----------------------------------------------------------------------------
1030
1031 getProgramName :: IO String
1032 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1033    where str `withoutSuffix` suff
1034             | suff `isSuffixOf` str = take (length str - length suff) str
1035             | otherwise             = str
1036
1037 bye :: String -> IO a
1038 bye s = putStr s >> exitWith ExitSuccess
1039
1040 die :: String -> IO a
1041 die = dieWith 1
1042
1043 dieWith :: Int -> String -> IO a
1044 dieWith ec s = do
1045   hFlush stdout
1046   prog <- getProgramName
1047   hPutStrLn stderr (prog ++ ": " ++ s)
1048   exitWith (ExitFailure ec)
1049
1050 dieOrForceAll :: Force -> String -> IO ()
1051 dieOrForceAll ForceAll s = ignoreError s
1052 dieOrForceAll _other s   = dieForcible s
1053
1054 dieOrForceFile :: Force -> String -> IO ()
1055 dieOrForceFile ForceAll   s = ignoreError s
1056 dieOrForceFile ForceFiles s = ignoreError s
1057 dieOrForceFile _other     s = dieForcible s
1058
1059 ignoreError :: String -> IO ()
1060 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1061
1062 dieForcible :: String -> IO ()
1063 dieForcible s = die (s ++ " (use --force to override)")
1064
1065 my_head :: String -> [a] -> a
1066 my_head s []      = error s
1067 my_head _ (x : _) = x
1068
1069 -----------------------------------------
1070 -- Cut and pasted from ghc/compiler/main/SysTools
1071
1072 #if defined(mingw32_HOST_OS)
1073 subst :: Char -> Char -> String -> String
1074 subst a b ls = map (\ x -> if x == a then b else x) ls
1075
1076 unDosifyPath :: FilePath -> FilePath
1077 unDosifyPath xs = subst '\\' '/' xs
1078
1079 getExecDir :: String -> IO (Maybe String)
1080 -- (getExecDir cmd) returns the directory in which the current
1081 --                  executable, which should be called 'cmd', is running
1082 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1083 -- you'll get "/a/b/c" back as the result
1084 getExecDir cmd
1085   = allocaArray len $ \buf -> do
1086         ret <- getModuleFileName nullPtr buf len
1087         if ret == 0 then return Nothing
1088                     else do s <- peekCString buf
1089                             return (Just (reverse (drop (length cmd)
1090                                                         (reverse (unDosifyPath s)))))
1091   where
1092     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1093
1094 foreign import stdcall unsafe  "GetModuleFileNameA"
1095   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1096 #else
1097 getExecDir :: String -> IO (Maybe String)
1098 getExecDir _ = return Nothing
1099 #endif
1100
1101 -----------------------------------------
1102 -- Adapted from ghc/compiler/utils/Panic
1103
1104 installSignalHandlers :: IO ()
1105 installSignalHandlers = do
1106   threadid <- myThreadId
1107   let
1108       interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1109   --
1110 #if !defined(mingw32_HOST_OS)
1111   installHandler sigQUIT (Catch interrupt) Nothing 
1112   installHandler sigINT  (Catch interrupt) Nothing
1113   return ()
1114 #elif __GLASGOW_HASKELL__ >= 603
1115   -- GHC 6.3+ has support for console events on Windows
1116   -- NOTE: running GHCi under a bash shell for some reason requires
1117   -- you to press Ctrl-Break rather than Ctrl-C to provoke
1118   -- an interrupt.  Ctrl-C is getting blocked somewhere, I don't know
1119   -- why --SDM 17/12/2004
1120   let sig_handler ControlC = interrupt
1121       sig_handler Break    = interrupt
1122       sig_handler _        = return ()
1123
1124   installHandler (Catch sig_handler)
1125   return ()
1126 #else
1127   return () -- nothing
1128 #endif
1129
1130 #if __GLASGOW_HASKELL__ <= 604
1131 isInfixOf               :: (Eq a) => [a] -> [a] -> Bool
1132 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1133 #endif
1134
1135 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1136 #if __GLASGOW_HASKELL__ >= 609
1137 catchIO = Exception.catch
1138 #else
1139 catchIO io handler = io `Exception.catch` handler'
1140     where handler' (Exception.IOException ioe) = handler ioe
1141           handler' e                           = Exception.throw e
1142 #endif
1143
1144 throwIOIO :: Exception.IOException -> IO a
1145 #if __GLASGOW_HASKELL__ >= 609
1146 throwIOIO = Exception.throwIO
1147 #else
1148 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1149 #endif
1150
1151 catchError :: IO a -> (String -> IO a) -> IO a
1152 #if __GLASGOW_HASKELL__ >= 609
1153 catchError io handler = io `Exception.catch` handler'
1154     where handler' (Exception.ErrorCall err) = handler err
1155 #else
1156 catchError io handler = io `Exception.catch` handler'
1157     where handler' (Exception.ErrorCall err) = handler err
1158           handler' e                         = Exception.throw e
1159 #endif
1160
1161 onException :: IO a -> IO () -> IO a
1162 #if __GLASGOW_HASKELL__ >= 609
1163 onException = Exception.onException
1164 #else
1165 onException io what = io `Exception.catch` \e -> do what
1166                                                     Exception.throw e
1167 #endif
1168
1169
1170 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1171 -- to use text files here, rather than binary files.
1172 writeFileAtomic :: FilePath -> String -> IO ()
1173 writeFileAtomic targetFile content = do
1174   (tmpFile, tmpHandle) <- openTempFile targetDir template
1175   do  hPutStr tmpHandle content
1176       hClose tmpHandle
1177 #if mingw32_HOST_OS || mingw32_TARGET_OS
1178       renameFile tmpFile targetFile
1179         -- If the targetFile exists then renameFile will fail
1180         `catchIO` \err -> do
1181           exists <- doesFileExist targetFile
1182           if exists
1183             then do removeFile targetFile
1184                     -- Big fat hairy race condition
1185                     renameFile tmpFile targetFile
1186                     -- If the removeFile succeeds and the renameFile fails
1187                     -- then we've lost the atomic property.
1188             else throwIOIO err
1189 #else
1190       renameFile tmpFile targetFile
1191 #endif
1192    `onException` do hClose tmpHandle
1193                     removeFile tmpFile
1194   where
1195     template = targetName <.> "tmp"
1196     targetDir | null targetDir_ = "."
1197               | otherwise       = targetDir_
1198     --TODO: remove this when takeDirectory/splitFileName is fixed
1199     --      to always return a valid dir
1200     (targetDir_,targetName) = splitFileName targetFile