1 {-# OPTIONS -fglasgow-exts -cpp #-}
2 -----------------------------------------------------------------------------
4 -- (c) The University of Glasgow 2004.
6 -- Package management tool
8 -----------------------------------------------------------------------------
12 -- * expanding of variables in new-style package conf
13 -- * version manipulation (checking whether old version exists,
14 -- hiding old version?)
16 module Main (main) where
18 import Version ( version, targetOS, targetARCH )
19 import Distribution.ModuleName hiding (main)
20 import Distribution.InstalledPackageInfo hiding (depends)
21 import Distribution.Compat.ReadP
22 import Distribution.ParseUtils
23 import Distribution.Package
24 import Distribution.Text
25 import Distribution.Version
26 import System.FilePath
27 import System.Cmd ( rawSystem )
28 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
32 #include "../../includes/ghcconfig.h"
34 import System.Console.GetOpt
35 import Text.PrettyPrint
36 #if __GLASGOW_HASKELL__ >= 609
37 import qualified Control.Exception as Exception
39 import qualified Control.Exception.Extensible as Exception
43 import Data.Char ( isSpace, toLower )
45 import System.Directory ( doesDirectoryExist, getDirectoryContents,
46 doesFileExist, renameFile, removeFile )
47 import System.Exit ( exitWith, ExitCode(..) )
48 import System.Environment ( getArgs, getProgName, getEnv )
50 import System.IO.Error (try)
52 import Control.Concurrent
56 #ifdef mingw32_HOST_OS
57 import GHC.ConsoleHandler
59 import System.Posix hiding (fdToHandle)
62 import IO ( isPermissionError )
63 import System.Posix.Internals
64 import GHC.Handle (fdToHandle)
67 import System.Process(runInteractiveCommand)
68 import qualified System.Info(os)
71 -- -----------------------------------------------------------------------------
78 case getOpt Permute (flags ++ deprecFlags) args of
79 (cli,_,[]) | FlagHelp `elem` cli -> do
80 prog <- getProgramName
81 bye (usageInfo (usageHeader prog) flags)
82 (cli,_,[]) | FlagVersion `elem` cli ->
87 prog <- getProgramName
88 die (concat errors ++ usageInfo (usageHeader prog) flags)
90 -- -----------------------------------------------------------------------------
91 -- Command-line syntax
99 | FlagGlobalConfig FilePath
109 flags :: [OptDescr Flag]
111 Option [] ["user"] (NoArg FlagUser)
112 "use the current user's package database",
113 Option [] ["global"] (NoArg FlagGlobal)
114 "use the global package database",
115 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
116 "use the specified package config file",
117 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
118 "location of the global package config",
119 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
120 "never read the user package database",
121 Option [] ["force"] (NoArg FlagForce)
122 "ignore missing dependencies, directories, and libraries",
123 Option [] ["force-files"] (NoArg FlagForceFiles)
124 "ignore missing directories and libraries only",
125 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
126 "automatically build libs for GHCi (with register)",
127 Option ['?'] ["help"] (NoArg FlagHelp)
128 "display this help and exit",
129 Option ['V'] ["version"] (NoArg FlagVersion)
130 "output version information and exit",
131 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
132 "print output in easy-to-parse format for some commands",
133 Option [] ["names-only"] (NoArg FlagNamesOnly)
134 "only print package names, not versions; can only be used with list --simple-output",
135 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
136 "ignore case for substring matching"
139 deprecFlags :: [OptDescr Flag]
141 -- put deprecated flags here
144 ourCopyright :: String
145 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
147 usageHeader :: String -> String
148 usageHeader prog = substProg prog $
150 " $p register {filename | -}\n" ++
151 " Register the package using the specified installed package\n" ++
152 " description. The syntax for the latter is given in the $p\n" ++
153 " documentation.\n" ++
155 " $p update {filename | -}\n" ++
156 " Register the package, overwriting any other package with the\n" ++
159 " $p unregister {pkg-id}\n" ++
160 " Unregister the specified package.\n" ++
162 " $p expose {pkg-id}\n" ++
163 " Expose the specified package.\n" ++
165 " $p hide {pkg-id}\n" ++
166 " Hide the specified package.\n" ++
168 " $p list [pkg]\n" ++
169 " List registered packages in the global database, and also the\n" ++
170 " user database if --user is given. If a package name is given\n" ++
171 " all the registered versions will be listed in ascending order.\n" ++
172 " Accepts the --simple-output flag.\n" ++
174 " $p find-module {module}\n" ++
175 " List registered packages exposing module {module} in the global\n" ++
176 " database, and also the user database if --user is given.\n" ++
177 " All the registered versions will be listed in ascending order.\n" ++
178 " Accepts the --simple-output flag.\n" ++
180 " $p latest {pkg-id}\n" ++
181 " Prints the highest registered version of a package.\n" ++
184 " Check the consistency of package depenencies and list broken packages.\n" ++
185 " Accepts the --simple-output flag.\n" ++
187 " $p describe {pkg}\n" ++
188 " Give the registered description for the specified package. The\n" ++
189 " description is returned in precisely the syntax required by $p\n" ++
192 " $p field {pkg} {field}\n" ++
193 " Extract the specified field of the package description for the\n" ++
194 " specified package. Accepts comma-separated multiple fields.\n" ++
197 " Dump the registered description for every package. This is like\n" ++
198 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
199 " by tools that parse the results, rather than humans.\n" ++
201 " Substring matching is supported for {module} in find-module and\n" ++
202 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
203 " open substring ends (prefix*, *suffix, *infix*).\n" ++
205 " When asked to modify a database (register, unregister, update,\n"++
206 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
207 " default. Specifying --user causes it to act on the user database,\n"++
208 " or --package-conf can be used to act on another database\n"++
209 " entirely. When multiple of these options are given, the rightmost\n"++
210 " one is used as the database to act upon.\n"++
212 " Commands that query the package database (list, latest, describe,\n"++
213 " field) operate on the list of databases specified by the flags\n"++
214 " --user, --global, and --package-conf. If none of these flags are\n"++
215 " given, the default is --global --user.\n"++
217 " The following optional flags are also accepted:\n"
219 substProg :: String -> String -> String
221 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
222 substProg prog (c:xs) = c : substProg prog xs
224 -- -----------------------------------------------------------------------------
227 data Force = NoForce | ForceFiles | ForceAll | CannotForce
230 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
232 runit :: [Flag] -> [String] -> IO ()
233 runit cli nonopts = do
234 installSignalHandlers -- catch ^C and clean up
235 prog <- getProgramName
238 | FlagForce `elem` cli = ForceAll
239 | FlagForceFiles `elem` cli = ForceFiles
240 | otherwise = NoForce
241 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
242 splitFields fields = unfoldr splitComma (',':fields)
243 where splitComma "" = Nothing
244 splitComma fs = Just $ break (==',') (tail fs)
246 substringCheck :: String -> Maybe (String -> Bool)
247 substringCheck "" = Nothing
248 substringCheck "*" = Just (const True)
249 substringCheck [_] = Nothing
250 substringCheck (h:t) =
251 case (h, init t, last t) of
252 ('*',s,'*') -> Just (isInfixOf (f s) . f)
253 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
254 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
256 where f | FlagIgnoreCase `elem` cli = map toLower
259 glob x | System.Info.os=="mingw32" = do
260 -- glob echoes its argument, after win32 filename globbing
261 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
262 txt <- hGetContents o
264 glob x | otherwise = return [x]
267 -- first, parse the command
270 -- dummy command to demonstrate usage and permit testing
271 -- without messing things up; use glob to selectively enable
272 -- windows filename globbing for file parameters
273 -- register, update, FlagGlobalConfig, FlagConfig; others?
274 ["glob", filename] -> do
276 glob filename >>= print
278 ["register", filename] ->
279 registerPackage filename cli auto_ghci_libs False force
280 ["update", filename] ->
281 registerPackage filename cli auto_ghci_libs True force
282 ["unregister", pkgid_str] -> do
283 pkgid <- readGlobPkgId pkgid_str
284 unregisterPackage pkgid cli force
285 ["expose", pkgid_str] -> do
286 pkgid <- readGlobPkgId pkgid_str
287 exposePackage pkgid cli force
288 ["hide", pkgid_str] -> do
289 pkgid <- readGlobPkgId pkgid_str
290 hidePackage pkgid cli force
292 listPackages cli Nothing Nothing
293 ["list", pkgid_str] ->
294 case substringCheck pkgid_str of
295 Nothing -> do pkgid <- readGlobPkgId pkgid_str
296 listPackages cli (Just (Id pkgid)) Nothing
297 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
298 ["find-module", moduleName] -> do
299 let match = maybe (==moduleName) id (substringCheck moduleName)
300 listPackages cli Nothing (Just match)
301 ["latest", pkgid_str] -> do
302 pkgid <- readGlobPkgId pkgid_str
303 latestPackage cli pkgid
304 ["describe", pkgid_str] ->
305 case substringCheck pkgid_str of
306 Nothing -> do pkgid <- readGlobPkgId pkgid_str
307 describePackage cli (Id pkgid)
308 Just m -> describePackage cli (Substring pkgid_str m)
309 ["field", pkgid_str, fields] ->
310 case substringCheck pkgid_str of
311 Nothing -> do pkgid <- readGlobPkgId pkgid_str
312 describeField cli (Id pkgid) (splitFields fields)
313 Just m -> describeField cli (Substring pkgid_str m)
322 die ("missing command\n" ++
323 usageInfo (usageHeader prog) flags)
325 die ("command-line syntax error\n" ++
326 usageInfo (usageHeader prog) flags)
328 parseCheck :: ReadP a a -> String -> String -> IO a
329 parseCheck parser str what =
330 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
332 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
334 readGlobPkgId :: String -> IO PackageIdentifier
335 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
337 parseGlobPackageId :: ReadP r PackageIdentifier
343 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
345 -- globVersion means "all versions"
346 globVersion :: Version
347 globVersion = Version{ versionBranch=[], versionTags=["*"] }
349 -- -----------------------------------------------------------------------------
352 -- Some commands operate on a single database:
353 -- register, unregister, expose, hide
354 -- however these commands also check the union of the available databases
355 -- in order to check consistency. For example, register will check that
356 -- dependencies exist before registering a package.
358 -- Some commands operate on multiple databases, with overlapping semantics:
359 -- list, describe, field
361 type PackageDBName = FilePath
362 type PackageDB = [InstalledPackageInfo]
364 type NamedPackageDB = (PackageDBName, PackageDB)
365 type PackageDBStack = [NamedPackageDB]
366 -- A stack of package databases. Convention: head is the topmost
367 -- in the stack. Earlier entries override later one.
369 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
370 allPackagesInStack = concatMap snd
372 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
373 getPkgDatabases modify my_flags = do
374 -- first we determine the location of the global package config. On Windows,
375 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
376 -- location is passed to the binary using the --global-config flag by the
378 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
380 case [ f | FlagGlobalConfig f <- my_flags ] of
381 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
383 Nothing -> die err_msg
385 do let path1 = dir </> "package.conf"
386 path2 = dir </> ".." </> ".." </> ".."
387 </> "inplace-datadir"
389 exists1 <- doesFileExist path1
390 exists2 <- doesFileExist path2
391 if exists1 then return path1
392 else if exists2 then return path2
393 else die "Can't find package.conf"
394 fs -> return (last fs)
396 let global_conf_dir = global_conf ++ ".d"
397 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
399 if global_conf_dir_exists
400 then do files <- getDirectoryContents global_conf_dir
401 return [ global_conf_dir ++ '/' : file
403 , isSuffixOf ".conf" file]
406 let no_user_db = FlagNoUserDb `elem` my_flags
408 -- get the location of the user package database, and create it if necessary
409 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
410 appdir <- try $ getAppUserDataDirectory "ghc"
413 if no_user_db then return Nothing else
416 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
417 user_conf = dir </> subdir </> "package.conf"
418 user_exists <- doesFileExist user_conf
419 return (Just (user_conf,user_exists))
423 -- If the user database doesn't exist, and this command isn't a
424 -- "modify" command, then we won't attempt to create or use it.
426 | Just (user_conf,user_exists) <- mb_user_conf,
427 modify || user_exists = user_conf : global_confs ++ [global_conf]
428 | otherwise = global_confs ++ [global_conf]
430 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
433 Left _ -> sys_databases
435 | last cs == "" -> init cs ++ sys_databases
437 where cs = parseSearchPath path
439 -- The "global" database is always the one at the bottom of the stack.
440 -- This is the database we modify by default.
441 virt_global_conf = last env_stack
443 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
444 where is_db_flag FlagUser
445 | Just (user_conf, _user_exists) <- mb_user_conf
447 is_db_flag FlagGlobal = Just virt_global_conf
448 is_db_flag (FlagConfig f) = Just f
449 is_db_flag _ = Nothing
451 (final_stack, to_modify) <-
453 then -- For a "read" command, we use all the databases
454 -- specified on the command line. If there are no
455 -- command-line flags specifying databases, the default
456 -- is to use all the ones we know about.
457 if null db_flags then return (env_stack, Nothing)
458 else return (reverse (nub db_flags), Nothing)
460 -- For a "modify" command, treat all the databases as
461 -- a stack, where we are modifying the top one, but it
462 -- can refer to packages in databases further down the
465 -- -f flags on the command line add to the database
466 -- stack, unless any of them are present in the stack
468 flag_stack = filter (`notElem` env_stack)
469 [ f | FlagConfig f <- reverse my_flags ]
472 -- the database we actually modify is the one mentioned
473 -- rightmost on the command-line.
474 to_modify = if null db_flags
475 then Just virt_global_conf
476 else Just (last db_flags)
478 return (flag_stack, to_modify)
480 db_stack <- mapM (readParseDatabase mb_user_conf) final_stack
481 return (db_stack, to_modify)
483 readParseDatabase :: Maybe (PackageDBName,Bool)
485 -> IO (PackageDBName,PackageDB)
486 readParseDatabase mb_user_conf filename
487 -- the user database (only) is allowed to be non-existent
488 | Just (user_conf,False) <- mb_user_conf, filename == user_conf
489 = return (filename, [])
491 = do str <- readFile filename
492 let packages = map convertPackageInfoIn $ read str
493 Exception.evaluate packages
495 die ("error while parsing " ++ filename ++ ": " ++ show e)
496 return (filename,packages)
498 -- -----------------------------------------------------------------------------
501 registerPackage :: FilePath
503 -> Bool -- auto_ghci_libs
507 registerPackage input my_flags auto_ghci_libs update force = do
508 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
510 db_to_operate_on = my_head "register" $
511 filter ((== to_modify).fst) db_stack
516 putStr "Reading package info from stdin ... "
519 putStr ("Reading package info from " ++ show f ++ " ... ")
522 expanded <- expandEnvVars s force
524 pkg <- parsePackageInfo expanded
527 let unversioned_deps = filter (not . realVersion) (depends pkg)
528 unless (null unversioned_deps) $
529 die ("Unversioned dependencies found: " ++
530 unwords (map display unversioned_deps))
532 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
533 -- truncate the stack for validation, because we don't allow
534 -- packages lower in the stack to refer to those higher up.
535 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
536 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
537 not_this p = package p /= package pkg
538 writeNewConfig to_modify new_details
542 -> IO InstalledPackageInfo
543 parsePackageInfo str =
544 case parseInstalledPackageInfo str of
545 ParseOk _warns ok -> return ok
546 ParseFailed err -> case locatedErrorMsg err of
547 (Nothing, s) -> die s
548 (Just l, s) -> die (show l ++ ": " ++ s)
550 -- -----------------------------------------------------------------------------
551 -- Exposing, Hiding, Unregistering are all similar
553 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
554 exposePackage = modifyPackage (\p -> [p{exposed=True}])
556 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
557 hidePackage = modifyPackage (\p -> [p{exposed=False}])
559 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
560 unregisterPackage = modifyPackage (\_ -> [])
563 :: (InstalledPackageInfo -> [InstalledPackageInfo])
568 modifyPackage fn pkgid my_flags force = do
569 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
570 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
571 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
572 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
574 pids = map package ps
576 | package pkg `elem` pids = fn pkg
578 new_config = concat (map modify pkgs)
581 old_broken = brokenPackages (allPackagesInStack db_stack)
582 rest_of_stack = [ (nm, mypkgs)
583 | (nm, mypkgs) <- db_stack, nm /= db_name ]
584 new_stack = (db_name,new_config) : rest_of_stack
585 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
586 newly_broken = filter (`notElem` map package old_broken) new_broken
588 when (not (null newly_broken)) $
589 dieOrForceAll force ("unregistering " ++ display pkgid ++
590 " would break the following packages: "
591 ++ unwords (map display newly_broken))
593 writeNewConfig db_name new_config
595 -- -----------------------------------------------------------------------------
598 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
599 listPackages my_flags mPackageName mModuleName = do
600 let simple_output = FlagSimpleOutput `elem` my_flags
601 (db_stack, _) <- getPkgDatabases False my_flags
602 let db_stack_filtered -- if a package is given, filter out all other packages
603 | Just this <- mPackageName =
604 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
606 | Just match <- mModuleName = -- packages which expose mModuleName
607 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
609 | otherwise = db_stack
612 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
613 where sort_pkgs = sortBy cmpPkgIds
614 cmpPkgIds pkg1 pkg2 =
615 case pkgName p1 `compare` pkgName p2 of
618 EQ -> pkgVersion p1 `compare` pkgVersion p2
619 where (p1,p2) = (package pkg1, package pkg2)
621 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
623 pkg_map = allPackagesInStack db_stack
624 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
626 show_func (reverse db_stack_sorted)
628 where show_normal pkg_map (db_name,pkg_confs) =
629 hPutStrLn stdout (render $
630 text db_name <> colon $$ nest 4 packages
632 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
633 broken = map package (brokenPackages pkg_map)
635 | package p `elem` broken = braces doc
637 | otherwise = parens doc
638 where doc = text (display (package p))
640 show_simple = simplePackageList my_flags . allPackagesInStack
642 simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
643 simplePackageList my_flags pkgs = do
644 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
646 strs = map showPkg $ sortBy compPkgIdVer $ map package pkgs
647 when (not (null pkgs)) $
648 hPutStrLn stdout $ concat $ intersperse " " strs
650 -- -----------------------------------------------------------------------------
651 -- Prints the highest (hidden or exposed) version of a package
653 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
654 latestPackage my_flags pkgid = do
655 (db_stack, _) <- getPkgDatabases False my_flags
656 ps <- findPackages db_stack (Id pkgid)
657 show_pkg (sortBy compPkgIdVer (map package ps))
659 show_pkg [] = die "no matches"
660 show_pkg pids = hPutStrLn stdout (display (last pids))
662 -- -----------------------------------------------------------------------------
665 describePackage :: [Flag] -> PackageArg -> IO ()
666 describePackage my_flags pkgarg = do
667 (db_stack, _) <- getPkgDatabases False my_flags
668 ps <- findPackages db_stack pkgarg
671 dumpPackages :: [Flag] -> IO ()
672 dumpPackages my_flags = do
673 (db_stack, _) <- getPkgDatabases False my_flags
674 doDump (allPackagesInStack db_stack)
676 doDump :: [InstalledPackageInfo] -> IO ()
677 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
679 -- PackageId is can have globVersion for the version
680 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
681 findPackages db_stack pkgarg
682 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
684 findPackagesByDB :: PackageDBStack -> PackageArg
685 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
686 findPackagesByDB db_stack pkgarg
687 = case [ (db, matched)
688 | db@(_, pkgs) <- db_stack,
689 let matched = filter (pkgarg `matchesPkg`) pkgs,
690 not (null matched) ] of
691 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
694 pkg_msg (Id pkgid) = display pkgid
695 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
697 matches :: PackageIdentifier -> PackageIdentifier -> Bool
699 = (pkgName pid == pkgName pid')
700 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
702 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
703 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
704 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
706 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
707 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
709 -- -----------------------------------------------------------------------------
712 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
713 describeField my_flags pkgarg fields = do
714 (db_stack, _) <- getPkgDatabases False my_flags
715 fns <- toFields fields
716 ps <- findPackages db_stack pkgarg
717 let top_dir = takeDirectory (fst (last db_stack))
718 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
719 where toFields [] = return []
720 toFields (f:fs) = case toField f of
721 Nothing -> die ("unknown field: " ++ f)
722 Just fn -> do fns <- toFields fs
724 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
726 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
727 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
728 -- with the current topdir (obtained from the -B option).
729 mungePackagePaths top_dir ps = map munge_pkg ps
731 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
732 includeDirs = munge_paths (includeDirs p),
733 libraryDirs = munge_paths (libraryDirs p),
734 frameworkDirs = munge_paths (frameworkDirs p),
735 haddockInterfaces = munge_paths (haddockInterfaces p),
736 haddockHTMLs = munge_paths (haddockHTMLs p)
739 munge_paths = map munge_path
742 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
743 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
746 toHttpPath p = "file:///" ++ p
748 maybePrefixMatch :: String -> String -> Maybe String
749 maybePrefixMatch [] rest = Just rest
750 maybePrefixMatch (_:_) [] = Nothing
751 maybePrefixMatch (p:pat) (r:rest)
752 | p == r = maybePrefixMatch pat rest
753 | otherwise = Nothing
755 toField :: String -> Maybe (InstalledPackageInfo -> String)
756 -- backwards compatibility:
757 toField "import_dirs" = Just $ strList . importDirs
758 toField "source_dirs" = Just $ strList . importDirs
759 toField "library_dirs" = Just $ strList . libraryDirs
760 toField "hs_libraries" = Just $ strList . hsLibraries
761 toField "extra_libraries" = Just $ strList . extraLibraries
762 toField "include_dirs" = Just $ strList . includeDirs
763 toField "c_includes" = Just $ strList . includes
764 toField "package_deps" = Just $ strList . map display. depends
765 toField "extra_cc_opts" = Just $ strList . ccOptions
766 toField "extra_ld_opts" = Just $ strList . ldOptions
767 toField "framework_dirs" = Just $ strList . frameworkDirs
768 toField "extra_frameworks"= Just $ strList . frameworks
769 toField s = showInstalledPackageInfoField s
771 strList :: [String] -> String
775 -- -----------------------------------------------------------------------------
776 -- Check: Check consistency of installed packages
778 checkConsistency :: [Flag] -> IO ()
779 checkConsistency my_flags = do
780 (db_stack, _) <- getPkgDatabases True my_flags
781 -- check behaves like modify for the purposes of deciding which
782 -- databases to use, because ordering is important.
784 let simple_output = FlagSimpleOutput `elem` my_flags
786 let pkgs = allPackagesInStack db_stack
789 (_,es) <- runValidate $ checkPackageConfig p db_stack False True
793 when (not simple_output) $ do
794 reportError ("There are problems in package " ++ display (package p) ++ ":")
795 reportValidateErrors es " " Nothing
799 broken_pkgs <- concat `fmap` mapM checkPackage pkgs
801 let filterOut pkgs1 pkgs2 = filter not_in pkgs2
802 where not_in p = package p `notElem` all_ps
803 all_ps = map package pkgs1
805 let not_broken_pkgs = filterOut broken_pkgs pkgs
806 (_, trans_broken_pkgs) = closure [] not_broken_pkgs
807 all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
809 when (not (null all_broken_pkgs)) $ do
811 then simplePackageList my_flags all_broken_pkgs
813 reportError ("\nThe following packages are broken, either because they have a problem\n"++
814 "listed above, or because they depend on a broken package.")
815 mapM_ (hPutStrLn stderr . display . package) all_broken_pkgs
817 when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
820 closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
821 -> ([InstalledPackageInfo], [InstalledPackageInfo])
822 closure pkgs db_stack = go pkgs db_stack
825 case partition (depsAvailable avail) not_avail of
826 ([], not_avail') -> (avail, not_avail')
827 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
829 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
831 depsAvailable pkgs_ok pkg = null dangling
832 where dangling = filter (`notElem` pids) (depends pkg)
833 pids = map package pkgs_ok
835 -- we want mutually recursive groups of package to show up
836 -- as broken. (#1750)
838 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
839 brokenPackages pkgs = snd (closure [] pkgs)
841 -- -----------------------------------------------------------------------------
842 -- Manipulating package.conf files
844 type InstalledPackageInfoString = InstalledPackageInfo_ String
846 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
847 convertPackageInfoOut
848 (pkgconf@(InstalledPackageInfo { exposedModules = e,
849 hiddenModules = h })) =
850 pkgconf{ exposedModules = map display e,
851 hiddenModules = map display h }
853 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
855 (pkgconf@(InstalledPackageInfo { exposedModules = e,
856 hiddenModules = h })) =
857 pkgconf{ exposedModules = map convert e,
858 hiddenModules = map convert h }
859 where convert = fromJust . simpleParse
861 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
862 writeNewConfig filename packages = do
863 hPutStr stdout "Writing new package config file... "
864 createDirectoryIfMissing True $ takeDirectory filename
865 let shown = concat $ intersperse ",\n "
866 $ map (show . convertPackageInfoOut) packages
867 fileContents = "[" ++ shown ++ "\n]"
868 writeFileAtomic filename fileContents
870 if isPermissionError e
871 then die (filename ++ ": you don't have permission to modify this file")
873 hPutStrLn stdout "done."
875 -----------------------------------------------------------------------------
876 -- Sanity-check a new package config, and automatically build GHCi libs
879 type ValidateError = (Force,String)
881 newtype Validate a = V { runValidate :: IO (a, [ValidateError]) }
883 instance Monad Validate where
884 return a = V $ return (a, [])
886 (a, es) <- runValidate m
887 (b, es') <- runValidate (k a)
890 verror :: Force -> String -> Validate ()
891 verror f s = V (return ((),[(f,s)]))
893 liftIO :: IO a -> Validate a
894 liftIO k = V (k >>= \a -> return (a,[]))
896 -- returns False if we should die
897 reportValidateErrors :: [ValidateError] -> String -> Maybe Force -> IO Bool
898 reportValidateErrors es prefix mb_force = do
899 oks <- mapM report es
903 | Just force <- mb_force
905 then do reportError (prefix ++ s ++ " (ignoring)")
907 else if f < CannotForce
908 then do reportError (prefix ++ s ++ " (use --force to override)")
910 else do reportError err
912 | otherwise = do reportError err
917 validatePackageConfig :: InstalledPackageInfo
919 -> Bool -- auto-ghc-libs
920 -> Bool -- update, or check
923 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
924 (_,es) <- runValidate $ checkPackageConfig pkg db_stack auto_ghci_libs update
925 ok <- reportValidateErrors es (display (package pkg) ++ ": ") (Just force)
926 when (not ok) $ exitWith (ExitFailure 1)
928 checkPackageConfig :: InstalledPackageInfo
930 -> Bool -- auto-ghc-libs
931 -> Bool -- update, or check
933 checkPackageConfig pkg db_stack auto_ghci_libs update = do
935 checkDuplicates db_stack pkg update
936 mapM_ (checkDep db_stack) (depends pkg)
937 checkDuplicateDepends (depends pkg)
938 mapM_ (checkDir "import-dirs") (importDirs pkg)
939 mapM_ (checkDir "library-dirs") (libraryDirs pkg)
940 mapM_ (checkDir "include-dirs") (includeDirs pkg)
942 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg)
943 -- ToDo: check these somehow?
944 -- extra_libraries :: [String],
945 -- c_includes :: [String],
947 -- When the package name and version are put together, sometimes we can
948 -- end up with a package id that cannot be parsed. This will lead to
949 -- difficulties when the user wants to refer to the package later, so
950 -- we check that the package id can be parsed properly here.
951 checkPackageId :: InstalledPackageInfo -> Validate ()
953 let str = display (package ipi) in
954 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
956 [] -> verror CannotForce ("invalid package identifier: " ++ str)
957 _ -> verror CannotForce ("ambiguous package identifier: " ++ str)
959 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Validate ()
960 checkDuplicates db_stack pkg update = do
963 (_top_db_name, pkgs) : _ = db_stack
965 -- Check whether this package id already exists in this DB
967 when (not update && (pkgid `elem` map package pkgs)) $
969 "package " ++ display pkgid ++ " is already installed"
972 uncasep = map toLower . display
973 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
975 when (not update && not (null dups)) $ verror ForceAll $
976 "Package names may be treated case-insensitively in the future.\n"++
977 "Package " ++ display pkgid ++
978 " overlaps with: " ++ unwords (map display dups)
981 checkDir :: String -> String -> Validate ()
983 | "$topdir" `isPrefixOf` d = return ()
984 | "$httptopdir" `isPrefixOf` d = return ()
985 -- can't check these, because we don't know what $(http)topdir is
987 there <- liftIO $ doesDirectoryExist d
989 verror ForceFiles (thisfield ++ ": " ++ d ++ " doesn't exist or isn't a directory")
991 checkDep :: PackageDBStack -> PackageIdentifier -> Validate ()
992 checkDep db_stack pkgid
993 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
994 | otherwise = verror ForceAll ("dependency " ++ display pkgid
997 -- for backwards compat, we treat 0.0 as a special version,
998 -- and don't check that it actually exists.
999 real_version = realVersion pkgid
1001 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
1002 name = pkgName pkgid
1004 all_pkgs = allPackagesInStack db_stack
1005 pkgids = map package all_pkgs
1007 checkDuplicateDepends :: [PackageIdentifier] -> Validate ()
1008 checkDuplicateDepends deps
1009 | null dups = return ()
1010 | otherwise = verror ForceAll ("package has duplicate dependencies: " ++
1011 unwords (map display dups))
1013 dups = [ p | (p:_:_) <- group (sort deps) ]
1015 realVersion :: PackageIdentifier -> Bool
1016 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
1018 checkHSLib :: [String] -> Bool -> String -> Validate ()
1019 checkHSLib dirs auto_ghci_libs lib = do
1020 let batch_lib_file = "lib" ++ lib ++ ".a"
1021 m <- liftIO $ doesFileExistOnPath batch_lib_file dirs
1023 Nothing -> verror ForceFiles ("cannot find " ++ batch_lib_file ++
1025 Just dir -> liftIO $ checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
1027 doesFileExistOnPath :: String -> [FilePath] -> IO (Maybe FilePath)
1028 doesFileExistOnPath file path = go path
1029 where go [] = return Nothing
1030 go (p:ps) = do b <- doesFileExistIn file p
1031 if b then return (Just p) else go ps
1033 doesFileExistIn :: String -> String -> IO Bool
1034 doesFileExistIn lib d
1035 | "$topdir" `isPrefixOf` d = return True
1036 | "$httptopdir" `isPrefixOf` d = return True
1037 | otherwise = doesFileExist (d </> lib)
1039 checkModules :: InstalledPackageInfo -> Validate ()
1040 checkModules pkg = do
1041 mapM_ findModule (exposedModules pkg ++ hiddenModules pkg)
1043 findModule modl = do
1044 -- there's no .hi file for GHC.Prim
1045 if modl == fromString "GHC.Prim" then return () else do
1046 let file = toFilePath modl <.> "hi"
1047 m <- liftIO $ doesFileExistOnPath file (importDirs pkg)
1048 when (isNothing m) $
1049 verror ForceFiles ("file " ++ file ++ " is missing")
1051 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
1052 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
1053 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
1055 m <- doesFileExistOnPath ghci_lib_file dirs
1056 when (isNothing m) $
1057 hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
1059 ghci_lib_file = lib <.> "o"
1061 -- automatically build the GHCi version of a batch lib,
1062 -- using ld --whole-archive.
1064 autoBuildGHCiLib :: String -> String -> String -> IO ()
1065 autoBuildGHCiLib dir batch_file ghci_file = do
1066 let ghci_lib_file = dir ++ '/':ghci_file
1067 batch_lib_file = dir ++ '/':batch_file
1068 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
1069 #if defined(darwin_HOST_OS)
1070 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
1071 #elif defined(mingw32_HOST_OS)
1072 execDir <- getExecDir "/bin/ghc-pkg.exe"
1073 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1075 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1077 when (r /= ExitSuccess) $ exitWith r
1078 hPutStrLn stderr (" done.")
1080 -- -----------------------------------------------------------------------------
1081 -- Searching for modules
1085 findModules :: [FilePath] -> IO [String]
1087 mms <- mapM searchDir paths
1090 searchDir path prefix = do
1091 fs <- getDirectoryEntries path `catch` \_ -> return []
1092 searchEntries path prefix fs
1094 searchEntries path prefix [] = return []
1095 searchEntries path prefix (f:fs)
1096 | looks_like_a_module = do
1097 ms <- searchEntries path prefix fs
1098 return (prefix `joinModule` f : ms)
1099 | looks_like_a_component = do
1100 ms <- searchDir (path </> f) (prefix `joinModule` f)
1101 ms' <- searchEntries path prefix fs
1104 searchEntries path prefix fs
1107 (base,suffix) = splitFileExt f
1108 looks_like_a_module =
1109 suffix `elem` haskell_suffixes &&
1110 all okInModuleName base
1111 looks_like_a_component =
1112 null suffix && all okInModuleName base
1118 -- ---------------------------------------------------------------------------
1119 -- expanding environment variables in the package configuration
1121 expandEnvVars :: String -> Force -> IO String
1122 expandEnvVars str0 force = go str0 ""
1124 go "" acc = return $! reverse acc
1125 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1126 = do value <- lookupEnvVar var
1127 go rest (reverse value ++ acc)
1128 where close c = c == '}' || c == '\n' -- don't span newlines
1132 lookupEnvVar :: String -> IO String
1134 catch (System.Environment.getEnv nm)
1135 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1139 -----------------------------------------------------------------------------
1141 getProgramName :: IO String
1142 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1143 where str `withoutSuffix` suff
1144 | suff `isSuffixOf` str = take (length str - length suff) str
1147 bye :: String -> IO a
1148 bye s = putStr s >> exitWith ExitSuccess
1150 die :: String -> IO a
1153 dieWith :: Int -> String -> IO a
1156 prog <- getProgramName
1157 hPutStrLn stderr (prog ++ ": " ++ s)
1158 exitWith (ExitFailure ec)
1160 dieOrForceAll :: Force -> String -> IO ()
1161 dieOrForceAll ForceAll s = ignoreError s
1162 dieOrForceAll _other s = dieForcible s
1164 ignoreError :: String -> IO ()
1165 ignoreError s = reportError (s ++ " (ignoring)")
1167 reportError :: String -> IO ()
1168 reportError s = do hFlush stdout; hPutStrLn stderr s
1170 dieForcible :: String -> IO ()
1171 dieForcible s = die (s ++ " (use --force to override)")
1173 my_head :: String -> [a] -> a
1174 my_head s [] = error s
1175 my_head _ (x : _) = x
1177 -----------------------------------------
1178 -- Cut and pasted from ghc/compiler/main/SysTools
1180 #if defined(mingw32_HOST_OS)
1181 subst :: Char -> Char -> String -> String
1182 subst a b ls = map (\ x -> if x == a then b else x) ls
1184 unDosifyPath :: FilePath -> FilePath
1185 unDosifyPath xs = subst '\\' '/' xs
1187 getExecDir :: String -> IO (Maybe String)
1188 -- (getExecDir cmd) returns the directory in which the current
1189 -- executable, which should be called 'cmd', is running
1190 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1191 -- you'll get "/a/b/c" back as the result
1193 = allocaArray len $ \buf -> do
1194 ret <- getModuleFileName nullPtr buf len
1195 if ret == 0 then return Nothing
1196 else do s <- peekCString buf
1197 return (Just (reverse (drop (length cmd)
1198 (reverse (unDosifyPath s)))))
1200 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1202 foreign import stdcall unsafe "GetModuleFileNameA"
1203 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1205 getExecDir :: String -> IO (Maybe String)
1206 getExecDir _ = return Nothing
1209 -----------------------------------------
1210 -- Adapted from ghc/compiler/utils/Panic
1212 installSignalHandlers :: IO ()
1213 installSignalHandlers = do
1214 threadid <- myThreadId
1216 interrupt = Exception.throwTo threadid
1217 (Exception.ErrorCall "interrupted")
1219 #if !defined(mingw32_HOST_OS)
1220 installHandler sigQUIT (Catch interrupt) Nothing
1221 installHandler sigINT (Catch interrupt) Nothing
1223 #elif __GLASGOW_HASKELL__ >= 603
1224 -- GHC 6.3+ has support for console events on Windows
1225 -- NOTE: running GHCi under a bash shell for some reason requires
1226 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1227 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1228 -- why --SDM 17/12/2004
1229 let sig_handler ControlC = interrupt
1230 sig_handler Break = interrupt
1231 sig_handler _ = return ()
1233 installHandler (Catch sig_handler)
1236 return () -- nothing
1239 #if __GLASGOW_HASKELL__ <= 604
1240 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1241 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1244 #if mingw32_HOST_OS || mingw32_TARGET_OS
1245 throwIOIO :: Exception.IOException -> IO a
1246 throwIOIO = Exception.throwIO
1248 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1249 catchIO = Exception.catch
1252 catchError :: IO a -> (String -> IO a) -> IO a
1253 catchError io handler = io `Exception.catch` handler'
1254 where handler' (Exception.ErrorCall err) = handler err
1257 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1258 -- to use text files here, rather than binary files.
1259 writeFileAtomic :: FilePath -> String -> IO ()
1260 writeFileAtomic targetFile content = do
1261 (newFile, newHandle) <- openNewFile targetDir template
1262 do hPutStr newHandle content
1264 #if mingw32_HOST_OS || mingw32_TARGET_OS
1265 renameFile newFile targetFile
1266 -- If the targetFile exists then renameFile will fail
1267 `catchIO` \err -> do
1268 exists <- doesFileExist targetFile
1270 then do removeFile targetFile
1271 -- Big fat hairy race condition
1272 renameFile newFile targetFile
1273 -- If the removeFile succeeds and the renameFile fails
1274 -- then we've lost the atomic property.
1277 renameFile newFile targetFile
1279 `Exception.onException` do hClose newHandle
1282 template = targetName <.> "tmp"
1283 targetDir | null targetDir_ = "."
1284 | otherwise = targetDir_
1285 --TODO: remove this when takeDirectory/splitFileName is fixed
1286 -- to always return a valid dir
1287 (targetDir_,targetName) = splitFileName targetFile
1289 -- Ugh, this is a copy/paste of code from the base library, but
1290 -- if uses 666 rather than 600 for the permissions.
1291 openNewFile :: FilePath -> String -> IO (FilePath, Handle)
1292 openNewFile dir template = do
1296 -- We split off the last extension, so we can use .foo.ext files
1297 -- for temporary files (hidden on Unix OSes). Unfortunately we're
1298 -- below filepath in the hierarchy here.
1300 case break (== '.') $ reverse template of
1301 -- First case: template contains no '.'s. Just re-reverse it.
1302 (rev_suffix, "") -> (reverse rev_suffix, "")
1303 -- Second case: template contains at least one '.'. Strip the
1304 -- dot from the prefix and prepend it to the suffix (if we don't
1305 -- do this, the unique number will get added after the '.' and
1306 -- thus be part of the extension, which is wrong.)
1307 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
1308 -- Otherwise, something is wrong, because (break (== '.')) should
1309 -- always return a pair with either the empty string or a string
1310 -- beginning with '.' as the second component.
1311 _ -> error "bug in System.IO.openTempFile"
1313 oflags = rw_flags .|. o_EXCL
1316 fd <- withCString filepath $ \ f ->
1317 c_open f oflags 0o666
1322 then findTempName (x+1)
1323 else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
1325 -- XXX We want to tell fdToHandle what the filepath is,
1326 -- as any exceptions etc will only be able to report the
1329 #if __GLASGOW_HASKELL__ >= 609
1332 fdToHandle (fromIntegral fd)
1334 `Exception.onException` c_close fd
1335 return (filepath, h)
1337 filename = prefix ++ show x ++ suffix
1338 filepath = dir `combine` filename
1340 -- XXX Copied from GHC.Handle
1341 std_flags, output_flags, rw_flags :: CInt
1342 std_flags = o_NONBLOCK .|. o_NOCTTY
1343 output_flags = std_flags .|. o_CREAT
1344 rw_flags = output_flags .|. o_RDWR
1346 -- | The function splits the given string to substrings
1347 -- using 'isSearchPathSeparator'.
1348 parseSearchPath :: String -> [FilePath]
1349 parseSearchPath path = split path
1351 split :: String -> [String]
1355 _:rest -> chunk : split rest
1359 #ifdef mingw32_HOST_OS
1360 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1364 (chunk', rest') = break isSearchPathSeparator s