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", package] -> do
213 listPackages cli (Just package)
214 ["latest", package] -> do
215 latestPackage cli package
216 ["describe", pkgid_str] -> do
217 pkgid <- readGlobPkgId pkgid_str
218 describePackage cli pkgid
219 ["field", pkgid_str, field] -> do
220 pkgid <- readGlobPkgId pkgid_str
221 describeField cli pkgid field
223 die ("missing command\n" ++
224 usageInfo (usageHeader prog) flags)
226 die ("command-line syntax error\n" ++
227 usageInfo (usageHeader prog) flags)
229 parseCheck :: ReadP a a -> String -> String -> IO a
230 parseCheck parser str what =
231 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
233 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
235 readPkgId :: String -> IO PackageIdentifier
236 readPkgId str = parseCheck parsePackageId str "package identifier"
238 readGlobPkgId :: String -> IO PackageIdentifier
239 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
241 parseGlobPackageId :: ReadP r PackageIdentifier
245 (do n <- parsePackageName; string "-*"
246 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
248 -- globVersion means "all versions"
249 globVersion :: Version
250 globVersion = Version{ versionBranch=[], versionTags=["*"] }
252 -- -----------------------------------------------------------------------------
255 -- Some commands operate on a single database:
256 -- register, unregister, expose, hide
257 -- however these commands also check the union of the available databases
258 -- in order to check consistency. For example, register will check that
259 -- dependencies exist before registering a package.
261 -- Some commands operate on multiple databases, with overlapping semantics:
262 -- list, describe, field
264 type PackageDBName = FilePath
265 type PackageDB = [InstalledPackageInfo]
267 type PackageDBStack = [(PackageDBName,PackageDB)]
268 -- A stack of package databases. Convention: head is the topmost
269 -- in the stack. Earlier entries override later one.
271 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
272 getPkgDatabases modify flags = do
273 -- first we determine the location of the global package config. On Windows,
274 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
275 -- location is passed to the binary using the --global-config flag by the
277 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
279 case [ f | FlagGlobalConfig f <- flags ] of
280 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
282 Nothing -> die err_msg
283 Just dir -> return (dir `joinFileName` "package.conf")
284 fs -> return (last fs)
286 -- get the location of the user package database, and create it if necessary
287 appdir <- getAppUserDataDirectory "ghc"
290 subdir = targetARCH ++ '-':targetOS ++ '-':version
291 archdir = appdir `joinFileName` subdir
292 user_conf = archdir `joinFileName` "package.conf"
293 user_exists <- doesFileExist user_conf
296 -- The semantics here are slightly strange. If we are
297 -- *modifying* the database, then the default is to modify
298 -- the global database by default, unless you say --user.
299 -- If we are not modifying (eg. list, describe etc.) then
300 -- the user database is included by default.
302 | modify = foldl addDB [global_conf] flags
303 | not user_exists = foldl addDB [global_conf] flags
304 | otherwise = foldl addDB [user_conf,global_conf] flags
306 -- implement the following rules:
307 -- --user means overlap with the user database
308 -- --global means reset to just the global database
309 -- -f <file> means overlap with <file>
311 | user_conf `elem` dbs = dbs
312 | modify || user_exists = user_conf : dbs
313 addDB dbs FlagGlobal = [global_conf]
314 addDB dbs (FlagConfig f) = f : dbs
317 -- we create the user database iff (a) we're modifying, and (b) the
318 -- user asked to use it by giving the --user flag.
319 when (not user_exists && user_conf `elem` databases) $ do
320 putStrLn ("Creating user package database in " ++ user_conf)
321 createDirectoryIfMissing True archdir
322 writeFile user_conf emptyPackageConfig
324 db_stack <- mapM readParseDatabase databases
327 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
328 readParseDatabase filename = do
329 str <- readFile filename
330 let packages = read str
331 Exception.evaluate packages
332 `Exception.catch` \_ ->
333 die (filename ++ ": parse error in package config file")
334 return (filename,packages)
336 emptyPackageConfig :: String
337 emptyPackageConfig = "[]"
339 -- -----------------------------------------------------------------------------
342 registerPackage :: FilePath
343 -> [(String,String)] -- defines
345 -> Bool -- auto_ghci_libs
349 registerPackage input defines flags auto_ghci_libs update force = do
350 db_stack <- getPkgDatabases True flags
352 db_to_operate_on = my_head "db" db_stack
353 db_filename = fst db_to_operate_on
355 checkConfigAccess db_filename
360 putStr "Reading package info from stdin ... "
363 putStr ("Reading package info from " ++ show f ++ " ... ")
366 expanded <- expandEnvVars s defines force
368 pkg0 <- parsePackageInfo expanded defines force
371 let pkg = resolveDeps db_stack pkg0
372 overlaps <- validatePackageConfig pkg db_stack auto_ghci_libs update force
373 new_details <- updatePackageDB db_stack overlaps (snd db_to_operate_on) pkg
374 savePackageConfig db_filename
375 maybeRestoreOldConfig db_filename $
376 writeNewConfig db_filename new_details
382 -> IO InstalledPackageInfo
383 parsePackageInfo str defines force =
384 case parseInstalledPackageInfo str of
385 ParseOk ok -> return ok
386 ParseFailed err -> die (showError err)
388 -- -----------------------------------------------------------------------------
389 -- Exposing, Hiding, Unregistering are all similar
391 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
392 exposePackage = modifyPackage (\p -> [p{exposed=True}])
394 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
395 hidePackage = modifyPackage (\p -> [p{exposed=False}])
397 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
398 unregisterPackage = modifyPackage (\p -> [])
401 :: (InstalledPackageInfo -> [InstalledPackageInfo])
405 modifyPackage fn pkgid flags = do
406 db_stack <- getPkgDatabases True{-modify-} flags
407 let ((db_name, pkgs) : _) = db_stack
408 checkConfigAccess db_name
409 ps <- findPackages [(db_name,pkgs)] pkgid
410 let pids = map package ps
411 savePackageConfig db_name
412 let new_config = concat (map modify pkgs)
414 | package pkg `elem` pids = fn pkg
416 maybeRestoreOldConfig db_name $
417 writeNewConfig db_name new_config
419 -- -----------------------------------------------------------------------------
422 listPackages :: [Flag] -> Maybe String -> IO ()
423 listPackages flags mPackageName = do
424 let simple_output = FlagSimpleOutput `elem` flags
425 db_stack <- getPkgDatabases False flags
426 let doesMatch p = fromJust mPackageName == pkgName (package p)
427 db_stack_filtered -- if a package is given, filter out all other packages
428 | Just p <- mPackageName =
429 map (\(conf,pkgs) -> (conf, filter doesMatch pkgs)) db_stack
430 | otherwise = db_stack
431 show_func = if simple_output then show_easy else mapM_ show_regular
432 show_func (reverse db_stack_filtered)
433 where show_regular (db_name,pkg_confs) =
434 hPutStrLn stdout (render $
435 text (db_name ++ ":") $$ nest 4 packages
437 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
440 | otherwise = parens doc
441 where doc = text (showPackageId (package p))
442 show_easy db_stack = do
443 let pkgs = map showPackageId $ sortBy compPkgIdVer $
444 map package (concatMap snd db_stack)
445 when (null pkgs) $ die "no matches"
446 hPutStrLn stdout $ concat $ intersperse " " pkgs
448 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
450 -- -----------------------------------------------------------------------------
451 -- Prints the highest (hidden or exposed) version of a package
453 latestPackage :: [Flag] -> String -> IO ()
454 latestPackage flags packageName = do
455 db_stack <- getPkgDatabases False flags
456 let allPids = map package $ concatMap snd db_stack
457 matches = filter (\p -> packageName == pkgName p) allPids
458 show_pkg (sortBy compPkgIdVer matches)
460 show_pkg [] = die "no matches"
461 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
462 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
464 -- -----------------------------------------------------------------------------
467 describePackage :: [Flag] -> PackageIdentifier -> IO ()
468 describePackage flags pkgid = do
469 db_stack <- getPkgDatabases False flags
470 ps <- findPackages db_stack pkgid
471 mapM_ (putStrLn . showInstalledPackageInfo) ps
473 -- PackageId is can have globVersion for the version
474 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
475 findPackages db_stack pkgid
476 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
477 [] -> die ("cannot find package " ++ showPackageId pkgid)
479 -- if the version is globVersion, then we are allowed to match
480 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
481 -- but "Cabal" matches just one Cabal package - if there are more,
483 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
486 -> die ("package " ++ showPackageId pkgid ++
487 " matches multiple packages: " ++
488 concat (intersperse ", " (
489 map (showPackageId.package) ps)))
492 = (pkgName pid == pkgName p)
493 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
494 where p = package pkg
496 all_pkgs = concat (map snd db_stack)
498 -- -----------------------------------------------------------------------------
501 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
502 describeField flags pkgid field = do
503 db_stack <- getPkgDatabases False flags
504 case toField field of
505 Nothing -> die ("unknown field: " ++ field)
507 ps <- findPackages db_stack pkgid
508 mapM_ (putStrLn.fn) ps
510 toField :: String -> Maybe (InstalledPackageInfo -> String)
511 -- backwards compatibility:
512 toField "import_dirs" = Just $ strList . importDirs
513 toField "source_dirs" = Just $ strList . importDirs
514 toField "library_dirs" = Just $ strList . libraryDirs
515 toField "hs_libraries" = Just $ strList . hsLibraries
516 toField "extra_libraries" = Just $ strList . extraLibraries
517 toField "include_dirs" = Just $ strList . includeDirs
518 toField "c_includes" = Just $ strList . includes
519 toField "package_deps" = Just $ strList . map showPackageId. depends
520 toField "extra_cc_opts" = Just $ strList . ccOptions
521 toField "extra_ld_opts" = Just $ strList . ldOptions
522 toField "framework_dirs" = Just $ strList . frameworkDirs
523 toField "extra_frameworks"= Just $ strList . frameworks
524 toField s = showInstalledPackageInfoField s
526 strList :: [String] -> String
529 -- -----------------------------------------------------------------------------
530 -- Manipulating package.conf files
532 checkConfigAccess :: FilePath -> IO ()
533 checkConfigAccess filename = do
534 access <- getPermissions filename
535 when (not (writable access))
536 (die (filename ++ ": you don't have permission to modify this file"))
538 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
539 maybeRestoreOldConfig filename io
540 = io `catch` \e -> do
541 hPutStrLn stderr (show e)
542 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
543 "configuration was being written. Attempting to \n"++
544 "restore the old configuration... ")
545 renameFile (filename ++ ".old") filename
546 hPutStrLn stdout "done."
549 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
550 writeNewConfig filename packages = do
551 hPutStr stdout "Writing new package config file... "
552 h <- openFile filename WriteMode
553 hPutStrLn h (show packages)
555 hPutStrLn stdout "done."
557 savePackageConfig :: FilePath -> IO ()
558 savePackageConfig filename = do
559 hPutStr stdout "Saving old package config file... "
560 -- mv rather than cp because we've already done an hGetContents
561 -- on this file so we won't be able to open it for writing
562 -- unless we move the old one out of the way...
563 let oldFile = filename ++ ".old"
564 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
565 when doesExist (removeFile oldFile `catch` (const $ return ()))
566 catch (renameFile filename oldFile)
568 hPutStrLn stderr (unwords [ "Unable to rename "
574 hPutStrLn stdout "done."
576 -----------------------------------------------------------------------------
577 -- Sanity-check a new package config, and automatically build GHCi libs
580 validatePackageConfig :: InstalledPackageInfo
582 -> Bool -- auto-ghc-libs
585 -> IO [PackageIdentifier]
586 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
588 overlaps <- checkDuplicates db_stack pkg update force
589 mapM_ (checkDep db_stack force) (depends pkg)
590 mapM_ (checkDir force) (importDirs pkg)
591 mapM_ (checkDir force) (libraryDirs pkg)
592 mapM_ (checkDir force) (includeDirs pkg)
593 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
595 -- ToDo: check these somehow?
596 -- extra_libraries :: [String],
597 -- c_includes :: [String],
599 -- When the package name and version are put together, sometimes we can
600 -- end up with a package id that cannot be parsed. This will lead to
601 -- difficulties when the user wants to refer to the package later, so
602 -- we check that the package id can be parsed properly here.
603 checkPackageId :: InstalledPackageInfo -> IO ()
605 let str = showPackageId (package ipi) in
606 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
608 [] -> die ("invalid package identifier: " ++ str)
609 _ -> die ("ambiguous package identifier: " ++ str)
611 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
612 resolveDeps db_stack p = updateDeps p
614 -- The input package spec is allowed to give a package dependency
615 -- without a version number; e.g.
617 -- Here, we update these dependencies without version numbers to
618 -- match the actual versions of the relevant packages installed.
619 updateDeps p = p{depends = map resolveDep (depends p)}
622 | realVersion dep_pkgid = dep_pkgid
623 | otherwise = lookupDep dep_pkgid
627 name = pkgName dep_pkgid
629 case [ pid | p <- concat (map snd db_stack),
631 pkgName pid == name ] of
632 (pid:_) -> pid -- Found installed package,
633 -- replete with its version
634 [] -> dep_pkgid -- No installed package; use
635 -- the version-less one
637 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
638 -> IO [PackageIdentifier]
639 checkDuplicates db_stack pkg update force = do
642 (_top_db_name, pkgs) : _ = db_stack
644 -- Check whether this package id already exists in this DB
646 when (not update && (pkgid `elem` map package pkgs)) $
647 die ("package " ++ showPackageId pkgid ++ " is already installed")
650 -- Check whether any of the dependencies of the current package
651 -- conflict with each other.
654 all_pkgs = concat (map snd db_stack)
656 allModules p = exposedModules p ++ hiddenModules p
658 our_dependencies = closePackageDeps all_pkgs [pkg]
659 all_dep_modules = concat (map (\p -> zip (allModules p) (repeat p))
662 overlaps = [ (m, map snd group)
663 | group@((m,_):_) <- groupBy eqfst (sortBy cmpfst all_dep_modules),
665 where eqfst (a,_) (b,_) = a == b
666 cmpfst (a,_) (b,_) = a `compare` b
668 when (not (null overlaps)) $
669 diePrettyOrForce force $ vcat [
670 text "package" <+> text (showPackageId (package pkg)) <+>
671 text "has conflicting dependencies:",
672 let complain_about (mod,ps) =
673 text mod <+> text "is in the following packages:" <+>
674 sep (map (text.showPackageId.package) ps)
676 nest 3 (vcat (map complain_about overlaps))
680 -- Now check whether exposing this package will result in conflicts, and
681 -- Figure out which packages we need to hide to resolve the conflicts.
684 closure_exposed_pkgs = closePackageDeps pkgs (filter exposed pkgs)
686 new_dep_modules = concat $ map allModules $
687 filter (\p -> package p `notElem`
688 map package closure_exposed_pkgs) $
691 pkgs_with_overlapping_modules =
692 [ (p, overlapping_mods)
693 | p <- closure_exposed_pkgs,
694 let overlapping_mods =
695 filter (`elem` new_dep_modules) (allModules p),
696 (_:_) <- [overlapping_mods] --trick to get the non-empty ones
699 to_hide = map package
701 $ closePackageDepsUpward pkgs
702 $ map fst pkgs_with_overlapping_modules
704 when (not update && exposed pkg && not (null pkgs_with_overlapping_modules)) $ do
706 text "package" <+> text (showPackageId (package pkg)) <+>
707 text "conflicts with the following packages, which are",
708 text "either exposed or a dependency (direct or indirect) of an exposed package:",
709 let complain_about (p, mods)
710 = text (showPackageId (package p)) <+> text "contains modules" <+>
711 sep (punctuate comma (map text mods)) in
712 nest 3 (vcat (map complain_about pkgs_with_overlapping_modules)),
713 text "Using 'update' instead of 'register' will cause the following packages",
714 text "to be hidden, which will eliminate the conflict:",
715 nest 3 (sep (map (text.showPackageId) to_hide))
718 when (not (null to_hide)) $ do
719 hPutStrLn stderr $ render $
720 sep [text "Warning: hiding the following packages to avoid conflict: ",
721 nest 2 (sep (map (text.showPackageId) to_hide))]
726 closure :: (a->[a]->Bool) -> (a -> [a]) -> [a] -> [a] -> [a]
727 closure pred more [] res = res
728 closure pred more (p:ps) res
729 | p `pred` res = closure pred more ps res
730 | otherwise = closure pred more (more p ++ ps) (p:res)
732 closePackageDeps :: [InstalledPackageInfo] -> [InstalledPackageInfo]
733 -> [InstalledPackageInfo]
734 closePackageDeps db start
735 = closure (\p ps -> package p `elem` map package ps) getDepends start []
737 getDepends p = [ pkg | dep <- depends p, pkg <- lookupPkg dep ]
738 lookupPkg p = [ q | q <- db, p == package q ]
740 closePackageDepsUpward :: [InstalledPackageInfo] -> [InstalledPackageInfo]
741 -> [InstalledPackageInfo]
742 closePackageDepsUpward db start
743 = closure (\p ps -> package p `elem` map package ps) getUpwardDepends start []
745 getUpwardDepends p = [ pkg | pkg <- db, package p `elem` depends pkg ]
748 checkDir :: Bool -> String -> IO ()
750 | "$topdir" `isPrefixOf` d = return ()
751 -- can't check this, because we don't know what $topdir is
753 there <- doesDirectoryExist d
755 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
757 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
758 checkDep db_stack force pkgid
759 | not real_version || pkgid `elem` pkgids = return ()
760 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
763 -- for backwards compat, we treat 0.0 as a special version,
764 -- and don't check that it actually exists.
765 real_version = realVersion pkgid
767 all_pkgs = concat (map snd db_stack)
768 pkgids = map package all_pkgs
770 realVersion :: PackageIdentifier -> Bool
771 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
773 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
774 checkHSLib dirs auto_ghci_libs force lib = do
775 let batch_lib_file = "lib" ++ lib ++ ".a"
776 bs <- mapM (doesLibExistIn batch_lib_file) dirs
777 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
778 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
780 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
782 doesLibExistIn :: String -> String -> IO Bool
784 | "$topdir" `isPrefixOf` d = return True
785 | otherwise = doesFileExist (d ++ '/':lib)
787 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
788 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
789 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
791 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
792 case [dir | (exists,dir) <- zip bs dirs, exists] of
793 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
796 ghci_lib_file = lib ++ ".o"
798 -- automatically build the GHCi version of a batch lib,
799 -- using ld --whole-archive.
801 autoBuildGHCiLib :: String -> String -> String -> IO ()
802 autoBuildGHCiLib dir batch_file ghci_file = do
803 let ghci_lib_file = dir ++ '/':ghci_file
804 batch_lib_file = dir ++ '/':batch_file
805 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
806 #if defined(darwin_HOST_OS)
807 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
808 #elif defined(mingw32_HOST_OS)
809 execDir <- getExecDir "/bin/ghc-pkg.exe"
810 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
812 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
814 when (r /= ExitSuccess) $ exitWith r
815 hPutStrLn stderr (" done.")
817 -- -----------------------------------------------------------------------------
818 -- Updating the DB with the new package.
821 :: PackageDBStack -- the full stack
822 -> [PackageIdentifier] -- packages to hide
823 -> [InstalledPackageInfo] -- packages in *this* DB
824 -> InstalledPackageInfo -- the new package
825 -> IO [InstalledPackageInfo]
826 updatePackageDB db_stack to_hide pkgs new_pkg = do
828 pkgid = package new_pkg
830 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
832 -- When update is on, and we're exposing the new package,
833 -- we hide any packages which conflict (see checkDuplicates)
834 -- in the current DB.
836 | exposed new_pkg && package p `elem` to_hide = p{ exposed = False }
839 return (pkgs'++ [new_pkg])
841 -- -----------------------------------------------------------------------------
842 -- Searching for modules
846 findModules :: [FilePath] -> IO [String]
848 mms <- mapM searchDir paths
851 searchDir path prefix = do
852 fs <- getDirectoryEntries path `catch` \_ -> return []
853 searchEntries path prefix fs
855 searchEntries path prefix [] = return []
856 searchEntries path prefix (f:fs)
857 | looks_like_a_module = do
858 ms <- searchEntries path prefix fs
859 return (prefix `joinModule` f : ms)
860 | looks_like_a_component = do
861 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
862 ms' <- searchEntries path prefix fs
865 searchEntries path prefix fs
868 (base,suffix) = splitFileExt f
869 looks_like_a_module =
870 suffix `elem` haskell_suffixes &&
871 all okInModuleName base
872 looks_like_a_component =
873 null suffix && all okInModuleName base
879 -- -----------------------------------------------------------------------------
880 -- The old command-line syntax, supported for backwards compatibility
887 | OF_Add Bool {- True => replace existing info -}
888 | OF_Remove String | OF_Show String
889 | OF_Field String | OF_AutoGHCiLibs | OF_Force
890 | OF_DefinedName String String
891 | OF_GlobalConfig FilePath
894 isAction :: OldFlag -> Bool
895 isAction OF_Config{} = False
896 isAction OF_Field{} = False
897 isAction OF_Input{} = False
898 isAction OF_AutoGHCiLibs{} = False
899 isAction OF_Force{} = False
900 isAction OF_DefinedName{} = False
901 isAction OF_GlobalConfig{} = False
904 oldFlags :: [OptDescr OldFlag]
906 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
907 "use the specified package config file",
908 Option ['l'] ["list-packages"] (NoArg OF_List)
909 "list packages in all config files",
910 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
911 "list packages in the specified config file",
912 Option ['a'] ["add-package"] (NoArg (OF_Add False))
914 Option ['u'] ["update-package"] (NoArg (OF_Add True))
915 "update package with new configuration",
916 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
917 "read new package info from specified file",
918 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
919 "show the configuration for package NAME",
920 Option [] ["field"] (ReqArg OF_Field "FIELD")
921 "(with --show-package) Show field FIELD only",
922 Option [] ["force"] (NoArg OF_Force)
923 "ignore missing directories/libraries",
924 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
925 "remove an installed package",
926 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
927 "automatically build libs for GHCi (with -a)",
928 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
929 "define NAME as VALUE",
930 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
931 "location of the global package config"
935 case break (=='=') str of
936 (nm,[]) -> OF_DefinedName nm []
937 (nm,_:val) -> OF_DefinedName nm val
939 oldRunit :: [OldFlag] -> IO ()
941 let new_flags = [ f | Just f <- map conv clis ]
943 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
944 conv (OF_Config f) = Just (FlagConfig f)
949 let fields = [ f | OF_Field f <- clis ]
951 let auto_ghci_libs = any isAuto clis
952 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
953 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
955 force = OF_Force `elem` clis
957 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
959 case [ c | c <- clis, isAction c ] of
960 [ OF_List ] -> listPackages new_flags Nothing
961 [ OF_ListLocal ] -> listPackages new_flags Nothing
963 registerPackage input_file defines new_flags auto_ghci_libs upd force
964 [ OF_Remove pkgid_str ] -> do
965 pkgid <- readPkgId pkgid_str
966 unregisterPackage pkgid new_flags
967 [ OF_Show pkgid_str ]
969 pkgid <- readPkgId pkgid_str
970 describePackage new_flags pkgid
972 pkgid <- readPkgId pkgid_str
973 mapM_ (describeField new_flags pkgid) fields
975 prog <- getProgramName
976 die (usageInfo (usageHeader prog) flags)
978 my_head :: String -> [a] -> a
979 my_head s [] = error s
982 -- ---------------------------------------------------------------------------
983 -- expanding environment variables in the package configuration
985 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
986 expandEnvVars str defines force = go str ""
988 go "" acc = return $! reverse acc
989 go ('$':'{':str) acc | (var, '}':rest) <- break close str
990 = do value <- lookupEnvVar var
991 go rest (reverse value ++ acc)
992 where close c = c == '}' || c == '\n' -- don't span newlines
996 lookupEnvVar :: String -> IO String
998 case lookup nm defines of
999 Just x | not (null x) -> return x
1001 catch (System.getEnv nm)
1002 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
1006 -----------------------------------------------------------------------------
1008 getProgramName :: IO String
1009 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1010 where str `withoutSuffix` suff
1011 | suff `isSuffixOf` str = take (length str - length suff) str
1014 bye :: String -> IO a
1015 bye s = putStr s >> exitWith ExitSuccess
1017 die :: String -> IO a
1020 prog <- getProgramName
1021 hPutStrLn stderr (prog ++ ": " ++ s)
1022 exitWith (ExitFailure 1)
1024 dieOrForce :: Bool -> String -> IO ()
1026 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1027 | otherwise = die (s ++ " (use --force to override)")
1029 diePretty :: Doc -> IO ()
1032 prog <- getProgramName
1033 hPutStrLn stderr $ render $ (text prog <> colon $$ nest 2 doc)
1034 exitWith (ExitFailure 1)
1036 diePrettyOrForce :: Bool -> Doc -> IO ()
1037 diePrettyOrForce force doc
1038 | force = do hFlush stdout; hPutStrLn stderr (render (doc $$ text "(ignoring)"))
1039 | otherwise = diePretty (doc $$ text "(use --force to override)")
1041 -----------------------------------------
1042 -- Cut and pasted from ghc/compiler/SysTools
1044 #if defined(mingw32_HOST_OS)
1045 subst a b ls = map (\ x -> if x == a then b else x) ls
1046 unDosifyPath xs = subst '\\' '/' xs
1048 getExecDir :: String -> IO (Maybe String)
1049 -- (getExecDir cmd) returns the directory in which the current
1050 -- executable, which should be called 'cmd', is running
1051 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1052 -- you'll get "/a/b/c" back as the result
1054 = allocaArray len $ \buf -> do
1055 ret <- getModuleFileName nullPtr buf len
1056 if ret == 0 then return Nothing
1057 else do s <- peekCString buf
1058 return (Just (reverse (drop (length cmd)
1059 (reverse (unDosifyPath s)))))
1061 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1063 foreign import stdcall unsafe "GetModuleFileNameA"
1064 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1066 getExecDir :: String -> IO (Maybe String)
1067 getExecDir _ = return Nothing
1070 -- -----------------------------------------------------------------------------
1073 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1074 -- It joins directory and file names to form a complete file path.
1076 -- The general rule is:
1078 -- > dir `joinFileName` basename == path
1080 -- > (dir,basename) = splitFileName path
1082 -- There might be an exceptions to the rule but in any case the
1083 -- reconstructed path will refer to the same object (file or directory).
1084 -- An example exception is that on Windows some slashes might be converted
1086 joinFileName :: String -> String -> FilePath
1087 joinFileName "" fname = fname
1088 joinFileName "." fname = fname
1089 joinFileName dir "" = dir
1090 joinFileName dir fname
1091 | isPathSeparator (last dir) = dir++fname
1092 | otherwise = dir++pathSeparator:fname
1094 -- | Checks whether the character is a valid path separator for the host
1095 -- platform. The valid character is a 'pathSeparator' but since the Windows
1096 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1097 -- checks for it on this platform, too.
1098 isPathSeparator :: Char -> Bool
1099 isPathSeparator ch = ch == pathSeparator || ch == '/'
1101 -- | Provides a platform-specific character used to separate directory levels in
1102 -- a path string that reflects a hierarchical file system organization. The
1103 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1104 -- (@\"\\\"@) on the Windows operating system.
1105 pathSeparator :: Char
1106 #ifdef mingw32_HOST_OS
1107 pathSeparator = '\\'