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