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