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