Switch from -this-package-key to -this-unit-id.
[ghc.git] / utils / ghc-pkg / Main.hs
1 {-# LANGUAGE CPP, TypeSynonymInstances, FlexibleInstances #-}
2 {-# OPTIONS_GHC -fno-warn-orphans #-}
3 -----------------------------------------------------------------------------
4 --
5 -- (c) The University of Glasgow 2004-2009.
6 --
7 -- Package management tool
8 --
9 -----------------------------------------------------------------------------
10
11 module Main (main) where
12
13 import Version ( version, targetOS, targetARCH )
14 import qualified GHC.PackageDb as GhcPkg
15 import qualified Distribution.Simple.PackageIndex as PackageIndex
16 import qualified Data.Graph as Graph
17 import qualified Distribution.ModuleName as ModuleName
18 import Distribution.ModuleName (ModuleName)
19 import Distribution.InstalledPackageInfo as Cabal
20 import Distribution.Compat.ReadP hiding (get)
21 import Distribution.ParseUtils
22 import Distribution.Package hiding (installedUnitId)
23 import Distribution.Text
24 import Distribution.Version
25 import Distribution.Simple.Utils (fromUTF8, toUTF8, writeUTF8File, readUTF8File)
26 import System.FilePath as FilePath
27 import qualified System.FilePath.Posix as FilePath.Posix
28 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing,
29 getModificationTime )
30 import Text.Printf
31
32 import Prelude
33
34 import System.Console.GetOpt
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, removeFile,
42 getCurrentDirectory )
43 import System.Exit ( exitWith, ExitCode(..) )
44 import System.Environment ( getArgs, getProgName, getEnv )
45 import System.IO
46 import System.IO.Error
47 import GHC.IO.Exception (IOErrorType(InappropriateType))
48 import Data.List
49 import Control.Concurrent
50
51 import qualified Data.ByteString.Char8 as BS
52
53 #if defined(mingw32_HOST_OS)
54 -- mingw32 needs these for getExecDir
55 import Foreign
56 import Foreign.C
57 #endif
58
59 #ifdef mingw32_HOST_OS
60 import GHC.ConsoleHandler
61 #else
62 import System.Posix hiding (fdToHandle)
63 #endif
64
65 #if defined(GLOB)
66 import qualified System.Info(os)
67 #endif
68
69 #if !defined(mingw32_HOST_OS) && !defined(BOOTSTRAPPING)
70 import System.Console.Terminfo as Terminfo
71 #endif
72
73 #ifdef mingw32_HOST_OS
74 # if defined(i386_HOST_ARCH)
75 # define WINDOWS_CCONV stdcall
76 # elif defined(x86_64_HOST_ARCH)
77 # define WINDOWS_CCONV ccall
78 # else
79 # error Unknown mingw32 arch
80 # endif
81 #endif
82
83 -- | Short-circuit 'any' with a \"monadic predicate\".
84 anyM :: (Monad m) => (a -> m Bool) -> [a] -> m Bool
85 anyM _ [] = return False
86 anyM p (x:xs) = do
87 b <- p x
88 if b
89 then return True
90 else anyM p xs
91
92 -- -----------------------------------------------------------------------------
93 -- Entry point
94
95 main :: IO ()
96 main = do
97 args <- getArgs
98
99 case getOpt Permute (flags ++ deprecFlags) args of
100 (cli,_,[]) | FlagHelp `elem` cli -> do
101 prog <- getProgramName
102 bye (usageInfo (usageHeader prog) flags)
103 (cli,_,[]) | FlagVersion `elem` cli ->
104 bye ourCopyright
105 (cli,nonopts,[]) ->
106 case getVerbosity Normal cli of
107 Right v -> runit v cli nonopts
108 Left err -> die err
109 (_,_,errors) -> do
110 prog <- getProgramName
111 die (concat errors ++ shortUsage prog)
112
113 -- -----------------------------------------------------------------------------
114 -- Command-line syntax
115
116 data Flag
117 = FlagUser
118 | FlagGlobal
119 | FlagHelp
120 | FlagVersion
121 | FlagConfig FilePath
122 | FlagGlobalConfig FilePath
123 | FlagUserConfig FilePath
124 | FlagForce
125 | FlagForceFiles
126 | FlagMultiInstance
127 | FlagExpandEnvVars
128 | FlagExpandPkgroot
129 | FlagNoExpandPkgroot
130 | FlagSimpleOutput
131 | FlagNamesOnly
132 | FlagIgnoreCase
133 | FlagNoUserDb
134 | FlagVerbosity (Maybe String)
135 | FlagUnitId
136 deriving Eq
137
138 flags :: [OptDescr Flag]
139 flags = [
140 Option [] ["user"] (NoArg FlagUser)
141 "use the current user's package database",
142 Option [] ["global"] (NoArg FlagGlobal)
143 "use the global package database",
144 Option ['f'] ["package-db"] (ReqArg FlagConfig "FILE/DIR")
145 "use the specified package database",
146 Option [] ["package-conf"] (ReqArg FlagConfig "FILE/DIR")
147 "use the specified package database (DEPRECATED)",
148 Option [] ["global-package-db"] (ReqArg FlagGlobalConfig "DIR")
149 "location of the global package database",
150 Option [] ["no-user-package-db"] (NoArg FlagNoUserDb)
151 "never read the user package database",
152 Option [] ["user-package-db"] (ReqArg FlagUserConfig "DIR")
153 "location of the user package database (use instead of default)",
154 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
155 "never read the user package database (DEPRECATED)",
156 Option [] ["force"] (NoArg FlagForce)
157 "ignore missing dependencies, directories, and libraries",
158 Option [] ["force-files"] (NoArg FlagForceFiles)
159 "ignore missing directories and libraries only",
160 Option [] ["enable-multi-instance"] (NoArg FlagMultiInstance)
161 "allow registering multiple instances of the same package version",
162 Option [] ["expand-env-vars"] (NoArg FlagExpandEnvVars)
163 "expand environment variables (${name}-style) in input package descriptions",
164 Option [] ["expand-pkgroot"] (NoArg FlagExpandPkgroot)
165 "expand ${pkgroot}-relative paths to absolute in output package descriptions",
166 Option [] ["no-expand-pkgroot"] (NoArg FlagNoExpandPkgroot)
167 "preserve ${pkgroot}-relative paths in output package descriptions",
168 Option ['?'] ["help"] (NoArg FlagHelp)
169 "display this help and exit",
170 Option ['V'] ["version"] (NoArg FlagVersion)
171 "output version information and exit",
172 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
173 "print output in easy-to-parse format for some commands",
174 Option [] ["names-only"] (NoArg FlagNamesOnly)
175 "only print package names, not versions; can only be used with list --simple-output",
176 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
177 "ignore case for substring matching",
178 Option [] ["ipid", "unit-id"] (NoArg FlagUnitId)
179 "interpret package arguments as unit IDs (e.g. installed package IDs)",
180 Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
181 "verbosity level (0-2, default 1)"
182 ]
183
184 data Verbosity = Silent | Normal | Verbose
185 deriving (Show, Eq, Ord)
186
187 getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
188 getVerbosity v [] = Right v
189 getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
190 getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
191 getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
192 getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
193 getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
194 getVerbosity v (_ : fs) = getVerbosity v fs
195
196 deprecFlags :: [OptDescr Flag]
197 deprecFlags = [
198 -- put deprecated flags here
199 ]
200
201 ourCopyright :: String
202 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
203
204 shortUsage :: String -> String
205 shortUsage prog = "For usage information see '" ++ prog ++ " --help'."
206
207 usageHeader :: String -> String
208 usageHeader prog = substProg prog $
209 "Usage:\n" ++
210 " $p init {path}\n" ++
211 " Create and initialise a package database at the location {path}.\n" ++
212 " Packages can be registered in the new database using the register\n" ++
213 " command with --package-db={path}. To use the new database with GHC,\n" ++
214 " use GHC's -package-db flag.\n" ++
215 "\n" ++
216 " $p register {filename | -}\n" ++
217 " Register the package using the specified installed package\n" ++
218 " description. The syntax for the latter is given in the $p\n" ++
219 " documentation. The input file should be encoded in UTF-8.\n" ++
220 "\n" ++
221 " $p update {filename | -}\n" ++
222 " Register the package, overwriting any other package with the\n" ++
223 " same name. The input file should be encoded in UTF-8.\n" ++
224 "\n" ++
225 " $p unregister {pkg-id}\n" ++
226 " Unregister the specified package.\n" ++
227 "\n" ++
228 " $p expose {pkg-id}\n" ++
229 " Expose the specified package.\n" ++
230 "\n" ++
231 " $p hide {pkg-id}\n" ++
232 " Hide the specified package.\n" ++
233 "\n" ++
234 " $p trust {pkg-id}\n" ++
235 " Trust the specified package.\n" ++
236 "\n" ++
237 " $p distrust {pkg-id}\n" ++
238 " Distrust the specified package.\n" ++
239 "\n" ++
240 " $p list [pkg]\n" ++
241 " List registered packages in the global database, and also the\n" ++
242 " user database if --user is given. If a package name is given\n" ++
243 " all the registered versions will be listed in ascending order.\n" ++
244 " Accepts the --simple-output flag.\n" ++
245 "\n" ++
246 " $p dot\n" ++
247 " Generate a graph of the package dependencies in a form suitable\n" ++
248 " for input for the graphviz tools. For example, to generate a PDF" ++
249 " of the dependency graph: ghc-pkg dot | tred | dot -Tpdf >pkgs.pdf" ++
250 "\n" ++
251 " $p find-module {module}\n" ++
252 " List registered packages exposing module {module} in the global\n" ++
253 " database, and also the user database if --user is given.\n" ++
254 " All the registered versions will be listed in ascending order.\n" ++
255 " Accepts the --simple-output flag.\n" ++
256 "\n" ++
257 " $p latest {pkg-id}\n" ++
258 " Prints the highest registered version of a package.\n" ++
259 "\n" ++
260 " $p check\n" ++
261 " Check the consistency of package dependencies and list broken packages.\n" ++
262 " Accepts the --simple-output flag.\n" ++
263 "\n" ++
264 " $p describe {pkg}\n" ++
265 " Give the registered description for the specified package. The\n" ++
266 " description is returned in precisely the syntax required by $p\n" ++
267 " register.\n" ++
268 "\n" ++
269 " $p field {pkg} {field}\n" ++
270 " Extract the specified field of the package description for the\n" ++
271 " specified package. Accepts comma-separated multiple fields.\n" ++
272 "\n" ++
273 " $p dump\n" ++
274 " Dump the registered description for every package. This is like\n" ++
275 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
276 " by tools that parse the results, rather than humans. The output is\n" ++
277 " always encoded in UTF-8, regardless of the current locale.\n" ++
278 "\n" ++
279 " $p recache\n" ++
280 " Regenerate the package database cache. This command should only be\n" ++
281 " necessary if you added a package to the database by dropping a file\n" ++
282 " into the database directory manually. By default, the global DB\n" ++
283 " is recached; to recache a different DB use --user or --package-db\n" ++
284 " as appropriate.\n" ++
285 "\n" ++
286 " Substring matching is supported for {module} in find-module and\n" ++
287 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
288 " open substring ends (prefix*, *suffix, *infix*). Use --ipid to\n" ++
289 " match against the installed package ID instead.\n" ++
290 "\n" ++
291 " When asked to modify a database (register, unregister, update,\n"++
292 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
293 " default. Specifying --user causes it to act on the user database,\n"++
294 " or --package-db can be used to act on another database\n"++
295 " entirely. When multiple of these options are given, the rightmost\n"++
296 " one is used as the database to act upon.\n"++
297 "\n"++
298 " Commands that query the package database (list, tree, latest, describe,\n"++
299 " field) operate on the list of databases specified by the flags\n"++
300 " --user, --global, and --package-db. If none of these flags are\n"++
301 " given, the default is --global --user.\n"++
302 "\n" ++
303 " The following optional flags are also accepted:\n"
304
305 substProg :: String -> String -> String
306 substProg _ [] = []
307 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
308 substProg prog (c:xs) = c : substProg prog xs
309
310 -- -----------------------------------------------------------------------------
311 -- Do the business
312
313 data Force = NoForce | ForceFiles | ForceAll | CannotForce
314 deriving (Eq,Ord)
315
316 -- | Enum flag representing argument type
317 data AsPackageArg
318 = AsUnitId
319 | AsDefault
320
321 -- | Represents how a package may be specified by a user on the command line.
322 data PackageArg
323 -- | A package identifier foo-0.1; the version might be a glob.
324 = Id PackageIdentifier
325 -- | An installed package ID foo-0.1-HASH. This is guaranteed to uniquely
326 -- match a single entry in the package database.
327 | IUId UnitId
328 -- | A glob against the package name. The first string is the literal
329 -- glob, the second is a function which returns @True@ if the argument
330 -- matches.
331 | Substring String (String->Bool)
332
333 runit :: Verbosity -> [Flag] -> [String] -> IO ()
334 runit verbosity cli nonopts = do
335 installSignalHandlers -- catch ^C and clean up
336 when (verbosity >= Verbose)
337 (putStr ourCopyright)
338 prog <- getProgramName
339 let
340 force
341 | FlagForce `elem` cli = ForceAll
342 | FlagForceFiles `elem` cli = ForceFiles
343 | otherwise = NoForce
344 as_arg | FlagUnitId `elem` cli = AsUnitId
345 | otherwise = AsDefault
346 multi_instance = FlagMultiInstance `elem` cli
347 expand_env_vars= FlagExpandEnvVars `elem` cli
348 mexpand_pkgroot= foldl' accumExpandPkgroot Nothing cli
349 where accumExpandPkgroot _ FlagExpandPkgroot = Just True
350 accumExpandPkgroot _ FlagNoExpandPkgroot = Just False
351 accumExpandPkgroot x _ = x
352
353 splitFields fields = unfoldr splitComma (',':fields)
354 where splitComma "" = Nothing
355 splitComma fs = Just $ break (==',') (tail fs)
356
357 -- | Parses a glob into a predicate which tests if a string matches
358 -- the glob. Returns Nothing if the string in question is not a glob.
359 -- At the moment, we only support globs at the beginning and/or end of
360 -- strings. This function respects case sensitivity.
361 --
362 -- >>> fromJust (substringCheck "*") "anything"
363 -- True
364 --
365 -- >>> fromJust (substringCheck "string") "string"
366 -- True
367 --
368 -- >>> fromJust (substringCheck "*bar") "foobar"
369 -- True
370 --
371 -- >>> fromJust (substringCheck "foo*") "foobar"
372 -- True
373 --
374 -- >>> fromJust (substringCheck "*ooba*") "foobar"
375 -- True
376 --
377 -- >>> fromJust (substringCheck "f*bar") "foobar"
378 -- False
379 substringCheck :: String -> Maybe (String -> Bool)
380 substringCheck "" = Nothing
381 substringCheck "*" = Just (const True)
382 substringCheck [_] = Nothing
383 substringCheck (h:t) =
384 case (h, init t, last t) of
385 ('*',s,'*') -> Just (isInfixOf (f s) . f)
386 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
387 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
388 _ -> Nothing
389 where f | FlagIgnoreCase `elem` cli = map toLower
390 | otherwise = id
391 #if defined(GLOB)
392 glob x | System.Info.os=="mingw32" = do
393 -- glob echoes its argument, after win32 filename globbing
394 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
395 txt <- hGetContents o
396 return (read txt)
397 glob x | otherwise = return [x]
398 #endif
399 --
400 -- first, parse the command
401 case nonopts of
402 #if defined(GLOB)
403 -- dummy command to demonstrate usage and permit testing
404 -- without messing things up; use glob to selectively enable
405 -- windows filename globbing for file parameters
406 -- register, update, FlagGlobalConfig, FlagConfig; others?
407 ["glob", filename] -> do
408 print filename
409 glob filename >>= print
410 #endif
411 ["init", filename] ->
412 initPackageDB filename verbosity cli
413 ["register", filename] ->
414 registerPackage filename verbosity cli
415 multi_instance
416 expand_env_vars False force
417 ["update", filename] ->
418 registerPackage filename verbosity cli
419 multi_instance
420 expand_env_vars True force
421 ["unregister", pkgarg_str] -> do
422 pkgarg <- readPackageArg as_arg pkgarg_str
423 unregisterPackage pkgarg verbosity cli force
424 ["expose", pkgarg_str] -> do
425 pkgarg <- readPackageArg as_arg pkgarg_str
426 exposePackage pkgarg verbosity cli force
427 ["hide", pkgarg_str] -> do
428 pkgarg <- readPackageArg as_arg pkgarg_str
429 hidePackage pkgarg verbosity cli force
430 ["trust", pkgarg_str] -> do
431 pkgarg <- readPackageArg as_arg pkgarg_str
432 trustPackage pkgarg verbosity cli force
433 ["distrust", pkgarg_str] -> do
434 pkgarg <- readPackageArg as_arg pkgarg_str
435 distrustPackage pkgarg verbosity cli force
436 ["list"] -> do
437 listPackages verbosity cli Nothing Nothing
438 ["list", pkgarg_str] ->
439 case substringCheck pkgarg_str of
440 Nothing -> do pkgarg <- readPackageArg as_arg pkgarg_str
441 listPackages verbosity cli (Just pkgarg) Nothing
442 Just m -> listPackages verbosity cli
443 (Just (Substring pkgarg_str m)) Nothing
444 ["dot"] -> do
445 showPackageDot verbosity cli
446 ["find-module", moduleName] -> do
447 let match = maybe (==moduleName) id (substringCheck moduleName)
448 listPackages verbosity cli Nothing (Just match)
449 ["latest", pkgid_str] -> do
450 pkgid <- readGlobPkgId pkgid_str
451 latestPackage verbosity cli pkgid
452 ["describe", pkgid_str] -> do
453 pkgarg <- case substringCheck pkgid_str of
454 Nothing -> readPackageArg as_arg pkgid_str
455 Just m -> return (Substring pkgid_str m)
456 describePackage verbosity cli pkgarg (fromMaybe False mexpand_pkgroot)
457
458 ["field", pkgid_str, fields] -> do
459 pkgarg <- case substringCheck pkgid_str of
460 Nothing -> readPackageArg as_arg pkgid_str
461 Just m -> return (Substring pkgid_str m)
462 describeField verbosity cli pkgarg
463 (splitFields fields) (fromMaybe True mexpand_pkgroot)
464
465 ["check"] -> do
466 checkConsistency verbosity cli
467
468 ["dump"] -> do
469 dumpPackages verbosity cli (fromMaybe False mexpand_pkgroot)
470
471 ["recache"] -> do
472 recache verbosity cli
473
474 [] -> do
475 die ("missing command\n" ++ shortUsage prog)
476 (_cmd:_) -> do
477 die ("command-line syntax error\n" ++ shortUsage prog)
478
479 parseCheck :: ReadP a a -> String -> String -> IO a
480 parseCheck parser str what =
481 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
482 [x] -> return x
483 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
484
485 readGlobPkgId :: String -> IO PackageIdentifier
486 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
487
488 parseGlobPackageId :: ReadP r PackageIdentifier
489 parseGlobPackageId =
490 parse
491 +++
492 (do n <- parse
493 _ <- string "-*"
494 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
495
496 readPackageArg :: AsPackageArg -> String -> IO PackageArg
497 readPackageArg AsUnitId str =
498 parseCheck (IUId `fmap` parse) str "installed package id"
499 readPackageArg AsDefault str = Id `fmap` readGlobPkgId str
500
501 -- globVersion means "all versions"
502 globVersion :: Version
503 globVersion = Version [] ["*"]
504
505 -- -----------------------------------------------------------------------------
506 -- Package databases
507
508 -- Some commands operate on a single database:
509 -- register, unregister, expose, hide, trust, distrust
510 -- however these commands also check the union of the available databases
511 -- in order to check consistency. For example, register will check that
512 -- dependencies exist before registering a package.
513 --
514 -- Some commands operate on multiple databases, with overlapping semantics:
515 -- list, describe, field
516
517 data PackageDB
518 = PackageDB {
519 location, locationAbsolute :: !FilePath,
520 -- We need both possibly-relative and definately-absolute package
521 -- db locations. This is because the relative location is used as
522 -- an identifier for the db, so it is important we do not modify it.
523 -- On the other hand we need the absolute path in a few places
524 -- particularly in relation to the ${pkgroot} stuff.
525
526 packages :: [InstalledPackageInfo]
527 }
528
529 type PackageDBStack = [PackageDB]
530 -- A stack of package databases. Convention: head is the topmost
531 -- in the stack.
532
533 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
534 allPackagesInStack = concatMap packages
535
536 getPkgDatabases :: Verbosity
537 -> Bool -- we are modifying, not reading
538 -> Bool -- use the user db
539 -> Bool -- read caches, if available
540 -> Bool -- expand vars, like ${pkgroot} and $topdir
541 -> [Flag]
542 -> IO (PackageDBStack,
543 -- the real package DB stack: [global,user] ++
544 -- DBs specified on the command line with -f.
545 Maybe FilePath,
546 -- which one to modify, if any
547 PackageDBStack)
548 -- the package DBs specified on the command
549 -- line, or [global,user] otherwise. This
550 -- is used as the list of package DBs for
551 -- commands that just read the DB, such as 'list'.
552
553 getPkgDatabases verbosity modify use_user use_cache expand_vars my_flags = do
554 -- first we determine the location of the global package config. On Windows,
555 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
556 -- location is passed to the binary using the --global-package-db flag by the
557 -- wrapper script.
558 let err_msg = "missing --global-package-db option, location of global package database unknown\n"
559 global_conf <-
560 case [ f | FlagGlobalConfig f <- my_flags ] of
561 [] -> do mb_dir <- getLibDir
562 case mb_dir of
563 Nothing -> die err_msg
564 Just dir -> do
565 r <- lookForPackageDBIn dir
566 case r of
567 Nothing -> die ("Can't find package database in " ++ dir)
568 Just path -> return path
569 fs -> return (last fs)
570
571 -- The value of the $topdir variable used in some package descriptions
572 -- Note that the way we calculate this is slightly different to how it
573 -- is done in ghc itself. We rely on the convention that the global
574 -- package db lives in ghc's libdir.
575 top_dir <- absolutePath (takeDirectory global_conf)
576
577 let no_user_db = FlagNoUserDb `elem` my_flags
578
579 -- get the location of the user package database, and create it if necessary
580 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
581 e_appdir <- tryIO $ getAppUserDataDirectory "ghc"
582
583 mb_user_conf <-
584 case [ f | FlagUserConfig f <- my_flags ] of
585 _ | no_user_db -> return Nothing
586 [] -> case e_appdir of
587 Left _ -> return Nothing
588 Right appdir -> do
589 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
590 dir = appdir </> subdir
591 r <- lookForPackageDBIn dir
592 case r of
593 Nothing -> return (Just (dir </> "package.conf.d", False))
594 Just f -> return (Just (f, True))
595 fs -> return (Just (last fs, True))
596
597 -- If the user database exists, and for "use_user" commands (which includes
598 -- "ghc-pkg check" and all commands that modify the db) we will attempt to
599 -- use the user db.
600 let sys_databases
601 | Just (user_conf,user_exists) <- mb_user_conf,
602 use_user || user_exists = [user_conf, global_conf]
603 | otherwise = [global_conf]
604
605 e_pkg_path <- tryIO (System.Environment.getEnv "GHC_PACKAGE_PATH")
606 let env_stack =
607 case e_pkg_path of
608 Left _ -> sys_databases
609 Right path
610 | not (null path) && isSearchPathSeparator (last path)
611 -> splitSearchPath (init path) ++ sys_databases
612 | otherwise
613 -> splitSearchPath path
614
615 -- The "global" database is always the one at the bottom of the stack.
616 -- This is the database we modify by default.
617 virt_global_conf = last env_stack
618
619 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
620 where is_db_flag FlagUser
621 | Just (user_conf, _user_exists) <- mb_user_conf
622 = Just user_conf
623 is_db_flag FlagGlobal = Just virt_global_conf
624 is_db_flag (FlagConfig f) = Just f
625 is_db_flag _ = Nothing
626
627 let flag_db_names | null db_flags = env_stack
628 | otherwise = reverse (nub db_flags)
629
630 -- For a "modify" command, treat all the databases as
631 -- a stack, where we are modifying the top one, but it
632 -- can refer to packages in databases further down the
633 -- stack.
634
635 -- -f flags on the command line add to the database
636 -- stack, unless any of them are present in the stack
637 -- already.
638 let final_stack = filter (`notElem` env_stack)
639 [ f | FlagConfig f <- reverse my_flags ]
640 ++ env_stack
641
642 -- the database we actually modify is the one mentioned
643 -- rightmost on the command-line.
644 let to_modify
645 | not modify = Nothing
646 | null db_flags = Just virt_global_conf
647 | otherwise = Just (last db_flags)
648
649 db_stack <- sequence
650 [ do db <- readParseDatabase verbosity mb_user_conf modify use_cache db_path
651 if expand_vars then return (mungePackageDBPaths top_dir db)
652 else return db
653 | db_path <- final_stack ]
654
655 let flag_db_stack = [ db | db_name <- flag_db_names,
656 db <- db_stack, location db == db_name ]
657
658 when (verbosity > Normal) $ do
659 infoLn ("db stack: " ++ show (map location db_stack))
660 infoLn ("modifying: " ++ show to_modify)
661 infoLn ("flag db stack: " ++ show (map location flag_db_stack))
662
663 return (db_stack, to_modify, flag_db_stack)
664
665
666 lookForPackageDBIn :: FilePath -> IO (Maybe FilePath)
667 lookForPackageDBIn dir = do
668 let path_dir = dir </> "package.conf.d"
669 exists_dir <- doesDirectoryExist path_dir
670 if exists_dir then return (Just path_dir) else do
671 let path_file = dir </> "package.conf"
672 exists_file <- doesFileExist path_file
673 if exists_file then return (Just path_file) else return Nothing
674
675 readParseDatabase :: Verbosity
676 -> Maybe (FilePath,Bool)
677 -> Bool -- we will be modifying, not just reading
678 -> Bool -- use cache
679 -> FilePath
680 -> IO PackageDB
681
682 readParseDatabase verbosity mb_user_conf modify use_cache path
683 -- the user database (only) is allowed to be non-existent
684 | Just (user_conf,False) <- mb_user_conf, path == user_conf
685 = mkPackageDB []
686 | otherwise
687 = do e <- tryIO $ getDirectoryContents path
688 case e of
689 Left err
690 | ioeGetErrorType err == InappropriateType -> do
691 -- We provide a limited degree of backwards compatibility for
692 -- old single-file style db:
693 mdb <- tryReadParseOldFileStyleDatabase verbosity
694 mb_user_conf modify use_cache path
695 case mdb of
696 Just db -> return db
697 Nothing ->
698 die $ "ghc no longer supports single-file style package "
699 ++ "databases (" ++ path ++ ") use 'ghc-pkg init'"
700 ++ "to create the database with the correct format."
701
702 | otherwise -> ioError err
703 Right fs
704 | not use_cache -> ignore_cache (const $ return ())
705 | otherwise -> do
706 let cache = path </> cachefilename
707 tdir <- getModificationTime path
708 e_tcache <- tryIO $ getModificationTime cache
709 case e_tcache of
710 Left ex -> do
711 whenReportCacheErrors $
712 if isDoesNotExistError ex
713 then do
714 warn ("WARNING: cache does not exist: " ++ cache)
715 warn ("ghc will fail to read this package db. " ++
716 recacheAdvice)
717 else do
718 warn ("WARNING: cache cannot be read: " ++ show ex)
719 warn "ghc will fail to read this package db."
720 ignore_cache (const $ return ())
721 Right tcache -> do
722 let compareTimestampToCache file =
723 when (verbosity >= Verbose) $ do
724 tFile <- getModificationTime file
725 compareTimestampToCache' file tFile
726 compareTimestampToCache' file tFile = do
727 let rel = case tcache `compare` tFile of
728 LT -> " (NEWER than cache)"
729 GT -> " (older than cache)"
730 EQ -> " (same as cache)"
731 warn ("Timestamp " ++ show tFile
732 ++ " for " ++ file ++ rel)
733 when (verbosity >= Verbose) $ do
734 warn ("Timestamp " ++ show tcache ++ " for " ++ cache)
735 compareTimestampToCache' path tdir
736 if tcache >= tdir
737 then do
738 when (verbosity > Normal) $
739 infoLn ("using cache: " ++ cache)
740 pkgs <- GhcPkg.readPackageDbForGhcPkg cache
741 mkPackageDB pkgs
742 else do
743 whenReportCacheErrors $ do
744 warn ("WARNING: cache is out of date: " ++ cache)
745 warn ("ghc will see an old view of this " ++
746 "package db. " ++ recacheAdvice)
747 ignore_cache compareTimestampToCache
748 where
749 ignore_cache :: (FilePath -> IO ()) -> IO PackageDB
750 ignore_cache checkTime = do
751 let confs = filter (".conf" `isSuffixOf`) fs
752 doFile f = do checkTime f
753 parseSingletonPackageConf verbosity f
754 pkgs <- mapM doFile $ map (path </>) confs
755 mkPackageDB pkgs
756
757 -- We normally report cache errors for read-only commands,
758 -- since modify commands because will usually fix the cache.
759 whenReportCacheErrors =
760 when ( verbosity > Normal
761 || verbosity >= Normal && not modify)
762 where
763 recacheAdvice
764 | Just (user_conf, True) <- mb_user_conf, path == user_conf
765 = "Use 'ghc-pkg recache --user' to fix."
766 | otherwise
767 = "Use 'ghc-pkg recache' to fix."
768
769 mkPackageDB pkgs = do
770 path_abs <- absolutePath path
771 return PackageDB {
772 location = path,
773 locationAbsolute = path_abs,
774 packages = pkgs
775 }
776
777 parseSingletonPackageConf :: Verbosity -> FilePath -> IO InstalledPackageInfo
778 parseSingletonPackageConf verbosity file = do
779 when (verbosity > Normal) $ infoLn ("reading package config: " ++ file)
780 readUTF8File file >>= fmap fst . parsePackageInfo
781
782 cachefilename :: FilePath
783 cachefilename = "package.cache"
784
785 mungePackageDBPaths :: FilePath -> PackageDB -> PackageDB
786 mungePackageDBPaths top_dir db@PackageDB { packages = pkgs } =
787 db { packages = map (mungePackagePaths top_dir pkgroot) pkgs }
788 where
789 pkgroot = takeDirectory (locationAbsolute db)
790 -- It so happens that for both styles of package db ("package.conf"
791 -- files and "package.conf.d" dirs) the pkgroot is the parent directory
792 -- ${pkgroot}/package.conf or ${pkgroot}/package.conf.d/
793
794 -- TODO: This code is duplicated in compiler/main/Packages.lhs
795 mungePackagePaths :: FilePath -> FilePath
796 -> InstalledPackageInfo -> InstalledPackageInfo
797 -- Perform path/URL variable substitution as per the Cabal ${pkgroot} spec
798 -- (http://www.haskell.org/pipermail/libraries/2009-May/011772.html)
799 -- Paths/URLs can be relative to ${pkgroot} or ${pkgrooturl}.
800 -- The "pkgroot" is the directory containing the package database.
801 --
802 -- Also perform a similar substitution for the older GHC-specific
803 -- "$topdir" variable. The "topdir" is the location of the ghc
804 -- installation (obtained from the -B option).
805 mungePackagePaths top_dir pkgroot pkg =
806 pkg {
807 importDirs = munge_paths (importDirs pkg),
808 includeDirs = munge_paths (includeDirs pkg),
809 libraryDirs = munge_paths (libraryDirs pkg),
810 frameworkDirs = munge_paths (frameworkDirs pkg),
811 haddockInterfaces = munge_paths (haddockInterfaces pkg),
812 -- haddock-html is allowed to be either a URL or a file
813 haddockHTMLs = munge_paths (munge_urls (haddockHTMLs pkg))
814 }
815 where
816 munge_paths = map munge_path
817 munge_urls = map munge_url
818
819 munge_path p
820 | Just p' <- stripVarPrefix "${pkgroot}" p = pkgroot ++ p'
821 | Just p' <- stripVarPrefix "$topdir" p = top_dir ++ p'
822 | otherwise = p
823
824 munge_url p
825 | Just p' <- stripVarPrefix "${pkgrooturl}" p = toUrlPath pkgroot p'
826 | Just p' <- stripVarPrefix "$httptopdir" p = toUrlPath top_dir p'
827 | otherwise = p
828
829 toUrlPath r p = "file:///"
830 -- URLs always use posix style '/' separators:
831 ++ FilePath.Posix.joinPath
832 (r : -- We need to drop a leading "/" or "\\"
833 -- if there is one:
834 dropWhile (all isPathSeparator)
835 (FilePath.splitDirectories p))
836
837 -- We could drop the separator here, and then use </> above. However,
838 -- by leaving it in and using ++ we keep the same path separator
839 -- rather than letting FilePath change it to use \ as the separator
840 stripVarPrefix var path = case stripPrefix var path of
841 Just [] -> Just []
842 Just cs@(c : _) | isPathSeparator c -> Just cs
843 _ -> Nothing
844
845
846 -- -----------------------------------------------------------------------------
847 -- Workaround for old single-file style package dbs
848
849 -- Single-file style package dbs have been deprecated for some time, but
850 -- it turns out that Cabal was using them in one place. So this code is for a
851 -- workaround to allow older Cabal versions to use this newer ghc.
852
853 -- We check if the file db contains just "[]" and if so, we look for a new
854 -- dir-style db in path.d/, ie in a dir next to the given file.
855 -- We cannot just replace the file with a new dir style since Cabal still
856 -- assumes it's a file and tries to overwrite with 'writeFile'.
857
858 -- ghc itself also cooperates in this workaround
859
860 tryReadParseOldFileStyleDatabase :: Verbosity -> Maybe (FilePath, Bool)
861 -> Bool -> Bool -> FilePath
862 -> IO (Maybe PackageDB)
863 tryReadParseOldFileStyleDatabase verbosity mb_user_conf modify use_cache path = do
864 -- assumes we've already established that path exists and is not a dir
865 content <- readFile path `catchIO` \_ -> return ""
866 if take 2 content == "[]"
867 then do
868 path_abs <- absolutePath path
869 let path_dir = path <.> "d"
870 warn $ "Warning: ignoring old file-style db and trying " ++ path_dir
871 direxists <- doesDirectoryExist path_dir
872 if direxists
873 then do db <- readParseDatabase verbosity mb_user_conf
874 modify use_cache path_dir
875 -- but pretend it was at the original location
876 return $ Just db {
877 location = path,
878 locationAbsolute = path_abs
879 }
880 else return $ Just PackageDB {
881 location = path,
882 locationAbsolute = path_abs,
883 packages = []
884 }
885
886 -- if the path is not a file, or is not an empty db then we fail
887 else return Nothing
888
889 adjustOldFileStylePackageDB :: PackageDB -> IO PackageDB
890 adjustOldFileStylePackageDB db = do
891 -- assumes we have not yet established if it's an old style or not
892 mcontent <- liftM Just (readFile (location db)) `catchIO` \_ -> return Nothing
893 case fmap (take 2) mcontent of
894 -- it is an old style and empty db, so look for a dir kind in location.d/
895 Just "[]" -> return db {
896 location = location db <.> "d",
897 locationAbsolute = locationAbsolute db <.> "d"
898 }
899 -- it is old style but not empty, we have to bail
900 Just _ -> die $ "ghc no longer supports single-file style package "
901 ++ "databases (" ++ location db ++ ") use 'ghc-pkg init'"
902 ++ "to create the database with the correct format."
903 -- probably not old style, carry on as normal
904 Nothing -> return db
905
906
907 -- -----------------------------------------------------------------------------
908 -- Creating a new package DB
909
910 initPackageDB :: FilePath -> Verbosity -> [Flag] -> IO ()
911 initPackageDB filename verbosity _flags = do
912 let eexist = die ("cannot create: " ++ filename ++ " already exists")
913 b1 <- doesFileExist filename
914 when b1 eexist
915 b2 <- doesDirectoryExist filename
916 when b2 eexist
917 filename_abs <- absolutePath filename
918 changeDB verbosity [] PackageDB {
919 location = filename, locationAbsolute = filename_abs,
920 packages = []
921 }
922
923 -- -----------------------------------------------------------------------------
924 -- Registering
925
926 registerPackage :: FilePath
927 -> Verbosity
928 -> [Flag]
929 -> Bool -- multi_instance
930 -> Bool -- expand_env_vars
931 -> Bool -- update
932 -> Force
933 -> IO ()
934 registerPackage input verbosity my_flags multi_instance
935 expand_env_vars update force = do
936 (db_stack, Just to_modify, _flag_dbs) <-
937 getPkgDatabases verbosity True{-modify-} True{-use user-}
938 True{-use cache-} False{-expand vars-} my_flags
939
940 let
941 db_to_operate_on = my_head "register" $
942 filter ((== to_modify).location) db_stack
943 s <-
944 case input of
945 "-" -> do
946 when (verbosity >= Normal) $
947 info "Reading package info from stdin ... "
948 -- fix the encoding to UTF-8, since this is an interchange format
949 hSetEncoding stdin utf8
950 getContents
951 f -> do
952 when (verbosity >= Normal) $
953 info ("Reading package info from " ++ show f ++ " ... ")
954 readUTF8File f
955
956 expanded <- if expand_env_vars then expandEnvVars s force
957 else return s
958
959 (pkg, ws) <- parsePackageInfo expanded
960 when (verbosity >= Normal) $
961 infoLn "done."
962
963 -- report any warnings from the parse phase
964 _ <- reportValidateErrors verbosity [] ws
965 (display (sourcePackageId pkg) ++ ": Warning: ") Nothing
966
967 -- validate the expanded pkg, but register the unexpanded
968 pkgroot <- absolutePath (takeDirectory to_modify)
969 let top_dir = takeDirectory (location (last db_stack))
970 pkg_expanded = mungePackagePaths top_dir pkgroot pkg
971
972 let truncated_stack = dropWhile ((/= to_modify).location) db_stack
973 -- truncate the stack for validation, because we don't allow
974 -- packages lower in the stack to refer to those higher up.
975 validatePackageConfig pkg_expanded verbosity truncated_stack
976 multi_instance update force
977
978 let
979 -- In the normal mode, we only allow one version of each package, so we
980 -- remove all instances with the same source package id as the one we're
981 -- adding. In the multi instance mode we don't do that, thus allowing
982 -- multiple instances with the same source package id.
983 removes = [ RemovePackage p
984 | not multi_instance,
985 p <- packages db_to_operate_on,
986 sourcePackageId p == sourcePackageId pkg ]
987 --
988 changeDB verbosity (removes ++ [AddPackage pkg]) db_to_operate_on
989
990 parsePackageInfo
991 :: String
992 -> IO (InstalledPackageInfo, [ValidateWarning])
993 parsePackageInfo str =
994 case parseInstalledPackageInfo str of
995 ParseOk warnings ok -> return (mungePackageInfo ok, ws)
996 where
997 ws = [ msg | PWarning msg <- warnings
998 , not ("Unrecognized field pkgroot" `isPrefixOf` msg) ]
999 ParseFailed err -> case locatedErrorMsg err of
1000 (Nothing, s) -> die s
1001 (Just l, s) -> die (show l ++ ": " ++ s)
1002
1003 mungePackageInfo :: InstalledPackageInfo -> InstalledPackageInfo
1004 mungePackageInfo ipi = ipi
1005
1006 -- -----------------------------------------------------------------------------
1007 -- Making changes to a package database
1008
1009 data DBOp = RemovePackage InstalledPackageInfo
1010 | AddPackage InstalledPackageInfo
1011 | ModifyPackage InstalledPackageInfo
1012
1013 changeDB :: Verbosity -> [DBOp] -> PackageDB -> IO ()
1014 changeDB verbosity cmds db = do
1015 let db' = updateInternalDB db cmds
1016 db'' <- adjustOldFileStylePackageDB db'
1017 createDirectoryIfMissing True (location db'')
1018 changeDBDir verbosity cmds db''
1019
1020 updateInternalDB :: PackageDB -> [DBOp] -> PackageDB
1021 updateInternalDB db cmds = db{ packages = foldl do_cmd (packages db) cmds }
1022 where
1023 do_cmd pkgs (RemovePackage p) =
1024 filter ((/= installedUnitId p) . installedUnitId) pkgs
1025 do_cmd pkgs (AddPackage p) = p : pkgs
1026 do_cmd pkgs (ModifyPackage p) =
1027 do_cmd (do_cmd pkgs (RemovePackage p)) (AddPackage p)
1028
1029
1030 changeDBDir :: Verbosity -> [DBOp] -> PackageDB -> IO ()
1031 changeDBDir verbosity cmds db = do
1032 mapM_ do_cmd cmds
1033 updateDBCache verbosity db
1034 where
1035 do_cmd (RemovePackage p) = do
1036 let file = location db </> display (installedUnitId p) <.> "conf"
1037 when (verbosity > Normal) $ infoLn ("removing " ++ file)
1038 removeFileSafe file
1039 do_cmd (AddPackage p) = do
1040 let file = location db </> display (installedUnitId p) <.> "conf"
1041 when (verbosity > Normal) $ infoLn ("writing " ++ file)
1042 writeUTF8File file (showInstalledPackageInfo p)
1043 do_cmd (ModifyPackage p) =
1044 do_cmd (AddPackage p)
1045
1046 updateDBCache :: Verbosity -> PackageDB -> IO ()
1047 updateDBCache verbosity db = do
1048 let filename = location db </> cachefilename
1049
1050 pkgsCabalFormat :: [InstalledPackageInfo]
1051 pkgsCabalFormat = packages db
1052
1053 pkgsGhcCacheFormat :: [PackageCacheFormat]
1054 pkgsGhcCacheFormat = map convertPackageInfoToCacheFormat pkgsCabalFormat
1055
1056 when (verbosity > Normal) $
1057 infoLn ("writing cache " ++ filename)
1058 GhcPkg.writePackageDb filename pkgsGhcCacheFormat pkgsCabalFormat
1059 `catchIO` \e ->
1060 if isPermissionError e
1061 then die (filename ++ ": you don't have permission to modify this file")
1062 else ioError e
1063 -- See Note [writeAtomic leaky abstraction]
1064 -- Cross-platform "touch". This only works if filename is not empty, and not
1065 -- open for writing already.
1066 -- TODO. When the Win32 or directory packages have either a touchFile or a
1067 -- setModificationTime function, use one of those.
1068 withBinaryFile filename ReadWriteMode $ \handle -> do
1069 c <- hGetChar handle
1070 hSeek handle AbsoluteSeek 0
1071 hPutChar handle c
1072
1073 type PackageCacheFormat = GhcPkg.InstalledPackageInfo
1074 String -- src package id
1075 String -- package name
1076 String -- unit id
1077 ModuleName -- module name
1078
1079 convertPackageInfoToCacheFormat :: InstalledPackageInfo -> PackageCacheFormat
1080 convertPackageInfoToCacheFormat pkg =
1081 GhcPkg.InstalledPackageInfo {
1082 GhcPkg.unitId = display (installedUnitId pkg),
1083 GhcPkg.sourcePackageId = display (sourcePackageId pkg),
1084 GhcPkg.packageName = display (packageName pkg),
1085 GhcPkg.packageVersion = packageVersion pkg,
1086 GhcPkg.depends = map display (depends pkg),
1087 GhcPkg.abiHash = let AbiHash abi = abiHash pkg
1088 in abi,
1089 GhcPkg.importDirs = importDirs pkg,
1090 GhcPkg.hsLibraries = hsLibraries pkg,
1091 GhcPkg.extraLibraries = extraLibraries pkg,
1092 GhcPkg.extraGHCiLibraries = extraGHCiLibraries pkg,
1093 GhcPkg.libraryDirs = libraryDirs pkg,
1094 GhcPkg.frameworks = frameworks pkg,
1095 GhcPkg.frameworkDirs = frameworkDirs pkg,
1096 GhcPkg.ldOptions = ldOptions pkg,
1097 GhcPkg.ccOptions = ccOptions pkg,
1098 GhcPkg.includes = includes pkg,
1099 GhcPkg.includeDirs = includeDirs pkg,
1100 GhcPkg.haddockInterfaces = haddockInterfaces pkg,
1101 GhcPkg.haddockHTMLs = haddockHTMLs pkg,
1102 GhcPkg.exposedModules = map convertExposed (exposedModules pkg),
1103 GhcPkg.hiddenModules = hiddenModules pkg,
1104 GhcPkg.exposed = exposed pkg,
1105 GhcPkg.trusted = trusted pkg
1106 }
1107 where convertExposed (ExposedModule n reexport) =
1108 GhcPkg.ExposedModule n (fmap convertOriginal reexport)
1109 convertOriginal (OriginalModule ipid m) =
1110 GhcPkg.OriginalModule (display ipid) m
1111
1112 instance GhcPkg.BinaryStringRep ModuleName where
1113 fromStringRep = ModuleName.fromString . fromUTF8 . BS.unpack
1114 toStringRep = BS.pack . toUTF8 . display
1115
1116 instance GhcPkg.BinaryStringRep String where
1117 fromStringRep = fromUTF8 . BS.unpack
1118 toStringRep = BS.pack . toUTF8
1119
1120
1121 -- -----------------------------------------------------------------------------
1122 -- Exposing, Hiding, Trusting, Distrusting, Unregistering are all similar
1123
1124 exposePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
1125 exposePackage = modifyPackage (\p -> ModifyPackage p{exposed=True})
1126
1127 hidePackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
1128 hidePackage = modifyPackage (\p -> ModifyPackage p{exposed=False})
1129
1130 trustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
1131 trustPackage = modifyPackage (\p -> ModifyPackage p{trusted=True})
1132
1133 distrustPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
1134 distrustPackage = modifyPackage (\p -> ModifyPackage p{trusted=False})
1135
1136 unregisterPackage :: PackageArg -> Verbosity -> [Flag] -> Force -> IO ()
1137 unregisterPackage = modifyPackage RemovePackage
1138
1139 modifyPackage
1140 :: (InstalledPackageInfo -> DBOp)
1141 -> PackageArg
1142 -> Verbosity
1143 -> [Flag]
1144 -> Force
1145 -> IO ()
1146 modifyPackage fn pkgarg verbosity my_flags force = do
1147 (db_stack, Just _to_modify, flag_dbs) <-
1148 getPkgDatabases verbosity True{-modify-} True{-use user-}
1149 True{-use cache-} False{-expand vars-} my_flags
1150
1151 -- Do the search for the package respecting flags...
1152 (db, ps) <- fmap head $ findPackagesByDB flag_dbs pkgarg
1153 let
1154 db_name = location db
1155 pkgs = packages db
1156
1157 pks = map installedUnitId ps
1158
1159 cmds = [ fn pkg | pkg <- pkgs, installedUnitId pkg `elem` pks ]
1160 new_db = updateInternalDB db cmds
1161
1162 -- ...but do consistency checks with regards to the full stack
1163 old_broken = brokenPackages (allPackagesInStack db_stack)
1164 rest_of_stack = filter ((/= db_name) . location) db_stack
1165 new_stack = new_db : rest_of_stack
1166 new_broken = brokenPackages (allPackagesInStack new_stack)
1167 newly_broken = filter ((`notElem` map installedUnitId old_broken)
1168 . installedUnitId) new_broken
1169 --
1170 let displayQualPkgId pkg
1171 | [_] <- filter ((== pkgid) . sourcePackageId)
1172 (allPackagesInStack db_stack)
1173 = display pkgid
1174 | otherwise = display pkgid ++ "@" ++ display (installedUnitId pkg)
1175 where pkgid = sourcePackageId pkg
1176 when (not (null newly_broken)) $
1177 dieOrForceAll force ("unregistering would break the following packages: "
1178 ++ unwords (map displayQualPkgId newly_broken))
1179
1180 changeDB verbosity cmds db
1181
1182 recache :: Verbosity -> [Flag] -> IO ()
1183 recache verbosity my_flags = do
1184 (db_stack, Just to_modify, _flag_dbs) <-
1185 getPkgDatabases verbosity True{-modify-} True{-use user-} False{-no cache-}
1186 False{-expand vars-} my_flags
1187 let
1188 db_to_operate_on = my_head "recache" $
1189 filter ((== to_modify).location) db_stack
1190 --
1191 changeDB verbosity [] db_to_operate_on
1192
1193 -- -----------------------------------------------------------------------------
1194 -- Listing packages
1195
1196 listPackages :: Verbosity -> [Flag] -> Maybe PackageArg
1197 -> Maybe (String->Bool)
1198 -> IO ()
1199 listPackages verbosity my_flags mPackageName mModuleName = do
1200 let simple_output = FlagSimpleOutput `elem` my_flags
1201 (db_stack, _, flag_db_stack) <-
1202 getPkgDatabases verbosity False{-modify-} False{-use user-}
1203 True{-use cache-} False{-expand vars-} my_flags
1204
1205 let db_stack_filtered -- if a package is given, filter out all other packages
1206 | Just this <- mPackageName =
1207 [ db{ packages = filter (this `matchesPkg`) (packages db) }
1208 | db <- flag_db_stack ]
1209 | Just match <- mModuleName = -- packages which expose mModuleName
1210 [ db{ packages = filter (match `exposedInPkg`) (packages db) }
1211 | db <- flag_db_stack ]
1212 | otherwise = flag_db_stack
1213
1214 db_stack_sorted
1215 = [ db{ packages = sort_pkgs (packages db) }
1216 | db <- db_stack_filtered ]
1217 where sort_pkgs = sortBy cmpPkgIds
1218 cmpPkgIds pkg1 pkg2 =
1219 case pkgName p1 `compare` pkgName p2 of
1220 LT -> LT
1221 GT -> GT
1222 EQ -> case pkgVersion p1 `compare` pkgVersion p2 of
1223 LT -> LT
1224 GT -> GT
1225 EQ -> installedUnitId pkg1 `compare` installedUnitId pkg2
1226 where (p1,p2) = (sourcePackageId pkg1, sourcePackageId pkg2)
1227
1228 stack = reverse db_stack_sorted
1229
1230 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
1231
1232 pkg_map = allPackagesInStack db_stack
1233 broken = map installedUnitId (brokenPackages pkg_map)
1234
1235 show_normal PackageDB{ location = db_name, packages = pkg_confs } =
1236 do hPutStrLn stdout db_name
1237 if null pkg_confs
1238 then hPutStrLn stdout " (no packages)"
1239 else hPutStrLn stdout $ unlines (map (" " ++) (map pp_pkg pkg_confs))
1240 where
1241 pp_pkg p
1242 | installedUnitId p `elem` broken = printf "{%s}" doc
1243 | exposed p = doc
1244 | otherwise = printf "(%s)" doc
1245 where doc | verbosity >= Verbose = printf "%s (%s)" pkg (display (installedUnitId p))
1246 | otherwise = pkg
1247 where
1248 pkg = display (sourcePackageId p)
1249
1250 show_simple = simplePackageList my_flags . allPackagesInStack
1251
1252 when (not (null broken) && not simple_output && verbosity /= Silent) $ do
1253 prog <- getProgramName
1254 warn ("WARNING: there are broken packages. Run '" ++ prog ++ " check' for more details.")
1255
1256 if simple_output then show_simple stack else do
1257
1258 #if defined(mingw32_HOST_OS) || defined(BOOTSTRAPPING)
1259 mapM_ show_normal stack
1260 #else
1261 let
1262 show_colour withF db@PackageDB{ packages = pkg_confs } =
1263 if null pkg_confs
1264 then termText (location db) <#> termText "\n (no packages)\n"
1265 else
1266 mconcat $ map (<#> termText "\n") $
1267 (termText (location db)
1268 : map (termText " " <#>) (map pp_pkg pkg_confs))
1269 where
1270 pp_pkg p
1271 | installedUnitId p `elem` broken = withF Red doc
1272 | exposed p = doc
1273 | otherwise = withF Blue doc
1274 where doc | verbosity >= Verbose
1275 = termText (printf "%s (%s)" pkg (display (installedUnitId p)))
1276 | otherwise
1277 = termText pkg
1278 where
1279 pkg = display (sourcePackageId p)
1280
1281 is_tty <- hIsTerminalDevice stdout
1282 if not is_tty
1283 then mapM_ show_normal stack
1284 else do tty <- Terminfo.setupTermFromEnv
1285 case Terminfo.getCapability tty withForegroundColor of
1286 Nothing -> mapM_ show_normal stack
1287 Just w -> runTermOutput tty $ mconcat $
1288 map (show_colour w) stack
1289 #endif
1290
1291 simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
1292 simplePackageList my_flags pkgs = do
1293 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
1294 else display
1295 strs = map showPkg $ map sourcePackageId pkgs
1296 when (not (null pkgs)) $
1297 hPutStrLn stdout $ concat $ intersperse " " strs
1298
1299 showPackageDot :: Verbosity -> [Flag] -> IO ()
1300 showPackageDot verbosity myflags = do
1301 (_, _, flag_db_stack) <-
1302 getPkgDatabases verbosity False{-modify-} False{-use user-}
1303 True{-use cache-} False{-expand vars-} myflags
1304
1305 let all_pkgs = allPackagesInStack flag_db_stack
1306 ipix = PackageIndex.fromList all_pkgs
1307
1308 putStrLn "digraph {"
1309 let quote s = '"':s ++ "\""
1310 mapM_ putStrLn [ quote from ++ " -> " ++ quote to
1311 | p <- all_pkgs,
1312 let from = display (sourcePackageId p),
1313 key <- depends p,
1314 Just dep <- [PackageIndex.lookupUnitId ipix key],
1315 let to = display (sourcePackageId dep)
1316 ]
1317 putStrLn "}"
1318
1319 -- -----------------------------------------------------------------------------
1320 -- Prints the highest (hidden or exposed) version of a package
1321
1322 -- ToDo: This is no longer well-defined with unit ids, because the
1323 -- dependencies may be varying versions
1324 latestPackage :: Verbosity -> [Flag] -> PackageIdentifier -> IO ()
1325 latestPackage verbosity my_flags pkgid = do
1326 (_, _, flag_db_stack) <-
1327 getPkgDatabases verbosity False{-modify-} False{-use user-}
1328 True{-use cache-} False{-expand vars-} my_flags
1329
1330 ps <- findPackages flag_db_stack (Id pkgid)
1331 case ps of
1332 [] -> die "no matches"
1333 _ -> show_pkg . maximum . map sourcePackageId $ ps
1334 where
1335 show_pkg pid = hPutStrLn stdout (display pid)
1336
1337 -- -----------------------------------------------------------------------------
1338 -- Describe
1339
1340 describePackage :: Verbosity -> [Flag] -> PackageArg -> Bool -> IO ()
1341 describePackage verbosity my_flags pkgarg expand_pkgroot = do
1342 (_, _, flag_db_stack) <-
1343 getPkgDatabases verbosity False{-modify-} False{-use user-}
1344 True{-use cache-} expand_pkgroot my_flags
1345 dbs <- findPackagesByDB flag_db_stack pkgarg
1346 doDump expand_pkgroot [ (pkg, locationAbsolute db)
1347 | (db, pkgs) <- dbs, pkg <- pkgs ]
1348
1349 dumpPackages :: Verbosity -> [Flag] -> Bool -> IO ()
1350 dumpPackages verbosity my_flags expand_pkgroot = do
1351 (_, _, flag_db_stack) <-
1352 getPkgDatabases verbosity False{-modify-} False{-use user-}
1353 True{-use cache-} expand_pkgroot my_flags
1354 doDump expand_pkgroot [ (pkg, locationAbsolute db)
1355 | db <- flag_db_stack, pkg <- packages db ]
1356
1357 doDump :: Bool -> [(InstalledPackageInfo, FilePath)] -> IO ()
1358 doDump expand_pkgroot pkgs = do
1359 -- fix the encoding to UTF-8, since this is an interchange format
1360 hSetEncoding stdout utf8
1361 putStrLn $
1362 intercalate "---\n"
1363 [ if expand_pkgroot
1364 then showInstalledPackageInfo pkg
1365 else showInstalledPackageInfo pkg ++ pkgrootField
1366 | (pkg, pkgloc) <- pkgs
1367 , let pkgroot = takeDirectory pkgloc
1368 pkgrootField = "pkgroot: " ++ show pkgroot ++ "\n" ]
1369
1370 -- PackageId is can have globVersion for the version
1371 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
1372 findPackages db_stack pkgarg
1373 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
1374
1375 findPackagesByDB :: PackageDBStack -> PackageArg
1376 -> IO [(PackageDB, [InstalledPackageInfo])]
1377 findPackagesByDB db_stack pkgarg
1378 = case [ (db, matched)
1379 | db <- db_stack,
1380 let matched = filter (pkgarg `matchesPkg`) (packages db),
1381 not (null matched) ] of
1382 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
1383 ps -> return ps
1384 where
1385 pkg_msg (Id pkgid) = display pkgid
1386 pkg_msg (IUId ipid) = display ipid
1387 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
1388
1389 matches :: PackageIdentifier -> PackageIdentifier -> Bool
1390 pid `matches` pid'
1391 = (pkgName pid == pkgName pid')
1392 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
1393
1394 realVersion :: PackageIdentifier -> Bool
1395 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
1396 -- when versionBranch == [], this is a glob
1397
1398 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
1399 (Id pid) `matchesPkg` pkg = pid `matches` sourcePackageId pkg
1400 (IUId ipid) `matchesPkg` pkg = ipid == installedUnitId pkg
1401 (Substring _ m) `matchesPkg` pkg = m (display (sourcePackageId pkg))
1402
1403 -- -----------------------------------------------------------------------------
1404 -- Field
1405
1406 describeField :: Verbosity -> [Flag] -> PackageArg -> [String] -> Bool -> IO ()
1407 describeField verbosity my_flags pkgarg fields expand_pkgroot = do
1408 (_, _, flag_db_stack) <-
1409 getPkgDatabases verbosity False{-modify-} False{-use user-}
1410 True{-use cache-} expand_pkgroot my_flags
1411 fns <- mapM toField fields
1412 ps <- findPackages flag_db_stack pkgarg
1413 mapM_ (selectFields fns) ps
1414 where showFun = if FlagSimpleOutput `elem` my_flags
1415 then showSimpleInstalledPackageInfoField
1416 else showInstalledPackageInfoField
1417 toField f = case showFun f of
1418 Nothing -> die ("unknown field: " ++ f)
1419 Just fn -> return fn
1420 selectFields fns pinfo = mapM_ (\fn->putStrLn (fn pinfo)) fns
1421
1422
1423 -- -----------------------------------------------------------------------------
1424 -- Check: Check consistency of installed packages
1425
1426 checkConsistency :: Verbosity -> [Flag] -> IO ()
1427 checkConsistency verbosity my_flags = do
1428 (db_stack, _, _) <-
1429 getPkgDatabases verbosity False{-modify-} True{-use user-}
1430 True{-use cache-} True{-expand vars-}
1431 my_flags
1432 -- although check is not a modify command, we do need to use the user
1433 -- db, because we may need it to verify package deps.
1434
1435 let simple_output = FlagSimpleOutput `elem` my_flags
1436
1437 let pkgs = allPackagesInStack db_stack
1438
1439 checkPackage p = do
1440 (_,es,ws) <- runValidate $ checkPackageConfig p verbosity db_stack
1441 True True
1442 if null es
1443 then do when (not simple_output) $ do
1444 _ <- reportValidateErrors verbosity [] ws "" Nothing
1445 return ()
1446 return []
1447 else do
1448 when (not simple_output) $ do
1449 reportError ("There are problems in package " ++ display (sourcePackageId p) ++ ":")
1450 _ <- reportValidateErrors verbosity es ws " " Nothing
1451 return ()
1452 return [p]
1453
1454 broken_pkgs <- concat `fmap` mapM checkPackage pkgs
1455
1456 let filterOut pkgs1 pkgs2 = filter not_in pkgs2
1457 where not_in p = sourcePackageId p `notElem` all_ps
1458 all_ps = map sourcePackageId pkgs1
1459
1460 let not_broken_pkgs = filterOut broken_pkgs pkgs
1461 (_, trans_broken_pkgs) = closure [] not_broken_pkgs
1462 all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
1463
1464 when (not (null all_broken_pkgs)) $ do
1465 if simple_output
1466 then simplePackageList my_flags all_broken_pkgs
1467 else do
1468 reportError ("\nThe following packages are broken, either because they have a problem\n"++
1469 "listed above, or because they depend on a broken package.")
1470 mapM_ (hPutStrLn stderr . display . sourcePackageId) all_broken_pkgs
1471
1472 when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
1473
1474
1475 closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
1476 -> ([InstalledPackageInfo], [InstalledPackageInfo])
1477 closure pkgs db_stack = go pkgs db_stack
1478 where
1479 go avail not_avail =
1480 case partition (depsAvailable avail) not_avail of
1481 ([], not_avail') -> (avail, not_avail')
1482 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
1483
1484 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
1485 -> Bool
1486 depsAvailable pkgs_ok pkg = null dangling
1487 where dangling = filter (`notElem` pids) (depends pkg)
1488 pids = map installedUnitId pkgs_ok
1489
1490 -- we want mutually recursive groups of package to show up
1491 -- as broken. (#1750)
1492
1493 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
1494 brokenPackages pkgs = snd (closure [] pkgs)
1495
1496 -----------------------------------------------------------------------------
1497 -- Sanity-check a new package config, and automatically build GHCi libs
1498 -- if requested.
1499
1500 type ValidateError = (Force,String)
1501 type ValidateWarning = String
1502
1503 newtype Validate a = V { runValidate :: IO (a, [ValidateError],[ValidateWarning]) }
1504
1505 instance Functor Validate where
1506 fmap = liftM
1507
1508 instance Applicative Validate where
1509 pure a = V $ pure (a, [], [])
1510 (<*>) = ap
1511
1512 instance Monad Validate where
1513 m >>= k = V $ do
1514 (a, es, ws) <- runValidate m
1515 (b, es', ws') <- runValidate (k a)
1516 return (b,es++es',ws++ws')
1517
1518 verror :: Force -> String -> Validate ()
1519 verror f s = V (return ((),[(f,s)],[]))
1520
1521 vwarn :: String -> Validate ()
1522 vwarn s = V (return ((),[],["Warning: " ++ s]))
1523
1524 liftIO :: IO a -> Validate a
1525 liftIO k = V (k >>= \a -> return (a,[],[]))
1526
1527 -- returns False if we should die
1528 reportValidateErrors :: Verbosity -> [ValidateError] -> [ValidateWarning]
1529 -> String -> Maybe Force -> IO Bool
1530 reportValidateErrors verbosity es ws prefix mb_force = do
1531 mapM_ (warn . (prefix++)) ws
1532 oks <- mapM report es
1533 return (and oks)
1534 where
1535 report (f,s)
1536 | Just force <- mb_force
1537 = if (force >= f)
1538 then do when (verbosity >= Normal) $
1539 reportError (prefix ++ s ++ " (ignoring)")
1540 return True
1541 else if f < CannotForce
1542 then do reportError (prefix ++ s ++ " (use --force to override)")
1543 return False
1544 else do reportError err
1545 return False
1546 | otherwise = do reportError err
1547 return False
1548 where
1549 err = prefix ++ s
1550
1551 validatePackageConfig :: InstalledPackageInfo
1552 -> Verbosity
1553 -> PackageDBStack
1554 -> Bool -- multi_instance
1555 -> Bool -- update, or check
1556 -> Force
1557 -> IO ()
1558 validatePackageConfig pkg verbosity db_stack
1559 multi_instance update force = do
1560 (_,es,ws) <- runValidate $
1561 checkPackageConfig pkg verbosity db_stack
1562 multi_instance update
1563 ok <- reportValidateErrors verbosity es ws
1564 (display (sourcePackageId pkg) ++ ": ") (Just force)
1565 when (not ok) $ exitWith (ExitFailure 1)
1566
1567 checkPackageConfig :: InstalledPackageInfo
1568 -> Verbosity
1569 -> PackageDBStack
1570 -> Bool -- multi_instance
1571 -> Bool -- update, or check
1572 -> Validate ()
1573 checkPackageConfig pkg verbosity db_stack
1574 multi_instance update = do
1575 checkPackageId pkg
1576 checkUnitId pkg db_stack update
1577 checkDuplicates db_stack pkg multi_instance update
1578 mapM_ (checkDep db_stack) (depends pkg)
1579 checkDuplicateDepends (depends pkg)
1580 mapM_ (checkDir False "import-dirs") (importDirs pkg)
1581 mapM_ (checkDir True "library-dirs") (libraryDirs pkg)
1582 mapM_ (checkDir True "include-dirs") (includeDirs pkg)
1583 mapM_ (checkDir True "framework-dirs") (frameworkDirs pkg)
1584 mapM_ (checkFile True "haddock-interfaces") (haddockInterfaces pkg)
1585 mapM_ (checkDirURL True "haddock-html") (haddockHTMLs pkg)
1586 checkDuplicateModules pkg
1587 checkExposedModules db_stack pkg
1588 checkOtherModules pkg
1589 mapM_ (checkHSLib verbosity (libraryDirs pkg)) (hsLibraries pkg)
1590 -- ToDo: check these somehow?
1591 -- extra_libraries :: [String],
1592 -- c_includes :: [String],
1593
1594 -- When the package name and version are put together, sometimes we can
1595 -- end up with a package id that cannot be parsed. This will lead to
1596 -- difficulties when the user wants to refer to the package later, so
1597 -- we check that the package id can be parsed properly here.
1598 checkPackageId :: InstalledPackageInfo -> Validate ()
1599 checkPackageId ipi =
1600 let str = display (sourcePackageId ipi) in
1601 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
1602 [_] -> return ()
1603 [] -> verror CannotForce ("invalid package identifier: " ++ str)
1604 _ -> verror CannotForce ("ambiguous package identifier: " ++ str)
1605
1606 checkUnitId :: InstalledPackageInfo -> PackageDBStack -> Bool
1607 -> Validate ()
1608 checkUnitId ipi db_stack update = do
1609 let uid = installedUnitId ipi
1610 when (null (display uid)) $ verror CannotForce "missing id field"
1611 let dups = [ p | p <- allPackagesInStack db_stack,
1612 installedUnitId p == uid ]
1613 when (not update && not (null dups)) $
1614 verror CannotForce $
1615 "package(s) with this id already exist: " ++
1616 unwords (map (display.installedUnitId) dups)
1617
1618 checkDuplicates :: PackageDBStack -> InstalledPackageInfo
1619 -> Bool -> Bool-> Validate ()
1620 checkDuplicates db_stack pkg multi_instance update = do
1621 let
1622 pkgid = sourcePackageId pkg
1623 pkgs = packages (head db_stack)
1624 --
1625 -- Check whether this package id already exists in this DB
1626 --
1627 when (not update && not multi_instance
1628 && (pkgid `elem` map sourcePackageId pkgs)) $
1629 verror CannotForce $
1630 "package " ++ display pkgid ++ " is already installed"
1631
1632 let
1633 uncasep = map toLower . display
1634 dups = filter ((== uncasep pkgid) . uncasep) (map sourcePackageId pkgs)
1635
1636 when (not update && not multi_instance
1637 && not (null dups)) $ verror ForceAll $
1638 "Package names may be treated case-insensitively in the future.\n"++
1639 "Package " ++ display pkgid ++
1640 " overlaps with: " ++ unwords (map display dups)
1641
1642 checkDir, checkFile, checkDirURL :: Bool -> String -> FilePath -> Validate ()
1643 checkDir = checkPath False True
1644 checkFile = checkPath False False
1645 checkDirURL = checkPath True True
1646
1647 checkPath :: Bool -> Bool -> Bool -> String -> FilePath -> Validate ()
1648 checkPath url_ok is_dir warn_only thisfield d
1649 | url_ok && ("http://" `isPrefixOf` d
1650 || "https://" `isPrefixOf` d) = return ()
1651
1652 | url_ok
1653 , Just d' <- stripPrefix "file://" d
1654 = checkPath False is_dir warn_only thisfield d'
1655
1656 -- Note: we don't check for $topdir/${pkgroot} here. We rely on these
1657 -- variables having been expanded already, see mungePackagePaths.
1658
1659 | isRelative d = verror ForceFiles $
1660 thisfield ++ ": " ++ d ++ " is a relative path which "
1661 ++ "makes no sense (as there is nothing for it to be "
1662 ++ "relative to). You can make paths relative to the "
1663 ++ "package database itself by using ${pkgroot}."
1664 -- relative paths don't make any sense; #4134
1665 | otherwise = do
1666 there <- liftIO $ if is_dir then doesDirectoryExist d else doesFileExist d
1667 when (not there) $
1668 let msg = thisfield ++ ": " ++ d ++ " doesn't exist or isn't a "
1669 ++ if is_dir then "directory" else "file"
1670 in
1671 if warn_only
1672 then vwarn msg
1673 else verror ForceFiles msg
1674
1675 checkDep :: PackageDBStack -> UnitId -> Validate ()
1676 checkDep db_stack pkgid
1677 | pkgid `elem` pkgids = return ()
1678 | otherwise = verror ForceAll ("dependency \"" ++ display pkgid
1679 ++ "\" doesn't exist")
1680 where
1681 all_pkgs = allPackagesInStack db_stack
1682 pkgids = map installedUnitId all_pkgs
1683
1684 checkDuplicateDepends :: [UnitId] -> Validate ()
1685 checkDuplicateDepends deps
1686 | null dups = return ()
1687 | otherwise = verror ForceAll ("package has duplicate dependencies: " ++
1688 unwords (map display dups))
1689 where
1690 dups = [ p | (p:_:_) <- group (sort deps) ]
1691
1692 checkHSLib :: Verbosity -> [String] -> String -> Validate ()
1693 checkHSLib _verbosity dirs lib = do
1694 let filenames = ["lib" ++ lib ++ ".a",
1695 "lib" ++ lib ++ ".p_a",
1696 "lib" ++ lib ++ "-ghc" ++ Version.version ++ ".so",
1697 "lib" ++ lib ++ "-ghc" ++ Version.version ++ ".dylib",
1698 lib ++ "-ghc" ++ Version.version ++ ".dll"]
1699 b <- liftIO $ doesFileExistOnPath filenames dirs
1700 when (not b) $
1701 verror ForceFiles ("cannot find any of " ++ show filenames ++
1702 " on library path")
1703
1704 doesFileExistOnPath :: [FilePath] -> [FilePath] -> IO Bool
1705 doesFileExistOnPath filenames paths = anyM doesFileExist fullFilenames
1706 where fullFilenames = [ path </> filename
1707 | filename <- filenames
1708 , path <- paths ]
1709
1710 -- | Perform validation checks (module file existence checks) on the
1711 -- @hidden-modules@ field.
1712 checkOtherModules :: InstalledPackageInfo -> Validate ()
1713 checkOtherModules pkg = mapM_ (checkModuleFile pkg) (hiddenModules pkg)
1714
1715 -- | Perform validation checks (module file existence checks and module
1716 -- reexport checks) on the @exposed-modules@ field.
1717 checkExposedModules :: PackageDBStack -> InstalledPackageInfo -> Validate ()
1718 checkExposedModules db_stack pkg =
1719 mapM_ checkExposedModule (exposedModules pkg)
1720 where
1721 checkExposedModule (ExposedModule modl reexport) = do
1722 let checkOriginal = checkModuleFile pkg modl
1723 checkReexport = checkOriginalModule "module reexport" db_stack pkg
1724 maybe checkOriginal checkReexport reexport
1725
1726 -- | Validates the existence of an appropriate @hi@ file associated with
1727 -- a module. Used for both @hidden-modules@ and @exposed-modules@ which
1728 -- are not reexports.
1729 checkModuleFile :: InstalledPackageInfo -> ModuleName -> Validate ()
1730 checkModuleFile pkg modl =
1731 -- there's no interface file for GHC.Prim
1732 unless (modl == ModuleName.fromString "GHC.Prim") $ do
1733 let files = [ ModuleName.toFilePath modl <.> extension
1734 | extension <- ["hi", "p_hi", "dyn_hi" ] ]
1735 b <- liftIO $ doesFileExistOnPath files (importDirs pkg)
1736 when (not b) $
1737 verror ForceFiles ("cannot find any of " ++ show files)
1738
1739 -- | Validates that @exposed-modules@ and @hidden-modules@ do not have duplicate
1740 -- entries.
1741 -- ToDo: this needs updating for signatures: signatures can validly show up
1742 -- multiple times in the @exposed-modules@ list as long as their backing
1743 -- implementations agree.
1744 checkDuplicateModules :: InstalledPackageInfo -> Validate ()
1745 checkDuplicateModules pkg
1746 | null dups = return ()
1747 | otherwise = verror ForceAll ("package has duplicate modules: " ++
1748 unwords (map display dups))
1749 where
1750 dups = [ m | (m:_:_) <- group (sort mods) ]
1751 mods = map exposedName (exposedModules pkg) ++ hiddenModules pkg
1752
1753 -- | Validates an original module entry, either the origin of a module reexport
1754 -- or the backing implementation of a signature, by checking that it exists,
1755 -- really is an original definition, and is accessible from the dependencies of
1756 -- the package.
1757 -- ToDo: If the original module in question is a backing signature
1758 -- implementation, then we should also check that the original module in
1759 -- question is NOT a signature (however, if it is a reexport, then it's fine
1760 -- for the original module to be a signature.)
1761 checkOriginalModule :: String
1762 -> PackageDBStack
1763 -> InstalledPackageInfo
1764 -> OriginalModule
1765 -> Validate ()
1766 checkOriginalModule field_name db_stack pkg
1767 (OriginalModule definingPkgId definingModule) =
1768 let mpkg = if definingPkgId == installedUnitId pkg
1769 then Just pkg
1770 else PackageIndex.lookupUnitId ipix definingPkgId
1771 in case mpkg of
1772 Nothing
1773 -> verror ForceAll (field_name ++ " refers to a non-existent " ++
1774 "defining package: " ++
1775 display definingPkgId)
1776
1777 Just definingPkg
1778 | not (isIndirectDependency definingPkgId)
1779 -> verror ForceAll (field_name ++ " refers to a defining " ++
1780 "package that is not a direct (or indirect) " ++
1781 "dependency of this package: " ++
1782 display definingPkgId)
1783
1784 | otherwise
1785 -> case find ((==definingModule).exposedName)
1786 (exposedModules definingPkg) of
1787 Nothing ->
1788 verror ForceAll (field_name ++ " refers to a module " ++
1789 display definingModule ++ " " ++
1790 "that is not exposed in the " ++
1791 "defining package " ++ display definingPkgId)
1792 Just (ExposedModule {exposedReexport = Just _} ) ->
1793 verror ForceAll (field_name ++ " refers to a module " ++
1794 display definingModule ++ " " ++
1795 "that is reexported but not defined in the " ++
1796 "defining package " ++ display definingPkgId)
1797 _ -> return ()
1798
1799 where
1800 all_pkgs = allPackagesInStack db_stack
1801 ipix = PackageIndex.fromList all_pkgs
1802
1803 isIndirectDependency pkgid = fromMaybe False $ do
1804 thispkg <- graphVertex (installedUnitId pkg)
1805 otherpkg <- graphVertex pkgid
1806 return (Graph.path depgraph thispkg otherpkg)
1807 (depgraph, _, graphVertex) =
1808 PackageIndex.dependencyGraph (PackageIndex.insert pkg ipix)
1809
1810
1811 -- ---------------------------------------------------------------------------
1812 -- expanding environment variables in the package configuration
1813
1814 expandEnvVars :: String -> Force -> IO String
1815 expandEnvVars str0 force = go str0 ""
1816 where
1817 go "" acc = return $! reverse acc
1818 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1819 = do value <- lookupEnvVar var
1820 go rest (reverse value ++ acc)
1821 where close c = c == '}' || c == '\n' -- don't span newlines
1822 go (c:str) acc
1823 = go str (c:acc)
1824
1825 lookupEnvVar :: String -> IO String
1826 lookupEnvVar "pkgroot" = return "${pkgroot}" -- these two are special,
1827 lookupEnvVar "pkgrooturl" = return "${pkgrooturl}" -- we don't expand them
1828 lookupEnvVar nm =
1829 catchIO (System.Environment.getEnv nm)
1830 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1831 show nm)
1832 return "")
1833
1834 -----------------------------------------------------------------------------
1835
1836 getProgramName :: IO String
1837 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1838 where str `withoutSuffix` suff
1839 | suff `isSuffixOf` str = take (length str - length suff) str
1840 | otherwise = str
1841
1842 bye :: String -> IO a
1843 bye s = putStr s >> exitWith ExitSuccess
1844
1845 die :: String -> IO a
1846 die = dieWith 1
1847
1848 dieWith :: Int -> String -> IO a
1849 dieWith ec s = do
1850 prog <- getProgramName
1851 reportError (prog ++ ": " ++ s)
1852 exitWith (ExitFailure ec)
1853
1854 dieOrForceAll :: Force -> String -> IO ()
1855 dieOrForceAll ForceAll s = ignoreError s
1856 dieOrForceAll _other s = dieForcible s
1857
1858 warn :: String -> IO ()
1859 warn = reportError
1860
1861 -- send info messages to stdout
1862 infoLn :: String -> IO ()
1863 infoLn = putStrLn
1864
1865 info :: String -> IO ()
1866 info = putStr
1867
1868 ignoreError :: String -> IO ()
1869 ignoreError s = reportError (s ++ " (ignoring)")
1870
1871 reportError :: String -> IO ()
1872 reportError s = do hFlush stdout; hPutStrLn stderr s
1873
1874 dieForcible :: String -> IO ()
1875 dieForcible s = die (s ++ " (use --force to override)")
1876
1877 my_head :: String -> [a] -> a
1878 my_head s [] = error s
1879 my_head _ (x : _) = x
1880
1881 -----------------------------------------
1882 -- Cut and pasted from ghc/compiler/main/SysTools
1883
1884 #if defined(mingw32_HOST_OS)
1885 subst :: Char -> Char -> String -> String
1886 subst a b ls = map (\ x -> if x == a then b else x) ls
1887
1888 unDosifyPath :: FilePath -> FilePath
1889 unDosifyPath xs = subst '\\' '/' xs
1890
1891 getLibDir :: IO (Maybe String)
1892 getLibDir = fmap (fmap (</> "lib")) $ getExecDir "/bin/ghc-pkg.exe"
1893
1894 -- (getExecDir cmd) returns the directory in which the current
1895 -- executable, which should be called 'cmd', is running
1896 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1897 -- you'll get "/a/b/c" back as the result
1898 getExecDir :: String -> IO (Maybe String)
1899 getExecDir cmd =
1900 getExecPath >>= maybe (return Nothing) removeCmdSuffix
1901 where initN n = reverse . drop n . reverse
1902 removeCmdSuffix = return . Just . initN (length cmd) . unDosifyPath
1903
1904 getExecPath :: IO (Maybe String)
1905 getExecPath = try_size 2048 -- plenty, PATH_MAX is 512 under Win32.
1906 where
1907 try_size size = allocaArray (fromIntegral size) $ \buf -> do
1908 ret <- c_GetModuleFileName nullPtr buf size
1909 case ret of
1910 0 -> return Nothing
1911 _ | ret < size -> fmap Just $ peekCWString buf
1912 | otherwise -> try_size (size * 2)
1913
1914 foreign import WINDOWS_CCONV unsafe "windows.h GetModuleFileNameW"
1915 c_GetModuleFileName :: Ptr () -> CWString -> Word32 -> IO Word32
1916 #else
1917 getLibDir :: IO (Maybe String)
1918 getLibDir = return Nothing
1919 #endif
1920
1921 -----------------------------------------
1922 -- Adapted from ghc/compiler/utils/Panic
1923
1924 installSignalHandlers :: IO ()
1925 installSignalHandlers = do
1926 threadid <- myThreadId
1927 let
1928 interrupt = Exception.throwTo threadid
1929 (Exception.ErrorCall "interrupted")
1930 --
1931 #if !defined(mingw32_HOST_OS)
1932 _ <- installHandler sigQUIT (Catch interrupt) Nothing
1933 _ <- installHandler sigINT (Catch interrupt) Nothing
1934 return ()
1935 #else
1936 -- GHC 6.3+ has support for console events on Windows
1937 -- NOTE: running GHCi under a bash shell for some reason requires
1938 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1939 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1940 -- why --SDM 17/12/2004
1941 let sig_handler ControlC = interrupt
1942 sig_handler Break = interrupt
1943 sig_handler _ = return ()
1944
1945 _ <- installHandler (Catch sig_handler)
1946 return ()
1947 #endif
1948
1949 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1950 catchIO = Exception.catch
1951
1952 tryIO :: IO a -> IO (Either Exception.IOException a)
1953 tryIO = Exception.try
1954
1955 -- removeFileSave doesn't throw an exceptions, if the file is already deleted
1956 removeFileSafe :: FilePath -> IO ()
1957 removeFileSafe fn =
1958 removeFile fn `catchIO` \ e ->
1959 when (not $ isDoesNotExistError e) $ ioError e
1960
1961 -- | Turn a path relative to the current directory into a (normalised)
1962 -- absolute path.
1963 absolutePath :: FilePath -> IO FilePath
1964 absolutePath path = return . normalise . (</> path) =<< getCurrentDirectory
1965
1966
1967 {- Note [writeAtomic leaky abstraction]
1968 GhcPkg.writePackageDb calls writeAtomic, which first writes to a temp file,
1969 and then moves the tempfile to its final destination. This all happens in the
1970 same directory (package.conf.d).
1971 Moving a file doesn't change its modification time, but it *does* change the
1972 modification time of the directory it is placed in. Since we compare the
1973 modification time of the cache file to that of the directory it is in to
1974 decide whether the cache is out-of-date, it will be instantly out-of-date
1975 after creation, if the renaming takes longer than the smallest time difference
1976 that the getModificationTime can measure.
1977
1978 The solution we opt for is a "touch" of the cache file right after it is
1979 created. This resets the modification time of the cache file and the directory
1980 to the current time.
1981
1982 Other possible solutions:
1983 * backdate the modification time of the directory to the modification time
1984 of the cachefile. This is what we used to do on posix platforms. An
1985 observer of the directory would see the modification time of the directory
1986 jump back in time. Not nice, although in practice probably not a problem.
1987 Also note that a cross-platform implementation of setModificationTime is
1988 currently not available.
1989 * set the modification time of the cache file to the modification time of
1990 the directory (instead of the curent time). This could also work,
1991 given that we are the only ones writing to this directory. It would also
1992 require a high-precision getModificationTime (lower precision times get
1993 rounded down it seems), or the cache would still be out-of-date.
1994 * change writeAtomic to create the tempfile outside of the target file's
1995 directory.
1996 * create the cachefile outside of the package.conf.d directory in the first
1997 place. But there are tests and there might be tools that currently rely on
1998 the package.conf.d/package.cache format.
1999 -}