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