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