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