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