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