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 import qualified Control.Exception as Exception
38 import Data.Char ( isSpace, toLower )
40 import System.Directory ( doesDirectoryExist, getDirectoryContents,
41 doesFileExist, renameFile, removeFile )
42 import System.Exit ( exitWith, ExitCode(..) )
43 import System.Environment ( getArgs, getProgName, getEnv )
45 import System.IO.Error (try)
47 import Control.Concurrent
51 #ifdef mingw32_HOST_OS
52 import GHC.ConsoleHandler
54 import System.Posix hiding (fdToHandle)
57 import IO ( isPermissionError )
58 import System.Posix.Internals
59 import GHC.Handle (fdToHandle)
62 import System.Process(runInteractiveCommand)
63 import qualified System.Info(os)
66 -- -----------------------------------------------------------------------------
73 case getOpt Permute (flags ++ deprecFlags) args of
74 (cli,_,[]) | FlagHelp `elem` cli -> do
75 prog <- getProgramName
76 bye (usageInfo (usageHeader prog) flags)
77 (cli,_,[]) | FlagVersion `elem` cli ->
82 prog <- getProgramName
83 die (concat errors ++ usageInfo (usageHeader prog) flags)
85 -- -----------------------------------------------------------------------------
86 -- Command-line syntax
94 | FlagGlobalConfig FilePath
104 flags :: [OptDescr Flag]
106 Option [] ["user"] (NoArg FlagUser)
107 "use the current user's package database",
108 Option [] ["global"] (NoArg FlagGlobal)
109 "use the global package database",
110 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
111 "use the specified package config file",
112 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
113 "location of the global package config",
114 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
115 "never read the user package database",
116 Option [] ["force"] (NoArg FlagForce)
117 "ignore missing dependencies, directories, and libraries",
118 Option [] ["force-files"] (NoArg FlagForceFiles)
119 "ignore missing directories and libraries only",
120 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
121 "automatically build libs for GHCi (with register)",
122 Option ['?'] ["help"] (NoArg FlagHelp)
123 "display this help and exit",
124 Option ['V'] ["version"] (NoArg FlagVersion)
125 "output version information and exit",
126 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
127 "print output in easy-to-parse format for some commands",
128 Option [] ["names-only"] (NoArg FlagNamesOnly)
129 "only print package names, not versions; can only be used with list --simple-output",
130 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
131 "ignore case for substring matching"
134 deprecFlags :: [OptDescr Flag]
136 -- put deprecated flags here
139 ourCopyright :: String
140 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
142 usageHeader :: String -> String
143 usageHeader prog = substProg prog $
145 " $p register {filename | -}\n" ++
146 " Register the package using the specified installed package\n" ++
147 " description. The syntax for the latter is given in the $p\n" ++
148 " documentation.\n" ++
150 " $p update {filename | -}\n" ++
151 " Register the package, overwriting any other package with the\n" ++
154 " $p unregister {pkg-id}\n" ++
155 " Unregister the specified package.\n" ++
157 " $p expose {pkg-id}\n" ++
158 " Expose the specified package.\n" ++
160 " $p hide {pkg-id}\n" ++
161 " Hide the specified package.\n" ++
163 " $p list [pkg]\n" ++
164 " List registered packages in the global database, and also the\n" ++
165 " user database if --user is given. If a package name is given\n" ++
166 " all the registered versions will be listed in ascending order.\n" ++
167 " Accepts the --simple-output flag.\n" ++
169 " $p find-module {module}\n" ++
170 " List registered packages exposing module {module} in the global\n" ++
171 " database, and also the user database if --user is given.\n" ++
172 " All the registered versions will be listed in ascending order.\n" ++
173 " Accepts the --simple-output flag.\n" ++
175 " $p latest {pkg-id}\n" ++
176 " Prints the highest registered version of a package.\n" ++
179 " Check the consistency of package depenencies and list broken packages.\n" ++
180 " Accepts the --simple-output flag.\n" ++
182 " $p describe {pkg}\n" ++
183 " Give the registered description for the specified package. The\n" ++
184 " description is returned in precisely the syntax required by $p\n" ++
187 " $p field {pkg} {field}\n" ++
188 " Extract the specified field of the package description for the\n" ++
189 " specified package. Accepts comma-separated multiple fields.\n" ++
192 " Dump the registered description for every package. This is like\n" ++
193 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
194 " by tools that parse the results, rather than humans.\n" ++
196 " Substring matching is supported for {module} in find-module and\n" ++
197 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
198 " open substring ends (prefix*, *suffix, *infix*).\n" ++
200 " When asked to modify a database (register, unregister, update,\n"++
201 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
202 " default. Specifying --user causes it to act on the user database,\n"++
203 " or --package-conf can be used to act on another database\n"++
204 " entirely. When multiple of these options are given, the rightmost\n"++
205 " one is used as the database to act upon.\n"++
207 " Commands that query the package database (list, latest, describe,\n"++
208 " field) operate on the list of databases specified by the flags\n"++
209 " --user, --global, and --package-conf. If none of these flags are\n"++
210 " given, the default is --global --user.\n"++
212 " The following optional flags are also accepted:\n"
214 substProg :: String -> String -> String
216 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
217 substProg prog (c:xs) = c : substProg prog xs
219 -- -----------------------------------------------------------------------------
222 data Force = ForceAll | ForceFiles | NoForce
224 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
226 runit :: [Flag] -> [String] -> IO ()
227 runit cli nonopts = do
228 installSignalHandlers -- catch ^C and clean up
229 prog <- getProgramName
232 | FlagForce `elem` cli = ForceAll
233 | FlagForceFiles `elem` cli = ForceFiles
234 | otherwise = NoForce
235 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
236 splitFields fields = unfoldr splitComma (',':fields)
237 where splitComma "" = Nothing
238 splitComma fs = Just $ break (==',') (tail fs)
240 substringCheck :: String -> Maybe (String -> Bool)
241 substringCheck "" = Nothing
242 substringCheck "*" = Just (const True)
243 substringCheck [_] = Nothing
244 substringCheck (h:t) =
245 case (h, init t, last t) of
246 ('*',s,'*') -> Just (isInfixOf (f s) . f)
247 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
248 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
250 where f | FlagIgnoreCase `elem` cli = map toLower
253 glob x | System.Info.os=="mingw32" = do
254 -- glob echoes its argument, after win32 filename globbing
255 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
256 txt <- hGetContents o
258 glob x | otherwise = return [x]
261 -- first, parse the command
264 -- dummy command to demonstrate usage and permit testing
265 -- without messing things up; use glob to selectively enable
266 -- windows filename globbing for file parameters
267 -- register, update, FlagGlobalConfig, FlagConfig; others?
268 ["glob", filename] -> do
270 glob filename >>= print
272 ["register", filename] ->
273 registerPackage filename cli auto_ghci_libs False force
274 ["update", filename] ->
275 registerPackage filename cli auto_ghci_libs True force
276 ["unregister", pkgid_str] -> do
277 pkgid <- readGlobPkgId pkgid_str
278 unregisterPackage pkgid cli force
279 ["expose", pkgid_str] -> do
280 pkgid <- readGlobPkgId pkgid_str
281 exposePackage pkgid cli force
282 ["hide", pkgid_str] -> do
283 pkgid <- readGlobPkgId pkgid_str
284 hidePackage pkgid cli force
286 listPackages cli Nothing Nothing
287 ["list", pkgid_str] ->
288 case substringCheck pkgid_str of
289 Nothing -> do pkgid <- readGlobPkgId pkgid_str
290 listPackages cli (Just (Id pkgid)) Nothing
291 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
292 ["find-module", moduleName] -> do
293 let match = maybe (==moduleName) id (substringCheck moduleName)
294 listPackages cli Nothing (Just match)
295 ["latest", pkgid_str] -> do
296 pkgid <- readGlobPkgId pkgid_str
297 latestPackage cli pkgid
298 ["describe", pkgid_str] ->
299 case substringCheck pkgid_str of
300 Nothing -> do pkgid <- readGlobPkgId pkgid_str
301 describePackage cli (Id pkgid)
302 Just m -> describePackage cli (Substring pkgid_str m)
303 ["field", pkgid_str, fields] ->
304 case substringCheck pkgid_str of
305 Nothing -> do pkgid <- readGlobPkgId pkgid_str
306 describeField cli (Id pkgid) (splitFields fields)
307 Just m -> describeField cli (Substring pkgid_str m)
316 die ("missing command\n" ++
317 usageInfo (usageHeader prog) flags)
319 die ("command-line syntax error\n" ++
320 usageInfo (usageHeader prog) flags)
322 parseCheck :: ReadP a a -> String -> String -> IO a
323 parseCheck parser str what =
324 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
326 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
328 readGlobPkgId :: String -> IO PackageIdentifier
329 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
331 parseGlobPackageId :: ReadP r PackageIdentifier
337 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
339 -- globVersion means "all versions"
340 globVersion :: Version
341 globVersion = Version{ versionBranch=[], versionTags=["*"] }
343 -- -----------------------------------------------------------------------------
346 -- Some commands operate on a single database:
347 -- register, unregister, expose, hide
348 -- however these commands also check the union of the available databases
349 -- in order to check consistency. For example, register will check that
350 -- dependencies exist before registering a package.
352 -- Some commands operate on multiple databases, with overlapping semantics:
353 -- list, describe, field
355 type PackageDBName = FilePath
356 type PackageDB = [InstalledPackageInfo]
358 type NamedPackageDB = (PackageDBName, PackageDB)
359 type PackageDBStack = [NamedPackageDB]
360 -- A stack of package databases. Convention: head is the topmost
361 -- in the stack. Earlier entries override later one.
363 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
364 allPackagesInStack = concatMap snd
366 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
367 getPkgDatabases modify my_flags = do
368 -- first we determine the location of the global package config. On Windows,
369 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
370 -- location is passed to the binary using the --global-config flag by the
372 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
374 case [ f | FlagGlobalConfig f <- my_flags ] of
375 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
377 Nothing -> die err_msg
379 do let path1 = dir </> "package.conf"
380 path2 = dir </> ".." </> ".." </> ".."
381 </> "inplace-datadir"
383 exists1 <- doesFileExist path1
384 exists2 <- doesFileExist path2
385 if exists1 then return path1
386 else if exists2 then return path2
387 else die "Can't find package.conf"
388 fs -> return (last fs)
390 let global_conf_dir = global_conf ++ ".d"
391 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
393 if global_conf_dir_exists
394 then do files <- getDirectoryContents global_conf_dir
395 return [ global_conf_dir ++ '/' : file
397 , isSuffixOf ".conf" file]
400 let no_user_db = FlagNoUserDb `elem` my_flags
402 -- get the location of the user package database, and create it if necessary
403 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
404 appdir <- try $ getAppUserDataDirectory "ghc"
407 if no_user_db then return Nothing else
410 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
411 user_conf = dir </> subdir </> "package.conf"
412 user_exists <- doesFileExist user_conf
413 return (Just (user_conf,user_exists))
417 -- If the user database doesn't exist, and this command isn't a
418 -- "modify" command, then we won't attempt to create or use it.
420 | Just (user_conf,user_exists) <- mb_user_conf,
421 modify || user_exists = user_conf : global_confs ++ [global_conf]
422 | otherwise = global_confs ++ [global_conf]
424 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
427 Left _ -> sys_databases
429 | last cs == "" -> init cs ++ sys_databases
431 where cs = parseSearchPath path
433 -- The "global" database is always the one at the bottom of the stack.
434 -- This is the database we modify by default.
435 virt_global_conf = last env_stack
437 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
438 where is_db_flag FlagUser
439 | Just (user_conf, _user_exists) <- mb_user_conf
441 is_db_flag FlagGlobal = Just virt_global_conf
442 is_db_flag (FlagConfig f) = Just f
443 is_db_flag _ = Nothing
445 (final_stack, to_modify) <-
447 then -- For a "read" command, we use all the databases
448 -- specified on the command line. If there are no
449 -- command-line flags specifying databases, the default
450 -- is to use all the ones we know about.
451 if null db_flags then return (env_stack, Nothing)
452 else return (reverse (nub db_flags), Nothing)
454 -- For a "modify" command, treat all the databases as
455 -- a stack, where we are modifying the top one, but it
456 -- can refer to packages in databases further down the
459 -- -f flags on the command line add to the database
460 -- stack, unless any of them are present in the stack
462 flag_stack = filter (`notElem` env_stack)
463 [ f | FlagConfig f <- reverse my_flags ]
466 -- the database we actually modify is the one mentioned
467 -- rightmost on the command-line.
468 to_modify = if null db_flags
469 then Just virt_global_conf
470 else Just (last db_flags)
472 return (flag_stack, to_modify)
474 db_stack <- mapM readParseDatabase final_stack
475 return (db_stack, to_modify)
477 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
478 readParseDatabase filename = do
479 str <- readFile filename `catchIO` \_ -> return emptyPackageConfig
480 let packages = map convertPackageInfoIn $ read str
481 Exception.evaluate packages
483 die ("error while parsing " ++ filename ++ ": " ++ show e)
484 return (filename,packages)
486 emptyPackageConfig :: String
487 emptyPackageConfig = "[]"
489 -- -----------------------------------------------------------------------------
492 registerPackage :: FilePath
494 -> Bool -- auto_ghci_libs
498 registerPackage input my_flags auto_ghci_libs update force = do
499 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
501 db_to_operate_on = my_head "register" $
502 filter ((== to_modify).fst) db_stack
507 putStr "Reading package info from stdin ... "
510 putStr ("Reading package info from " ++ show f ++ " ... ")
513 expanded <- expandEnvVars s force
515 pkg <- parsePackageInfo expanded
518 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
519 -- truncate the stack for validation, because we don't allow
520 -- packages lower in the stack to refer to those higher up.
521 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
522 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
523 not_this p = package p /= package pkg
524 writeNewConfig to_modify new_details
528 -> IO InstalledPackageInfo
529 parsePackageInfo str =
530 case parseInstalledPackageInfo str of
531 ParseOk _warns ok -> return ok
532 ParseFailed err -> case locatedErrorMsg err of
533 (Nothing, s) -> die s
534 (Just l, s) -> die (show l ++ ": " ++ s)
536 -- -----------------------------------------------------------------------------
537 -- Exposing, Hiding, Unregistering are all similar
539 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
540 exposePackage = modifyPackage (\p -> [p{exposed=True}])
542 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
543 hidePackage = modifyPackage (\p -> [p{exposed=False}])
545 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
546 unregisterPackage = modifyPackage (\_ -> [])
549 :: (InstalledPackageInfo -> [InstalledPackageInfo])
554 modifyPackage fn pkgid my_flags force = do
555 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
556 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
557 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
558 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
560 pids = map package ps
562 | package pkg `elem` pids = fn pkg
564 new_config = concat (map modify pkgs)
567 old_broken = brokenPackages (allPackagesInStack db_stack)
568 rest_of_stack = [ (nm, mypkgs)
569 | (nm, mypkgs) <- db_stack, nm /= db_name ]
570 new_stack = (db_name,new_config) : rest_of_stack
571 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
572 newly_broken = filter (`notElem` map package old_broken) new_broken
574 when (not (null newly_broken)) $
575 dieOrForceAll force ("unregistering " ++ display pkgid ++
576 " would break the following packages: "
577 ++ unwords (map display newly_broken))
579 writeNewConfig db_name new_config
581 -- -----------------------------------------------------------------------------
584 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
585 listPackages my_flags mPackageName mModuleName = do
586 let simple_output = FlagSimpleOutput `elem` my_flags
587 (db_stack, _) <- getPkgDatabases False my_flags
588 let db_stack_filtered -- if a package is given, filter out all other packages
589 | Just this <- mPackageName =
590 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
592 | Just match <- mModuleName = -- packages which expose mModuleName
593 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
595 | otherwise = db_stack
598 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
599 where sort_pkgs = sortBy cmpPkgIds
600 cmpPkgIds pkg1 pkg2 =
601 case pkgName p1 `compare` pkgName p2 of
604 EQ -> pkgVersion p1 `compare` pkgVersion p2
605 where (p1,p2) = (package pkg1, package pkg2)
607 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
609 pkg_map = allPackagesInStack db_stack
610 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
612 show_func (reverse db_stack_sorted)
614 where show_normal pkg_map (db_name,pkg_confs) =
615 hPutStrLn stdout (render $
616 text db_name <> colon $$ nest 4 packages
618 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
619 broken = map package (brokenPackages pkg_map)
621 | package p `elem` broken = braces doc
623 | otherwise = parens doc
624 where doc = text (display (package p))
626 show_simple db_stack = do
627 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
629 pkgs = map showPkg $ sortBy compPkgIdVer $
630 map package (allPackagesInStack db_stack)
631 when (not (null pkgs)) $
632 hPutStrLn stdout $ concat $ intersperse " " pkgs
634 -- -----------------------------------------------------------------------------
635 -- Prints the highest (hidden or exposed) version of a package
637 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
638 latestPackage my_flags pkgid = do
639 (db_stack, _) <- getPkgDatabases False my_flags
640 ps <- findPackages db_stack (Id pkgid)
641 show_pkg (sortBy compPkgIdVer (map package ps))
643 show_pkg [] = die "no matches"
644 show_pkg pids = hPutStrLn stdout (display (last pids))
646 -- -----------------------------------------------------------------------------
649 describePackage :: [Flag] -> PackageArg -> IO ()
650 describePackage my_flags pkgarg = do
651 (db_stack, _) <- getPkgDatabases False my_flags
652 ps <- findPackages db_stack pkgarg
655 dumpPackages :: [Flag] -> IO ()
656 dumpPackages my_flags = do
657 (db_stack, _) <- getPkgDatabases False my_flags
658 doDump (allPackagesInStack db_stack)
660 doDump :: [InstalledPackageInfo] -> IO ()
661 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
663 -- PackageId is can have globVersion for the version
664 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
665 findPackages db_stack pkgarg
666 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
668 findPackagesByDB :: PackageDBStack -> PackageArg
669 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
670 findPackagesByDB db_stack pkgarg
671 = case [ (db, matched)
672 | db@(_, pkgs) <- db_stack,
673 let matched = filter (pkgarg `matchesPkg`) pkgs,
674 not (null matched) ] of
675 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
678 pkg_msg (Id pkgid) = display pkgid
679 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
681 matches :: PackageIdentifier -> PackageIdentifier -> Bool
683 = (pkgName pid == pkgName pid')
684 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
686 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
687 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
688 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
690 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
691 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
693 -- -----------------------------------------------------------------------------
696 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
697 describeField my_flags pkgarg fields = do
698 (db_stack, _) <- getPkgDatabases False my_flags
699 fns <- toFields fields
700 ps <- findPackages db_stack pkgarg
701 let top_dir = takeDirectory (fst (last db_stack))
702 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
703 where toFields [] = return []
704 toFields (f:fs) = case toField f of
705 Nothing -> die ("unknown field: " ++ f)
706 Just fn -> do fns <- toFields fs
708 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
710 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
711 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
712 -- with the current topdir (obtained from the -B option).
713 mungePackagePaths top_dir ps = map munge_pkg ps
715 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
716 includeDirs = munge_paths (includeDirs p),
717 libraryDirs = munge_paths (libraryDirs p),
718 frameworkDirs = munge_paths (frameworkDirs p),
719 haddockInterfaces = munge_paths (haddockInterfaces p),
720 haddockHTMLs = munge_paths (haddockHTMLs p)
723 munge_paths = map munge_path
726 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
727 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
730 toHttpPath p = "file:///" ++ p
732 maybePrefixMatch :: String -> String -> Maybe String
733 maybePrefixMatch [] rest = Just rest
734 maybePrefixMatch (_:_) [] = Nothing
735 maybePrefixMatch (p:pat) (r:rest)
736 | p == r = maybePrefixMatch pat rest
737 | otherwise = Nothing
739 toField :: String -> Maybe (InstalledPackageInfo -> String)
740 -- backwards compatibility:
741 toField "import_dirs" = Just $ strList . importDirs
742 toField "source_dirs" = Just $ strList . importDirs
743 toField "library_dirs" = Just $ strList . libraryDirs
744 toField "hs_libraries" = Just $ strList . hsLibraries
745 toField "extra_libraries" = Just $ strList . extraLibraries
746 toField "include_dirs" = Just $ strList . includeDirs
747 toField "c_includes" = Just $ strList . includes
748 toField "package_deps" = Just $ strList . map display. depends
749 toField "extra_cc_opts" = Just $ strList . ccOptions
750 toField "extra_ld_opts" = Just $ strList . ldOptions
751 toField "framework_dirs" = Just $ strList . frameworkDirs
752 toField "extra_frameworks"= Just $ strList . frameworks
753 toField s = showInstalledPackageInfoField s
755 strList :: [String] -> String
759 -- -----------------------------------------------------------------------------
760 -- Check: Check consistency of installed packages
762 checkConsistency :: [Flag] -> IO ()
763 checkConsistency my_flags = do
764 (db_stack, _) <- getPkgDatabases True my_flags
765 -- check behaves like modify for the purposes of deciding which
766 -- databases to use, because ordering is important.
767 let pkgs = allPackagesInStack db_stack
768 broken_pkgs = brokenPackages pkgs
769 broken_ids = map package broken_pkgs
770 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
772 mapM_ (putStrLn . render . show_func) broken_why
774 show_func | FlagSimpleOutput `elem` my_flags = show_simple
775 | otherwise = show_normal
776 show_simple (pid,deps) =
777 text (display pid) <> colon
778 <+> fsep (punctuate comma (map (text . display) deps))
779 show_normal (pid,deps) =
780 text "package" <+> text (display pid) <+> text "has missing dependencies:"
781 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
784 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
785 brokenPackages pkgs = go [] pkgs
788 case partition (depsAvailable avail) not_avail of
789 ([], not_avail') -> not_avail'
790 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
792 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
794 depsAvailable pkgs_ok pkg = null dangling
795 where dangling = filter (`notElem` pids) (depends pkg)
796 pids = map package pkgs_ok
798 -- we want mutually recursive groups of package to show up
799 -- as broken. (#1750)
801 -- -----------------------------------------------------------------------------
802 -- Manipulating package.conf files
804 type InstalledPackageInfoString = InstalledPackageInfo_ String
806 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
807 convertPackageInfoOut
808 (pkgconf@(InstalledPackageInfo { exposedModules = e,
809 hiddenModules = h })) =
810 pkgconf{ exposedModules = map display e,
811 hiddenModules = map display h }
813 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
815 (pkgconf@(InstalledPackageInfo { exposedModules = e,
816 hiddenModules = h })) =
817 pkgconf{ exposedModules = map convert e,
818 hiddenModules = map convert h }
819 where convert = fromJust . simpleParse
821 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
822 writeNewConfig filename packages = do
823 hPutStr stdout "Writing new package config file... "
824 createDirectoryIfMissing True $ takeDirectory filename
825 let shown = concat $ intersperse ",\n "
826 $ map (show . convertPackageInfoOut) packages
827 fileContents = "[" ++ shown ++ "\n]"
828 writeFileAtomic filename fileContents
830 if isPermissionError e
831 then die (filename ++ ": you don't have permission to modify this file")
833 hPutStrLn stdout "done."
835 -----------------------------------------------------------------------------
836 -- Sanity-check a new package config, and automatically build GHCi libs
839 validatePackageConfig :: InstalledPackageInfo
841 -> Bool -- auto-ghc-libs
845 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
847 checkDuplicates db_stack pkg update force
848 mapM_ (checkDep db_stack force) (depends pkg)
849 checkDuplicateDepends force (depends pkg)
850 mapM_ (checkDir force) (importDirs pkg)
851 mapM_ (checkDir force) (libraryDirs pkg)
852 mapM_ (checkDir force) (includeDirs pkg)
853 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
854 -- ToDo: check these somehow?
855 -- extra_libraries :: [String],
856 -- c_includes :: [String],
858 -- When the package name and version are put together, sometimes we can
859 -- end up with a package id that cannot be parsed. This will lead to
860 -- difficulties when the user wants to refer to the package later, so
861 -- we check that the package id can be parsed properly here.
862 checkPackageId :: InstalledPackageInfo -> IO ()
864 let str = display (package ipi) in
865 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
867 [] -> die ("invalid package identifier: " ++ str)
868 _ -> die ("ambiguous package identifier: " ++ str)
870 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
871 checkDuplicates db_stack pkg update force = do
874 (_top_db_name, pkgs) : _ = db_stack
876 -- Check whether this package id already exists in this DB
878 when (not update && (pkgid `elem` map package pkgs)) $
879 die ("package " ++ display pkgid ++ " is already installed")
882 uncasep = map toLower . display
883 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
885 when (not update && not (null dups)) $ dieOrForceAll force $
886 "Package names may be treated case-insensitively in the future.\n"++
887 "Package " ++ display pkgid ++
888 " overlaps with: " ++ unwords (map display dups)
891 checkDir :: Force -> String -> IO ()
893 | "$topdir" `isPrefixOf` d = return ()
894 | "$httptopdir" `isPrefixOf` d = return ()
895 -- can't check these, because we don't know what $(http)topdir is
897 there <- doesDirectoryExist d
899 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
901 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
902 checkDep db_stack force pkgid
903 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
904 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
907 -- for backwards compat, we treat 0.0 as a special version,
908 -- and don't check that it actually exists.
909 real_version = realVersion pkgid
911 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
914 all_pkgs = allPackagesInStack db_stack
915 pkgids = map package all_pkgs
917 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
918 checkDuplicateDepends force deps
919 | null dups = return ()
920 | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
921 unwords (map display dups))
923 dups = [ p | (p:_:_) <- group (sort deps) ]
925 realVersion :: PackageIdentifier -> Bool
926 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
928 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
929 checkHSLib dirs auto_ghci_libs force lib = do
930 let batch_lib_file = "lib" ++ lib ++ ".a"
931 bs <- mapM (doesLibExistIn batch_lib_file) dirs
932 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
933 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
935 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
937 doesLibExistIn :: String -> String -> IO Bool
939 | "$topdir" `isPrefixOf` d = return True
940 | "$httptopdir" `isPrefixOf` d = return True
941 | otherwise = doesFileExist (d ++ '/':lib)
943 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
944 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
945 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
947 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
948 case [dir | (exists,dir) <- zip bs dirs, exists] of
949 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
952 ghci_lib_file = lib ++ ".o"
954 -- automatically build the GHCi version of a batch lib,
955 -- using ld --whole-archive.
957 autoBuildGHCiLib :: String -> String -> String -> IO ()
958 autoBuildGHCiLib dir batch_file ghci_file = do
959 let ghci_lib_file = dir ++ '/':ghci_file
960 batch_lib_file = dir ++ '/':batch_file
961 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
962 #if defined(darwin_HOST_OS)
963 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
964 #elif defined(mingw32_HOST_OS)
965 execDir <- getExecDir "/bin/ghc-pkg.exe"
966 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
968 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
970 when (r /= ExitSuccess) $ exitWith r
971 hPutStrLn stderr (" done.")
973 -- -----------------------------------------------------------------------------
974 -- Searching for modules
978 findModules :: [FilePath] -> IO [String]
980 mms <- mapM searchDir paths
983 searchDir path prefix = do
984 fs <- getDirectoryEntries path `catch` \_ -> return []
985 searchEntries path prefix fs
987 searchEntries path prefix [] = return []
988 searchEntries path prefix (f:fs)
989 | looks_like_a_module = do
990 ms <- searchEntries path prefix fs
991 return (prefix `joinModule` f : ms)
992 | looks_like_a_component = do
993 ms <- searchDir (path </> f) (prefix `joinModule` f)
994 ms' <- searchEntries path prefix fs
997 searchEntries path prefix fs
1000 (base,suffix) = splitFileExt f
1001 looks_like_a_module =
1002 suffix `elem` haskell_suffixes &&
1003 all okInModuleName base
1004 looks_like_a_component =
1005 null suffix && all okInModuleName base
1011 -- ---------------------------------------------------------------------------
1012 -- expanding environment variables in the package configuration
1014 expandEnvVars :: String -> Force -> IO String
1015 expandEnvVars str0 force = go str0 ""
1017 go "" acc = return $! reverse acc
1018 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1019 = do value <- lookupEnvVar var
1020 go rest (reverse value ++ acc)
1021 where close c = c == '}' || c == '\n' -- don't span newlines
1025 lookupEnvVar :: String -> IO String
1027 catch (System.Environment.getEnv nm)
1028 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1032 -----------------------------------------------------------------------------
1034 getProgramName :: IO String
1035 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1036 where str `withoutSuffix` suff
1037 | suff `isSuffixOf` str = take (length str - length suff) str
1040 bye :: String -> IO a
1041 bye s = putStr s >> exitWith ExitSuccess
1043 die :: String -> IO a
1046 dieWith :: Int -> String -> IO a
1049 prog <- getProgramName
1050 hPutStrLn stderr (prog ++ ": " ++ s)
1051 exitWith (ExitFailure ec)
1053 dieOrForceAll :: Force -> String -> IO ()
1054 dieOrForceAll ForceAll s = ignoreError s
1055 dieOrForceAll _other s = dieForcible s
1057 dieOrForceFile :: Force -> String -> IO ()
1058 dieOrForceFile ForceAll s = ignoreError s
1059 dieOrForceFile ForceFiles s = ignoreError s
1060 dieOrForceFile _other s = dieForcible s
1062 ignoreError :: String -> IO ()
1063 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1065 dieForcible :: String -> IO ()
1066 dieForcible s = die (s ++ " (use --force to override)")
1068 my_head :: String -> [a] -> a
1069 my_head s [] = error s
1070 my_head _ (x : _) = x
1072 -----------------------------------------
1073 -- Cut and pasted from ghc/compiler/main/SysTools
1075 #if defined(mingw32_HOST_OS)
1076 subst :: Char -> Char -> String -> String
1077 subst a b ls = map (\ x -> if x == a then b else x) ls
1079 unDosifyPath :: FilePath -> FilePath
1080 unDosifyPath xs = subst '\\' '/' xs
1082 getExecDir :: String -> IO (Maybe String)
1083 -- (getExecDir cmd) returns the directory in which the current
1084 -- executable, which should be called 'cmd', is running
1085 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1086 -- you'll get "/a/b/c" back as the result
1088 = allocaArray len $ \buf -> do
1089 ret <- getModuleFileName nullPtr buf len
1090 if ret == 0 then return Nothing
1091 else do s <- peekCString buf
1092 return (Just (reverse (drop (length cmd)
1093 (reverse (unDosifyPath s)))))
1095 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1097 foreign import stdcall unsafe "GetModuleFileNameA"
1098 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1100 getExecDir :: String -> IO (Maybe String)
1101 getExecDir _ = return Nothing
1104 -----------------------------------------
1105 -- Adapted from ghc/compiler/utils/Panic
1107 installSignalHandlers :: IO ()
1108 installSignalHandlers = do
1109 threadid <- myThreadId
1111 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1113 #if !defined(mingw32_HOST_OS)
1114 installHandler sigQUIT (Catch interrupt) Nothing
1115 installHandler sigINT (Catch interrupt) Nothing
1117 #elif __GLASGOW_HASKELL__ >= 603
1118 -- GHC 6.3+ has support for console events on Windows
1119 -- NOTE: running GHCi under a bash shell for some reason requires
1120 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1121 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1122 -- why --SDM 17/12/2004
1123 let sig_handler ControlC = interrupt
1124 sig_handler Break = interrupt
1125 sig_handler _ = return ()
1127 installHandler (Catch sig_handler)
1130 return () -- nothing
1133 #if __GLASGOW_HASKELL__ <= 604
1134 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1135 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1138 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1139 #if __GLASGOW_HASKELL__ >= 609
1140 catchIO = Exception.catch
1142 catchIO io handler = io `Exception.catch` handler'
1143 where handler' (Exception.IOException ioe) = handler ioe
1144 handler' e = Exception.throw e
1147 #if mingw32_HOST_OS || mingw32_TARGET_OS
1148 throwIOIO :: Exception.IOException -> IO a
1149 #if __GLASGOW_HASKELL__ >= 609
1150 throwIOIO = Exception.throwIO
1152 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1156 catchError :: IO a -> (String -> IO a) -> IO a
1157 #if __GLASGOW_HASKELL__ >= 609
1158 catchError io handler = io `Exception.catch` handler'
1159 where handler' (Exception.ErrorCall err) = handler err
1161 catchError io handler = io `Exception.catch` handler'
1162 where handler' (Exception.ErrorCall err) = handler err
1163 handler' e = Exception.throw e
1166 onException :: IO a -> IO b -> IO a
1167 #if __GLASGOW_HASKELL__ >= 609
1168 onException = Exception.onException
1170 onException io what = io `Exception.catch` \e -> do what
1175 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1176 -- to use text files here, rather than binary files.
1177 writeFileAtomic :: FilePath -> String -> IO ()
1178 writeFileAtomic targetFile content = do
1179 (newFile, newHandle) <- openNewFile targetDir template
1180 do hPutStr newHandle content
1182 #if mingw32_HOST_OS || mingw32_TARGET_OS
1183 renameFile newFile targetFile
1184 -- If the targetFile exists then renameFile will fail
1185 `catchIO` \err -> do
1186 exists <- doesFileExist targetFile
1188 then do removeFile targetFile
1189 -- Big fat hairy race condition
1190 renameFile newFile targetFile
1191 -- If the removeFile succeeds and the renameFile fails
1192 -- then we've lost the atomic property.
1195 renameFile newFile targetFile
1197 `onException` do hClose newHandle
1200 template = targetName <.> "tmp"
1201 targetDir | null targetDir_ = "."
1202 | otherwise = targetDir_
1203 --TODO: remove this when takeDirectory/splitFileName is fixed
1204 -- to always return a valid dir
1205 (targetDir_,targetName) = splitFileName targetFile
1207 -- Ugh, this is a copy/paste of code from the base library, but
1208 -- if uses 666 rather than 600 for the permissions.
1209 openNewFile :: FilePath -> String -> IO (FilePath, Handle)
1210 openNewFile dir template = do
1214 -- We split off the last extension, so we can use .foo.ext files
1215 -- for temporary files (hidden on Unix OSes). Unfortunately we're
1216 -- below filepath in the hierarchy here.
1218 case break (== '.') $ reverse template of
1219 -- First case: template contains no '.'s. Just re-reverse it.
1220 (rev_suffix, "") -> (reverse rev_suffix, "")
1221 -- Second case: template contains at least one '.'. Strip the
1222 -- dot from the prefix and prepend it to the suffix (if we don't
1223 -- do this, the unique number will get added after the '.' and
1224 -- thus be part of the extension, which is wrong.)
1225 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
1226 -- Otherwise, something is wrong, because (break (== '.')) should
1227 -- always return a pair with either the empty string or a string
1228 -- beginning with '.' as the second component.
1229 _ -> error "bug in System.IO.openTempFile"
1231 oflags = rw_flags .|. o_EXCL
1234 fd <- withCString filepath $ \ f ->
1235 c_open f oflags 0o666
1240 then findTempName (x+1)
1241 else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
1243 -- XXX We want to tell fdToHandle what the filepath is,
1244 -- as any exceptions etc will only be able to report the
1247 #if __GLASGOW_HASKELL__ >= 609
1250 fdToHandle (fromIntegral fd)
1252 `onException` c_close fd
1253 return (filepath, h)
1255 filename = prefix ++ show x ++ suffix
1256 filepath = dir `combine` filename
1258 -- XXX Copied from GHC.Handle
1259 std_flags, output_flags, rw_flags :: CInt
1260 std_flags = o_NONBLOCK .|. o_NOCTTY
1261 output_flags = std_flags .|. o_CREAT
1262 rw_flags = output_flags .|. o_RDWR
1264 -- | The function splits the given string to substrings
1265 -- using 'isSearchPathSeparator'.
1266 parseSearchPath :: String -> [FilePath]
1267 parseSearchPath path = split path
1269 split :: String -> [String]
1273 _:rest -> chunk : split rest
1277 #ifdef mingw32_HOST_OS
1278 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1282 (chunk', rest') = break isSearchPathSeparator s