996cd62efd21f5f6497f38c2088eef31294ce0f8
[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   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 -- ToDo: remove this (see #1837)
719 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> IO InstalledPackageInfo
720 resolveDeps db_stack p  = do
721     when (not (null unversioned_deps)) $
722        hPutStr stderr ("WARNING: unversioned dependencies are deprecated, "++
723                        "and will NOT be accepted by GHC 6.10: " ++
724                        unwords (map showPackageId unversioned_deps) ++ "\n")
725     return (updateDeps p)
726   where
727         unversioned_deps = filter (not.realVersion) (depends p)
728
729         -- The input package spec is allowed to give a package dependency
730         -- without a version number; e.g.
731         --      depends: base
732         -- Here, we update these dependencies without version numbers to
733         -- match the actual versions of the relevant packages installed.
734         updateDeps p = p{depends = map resolveDep (depends p)}
735
736         resolveDep dep_pkgid
737            | realVersion dep_pkgid  = dep_pkgid
738            | otherwise              = lookupDep dep_pkgid
739
740         lookupDep dep_pkgid
741            = let
742                 name = pkgName dep_pkgid
743              in
744              case [ pid | p <- concat (map snd db_stack),
745                           let pid = package p,
746                           pkgName pid == name ] of
747                 (pid:_) -> pid          -- Found installed package,
748                                         -- replete with its version
749                 []      -> dep_pkgid    -- No installed package; use
750                                         -- the version-less one
751
752 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
753 checkDuplicates db_stack pkg update = do
754   let
755         pkgid = package pkg
756         (_top_db_name, pkgs) : _  = db_stack
757   --
758   -- Check whether this package id already exists in this DB
759   --
760   when (not update && (pkgid `elem` map package pkgs)) $
761        die ("package " ++ showPackageId pkgid ++ " is already installed")
762
763
764
765 checkDir :: Force -> String -> IO ()
766 checkDir force d
767  | "$topdir"     `isPrefixOf` d = return ()
768  | "$httptopdir" `isPrefixOf` d = return ()
769         -- can't check these, because we don't know what $(http)topdir is
770  | otherwise = do
771    there <- doesDirectoryExist d
772    when (not there)
773        (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
774
775 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
776 checkDep db_stack force pkgid
777   | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
778   | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
779                                         ++ " doesn't exist")
780   where
781         -- for backwards compat, we treat 0.0 as a special version,
782         -- and don't check that it actually exists.
783         real_version = realVersion pkgid
784
785         name_exists = any (\p -> pkgName (package p) == name) all_pkgs
786         name = pkgName pkgid
787
788         all_pkgs = concat (map snd db_stack)
789         pkgids = map package all_pkgs
790
791 realVersion :: PackageIdentifier -> Bool
792 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
793
794 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
795 checkHSLib dirs auto_ghci_libs force lib = do
796   let batch_lib_file = "lib" ++ lib ++ ".a"
797   bs <- mapM (doesLibExistIn batch_lib_file) dirs
798   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
799         [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
800                                     " on library path")
801         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
802
803 doesLibExistIn :: String -> String -> IO Bool
804 doesLibExistIn lib d
805  | "$topdir"     `isPrefixOf` d = return True
806  | "$httptopdir" `isPrefixOf` d = return True
807  | otherwise                = doesFileExist (d ++ '/':lib)
808
809 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
810 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
811   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
812   | otherwise  = do
813       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
814       case [dir | (exists,dir) <- zip bs dirs, exists] of
815         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
816         (_:_) -> return ()
817   where
818     ghci_lib_file = lib ++ ".o"
819
820 -- automatically build the GHCi version of a batch lib,
821 -- using ld --whole-archive.
822
823 autoBuildGHCiLib :: String -> String -> String -> IO ()
824 autoBuildGHCiLib dir batch_file ghci_file = do
825   let ghci_lib_file  = dir ++ '/':ghci_file
826       batch_lib_file = dir ++ '/':batch_file
827   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
828 #if defined(darwin_HOST_OS)
829   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
830 #elif defined(mingw32_HOST_OS)
831   execDir <- getExecDir "/bin/ghc-pkg.exe"
832   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
833 #else
834   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
835 #endif
836   when (r /= ExitSuccess) $ exitWith r
837   hPutStrLn stderr (" done.")
838
839 -- -----------------------------------------------------------------------------
840 -- Searching for modules
841
842 #if not_yet
843
844 findModules :: [FilePath] -> IO [String]
845 findModules paths =
846   mms <- mapM searchDir paths
847   return (concat mms)
848
849 searchDir path prefix = do
850   fs <- getDirectoryEntries path `catch` \_ -> return []
851   searchEntries path prefix fs
852
853 searchEntries path prefix [] = return []
854 searchEntries path prefix (f:fs)
855   | looks_like_a_module  =  do
856         ms <- searchEntries path prefix fs
857         return (prefix `joinModule` f : ms)
858   | looks_like_a_component  =  do
859         ms <- searchDir (path </> f) (prefix `joinModule` f)
860         ms' <- searchEntries path prefix fs
861         return (ms ++ ms')
862   | otherwise
863         searchEntries path prefix fs
864
865   where
866         (base,suffix) = splitFileExt f
867         looks_like_a_module =
868                 suffix `elem` haskell_suffixes &&
869                 all okInModuleName base
870         looks_like_a_component =
871                 null suffix && all okInModuleName base
872
873 okInModuleName c
874
875 #endif
876
877 -- -----------------------------------------------------------------------------
878 -- The old command-line syntax, supported for backwards compatibility
879
880 data OldFlag
881   = OF_Config FilePath
882   | OF_Input FilePath
883   | OF_List
884   | OF_ListLocal
885   | OF_Add Bool {- True => replace existing info -}
886   | OF_Remove String | OF_Show String
887   | OF_Field String | OF_AutoGHCiLibs | OF_Force
888   | OF_DefinedName String String
889   | OF_GlobalConfig FilePath
890   deriving (Eq)
891
892 isAction :: OldFlag -> Bool
893 isAction OF_Config{}        = False
894 isAction OF_Field{}         = False
895 isAction OF_Input{}         = False
896 isAction OF_AutoGHCiLibs{}  = False
897 isAction OF_Force{}         = False
898 isAction OF_DefinedName{}   = False
899 isAction OF_GlobalConfig{}  = False
900 isAction _                  = True
901
902 oldFlags :: [OptDescr OldFlag]
903 oldFlags = [
904   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
905         "use the specified package config file",
906   Option ['l'] ["list-packages"] (NoArg OF_List)
907         "list packages in all config files",
908   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
909         "list packages in the specified config file",
910   Option ['a'] ["add-package"] (NoArg (OF_Add False))
911         "add a new package",
912   Option ['u'] ["update-package"] (NoArg (OF_Add True))
913         "update package with new configuration",
914   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
915         "read new package info from specified file",
916   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
917         "show the configuration for package NAME",
918   Option [] ["field"] (ReqArg OF_Field "FIELD")
919         "(with --show-package) Show field FIELD only",
920   Option [] ["force"] (NoArg OF_Force)
921         "ignore missing directories/libraries",
922   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
923         "remove an installed package",
924   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
925         "automatically build libs for GHCi (with -a)",
926   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
927         "define NAME as VALUE",
928   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
929         "location of the global package config"
930   ]
931  where
932   toDefined str =
933     case break (=='=') str of
934       (nm,[]) -> OF_DefinedName nm []
935       (nm,_:val) -> OF_DefinedName nm val
936
937 oldRunit :: [OldFlag] -> IO ()
938 oldRunit clis = do
939   let new_flags = [ f | Just f <- map conv clis ]
940
941       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
942       conv (OF_Config f)       = Just (FlagConfig f)
943       conv _                   = Nothing
944
945
946
947   let fields = [ f | OF_Field f <- clis ]
948
949   let auto_ghci_libs = any isAuto clis
950          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
951       input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
952
953       force = if OF_Force `elem` clis then ForceAll else NoForce
954
955       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
956
957   case [ c | c <- clis, isAction c ] of
958     [ OF_List ]      -> listPackages new_flags Nothing
959     [ OF_ListLocal ] -> listPackages new_flags Nothing
960     [ OF_Add upd ]   ->
961         registerPackage input_file defines new_flags auto_ghci_libs upd force
962     [ OF_Remove pkgid_str ]  -> do
963         pkgid <- readPkgId pkgid_str
964         unregisterPackage pkgid new_flags
965     [ OF_Show pkgid_str ]
966         | null fields -> do
967                 pkgid <- readPkgId pkgid_str
968                 describePackage new_flags pkgid
969         | otherwise   -> do
970                 pkgid <- readPkgId pkgid_str
971                 mapM_ (describeField new_flags pkgid) fields
972     _ -> do
973         prog <- getProgramName
974         die (usageInfo (usageHeader prog) flags)
975
976 my_head :: String -> [a] -> a
977 my_head s [] = error s
978 my_head s (x:xs) = x
979
980 -- ---------------------------------------------------------------------------
981 -- expanding environment variables in the package configuration
982
983 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
984 expandEnvVars str defines force = go str ""
985  where
986    go "" acc = return $! reverse acc
987    go ('$':'{':str) acc | (var, '}':rest) <- break close str
988         = do value <- lookupEnvVar var
989              go rest (reverse value ++ acc)
990         where close c = c == '}' || c == '\n' -- don't span newlines
991    go (c:str) acc
992         = go str (c:acc)
993
994    lookupEnvVar :: String -> IO String
995    lookupEnvVar nm =
996      case lookup nm defines of
997        Just x | not (null x) -> return x
998        _      ->
999         catch (System.getEnv nm)
1000            (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1001                                         show nm)
1002                       return "")
1003
1004 -----------------------------------------------------------------------------
1005
1006 getProgramName :: IO String
1007 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1008    where str `withoutSuffix` suff
1009             | suff `isSuffixOf` str = take (length str - length suff) str
1010             | otherwise             = str
1011
1012 bye :: String -> IO a
1013 bye s = putStr s >> exitWith ExitSuccess
1014
1015 die :: String -> IO a
1016 die s = do
1017   hFlush stdout
1018   prog <- getProgramName
1019   hPutStrLn stderr (prog ++ ": " ++ s)
1020   exitWith (ExitFailure 1)
1021
1022 dieOrForceAll :: Force -> String -> IO ()
1023 dieOrForceAll ForceAll s = ignoreError s
1024 dieOrForceAll _other s   = dieForcible s
1025
1026 dieOrForceFile :: Force -> String -> IO ()
1027 dieOrForceFile ForceAll   s = ignoreError s
1028 dieOrForceFile ForceFiles s = ignoreError s
1029 dieOrForceFile _other     s = dieForcible s
1030
1031 ignoreError :: String -> IO ()
1032 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1033
1034 dieForcible :: String -> IO ()
1035 dieForcible s = die (s ++ " (use --force to override)")
1036
1037 -----------------------------------------
1038 -- Cut and pasted from ghc/compiler/SysTools
1039
1040 #if defined(mingw32_HOST_OS)
1041 subst :: Char -> Char -> String -> String
1042 subst a b ls = map (\ x -> if x == a then b else x) ls
1043
1044 unDosifyPath :: FilePath -> FilePath
1045 unDosifyPath xs = subst '\\' '/' xs
1046
1047 getExecDir :: String -> IO (Maybe String)
1048 -- (getExecDir cmd) returns the directory in which the current
1049 --                  executable, which should be called 'cmd', is running
1050 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1051 -- you'll get "/a/b/c" back as the result
1052 getExecDir cmd
1053   = allocaArray len $ \buf -> do
1054         ret <- getModuleFileName nullPtr buf len
1055         if ret == 0 then return Nothing
1056                     else do s <- peekCString buf
1057                             return (Just (reverse (drop (length cmd)
1058                                                         (reverse (unDosifyPath s)))))
1059   where
1060     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1061
1062 foreign import stdcall unsafe  "GetModuleFileNameA"
1063   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1064 #else
1065 getExecDir :: String -> IO (Maybe String)
1066 getExecDir _ = return Nothing
1067 #endif