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