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