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