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.InstalledPackageInfo hiding (depends)
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils
22 import Distribution.Package
23 import Distribution.Text
24 import Distribution.Version
25 import System.FilePath
26 import System.Cmd ( rawSystem )
27 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
31 #include "../../includes/ghcconfig.h"
33 import System.Console.GetOpt
34 import Text.PrettyPrint
35 #if __GLASGOW_HASKELL__ >= 609
36 import qualified Control.Exception as Exception
38 import qualified Control.Exception.Extensible as Exception
42 import Data.Char ( isSpace, toLower )
44 import System.Directory ( doesDirectoryExist, getDirectoryContents,
45 doesFileExist, renameFile, removeFile )
46 import System.Exit ( exitWith, ExitCode(..) )
47 import System.Environment ( getArgs, getProgName, getEnv )
49 import System.IO.Error (try)
51 import Control.Concurrent
55 #ifdef mingw32_HOST_OS
56 import GHC.ConsoleHandler
58 import System.Posix hiding (fdToHandle)
61 import IO ( isPermissionError )
62 import System.Posix.Internals
63 import GHC.Handle (fdToHandle)
66 import System.Process(runInteractiveCommand)
67 import qualified System.Info(os)
70 -- -----------------------------------------------------------------------------
77 case getOpt Permute (flags ++ deprecFlags) args of
78 (cli,_,[]) | FlagHelp `elem` cli -> do
79 prog <- getProgramName
80 bye (usageInfo (usageHeader prog) flags)
81 (cli,_,[]) | FlagVersion `elem` cli ->
86 prog <- getProgramName
87 die (concat errors ++ usageInfo (usageHeader prog) flags)
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
98 | FlagGlobalConfig FilePath
108 flags :: [OptDescr Flag]
110 Option [] ["user"] (NoArg FlagUser)
111 "use the current user's package database",
112 Option [] ["global"] (NoArg FlagGlobal)
113 "use the global package database",
114 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
115 "use the specified package config file",
116 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
117 "location of the global package config",
118 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
119 "never read the user package database",
120 Option [] ["force"] (NoArg FlagForce)
121 "ignore missing dependencies, directories, and libraries",
122 Option [] ["force-files"] (NoArg FlagForceFiles)
123 "ignore missing directories and libraries only",
124 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
125 "automatically build libs for GHCi (with register)",
126 Option ['?'] ["help"] (NoArg FlagHelp)
127 "display this help and exit",
128 Option ['V'] ["version"] (NoArg FlagVersion)
129 "output version information and exit",
130 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
131 "print output in easy-to-parse format for some commands",
132 Option [] ["names-only"] (NoArg FlagNamesOnly)
133 "only print package names, not versions; can only be used with list --simple-output",
134 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
135 "ignore case for substring matching"
138 deprecFlags :: [OptDescr Flag]
140 -- put deprecated flags here
143 ourCopyright :: String
144 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
146 usageHeader :: String -> String
147 usageHeader prog = substProg prog $
149 " $p register {filename | -}\n" ++
150 " Register the package using the specified installed package\n" ++
151 " description. The syntax for the latter is given in the $p\n" ++
152 " documentation.\n" ++
154 " $p update {filename | -}\n" ++
155 " Register the package, overwriting any other package with the\n" ++
158 " $p unregister {pkg-id}\n" ++
159 " Unregister the specified package.\n" ++
161 " $p expose {pkg-id}\n" ++
162 " Expose the specified package.\n" ++
164 " $p hide {pkg-id}\n" ++
165 " Hide the specified package.\n" ++
167 " $p list [pkg]\n" ++
168 " List registered packages in the global database, and also the\n" ++
169 " user database if --user is given. If a package name is given\n" ++
170 " all the registered versions will be listed in ascending order.\n" ++
171 " Accepts the --simple-output flag.\n" ++
173 " $p find-module {module}\n" ++
174 " List registered packages exposing module {module} in the global\n" ++
175 " database, and also the user database if --user is given.\n" ++
176 " All the registered versions will be listed in ascending order.\n" ++
177 " Accepts the --simple-output flag.\n" ++
179 " $p latest {pkg-id}\n" ++
180 " Prints the highest registered version of a package.\n" ++
183 " Check the consistency of package depenencies and list broken packages.\n" ++
184 " Accepts the --simple-output flag.\n" ++
186 " $p describe {pkg}\n" ++
187 " Give the registered description for the specified package. The\n" ++
188 " description is returned in precisely the syntax required by $p\n" ++
191 " $p field {pkg} {field}\n" ++
192 " Extract the specified field of the package description for the\n" ++
193 " specified package. Accepts comma-separated multiple fields.\n" ++
196 " Dump the registered description for every package. This is like\n" ++
197 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
198 " by tools that parse the results, rather than humans.\n" ++
200 " Substring matching is supported for {module} in find-module and\n" ++
201 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
202 " open substring ends (prefix*, *suffix, *infix*).\n" ++
204 " When asked to modify a database (register, unregister, update,\n"++
205 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
206 " default. Specifying --user causes it to act on the user database,\n"++
207 " or --package-conf can be used to act on another database\n"++
208 " entirely. When multiple of these options are given, the rightmost\n"++
209 " one is used as the database to act upon.\n"++
211 " Commands that query the package database (list, latest, describe,\n"++
212 " field) operate on the list of databases specified by the flags\n"++
213 " --user, --global, and --package-conf. If none of these flags are\n"++
214 " given, the default is --global --user.\n"++
216 " The following optional flags are also accepted:\n"
218 substProg :: String -> String -> String
220 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
221 substProg prog (c:xs) = c : substProg prog xs
223 -- -----------------------------------------------------------------------------
226 data Force = ForceAll | ForceFiles | NoForce
228 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
230 runit :: [Flag] -> [String] -> IO ()
231 runit cli nonopts = do
232 installSignalHandlers -- catch ^C and clean up
233 prog <- getProgramName
236 | FlagForce `elem` cli = ForceAll
237 | FlagForceFiles `elem` cli = ForceFiles
238 | otherwise = NoForce
239 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
240 splitFields fields = unfoldr splitComma (',':fields)
241 where splitComma "" = Nothing
242 splitComma fs = Just $ break (==',') (tail fs)
244 substringCheck :: String -> Maybe (String -> Bool)
245 substringCheck "" = Nothing
246 substringCheck "*" = Just (const True)
247 substringCheck [_] = Nothing
248 substringCheck (h:t) =
249 case (h, init t, last t) of
250 ('*',s,'*') -> Just (isInfixOf (f s) . f)
251 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
252 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
254 where f | FlagIgnoreCase `elem` cli = map toLower
257 glob x | System.Info.os=="mingw32" = do
258 -- glob echoes its argument, after win32 filename globbing
259 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
260 txt <- hGetContents o
262 glob x | otherwise = return [x]
265 -- first, parse the command
268 -- dummy command to demonstrate usage and permit testing
269 -- without messing things up; use glob to selectively enable
270 -- windows filename globbing for file parameters
271 -- register, update, FlagGlobalConfig, FlagConfig; others?
272 ["glob", filename] -> do
274 glob filename >>= print
276 ["register", filename] ->
277 registerPackage filename cli auto_ghci_libs False force
278 ["update", filename] ->
279 registerPackage filename cli auto_ghci_libs True force
280 ["unregister", pkgid_str] -> do
281 pkgid <- readGlobPkgId pkgid_str
282 unregisterPackage pkgid cli force
283 ["expose", pkgid_str] -> do
284 pkgid <- readGlobPkgId pkgid_str
285 exposePackage pkgid cli force
286 ["hide", pkgid_str] -> do
287 pkgid <- readGlobPkgId pkgid_str
288 hidePackage pkgid cli force
290 listPackages cli Nothing Nothing
291 ["list", pkgid_str] ->
292 case substringCheck pkgid_str of
293 Nothing -> do pkgid <- readGlobPkgId pkgid_str
294 listPackages cli (Just (Id pkgid)) Nothing
295 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
296 ["find-module", moduleName] -> do
297 let match = maybe (==moduleName) id (substringCheck moduleName)
298 listPackages cli Nothing (Just match)
299 ["latest", pkgid_str] -> do
300 pkgid <- readGlobPkgId pkgid_str
301 latestPackage cli pkgid
302 ["describe", pkgid_str] ->
303 case substringCheck pkgid_str of
304 Nothing -> do pkgid <- readGlobPkgId pkgid_str
305 describePackage cli (Id pkgid)
306 Just m -> describePackage cli (Substring pkgid_str m)
307 ["field", pkgid_str, fields] ->
308 case substringCheck pkgid_str of
309 Nothing -> do pkgid <- readGlobPkgId pkgid_str
310 describeField cli (Id pkgid) (splitFields fields)
311 Just m -> describeField cli (Substring pkgid_str m)
320 die ("missing command\n" ++
321 usageInfo (usageHeader prog) flags)
323 die ("command-line syntax error\n" ++
324 usageInfo (usageHeader prog) flags)
326 parseCheck :: ReadP a a -> String -> String -> IO a
327 parseCheck parser str what =
328 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
330 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
332 readGlobPkgId :: String -> IO PackageIdentifier
333 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
335 parseGlobPackageId :: ReadP r PackageIdentifier
341 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
343 -- globVersion means "all versions"
344 globVersion :: Version
345 globVersion = Version{ versionBranch=[], versionTags=["*"] }
347 -- -----------------------------------------------------------------------------
350 -- Some commands operate on a single database:
351 -- register, unregister, expose, hide
352 -- however these commands also check the union of the available databases
353 -- in order to check consistency. For example, register will check that
354 -- dependencies exist before registering a package.
356 -- Some commands operate on multiple databases, with overlapping semantics:
357 -- list, describe, field
359 type PackageDBName = FilePath
360 type PackageDB = [InstalledPackageInfo]
362 type NamedPackageDB = (PackageDBName, PackageDB)
363 type PackageDBStack = [NamedPackageDB]
364 -- A stack of package databases. Convention: head is the topmost
365 -- in the stack. Earlier entries override later one.
367 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
368 allPackagesInStack = concatMap snd
370 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
371 getPkgDatabases modify my_flags = do
372 -- first we determine the location of the global package config. On Windows,
373 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
374 -- location is passed to the binary using the --global-config flag by the
376 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
378 case [ f | FlagGlobalConfig f <- my_flags ] of
379 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
381 Nothing -> die err_msg
383 do let path1 = dir </> "package.conf"
384 path2 = dir </> ".." </> ".." </> ".."
385 </> "inplace-datadir"
387 exists1 <- doesFileExist path1
388 exists2 <- doesFileExist path2
389 if exists1 then return path1
390 else if exists2 then return path2
391 else die "Can't find package.conf"
392 fs -> return (last fs)
394 let global_conf_dir = global_conf ++ ".d"
395 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
397 if global_conf_dir_exists
398 then do files <- getDirectoryContents global_conf_dir
399 return [ global_conf_dir ++ '/' : file
401 , isSuffixOf ".conf" file]
404 let no_user_db = FlagNoUserDb `elem` my_flags
406 -- get the location of the user package database, and create it if necessary
407 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
408 appdir <- try $ getAppUserDataDirectory "ghc"
411 if no_user_db then return Nothing else
414 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
415 user_conf = dir </> subdir </> "package.conf"
416 user_exists <- doesFileExist user_conf
417 return (Just (user_conf,user_exists))
421 -- If the user database doesn't exist, and this command isn't a
422 -- "modify" command, then we won't attempt to create or use it.
424 | Just (user_conf,user_exists) <- mb_user_conf,
425 modify || user_exists = user_conf : global_confs ++ [global_conf]
426 | otherwise = global_confs ++ [global_conf]
428 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
431 Left _ -> sys_databases
433 | last cs == "" -> init cs ++ sys_databases
435 where cs = parseSearchPath path
437 -- The "global" database is always the one at the bottom of the stack.
438 -- This is the database we modify by default.
439 virt_global_conf = last env_stack
441 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
442 where is_db_flag FlagUser
443 | Just (user_conf, _user_exists) <- mb_user_conf
445 is_db_flag FlagGlobal = Just virt_global_conf
446 is_db_flag (FlagConfig f) = Just f
447 is_db_flag _ = Nothing
449 (final_stack, to_modify) <-
451 then -- For a "read" command, we use all the databases
452 -- specified on the command line. If there are no
453 -- command-line flags specifying databases, the default
454 -- is to use all the ones we know about.
455 if null db_flags then return (env_stack, Nothing)
456 else return (reverse (nub db_flags), Nothing)
458 -- For a "modify" command, treat all the databases as
459 -- a stack, where we are modifying the top one, but it
460 -- can refer to packages in databases further down the
463 -- -f flags on the command line add to the database
464 -- stack, unless any of them are present in the stack
466 flag_stack = filter (`notElem` env_stack)
467 [ f | FlagConfig f <- reverse my_flags ]
470 -- the database we actually modify is the one mentioned
471 -- rightmost on the command-line.
472 to_modify = if null db_flags
473 then Just virt_global_conf
474 else Just (last db_flags)
476 return (flag_stack, to_modify)
478 db_stack <- mapM (readParseDatabase mb_user_conf) final_stack
479 return (db_stack, to_modify)
481 readParseDatabase :: Maybe (PackageDBName,Bool)
483 -> IO (PackageDBName,PackageDB)
484 readParseDatabase mb_user_conf filename
485 -- the user database (only) is allowed to be non-existent
486 | Just (user_conf,False) <- mb_user_conf, filename == user_conf
487 = return (filename, [])
489 = do str <- readFile filename
490 let packages = map convertPackageInfoIn $ read str
491 Exception.evaluate packages
493 die ("error while parsing " ++ filename ++ ": " ++ show e)
494 return (filename,packages)
496 -- -----------------------------------------------------------------------------
499 registerPackage :: FilePath
501 -> Bool -- auto_ghci_libs
505 registerPackage input my_flags auto_ghci_libs update force = do
506 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
508 db_to_operate_on = my_head "register" $
509 filter ((== to_modify).fst) db_stack
514 putStr "Reading package info from stdin ... "
517 putStr ("Reading package info from " ++ show f ++ " ... ")
520 expanded <- expandEnvVars s force
522 pkg <- parsePackageInfo expanded
525 let unversioned_deps = filter (not . realVersion) (depends pkg)
526 unless (null unversioned_deps) $
527 die ("Unversioned dependencies found: " ++
528 unwords (map display unversioned_deps))
530 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
531 -- truncate the stack for validation, because we don't allow
532 -- packages lower in the stack to refer to those higher up.
533 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
534 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
535 not_this p = package p /= package pkg
536 writeNewConfig to_modify new_details
540 -> IO InstalledPackageInfo
541 parsePackageInfo str =
542 case parseInstalledPackageInfo str of
543 ParseOk _warns ok -> return ok
544 ParseFailed err -> case locatedErrorMsg err of
545 (Nothing, s) -> die s
546 (Just l, s) -> die (show l ++ ": " ++ s)
548 -- -----------------------------------------------------------------------------
549 -- Exposing, Hiding, Unregistering are all similar
551 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
552 exposePackage = modifyPackage (\p -> [p{exposed=True}])
554 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
555 hidePackage = modifyPackage (\p -> [p{exposed=False}])
557 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
558 unregisterPackage = modifyPackage (\_ -> [])
561 :: (InstalledPackageInfo -> [InstalledPackageInfo])
566 modifyPackage fn pkgid my_flags force = do
567 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
568 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
569 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
570 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
572 pids = map package ps
574 | package pkg `elem` pids = fn pkg
576 new_config = concat (map modify pkgs)
579 old_broken = brokenPackages (allPackagesInStack db_stack)
580 rest_of_stack = [ (nm, mypkgs)
581 | (nm, mypkgs) <- db_stack, nm /= db_name ]
582 new_stack = (db_name,new_config) : rest_of_stack
583 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
584 newly_broken = filter (`notElem` map package old_broken) new_broken
586 when (not (null newly_broken)) $
587 dieOrForceAll force ("unregistering " ++ display pkgid ++
588 " would break the following packages: "
589 ++ unwords (map display newly_broken))
591 writeNewConfig db_name new_config
593 -- -----------------------------------------------------------------------------
596 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
597 listPackages my_flags mPackageName mModuleName = do
598 let simple_output = FlagSimpleOutput `elem` my_flags
599 (db_stack, _) <- getPkgDatabases False my_flags
600 let db_stack_filtered -- if a package is given, filter out all other packages
601 | Just this <- mPackageName =
602 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
604 | Just match <- mModuleName = -- packages which expose mModuleName
605 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
607 | otherwise = db_stack
610 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
611 where sort_pkgs = sortBy cmpPkgIds
612 cmpPkgIds pkg1 pkg2 =
613 case pkgName p1 `compare` pkgName p2 of
616 EQ -> pkgVersion p1 `compare` pkgVersion p2
617 where (p1,p2) = (package pkg1, package pkg2)
619 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
621 pkg_map = allPackagesInStack db_stack
622 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
624 show_func (reverse db_stack_sorted)
626 where show_normal pkg_map (db_name,pkg_confs) =
627 hPutStrLn stdout (render $
628 text db_name <> colon $$ nest 4 packages
630 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
631 broken = map package (brokenPackages pkg_map)
633 | package p `elem` broken = braces doc
635 | otherwise = parens doc
636 where doc = text (display (package p))
638 show_simple db_stack = do
639 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
641 pkgs = map showPkg $ sortBy compPkgIdVer $
642 map package (allPackagesInStack db_stack)
643 when (not (null pkgs)) $
644 hPutStrLn stdout $ concat $ intersperse " " pkgs
646 -- -----------------------------------------------------------------------------
647 -- Prints the highest (hidden or exposed) version of a package
649 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
650 latestPackage my_flags pkgid = do
651 (db_stack, _) <- getPkgDatabases False my_flags
652 ps <- findPackages db_stack (Id pkgid)
653 show_pkg (sortBy compPkgIdVer (map package ps))
655 show_pkg [] = die "no matches"
656 show_pkg pids = hPutStrLn stdout (display (last pids))
658 -- -----------------------------------------------------------------------------
661 describePackage :: [Flag] -> PackageArg -> IO ()
662 describePackage my_flags pkgarg = do
663 (db_stack, _) <- getPkgDatabases False my_flags
664 ps <- findPackages db_stack pkgarg
667 dumpPackages :: [Flag] -> IO ()
668 dumpPackages my_flags = do
669 (db_stack, _) <- getPkgDatabases False my_flags
670 doDump (allPackagesInStack db_stack)
672 doDump :: [InstalledPackageInfo] -> IO ()
673 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
675 -- PackageId is can have globVersion for the version
676 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
677 findPackages db_stack pkgarg
678 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
680 findPackagesByDB :: PackageDBStack -> PackageArg
681 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
682 findPackagesByDB db_stack pkgarg
683 = case [ (db, matched)
684 | db@(_, pkgs) <- db_stack,
685 let matched = filter (pkgarg `matchesPkg`) pkgs,
686 not (null matched) ] of
687 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
690 pkg_msg (Id pkgid) = display pkgid
691 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
693 matches :: PackageIdentifier -> PackageIdentifier -> Bool
695 = (pkgName pid == pkgName pid')
696 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
698 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
699 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
700 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
702 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
703 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
705 -- -----------------------------------------------------------------------------
708 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
709 describeField my_flags pkgarg fields = do
710 (db_stack, _) <- getPkgDatabases False my_flags
711 fns <- toFields fields
712 ps <- findPackages db_stack pkgarg
713 let top_dir = takeDirectory (fst (last db_stack))
714 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
715 where toFields [] = return []
716 toFields (f:fs) = case toField f of
717 Nothing -> die ("unknown field: " ++ f)
718 Just fn -> do fns <- toFields fs
720 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
722 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
723 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
724 -- with the current topdir (obtained from the -B option).
725 mungePackagePaths top_dir ps = map munge_pkg ps
727 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
728 includeDirs = munge_paths (includeDirs p),
729 libraryDirs = munge_paths (libraryDirs p),
730 frameworkDirs = munge_paths (frameworkDirs p),
731 haddockInterfaces = munge_paths (haddockInterfaces p),
732 haddockHTMLs = munge_paths (haddockHTMLs p)
735 munge_paths = map munge_path
738 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
739 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
742 toHttpPath p = "file:///" ++ p
744 maybePrefixMatch :: String -> String -> Maybe String
745 maybePrefixMatch [] rest = Just rest
746 maybePrefixMatch (_:_) [] = Nothing
747 maybePrefixMatch (p:pat) (r:rest)
748 | p == r = maybePrefixMatch pat rest
749 | otherwise = Nothing
751 toField :: String -> Maybe (InstalledPackageInfo -> String)
752 -- backwards compatibility:
753 toField "import_dirs" = Just $ strList . importDirs
754 toField "source_dirs" = Just $ strList . importDirs
755 toField "library_dirs" = Just $ strList . libraryDirs
756 toField "hs_libraries" = Just $ strList . hsLibraries
757 toField "extra_libraries" = Just $ strList . extraLibraries
758 toField "include_dirs" = Just $ strList . includeDirs
759 toField "c_includes" = Just $ strList . includes
760 toField "package_deps" = Just $ strList . map display. depends
761 toField "extra_cc_opts" = Just $ strList . ccOptions
762 toField "extra_ld_opts" = Just $ strList . ldOptions
763 toField "framework_dirs" = Just $ strList . frameworkDirs
764 toField "extra_frameworks"= Just $ strList . frameworks
765 toField s = showInstalledPackageInfoField s
767 strList :: [String] -> String
771 -- -----------------------------------------------------------------------------
772 -- Check: Check consistency of installed packages
774 checkConsistency :: [Flag] -> IO ()
775 checkConsistency my_flags = do
776 (db_stack, _) <- getPkgDatabases True my_flags
777 -- check behaves like modify for the purposes of deciding which
778 -- databases to use, because ordering is important.
779 let pkgs = allPackagesInStack db_stack
780 broken_pkgs = brokenPackages pkgs
781 broken_ids = map package broken_pkgs
782 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
784 mapM_ (putStrLn . render . show_func) broken_why
786 show_func | FlagSimpleOutput `elem` my_flags = show_simple
787 | otherwise = show_normal
788 show_simple (pid,deps) =
789 text (display pid) <> colon
790 <+> fsep (punctuate comma (map (text . display) deps))
791 show_normal (pid,deps) =
792 text "package" <+> text (display pid) <+> text "has missing dependencies:"
793 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
796 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
797 brokenPackages pkgs = go [] pkgs
800 case partition (depsAvailable avail) not_avail of
801 ([], not_avail') -> not_avail'
802 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
804 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
806 depsAvailable pkgs_ok pkg = null dangling
807 where dangling = filter (`notElem` pids) (depends pkg)
808 pids = map package pkgs_ok
810 -- we want mutually recursive groups of package to show up
811 -- as broken. (#1750)
813 -- -----------------------------------------------------------------------------
814 -- Manipulating package.conf files
816 type InstalledPackageInfoString = InstalledPackageInfo_ String
818 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
819 convertPackageInfoOut
820 (pkgconf@(InstalledPackageInfo { exposedModules = e,
821 hiddenModules = h })) =
822 pkgconf{ exposedModules = map display e,
823 hiddenModules = map display h }
825 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
827 (pkgconf@(InstalledPackageInfo { exposedModules = e,
828 hiddenModules = h })) =
829 pkgconf{ exposedModules = map convert e,
830 hiddenModules = map convert h }
831 where convert = fromJust . simpleParse
833 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
834 writeNewConfig filename packages = do
835 hPutStr stdout "Writing new package config file... "
836 createDirectoryIfMissing True $ takeDirectory filename
837 let shown = concat $ intersperse ",\n "
838 $ map (show . convertPackageInfoOut) packages
839 fileContents = "[" ++ shown ++ "\n]"
840 writeFileAtomic filename fileContents
842 if isPermissionError e
843 then die (filename ++ ": you don't have permission to modify this file")
845 hPutStrLn stdout "done."
847 -----------------------------------------------------------------------------
848 -- Sanity-check a new package config, and automatically build GHCi libs
851 validatePackageConfig :: InstalledPackageInfo
853 -> Bool -- auto-ghc-libs
857 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
859 checkDuplicates db_stack pkg update force
860 mapM_ (checkDep db_stack force) (depends pkg)
861 checkDuplicateDepends force (depends pkg)
862 mapM_ (checkDir force) (importDirs pkg)
863 mapM_ (checkDir force) (libraryDirs pkg)
864 mapM_ (checkDir force) (includeDirs pkg)
865 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
866 -- ToDo: check these somehow?
867 -- extra_libraries :: [String],
868 -- c_includes :: [String],
870 -- When the package name and version are put together, sometimes we can
871 -- end up with a package id that cannot be parsed. This will lead to
872 -- difficulties when the user wants to refer to the package later, so
873 -- we check that the package id can be parsed properly here.
874 checkPackageId :: InstalledPackageInfo -> IO ()
876 let str = display (package ipi) in
877 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
879 [] -> die ("invalid package identifier: " ++ str)
880 _ -> die ("ambiguous package identifier: " ++ str)
882 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
883 checkDuplicates db_stack pkg update force = do
886 (_top_db_name, pkgs) : _ = db_stack
888 -- Check whether this package id already exists in this DB
890 when (not update && (pkgid `elem` map package pkgs)) $
891 die ("package " ++ display pkgid ++ " is already installed")
894 uncasep = map toLower . display
895 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
897 when (not update && not (null dups)) $ dieOrForceAll force $
898 "Package names may be treated case-insensitively in the future.\n"++
899 "Package " ++ display pkgid ++
900 " overlaps with: " ++ unwords (map display dups)
903 checkDir :: Force -> String -> IO ()
905 | "$topdir" `isPrefixOf` d = return ()
906 | "$httptopdir" `isPrefixOf` d = return ()
907 -- can't check these, because we don't know what $(http)topdir is
909 there <- doesDirectoryExist d
911 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
913 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
914 checkDep db_stack force pkgid
915 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
916 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
919 -- for backwards compat, we treat 0.0 as a special version,
920 -- and don't check that it actually exists.
921 real_version = realVersion pkgid
923 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
926 all_pkgs = allPackagesInStack db_stack
927 pkgids = map package all_pkgs
929 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
930 checkDuplicateDepends force deps
931 | null dups = return ()
932 | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
933 unwords (map display dups))
935 dups = [ p | (p:_:_) <- group (sort deps) ]
937 realVersion :: PackageIdentifier -> Bool
938 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
940 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
941 checkHSLib dirs auto_ghci_libs force lib = do
942 let batch_lib_file = "lib" ++ lib ++ ".a"
943 bs <- mapM (doesLibExistIn batch_lib_file) dirs
944 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
945 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
947 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
949 doesLibExistIn :: String -> String -> IO Bool
951 | "$topdir" `isPrefixOf` d = return True
952 | "$httptopdir" `isPrefixOf` d = return True
953 | otherwise = doesFileExist (d ++ '/':lib)
955 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
956 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
957 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
959 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
960 case [dir | (exists,dir) <- zip bs dirs, exists] of
961 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
964 ghci_lib_file = lib ++ ".o"
966 -- automatically build the GHCi version of a batch lib,
967 -- using ld --whole-archive.
969 autoBuildGHCiLib :: String -> String -> String -> IO ()
970 autoBuildGHCiLib dir batch_file ghci_file = do
971 let ghci_lib_file = dir ++ '/':ghci_file
972 batch_lib_file = dir ++ '/':batch_file
973 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
974 #if defined(darwin_HOST_OS)
975 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
976 #elif defined(mingw32_HOST_OS)
977 execDir <- getExecDir "/bin/ghc-pkg.exe"
978 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
980 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
982 when (r /= ExitSuccess) $ exitWith r
983 hPutStrLn stderr (" done.")
985 -- -----------------------------------------------------------------------------
986 -- Searching for modules
990 findModules :: [FilePath] -> IO [String]
992 mms <- mapM searchDir paths
995 searchDir path prefix = do
996 fs <- getDirectoryEntries path `catch` \_ -> return []
997 searchEntries path prefix fs
999 searchEntries path prefix [] = return []
1000 searchEntries path prefix (f:fs)
1001 | looks_like_a_module = do
1002 ms <- searchEntries path prefix fs
1003 return (prefix `joinModule` f : ms)
1004 | looks_like_a_component = do
1005 ms <- searchDir (path </> f) (prefix `joinModule` f)
1006 ms' <- searchEntries path prefix fs
1009 searchEntries path prefix fs
1012 (base,suffix) = splitFileExt f
1013 looks_like_a_module =
1014 suffix `elem` haskell_suffixes &&
1015 all okInModuleName base
1016 looks_like_a_component =
1017 null suffix && all okInModuleName base
1023 -- ---------------------------------------------------------------------------
1024 -- expanding environment variables in the package configuration
1026 expandEnvVars :: String -> Force -> IO String
1027 expandEnvVars str0 force = go str0 ""
1029 go "" acc = return $! reverse acc
1030 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1031 = do value <- lookupEnvVar var
1032 go rest (reverse value ++ acc)
1033 where close c = c == '}' || c == '\n' -- don't span newlines
1037 lookupEnvVar :: String -> IO String
1039 catch (System.Environment.getEnv nm)
1040 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1044 -----------------------------------------------------------------------------
1046 getProgramName :: IO String
1047 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1048 where str `withoutSuffix` suff
1049 | suff `isSuffixOf` str = take (length str - length suff) str
1052 bye :: String -> IO a
1053 bye s = putStr s >> exitWith ExitSuccess
1055 die :: String -> IO a
1058 dieWith :: Int -> String -> IO a
1061 prog <- getProgramName
1062 hPutStrLn stderr (prog ++ ": " ++ s)
1063 exitWith (ExitFailure ec)
1065 dieOrForceAll :: Force -> String -> IO ()
1066 dieOrForceAll ForceAll s = ignoreError s
1067 dieOrForceAll _other s = dieForcible s
1069 dieOrForceFile :: Force -> String -> IO ()
1070 dieOrForceFile ForceAll s = ignoreError s
1071 dieOrForceFile ForceFiles s = ignoreError s
1072 dieOrForceFile _other s = dieForcible s
1074 ignoreError :: String -> IO ()
1075 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1077 dieForcible :: String -> IO ()
1078 dieForcible s = die (s ++ " (use --force to override)")
1080 my_head :: String -> [a] -> a
1081 my_head s [] = error s
1082 my_head _ (x : _) = x
1084 -----------------------------------------
1085 -- Cut and pasted from ghc/compiler/main/SysTools
1087 #if defined(mingw32_HOST_OS)
1088 subst :: Char -> Char -> String -> String
1089 subst a b ls = map (\ x -> if x == a then b else x) ls
1091 unDosifyPath :: FilePath -> FilePath
1092 unDosifyPath xs = subst '\\' '/' xs
1094 getExecDir :: String -> IO (Maybe String)
1095 -- (getExecDir cmd) returns the directory in which the current
1096 -- executable, which should be called 'cmd', is running
1097 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1098 -- you'll get "/a/b/c" back as the result
1100 = allocaArray len $ \buf -> do
1101 ret <- getModuleFileName nullPtr buf len
1102 if ret == 0 then return Nothing
1103 else do s <- peekCString buf
1104 return (Just (reverse (drop (length cmd)
1105 (reverse (unDosifyPath s)))))
1107 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1109 foreign import stdcall unsafe "GetModuleFileNameA"
1110 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1112 getExecDir :: String -> IO (Maybe String)
1113 getExecDir _ = return Nothing
1116 -----------------------------------------
1117 -- Adapted from ghc/compiler/utils/Panic
1119 installSignalHandlers :: IO ()
1120 installSignalHandlers = do
1121 threadid <- myThreadId
1123 interrupt = Exception.throwTo threadid
1124 (Exception.ErrorCall "interrupted")
1126 #if !defined(mingw32_HOST_OS)
1127 installHandler sigQUIT (Catch interrupt) Nothing
1128 installHandler sigINT (Catch interrupt) Nothing
1130 #elif __GLASGOW_HASKELL__ >= 603
1131 -- GHC 6.3+ has support for console events on Windows
1132 -- NOTE: running GHCi under a bash shell for some reason requires
1133 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1134 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1135 -- why --SDM 17/12/2004
1136 let sig_handler ControlC = interrupt
1137 sig_handler Break = interrupt
1138 sig_handler _ = return ()
1140 installHandler (Catch sig_handler)
1143 return () -- nothing
1146 #if __GLASGOW_HASKELL__ <= 604
1147 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1148 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1151 #if mingw32_HOST_OS || mingw32_TARGET_OS
1152 throwIOIO :: Exception.IOException -> IO a
1153 throwIOIO = Exception.throwIO
1156 catchError :: IO a -> (String -> IO a) -> IO a
1157 catchError io handler = io `Exception.catch` handler'
1158 where handler' (Exception.ErrorCall err) = handler err
1161 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1162 -- to use text files here, rather than binary files.
1163 writeFileAtomic :: FilePath -> String -> IO ()
1164 writeFileAtomic targetFile content = do
1165 (newFile, newHandle) <- openNewFile targetDir template
1166 do hPutStr newHandle content
1168 #if mingw32_HOST_OS || mingw32_TARGET_OS
1169 renameFile newFile targetFile
1170 -- If the targetFile exists then renameFile will fail
1171 `catchIO` \err -> do
1172 exists <- doesFileExist targetFile
1174 then do removeFile targetFile
1175 -- Big fat hairy race condition
1176 renameFile newFile targetFile
1177 -- If the removeFile succeeds and the renameFile fails
1178 -- then we've lost the atomic property.
1181 renameFile newFile targetFile
1183 `Exception.onException` do hClose newHandle
1186 template = targetName <.> "tmp"
1187 targetDir | null targetDir_ = "."
1188 | otherwise = targetDir_
1189 --TODO: remove this when takeDirectory/splitFileName is fixed
1190 -- to always return a valid dir
1191 (targetDir_,targetName) = splitFileName targetFile
1193 -- Ugh, this is a copy/paste of code from the base library, but
1194 -- if uses 666 rather than 600 for the permissions.
1195 openNewFile :: FilePath -> String -> IO (FilePath, Handle)
1196 openNewFile dir template = do
1200 -- We split off the last extension, so we can use .foo.ext files
1201 -- for temporary files (hidden on Unix OSes). Unfortunately we're
1202 -- below filepath in the hierarchy here.
1204 case break (== '.') $ reverse template of
1205 -- First case: template contains no '.'s. Just re-reverse it.
1206 (rev_suffix, "") -> (reverse rev_suffix, "")
1207 -- Second case: template contains at least one '.'. Strip the
1208 -- dot from the prefix and prepend it to the suffix (if we don't
1209 -- do this, the unique number will get added after the '.' and
1210 -- thus be part of the extension, which is wrong.)
1211 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
1212 -- Otherwise, something is wrong, because (break (== '.')) should
1213 -- always return a pair with either the empty string or a string
1214 -- beginning with '.' as the second component.
1215 _ -> error "bug in System.IO.openTempFile"
1217 oflags = rw_flags .|. o_EXCL
1220 fd <- withCString filepath $ \ f ->
1221 c_open f oflags 0o666
1226 then findTempName (x+1)
1227 else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
1229 -- XXX We want to tell fdToHandle what the filepath is,
1230 -- as any exceptions etc will only be able to report the
1233 #if __GLASGOW_HASKELL__ >= 609
1236 fdToHandle (fromIntegral fd)
1238 `Exception.onException` c_close fd
1239 return (filepath, h)
1241 filename = prefix ++ show x ++ suffix
1242 filepath = dir `combine` filename
1244 -- XXX Copied from GHC.Handle
1245 std_flags, output_flags, rw_flags :: CInt
1246 std_flags = o_NONBLOCK .|. o_NOCTTY
1247 output_flags = std_flags .|. o_CREAT
1248 rw_flags = output_flags .|. o_RDWR
1250 -- | The function splits the given string to substrings
1251 -- using 'isSearchPathSeparator'.
1252 parseSearchPath :: String -> [FilePath]
1253 parseSearchPath path = split path
1255 split :: String -> [String]
1259 _:rest -> chunk : split rest
1263 #ifdef mingw32_HOST_OS
1264 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1268 (chunk', rest') = break isSearchPathSeparator s