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