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