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