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