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
27 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
28 import Compat.RawSystem ( rawSystem )
30 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
31 import System.Cmd ( rawSystem )
36 #include "../../includes/ghcconfig.h"
38 import System.Console.GetOpt
39 import Text.PrettyPrint
40 import qualified Control.Exception as Exception
43 import Data.Char ( isSpace, toLower )
45 import System.Directory ( doesDirectoryExist, getDirectoryContents,
46 doesFileExist, renameFile, removeFile )
47 import System.Exit ( exitWith, ExitCode(..) )
48 import System.Environment ( getArgs, getProgName, getEnv )
50 import System.IO.Error (try)
51 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy, nub,
53 #if __GLASGOW_HASKELL__ > 604
54 import Data.List ( isInfixOf )
56 import Data.List ( tails )
58 import Control.Concurrent
60 #ifdef mingw32_HOST_OS
62 import Foreign.C.String
63 import GHC.ConsoleHandler
68 import IO ( isPermissionError, isDoesNotExistError )
71 import System.Process(runInteractiveCommand)
72 import qualified System.Info(os)
75 -- -----------------------------------------------------------------------------
82 case getOpt Permute (flags ++ deprecFlags) args of
83 (cli,_,[]) | FlagHelp `elem` cli -> do
84 prog <- getProgramName
85 bye (usageInfo (usageHeader prog) flags)
86 (cli,_,[]) | FlagVersion `elem` cli ->
91 prog <- getProgramName
92 die (concat errors ++ usageInfo (usageHeader prog) flags)
94 -- -----------------------------------------------------------------------------
95 -- Command-line syntax
102 | FlagConfig FilePath
103 | FlagGlobalConfig FilePath
112 flags :: [OptDescr Flag]
114 Option [] ["user"] (NoArg FlagUser)
115 "use the current user's package database",
116 Option [] ["global"] (NoArg FlagGlobal)
117 "use the global package database",
118 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
119 "use the specified package config file",
120 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
121 "location of the global package config",
122 Option [] ["force"] (NoArg FlagForce)
123 "ignore missing dependencies, directories, and libraries",
124 Option [] ["force-files"] (NoArg FlagForceFiles)
125 "ignore missing directories and libraries only",
126 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
127 "automatically build libs for GHCi (with register)",
128 Option ['?'] ["help"] (NoArg FlagHelp)
129 "display this help and exit",
130 Option ['V'] ["version"] (NoArg FlagVersion)
131 "output version information and exit",
132 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
133 "print output in easy-to-parse format for some commands",
134 Option [] ["names-only"] (NoArg FlagNamesOnly)
135 "only print package names, not versions; can only be used with list --simple-output",
136 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
137 "ignore case for substring matching"
140 deprecFlags :: [OptDescr Flag]
142 -- put deprecated flags here
145 ourCopyright :: String
146 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
148 usageHeader :: String -> String
149 usageHeader prog = substProg prog $
151 " $p register {filename | -}\n" ++
152 " Register the package using the specified installed package\n" ++
153 " description. The syntax for the latter is given in the $p\n" ++
154 " documentation.\n" ++
156 " $p update {filename | -}\n" ++
157 " Register the package, overwriting any other package with the\n" ++
160 " $p unregister {pkg-id}\n" ++
161 " Unregister the specified package.\n" ++
163 " $p expose {pkg-id}\n" ++
164 " Expose the specified package.\n" ++
166 " $p hide {pkg-id}\n" ++
167 " Hide the specified package.\n" ++
169 " $p list [pkg]\n" ++
170 " List registered packages in the global database, and also the\n" ++
171 " user database if --user is given. If a package name is given\n" ++
172 " All the registered versions will be listed in ascending order.\n" ++
173 " Accepts the --simple-output flag.\n" ++
175 " $p find-module {module}\n" ++
176 " List registered packages exposing module {module} in the global\n" ++
177 " database, and also the user database if --user is given. \n" ++
178 " All the registered versions will be listed in ascending order.\n" ++
179 " Accepts the --simple-output flag.\n" ++
181 " $p latest {pkg-id}\n" ++
182 " Prints the highest registered version of a package.\n" ++
185 " Check the consistency of package depenencies and list broken packages.\n" ++
186 " Accepts the --simple-output flag.\n" ++
188 " $p describe {pkg}\n" ++
189 " Give the registered description for the specified package. The\n" ++
190 " description is returned in precisely the syntax required by $p\n" ++
193 " $p field {pkg} {field}\n" ++
194 " Extract the specified field of the package description for the\n" ++
195 " specified package. Accepts comma-separated multiple fields.\n" ++
197 " Substring matching is supported for {module} in find-module and\n" ++
198 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
199 " open substring ends (prefix*, *suffix, *infix*).\n" ++
201 " When asked to modify a database (register, unregister, update,\n"++
202 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
203 " default. Specifying --user causes it to act on the user database,\n"++
204 " or --package-conf can be used to act on another database\n"++
205 " entirely. When multiple of these options are given, the rightmost\n"++
206 " one is used as the database to act upon.\n"++
208 " Commands that query the package database (list, latest, describe,\n"++
209 " field) operate on the list of databases specified by the flags\n"++
210 " --user, --global, and --package-conf. If none of these flags are\n"++
211 " given, the default is --global --user.\n"++
213 " The following optional flags are also accepted:\n"
215 substProg :: String -> String -> String
217 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
218 substProg prog (c:xs) = c : substProg prog xs
220 -- -----------------------------------------------------------------------------
223 data Force = ForceAll | ForceFiles | NoForce
225 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
227 runit :: [Flag] -> [String] -> IO ()
228 runit cli nonopts = do
229 installSignalHandlers -- catch ^C and clean up
230 prog <- getProgramName
233 | FlagForce `elem` cli = ForceAll
234 | FlagForceFiles `elem` cli = ForceFiles
235 | otherwise = NoForce
236 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
237 splitFields fields = unfoldr splitComma (',':fields)
238 where splitComma "" = Nothing
239 splitComma fs = Just $ break (==',') (tail fs)
241 substringCheck :: String -> Maybe (String -> Bool)
242 substringCheck "" = Nothing
243 substringCheck "*" = Just (const True)
244 substringCheck [_] = Nothing
245 substringCheck (h:t) =
246 case (h, init t, last t) of
247 ('*',s,'*') -> Just (isInfixOf (f s) . f)
248 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
249 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
251 where f | FlagIgnoreCase `elem` cli = map toLower
254 glob x | System.Info.os=="mingw32" = do
255 -- glob echoes its argument, after win32 filename globbing
256 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
257 txt <- hGetContents o
259 glob x | otherwise = return [x]
262 -- first, parse the command
265 -- dummy command to demonstrate usage and permit testing
266 -- without messing things up; use glob to selectively enable
267 -- windows filename globbing for file parameters
268 -- register, update, FlagGlobalConfig, FlagConfig; others?
269 ["glob", filename] -> do
271 glob filename >>= print
273 ["register", filename] ->
274 registerPackage filename cli auto_ghci_libs False force
275 ["update", filename] ->
276 registerPackage filename cli auto_ghci_libs True force
277 ["unregister", pkgid_str] -> do
278 pkgid <- readGlobPkgId pkgid_str
279 unregisterPackage pkgid cli
280 ["expose", pkgid_str] -> do
281 pkgid <- readGlobPkgId pkgid_str
282 exposePackage pkgid cli
283 ["hide", pkgid_str] -> do
284 pkgid <- readGlobPkgId pkgid_str
285 hidePackage pkgid cli
287 listPackages cli Nothing Nothing
288 ["list", pkgid_str] ->
289 case substringCheck pkgid_str of
290 Nothing -> do pkgid <- readGlobPkgId pkgid_str
291 listPackages cli (Just (Id pkgid)) Nothing
292 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
293 ["find-module", moduleName] -> do
294 let match = maybe (==moduleName) id (substringCheck moduleName)
295 listPackages cli Nothing (Just match)
296 ["latest", pkgid_str] -> do
297 pkgid <- readGlobPkgId pkgid_str
298 latestPackage cli pkgid
299 ["describe", pkgid_str] ->
300 case substringCheck pkgid_str of
301 Nothing -> do pkgid <- readGlobPkgId pkgid_str
302 describePackage cli (Id pkgid)
303 Just m -> describePackage cli (Substring pkgid_str m)
304 ["field", pkgid_str, fields] ->
305 case substringCheck pkgid_str of
306 Nothing -> do pkgid <- readGlobPkgId pkgid_str
307 describeField cli (Id pkgid) (splitFields fields)
308 Just m -> describeField cli (Substring pkgid_str m)
313 die ("missing command\n" ++
314 usageInfo (usageHeader prog) flags)
316 die ("command-line syntax error\n" ++
317 usageInfo (usageHeader prog) flags)
319 parseCheck :: ReadP a a -> String -> String -> IO a
320 parseCheck parser str what =
321 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
323 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
325 readGlobPkgId :: String -> IO PackageIdentifier
326 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
328 parseGlobPackageId :: ReadP r PackageIdentifier
332 (do n <- parsePackageName; string "-*"
333 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
335 -- globVersion means "all versions"
336 globVersion :: Version
337 globVersion = Version{ versionBranch=[], versionTags=["*"] }
339 -- -----------------------------------------------------------------------------
342 -- Some commands operate on a single database:
343 -- register, unregister, expose, hide
344 -- however these commands also check the union of the available databases
345 -- in order to check consistency. For example, register will check that
346 -- dependencies exist before registering a package.
348 -- Some commands operate on multiple databases, with overlapping semantics:
349 -- list, describe, field
351 type PackageDBName = FilePath
352 type PackageDB = [InstalledPackageInfo]
354 type PackageDBStack = [(PackageDBName,PackageDB)]
355 -- A stack of package databases. Convention: head is the topmost
356 -- in the stack. Earlier entries override later one.
358 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
359 getPkgDatabases modify flags = do
360 -- first we determine the location of the global package config. On Windows,
361 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
362 -- location is passed to the binary using the --global-config flag by the
364 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
366 case [ f | FlagGlobalConfig f <- flags ] of
367 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
369 Nothing -> die err_msg
370 Just dir -> return (dir </> "package.conf")
371 fs -> return (last fs)
373 let global_conf_dir = global_conf ++ ".d"
374 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
376 if global_conf_dir_exists
377 then do files <- getDirectoryContents global_conf_dir
378 return [ global_conf_dir ++ '/' : file
380 , isSuffixOf ".conf" file]
383 -- get the location of the user package database, and create it if necessary
384 appdir <- getAppUserDataDirectory "ghc"
387 subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
388 archdir = appdir </> subdir
389 user_conf = archdir </> "package.conf"
390 user_exists <- doesFileExist user_conf
392 -- If the user database doesn't exist, and this command isn't a
393 -- "modify" command, then we won't attempt to create or use it.
395 | modify || user_exists = user_conf : global_confs ++ [global_conf]
396 | otherwise = global_confs ++ [global_conf]
398 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
401 Left _ -> sys_databases
403 | last cs == "" -> init cs ++ sys_databases
405 where cs = splitSearchPath path
407 -- The "global" database is always the one at the bottom of the stack.
408 -- This is the database we modify by default.
409 virt_global_conf = last env_stack
411 let db_flags = [ f | Just f <- map is_db_flag flags ]
412 where is_db_flag FlagUser = Just user_conf
413 is_db_flag FlagGlobal = Just virt_global_conf
414 is_db_flag (FlagConfig f) = Just f
415 is_db_flag _ = Nothing
419 then -- For a "read" command, we use all the databases
420 -- specified on the command line. If there are no
421 -- command-line flags specifying databases, the default
422 -- is to use all the ones we know about.
423 if null db_flags then return env_stack
424 else return (reverse (nub db_flags))
426 -- For a "modify" command, treat all the databases as
427 -- a stack, where we are modifying the top one, but it
428 -- can refer to packages in databases further down the
431 -- -f flags on the command line add to the database
432 -- stack, unless any of them are present in the stack
434 flag_stack = filter (`notElem` env_stack)
435 [ f | FlagConfig f <- reverse flags ]
439 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
440 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
443 then modifying virt_global_conf
444 else modifying (head db_flags)
446 db_stack <- mapM readParseDatabase final_stack
449 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
450 readParseDatabase filename = do
451 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
452 let packages = read str
453 Exception.evaluate packages
454 `Exception.catch` \e->
455 die ("error while parsing " ++ filename ++ ": " ++ show e)
456 return (filename,packages)
458 emptyPackageConfig :: String
459 emptyPackageConfig = "[]"
461 -- -----------------------------------------------------------------------------
464 registerPackage :: FilePath
466 -> Bool -- auto_ghci_libs
470 registerPackage input flags auto_ghci_libs update force = do
471 db_stack <- getPkgDatabases True flags
473 db_to_operate_on = my_head "db" db_stack
474 db_filename = fst db_to_operate_on
480 putStr "Reading package info from stdin ... "
483 putStr ("Reading package info from " ++ show f ++ " ... ")
486 expanded <- expandEnvVars s force
488 pkg <- parsePackageInfo expanded
491 validatePackageConfig pkg db_stack auto_ghci_libs update force
492 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
493 not_this p = package p /= package pkg
494 savingOldConfig db_filename $
495 writeNewConfig db_filename new_details
499 -> IO InstalledPackageInfo
500 parsePackageInfo str =
501 case parseInstalledPackageInfo str of
502 ParseOk _warns ok -> return ok
503 ParseFailed err -> case locatedErrorMsg err of
504 (Nothing, s) -> die s
505 (Just l, s) -> die (show l ++ ": " ++ s)
507 -- -----------------------------------------------------------------------------
508 -- Exposing, Hiding, Unregistering are all similar
510 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
511 exposePackage = modifyPackage (\p -> [p{exposed=True}])
513 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
514 hidePackage = modifyPackage (\p -> [p{exposed=False}])
516 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
517 unregisterPackage = modifyPackage (\p -> [])
520 :: (InstalledPackageInfo -> [InstalledPackageInfo])
524 modifyPackage fn pkgid flags = do
525 db_stack <- getPkgDatabases True{-modify-} flags
526 let ((db_name, pkgs) : _) = db_stack
527 ps <- findPackages [(db_name,pkgs)] (Id pkgid)
528 let pids = map package ps
529 let new_config = concat (map modify pkgs)
531 | package pkg `elem` pids = fn pkg
533 savingOldConfig db_name $
534 writeNewConfig db_name new_config
536 -- -----------------------------------------------------------------------------
539 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
540 listPackages flags mPackageName mModuleName = do
541 let simple_output = FlagSimpleOutput `elem` flags
542 db_stack <- getPkgDatabases False flags
543 let db_stack_filtered -- if a package is given, filter out all other packages
544 | Just this <- mPackageName =
545 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
547 | Just match <- mModuleName = -- packages which expose mModuleName
548 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
550 | otherwise = db_stack
553 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
554 where sort_pkgs = sortBy cmpPkgIds
555 cmpPkgIds pkg1 pkg2 =
556 case pkgName p1 `compare` pkgName p2 of
559 EQ -> pkgVersion p1 `compare` pkgVersion p2
560 where (p1,p2) = (package pkg1, package pkg2)
562 match `exposedInPkg` pkg = any match (exposedModules pkg)
564 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
565 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
567 show_func (reverse db_stack_sorted)
569 where show_normal pkg_map (db_name,pkg_confs) =
570 hPutStrLn stdout (render $
571 text db_name <> colon $$ nest 4 packages
573 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
575 | isBrokenPackage p pkg_map = braces doc
577 | otherwise = parens doc
578 where doc = text (showPackageId (package p))
580 show_simple db_stack = do
581 let showPkg = if FlagNamesOnly `elem` flags then pkgName
583 pkgs = map showPkg $ sortBy compPkgIdVer $
584 map package (concatMap snd db_stack)
585 when (not (null pkgs)) $
586 hPutStrLn stdout $ concat $ intersperse " " pkgs
588 -- -----------------------------------------------------------------------------
589 -- Prints the highest (hidden or exposed) version of a package
591 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
592 latestPackage flags pkgid = do
593 db_stack <- getPkgDatabases False flags
594 ps <- findPackages db_stack (Id pkgid)
595 show_pkg (sortBy compPkgIdVer (map package ps))
597 show_pkg [] = die "no matches"
598 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
600 -- -----------------------------------------------------------------------------
603 describePackage :: [Flag] -> PackageArg -> IO ()
604 describePackage flags pkgarg = do
605 db_stack <- getPkgDatabases False flags
606 ps <- findPackages db_stack pkgarg
607 mapM_ (putStrLn . showInstalledPackageInfo) ps
609 -- PackageId is can have globVersion for the version
610 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
611 findPackages db_stack pkgarg
612 = case [ p | p <- all_pkgs, pkgarg `matchesPkg` p ] of
613 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
616 all_pkgs = concat (map snd db_stack)
617 pkg_msg (Id pkgid) = showPackageId pkgid
618 pkg_msg (Substring pkgpat _) = "matching "++pkgpat
620 matches :: PackageIdentifier -> PackageIdentifier -> Bool
622 = (pkgName pid == pkgName pid')
623 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
625 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
626 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
627 (Substring _ m) `matchesPkg` pkg = m (pkgName (package pkg))
629 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
630 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
632 -- -----------------------------------------------------------------------------
635 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
636 describeField flags pkgarg fields = do
637 db_stack <- getPkgDatabases False flags
638 fns <- toFields fields
639 ps <- findPackages db_stack pkgarg
640 let top_dir = takeDirectory (fst (last db_stack))
641 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
642 where toFields [] = return []
643 toFields (f:fs) = case toField f of
644 Nothing -> die ("unknown field: " ++ f)
645 Just fn -> do fns <- toFields fs
647 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
649 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
650 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
651 -- with the current topdir (obtained from the -B option).
652 mungePackagePaths top_dir ps = map munge_pkg ps
654 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
655 includeDirs = munge_paths (includeDirs p),
656 libraryDirs = munge_paths (libraryDirs p),
657 frameworkDirs = munge_paths (frameworkDirs p),
658 haddockInterfaces = munge_paths (haddockInterfaces p),
659 haddockHTMLs = munge_paths (haddockHTMLs p)
662 munge_paths = map munge_path
665 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
666 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
669 toHttpPath p = "file:///" ++ p
671 maybePrefixMatch :: String -> String -> Maybe String
672 maybePrefixMatch [] rest = Just rest
673 maybePrefixMatch (_:_) [] = Nothing
674 maybePrefixMatch (p:pat) (r:rest)
675 | p == r = maybePrefixMatch pat rest
676 | otherwise = Nothing
678 toField :: String -> Maybe (InstalledPackageInfo -> String)
679 -- backwards compatibility:
680 toField "import_dirs" = Just $ strList . importDirs
681 toField "source_dirs" = Just $ strList . importDirs
682 toField "library_dirs" = Just $ strList . libraryDirs
683 toField "hs_libraries" = Just $ strList . hsLibraries
684 toField "extra_libraries" = Just $ strList . extraLibraries
685 toField "include_dirs" = Just $ strList . includeDirs
686 toField "c_includes" = Just $ strList . includes
687 toField "package_deps" = Just $ strList . map showPackageId. depends
688 toField "extra_cc_opts" = Just $ strList . ccOptions
689 toField "extra_ld_opts" = Just $ strList . ldOptions
690 toField "framework_dirs" = Just $ strList . frameworkDirs
691 toField "extra_frameworks"= Just $ strList . frameworks
692 toField s = showInstalledPackageInfoField s
694 strList :: [String] -> String
698 -- -----------------------------------------------------------------------------
699 -- Check: Check consistency of installed packages
701 checkConsistency :: [Flag] -> IO ()
702 checkConsistency flags = do
703 db_stack <- getPkgDatabases True flags
704 -- check behaves like modify for the purposes of deciding which
705 -- databases to use, because ordering is important.
706 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
709 let broken_deps = missingPackageDeps p pkgs
710 guard (not . null $ broken_deps)
711 return (pid, broken_deps)
712 mapM_ (putStrLn . render . show_func) broken_pkgs
714 show_func | FlagSimpleOutput `elem` flags = show_simple
715 | otherwise = show_normal
716 show_simple (pid,deps) =
717 text (showPackageId pid) <> colon
718 <+> fsep (punctuate comma (map (text . showPackageId) deps))
719 show_normal (pid,deps) =
720 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
721 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
723 missingPackageDeps :: InstalledPackageInfo
724 -> [(PackageIdentifier, InstalledPackageInfo)]
725 -> [PackageIdentifier]
726 missingPackageDeps pkg pkg_map =
727 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
728 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map),
729 isBrokenPackage p pkg_map]
731 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
732 isBrokenPackage pkg pkg_map
733 = not . null $ missingPackageDeps pkg (filter notme pkg_map)
734 where notme (p,ipi) = package pkg /= p
735 -- remove p from the database when we invoke missingPackageDeps,
736 -- because we want mutually recursive groups of package to show up
737 -- as broken. (#1750)
739 -- -----------------------------------------------------------------------------
740 -- Manipulating package.conf files
742 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
743 writeNewConfig filename packages = do
744 hPutStr stdout "Writing new package config file... "
745 createDirectoryIfMissing True $ takeDirectory filename
746 h <- openFile filename WriteMode `catch` \e ->
747 if isPermissionError e
748 then die (filename ++ ": you don't have permission to modify this file")
750 let shown = concat $ intersperse ",\n " $ map show packages
751 fileContents = "[" ++ shown ++ "\n]"
752 hPutStrLn h fileContents
754 hPutStrLn stdout "done."
756 savingOldConfig :: FilePath -> IO () -> IO ()
757 savingOldConfig filename io = Exception.block $ do
758 hPutStr stdout "Saving old package config file... "
759 -- mv rather than cp because we've already done an hGetContents
760 -- on this file so we won't be able to open it for writing
761 -- unless we move the old one out of the way...
762 let oldFile = filename ++ ".old"
763 restore_on_error <- catch (renameFile filename oldFile >> return True) $
765 unless (isDoesNotExistError err) $ do
766 hPutStrLn stderr (unwords ["Unable to rename", show filename,
770 (do hPutStrLn stdout "done."; io)
771 `Exception.catch` \e -> do
772 hPutStr stdout ("WARNING: an error was encountered while writing "
773 ++ "the new configuration.\n")
774 -- remove any partially complete new version:
775 try (removeFile filename)
776 -- and attempt to restore the old one, if we had one:
777 when restore_on_error $ do
778 hPutStr stdout "Attempting to restore the old configuration... "
779 do renameFile oldFile filename
780 hPutStrLn stdout "done."
781 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
782 -- Note the above renameFile sometimes fails on Windows with
783 -- "permission denied", I have no idea why --SDM.
786 -----------------------------------------------------------------------------
787 -- Sanity-check a new package config, and automatically build GHCi libs
790 validatePackageConfig :: InstalledPackageInfo
792 -> Bool -- auto-ghc-libs
796 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
798 checkDuplicates db_stack pkg update force
799 mapM_ (checkDep db_stack force) (depends pkg)
800 mapM_ (checkDir force) (importDirs pkg)
801 mapM_ (checkDir force) (libraryDirs pkg)
802 mapM_ (checkDir force) (includeDirs pkg)
803 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
804 -- ToDo: check these somehow?
805 -- extra_libraries :: [String],
806 -- c_includes :: [String],
808 -- When the package name and version are put together, sometimes we can
809 -- end up with a package id that cannot be parsed. This will lead to
810 -- difficulties when the user wants to refer to the package later, so
811 -- we check that the package id can be parsed properly here.
812 checkPackageId :: InstalledPackageInfo -> IO ()
814 let str = showPackageId (package ipi) in
815 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
817 [] -> die ("invalid package identifier: " ++ str)
818 _ -> die ("ambiguous package identifier: " ++ str)
820 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
821 checkDuplicates db_stack pkg update force = do
824 (_top_db_name, pkgs) : _ = db_stack
826 -- Check whether this package id already exists in this DB
828 when (not update && (pkgid `elem` map package pkgs)) $
829 die ("package " ++ showPackageId pkgid ++ " is already installed")
832 uncasep = map toLower . showPackageId
833 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
835 when (not update && not (null dups)) $ dieOrForceAll force $
836 "Package names may be treated case-insensitively in the future.\n"++
837 "Package " ++ showPackageId pkgid ++
838 " overlaps with: " ++ unwords (map showPackageId dups)
841 checkDir :: Force -> String -> IO ()
843 | "$topdir" `isPrefixOf` d = return ()
844 | "$httptopdir" `isPrefixOf` d = return ()
845 -- can't check these, because we don't know what $(http)topdir is
847 there <- doesDirectoryExist d
849 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
851 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
852 checkDep db_stack force pkgid
853 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
854 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
857 -- for backwards compat, we treat 0.0 as a special version,
858 -- and don't check that it actually exists.
859 real_version = realVersion pkgid
861 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
864 all_pkgs = concat (map snd db_stack)
865 pkgids = map package all_pkgs
867 realVersion :: PackageIdentifier -> Bool
868 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
870 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
871 checkHSLib dirs auto_ghci_libs force lib = do
872 let batch_lib_file = "lib" ++ lib ++ ".a"
873 bs <- mapM (doesLibExistIn batch_lib_file) dirs
874 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
875 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
877 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
879 doesLibExistIn :: String -> String -> IO Bool
881 | "$topdir" `isPrefixOf` d = return True
882 | "$httptopdir" `isPrefixOf` d = return True
883 | otherwise = doesFileExist (d ++ '/':lib)
885 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
886 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
887 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
889 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
890 case [dir | (exists,dir) <- zip bs dirs, exists] of
891 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
894 ghci_lib_file = lib ++ ".o"
896 -- automatically build the GHCi version of a batch lib,
897 -- using ld --whole-archive.
899 autoBuildGHCiLib :: String -> String -> String -> IO ()
900 autoBuildGHCiLib dir batch_file ghci_file = do
901 let ghci_lib_file = dir ++ '/':ghci_file
902 batch_lib_file = dir ++ '/':batch_file
903 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
904 #if defined(darwin_HOST_OS)
905 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
906 #elif defined(mingw32_HOST_OS)
907 execDir <- getExecDir "/bin/ghc-pkg.exe"
908 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
910 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
912 when (r /= ExitSuccess) $ exitWith r
913 hPutStrLn stderr (" done.")
915 -- -----------------------------------------------------------------------------
916 -- Searching for modules
920 findModules :: [FilePath] -> IO [String]
922 mms <- mapM searchDir paths
925 searchDir path prefix = do
926 fs <- getDirectoryEntries path `catch` \_ -> return []
927 searchEntries path prefix fs
929 searchEntries path prefix [] = return []
930 searchEntries path prefix (f:fs)
931 | looks_like_a_module = do
932 ms <- searchEntries path prefix fs
933 return (prefix `joinModule` f : ms)
934 | looks_like_a_component = do
935 ms <- searchDir (path </> f) (prefix `joinModule` f)
936 ms' <- searchEntries path prefix fs
939 searchEntries path prefix fs
942 (base,suffix) = splitFileExt f
943 looks_like_a_module =
944 suffix `elem` haskell_suffixes &&
945 all okInModuleName base
946 looks_like_a_component =
947 null suffix && all okInModuleName base
953 -- ---------------------------------------------------------------------------
954 -- expanding environment variables in the package configuration
956 expandEnvVars :: String -> Force -> IO String
957 expandEnvVars str force = go str ""
959 go "" acc = return $! reverse acc
960 go ('$':'{':str) acc | (var, '}':rest) <- break close str
961 = do value <- lookupEnvVar var
962 go rest (reverse value ++ acc)
963 where close c = c == '}' || c == '\n' -- don't span newlines
967 lookupEnvVar :: String -> IO String
969 catch (System.Environment.getEnv nm)
970 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
974 -----------------------------------------------------------------------------
976 getProgramName :: IO String
977 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
978 where str `withoutSuffix` suff
979 | suff `isSuffixOf` str = take (length str - length suff) str
982 bye :: String -> IO a
983 bye s = putStr s >> exitWith ExitSuccess
985 die :: String -> IO a
988 prog <- getProgramName
989 hPutStrLn stderr (prog ++ ": " ++ s)
990 exitWith (ExitFailure 1)
992 dieOrForceAll :: Force -> String -> IO ()
993 dieOrForceAll ForceAll s = ignoreError s
994 dieOrForceAll _other s = dieForcible s
996 dieOrForceFile :: Force -> String -> IO ()
997 dieOrForceFile ForceAll s = ignoreError s
998 dieOrForceFile ForceFiles s = ignoreError s
999 dieOrForceFile _other s = dieForcible s
1001 ignoreError :: String -> IO ()
1002 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1004 dieForcible :: String -> IO ()
1005 dieForcible s = die (s ++ " (use --force to override)")
1007 my_head :: String -> [a] -> a
1008 my_head s [] = error s
1009 my_head s (x:xs) = x
1011 -----------------------------------------
1012 -- Cut and pasted from ghc/compiler/main/SysTools
1014 #if defined(mingw32_HOST_OS)
1015 subst :: Char -> Char -> String -> String
1016 subst a b ls = map (\ x -> if x == a then b else x) ls
1018 unDosifyPath :: FilePath -> FilePath
1019 unDosifyPath xs = subst '\\' '/' xs
1021 getExecDir :: String -> IO (Maybe String)
1022 -- (getExecDir cmd) returns the directory in which the current
1023 -- executable, which should be called 'cmd', is running
1024 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1025 -- you'll get "/a/b/c" back as the result
1027 = allocaArray len $ \buf -> do
1028 ret <- getModuleFileName nullPtr buf len
1029 if ret == 0 then return Nothing
1030 else do s <- peekCString buf
1031 return (Just (reverse (drop (length cmd)
1032 (reverse (unDosifyPath s)))))
1034 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1036 foreign import stdcall unsafe "GetModuleFileNameA"
1037 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1039 getExecDir :: String -> IO (Maybe String)
1040 getExecDir _ = return Nothing
1043 -----------------------------------------
1044 -- Adapted from ghc/compiler/utils/Panic
1046 installSignalHandlers :: IO ()
1047 installSignalHandlers = do
1048 threadid <- myThreadId
1050 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1052 #if !defined(mingw32_HOST_OS)
1053 installHandler sigQUIT (Catch interrupt) Nothing
1054 installHandler sigINT (Catch interrupt) Nothing
1056 #elif __GLASGOW_HASKELL__ >= 603
1057 -- GHC 6.3+ has support for console events on Windows
1058 -- NOTE: running GHCi under a bash shell for some reason requires
1059 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1060 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1061 -- why --SDM 17/12/2004
1062 let sig_handler ControlC = interrupt
1063 sig_handler Break = interrupt
1064 sig_handler _ = return ()
1066 installHandler (Catch sig_handler)
1069 return () -- nothing
1072 #if __GLASGOW_HASKELL__ <= 604
1073 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1074 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)