1 {-# OPTIONS -fglasgow-exts #-}
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 ( showError )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem ( rawSystem )
29 #include "../../includes/ghcconfig.h"
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
39 import qualified Exception
43 import Data.Char ( isSpace )
46 import System ( getArgs, getProgName, getEnv,
47 exitWith, ExitCode(..)
50 import Data.List ( isPrefixOf, isSuffixOf, intersperse, groupBy, sortBy )
52 #ifdef mingw32_HOST_OS
55 #if __GLASGOW_HASKELL__ >= 504
56 import Foreign.C.String
62 -- -----------------------------------------------------------------------------
69 case getOpt Permute flags args of
70 (cli,_,[]) | FlagHelp `elem` cli -> do
71 prog <- getProgramName
72 bye (usageInfo (usageHeader prog) flags)
73 (cli,_,[]) | FlagVersion `elem` cli ->
77 (_,_,errors) -> tryOldCmdLine errors args
79 -- If the new command-line syntax fails, then we try the old. If that
80 -- fails too, then we output the original errors and the new syntax
81 -- (so the old syntax is still available, but hidden).
82 tryOldCmdLine :: [String] -> [String] -> IO ()
83 tryOldCmdLine errors args = do
84 case getOpt Permute oldFlags args of
88 prog <- getProgramName
89 die (concat errors ++ usageInfo (usageHeader prog) flags)
91 -- -----------------------------------------------------------------------------
92 -- Command-line syntax
100 | FlagGlobalConfig FilePath
103 | FlagDefinedName String String
107 flags :: [OptDescr Flag]
109 Option [] ["user"] (NoArg FlagUser)
110 "use the current user's package database",
111 Option [] ["global"] (NoArg FlagGlobal)
112 "(default) use the global package database",
113 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
114 "act upon specified package config file (only)",
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 ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
120 "automatically build libs for GHCi (with register)",
121 Option ['?'] ["help"] (NoArg FlagHelp)
122 "display this help and exit",
123 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
124 "define NAME as VALUE",
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 when running command 'list'"
132 case break (=='=') str of
133 (nm,[]) -> FlagDefinedName nm []
134 (nm,_:val) -> FlagDefinedName nm val
136 ourCopyright :: String
137 ourCopyright = "GHC package manager version " ++ version ++ "\n"
139 usageHeader :: String -> String
140 usageHeader prog = substProg prog $
142 " $p register {filename | -}\n" ++
143 " Register the package using the specified installed package\n" ++
144 " description. The syntax for the latter is given in the $p\n" ++
145 " documentation.\n" ++
147 " $p update {filename | -}\n" ++
148 " Register the package, overwriting any other package with the\n" ++
151 " $p unregister {pkg-id}\n" ++
152 " Unregister the specified package.\n" ++
154 " $p expose {pkg-id}\n" ++
155 " Expose the specified package.\n" ++
157 " $p hide {pkg-id}\n" ++
158 " Hide the specified package.\n" ++
160 " $p list [pkg]\n" ++
161 " List registered packages in the global database, and also the\n" ++
162 " user database if --user is given. If a package name is given\n" ++
163 " all the registered versions will be listed in ascending order.\n" ++
165 " $p latest pkg\n" ++
166 " Prints the highest registered version of a package.\n" ++
168 " $p describe {pkg-id}\n" ++
169 " Give the registered description for the specified package. The\n" ++
170 " description is returned in precisely the syntax required by $p\n" ++
173 " $p field {pkg-id} {field}\n" ++
174 " Extract the specified field of the package description for the\n" ++
175 " specified package.\n" ++
177 " The following optional flags are also accepted:\n"
179 substProg :: String -> String -> String
181 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
182 substProg prog (c:xs) = c : substProg prog xs
184 -- -----------------------------------------------------------------------------
187 runit :: [Flag] -> [String] -> IO ()
188 runit cli nonopts = do
189 prog <- getProgramName
191 force = FlagForce `elem` cli
192 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
193 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
195 -- first, parse the command
197 ["register", filename] ->
198 registerPackage filename defines cli auto_ghci_libs False force
199 ["update", filename] ->
200 registerPackage filename defines cli auto_ghci_libs True force
201 ["unregister", pkgid_str] -> do
202 pkgid <- readGlobPkgId pkgid_str
203 unregisterPackage pkgid cli
204 ["expose", pkgid_str] -> do
205 pkgid <- readGlobPkgId pkgid_str
206 exposePackage pkgid cli
207 ["hide", pkgid_str] -> do
208 pkgid <- readGlobPkgId pkgid_str
209 hidePackage pkgid cli
211 listPackages cli Nothing
212 ["list", pkgid_str] -> do
213 pkgid <- readGlobPkgId pkgid_str
214 listPackages cli (Just pkgid)
215 ["latest", pkgid_str] -> do
216 pkgid <- readGlobPkgId pkgid_str
217 latestPackage cli pkgid
218 ["describe", pkgid_str] -> do
219 pkgid <- readGlobPkgId pkgid_str
220 describePackage cli pkgid
221 ["field", pkgid_str, field] -> do
222 pkgid <- readGlobPkgId pkgid_str
223 describeField cli pkgid field
225 die ("missing command\n" ++
226 usageInfo (usageHeader prog) flags)
228 die ("command-line syntax error\n" ++
229 usageInfo (usageHeader prog) flags)
231 parseCheck :: ReadP a a -> String -> String -> IO a
232 parseCheck parser str what =
233 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
235 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
237 readPkgId :: String -> IO PackageIdentifier
238 readPkgId str = parseCheck parsePackageId str "package identifier"
240 readGlobPkgId :: String -> IO PackageIdentifier
241 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
243 parseGlobPackageId :: ReadP r PackageIdentifier
247 (do n <- parsePackageName; string "-*"
248 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
250 -- globVersion means "all versions"
251 globVersion :: Version
252 globVersion = Version{ versionBranch=[], versionTags=["*"] }
254 -- -----------------------------------------------------------------------------
257 -- Some commands operate on a single database:
258 -- register, unregister, expose, hide
259 -- however these commands also check the union of the available databases
260 -- in order to check consistency. For example, register will check that
261 -- dependencies exist before registering a package.
263 -- Some commands operate on multiple databases, with overlapping semantics:
264 -- list, describe, field
266 type PackageDBName = FilePath
267 type PackageDB = [InstalledPackageInfo]
269 type PackageDBStack = [(PackageDBName,PackageDB)]
270 -- A stack of package databases. Convention: head is the topmost
271 -- in the stack. Earlier entries override later one.
273 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
274 getPkgDatabases modify flags = do
275 -- first we determine the location of the global package config. On Windows,
276 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
277 -- location is passed to the binary using the --global-config flag by the
279 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
281 case [ f | FlagGlobalConfig f <- flags ] of
282 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
284 Nothing -> die err_msg
285 Just dir -> return (dir `joinFileName` "package.conf")
286 fs -> return (last fs)
288 -- get the location of the user package database, and create it if necessary
289 appdir <- getAppUserDataDirectory "ghc"
292 subdir = targetARCH ++ '-':targetOS ++ '-':version
293 archdir = appdir `joinFileName` subdir
294 user_conf = archdir `joinFileName` "package.conf"
295 user_exists <- doesFileExist user_conf
298 -- The semantics here are slightly strange. If we are
299 -- *modifying* the database, then the default is to modify
300 -- the global database by default, unless you say --user.
301 -- If we are not modifying (eg. list, describe etc.) then
302 -- the user database is included by default.
304 | modify = foldl addDB [global_conf] flags
305 | not user_exists = foldl addDB [global_conf] flags
306 | otherwise = foldl addDB [user_conf,global_conf] flags
308 -- implement the following rules:
309 -- --user means overlap with the user database
310 -- --global means reset to just the global database
311 -- -f <file> means overlap with <file>
313 | user_conf `elem` dbs = dbs
314 | modify || user_exists = user_conf : dbs
315 addDB dbs FlagGlobal = [global_conf]
316 addDB dbs (FlagConfig f) = f : dbs
319 -- we create the user database iff (a) we're modifying, and (b) the
320 -- user asked to use it by giving the --user flag.
321 when (not user_exists && user_conf `elem` databases) $ do
322 putStrLn ("Creating user package database in " ++ user_conf)
323 createDirectoryIfMissing True archdir
324 writeFile user_conf emptyPackageConfig
326 db_stack <- mapM readParseDatabase databases
329 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
330 readParseDatabase filename = do
331 str <- readFile filename
332 let packages = read str
333 Exception.evaluate packages
334 `Exception.catch` \_ ->
335 die (filename ++ ": parse error in package config file")
336 return (filename,packages)
338 emptyPackageConfig :: String
339 emptyPackageConfig = "[]"
341 -- -----------------------------------------------------------------------------
344 registerPackage :: FilePath
345 -> [(String,String)] -- defines
347 -> Bool -- auto_ghci_libs
351 registerPackage input defines flags auto_ghci_libs update force = do
352 db_stack <- getPkgDatabases True flags
354 db_to_operate_on = my_head "db" db_stack
355 db_filename = fst db_to_operate_on
357 checkConfigAccess db_filename
362 putStr "Reading package info from stdin ... "
365 putStr ("Reading package info from " ++ show f ++ " ... ")
368 expanded <- expandEnvVars s defines force
370 pkg0 <- parsePackageInfo expanded defines force
373 let pkg = resolveDeps db_stack pkg0
374 overlaps <- validatePackageConfig pkg db_stack auto_ghci_libs update force
375 new_details <- updatePackageDB db_stack overlaps (snd db_to_operate_on) pkg
376 savePackageConfig db_filename
377 maybeRestoreOldConfig db_filename $
378 writeNewConfig db_filename new_details
384 -> IO InstalledPackageInfo
385 parsePackageInfo str defines force =
386 case parseInstalledPackageInfo str of
387 ParseOk ok -> return ok
388 ParseFailed err -> die (showError err)
390 -- -----------------------------------------------------------------------------
391 -- Exposing, Hiding, Unregistering are all similar
393 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
394 exposePackage = modifyPackage (\p -> [p{exposed=True}])
396 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
397 hidePackage = modifyPackage (\p -> [p{exposed=False}])
399 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
400 unregisterPackage = modifyPackage (\p -> [])
403 :: (InstalledPackageInfo -> [InstalledPackageInfo])
407 modifyPackage fn pkgid flags = do
408 db_stack <- getPkgDatabases True{-modify-} flags
409 let ((db_name, pkgs) : _) = db_stack
410 checkConfigAccess db_name
411 ps <- findPackages [(db_name,pkgs)] pkgid
412 let pids = map package ps
413 savePackageConfig db_name
414 let new_config = concat (map modify pkgs)
416 | package pkg `elem` pids = fn pkg
418 maybeRestoreOldConfig db_name $
419 writeNewConfig db_name new_config
421 -- -----------------------------------------------------------------------------
424 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
425 listPackages flags mPackageName = do
426 let simple_output = FlagSimpleOutput `elem` flags
427 db_stack <- getPkgDatabases False flags
428 let db_stack_filtered -- if a package is given, filter out all other packages
429 | Just this <- mPackageName =
430 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
432 | otherwise = db_stack
433 show_func = if simple_output then show_easy else mapM_ show_regular
434 show_func (reverse db_stack_filtered)
435 where show_regular (db_name,pkg_confs) =
436 hPutStrLn stdout (render $
437 text (db_name ++ ":") $$ nest 4 packages
439 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
442 | otherwise = parens doc
443 where doc = text (showPackageId (package p))
444 show_easy db_stack = do
445 let pkgs = map showPackageId $ sortBy compPkgIdVer $
446 map package (concatMap snd db_stack)
447 when (null pkgs) $ die "no matches"
448 hPutStrLn stdout $ concat $ intersperse " " pkgs
450 -- -----------------------------------------------------------------------------
451 -- Prints the highest (hidden or exposed) version of a package
453 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
454 latestPackage flags pkgid = do
455 db_stack <- getPkgDatabases False flags
456 ps <- findPackages db_stack pkgid
457 show_pkg (sortBy compPkgIdVer (map package ps))
459 show_pkg [] = die "no matches"
460 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
462 -- -----------------------------------------------------------------------------
465 describePackage :: [Flag] -> PackageIdentifier -> IO ()
466 describePackage flags pkgid = do
467 db_stack <- getPkgDatabases False flags
468 ps <- findPackages db_stack pkgid
469 mapM_ (putStrLn . showInstalledPackageInfo) ps
471 -- PackageId is can have globVersion for the version
472 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
473 findPackages db_stack pkgid
474 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
475 [] -> die ("cannot find package " ++ showPackageId pkgid)
478 all_pkgs = concat (map snd db_stack)
480 matches :: PackageIdentifier -> PackageIdentifier -> Bool
482 = (pkgName pid == pkgName pid')
483 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
485 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
486 pid `matchesPkg` pkg = pid `matches` package pkg
488 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
489 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
491 -- -----------------------------------------------------------------------------
494 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
495 describeField flags pkgid field = do
496 db_stack <- getPkgDatabases False flags
497 case toField field of
498 Nothing -> die ("unknown field: " ++ field)
500 ps <- findPackages db_stack pkgid
501 mapM_ (putStrLn.fn) ps
503 toField :: String -> Maybe (InstalledPackageInfo -> String)
504 -- backwards compatibility:
505 toField "import_dirs" = Just $ strList . importDirs
506 toField "source_dirs" = Just $ strList . importDirs
507 toField "library_dirs" = Just $ strList . libraryDirs
508 toField "hs_libraries" = Just $ strList . hsLibraries
509 toField "extra_libraries" = Just $ strList . extraLibraries
510 toField "include_dirs" = Just $ strList . includeDirs
511 toField "c_includes" = Just $ strList . includes
512 toField "package_deps" = Just $ strList . map showPackageId. depends
513 toField "extra_cc_opts" = Just $ strList . ccOptions
514 toField "extra_ld_opts" = Just $ strList . ldOptions
515 toField "framework_dirs" = Just $ strList . frameworkDirs
516 toField "extra_frameworks"= Just $ strList . frameworks
517 toField s = showInstalledPackageInfoField s
519 strList :: [String] -> String
522 -- -----------------------------------------------------------------------------
523 -- Manipulating package.conf files
525 checkConfigAccess :: FilePath -> IO ()
526 checkConfigAccess filename = do
527 access <- getPermissions filename
528 when (not (writable access))
529 (die (filename ++ ": you don't have permission to modify this file"))
531 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
532 maybeRestoreOldConfig filename io
533 = io `catch` \e -> do
534 hPutStrLn stderr (show e)
535 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
536 "configuration was being written. Attempting to \n"++
537 "restore the old configuration... ")
538 renameFile (filename ++ ".old") filename
539 hPutStrLn stdout "done."
542 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
543 writeNewConfig filename packages = do
544 hPutStr stdout "Writing new package config file... "
545 h <- openFile filename WriteMode
546 hPutStrLn h (show packages)
548 hPutStrLn stdout "done."
550 savePackageConfig :: FilePath -> IO ()
551 savePackageConfig filename = do
552 hPutStr stdout "Saving old package config file... "
553 -- mv rather than cp because we've already done an hGetContents
554 -- on this file so we won't be able to open it for writing
555 -- unless we move the old one out of the way...
556 let oldFile = filename ++ ".old"
557 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
558 when doesExist (removeFile oldFile `catch` (const $ return ()))
559 catch (renameFile filename oldFile)
561 hPutStrLn stderr (unwords [ "Unable to rename "
567 hPutStrLn stdout "done."
569 -----------------------------------------------------------------------------
570 -- Sanity-check a new package config, and automatically build GHCi libs
573 validatePackageConfig :: InstalledPackageInfo
575 -> Bool -- auto-ghc-libs
578 -> IO [PackageIdentifier]
579 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
581 overlaps <- checkDuplicates db_stack pkg update force
582 mapM_ (checkDep db_stack force) (depends pkg)
583 mapM_ (checkDir force) (importDirs pkg)
584 mapM_ (checkDir force) (libraryDirs pkg)
585 mapM_ (checkDir force) (includeDirs pkg)
586 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
588 -- ToDo: check these somehow?
589 -- extra_libraries :: [String],
590 -- c_includes :: [String],
592 -- When the package name and version are put together, sometimes we can
593 -- end up with a package id that cannot be parsed. This will lead to
594 -- difficulties when the user wants to refer to the package later, so
595 -- we check that the package id can be parsed properly here.
596 checkPackageId :: InstalledPackageInfo -> IO ()
598 let str = showPackageId (package ipi) in
599 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
601 [] -> die ("invalid package identifier: " ++ str)
602 _ -> die ("ambiguous package identifier: " ++ str)
604 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
605 resolveDeps db_stack p = updateDeps p
607 -- The input package spec is allowed to give a package dependency
608 -- without a version number; e.g.
610 -- Here, we update these dependencies without version numbers to
611 -- match the actual versions of the relevant packages installed.
612 updateDeps p = p{depends = map resolveDep (depends p)}
615 | realVersion dep_pkgid = dep_pkgid
616 | otherwise = lookupDep dep_pkgid
620 name = pkgName dep_pkgid
622 case [ pid | p <- concat (map snd db_stack),
624 pkgName pid == name ] of
625 (pid:_) -> pid -- Found installed package,
626 -- replete with its version
627 [] -> dep_pkgid -- No installed package; use
628 -- the version-less one
630 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
631 -> IO [PackageIdentifier]
632 checkDuplicates db_stack pkg update force = do
635 (_top_db_name, pkgs) : _ = db_stack
637 -- Check whether this package id already exists in this DB
639 when (not update && (pkgid `elem` map package pkgs)) $
640 die ("package " ++ showPackageId pkgid ++ " is already installed")
643 -- Check whether any of the dependencies of the current package
644 -- conflict with each other.
647 all_pkgs = concat (map snd db_stack)
649 allModules p = exposedModules p ++ hiddenModules p
651 our_dependencies = closePackageDeps all_pkgs [pkg]
652 all_dep_modules = concat (map (\p -> zip (allModules p) (repeat p))
655 overlaps = [ (m, map snd group)
656 | group@((m,_):_) <- groupBy eqfst (sortBy cmpfst all_dep_modules),
658 where eqfst (a,_) (b,_) = a == b
659 cmpfst (a,_) (b,_) = a `compare` b
661 when (not (null overlaps)) $
662 diePrettyOrForce force $ vcat [
663 text "package" <+> text (showPackageId (package pkg)) <+>
664 text "has conflicting dependencies:",
665 let complain_about (mod,ps) =
666 text mod <+> text "is in the following packages:" <+>
667 sep (map (text.showPackageId.package) ps)
669 nest 3 (vcat (map complain_about overlaps))
673 -- Now check whether exposing this package will result in conflicts, and
674 -- Figure out which packages we need to hide to resolve the conflicts.
677 closure_exposed_pkgs = closePackageDeps pkgs (filter exposed pkgs)
679 new_dep_modules = concat $ map allModules $
680 filter (\p -> package p `notElem`
681 map package closure_exposed_pkgs) $
684 pkgs_with_overlapping_modules =
685 [ (p, overlapping_mods)
686 | p <- closure_exposed_pkgs,
687 let overlapping_mods =
688 filter (`elem` new_dep_modules) (allModules p),
689 (_:_) <- [overlapping_mods] --trick to get the non-empty ones
692 to_hide = map package
694 $ closePackageDepsUpward pkgs
695 $ map fst pkgs_with_overlapping_modules
697 when (not update && exposed pkg && not (null pkgs_with_overlapping_modules)) $ do
699 text "package" <+> text (showPackageId (package pkg)) <+>
700 text "conflicts with the following packages, which are",
701 text "either exposed or a dependency (direct or indirect) of an exposed package:",
702 let complain_about (p, mods)
703 = text (showPackageId (package p)) <+> text "contains modules" <+>
704 sep (punctuate comma (map text mods)) in
705 nest 3 (vcat (map complain_about pkgs_with_overlapping_modules)),
706 text "Using 'update' instead of 'register' will cause the following packages",
707 text "to be hidden, which will eliminate the conflict:",
708 nest 3 (sep (map (text.showPackageId) to_hide))
711 when (not (null to_hide)) $ do
712 hPutStrLn stderr $ render $
713 sep [text "Warning: hiding the following packages to avoid conflict: ",
714 nest 2 (sep (map (text.showPackageId) to_hide))]
719 closure :: (a->[a]->Bool) -> (a -> [a]) -> [a] -> [a] -> [a]
720 closure pred more [] res = res
721 closure pred more (p:ps) res
722 | p `pred` res = closure pred more ps res
723 | otherwise = closure pred more (more p ++ ps) (p:res)
725 closePackageDeps :: [InstalledPackageInfo] -> [InstalledPackageInfo]
726 -> [InstalledPackageInfo]
727 closePackageDeps db start
728 = closure (\p ps -> package p `elem` map package ps) getDepends start []
730 getDepends p = [ pkg | dep <- depends p, pkg <- lookupPkg dep ]
731 lookupPkg p = [ q | q <- db, p == package q ]
733 closePackageDepsUpward :: [InstalledPackageInfo] -> [InstalledPackageInfo]
734 -> [InstalledPackageInfo]
735 closePackageDepsUpward db start
736 = closure (\p ps -> package p `elem` map package ps) getUpwardDepends start []
738 getUpwardDepends p = [ pkg | pkg <- db, package p `elem` depends pkg ]
741 checkDir :: Bool -> String -> IO ()
743 | "$topdir" `isPrefixOf` d = return ()
744 -- can't check this, because we don't know what $topdir is
746 there <- doesDirectoryExist d
748 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
750 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
751 checkDep db_stack force pkgid
752 | not real_version || pkgid `elem` pkgids = return ()
753 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
756 -- for backwards compat, we treat 0.0 as a special version,
757 -- and don't check that it actually exists.
758 real_version = realVersion pkgid
760 all_pkgs = concat (map snd db_stack)
761 pkgids = map package all_pkgs
763 realVersion :: PackageIdentifier -> Bool
764 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
766 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
767 checkHSLib dirs auto_ghci_libs force lib = do
768 let batch_lib_file = "lib" ++ lib ++ ".a"
769 bs <- mapM (doesLibExistIn batch_lib_file) dirs
770 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
771 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
773 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
775 doesLibExistIn :: String -> String -> IO Bool
777 | "$topdir" `isPrefixOf` d = return True
778 | otherwise = doesFileExist (d ++ '/':lib)
780 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
781 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
782 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
784 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
785 case [dir | (exists,dir) <- zip bs dirs, exists] of
786 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
789 ghci_lib_file = lib ++ ".o"
791 -- automatically build the GHCi version of a batch lib,
792 -- using ld --whole-archive.
794 autoBuildGHCiLib :: String -> String -> String -> IO ()
795 autoBuildGHCiLib dir batch_file ghci_file = do
796 let ghci_lib_file = dir ++ '/':ghci_file
797 batch_lib_file = dir ++ '/':batch_file
798 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
799 #if defined(darwin_HOST_OS)
800 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
801 #elif defined(mingw32_HOST_OS)
802 execDir <- getExecDir "/bin/ghc-pkg.exe"
803 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
805 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
807 when (r /= ExitSuccess) $ exitWith r
808 hPutStrLn stderr (" done.")
810 -- -----------------------------------------------------------------------------
811 -- Updating the DB with the new package.
814 :: PackageDBStack -- the full stack
815 -> [PackageIdentifier] -- packages to hide
816 -> [InstalledPackageInfo] -- packages in *this* DB
817 -> InstalledPackageInfo -- the new package
818 -> IO [InstalledPackageInfo]
819 updatePackageDB db_stack to_hide pkgs new_pkg = do
821 pkgid = package new_pkg
823 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
825 -- When update is on, and we're exposing the new package,
826 -- we hide any packages which conflict (see checkDuplicates)
827 -- in the current DB.
829 | exposed new_pkg && package p `elem` to_hide = p{ exposed = False }
832 return (pkgs'++ [new_pkg])
834 -- -----------------------------------------------------------------------------
835 -- Searching for modules
839 findModules :: [FilePath] -> IO [String]
841 mms <- mapM searchDir paths
844 searchDir path prefix = do
845 fs <- getDirectoryEntries path `catch` \_ -> return []
846 searchEntries path prefix fs
848 searchEntries path prefix [] = return []
849 searchEntries path prefix (f:fs)
850 | looks_like_a_module = do
851 ms <- searchEntries path prefix fs
852 return (prefix `joinModule` f : ms)
853 | looks_like_a_component = do
854 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
855 ms' <- searchEntries path prefix fs
858 searchEntries path prefix fs
861 (base,suffix) = splitFileExt f
862 looks_like_a_module =
863 suffix `elem` haskell_suffixes &&
864 all okInModuleName base
865 looks_like_a_component =
866 null suffix && all okInModuleName base
872 -- -----------------------------------------------------------------------------
873 -- The old command-line syntax, supported for backwards compatibility
880 | OF_Add Bool {- True => replace existing info -}
881 | OF_Remove String | OF_Show String
882 | OF_Field String | OF_AutoGHCiLibs | OF_Force
883 | OF_DefinedName String String
884 | OF_GlobalConfig FilePath
887 isAction :: OldFlag -> Bool
888 isAction OF_Config{} = False
889 isAction OF_Field{} = False
890 isAction OF_Input{} = False
891 isAction OF_AutoGHCiLibs{} = False
892 isAction OF_Force{} = False
893 isAction OF_DefinedName{} = False
894 isAction OF_GlobalConfig{} = False
897 oldFlags :: [OptDescr OldFlag]
899 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
900 "use the specified package config file",
901 Option ['l'] ["list-packages"] (NoArg OF_List)
902 "list packages in all config files",
903 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
904 "list packages in the specified config file",
905 Option ['a'] ["add-package"] (NoArg (OF_Add False))
907 Option ['u'] ["update-package"] (NoArg (OF_Add True))
908 "update package with new configuration",
909 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
910 "read new package info from specified file",
911 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
912 "show the configuration for package NAME",
913 Option [] ["field"] (ReqArg OF_Field "FIELD")
914 "(with --show-package) Show field FIELD only",
915 Option [] ["force"] (NoArg OF_Force)
916 "ignore missing directories/libraries",
917 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
918 "remove an installed package",
919 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
920 "automatically build libs for GHCi (with -a)",
921 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
922 "define NAME as VALUE",
923 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
924 "location of the global package config"
928 case break (=='=') str of
929 (nm,[]) -> OF_DefinedName nm []
930 (nm,_:val) -> OF_DefinedName nm val
932 oldRunit :: [OldFlag] -> IO ()
934 let new_flags = [ f | Just f <- map conv clis ]
936 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
937 conv (OF_Config f) = Just (FlagConfig f)
942 let fields = [ f | OF_Field f <- clis ]
944 let auto_ghci_libs = any isAuto clis
945 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
946 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
948 force = OF_Force `elem` clis
950 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
952 case [ c | c <- clis, isAction c ] of
953 [ OF_List ] -> listPackages new_flags Nothing
954 [ OF_ListLocal ] -> listPackages new_flags Nothing
956 registerPackage input_file defines new_flags auto_ghci_libs upd force
957 [ OF_Remove pkgid_str ] -> do
958 pkgid <- readPkgId pkgid_str
959 unregisterPackage pkgid new_flags
960 [ OF_Show pkgid_str ]
962 pkgid <- readPkgId pkgid_str
963 describePackage new_flags pkgid
965 pkgid <- readPkgId pkgid_str
966 mapM_ (describeField new_flags pkgid) fields
968 prog <- getProgramName
969 die (usageInfo (usageHeader prog) flags)
971 my_head :: String -> [a] -> a
972 my_head s [] = error s
975 -- ---------------------------------------------------------------------------
976 -- expanding environment variables in the package configuration
978 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
979 expandEnvVars str defines force = go str ""
981 go "" acc = return $! reverse acc
982 go ('$':'{':str) acc | (var, '}':rest) <- break close str
983 = do value <- lookupEnvVar var
984 go rest (reverse value ++ acc)
985 where close c = c == '}' || c == '\n' -- don't span newlines
989 lookupEnvVar :: String -> IO String
991 case lookup nm defines of
992 Just x | not (null x) -> return x
994 catch (System.getEnv nm)
995 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
999 -----------------------------------------------------------------------------
1001 getProgramName :: IO String
1002 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1003 where str `withoutSuffix` suff
1004 | suff `isSuffixOf` str = take (length str - length suff) str
1007 bye :: String -> IO a
1008 bye s = putStr s >> exitWith ExitSuccess
1010 die :: String -> IO a
1013 prog <- getProgramName
1014 hPutStrLn stderr (prog ++ ": " ++ s)
1015 exitWith (ExitFailure 1)
1017 dieOrForce :: Bool -> String -> IO ()
1019 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1020 | otherwise = die (s ++ " (use --force to override)")
1022 diePretty :: Doc -> IO ()
1025 prog <- getProgramName
1026 hPutStrLn stderr $ render $ (text prog <> colon $$ nest 2 doc)
1027 exitWith (ExitFailure 1)
1029 diePrettyOrForce :: Bool -> Doc -> IO ()
1030 diePrettyOrForce force doc
1031 | force = do hFlush stdout; hPutStrLn stderr (render (doc $$ text "(ignoring)"))
1032 | otherwise = diePretty (doc $$ text "(use --force to override)")
1034 -----------------------------------------
1035 -- Cut and pasted from ghc/compiler/SysTools
1037 #if defined(mingw32_HOST_OS)
1038 subst a b ls = map (\ x -> if x == a then b else x) ls
1039 unDosifyPath xs = subst '\\' '/' xs
1041 getExecDir :: String -> IO (Maybe String)
1042 -- (getExecDir cmd) returns the directory in which the current
1043 -- executable, which should be called 'cmd', is running
1044 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1045 -- you'll get "/a/b/c" back as the result
1047 = allocaArray len $ \buf -> do
1048 ret <- getModuleFileName nullPtr buf len
1049 if ret == 0 then return Nothing
1050 else do s <- peekCString buf
1051 return (Just (reverse (drop (length cmd)
1052 (reverse (unDosifyPath s)))))
1054 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1056 foreign import stdcall unsafe "GetModuleFileNameA"
1057 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1059 getExecDir :: String -> IO (Maybe String)
1060 getExecDir _ = return Nothing
1063 -- -----------------------------------------------------------------------------
1066 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1067 -- It joins directory and file names to form a complete file path.
1069 -- The general rule is:
1071 -- > dir `joinFileName` basename == path
1073 -- > (dir,basename) = splitFileName path
1075 -- There might be an exceptions to the rule but in any case the
1076 -- reconstructed path will refer to the same object (file or directory).
1077 -- An example exception is that on Windows some slashes might be converted
1079 joinFileName :: String -> String -> FilePath
1080 joinFileName "" fname = fname
1081 joinFileName "." fname = fname
1082 joinFileName dir "" = dir
1083 joinFileName dir fname
1084 | isPathSeparator (last dir) = dir++fname
1085 | otherwise = dir++pathSeparator:fname
1087 -- | Checks whether the character is a valid path separator for the host
1088 -- platform. The valid character is a 'pathSeparator' but since the Windows
1089 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1090 -- checks for it on this platform, too.
1091 isPathSeparator :: Char -> Bool
1092 isPathSeparator ch = ch == pathSeparator || ch == '/'
1094 -- | Provides a platform-specific character used to separate directory levels in
1095 -- a path string that reflects a hierarchical file system organization. The
1096 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1097 -- (@\"\\\"@) on the Windows operating system.
1098 pathSeparator :: Char
1099 #ifdef mingw32_HOST_OS
1100 pathSeparator = '\\'