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