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
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils
22 import Distribution.Package
23 import Distribution.Version
24 import System.FilePath
25 import System.Cmd ( rawSystem )
26 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
30 #include "../../includes/ghcconfig.h"
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
37 import Data.Char ( isSpace, toLower )
39 import System.Directory ( doesDirectoryExist, getDirectoryContents,
40 doesFileExist, renameFile, removeFile )
41 import System.Exit ( exitWith, ExitCode(..) )
42 import System.Environment ( getArgs, getProgName, getEnv )
44 import System.IO.Error (try)
45 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy, nub,
47 #if __GLASGOW_HASKELL__ > 604
48 import Data.List ( isInfixOf )
50 import Data.List ( tails )
52 import Control.Concurrent
54 #ifdef mingw32_HOST_OS
56 import Foreign.C.String
57 import GHC.ConsoleHandler
62 import IO ( isPermissionError, isDoesNotExistError )
65 import System.Process(runInteractiveCommand)
66 import qualified System.Info(os)
69 -- -----------------------------------------------------------------------------
76 case getOpt Permute (flags ++ deprecFlags) args of
77 (cli,_,[]) | FlagHelp `elem` cli -> do
78 prog <- getProgramName
79 bye (usageInfo (usageHeader prog) flags)
80 (cli,_,[]) | FlagVersion `elem` cli ->
85 prog <- getProgramName
86 die (concat errors ++ usageInfo (usageHeader prog) flags)
88 -- -----------------------------------------------------------------------------
89 -- Command-line syntax
97 | FlagGlobalConfig FilePath
106 flags :: [OptDescr Flag]
108 Option [] ["user"] (NoArg FlagUser)
109 "use the current user's package database",
110 Option [] ["global"] (NoArg FlagGlobal)
111 "use the global package database",
112 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
113 "use the specified package config file",
114 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
115 "location of the global package config",
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" ++
191 " Substring matching is supported for {module} in find-module and\n" ++
192 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
193 " open substring ends (prefix*, *suffix, *infix*).\n" ++
195 " When asked to modify a database (register, unregister, update,\n"++
196 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
197 " default. Specifying --user causes it to act on the user database,\n"++
198 " or --package-conf can be used to act on another database\n"++
199 " entirely. When multiple of these options are given, the rightmost\n"++
200 " one is used as the database to act upon.\n"++
202 " Commands that query the package database (list, latest, describe,\n"++
203 " field) operate on the list of databases specified by the flags\n"++
204 " --user, --global, and --package-conf. If none of these flags are\n"++
205 " given, the default is --global --user.\n"++
207 " The following optional flags are also accepted:\n"
209 substProg :: String -> String -> String
211 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
212 substProg prog (c:xs) = c : substProg prog xs
214 -- -----------------------------------------------------------------------------
217 data Force = ForceAll | ForceFiles | NoForce
219 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
221 runit :: [Flag] -> [String] -> IO ()
222 runit cli nonopts = do
223 installSignalHandlers -- catch ^C and clean up
224 prog <- getProgramName
227 | FlagForce `elem` cli = ForceAll
228 | FlagForceFiles `elem` cli = ForceFiles
229 | otherwise = NoForce
230 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
231 splitFields fields = unfoldr splitComma (',':fields)
232 where splitComma "" = Nothing
233 splitComma fs = Just $ break (==',') (tail fs)
235 substringCheck :: String -> Maybe (String -> Bool)
236 substringCheck "" = Nothing
237 substringCheck "*" = Just (const True)
238 substringCheck [_] = Nothing
239 substringCheck (h:t) =
240 case (h, init t, last t) of
241 ('*',s,'*') -> Just (isInfixOf (f s) . f)
242 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
243 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
245 where f | FlagIgnoreCase `elem` cli = map toLower
248 glob x | System.Info.os=="mingw32" = do
249 -- glob echoes its argument, after win32 filename globbing
250 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
251 txt <- hGetContents o
253 glob x | otherwise = return [x]
256 -- first, parse the command
259 -- dummy command to demonstrate usage and permit testing
260 -- without messing things up; use glob to selectively enable
261 -- windows filename globbing for file parameters
262 -- register, update, FlagGlobalConfig, FlagConfig; others?
263 ["glob", filename] -> do
265 glob filename >>= print
267 ["register", filename] ->
268 registerPackage filename cli auto_ghci_libs False force
269 ["update", filename] ->
270 registerPackage filename cli auto_ghci_libs True force
271 ["unregister", pkgid_str] -> do
272 pkgid <- readGlobPkgId pkgid_str
273 unregisterPackage pkgid cli
274 ["expose", pkgid_str] -> do
275 pkgid <- readGlobPkgId pkgid_str
276 exposePackage pkgid cli
277 ["hide", pkgid_str] -> do
278 pkgid <- readGlobPkgId pkgid_str
279 hidePackage pkgid cli
281 listPackages cli Nothing Nothing
282 ["list", pkgid_str] ->
283 case substringCheck pkgid_str of
284 Nothing -> do pkgid <- readGlobPkgId pkgid_str
285 listPackages cli (Just (Id pkgid)) Nothing
286 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
287 ["find-module", moduleName] -> do
288 let match = maybe (==moduleName) id (substringCheck moduleName)
289 listPackages cli Nothing (Just match)
290 ["latest", pkgid_str] -> do
291 pkgid <- readGlobPkgId pkgid_str
292 latestPackage cli pkgid
293 ["describe", pkgid_str] ->
294 case substringCheck pkgid_str of
295 Nothing -> do pkgid <- readGlobPkgId pkgid_str
296 describePackage cli (Id pkgid)
297 Just m -> describePackage cli (Substring pkgid_str m)
298 ["field", pkgid_str, fields] ->
299 case substringCheck pkgid_str of
300 Nothing -> do pkgid <- readGlobPkgId pkgid_str
301 describeField cli (Id pkgid) (splitFields fields)
302 Just m -> describeField cli (Substring pkgid_str m)
307 die ("missing command\n" ++
308 usageInfo (usageHeader prog) flags)
310 die ("command-line syntax error\n" ++
311 usageInfo (usageHeader prog) flags)
313 parseCheck :: ReadP a a -> String -> String -> IO a
314 parseCheck parser str what =
315 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
317 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
319 readGlobPkgId :: String -> IO PackageIdentifier
320 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
322 parseGlobPackageId :: ReadP r PackageIdentifier
326 (do n <- parsePackageName; string "-*"
327 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
329 -- globVersion means "all versions"
330 globVersion :: Version
331 globVersion = Version{ versionBranch=[], versionTags=["*"] }
333 -- -----------------------------------------------------------------------------
336 -- Some commands operate on a single database:
337 -- register, unregister, expose, hide
338 -- however these commands also check the union of the available databases
339 -- in order to check consistency. For example, register will check that
340 -- dependencies exist before registering a package.
342 -- Some commands operate on multiple databases, with overlapping semantics:
343 -- list, describe, field
345 type PackageDBName = FilePath
346 type PackageDB = [InstalledPackageInfo]
348 type PackageDBStack = [(PackageDBName,PackageDB)]
349 -- A stack of package databases. Convention: head is the topmost
350 -- in the stack. Earlier entries override later one.
352 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
353 getPkgDatabases modify flags = do
354 -- first we determine the location of the global package config. On Windows,
355 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
356 -- location is passed to the binary using the --global-config flag by the
358 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
360 case [ f | FlagGlobalConfig f <- flags ] of
361 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
363 Nothing -> die err_msg
364 Just dir -> return (dir </> "package.conf")
365 fs -> return (last fs)
367 let global_conf_dir = global_conf ++ ".d"
368 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
370 if global_conf_dir_exists
371 then do files <- getDirectoryContents global_conf_dir
372 return [ global_conf_dir ++ '/' : file
374 , isSuffixOf ".conf" file]
377 -- get the location of the user package database, and create it if necessary
378 appdir <- getAppUserDataDirectory "ghc"
381 subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
382 archdir = appdir </> subdir
383 user_conf = archdir </> "package.conf"
384 user_exists <- doesFileExist user_conf
386 -- If the user database doesn't exist, and this command isn't a
387 -- "modify" command, then we won't attempt to create or use it.
389 | modify || user_exists = user_conf : global_confs ++ [global_conf]
390 | otherwise = global_confs ++ [global_conf]
392 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
395 Left _ -> sys_databases
397 | last cs == "" -> init cs ++ sys_databases
399 where cs = splitSearchPath path
401 -- The "global" database is always the one at the bottom of the stack.
402 -- This is the database we modify by default.
403 virt_global_conf = last env_stack
405 let db_flags = [ f | Just f <- map is_db_flag flags ]
406 where is_db_flag FlagUser = Just user_conf
407 is_db_flag FlagGlobal = Just virt_global_conf
408 is_db_flag (FlagConfig f) = Just f
409 is_db_flag _ = Nothing
413 then -- For a "read" command, we use all the databases
414 -- specified on the command line. If there are no
415 -- command-line flags specifying databases, the default
416 -- is to use all the ones we know about.
417 if null db_flags then return env_stack
418 else return (reverse (nub db_flags))
420 -- For a "modify" command, treat all the databases as
421 -- a stack, where we are modifying the top one, but it
422 -- can refer to packages in databases further down the
425 -- -f flags on the command line add to the database
426 -- stack, unless any of them are present in the stack
428 flag_stack = filter (`notElem` env_stack)
429 [ f | FlagConfig f <- reverse flags ]
433 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
434 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
437 then modifying virt_global_conf
438 else modifying (head db_flags)
440 db_stack <- mapM readParseDatabase final_stack
443 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
444 readParseDatabase filename = do
445 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
446 let packages = read str
447 Exception.evaluate packages
448 `Exception.catch` \e->
449 die ("error while parsing " ++ filename ++ ": " ++ show e)
450 return (filename,packages)
452 emptyPackageConfig :: String
453 emptyPackageConfig = "[]"
455 -- -----------------------------------------------------------------------------
458 registerPackage :: FilePath
460 -> Bool -- auto_ghci_libs
464 registerPackage input flags auto_ghci_libs update force = do
465 db_stack <- getPkgDatabases True flags
467 db_to_operate_on = my_head "db" db_stack
468 db_filename = fst db_to_operate_on
474 putStr "Reading package info from stdin ... "
477 putStr ("Reading package info from " ++ show f ++ " ... ")
480 expanded <- expandEnvVars s force
482 pkg <- parsePackageInfo expanded
485 validatePackageConfig pkg db_stack auto_ghci_libs update force
486 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
487 not_this p = package p /= package pkg
488 savingOldConfig db_filename $
489 writeNewConfig db_filename new_details
493 -> IO InstalledPackageInfo
494 parsePackageInfo str =
495 case parseInstalledPackageInfo str of
496 ParseOk _warns ok -> return ok
497 ParseFailed err -> case locatedErrorMsg err of
498 (Nothing, s) -> die s
499 (Just l, s) -> die (show l ++ ": " ++ s)
501 -- -----------------------------------------------------------------------------
502 -- Exposing, Hiding, Unregistering are all similar
504 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
505 exposePackage = modifyPackage (\p -> [p{exposed=True}])
507 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
508 hidePackage = modifyPackage (\p -> [p{exposed=False}])
510 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
511 unregisterPackage = modifyPackage (\p -> [])
514 :: (InstalledPackageInfo -> [InstalledPackageInfo])
518 modifyPackage fn pkgid flags = do
519 db_stack <- getPkgDatabases True{-modify-} flags
520 let ((db_name, pkgs) : _) = db_stack
521 ps <- findPackages [(db_name,pkgs)] (Id pkgid)
522 let pids = map package ps
523 let new_config = concat (map modify pkgs)
525 | package pkg `elem` pids = fn pkg
527 savingOldConfig db_name $
528 writeNewConfig db_name new_config
530 -- -----------------------------------------------------------------------------
533 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
534 listPackages flags mPackageName mModuleName = do
535 let simple_output = FlagSimpleOutput `elem` flags
536 db_stack <- getPkgDatabases False flags
537 let db_stack_filtered -- if a package is given, filter out all other packages
538 | Just this <- mPackageName =
539 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
541 | Just match <- mModuleName = -- packages which expose mModuleName
542 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
544 | otherwise = db_stack
547 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
548 where sort_pkgs = sortBy cmpPkgIds
549 cmpPkgIds pkg1 pkg2 =
550 case pkgName p1 `compare` pkgName p2 of
553 EQ -> pkgVersion p1 `compare` pkgVersion p2
554 where (p1,p2) = (package pkg1, package pkg2)
556 match `exposedInPkg` pkg = any match (exposedModules pkg)
558 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
559 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
561 show_func (reverse db_stack_sorted)
563 where show_normal pkg_map (db_name,pkg_confs) =
564 hPutStrLn stdout (render $
565 text db_name <> colon $$ nest 4 packages
567 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
569 | isBrokenPackage p pkg_map = braces doc
571 | otherwise = parens doc
572 where doc = text (showPackageId (package p))
574 show_simple db_stack = do
575 let showPkg = if FlagNamesOnly `elem` flags then pkgName
577 pkgs = map showPkg $ sortBy compPkgIdVer $
578 map package (concatMap snd db_stack)
579 when (not (null pkgs)) $
580 hPutStrLn stdout $ concat $ intersperse " " pkgs
582 -- -----------------------------------------------------------------------------
583 -- Prints the highest (hidden or exposed) version of a package
585 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
586 latestPackage flags pkgid = do
587 db_stack <- getPkgDatabases False flags
588 ps <- findPackages db_stack (Id pkgid)
589 show_pkg (sortBy compPkgIdVer (map package ps))
591 show_pkg [] = die "no matches"
592 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
594 -- -----------------------------------------------------------------------------
597 describePackage :: [Flag] -> PackageArg -> IO ()
598 describePackage flags pkgarg = do
599 db_stack <- getPkgDatabases False flags
600 ps <- findPackages db_stack pkgarg
601 mapM_ (putStrLn . showInstalledPackageInfo) ps
603 -- PackageId is can have globVersion for the version
604 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
605 findPackages db_stack pkgarg
606 = case [ p | p <- all_pkgs, pkgarg `matchesPkg` p ] of
607 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
610 all_pkgs = concat (map snd db_stack)
611 pkg_msg (Id pkgid) = showPackageId pkgid
612 pkg_msg (Substring pkgpat _) = "matching "++pkgpat
614 matches :: PackageIdentifier -> PackageIdentifier -> Bool
616 = (pkgName pid == pkgName pid')
617 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
619 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
620 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
621 (Substring _ m) `matchesPkg` pkg = m (showPackageId (package pkg))
623 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
624 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
626 -- -----------------------------------------------------------------------------
629 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
630 describeField flags pkgarg fields = do
631 db_stack <- getPkgDatabases False flags
632 fns <- toFields fields
633 ps <- findPackages db_stack pkgarg
634 let top_dir = takeDirectory (fst (last db_stack))
635 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
636 where toFields [] = return []
637 toFields (f:fs) = case toField f of
638 Nothing -> die ("unknown field: " ++ f)
639 Just fn -> do fns <- toFields fs
641 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
643 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
644 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
645 -- with the current topdir (obtained from the -B option).
646 mungePackagePaths top_dir ps = map munge_pkg ps
648 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
649 includeDirs = munge_paths (includeDirs p),
650 libraryDirs = munge_paths (libraryDirs p),
651 frameworkDirs = munge_paths (frameworkDirs p),
652 haddockInterfaces = munge_paths (haddockInterfaces p),
653 haddockHTMLs = munge_paths (haddockHTMLs p)
656 munge_paths = map munge_path
659 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
660 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
663 toHttpPath p = "file:///" ++ p
665 maybePrefixMatch :: String -> String -> Maybe String
666 maybePrefixMatch [] rest = Just rest
667 maybePrefixMatch (_:_) [] = Nothing
668 maybePrefixMatch (p:pat) (r:rest)
669 | p == r = maybePrefixMatch pat rest
670 | otherwise = Nothing
672 toField :: String -> Maybe (InstalledPackageInfo -> String)
673 -- backwards compatibility:
674 toField "import_dirs" = Just $ strList . importDirs
675 toField "source_dirs" = Just $ strList . importDirs
676 toField "library_dirs" = Just $ strList . libraryDirs
677 toField "hs_libraries" = Just $ strList . hsLibraries
678 toField "extra_libraries" = Just $ strList . extraLibraries
679 toField "include_dirs" = Just $ strList . includeDirs
680 toField "c_includes" = Just $ strList . includes
681 toField "package_deps" = Just $ strList . map showPackageId. depends
682 toField "extra_cc_opts" = Just $ strList . ccOptions
683 toField "extra_ld_opts" = Just $ strList . ldOptions
684 toField "framework_dirs" = Just $ strList . frameworkDirs
685 toField "extra_frameworks"= Just $ strList . frameworks
686 toField s = showInstalledPackageInfoField s
688 strList :: [String] -> String
692 -- -----------------------------------------------------------------------------
693 -- Check: Check consistency of installed packages
695 checkConsistency :: [Flag] -> IO ()
696 checkConsistency flags = do
697 db_stack <- getPkgDatabases True flags
698 -- check behaves like modify for the purposes of deciding which
699 -- databases to use, because ordering is important.
700 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
703 let broken_deps = missingPackageDeps p pkgs
704 guard (not . null $ broken_deps)
705 return (pid, broken_deps)
706 mapM_ (putStrLn . render . show_func) broken_pkgs
708 show_func | FlagSimpleOutput `elem` flags = show_simple
709 | otherwise = show_normal
710 show_simple (pid,deps) =
711 text (showPackageId pid) <> colon
712 <+> fsep (punctuate comma (map (text . showPackageId) deps))
713 show_normal (pid,deps) =
714 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
715 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
717 missingPackageDeps :: InstalledPackageInfo
718 -> [(PackageIdentifier, InstalledPackageInfo)]
719 -> [PackageIdentifier]
720 missingPackageDeps pkg pkg_map =
721 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
722 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map),
723 isBrokenPackage p pkg_map]
725 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
726 isBrokenPackage pkg pkg_map
727 = not . null $ missingPackageDeps pkg (filter notme pkg_map)
728 where notme (p,ipi) = package pkg /= p
729 -- remove p from the database when we invoke missingPackageDeps,
730 -- because we want mutually recursive groups of package to show up
731 -- as broken. (#1750)
733 -- -----------------------------------------------------------------------------
734 -- Manipulating package.conf files
736 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
737 writeNewConfig filename packages = do
738 hPutStr stdout "Writing new package config file... "
739 createDirectoryIfMissing True $ takeDirectory filename
740 h <- openFile filename WriteMode `catch` \e ->
741 if isPermissionError e
742 then die (filename ++ ": you don't have permission to modify this file")
744 let shown = concat $ intersperse ",\n " $ map show packages
745 fileContents = "[" ++ shown ++ "\n]"
746 hPutStrLn h fileContents
748 hPutStrLn stdout "done."
750 savingOldConfig :: FilePath -> IO () -> IO ()
751 savingOldConfig filename io = Exception.block $ do
752 hPutStr stdout "Saving old package config file... "
753 -- mv rather than cp because we've already done an hGetContents
754 -- on this file so we won't be able to open it for writing
755 -- unless we move the old one out of the way...
756 let oldFile = filename ++ ".old"
757 restore_on_error <- catch (renameFile filename oldFile >> return True) $
759 unless (isDoesNotExistError err) $ do
760 hPutStrLn stderr (unwords ["Unable to rename", show filename,
764 (do hPutStrLn stdout "done."; io)
765 `Exception.catch` \e -> do
766 hPutStr stdout ("WARNING: an error was encountered while writing "
767 ++ "the new configuration.\n")
768 -- remove any partially complete new version:
769 try (removeFile filename)
770 -- and attempt to restore the old one, if we had one:
771 when restore_on_error $ do
772 hPutStr stdout "Attempting to restore the old configuration... "
773 do renameFile oldFile filename
774 hPutStrLn stdout "done."
775 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
776 -- Note the above renameFile sometimes fails on Windows with
777 -- "permission denied", I have no idea why --SDM.
780 -----------------------------------------------------------------------------
781 -- Sanity-check a new package config, and automatically build GHCi libs
784 validatePackageConfig :: InstalledPackageInfo
786 -> Bool -- auto-ghc-libs
790 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
792 checkDuplicates db_stack pkg update force
793 mapM_ (checkDep db_stack force) (depends pkg)
794 mapM_ (checkDir force) (importDirs pkg)
795 mapM_ (checkDir force) (libraryDirs pkg)
796 mapM_ (checkDir force) (includeDirs pkg)
797 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
798 -- ToDo: check these somehow?
799 -- extra_libraries :: [String],
800 -- c_includes :: [String],
802 -- When the package name and version are put together, sometimes we can
803 -- end up with a package id that cannot be parsed. This will lead to
804 -- difficulties when the user wants to refer to the package later, so
805 -- we check that the package id can be parsed properly here.
806 checkPackageId :: InstalledPackageInfo -> IO ()
808 let str = showPackageId (package ipi) in
809 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
811 [] -> die ("invalid package identifier: " ++ str)
812 _ -> die ("ambiguous package identifier: " ++ str)
814 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
815 checkDuplicates db_stack pkg update force = do
818 (_top_db_name, pkgs) : _ = db_stack
820 -- Check whether this package id already exists in this DB
822 when (not update && (pkgid `elem` map package pkgs)) $
823 die ("package " ++ showPackageId pkgid ++ " is already installed")
826 uncasep = map toLower . showPackageId
827 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
829 when (not update && not (null dups)) $ dieOrForceAll force $
830 "Package names may be treated case-insensitively in the future.\n"++
831 "Package " ++ showPackageId pkgid ++
832 " overlaps with: " ++ unwords (map showPackageId dups)
835 checkDir :: Force -> String -> IO ()
837 | "$topdir" `isPrefixOf` d = return ()
838 | "$httptopdir" `isPrefixOf` d = return ()
839 -- can't check these, because we don't know what $(http)topdir is
841 there <- doesDirectoryExist d
843 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
845 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
846 checkDep db_stack force pkgid
847 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
848 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
851 -- for backwards compat, we treat 0.0 as a special version,
852 -- and don't check that it actually exists.
853 real_version = realVersion pkgid
855 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
858 all_pkgs = concat (map snd db_stack)
859 pkgids = map package all_pkgs
861 realVersion :: PackageIdentifier -> Bool
862 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
864 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
865 checkHSLib dirs auto_ghci_libs force lib = do
866 let batch_lib_file = "lib" ++ lib ++ ".a"
867 bs <- mapM (doesLibExistIn batch_lib_file) dirs
868 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
869 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
871 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
873 doesLibExistIn :: String -> String -> IO Bool
875 | "$topdir" `isPrefixOf` d = return True
876 | "$httptopdir" `isPrefixOf` d = return True
877 | otherwise = doesFileExist (d ++ '/':lib)
879 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
880 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
881 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
883 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
884 case [dir | (exists,dir) <- zip bs dirs, exists] of
885 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
888 ghci_lib_file = lib ++ ".o"
890 -- automatically build the GHCi version of a batch lib,
891 -- using ld --whole-archive.
893 autoBuildGHCiLib :: String -> String -> String -> IO ()
894 autoBuildGHCiLib dir batch_file ghci_file = do
895 let ghci_lib_file = dir ++ '/':ghci_file
896 batch_lib_file = dir ++ '/':batch_file
897 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
898 #if defined(darwin_HOST_OS)
899 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
900 #elif defined(mingw32_HOST_OS)
901 execDir <- getExecDir "/bin/ghc-pkg.exe"
902 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
904 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
906 when (r /= ExitSuccess) $ exitWith r
907 hPutStrLn stderr (" done.")
909 -- -----------------------------------------------------------------------------
910 -- Searching for modules
914 findModules :: [FilePath] -> IO [String]
916 mms <- mapM searchDir paths
919 searchDir path prefix = do
920 fs <- getDirectoryEntries path `catch` \_ -> return []
921 searchEntries path prefix fs
923 searchEntries path prefix [] = return []
924 searchEntries path prefix (f:fs)
925 | looks_like_a_module = do
926 ms <- searchEntries path prefix fs
927 return (prefix `joinModule` f : ms)
928 | looks_like_a_component = do
929 ms <- searchDir (path </> f) (prefix `joinModule` f)
930 ms' <- searchEntries path prefix fs
933 searchEntries path prefix fs
936 (base,suffix) = splitFileExt f
937 looks_like_a_module =
938 suffix `elem` haskell_suffixes &&
939 all okInModuleName base
940 looks_like_a_component =
941 null suffix && all okInModuleName base
947 -- ---------------------------------------------------------------------------
948 -- expanding environment variables in the package configuration
950 expandEnvVars :: String -> Force -> IO String
951 expandEnvVars str force = go str ""
953 go "" acc = return $! reverse acc
954 go ('$':'{':str) acc | (var, '}':rest) <- break close str
955 = do value <- lookupEnvVar var
956 go rest (reverse value ++ acc)
957 where close c = c == '}' || c == '\n' -- don't span newlines
961 lookupEnvVar :: String -> IO String
963 catch (System.Environment.getEnv nm)
964 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
968 -----------------------------------------------------------------------------
970 getProgramName :: IO String
971 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
972 where str `withoutSuffix` suff
973 | suff `isSuffixOf` str = take (length str - length suff) str
976 bye :: String -> IO a
977 bye s = putStr s >> exitWith ExitSuccess
979 die :: String -> IO a
982 prog <- getProgramName
983 hPutStrLn stderr (prog ++ ": " ++ s)
984 exitWith (ExitFailure 1)
986 dieOrForceAll :: Force -> String -> IO ()
987 dieOrForceAll ForceAll s = ignoreError s
988 dieOrForceAll _other s = dieForcible s
990 dieOrForceFile :: Force -> String -> IO ()
991 dieOrForceFile ForceAll s = ignoreError s
992 dieOrForceFile ForceFiles s = ignoreError s
993 dieOrForceFile _other s = dieForcible s
995 ignoreError :: String -> IO ()
996 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
998 dieForcible :: String -> IO ()
999 dieForcible s = die (s ++ " (use --force to override)")
1001 my_head :: String -> [a] -> a
1002 my_head s [] = error s
1003 my_head s (x:xs) = x
1005 -----------------------------------------
1006 -- Cut and pasted from ghc/compiler/main/SysTools
1008 #if defined(mingw32_HOST_OS)
1009 subst :: Char -> Char -> String -> String
1010 subst a b ls = map (\ x -> if x == a then b else x) ls
1012 unDosifyPath :: FilePath -> FilePath
1013 unDosifyPath xs = subst '\\' '/' xs
1015 getExecDir :: String -> IO (Maybe String)
1016 -- (getExecDir cmd) returns the directory in which the current
1017 -- executable, which should be called 'cmd', is running
1018 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1019 -- you'll get "/a/b/c" back as the result
1021 = allocaArray len $ \buf -> do
1022 ret <- getModuleFileName nullPtr buf len
1023 if ret == 0 then return Nothing
1024 else do s <- peekCString buf
1025 return (Just (reverse (drop (length cmd)
1026 (reverse (unDosifyPath s)))))
1028 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1030 foreign import stdcall unsafe "GetModuleFileNameA"
1031 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1033 getExecDir :: String -> IO (Maybe String)
1034 getExecDir _ = return Nothing
1037 -----------------------------------------
1038 -- Adapted from ghc/compiler/utils/Panic
1040 installSignalHandlers :: IO ()
1041 installSignalHandlers = do
1042 threadid <- myThreadId
1044 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1046 #if !defined(mingw32_HOST_OS)
1047 installHandler sigQUIT (Catch interrupt) Nothing
1048 installHandler sigINT (Catch interrupt) Nothing
1050 #elif __GLASGOW_HASKELL__ >= 603
1051 -- GHC 6.3+ has support for console events on Windows
1052 -- NOTE: running GHCi under a bash shell for some reason requires
1053 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1054 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1055 -- why --SDM 17/12/2004
1056 let sig_handler ControlC = interrupt
1057 sig_handler Break = interrupt
1058 sig_handler _ = return ()
1060 installHandler (Catch sig_handler)
1063 return () -- nothing
1066 #if __GLASGOW_HASKELL__ <= 604
1067 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1068 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)