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