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)
46 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy, nub,
47 unfoldr, break, partition )
48 #if __GLASGOW_HASKELL__ > 604
49 import Data.List ( isInfixOf )
51 import Data.List ( tails )
53 import Control.Concurrent
55 #ifdef mingw32_HOST_OS
57 import Foreign.C.String
58 import GHC.ConsoleHandler
63 import IO ( isPermissionError, isDoesNotExistError )
66 import System.Process(runInteractiveCommand)
67 import qualified System.Info(os)
70 -- -----------------------------------------------------------------------------
77 case getOpt Permute (flags ++ deprecFlags) args of
78 (cli,_,[]) | FlagHelp `elem` cli -> do
79 prog <- getProgramName
80 bye (usageInfo (usageHeader prog) flags)
81 (cli,_,[]) | FlagVersion `elem` cli ->
86 prog <- getProgramName
87 die (concat errors ++ usageInfo (usageHeader prog) flags)
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
98 | FlagGlobalConfig FilePath
107 flags :: [OptDescr Flag]
109 Option [] ["user"] (NoArg FlagUser)
110 "use the current user's package database",
111 Option [] ["global"] (NoArg FlagGlobal)
112 "use the global package database",
113 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
114 "use the specified package config file",
115 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
116 "location of the global package config",
117 Option [] ["force"] (NoArg FlagForce)
118 "ignore missing dependencies, directories, and libraries",
119 Option [] ["force-files"] (NoArg FlagForceFiles)
120 "ignore missing directories and libraries only",
121 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
122 "automatically build libs for GHCi (with register)",
123 Option ['?'] ["help"] (NoArg FlagHelp)
124 "display this help and exit",
125 Option ['V'] ["version"] (NoArg FlagVersion)
126 "output version information and exit",
127 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
128 "print output in easy-to-parse format for some commands",
129 Option [] ["names-only"] (NoArg FlagNamesOnly)
130 "only print package names, not versions; can only be used with list --simple-output",
131 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
132 "ignore case for substring matching"
135 deprecFlags :: [OptDescr Flag]
137 -- put deprecated flags here
140 ourCopyright :: String
141 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
143 usageHeader :: String -> String
144 usageHeader prog = substProg prog $
146 " $p register {filename | -}\n" ++
147 " Register the package using the specified installed package\n" ++
148 " description. The syntax for the latter is given in the $p\n" ++
149 " documentation.\n" ++
151 " $p update {filename | -}\n" ++
152 " Register the package, overwriting any other package with the\n" ++
155 " $p unregister {pkg-id}\n" ++
156 " Unregister the specified package.\n" ++
158 " $p expose {pkg-id}\n" ++
159 " Expose the specified package.\n" ++
161 " $p hide {pkg-id}\n" ++
162 " Hide the specified package.\n" ++
164 " $p list [pkg]\n" ++
165 " List registered packages in the global database, and also the\n" ++
166 " user database if --user is given. If a package name is given\n" ++
167 " all the registered versions will be listed in ascending order.\n" ++
168 " Accepts the --simple-output flag.\n" ++
170 " $p find-module {module}\n" ++
171 " List registered packages exposing module {module} in the global\n" ++
172 " database, and also the user database if --user is given.\n" ++
173 " All the registered versions will be listed in ascending order.\n" ++
174 " Accepts the --simple-output flag.\n" ++
176 " $p latest {pkg-id}\n" ++
177 " Prints the highest registered version of a package.\n" ++
180 " Check the consistency of package depenencies and list broken packages.\n" ++
181 " Accepts the --simple-output flag.\n" ++
183 " $p describe {pkg}\n" ++
184 " Give the registered description for the specified package. The\n" ++
185 " description is returned in precisely the syntax required by $p\n" ++
188 " $p field {pkg} {field}\n" ++
189 " Extract the specified field of the package description for the\n" ++
190 " specified package. Accepts comma-separated multiple fields.\n" ++
193 " Dump the registered description for every package. This is like\n" ++
194 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
195 " by tools that parse the results, rather than humans.\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 force
280 ["expose", pkgid_str] -> do
281 pkgid <- readGlobPkgId pkgid_str
282 exposePackage pkgid cli force
283 ["hide", pkgid_str] -> do
284 pkgid <- readGlobPkgId pkgid_str
285 hidePackage pkgid cli force
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)
317 die ("missing command\n" ++
318 usageInfo (usageHeader prog) flags)
320 die ("command-line syntax error\n" ++
321 usageInfo (usageHeader prog) flags)
323 parseCheck :: ReadP a a -> String -> String -> IO a
324 parseCheck parser str what =
325 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
327 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
329 readGlobPkgId :: String -> IO PackageIdentifier
330 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
332 parseGlobPackageId :: ReadP r PackageIdentifier
338 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
340 -- globVersion means "all versions"
341 globVersion :: Version
342 globVersion = Version{ versionBranch=[], versionTags=["*"] }
344 -- -----------------------------------------------------------------------------
347 -- Some commands operate on a single database:
348 -- register, unregister, expose, hide
349 -- however these commands also check the union of the available databases
350 -- in order to check consistency. For example, register will check that
351 -- dependencies exist before registering a package.
353 -- Some commands operate on multiple databases, with overlapping semantics:
354 -- list, describe, field
356 type PackageDBName = FilePath
357 type PackageDB = [InstalledPackageInfo]
359 type PackageDBStack = [(PackageDBName,PackageDB)]
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
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 -- get the location of the user package database, and create it if necessary
401 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
402 appdir <- try $ getAppUserDataDirectory "ghc"
407 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
408 user_conf = dir </> subdir </> "package.conf"
409 user_exists <- doesFileExist user_conf
410 return (Just (user_conf,user_exists))
414 -- If the user database doesn't exist, and this command isn't a
415 -- "modify" command, then we won't attempt to create or use it.
417 | Just (user_conf,user_exists) <- mb_user_conf,
418 modify || user_exists = user_conf : global_confs ++ [global_conf]
419 | otherwise = global_confs ++ [global_conf]
421 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
424 Left _ -> sys_databases
426 | last cs == "" -> init cs ++ sys_databases
428 where cs = splitSearchPath path
430 -- The "global" database is always the one at the bottom of the stack.
431 -- This is the database we modify by default.
432 virt_global_conf = last env_stack
434 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
435 where is_db_flag FlagUser
436 | Just (user_conf,user_exists) <- mb_user_conf
438 is_db_flag FlagGlobal = Just virt_global_conf
439 is_db_flag (FlagConfig f) = Just f
440 is_db_flag _ = Nothing
444 then -- For a "read" command, we use all the databases
445 -- specified on the command line. If there are no
446 -- command-line flags specifying databases, the default
447 -- is to use all the ones we know about.
448 if null db_flags then return env_stack
449 else return (reverse (nub db_flags))
451 -- For a "modify" command, treat all the databases as
452 -- a stack, where we are modifying the top one, but it
453 -- can refer to packages in databases further down the
456 -- -f flags on the command line add to the database
457 -- stack, unless any of them are present in the stack
459 flag_stack = filter (`notElem` env_stack)
460 [ f | FlagConfig f <- reverse my_flags ]
464 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
465 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
468 then modifying virt_global_conf
469 else modifying (head db_flags)
471 db_stack <- mapM readParseDatabase final_stack
474 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
475 readParseDatabase filename = do
476 str <- readFile filename `catchIO` \_ -> return emptyPackageConfig
477 let packages = map convertPackageInfoIn $ read str
478 Exception.evaluate packages
480 die ("error while parsing " ++ filename ++ ": " ++ show e)
481 return (filename,packages)
483 emptyPackageConfig :: String
484 emptyPackageConfig = "[]"
486 -- -----------------------------------------------------------------------------
489 registerPackage :: FilePath
491 -> Bool -- auto_ghci_libs
495 registerPackage input my_flags auto_ghci_libs update force = do
496 db_stack <- getPkgDatabases True my_flags
498 db_to_operate_on = my_head "db" db_stack
499 db_filename = fst db_to_operate_on
505 putStr "Reading package info from stdin ... "
508 putStr ("Reading package info from " ++ show f ++ " ... ")
511 expanded <- expandEnvVars s force
513 pkg <- parsePackageInfo expanded
516 validatePackageConfig pkg db_stack auto_ghci_libs update force
517 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
518 not_this p = package p /= package pkg
519 writeNewConfig db_filename new_details
523 -> IO InstalledPackageInfo
524 parsePackageInfo str =
525 case parseInstalledPackageInfo str of
526 ParseOk _warns ok -> return ok
527 ParseFailed err -> case locatedErrorMsg err of
528 (Nothing, s) -> die s
529 (Just l, s) -> die (show l ++ ": " ++ s)
531 -- -----------------------------------------------------------------------------
532 -- Exposing, Hiding, Unregistering are all similar
534 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
535 exposePackage = modifyPackage (\p -> [p{exposed=True}])
537 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
538 hidePackage = modifyPackage (\p -> [p{exposed=False}])
540 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
541 unregisterPackage = modifyPackage (\_ -> [])
544 :: (InstalledPackageInfo -> [InstalledPackageInfo])
549 modifyPackage fn pkgid my_flags force = do
550 db_stack <- getPkgDatabases True{-modify-} my_flags
551 let old_broken = brokenPackages (allPackagesInStack db_stack)
552 let ((db_name, pkgs) : rest_of_stack) = db_stack
553 ps <- findPackages [(db_name,pkgs)] (Id pkgid)
554 let pids = map package ps
555 let new_config = concat (map modify pkgs)
557 | package pkg `elem` pids = fn pkg
559 let new_stack = (db_name,new_config) : rest_of_stack
560 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
561 newly_broken = filter (`notElem` map package old_broken) new_broken
563 when (not (null newly_broken)) $
564 dieOrForceAll force ("unregistering " ++ display pkgid ++
565 " would break the following packages: "
566 ++ unwords (map display newly_broken))
568 writeNewConfig db_name new_config
570 -- -----------------------------------------------------------------------------
573 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
574 listPackages my_flags mPackageName mModuleName = do
575 let simple_output = FlagSimpleOutput `elem` my_flags
576 db_stack <- getPkgDatabases False my_flags
577 let db_stack_filtered -- if a package is given, filter out all other packages
578 | Just this <- mPackageName =
579 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
581 | Just match <- mModuleName = -- packages which expose mModuleName
582 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
584 | otherwise = db_stack
587 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
588 where sort_pkgs = sortBy cmpPkgIds
589 cmpPkgIds pkg1 pkg2 =
590 case pkgName p1 `compare` pkgName p2 of
593 EQ -> pkgVersion p1 `compare` pkgVersion p2
594 where (p1,p2) = (package pkg1, package pkg2)
596 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
598 pkg_map = allPackagesInStack db_stack
599 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
601 show_func (reverse db_stack_sorted)
603 where show_normal pkg_map (db_name,pkg_confs) =
604 hPutStrLn stdout (render $
605 text db_name <> colon $$ nest 4 packages
607 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
608 broken = map package (brokenPackages pkg_map)
610 | package p `elem` broken = braces doc
612 | otherwise = parens doc
613 where doc = text (display (package p))
615 show_simple db_stack = do
616 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
618 pkgs = map showPkg $ sortBy compPkgIdVer $
619 map package (allPackagesInStack db_stack)
620 when (not (null pkgs)) $
621 hPutStrLn stdout $ concat $ intersperse " " pkgs
623 -- -----------------------------------------------------------------------------
624 -- Prints the highest (hidden or exposed) version of a package
626 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
627 latestPackage my_flags pkgid = do
628 db_stack <- getPkgDatabases False my_flags
629 ps <- findPackages db_stack (Id pkgid)
630 show_pkg (sortBy compPkgIdVer (map package ps))
632 show_pkg [] = die "no matches"
633 show_pkg pids = hPutStrLn stdout (display (last pids))
635 -- -----------------------------------------------------------------------------
638 describePackage :: [Flag] -> PackageArg -> IO ()
639 describePackage my_flags pkgarg = do
640 db_stack <- getPkgDatabases False my_flags
641 ps <- findPackages db_stack pkgarg
644 dumpPackages :: [Flag] -> IO ()
645 dumpPackages my_flags = do
646 db_stack <- getPkgDatabases False my_flags
647 doDump (allPackagesInStack db_stack)
649 doDump :: [InstalledPackageInfo] -> IO ()
650 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
652 -- PackageId is can have globVersion for the version
653 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
654 findPackages db_stack pkgarg
655 = case [ p | p <- all_pkgs, pkgarg `matchesPkg` p ] of
656 [] -> dieWith 2 ("cannot find package " ++ pkg_msg pkgarg)
659 all_pkgs = allPackagesInStack db_stack
660 pkg_msg (Id pkgid) = display pkgid
661 pkg_msg (Substring pkgpat _) = "matching "++pkgpat
663 matches :: PackageIdentifier -> PackageIdentifier -> Bool
665 = (pkgName pid == pkgName pid')
666 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
668 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
669 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
670 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
672 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
673 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
675 -- -----------------------------------------------------------------------------
678 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
679 describeField my_flags pkgarg fields = do
680 db_stack <- getPkgDatabases False my_flags
681 fns <- toFields fields
682 ps <- findPackages db_stack pkgarg
683 let top_dir = takeDirectory (fst (last db_stack))
684 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
685 where toFields [] = return []
686 toFields (f:fs) = case toField f of
687 Nothing -> die ("unknown field: " ++ f)
688 Just fn -> do fns <- toFields fs
690 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
692 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
693 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
694 -- with the current topdir (obtained from the -B option).
695 mungePackagePaths top_dir ps = map munge_pkg ps
697 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
698 includeDirs = munge_paths (includeDirs p),
699 libraryDirs = munge_paths (libraryDirs p),
700 frameworkDirs = munge_paths (frameworkDirs p),
701 haddockInterfaces = munge_paths (haddockInterfaces p),
702 haddockHTMLs = munge_paths (haddockHTMLs p)
705 munge_paths = map munge_path
708 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
709 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
712 toHttpPath p = "file:///" ++ p
714 maybePrefixMatch :: String -> String -> Maybe String
715 maybePrefixMatch [] rest = Just rest
716 maybePrefixMatch (_:_) [] = Nothing
717 maybePrefixMatch (p:pat) (r:rest)
718 | p == r = maybePrefixMatch pat rest
719 | otherwise = Nothing
721 toField :: String -> Maybe (InstalledPackageInfo -> String)
722 -- backwards compatibility:
723 toField "import_dirs" = Just $ strList . importDirs
724 toField "source_dirs" = Just $ strList . importDirs
725 toField "library_dirs" = Just $ strList . libraryDirs
726 toField "hs_libraries" = Just $ strList . hsLibraries
727 toField "extra_libraries" = Just $ strList . extraLibraries
728 toField "include_dirs" = Just $ strList . includeDirs
729 toField "c_includes" = Just $ strList . includes
730 toField "package_deps" = Just $ strList . map display. depends
731 toField "extra_cc_opts" = Just $ strList . ccOptions
732 toField "extra_ld_opts" = Just $ strList . ldOptions
733 toField "framework_dirs" = Just $ strList . frameworkDirs
734 toField "extra_frameworks"= Just $ strList . frameworks
735 toField s = showInstalledPackageInfoField s
737 strList :: [String] -> String
741 -- -----------------------------------------------------------------------------
742 -- Check: Check consistency of installed packages
744 checkConsistency :: [Flag] -> IO ()
745 checkConsistency my_flags = do
746 db_stack <- getPkgDatabases True my_flags
747 -- check behaves like modify for the purposes of deciding which
748 -- databases to use, because ordering is important.
749 let pkgs = allPackagesInStack db_stack
750 broken_pkgs = brokenPackages pkgs
751 broken_ids = map package broken_pkgs
752 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
754 mapM_ (putStrLn . render . show_func) broken_why
756 show_func | FlagSimpleOutput `elem` my_flags = show_simple
757 | otherwise = show_normal
758 show_simple (pid,deps) =
759 text (display pid) <> colon
760 <+> fsep (punctuate comma (map (text . display) deps))
761 show_normal (pid,deps) =
762 text "package" <+> text (display pid) <+> text "has missing dependencies:"
763 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
766 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
767 brokenPackages pkgs = go [] pkgs
770 case partition (depsAvailable avail) not_avail of
771 ([], not_avail) -> not_avail
772 (new_avail, not_avail) -> go (new_avail ++ avail) not_avail
774 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
776 depsAvailable pkgs_ok pkg = null dangling
777 where dangling = filter (`notElem` pids) (depends pkg)
778 pids = map package pkgs_ok
780 -- we want mutually recursive groups of package to show up
781 -- as broken. (#1750)
783 -- -----------------------------------------------------------------------------
784 -- Manipulating package.conf files
786 type InstalledPackageInfoString = InstalledPackageInfo_ String
788 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
789 convertPackageInfoOut
790 (pkgconf@(InstalledPackageInfo { exposedModules = e,
791 hiddenModules = h })) =
792 pkgconf{ exposedModules = map display e,
793 hiddenModules = map display h }
795 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
797 (pkgconf@(InstalledPackageInfo { exposedModules = e,
798 hiddenModules = h })) =
799 pkgconf{ exposedModules = map convert e,
800 hiddenModules = map convert h }
801 where convert = fromJust . simpleParse
803 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
804 writeNewConfig filename packages = do
805 hPutStr stdout "Writing new package config file... "
806 createDirectoryIfMissing True $ takeDirectory filename
807 let shown = concat $ intersperse ",\n "
808 $ map (show . convertPackageInfoOut) packages
809 fileContents = "[" ++ shown ++ "\n]"
810 writeFileAtomic filename fileContents
812 if isPermissionError e
813 then die (filename ++ ": you don't have permission to modify this file")
815 hPutStrLn stdout "done."
817 -----------------------------------------------------------------------------
818 -- Sanity-check a new package config, and automatically build GHCi libs
821 validatePackageConfig :: InstalledPackageInfo
823 -> Bool -- auto-ghc-libs
827 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
829 checkDuplicates db_stack pkg update force
830 mapM_ (checkDep db_stack force) (depends pkg)
831 mapM_ (checkDir force) (importDirs pkg)
832 mapM_ (checkDir force) (libraryDirs pkg)
833 mapM_ (checkDir force) (includeDirs pkg)
834 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
835 -- ToDo: check these somehow?
836 -- extra_libraries :: [String],
837 -- c_includes :: [String],
839 -- When the package name and version are put together, sometimes we can
840 -- end up with a package id that cannot be parsed. This will lead to
841 -- difficulties when the user wants to refer to the package later, so
842 -- we check that the package id can be parsed properly here.
843 checkPackageId :: InstalledPackageInfo -> IO ()
845 let str = display (package ipi) in
846 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
848 [] -> die ("invalid package identifier: " ++ str)
849 _ -> die ("ambiguous package identifier: " ++ str)
851 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
852 checkDuplicates db_stack pkg update force = do
855 (_top_db_name, pkgs) : _ = db_stack
857 -- Check whether this package id already exists in this DB
859 when (not update && (pkgid `elem` map package pkgs)) $
860 die ("package " ++ display pkgid ++ " is already installed")
863 uncasep = map toLower . display
864 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
866 when (not update && not (null dups)) $ dieOrForceAll force $
867 "Package names may be treated case-insensitively in the future.\n"++
868 "Package " ++ display pkgid ++
869 " overlaps with: " ++ unwords (map display dups)
872 checkDir :: Force -> String -> IO ()
874 | "$topdir" `isPrefixOf` d = return ()
875 | "$httptopdir" `isPrefixOf` d = return ()
876 -- can't check these, because we don't know what $(http)topdir is
878 there <- doesDirectoryExist d
880 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
882 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
883 checkDep db_stack force pkgid
884 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
885 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
888 -- for backwards compat, we treat 0.0 as a special version,
889 -- and don't check that it actually exists.
890 real_version = realVersion pkgid
892 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
895 all_pkgs = allPackagesInStack db_stack
896 pkgids = map package all_pkgs
898 realVersion :: PackageIdentifier -> Bool
899 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
901 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
902 checkHSLib dirs auto_ghci_libs force lib = do
903 let batch_lib_file = "lib" ++ lib ++ ".a"
904 bs <- mapM (doesLibExistIn batch_lib_file) dirs
905 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
906 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
908 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
910 doesLibExistIn :: String -> String -> IO Bool
912 | "$topdir" `isPrefixOf` d = return True
913 | "$httptopdir" `isPrefixOf` d = return True
914 | otherwise = doesFileExist (d ++ '/':lib)
916 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
917 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
918 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
920 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
921 case [dir | (exists,dir) <- zip bs dirs, exists] of
922 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
925 ghci_lib_file = lib ++ ".o"
927 -- automatically build the GHCi version of a batch lib,
928 -- using ld --whole-archive.
930 autoBuildGHCiLib :: String -> String -> String -> IO ()
931 autoBuildGHCiLib dir batch_file ghci_file = do
932 let ghci_lib_file = dir ++ '/':ghci_file
933 batch_lib_file = dir ++ '/':batch_file
934 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
935 #if defined(darwin_HOST_OS)
936 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
937 #elif defined(mingw32_HOST_OS)
938 execDir <- getExecDir "/bin/ghc-pkg.exe"
939 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
941 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
943 when (r /= ExitSuccess) $ exitWith r
944 hPutStrLn stderr (" done.")
946 -- -----------------------------------------------------------------------------
947 -- Searching for modules
951 findModules :: [FilePath] -> IO [String]
953 mms <- mapM searchDir paths
956 searchDir path prefix = do
957 fs <- getDirectoryEntries path `catch` \_ -> return []
958 searchEntries path prefix fs
960 searchEntries path prefix [] = return []
961 searchEntries path prefix (f:fs)
962 | looks_like_a_module = do
963 ms <- searchEntries path prefix fs
964 return (prefix `joinModule` f : ms)
965 | looks_like_a_component = do
966 ms <- searchDir (path </> f) (prefix `joinModule` f)
967 ms' <- searchEntries path prefix fs
970 searchEntries path prefix fs
973 (base,suffix) = splitFileExt f
974 looks_like_a_module =
975 suffix `elem` haskell_suffixes &&
976 all okInModuleName base
977 looks_like_a_component =
978 null suffix && all okInModuleName base
984 -- ---------------------------------------------------------------------------
985 -- expanding environment variables in the package configuration
987 expandEnvVars :: String -> Force -> IO String
988 expandEnvVars str0 force = go str0 ""
990 go "" acc = return $! reverse acc
991 go ('$':'{':str) acc | (var, '}':rest) <- break close str
992 = do value <- lookupEnvVar var
993 go rest (reverse value ++ acc)
994 where close c = c == '}' || c == '\n' -- don't span newlines
998 lookupEnvVar :: String -> IO String
1000 catch (System.Environment.getEnv nm)
1001 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1005 -----------------------------------------------------------------------------
1007 getProgramName :: IO String
1008 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1009 where str `withoutSuffix` suff
1010 | suff `isSuffixOf` str = take (length str - length suff) str
1013 bye :: String -> IO a
1014 bye s = putStr s >> exitWith ExitSuccess
1016 die :: String -> IO a
1019 dieWith :: Int -> String -> IO a
1022 prog <- getProgramName
1023 hPutStrLn stderr (prog ++ ": " ++ s)
1024 exitWith (ExitFailure ec)
1026 dieOrForceAll :: Force -> String -> IO ()
1027 dieOrForceAll ForceAll s = ignoreError s
1028 dieOrForceAll _other s = dieForcible s
1030 dieOrForceFile :: Force -> String -> IO ()
1031 dieOrForceFile ForceAll s = ignoreError s
1032 dieOrForceFile ForceFiles s = ignoreError s
1033 dieOrForceFile _other s = dieForcible s
1035 ignoreError :: String -> IO ()
1036 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1038 dieForcible :: String -> IO ()
1039 dieForcible s = die (s ++ " (use --force to override)")
1041 my_head :: String -> [a] -> a
1042 my_head s [] = error s
1043 my_head _ (x : _) = x
1045 -----------------------------------------
1046 -- Cut and pasted from ghc/compiler/main/SysTools
1048 #if defined(mingw32_HOST_OS)
1049 subst :: Char -> Char -> String -> String
1050 subst a b ls = map (\ x -> if x == a then b else x) ls
1052 unDosifyPath :: FilePath -> FilePath
1053 unDosifyPath xs = subst '\\' '/' xs
1055 getExecDir :: String -> IO (Maybe String)
1056 -- (getExecDir cmd) returns the directory in which the current
1057 -- executable, which should be called 'cmd', is running
1058 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1059 -- you'll get "/a/b/c" back as the result
1061 = allocaArray len $ \buf -> do
1062 ret <- getModuleFileName nullPtr buf len
1063 if ret == 0 then return Nothing
1064 else do s <- peekCString buf
1065 return (Just (reverse (drop (length cmd)
1066 (reverse (unDosifyPath s)))))
1068 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1070 foreign import stdcall unsafe "GetModuleFileNameA"
1071 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1073 getExecDir :: String -> IO (Maybe String)
1074 getExecDir _ = return Nothing
1077 -----------------------------------------
1078 -- Adapted from ghc/compiler/utils/Panic
1080 installSignalHandlers :: IO ()
1081 installSignalHandlers = do
1082 threadid <- myThreadId
1084 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1086 #if !defined(mingw32_HOST_OS)
1087 installHandler sigQUIT (Catch interrupt) Nothing
1088 installHandler sigINT (Catch interrupt) Nothing
1090 #elif __GLASGOW_HASKELL__ >= 603
1091 -- GHC 6.3+ has support for console events on Windows
1092 -- NOTE: running GHCi under a bash shell for some reason requires
1093 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1094 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1095 -- why --SDM 17/12/2004
1096 let sig_handler ControlC = interrupt
1097 sig_handler Break = interrupt
1098 sig_handler _ = return ()
1100 installHandler (Catch sig_handler)
1103 return () -- nothing
1106 #if __GLASGOW_HASKELL__ <= 604
1107 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1108 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1111 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1112 #if __GLASGOW_HASKELL__ >= 609
1113 catchIO = Exception.catch
1115 catchIO io handler = io `Exception.catch` handler'
1116 where handler' (Exception.IOException ioe) = handler ioe
1117 handler' e = Exception.throw e
1120 throwIOIO :: Exception.IOException -> IO a
1121 #if __GLASGOW_HASKELL__ >= 609
1122 throwIOIO = Exception.throwIO
1124 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1127 catchError :: IO a -> (String -> IO a) -> IO a
1128 #if __GLASGOW_HASKELL__ >= 609
1129 catchError io handler = io `Exception.catch` handler'
1130 where handler' (Exception.ErrorCall err) = handler err
1132 catchError io handler = io `Exception.catch` handler'
1133 where handler' (Exception.ErrorCall err) = handler err
1134 handler' e = Exception.throw e
1137 onException :: IO a -> IO () -> IO a
1138 #if __GLASGOW_HASKELL__ >= 609
1139 onException = Exception.onException
1141 onException io what = io `Exception.catch` \e -> do what
1146 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1147 -- to use text files here, rather than binary files.
1148 writeFileAtomic :: FilePath -> String -> IO ()
1149 writeFileAtomic targetFile content = do
1150 (tmpFile, tmpHandle) <- openTempFile targetDir template
1151 do hPutStr tmpHandle content
1153 #if mingw32_HOST_OS || mingw32_TARGET_OS
1154 renameFile tmpFile targetFile
1155 -- If the targetFile exists then renameFile will fail
1156 `catchIO` \err -> do
1157 exists <- doesFileExist targetFile
1159 then do removeFile targetFile
1160 -- Big fat hairy race condition
1161 renameFile tmpFile targetFile
1162 -- If the removeFile succeeds and the renameFile fails
1163 -- then we've lost the atomic property.
1166 renameFile tmpFile targetFile
1168 `onException` do hClose tmpHandle
1171 template = targetName <.> "tmp"
1172 targetDir | null targetDir_ = "."
1173 | otherwise = targetDir_
1174 --TODO: remove this when takeDirectory/splitFileName is fixed
1175 -- to always return a valid dir
1176 (targetDir_,targetName) = splitFileName targetFile