add --no-user-package-conf
[ghc-hetmet.git] / utils / ghc-pkg / Main.hs
1 {-# OPTIONS -fglasgow-exts -cpp #-}
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 hiding (depends)
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils
22 import Distribution.Package
23 import Distribution.Text
24 import Distribution.Version
25 import System.FilePath
26 import System.Cmd       ( rawSystem )
27 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
28
29 import Prelude
30
31 #include "../../includes/ghcconfig.h"
32
33 import System.Console.GetOpt
34 import Text.PrettyPrint
35 import qualified Control.Exception as Exception
36 import Data.Maybe
37
38 import Data.Char ( isSpace, toLower )
39 import Control.Monad
40 import System.Directory ( doesDirectoryExist, getDirectoryContents,
41                           doesFileExist, renameFile, removeFile )
42 import System.Exit ( exitWith, ExitCode(..) )
43 import System.Environment ( getArgs, getProgName, getEnv )
44 import System.IO
45 import System.IO.Error (try)
46 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy, nub,
47                    unfoldr, break, partition )
48 #if __GLASGOW_HASKELL__ > 604
49 import Data.List ( isInfixOf )
50 #else
51 import Data.List ( tails )
52 #endif
53 import Control.Concurrent
54
55 #ifdef mingw32_HOST_OS
56 import Foreign
57 import Foreign.C.String
58 import GHC.ConsoleHandler
59 #else
60 import System.Posix
61 #endif
62
63 import IO ( isPermissionError, isDoesNotExistError )
64
65 #if defined(GLOB)
66 import System.Process(runInteractiveCommand)
67 import qualified System.Info(os)
68 #endif
69
70 -- -----------------------------------------------------------------------------
71 -- Entry point
72
73 main :: IO ()
74 main = do
75   args <- getArgs
76
77   case getOpt Permute (flags ++ deprecFlags) args of
78         (cli,_,[]) | FlagHelp `elem` cli -> do
79            prog <- getProgramName
80            bye (usageInfo (usageHeader prog) flags)
81         (cli,_,[]) | FlagVersion `elem` cli ->
82            bye ourCopyright
83         (cli,nonopts,[]) ->
84            runit cli nonopts
85         (_,_,errors) -> do
86            prog <- getProgramName
87            die (concat errors ++ usageInfo (usageHeader prog) flags)
88
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
91
92 data Flag
93   = FlagUser
94   | FlagGlobal
95   | FlagHelp
96   | FlagVersion
97   | FlagConfig FilePath
98   | FlagGlobalConfig FilePath
99   | FlagForce
100   | FlagForceFiles
101   | FlagAutoGHCiLibs
102   | FlagSimpleOutput
103   | FlagNamesOnly
104   | FlagIgnoreCase
105   | FlagNoUserDb
106   deriving Eq
107
108 flags :: [OptDescr Flag]
109 flags = [
110   Option [] ["user"] (NoArg FlagUser)
111         "use the current user's package database",
112   Option [] ["global"] (NoArg FlagGlobal)
113         "use the global package database",
114   Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
115         "use the specified package config file",
116   Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
117         "location of the global package config",
118   Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
119         "never read the user package database",
120   Option [] ["force"] (NoArg FlagForce)
121          "ignore missing dependencies, directories, and libraries",
122   Option [] ["force-files"] (NoArg FlagForceFiles)
123          "ignore missing directories and libraries only",
124   Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
125         "automatically build libs for GHCi (with register)",
126   Option ['?'] ["help"] (NoArg FlagHelp)
127         "display this help and exit",
128   Option ['V'] ["version"] (NoArg FlagVersion)
129         "output version information and exit",
130   Option [] ["simple-output"] (NoArg FlagSimpleOutput)
131         "print output in easy-to-parse format for some commands",
132   Option [] ["names-only"] (NoArg FlagNamesOnly)
133         "only print package names, not versions; can only be used with list --simple-output",
134   Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
135         "ignore case for substring matching"
136   ]
137
138 deprecFlags :: [OptDescr Flag]
139 deprecFlags = [
140         -- put deprecated flags here
141   ]
142
143 ourCopyright :: String
144 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
145
146 usageHeader :: String -> String
147 usageHeader prog = substProg prog $
148   "Usage:\n" ++
149   "  $p register {filename | -}\n" ++
150   "    Register the package using the specified installed package\n" ++
151   "    description. The syntax for the latter is given in the $p\n" ++
152   "    documentation.\n" ++
153   "\n" ++
154   "  $p update {filename | -}\n" ++
155   "    Register the package, overwriting any other package with the\n" ++
156   "    same name.\n" ++
157   "\n" ++
158   "  $p unregister {pkg-id}\n" ++
159   "    Unregister the specified package.\n" ++
160   "\n" ++
161   "  $p expose {pkg-id}\n" ++
162   "    Expose the specified package.\n" ++
163   "\n" ++
164   "  $p hide {pkg-id}\n" ++
165   "    Hide the specified package.\n" ++
166   "\n" ++
167   "  $p list [pkg]\n" ++
168   "    List registered packages in the global database, and also the\n" ++
169   "    user database if --user is given. If a package name is given\n" ++
170   "    all the registered versions will be listed in ascending order.\n" ++
171   "    Accepts the --simple-output flag.\n" ++
172   "\n" ++
173   "  $p find-module {module}\n" ++
174   "    List registered packages exposing module {module} in the global\n" ++
175   "    database, and also the user database if --user is given.\n" ++
176   "    All the registered versions will be listed in ascending order.\n" ++
177   "    Accepts the --simple-output flag.\n" ++
178   "\n" ++
179   "  $p latest {pkg-id}\n" ++
180   "    Prints the highest registered version of a package.\n" ++
181   "\n" ++
182   "  $p check\n" ++
183   "    Check the consistency of package depenencies and list broken packages.\n" ++
184   "    Accepts the --simple-output flag.\n" ++
185   "\n" ++
186   "  $p describe {pkg}\n" ++
187   "    Give the registered description for the specified package. The\n" ++
188   "    description is returned in precisely the syntax required by $p\n" ++
189   "    register.\n" ++
190   "\n" ++
191   "  $p field {pkg} {field}\n" ++
192   "    Extract the specified field of the package description for the\n" ++
193   "    specified package. Accepts comma-separated multiple fields.\n" ++
194   "\n" ++
195   "  $p dump\n" ++
196   "    Dump the registered description for every package.  This is like\n" ++
197   "    \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
198   "    by tools that parse the results, rather than humans.\n" ++
199   "\n" ++
200   " Substring matching is supported for {module} in find-module and\n" ++
201   " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
202   " open substring ends (prefix*, *suffix, *infix*).\n" ++
203   "\n" ++
204   "  When asked to modify a database (register, unregister, update,\n"++
205   "  hide, expose, and also check), ghc-pkg modifies the global database by\n"++
206   "  default.  Specifying --user causes it to act on the user database,\n"++
207   "  or --package-conf can be used to act on another database\n"++
208   "  entirely. When multiple of these options are given, the rightmost\n"++
209   "  one is used as the database to act upon.\n"++
210   "\n"++
211   "  Commands that query the package database (list, latest, describe,\n"++
212   "  field) operate on the list of databases specified by the flags\n"++
213   "  --user, --global, and --package-conf.  If none of these flags are\n"++
214   "  given, the default is --global --user.\n"++
215   "\n" ++
216   " The following optional flags are also accepted:\n"
217
218 substProg :: String -> String -> String
219 substProg _ [] = []
220 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
221 substProg prog (c:xs) = c : substProg prog xs
222
223 -- -----------------------------------------------------------------------------
224 -- Do the business
225
226 data Force = ForceAll | ForceFiles | NoForce
227
228 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
229
230 runit :: [Flag] -> [String] -> IO ()
231 runit cli nonopts = do
232   installSignalHandlers -- catch ^C and clean up
233   prog <- getProgramName
234   let
235         force
236           | FlagForce `elem` cli        = ForceAll
237           | FlagForceFiles `elem` cli   = ForceFiles
238           | otherwise                   = NoForce
239         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
240         splitFields fields = unfoldr splitComma (',':fields)
241           where splitComma "" = Nothing
242                 splitComma fs = Just $ break (==',') (tail fs)
243
244         substringCheck :: String -> Maybe (String -> Bool)
245         substringCheck ""    = Nothing
246         substringCheck "*"   = Just (const True)
247         substringCheck [_]   = Nothing
248         substringCheck (h:t) =
249           case (h, init t, last t) of
250             ('*',s,'*') -> Just (isInfixOf (f s) . f)
251             ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
252             ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
253             _           -> Nothing
254           where f | FlagIgnoreCase `elem` cli = map toLower
255                   | otherwise                 = id
256 #if defined(GLOB)
257         glob x | System.Info.os=="mingw32" = do
258           -- glob echoes its argument, after win32 filename globbing
259           (_,o,_,_) <- runInteractiveCommand ("glob "++x)
260           txt <- hGetContents o
261           return (read txt)
262         glob x | otherwise = return [x]
263 #endif
264   --
265   -- first, parse the command
266   case nonopts of
267 #if defined(GLOB)
268     -- dummy command to demonstrate usage and permit testing
269     -- without messing things up; use glob to selectively enable
270     -- windows filename globbing for file parameters
271     -- register, update, FlagGlobalConfig, FlagConfig; others?
272     ["glob", filename] -> do
273         print filename
274         glob filename >>= print
275 #endif
276     ["register", filename] ->
277         registerPackage filename cli auto_ghci_libs False force
278     ["update", filename] ->
279         registerPackage filename cli auto_ghci_libs True force
280     ["unregister", pkgid_str] -> do
281         pkgid <- readGlobPkgId pkgid_str
282         unregisterPackage pkgid cli force
283     ["expose", pkgid_str] -> do
284         pkgid <- readGlobPkgId pkgid_str
285         exposePackage pkgid cli force
286     ["hide",   pkgid_str] -> do
287         pkgid <- readGlobPkgId pkgid_str
288         hidePackage pkgid cli force
289     ["list"] -> do
290         listPackages cli Nothing Nothing
291     ["list", pkgid_str] ->
292         case substringCheck pkgid_str of
293           Nothing -> do pkgid <- readGlobPkgId pkgid_str
294                         listPackages cli (Just (Id pkgid)) Nothing
295           Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
296     ["find-module", moduleName] -> do
297         let match = maybe (==moduleName) id (substringCheck moduleName)
298         listPackages cli Nothing (Just match)
299     ["latest", pkgid_str] -> do
300         pkgid <- readGlobPkgId pkgid_str
301         latestPackage cli pkgid
302     ["describe", pkgid_str] ->
303         case substringCheck pkgid_str of
304           Nothing -> do pkgid <- readGlobPkgId pkgid_str
305                         describePackage cli (Id pkgid)
306           Just m -> describePackage cli (Substring pkgid_str m)
307     ["field", pkgid_str, fields] ->
308         case substringCheck pkgid_str of
309           Nothing -> do pkgid <- readGlobPkgId pkgid_str
310                         describeField cli (Id pkgid) (splitFields fields)
311           Just m -> describeField cli (Substring pkgid_str m)
312                                       (splitFields fields)
313     ["check"] -> do
314         checkConsistency cli
315
316     ["dump"] -> do
317         dumpPackages cli
318
319     [] -> do
320         die ("missing command\n" ++
321                 usageInfo (usageHeader prog) flags)
322     (_cmd:_) -> do
323         die ("command-line syntax error\n" ++
324                 usageInfo (usageHeader prog) flags)
325
326 parseCheck :: ReadP a a -> String -> String -> IO a
327 parseCheck parser str what =
328   case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
329     [x] -> return x
330     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
331
332 readGlobPkgId :: String -> IO PackageIdentifier
333 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
334
335 parseGlobPackageId :: ReadP r PackageIdentifier
336 parseGlobPackageId =
337   parse
338      +++
339   (do n <- parse
340       string "-*"
341       return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
342
343 -- globVersion means "all versions"
344 globVersion :: Version
345 globVersion = Version{ versionBranch=[], versionTags=["*"] }
346
347 -- -----------------------------------------------------------------------------
348 -- Package databases
349
350 -- Some commands operate on a single database:
351 --      register, unregister, expose, hide
352 -- however these commands also check the union of the available databases
353 -- in order to check consistency.  For example, register will check that
354 -- dependencies exist before registering a package.
355 --
356 -- Some commands operate  on multiple databases, with overlapping semantics:
357 --      list, describe, field
358
359 type PackageDBName  = FilePath
360 type PackageDB      = [InstalledPackageInfo]
361
362 type PackageDBStack = [(PackageDBName,PackageDB)]
363         -- A stack of package databases.  Convention: head is the topmost
364         -- in the stack.  Earlier entries override later one.
365
366 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
367 allPackagesInStack = concatMap snd
368
369 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
370 getPkgDatabases modify my_flags = do
371   -- first we determine the location of the global package config.  On Windows,
372   -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
373   -- location is passed to the binary using the --global-config flag by the
374   -- wrapper script.
375   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
376   global_conf <-
377      case [ f | FlagGlobalConfig f <- my_flags ] of
378         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
379                  case mb_dir of
380                         Nothing  -> die err_msg
381                         Just dir ->
382                             do let path1 = dir </> "package.conf"
383                                    path2 = dir </> ".." </> ".." </> ".."
384                                                </> "inplace-datadir"
385                                                </> "package.conf"
386                                exists1 <- doesFileExist path1
387                                exists2 <- doesFileExist path2
388                                if exists1 then return path1
389                                    else if exists2 then return path2
390                                    else die "Can't find package.conf"
391         fs -> return (last fs)
392
393   let global_conf_dir = global_conf ++ ".d"
394   global_conf_dir_exists <- doesDirectoryExist global_conf_dir
395   global_confs <-
396     if global_conf_dir_exists
397       then do files <- getDirectoryContents global_conf_dir
398               return [ global_conf_dir ++ '/' : file
399                      | file <- files
400                      , isSuffixOf ".conf" file]
401       else return []
402
403   let no_user_db = FlagNoUserDb `elem` my_flags
404
405   -- get the location of the user package database, and create it if necessary
406   -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
407   appdir <- try $ getAppUserDataDirectory "ghc"
408
409   mb_user_conf <-
410      if no_user_db then return Nothing else
411      case appdir of
412        Right dir -> do
413                let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
414                    user_conf = dir </> subdir </> "package.conf"
415                user_exists <- doesFileExist user_conf
416                return (Just (user_conf,user_exists))
417        Left ex ->
418                return Nothing
419
420   -- If the user database doesn't exist, and this command isn't a
421   -- "modify" command, then we won't attempt to create or use it.
422   let sys_databases
423         | Just (user_conf,user_exists) <- mb_user_conf,
424           modify || user_exists = user_conf : global_confs ++ [global_conf]
425         | otherwise             = global_confs ++ [global_conf]
426
427   e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
428   let env_stack =
429         case e_pkg_path of
430                 Left  _ -> sys_databases
431                 Right path
432                   | last cs == ""  -> init cs ++ sys_databases
433                   | otherwise      -> cs
434                   where cs = splitSearchPath path
435
436         -- The "global" database is always the one at the bottom of the stack.
437         -- This is the database we modify by default.
438       virt_global_conf = last env_stack
439
440   let db_flags = [ f | Just f <- map is_db_flag my_flags ]
441          where is_db_flag FlagUser
442                       | Just (user_conf,user_exists) <- mb_user_conf 
443                       = Just user_conf
444                is_db_flag FlagGlobal     = Just virt_global_conf
445                is_db_flag (FlagConfig f) = Just f
446                is_db_flag _              = Nothing
447
448   final_stack <-
449      if not modify
450         then    -- For a "read" command, we use all the databases
451                 -- specified on the command line.  If there are no
452                 -- command-line flags specifying databases, the default
453                 -- is to use all the ones we know about.
454              if null db_flags then return env_stack 
455                               else return (reverse (nub db_flags))
456         else let
457                 -- For a "modify" command, treat all the databases as
458                 -- a stack, where we are modifying the top one, but it
459                 -- can refer to packages in databases further down the
460                 -- stack.
461
462                 -- -f flags on the command line add to the database
463                 -- stack, unless any of them are present in the stack
464                 -- already.
465                 flag_stack = filter (`notElem` env_stack)
466                                 [ f | FlagConfig f <- reverse my_flags ]
467                                 ++ env_stack
468
469                 modifying f
470                   | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
471                   | otherwise           = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
472              in
473                 if null db_flags 
474                    then modifying virt_global_conf
475                    else modifying (head db_flags)
476
477   db_stack <- mapM readParseDatabase final_stack
478   return db_stack
479
480 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
481 readParseDatabase filename = do
482   str <- readFile filename `catchIO` \_ -> return emptyPackageConfig
483   let packages = map convertPackageInfoIn $ read str
484   Exception.evaluate packages
485     `catchError` \e->
486         die ("error while parsing " ++ filename ++ ": " ++ show e)
487   return (filename,packages)
488
489 emptyPackageConfig :: String
490 emptyPackageConfig = "[]"
491
492 -- -----------------------------------------------------------------------------
493 -- Registering
494
495 registerPackage :: FilePath
496                 -> [Flag]
497                 -> Bool              -- auto_ghci_libs
498                 -> Bool              -- update
499                 -> Force
500                 -> IO ()
501 registerPackage input my_flags auto_ghci_libs update force = do
502   db_stack <- getPkgDatabases True my_flags
503   let
504         db_to_operate_on = my_head "db" db_stack
505         db_filename      = fst db_to_operate_on
506   --
507
508   s <-
509     case input of
510       "-" -> do
511         putStr "Reading package info from stdin ... "
512         getContents
513       f   -> do
514         putStr ("Reading package info from " ++ show f ++ " ... ")
515         readFile f
516
517   expanded <- expandEnvVars s force
518
519   pkg <- parsePackageInfo expanded
520   putStrLn "done."
521
522   validatePackageConfig pkg db_stack auto_ghci_libs update force
523   let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
524       not_this p = package p /= package pkg
525   writeNewConfig db_filename new_details
526
527 parsePackageInfo
528         :: String
529         -> IO InstalledPackageInfo
530 parsePackageInfo str =
531   case parseInstalledPackageInfo str of
532     ParseOk _warns ok -> return ok
533     ParseFailed err -> case locatedErrorMsg err of
534                            (Nothing, s) -> die s
535                            (Just l, s) -> die (show l ++ ": " ++ s)
536
537 -- -----------------------------------------------------------------------------
538 -- Exposing, Hiding, Unregistering are all similar
539
540 exposePackage :: PackageIdentifier ->  [Flag] -> Force -> IO ()
541 exposePackage = modifyPackage (\p -> [p{exposed=True}])
542
543 hidePackage :: PackageIdentifier ->  [Flag] -> Force -> IO ()
544 hidePackage = modifyPackage (\p -> [p{exposed=False}])
545
546 unregisterPackage :: PackageIdentifier ->  [Flag] -> Force -> IO ()
547 unregisterPackage = modifyPackage (\_ -> [])
548
549 modifyPackage
550   :: (InstalledPackageInfo -> [InstalledPackageInfo])
551   -> PackageIdentifier
552   -> [Flag]
553   -> Force
554   -> IO ()
555 modifyPackage fn pkgid my_flags force = do
556   db_stack <- getPkgDatabases True{-modify-} my_flags
557   let old_broken = brokenPackages (allPackagesInStack db_stack)
558   let ((db_name, pkgs) : rest_of_stack) = db_stack
559   ps <- findPackages [(db_name,pkgs)] (Id pkgid)
560   let pids = map package ps
561   let new_config = concat (map modify pkgs)
562       modify pkg
563           | package pkg `elem` pids = fn pkg
564           | otherwise               = [pkg]
565   let new_stack = (db_name,new_config) : rest_of_stack
566       new_broken = map package (brokenPackages (allPackagesInStack new_stack))
567       newly_broken = filter (`notElem` map package old_broken) new_broken
568
569   when (not (null newly_broken)) $
570       dieOrForceAll force ("unregistering " ++ display pkgid ++
571            " would break the following packages: "
572               ++ unwords (map display newly_broken))
573
574   writeNewConfig db_name new_config
575
576 -- -----------------------------------------------------------------------------
577 -- Listing packages
578
579 listPackages ::  [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
580 listPackages my_flags mPackageName mModuleName = do
581   let simple_output = FlagSimpleOutput `elem` my_flags
582   db_stack <- getPkgDatabases False my_flags
583   let db_stack_filtered -- if a package is given, filter out all other packages
584         | Just this <- mPackageName =
585             map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
586                 db_stack
587         | Just match <- mModuleName = -- packages which expose mModuleName
588             map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
589                 db_stack
590         | otherwise = db_stack
591
592       db_stack_sorted
593           = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
594           where sort_pkgs = sortBy cmpPkgIds
595                 cmpPkgIds pkg1 pkg2 =
596                    case pkgName p1 `compare` pkgName p2 of
597                         LT -> LT
598                         GT -> GT
599                         EQ -> pkgVersion p1 `compare` pkgVersion p2
600                    where (p1,p2) = (package pkg1, package pkg2)
601
602       match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
603
604       pkg_map = allPackagesInStack db_stack
605       show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
606
607   show_func (reverse db_stack_sorted)
608
609   where show_normal pkg_map (db_name,pkg_confs) =
610           hPutStrLn stdout (render $
611                 text db_name <> colon $$ nest 4 packages
612                 )
613            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
614                  broken = map package (brokenPackages pkg_map)
615                  pp_pkg p
616                    | package p `elem` broken = braces doc
617                    | exposed p = doc
618                    | otherwise = parens doc
619                    where doc = text (display (package p))
620
621         show_simple db_stack = do
622           let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
623                                                          else display
624               pkgs = map showPkg $ sortBy compPkgIdVer $
625                           map package (allPackagesInStack db_stack)
626           when (not (null pkgs)) $ 
627              hPutStrLn stdout $ concat $ intersperse " " pkgs
628
629 -- -----------------------------------------------------------------------------
630 -- Prints the highest (hidden or exposed) version of a package
631
632 latestPackage ::  [Flag] -> PackageIdentifier -> IO ()
633 latestPackage my_flags pkgid = do
634   db_stack <- getPkgDatabases False my_flags
635   ps <- findPackages db_stack (Id pkgid)
636   show_pkg (sortBy compPkgIdVer (map package ps))
637   where
638     show_pkg [] = die "no matches"
639     show_pkg pids = hPutStrLn stdout (display (last pids))
640
641 -- -----------------------------------------------------------------------------
642 -- Describe
643
644 describePackage :: [Flag] -> PackageArg -> IO ()
645 describePackage my_flags pkgarg = do
646   db_stack <- getPkgDatabases False my_flags
647   ps <- findPackages db_stack pkgarg
648   doDump ps
649
650 dumpPackages :: [Flag] -> IO ()
651 dumpPackages my_flags = do
652   db_stack <- getPkgDatabases False my_flags
653   doDump (allPackagesInStack db_stack)
654
655 doDump :: [InstalledPackageInfo] -> IO ()
656 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
657
658 -- PackageId is can have globVersion for the version
659 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
660 findPackages db_stack pkgarg
661   = case [ p | p <- all_pkgs, pkgarg `matchesPkg` p ] of
662         []  -> dieWith 2 ("cannot find package " ++ pkg_msg pkgarg)
663         ps -> return ps
664   where
665         all_pkgs = allPackagesInStack db_stack
666         pkg_msg (Id pkgid)           = display pkgid
667         pkg_msg (Substring pkgpat _) = "matching "++pkgpat
668
669 matches :: PackageIdentifier -> PackageIdentifier -> Bool
670 pid `matches` pid'
671   = (pkgName pid == pkgName pid')
672     && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
673
674 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
675 (Id pid)        `matchesPkg` pkg = pid `matches` package pkg
676 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
677
678 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
679 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
680
681 -- -----------------------------------------------------------------------------
682 -- Field
683
684 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
685 describeField my_flags pkgarg fields = do
686   db_stack <- getPkgDatabases False my_flags
687   fns <- toFields fields
688   ps <- findPackages db_stack pkgarg
689   let top_dir = takeDirectory (fst (last db_stack))
690   mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
691   where toFields [] = return []
692         toFields (f:fs) = case toField f of
693             Nothing -> die ("unknown field: " ++ f)
694             Just fn -> do fns <- toFields fs
695                           return (fn:fns)
696         selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
697
698 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
699 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
700 -- with the current topdir (obtained from the -B option).
701 mungePackagePaths top_dir ps = map munge_pkg ps
702   where
703   munge_pkg p = p{ importDirs        = munge_paths (importDirs p),
704                    includeDirs       = munge_paths (includeDirs p),
705                    libraryDirs       = munge_paths (libraryDirs p),
706                    frameworkDirs     = munge_paths (frameworkDirs p),
707                    haddockInterfaces = munge_paths (haddockInterfaces p),
708                    haddockHTMLs      = munge_paths (haddockHTMLs p)
709                  }
710
711   munge_paths = map munge_path
712
713   munge_path p
714    | Just p' <- maybePrefixMatch "$topdir"     p =            top_dir ++ p'
715    | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
716    | otherwise                               = p
717
718   toHttpPath p = "file:///" ++ p
719
720 maybePrefixMatch :: String -> String -> Maybe String
721 maybePrefixMatch []    rest = Just rest
722 maybePrefixMatch (_:_) []   = Nothing
723 maybePrefixMatch (p:pat) (r:rest)
724   | p == r    = maybePrefixMatch pat rest
725   | otherwise = Nothing
726
727 toField :: String -> Maybe (InstalledPackageInfo -> String)
728 -- backwards compatibility:
729 toField "import_dirs"     = Just $ strList . importDirs
730 toField "source_dirs"     = Just $ strList . importDirs
731 toField "library_dirs"    = Just $ strList . libraryDirs
732 toField "hs_libraries"    = Just $ strList . hsLibraries
733 toField "extra_libraries" = Just $ strList . extraLibraries
734 toField "include_dirs"    = Just $ strList . includeDirs
735 toField "c_includes"      = Just $ strList . includes
736 toField "package_deps"    = Just $ strList . map display. depends
737 toField "extra_cc_opts"   = Just $ strList . ccOptions
738 toField "extra_ld_opts"   = Just $ strList . ldOptions
739 toField "framework_dirs"  = Just $ strList . frameworkDirs
740 toField "extra_frameworks"= Just $ strList . frameworks
741 toField s                 = showInstalledPackageInfoField s
742
743 strList :: [String] -> String
744 strList = show
745
746
747 -- -----------------------------------------------------------------------------
748 -- Check: Check consistency of installed packages
749
750 checkConsistency :: [Flag] -> IO ()
751 checkConsistency my_flags = do
752   db_stack <- getPkgDatabases True my_flags
753          -- check behaves like modify for the purposes of deciding which
754          -- databases to use, because ordering is important.
755   let pkgs = allPackagesInStack db_stack
756       broken_pkgs = brokenPackages pkgs
757       broken_ids = map package broken_pkgs
758       broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
759                    | p <- broken_pkgs ]
760   mapM_ (putStrLn . render . show_func) broken_why
761   where
762   show_func | FlagSimpleOutput `elem` my_flags = show_simple
763             | otherwise = show_normal
764   show_simple (pid,deps) =
765     text (display pid) <> colon
766       <+> fsep (punctuate comma (map (text . display) deps))
767   show_normal (pid,deps) =
768     text "package" <+> text (display pid) <+> text "has missing dependencies:"
769       $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
770
771
772 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
773 brokenPackages pkgs = go [] pkgs
774  where
775    go avail not_avail =
776      case partition (depsAvailable avail) not_avail of
777         ([],        not_avail) -> not_avail
778         (new_avail, not_avail) -> go (new_avail ++ avail) not_avail
779
780    depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
781                  -> Bool
782    depsAvailable pkgs_ok pkg = null dangling
783         where dangling = filter (`notElem` pids) (depends pkg)
784               pids = map package pkgs_ok
785
786         -- we want mutually recursive groups of package to show up
787         -- as broken. (#1750)
788
789 -- -----------------------------------------------------------------------------
790 -- Manipulating package.conf files
791
792 type InstalledPackageInfoString = InstalledPackageInfo_ String
793
794 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
795 convertPackageInfoOut
796     (pkgconf@(InstalledPackageInfo { exposedModules = e,
797                                      hiddenModules = h })) =
798         pkgconf{ exposedModules = map display e,
799                  hiddenModules  = map display h }
800
801 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
802 convertPackageInfoIn
803     (pkgconf@(InstalledPackageInfo { exposedModules = e,
804                                      hiddenModules = h })) =
805         pkgconf{ exposedModules = map convert e,
806                  hiddenModules  = map convert h }
807     where convert = fromJust . simpleParse
808
809 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
810 writeNewConfig filename packages = do
811   hPutStr stdout "Writing new package config file... "
812   createDirectoryIfMissing True $ takeDirectory filename
813   let shown = concat $ intersperse ",\n "
814                      $ map (show . convertPackageInfoOut) packages
815       fileContents = "[" ++ shown ++ "\n]"
816   writeFileAtomic filename fileContents
817     `catch` \e ->
818       if isPermissionError e
819       then die (filename ++ ": you don't have permission to modify this file")
820       else ioError e
821   hPutStrLn stdout "done."
822
823 -----------------------------------------------------------------------------
824 -- Sanity-check a new package config, and automatically build GHCi libs
825 -- if requested.
826
827 validatePackageConfig :: InstalledPackageInfo
828                       -> PackageDBStack
829                       -> Bool   -- auto-ghc-libs
830                       -> Bool   -- update
831                       -> Force
832                       -> IO ()
833 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
834   checkPackageId pkg
835   checkDuplicates db_stack pkg update force
836   mapM_ (checkDep db_stack force) (depends pkg)
837   mapM_ (checkDir force) (importDirs pkg)
838   mapM_ (checkDir force) (libraryDirs pkg)
839   mapM_ (checkDir force) (includeDirs pkg)
840   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
841   -- ToDo: check these somehow?
842   --    extra_libraries :: [String],
843   --    c_includes      :: [String],
844
845 -- When the package name and version are put together, sometimes we can
846 -- end up with a package id that cannot be parsed.  This will lead to
847 -- difficulties when the user wants to refer to the package later, so
848 -- we check that the package id can be parsed properly here.
849 checkPackageId :: InstalledPackageInfo -> IO ()
850 checkPackageId ipi =
851   let str = display (package ipi) in
852   case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
853     [_] -> return ()
854     []  -> die ("invalid package identifier: " ++ str)
855     _   -> die ("ambiguous package identifier: " ++ str)
856
857 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
858 checkDuplicates db_stack pkg update force = do
859   let
860         pkgid = package pkg
861         (_top_db_name, pkgs) : _  = db_stack
862   --
863   -- Check whether this package id already exists in this DB
864   --
865   when (not update && (pkgid `elem` map package pkgs)) $
866        die ("package " ++ display pkgid ++ " is already installed")
867
868   let
869         uncasep = map toLower . display
870         dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
871
872   when (not update && not (null dups)) $ dieOrForceAll force $
873         "Package names may be treated case-insensitively in the future.\n"++
874         "Package " ++ display pkgid ++
875         " overlaps with: " ++ unwords (map display dups)
876
877
878 checkDir :: Force -> String -> IO ()
879 checkDir force d
880  | "$topdir"     `isPrefixOf` d = return ()
881  | "$httptopdir" `isPrefixOf` d = return ()
882         -- can't check these, because we don't know what $(http)topdir is
883  | otherwise = do
884    there <- doesDirectoryExist d
885    when (not there)
886        (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
887
888 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
889 checkDep db_stack force pkgid
890   | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
891   | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
892                                         ++ " doesn't exist")
893   where
894         -- for backwards compat, we treat 0.0 as a special version,
895         -- and don't check that it actually exists.
896         real_version = realVersion pkgid
897
898         name_exists = any (\p -> pkgName (package p) == name) all_pkgs
899         name = pkgName pkgid
900
901         all_pkgs = allPackagesInStack db_stack
902         pkgids = map package all_pkgs
903
904 realVersion :: PackageIdentifier -> Bool
905 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
906
907 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
908 checkHSLib dirs auto_ghci_libs force lib = do
909   let batch_lib_file = "lib" ++ lib ++ ".a"
910   bs <- mapM (doesLibExistIn batch_lib_file) dirs
911   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
912         [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
913                                     " on library path")
914         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
915
916 doesLibExistIn :: String -> String -> IO Bool
917 doesLibExistIn lib d
918  | "$topdir"     `isPrefixOf` d = return True
919  | "$httptopdir" `isPrefixOf` d = return True
920  | otherwise                = doesFileExist (d ++ '/':lib)
921
922 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
923 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
924   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
925   | otherwise  = do
926       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
927       case [dir | (exists,dir) <- zip bs dirs, exists] of
928         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
929         (_:_) -> return ()
930   where
931     ghci_lib_file = lib ++ ".o"
932
933 -- automatically build the GHCi version of a batch lib,
934 -- using ld --whole-archive.
935
936 autoBuildGHCiLib :: String -> String -> String -> IO ()
937 autoBuildGHCiLib dir batch_file ghci_file = do
938   let ghci_lib_file  = dir ++ '/':ghci_file
939       batch_lib_file = dir ++ '/':batch_file
940   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
941 #if defined(darwin_HOST_OS)
942   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
943 #elif defined(mingw32_HOST_OS)
944   execDir <- getExecDir "/bin/ghc-pkg.exe"
945   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
946 #else
947   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
948 #endif
949   when (r /= ExitSuccess) $ exitWith r
950   hPutStrLn stderr (" done.")
951
952 -- -----------------------------------------------------------------------------
953 -- Searching for modules
954
955 #if not_yet
956
957 findModules :: [FilePath] -> IO [String]
958 findModules paths =
959   mms <- mapM searchDir paths
960   return (concat mms)
961
962 searchDir path prefix = do
963   fs <- getDirectoryEntries path `catch` \_ -> return []
964   searchEntries path prefix fs
965
966 searchEntries path prefix [] = return []
967 searchEntries path prefix (f:fs)
968   | looks_like_a_module  =  do
969         ms <- searchEntries path prefix fs
970         return (prefix `joinModule` f : ms)
971   | looks_like_a_component  =  do
972         ms <- searchDir (path </> f) (prefix `joinModule` f)
973         ms' <- searchEntries path prefix fs
974         return (ms ++ ms')
975   | otherwise
976         searchEntries path prefix fs
977
978   where
979         (base,suffix) = splitFileExt f
980         looks_like_a_module =
981                 suffix `elem` haskell_suffixes &&
982                 all okInModuleName base
983         looks_like_a_component =
984                 null suffix && all okInModuleName base
985
986 okInModuleName c
987
988 #endif
989
990 -- ---------------------------------------------------------------------------
991 -- expanding environment variables in the package configuration
992
993 expandEnvVars :: String -> Force -> IO String
994 expandEnvVars str0 force = go str0 ""
995  where
996    go "" acc = return $! reverse acc
997    go ('$':'{':str) acc | (var, '}':rest) <- break close str
998         = do value <- lookupEnvVar var
999              go rest (reverse value ++ acc)
1000         where close c = c == '}' || c == '\n' -- don't span newlines
1001    go (c:str) acc
1002         = go str (c:acc)
1003
1004    lookupEnvVar :: String -> IO String
1005    lookupEnvVar nm =
1006         catch (System.Environment.getEnv nm)
1007            (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1008                                         show nm)
1009                       return "")
1010
1011 -----------------------------------------------------------------------------
1012
1013 getProgramName :: IO String
1014 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1015    where str `withoutSuffix` suff
1016             | suff `isSuffixOf` str = take (length str - length suff) str
1017             | otherwise             = str
1018
1019 bye :: String -> IO a
1020 bye s = putStr s >> exitWith ExitSuccess
1021
1022 die :: String -> IO a
1023 die = dieWith 1
1024
1025 dieWith :: Int -> String -> IO a
1026 dieWith ec s = do
1027   hFlush stdout
1028   prog <- getProgramName
1029   hPutStrLn stderr (prog ++ ": " ++ s)
1030   exitWith (ExitFailure ec)
1031
1032 dieOrForceAll :: Force -> String -> IO ()
1033 dieOrForceAll ForceAll s = ignoreError s
1034 dieOrForceAll _other s   = dieForcible s
1035
1036 dieOrForceFile :: Force -> String -> IO ()
1037 dieOrForceFile ForceAll   s = ignoreError s
1038 dieOrForceFile ForceFiles s = ignoreError s
1039 dieOrForceFile _other     s = dieForcible s
1040
1041 ignoreError :: String -> IO ()
1042 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1043
1044 dieForcible :: String -> IO ()
1045 dieForcible s = die (s ++ " (use --force to override)")
1046
1047 my_head :: String -> [a] -> a
1048 my_head s []      = error s
1049 my_head _ (x : _) = x
1050
1051 -----------------------------------------
1052 -- Cut and pasted from ghc/compiler/main/SysTools
1053
1054 #if defined(mingw32_HOST_OS)
1055 subst :: Char -> Char -> String -> String
1056 subst a b ls = map (\ x -> if x == a then b else x) ls
1057
1058 unDosifyPath :: FilePath -> FilePath
1059 unDosifyPath xs = subst '\\' '/' xs
1060
1061 getExecDir :: String -> IO (Maybe String)
1062 -- (getExecDir cmd) returns the directory in which the current
1063 --                  executable, which should be called 'cmd', is running
1064 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1065 -- you'll get "/a/b/c" back as the result
1066 getExecDir cmd
1067   = allocaArray len $ \buf -> do
1068         ret <- getModuleFileName nullPtr buf len
1069         if ret == 0 then return Nothing
1070                     else do s <- peekCString buf
1071                             return (Just (reverse (drop (length cmd)
1072                                                         (reverse (unDosifyPath s)))))
1073   where
1074     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1075
1076 foreign import stdcall unsafe  "GetModuleFileNameA"
1077   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1078 #else
1079 getExecDir :: String -> IO (Maybe String)
1080 getExecDir _ = return Nothing
1081 #endif
1082
1083 -----------------------------------------
1084 -- Adapted from ghc/compiler/utils/Panic
1085
1086 installSignalHandlers :: IO ()
1087 installSignalHandlers = do
1088   threadid <- myThreadId
1089   let
1090       interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1091   --
1092 #if !defined(mingw32_HOST_OS)
1093   installHandler sigQUIT (Catch interrupt) Nothing 
1094   installHandler sigINT  (Catch interrupt) Nothing
1095   return ()
1096 #elif __GLASGOW_HASKELL__ >= 603
1097   -- GHC 6.3+ has support for console events on Windows
1098   -- NOTE: running GHCi under a bash shell for some reason requires
1099   -- you to press Ctrl-Break rather than Ctrl-C to provoke
1100   -- an interrupt.  Ctrl-C is getting blocked somewhere, I don't know
1101   -- why --SDM 17/12/2004
1102   let sig_handler ControlC = interrupt
1103       sig_handler Break    = interrupt
1104       sig_handler _        = return ()
1105
1106   installHandler (Catch sig_handler)
1107   return ()
1108 #else
1109   return () -- nothing
1110 #endif
1111
1112 #if __GLASGOW_HASKELL__ <= 604
1113 isInfixOf               :: (Eq a) => [a] -> [a] -> Bool
1114 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1115 #endif
1116
1117 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1118 #if __GLASGOW_HASKELL__ >= 609
1119 catchIO = Exception.catch
1120 #else
1121 catchIO io handler = io `Exception.catch` handler'
1122     where handler' (Exception.IOException ioe) = handler ioe
1123           handler' e                           = Exception.throw e
1124 #endif
1125
1126 throwIOIO :: Exception.IOException -> IO a
1127 #if __GLASGOW_HASKELL__ >= 609
1128 throwIOIO = Exception.throwIO
1129 #else
1130 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1131 #endif
1132
1133 catchError :: IO a -> (String -> IO a) -> IO a
1134 #if __GLASGOW_HASKELL__ >= 609
1135 catchError io handler = io `Exception.catch` handler'
1136     where handler' (Exception.ErrorCall err) = handler err
1137 #else
1138 catchError io handler = io `Exception.catch` handler'
1139     where handler' (Exception.ErrorCall err) = handler err
1140           handler' e                         = Exception.throw e
1141 #endif
1142
1143 onException :: IO a -> IO () -> IO a
1144 #if __GLASGOW_HASKELL__ >= 609
1145 onException = Exception.onException
1146 #else
1147 onException io what = io `Exception.catch` \e -> do what
1148                                                     Exception.throw e
1149 #endif
1150
1151
1152 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1153 -- to use text files here, rather than binary files.
1154 writeFileAtomic :: FilePath -> String -> IO ()
1155 writeFileAtomic targetFile content = do
1156   (tmpFile, tmpHandle) <- openTempFile targetDir template
1157   do  hPutStr tmpHandle content
1158       hClose tmpHandle
1159 #if mingw32_HOST_OS || mingw32_TARGET_OS
1160       renameFile tmpFile targetFile
1161         -- If the targetFile exists then renameFile will fail
1162         `catchIO` \err -> do
1163           exists <- doesFileExist targetFile
1164           if exists
1165             then do removeFile targetFile
1166                     -- Big fat hairy race condition
1167                     renameFile tmpFile targetFile
1168                     -- If the removeFile succeeds and the renameFile fails
1169                     -- then we've lost the atomic property.
1170             else throwIOIO err
1171 #else
1172       renameFile tmpFile targetFile
1173 #endif
1174    `onException` do hClose tmpHandle
1175                     removeFile tmpFile
1176   where
1177     template = targetName <.> "tmp"
1178     targetDir | null targetDir_ = "."
1179               | otherwise       = targetDir_
1180     --TODO: remove this when takeDirectory/splitFileName is fixed
1181     --      to always return a valid dir
1182     (targetDir_,targetName) = splitFileName targetFile