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