[project @ 2005-08-03 09:13:32 by simonmar]
[ghc-hetmet.git] / ghc / utils / ghc-pkg / Main.hs
1 {-# OPTIONS -fglasgow-exts #-}
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  ( showError )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory         ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem         ( rawSystem )
26
27 import Prelude
28
29 #include "../../includes/ghcconfig.h"
30
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
35 import Data.Maybe
36 #else
37 import GetOpt
38 import Pretty
39 import qualified Exception
40 import Maybe
41 #endif
42
43 import Data.Char        ( isSpace )
44 import Monad
45 import Directory
46 import System   ( getArgs, getProgName, getEnv,
47                   exitWith, ExitCode(..)
48                 )
49 import System.IO
50 import Data.List ( isPrefixOf, isSuffixOf, intersperse, groupBy, sortBy )
51
52 #ifdef mingw32_HOST_OS
53 import Foreign
54
55 #if __GLASGOW_HASKELL__ >= 504
56 import Foreign.C.String
57 #else
58 import CString
59 #endif
60 #endif
61
62 -- -----------------------------------------------------------------------------
63 -- Entry point
64
65 main :: IO ()
66 main = do
67   args <- getArgs
68
69   case getOpt Permute flags args of
70         (cli,_,[]) | FlagHelp `elem` cli -> do
71            prog <- getProgramName
72            bye (usageInfo (usageHeader prog) flags)
73         (cli,_,[]) | FlagVersion `elem` cli ->
74            bye ourCopyright
75         (cli,nonopts,[]) ->
76            runit cli nonopts
77         (_,_,errors) -> tryOldCmdLine errors args
78
79 -- If the new command-line syntax fails, then we try the old.  If that
80 -- fails too, then we output the original errors and the new syntax
81 -- (so the old syntax is still available, but hidden).
82 tryOldCmdLine :: [String] -> [String] -> IO ()
83 tryOldCmdLine errors args = do
84   case getOpt Permute oldFlags args of
85         (cli@(_:_),[],[]) -> 
86            oldRunit cli
87         _failed -> do
88            prog <- getProgramName
89            die (concat errors ++ usageInfo (usageHeader prog) flags)
90
91 -- -----------------------------------------------------------------------------
92 -- Command-line syntax
93
94 data Flag
95   = FlagUser
96   | FlagGlobal
97   | FlagHelp
98   | FlagVersion
99   | FlagConfig  FilePath
100   | FlagGlobalConfig FilePath
101   | FlagForce
102   | FlagAutoGHCiLibs
103   | FlagDefinedName String String
104   | FlagSimpleOutput
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         "(default) use the global package database",
113   Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
114         "act upon specified package config file (only)",
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 ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
120         "automatically build libs for GHCi (with register)",
121   Option ['?'] ["help"] (NoArg FlagHelp)
122         "display this help and exit",
123   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
124         "define NAME as VALUE",
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 when running command 'list'"
129   ]
130  where
131   toDefined str = 
132     case break (=='=') str of
133       (nm,[])    -> FlagDefinedName nm []
134       (nm,_:val) -> FlagDefinedName nm val
135
136 ourCopyright :: String
137 ourCopyright = "GHC package manager version " ++ version ++ "\n"
138
139 usageHeader :: String -> String
140 usageHeader prog = substProg prog $
141   "Usage:\n" ++
142   "  $p register {filename | -}\n" ++
143   "    Register the package using the specified installed package\n" ++
144   "    description. The syntax for the latter is given in the $p\n" ++
145   "    documentation.\n" ++
146   "\n" ++
147   "  $p update {filename | -}\n" ++
148   "    Register the package, overwriting any other package with the\n" ++
149   "    same name.\n" ++
150   "\n" ++
151   "  $p unregister {pkg-id}\n" ++
152   "    Unregister the specified package.\n" ++
153   "\n" ++
154   "  $p expose {pkg-id}\n" ++
155   "    Expose the specified package.\n" ++
156   "\n" ++
157   "  $p hide {pkg-id}\n" ++
158   "    Hide the specified package.\n" ++
159   "\n" ++
160   "  $p list [pkg]\n" ++
161   "    List registered packages in the global database, and also the\n" ++
162   "    user database if --user is given. If a package name is given\n" ++
163   "    all the registered versions will be listed in ascending order.\n" ++
164   "\n" ++
165   "  $p latest pkg\n" ++
166   "    Prints the highest registered version of a package.\n" ++
167   "\n" ++
168   "  $p describe {pkg-id}\n" ++
169   "    Give the registered description for the specified package. The\n" ++
170   "    description is returned in precisely the syntax required by $p\n" ++
171   "    register.\n" ++
172   "\n" ++
173   "  $p field {pkg-id} {field}\n" ++
174   "    Extract the specified field of the package description for the\n" ++
175   "    specified package.\n" ++
176   "\n" ++
177   " The following optional flags are also accepted:\n"
178
179 substProg :: String -> String -> String
180 substProg _ [] = []
181 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
182 substProg prog (c:xs) = c : substProg prog xs
183
184 -- -----------------------------------------------------------------------------
185 -- Do the business
186
187 runit :: [Flag] -> [String] -> IO ()
188 runit cli nonopts = do
189   prog <- getProgramName
190   let
191         force = FlagForce `elem` cli
192         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
193         defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
194   --
195   -- first, parse the command
196   case nonopts of
197     ["register", filename] -> 
198         registerPackage filename defines cli auto_ghci_libs False force
199     ["update", filename] -> 
200         registerPackage filename defines cli auto_ghci_libs True force
201     ["unregister", pkgid_str] -> do
202         pkgid <- readGlobPkgId pkgid_str
203         unregisterPackage pkgid cli
204     ["expose", pkgid_str] -> do
205         pkgid <- readGlobPkgId pkgid_str
206         exposePackage pkgid cli
207     ["hide",   pkgid_str] -> do
208         pkgid <- readGlobPkgId pkgid_str
209         hidePackage pkgid cli
210     ["list"] -> do
211         listPackages cli Nothing
212     ["list", package] -> do
213         listPackages cli (Just package)
214     ["latest", package] -> do
215         latestPackage cli package
216     ["describe", pkgid_str] -> do
217         pkgid <- readGlobPkgId pkgid_str
218         describePackage cli pkgid
219     ["field", pkgid_str, field] -> do
220         pkgid <- readGlobPkgId pkgid_str
221         describeField cli pkgid field
222     [] -> do
223         die ("missing command\n" ++ 
224                 usageInfo (usageHeader prog) flags)
225     (_cmd:_) -> do
226         die ("command-line syntax error\n" ++ 
227                 usageInfo (usageHeader prog) flags)
228
229 parseCheck :: ReadP a a -> String -> String -> IO a
230 parseCheck parser str what = 
231   case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
232     [x] -> return x
233     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
234
235 readPkgId :: String -> IO PackageIdentifier
236 readPkgId str = parseCheck parsePackageId str "package identifier"
237
238 readGlobPkgId :: String -> IO PackageIdentifier
239 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
240
241 parseGlobPackageId :: ReadP r PackageIdentifier
242 parseGlobPackageId = 
243   parsePackageId
244      +++
245   (do n <- parsePackageName; string "-*"
246       return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
247
248 -- globVersion means "all versions"
249 globVersion :: Version
250 globVersion = Version{ versionBranch=[], versionTags=["*"] }
251
252 -- -----------------------------------------------------------------------------
253 -- Package databases
254
255 -- Some commands operate on a single database:
256 --      register, unregister, expose, hide
257 -- however these commands also check the union of the available databases
258 -- in order to check consistency.  For example, register will check that
259 -- dependencies exist before registering a package.
260 --
261 -- Some commands operate  on multiple databases, with overlapping semantics:
262 --      list, describe, field
263
264 type PackageDBName  = FilePath
265 type PackageDB      = [InstalledPackageInfo]
266
267 type PackageDBStack = [(PackageDBName,PackageDB)]
268         -- A stack of package databases.  Convention: head is the topmost
269         -- in the stack.  Earlier entries override later one.
270
271 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
272 getPkgDatabases modify flags = do
273   -- first we determine the location of the global package config.  On Windows,
274   -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
275   -- location is passed to the binary using the --global-config flag by the
276   -- wrapper script.
277   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
278   global_conf <- 
279      case [ f | FlagGlobalConfig f <- flags ] of
280         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
281                  case mb_dir of
282                         Nothing  -> die err_msg
283                         Just dir -> return (dir `joinFileName` "package.conf")
284         fs -> return (last fs)
285
286   -- get the location of the user package database, and create it if necessary
287   appdir <- getAppUserDataDirectory "ghc"
288
289   let
290         subdir = targetARCH ++ '-':targetOS ++ '-':version
291         archdir   = appdir `joinFileName` subdir
292         user_conf = archdir `joinFileName` "package.conf"
293   user_exists <- doesFileExist user_conf
294
295   let
296         -- The semantics here are slightly strange.  If we are
297         -- *modifying* the database, then the default is to modify
298         -- the global database by default, unless you say --user.
299         -- If we are not modifying (eg. list, describe etc.) then
300         -- the user database is included by default.
301         databases
302           | modify          = foldl addDB [global_conf] flags
303           | not user_exists = foldl addDB [global_conf] flags
304           | otherwise       = foldl addDB [user_conf,global_conf] flags
305
306         -- implement the following rules:
307         --      --user means overlap with the user database
308         --      --global means reset to just the global database
309         --      -f <file> means overlap with <file>
310         addDB dbs FlagUser
311            | user_conf `elem` dbs     = dbs
312            | modify || user_exists    = user_conf : dbs
313         addDB dbs FlagGlobal     = [global_conf]
314         addDB dbs (FlagConfig f) = f : dbs
315         addDB dbs _              = dbs
316
317   -- we create the user database iff (a) we're modifying, and (b) the
318   -- user asked to use it by giving the --user flag.
319   when (not user_exists && user_conf `elem` databases) $ do
320         putStrLn ("Creating user package database in " ++ user_conf)
321         createDirectoryIfMissing True archdir
322         writeFile user_conf emptyPackageConfig
323
324   db_stack <- mapM readParseDatabase databases
325   return db_stack
326
327 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
328 readParseDatabase filename = do
329   str <- readFile filename
330   let packages = read str
331   Exception.evaluate packages
332     `Exception.catch` \_ -> 
333         die (filename ++ ": parse error in package config file")
334   return (filename,packages)
335
336 emptyPackageConfig :: String
337 emptyPackageConfig = "[]"
338
339 -- -----------------------------------------------------------------------------
340 -- Registering
341
342 registerPackage :: FilePath
343                 -> [(String,String)] -- defines
344                 -> [Flag]
345                 -> Bool         -- auto_ghci_libs
346                 -> Bool         -- update
347                 -> Bool         -- force
348                 -> IO ()
349 registerPackage input defines flags auto_ghci_libs update force = do
350   db_stack <- getPkgDatabases True flags
351   let
352         db_to_operate_on = my_head "db" db_stack
353         db_filename      = fst db_to_operate_on
354   --
355   checkConfigAccess db_filename
356
357   s <-
358     case input of
359       "-" -> do
360         putStr "Reading package info from stdin ... "
361         getContents
362       f   -> do
363         putStr ("Reading package info from " ++ show f ++ " ... ")
364         readFile f
365
366   expanded <- expandEnvVars s defines force
367
368   pkg0 <- parsePackageInfo expanded defines force
369   putStrLn "done."
370
371   let pkg = resolveDeps db_stack pkg0
372   overlaps <- validatePackageConfig pkg db_stack auto_ghci_libs update force
373   new_details <- updatePackageDB db_stack overlaps (snd db_to_operate_on) pkg
374   savePackageConfig db_filename
375   maybeRestoreOldConfig db_filename $
376     writeNewConfig db_filename new_details
377
378 parsePackageInfo
379         :: String
380         -> [(String,String)]
381         -> Bool
382         -> IO InstalledPackageInfo
383 parsePackageInfo str defines force =
384   case parseInstalledPackageInfo str of
385     ParseOk ok -> return ok
386     ParseFailed err -> die (showError err)
387
388 -- -----------------------------------------------------------------------------
389 -- Exposing, Hiding, Unregistering are all similar
390
391 exposePackage :: PackageIdentifier ->  [Flag] -> IO ()
392 exposePackage = modifyPackage (\p -> [p{exposed=True}])
393
394 hidePackage :: PackageIdentifier ->  [Flag] -> IO ()
395 hidePackage = modifyPackage (\p -> [p{exposed=False}])
396
397 unregisterPackage :: PackageIdentifier ->  [Flag] -> IO ()
398 unregisterPackage = modifyPackage (\p -> [])
399
400 modifyPackage
401   :: (InstalledPackageInfo -> [InstalledPackageInfo])
402   -> PackageIdentifier
403   -> [Flag]
404   -> IO ()
405 modifyPackage fn pkgid flags  = do
406   db_stack <- getPkgDatabases True{-modify-} flags
407   let ((db_name, pkgs) : _) = db_stack
408   checkConfigAccess db_name
409   ps <- findPackages [(db_name,pkgs)] pkgid
410   let pids = map package ps
411   savePackageConfig db_name
412   let new_config = concat (map modify pkgs)
413       modify pkg
414           | package pkg `elem` pids = fn pkg
415           | otherwise               = [pkg]
416   maybeRestoreOldConfig db_name $
417       writeNewConfig db_name new_config
418
419 -- -----------------------------------------------------------------------------
420 -- Listing packages
421
422 listPackages ::  [Flag] -> Maybe String -> IO ()
423 listPackages flags mPackageName = do
424   let simple_output = FlagSimpleOutput `elem` flags
425   db_stack <- getPkgDatabases False flags
426   let doesMatch p = fromJust mPackageName == pkgName (package p)
427       db_stack_filtered -- if a package is given, filter out all other packages
428         | Just p <- mPackageName =
429             map (\(conf,pkgs) -> (conf, filter doesMatch pkgs)) db_stack
430         | otherwise = db_stack
431       show_func = if simple_output then show_easy else mapM_ show_regular
432   show_func (reverse db_stack_filtered)
433   where show_regular (db_name,pkg_confs) =
434           hPutStrLn stdout (render $
435                 text (db_name ++ ":") $$ nest 4 packages
436                 )
437            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
438                  pp_pkg p
439                    | exposed p = doc
440                    | otherwise = parens doc
441                    where doc = text (showPackageId (package p))
442         show_easy db_stack = do
443           let pkgs = map showPackageId $ sortBy compPkgIdVer $
444                           map package (concatMap snd db_stack)
445           when (null pkgs) $ die "no matches"
446           hPutStrLn stdout $ concat $ intersperse " " pkgs
447           where
448             compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
449
450 -- -----------------------------------------------------------------------------
451 -- Prints the highest (hidden or exposed) version of a package
452
453 latestPackage ::  [Flag] -> String -> IO ()
454 latestPackage flags packageName = do
455   db_stack <- getPkgDatabases False flags
456   let allPids = map package $ concatMap snd db_stack
457       matches = filter (\p -> packageName == pkgName p) allPids
458   show_pkg (sortBy compPkgIdVer matches)
459   where
460     show_pkg [] = die "no matches"
461     show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
462     compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
463
464 -- -----------------------------------------------------------------------------
465 -- Describe
466
467 describePackage :: [Flag] -> PackageIdentifier -> IO ()
468 describePackage flags pkgid = do
469   db_stack <- getPkgDatabases False flags
470   ps <- findPackages db_stack pkgid
471   mapM_ (putStrLn . showInstalledPackageInfo) ps
472
473 -- PackageId is can have globVersion for the version
474 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
475 findPackages db_stack pkgid
476   = case [ p | p <- all_pkgs, pkgid `matches` p ] of
477         []  -> die ("cannot find package " ++ showPackageId pkgid)
478         [p] -> return [p]
479          -- if the version is globVersion, then we are allowed to match
480          -- multiple packages.  So eg. "Cabal-*" matches all Cabal packages,
481          -- but "Cabal" matches just one Cabal package - if there are more,
482          -- you get an error.
483         ps | versionTags (pkgVersion pkgid) == versionTags globVersion
484            -> return ps
485            | otherwise
486            -> die ("package " ++ showPackageId pkgid ++ 
487                         " matches multiple packages: " ++ 
488                         concat (intersperse ", " (
489                                  map (showPackageId.package) ps)))
490   where
491         pid `matches` pkg
492           = (pkgName pid == pkgName p)
493             && (pkgVersion pid == pkgVersion p || not (realVersion pid))
494           where p = package pkg
495
496         all_pkgs = concat (map snd db_stack)
497
498 -- -----------------------------------------------------------------------------
499 -- Field
500
501 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
502 describeField flags pkgid field = do
503   db_stack <- getPkgDatabases False flags
504   case toField field of
505     Nothing -> die ("unknown field: " ++ field)
506     Just fn -> do
507         ps <- findPackages db_stack pkgid 
508         mapM_ (putStrLn.fn) ps
509
510 toField :: String -> Maybe (InstalledPackageInfo -> String)
511 -- backwards compatibility:
512 toField "import_dirs"     = Just $ strList . importDirs
513 toField "source_dirs"     = Just $ strList . importDirs
514 toField "library_dirs"    = Just $ strList . libraryDirs
515 toField "hs_libraries"    = Just $ strList . hsLibraries
516 toField "extra_libraries" = Just $ strList . extraLibraries
517 toField "include_dirs"    = Just $ strList . includeDirs
518 toField "c_includes"      = Just $ strList . includes
519 toField "package_deps"    = Just $ strList . map showPackageId. depends
520 toField "extra_cc_opts"   = Just $ strList . ccOptions
521 toField "extra_ld_opts"   = Just $ strList . ldOptions
522 toField "framework_dirs"  = Just $ strList . frameworkDirs  
523 toField "extra_frameworks"= Just $ strList . frameworks  
524 toField s                 = showInstalledPackageInfoField s
525
526 strList :: [String] -> String
527 strList = show
528
529 -- -----------------------------------------------------------------------------
530 -- Manipulating package.conf files
531
532 checkConfigAccess :: FilePath -> IO ()
533 checkConfigAccess filename = do
534   access <- getPermissions filename
535   when (not (writable access))
536       (die (filename ++ ": you don't have permission to modify this file"))
537
538 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
539 maybeRestoreOldConfig filename io
540   = io `catch` \e -> do
541         hPutStrLn stderr (show e)
542         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
543                           "configuration was being written.  Attempting to \n"++
544                           "restore the old configuration... ")
545         renameFile (filename ++ ".old")  filename
546         hPutStrLn stdout "done."
547         ioError e
548
549 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
550 writeNewConfig filename packages = do
551   hPutStr stdout "Writing new package config file... "
552   h <- openFile filename WriteMode
553   hPutStrLn h (show packages)
554   hClose h
555   hPutStrLn stdout "done."
556
557 savePackageConfig :: FilePath -> IO ()
558 savePackageConfig filename = do
559   hPutStr stdout "Saving old package config file... "
560     -- mv rather than cp because we've already done an hGetContents
561     -- on this file so we won't be able to open it for writing
562     -- unless we move the old one out of the way...
563   let oldFile = filename ++ ".old"
564   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
565   when doesExist (removeFile oldFile `catch` (const $ return ()))
566   catch (renameFile filename oldFile)
567         (\ err -> do
568                 hPutStrLn stderr (unwords [ "Unable to rename "
569                                           , show filename
570                                           , " to "
571                                           , show oldFile
572                                           ])
573                 ioError err)
574   hPutStrLn stdout "done."
575
576 -----------------------------------------------------------------------------
577 -- Sanity-check a new package config, and automatically build GHCi libs
578 -- if requested.
579
580 validatePackageConfig :: InstalledPackageInfo
581                       -> PackageDBStack
582                       -> Bool   -- auto-ghc-libs
583                       -> Bool   -- update
584                       -> Bool   -- force
585                       -> IO [PackageIdentifier]
586 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
587   checkPackageId pkg
588   overlaps <- checkDuplicates db_stack pkg update force
589   mapM_ (checkDep db_stack force) (depends pkg)
590   mapM_ (checkDir force) (importDirs pkg)
591   mapM_ (checkDir force) (libraryDirs pkg)
592   mapM_ (checkDir force) (includeDirs pkg)
593   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
594   return overlaps
595   -- ToDo: check these somehow?
596   --    extra_libraries :: [String],
597   --    c_includes      :: [String],
598
599 -- When the package name and version are put together, sometimes we can
600 -- end up with a package id that cannot be parsed.  This will lead to 
601 -- difficulties when the user wants to refer to the package later, so
602 -- we check that the package id can be parsed properly here.
603 checkPackageId :: InstalledPackageInfo -> IO ()
604 checkPackageId ipi =
605   let str = showPackageId (package ipi) in
606   case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
607     [_] -> return ()
608     []  -> die ("invalid package identifier: " ++ str)
609     _   -> die ("ambiguous package identifier: " ++ str)
610
611 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
612 resolveDeps db_stack p = updateDeps p
613   where
614         -- The input package spec is allowed to give a package dependency
615         -- without a version number; e.g.
616         --      depends: base
617         -- Here, we update these dependencies without version numbers to
618         -- match the actual versions of the relevant packages installed.
619         updateDeps p = p{depends = map resolveDep (depends p)}
620
621         resolveDep dep_pkgid
622            | realVersion dep_pkgid  = dep_pkgid
623            | otherwise              = lookupDep dep_pkgid
624
625         lookupDep dep_pkgid
626            = let 
627                 name = pkgName dep_pkgid
628              in
629              case [ pid | p <- concat (map snd db_stack), 
630                           let pid = package p,
631                           pkgName pid == name ] of
632                 (pid:_) -> pid          -- Found installed package,
633                                         -- replete with its version
634                 []      -> dep_pkgid    -- No installed package; use 
635                                         -- the version-less one
636
637 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
638          -> IO [PackageIdentifier]
639 checkDuplicates db_stack pkg update force = do
640   let
641         pkgid = package pkg
642         (_top_db_name, pkgs) : _  = db_stack
643   --
644   -- Check whether this package id already exists in this DB
645   --
646   when (not update && (pkgid `elem` map package pkgs)) $
647        die ("package " ++ showPackageId pkgid ++ " is already installed")
648
649   -- 
650   -- Check whether any of the dependencies of the current package
651   -- conflict with each other.
652   --
653   let
654         all_pkgs = concat (map snd db_stack)
655
656         allModules p = exposedModules p ++ hiddenModules p
657
658         our_dependencies = closePackageDeps all_pkgs [pkg]
659         all_dep_modules = concat (map (\p -> zip (allModules p) (repeat p))
660                                          our_dependencies)
661
662         overlaps = [ (m, map snd group) 
663                    | group@((m,_):_) <- groupBy eqfst (sortBy cmpfst all_dep_modules),
664                      length group > 1 ]
665                 where eqfst  (a,_) (b,_) = a == b
666                       cmpfst (a,_) (b,_) = a `compare` b
667
668   when (not (null overlaps)) $
669     diePrettyOrForce force $ vcat [
670         text "package" <+> text (showPackageId (package pkg)) <+>
671           text "has conflicting dependencies:",
672         let complain_about (mod,ps) =
673                 text mod <+> text "is in the following packages:" <+> 
674                         sep (map (text.showPackageId.package) ps)
675         in
676         nest 3 (vcat (map complain_about overlaps))
677         ]
678
679   --
680   -- Now check whether exposing this package will result in conflicts, and
681   -- Figure out which packages we need to hide to resolve the conflicts.
682   --
683   let
684         closure_exposed_pkgs = closePackageDeps pkgs (filter exposed pkgs)
685
686         new_dep_modules = concat $ map allModules $
687                           filter (\p -> package p `notElem` 
688                                         map package closure_exposed_pkgs) $
689                           our_dependencies
690
691         pkgs_with_overlapping_modules =
692                 [ (p, overlapping_mods)
693                 | p <- closure_exposed_pkgs, 
694                   let overlapping_mods = 
695                         filter (`elem` new_dep_modules) (allModules p),
696                   (_:_) <- [overlapping_mods] --trick to get the non-empty ones
697                 ]
698
699         to_hide = map package
700                  $ filter exposed
701                  $ closePackageDepsUpward pkgs
702                  $ map fst pkgs_with_overlapping_modules
703
704   when (not update && exposed pkg && not (null pkgs_with_overlapping_modules)) $ do
705     diePretty $ vcat [
706             text "package" <+> text (showPackageId (package pkg)) <+> 
707                 text "conflicts with the following packages, which are",
708             text "either exposed or a dependency (direct or indirect) of an exposed package:",
709             let complain_about (p, mods)
710                   = text (showPackageId (package p)) <+> text "contains modules" <+> 
711                         sep (punctuate comma (map text mods)) in
712             nest 3 (vcat (map complain_about pkgs_with_overlapping_modules)),
713             text "Using 'update' instead of 'register' will cause the following packages",
714             text "to be hidden, which will eliminate the conflict:",
715             nest 3 (sep (map (text.showPackageId) to_hide))
716           ]
717
718   when (not (null to_hide)) $ do
719     hPutStrLn stderr $ render $ 
720         sep [text "Warning: hiding the following packages to avoid conflict: ",
721              nest 2 (sep (map (text.showPackageId) to_hide))]
722
723   return to_hide
724
725
726 closure :: (a->[a]->Bool) -> (a -> [a]) -> [a] -> [a] -> [a]
727 closure pred more []     res = res
728 closure pred more (p:ps) res
729   | p `pred` res = closure pred more ps res
730   | otherwise    = closure pred more (more p ++ ps) (p:res)
731
732 closePackageDeps :: [InstalledPackageInfo] -> [InstalledPackageInfo]
733          -> [InstalledPackageInfo]
734 closePackageDeps db start 
735   = closure (\p ps -> package p `elem` map package ps) getDepends start []
736   where
737         getDepends p = [ pkg | dep <- depends p, pkg <- lookupPkg dep ]
738         lookupPkg p = [ q | q <- db, p == package q ]
739
740 closePackageDepsUpward :: [InstalledPackageInfo] -> [InstalledPackageInfo]
741          -> [InstalledPackageInfo]
742 closePackageDepsUpward db start
743   = closure (\p ps -> package p `elem` map package ps) getUpwardDepends start []
744   where
745         getUpwardDepends p = [ pkg | pkg <- db, package p `elem` depends pkg ]
746
747
748 checkDir :: Bool -> String -> IO ()
749 checkDir force d
750  | "$topdir" `isPrefixOf` d = return ()
751         -- can't check this, because we don't know what $topdir is
752  | otherwise = do
753    there <- doesDirectoryExist d
754    when (not there)
755        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
756
757 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
758 checkDep db_stack force pkgid
759   | not real_version || pkgid `elem` pkgids = return ()
760   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
761                                         ++ " doesn't exist")
762   where
763         -- for backwards compat, we treat 0.0 as a special version,
764         -- and don't check that it actually exists.
765         real_version = realVersion pkgid
766         
767         all_pkgs = concat (map snd db_stack)
768         pkgids = map package all_pkgs
769
770 realVersion :: PackageIdentifier -> Bool
771 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
772
773 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
774 checkHSLib dirs auto_ghci_libs force lib = do
775   let batch_lib_file = "lib" ++ lib ++ ".a"
776   bs <- mapM (doesLibExistIn batch_lib_file) dirs
777   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
778         [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
779                                  " on library path") 
780         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
781
782 doesLibExistIn :: String -> String -> IO Bool
783 doesLibExistIn lib d
784  | "$topdir" `isPrefixOf` d = return True
785  | otherwise                = doesFileExist (d ++ '/':lib)
786
787 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
788 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
789   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
790   | otherwise  = do
791       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
792       case [dir | (exists,dir) <- zip bs dirs, exists] of
793         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
794         (_:_) -> return ()
795   where
796     ghci_lib_file = lib ++ ".o"
797
798 -- automatically build the GHCi version of a batch lib, 
799 -- using ld --whole-archive.
800
801 autoBuildGHCiLib :: String -> String -> String -> IO ()
802 autoBuildGHCiLib dir batch_file ghci_file = do
803   let ghci_lib_file  = dir ++ '/':ghci_file
804       batch_lib_file = dir ++ '/':batch_file
805   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
806 #if defined(darwin_HOST_OS)
807   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
808 #elif defined(mingw32_HOST_OS)
809   execDir <- getExecDir "/bin/ghc-pkg.exe"
810   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
811 #else
812   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
813 #endif
814   when (r /= ExitSuccess) $ exitWith r
815   hPutStrLn stderr (" done.")
816
817 -- -----------------------------------------------------------------------------
818 -- Updating the DB with the new package.
819
820 updatePackageDB
821         :: PackageDBStack               -- the full stack
822         -> [PackageIdentifier]          -- packages to hide
823         -> [InstalledPackageInfo]       -- packages in *this* DB
824         -> InstalledPackageInfo         -- the new package
825         -> IO [InstalledPackageInfo]
826 updatePackageDB db_stack to_hide pkgs new_pkg = do
827   let
828         pkgid = package new_pkg
829
830         pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
831         
832         -- When update is on, and we're exposing the new package,
833         -- we hide any packages which conflict (see checkDuplicates)
834         -- in the current DB.
835         maybe_hide p
836           | exposed new_pkg && package p `elem` to_hide = p{ exposed = False }
837           | otherwise = p
838   --
839   return (pkgs'++ [new_pkg])
840
841 -- -----------------------------------------------------------------------------
842 -- Searching for modules
843
844 #if not_yet
845
846 findModules :: [FilePath] -> IO [String]
847 findModules paths = 
848   mms <- mapM searchDir paths
849   return (concat mms)
850
851 searchDir path prefix = do
852   fs <- getDirectoryEntries path `catch` \_ -> return []
853   searchEntries path prefix fs
854
855 searchEntries path prefix [] = return []
856 searchEntries path prefix (f:fs)
857   | looks_like_a_module  =  do
858         ms <- searchEntries path prefix fs
859         return (prefix `joinModule` f : ms)
860   | looks_like_a_component  =  do
861         ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
862         ms' <- searchEntries path prefix fs
863         return (ms ++ ms')      
864   | otherwise
865         searchEntries path prefix fs
866
867   where
868         (base,suffix) = splitFileExt f
869         looks_like_a_module = 
870                 suffix `elem` haskell_suffixes && 
871                 all okInModuleName base
872         looks_like_a_component =
873                 null suffix && all okInModuleName base
874
875 okInModuleName c
876
877 #endif
878
879 -- -----------------------------------------------------------------------------
880 -- The old command-line syntax, supported for backwards compatibility
881
882 data OldFlag 
883   = OF_Config FilePath
884   | OF_Input FilePath
885   | OF_List
886   | OF_ListLocal
887   | OF_Add Bool {- True => replace existing info -}
888   | OF_Remove String | OF_Show String 
889   | OF_Field String | OF_AutoGHCiLibs | OF_Force
890   | OF_DefinedName String String
891   | OF_GlobalConfig FilePath
892   deriving (Eq)
893
894 isAction :: OldFlag -> Bool
895 isAction OF_Config{}        = False
896 isAction OF_Field{}         = False
897 isAction OF_Input{}         = False
898 isAction OF_AutoGHCiLibs{}  = False
899 isAction OF_Force{}         = False
900 isAction OF_DefinedName{}   = False
901 isAction OF_GlobalConfig{}  = False
902 isAction _                  = True
903
904 oldFlags :: [OptDescr OldFlag]
905 oldFlags = [
906   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
907         "use the specified package config file",
908   Option ['l'] ["list-packages"] (NoArg OF_List)
909         "list packages in all config files",
910   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
911         "list packages in the specified config file",
912   Option ['a'] ["add-package"] (NoArg (OF_Add False))
913         "add a new package",
914   Option ['u'] ["update-package"] (NoArg (OF_Add True))
915         "update package with new configuration",
916   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
917         "read new package info from specified file",
918   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
919         "show the configuration for package NAME",
920   Option [] ["field"] (ReqArg OF_Field "FIELD")
921         "(with --show-package) Show field FIELD only",
922   Option [] ["force"] (NoArg OF_Force)
923         "ignore missing directories/libraries",
924   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
925         "remove an installed package",
926   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
927         "automatically build libs for GHCi (with -a)",
928   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
929         "define NAME as VALUE",
930   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
931         "location of the global package config"
932   ]
933  where
934   toDefined str = 
935     case break (=='=') str of
936       (nm,[]) -> OF_DefinedName nm []
937       (nm,_:val) -> OF_DefinedName nm val
938
939 oldRunit :: [OldFlag] -> IO ()
940 oldRunit clis = do
941   let new_flags = [ f | Just f <- map conv clis ]
942
943       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
944       conv (OF_Config f)       = Just (FlagConfig f)
945       conv _                   = Nothing
946
947   
948
949   let fields = [ f | OF_Field f <- clis ]
950
951   let auto_ghci_libs = any isAuto clis 
952          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
953       input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
954
955       force = OF_Force `elem` clis
956       
957       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
958
959   case [ c | c <- clis, isAction c ] of
960     [ OF_List ]      -> listPackages new_flags Nothing
961     [ OF_ListLocal ] -> listPackages new_flags Nothing
962     [ OF_Add upd ]   -> 
963         registerPackage input_file defines new_flags auto_ghci_libs upd force
964     [ OF_Remove pkgid_str ]  -> do
965         pkgid <- readPkgId pkgid_str
966         unregisterPackage pkgid new_flags
967     [ OF_Show pkgid_str ]
968         | null fields -> do
969                 pkgid <- readPkgId pkgid_str
970                 describePackage new_flags pkgid
971         | otherwise   -> do
972                 pkgid <- readPkgId pkgid_str
973                 mapM_ (describeField new_flags pkgid) fields
974     _ -> do 
975         prog <- getProgramName
976         die (usageInfo (usageHeader prog) flags)
977
978 my_head :: String -> [a] -> a
979 my_head s [] = error s
980 my_head s (x:xs) = x
981
982 -- ---------------------------------------------------------------------------
983 -- expanding environment variables in the package configuration
984
985 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
986 expandEnvVars str defines force = go str ""
987  where
988    go "" acc = return $! reverse acc
989    go ('$':'{':str) acc | (var, '}':rest) <- break close str
990         = do value <- lookupEnvVar var
991              go rest (reverse value ++ acc)
992         where close c = c == '}' || c == '\n' -- don't span newlines
993    go (c:str) acc
994         = go str (c:acc)
995
996    lookupEnvVar :: String -> IO String
997    lookupEnvVar nm = 
998      case lookup nm defines of
999        Just x | not (null x) -> return x
1000        _      -> 
1001         catch (System.getEnv nm)
1002            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
1003                                         show nm)
1004                       return "")
1005
1006 -----------------------------------------------------------------------------
1007
1008 getProgramName :: IO String
1009 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1010    where str `withoutSuffix` suff
1011             | suff `isSuffixOf` str = take (length str - length suff) str
1012             | otherwise             = str
1013
1014 bye :: String -> IO a
1015 bye s = putStr s >> exitWith ExitSuccess
1016
1017 die :: String -> IO a
1018 die s = do 
1019   hFlush stdout
1020   prog <- getProgramName
1021   hPutStrLn stderr (prog ++ ": " ++ s)
1022   exitWith (ExitFailure 1)
1023
1024 dieOrForce :: Bool -> String -> IO ()
1025 dieOrForce force s 
1026   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1027   | otherwise = die (s ++ " (use --force to override)")
1028
1029 diePretty :: Doc -> IO ()
1030 diePretty doc = do
1031   hFlush stdout
1032   prog <- getProgramName
1033   hPutStrLn stderr $ render $ (text prog <> colon $$ nest 2 doc)
1034   exitWith (ExitFailure 1)
1035
1036 diePrettyOrForce :: Bool -> Doc -> IO ()
1037 diePrettyOrForce force doc
1038   | force     = do hFlush stdout; hPutStrLn stderr (render (doc $$  text "(ignoring)"))
1039   | otherwise = diePretty (doc $$ text "(use --force to override)")
1040
1041 -----------------------------------------
1042 --      Cut and pasted from ghc/compiler/SysTools
1043
1044 #if defined(mingw32_HOST_OS)
1045 subst a b ls = map (\ x -> if x == a then b else x) ls
1046 unDosifyPath xs = subst '\\' '/' xs
1047
1048 getExecDir :: String -> IO (Maybe String)
1049 -- (getExecDir cmd) returns the directory in which the current
1050 --                  executable, which should be called 'cmd', is running
1051 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1052 -- you'll get "/a/b/c" back as the result
1053 getExecDir cmd
1054   = allocaArray len $ \buf -> do
1055         ret <- getModuleFileName nullPtr buf len
1056         if ret == 0 then return Nothing
1057                     else do s <- peekCString buf
1058                             return (Just (reverse (drop (length cmd) 
1059                                                         (reverse (unDosifyPath s)))))
1060   where
1061     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1062
1063 foreign import stdcall unsafe  "GetModuleFileNameA"
1064   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1065 #else
1066 getExecDir :: String -> IO (Maybe String) 
1067 getExecDir _ = return Nothing
1068 #endif
1069
1070 -- -----------------------------------------------------------------------------
1071 -- FilePath utils
1072
1073 -- | The 'joinFileName' function is the opposite of 'splitFileName'. 
1074 -- It joins directory and file names to form a complete file path.
1075 --
1076 -- The general rule is:
1077 --
1078 -- > dir `joinFileName` basename == path
1079 -- >   where
1080 -- >     (dir,basename) = splitFileName path
1081 --
1082 -- There might be an exceptions to the rule but in any case the
1083 -- reconstructed path will refer to the same object (file or directory).
1084 -- An example exception is that on Windows some slashes might be converted
1085 -- to backslashes.
1086 joinFileName :: String -> String -> FilePath
1087 joinFileName ""  fname = fname
1088 joinFileName "." fname = fname
1089 joinFileName dir ""    = dir
1090 joinFileName dir fname
1091   | isPathSeparator (last dir) = dir++fname
1092   | otherwise                  = dir++pathSeparator:fname
1093
1094 -- | Checks whether the character is a valid path separator for the host
1095 -- platform. The valid character is a 'pathSeparator' but since the Windows
1096 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1097 -- checks for it on this platform, too.
1098 isPathSeparator :: Char -> Bool
1099 isPathSeparator ch = ch == pathSeparator || ch == '/'
1100
1101 -- | Provides a platform-specific character used to separate directory levels in
1102 -- a path string that reflects a hierarchical file system organization. The
1103 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1104 -- (@\"\\\"@) on the Windows operating system.
1105 pathSeparator :: Char
1106 #ifdef mingw32_HOST_OS
1107 pathSeparator = '\\'
1108 #else
1109 pathSeparator = '/'
1110 #endif