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