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