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