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