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