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
38 import qualified Exception
41 import Data.Char ( isSpace )
44 import System ( getArgs, getProgName, getEnv,
45 exitWith, ExitCode(..)
48 import Data.List ( isPrefixOf, isSuffixOf, intersperse, groupBy, sortBy )
50 #ifdef mingw32_HOST_OS
53 #if __GLASGOW_HASKELL__ >= 504
54 import Foreign.C.String
60 -- -----------------------------------------------------------------------------
67 case getOpt Permute flags args of
68 (cli,_,[]) | FlagHelp `elem` cli -> do
69 prog <- getProgramName
70 bye (usageInfo (usageHeader prog) flags)
71 (cli,_,[]) | FlagVersion `elem` cli ->
75 (_,_,errors) -> tryOldCmdLine errors args
77 -- If the new command-line syntax fails, then we try the old. If that
78 -- fails too, then we output the original errors and the new syntax
79 -- (so the old syntax is still available, but hidden).
80 tryOldCmdLine :: [String] -> [String] -> IO ()
81 tryOldCmdLine errors args = do
82 case getOpt Permute oldFlags args of
86 prog <- getProgramName
87 die (concat errors ++ usageInfo (usageHeader prog) flags)
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
98 | FlagGlobalConfig FilePath
101 | FlagDefinedName String String
104 flags :: [OptDescr Flag]
106 Option [] ["user"] (NoArg FlagUser)
107 "use the current user's package database",
108 Option [] ["global"] (NoArg FlagGlobal)
109 "(default) use the global package database",
110 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
111 "act upon specified package config file (only)",
112 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
113 "location of the global package config",
114 Option [] ["force"] (NoArg FlagForce)
115 "ignore missing dependencies, directories, and libraries",
116 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
117 "automatically build libs for GHCi (with register)",
118 Option ['?'] ["help"] (NoArg FlagHelp)
119 "display this help and exit",
120 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
121 "define NAME as VALUE",
122 Option ['V'] ["version"] (NoArg FlagVersion)
123 "output version information and exit"
127 case break (=='=') str of
128 (nm,[]) -> FlagDefinedName nm []
129 (nm,_:val) -> FlagDefinedName nm val
131 ourCopyright :: String
132 ourCopyright = "GHC package manager version " ++ version ++ "\n"
134 usageHeader :: String -> String
135 usageHeader prog = substProg prog $
137 " $p register {filename | -}\n" ++
138 " Register the package using the specified installed package\n" ++
139 " description. The syntax for the latter is given in the $p\n" ++
140 " documentation.\n" ++
142 " $p update {filename | -}\n" ++
143 " Register the package, overwriting any other package with the\n" ++
146 " $p unregister {pkg-id}\n" ++
147 " Unregister the specified package.\n" ++
149 " $p expose {pkg-id}\n" ++
150 " Expose the specified package.\n" ++
152 " $p hide {pkg-id}\n" ++
153 " Hide the specified package.\n" ++
156 " List registered packages in the global database, and also the" ++
157 " user database if --user is given.\n" ++
159 " $p describe {pkg-id}\n" ++
160 " Give the registered description for the specified package. The\n" ++
161 " description is returned in precisely the syntax required by $p\n" ++
164 " $p field {pkg-id} {field}\n" ++
165 " Extract the specified field of the package description for the\n" ++
166 " specified package.\n" ++
168 " The following optional flags are also accepted:\n"
170 substProg :: String -> String -> String
172 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
173 substProg prog (c:xs) = c : substProg prog xs
175 -- -----------------------------------------------------------------------------
178 runit :: [Flag] -> [String] -> IO ()
179 runit cli nonopts = do
180 prog <- getProgramName
182 force = FlagForce `elem` cli
183 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
184 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
186 -- first, parse the command
188 ["register", filename] ->
189 registerPackage filename defines cli auto_ghci_libs False force
190 ["update", filename] ->
191 registerPackage filename defines cli auto_ghci_libs True force
192 ["unregister", pkgid_str] -> do
193 pkgid <- readGlobPkgId pkgid_str
194 unregisterPackage pkgid cli
195 ["expose", pkgid_str] -> do
196 pkgid <- readGlobPkgId pkgid_str
197 exposePackage pkgid cli
198 ["hide", pkgid_str] -> do
199 pkgid <- readGlobPkgId pkgid_str
200 hidePackage pkgid cli
203 ["describe", pkgid_str] -> do
204 pkgid <- readGlobPkgId pkgid_str
205 describePackage cli pkgid
206 ["field", pkgid_str, field] -> do
207 pkgid <- readGlobPkgId pkgid_str
208 describeField cli pkgid field
210 die ("missing command\n" ++
211 usageInfo (usageHeader prog) flags)
213 die ("command-line syntax error\n" ++
214 usageInfo (usageHeader prog) flags)
216 parseCheck :: ReadP a a -> String -> String -> IO a
217 parseCheck parser str what =
218 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
220 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
222 readPkgId :: String -> IO PackageIdentifier
223 readPkgId str = parseCheck parsePackageId str "package identifier"
225 readGlobPkgId :: String -> IO PackageIdentifier
226 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
228 parseGlobPackageId :: ReadP r PackageIdentifier
232 (do n <- parsePackageName; string "-*"
233 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
235 -- globVersion means "all versions"
236 globVersion :: Version
237 globVersion = Version{ versionBranch=[], versionTags=["*"] }
239 -- -----------------------------------------------------------------------------
242 -- Some commands operate on a single database:
243 -- register, unregister, expose, hide
244 -- however these commands also check the union of the available databases
245 -- in order to check consistency. For example, register will check that
246 -- dependencies exist before registering a package.
248 -- Some commands operate on multiple databases, with overlapping semantics:
249 -- list, describe, field
251 type PackageDBName = FilePath
252 type PackageDB = [InstalledPackageInfo]
254 type PackageDBStack = [(PackageDBName,PackageDB)]
255 -- A stack of package databases. Convention: head is the topmost
256 -- in the stack. Earlier entries override later one.
258 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
259 getPkgDatabases modify flags = do
260 -- first we determine the location of the global package config. On Windows,
261 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
262 -- location is passed to the binary using the --global-config flag by the
264 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
266 case [ f | FlagGlobalConfig f <- flags ] of
267 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
269 Nothing -> die err_msg
270 Just dir -> return (dir `joinFileName` "package.conf")
271 fs -> return (last fs)
273 -- get the location of the user package database, and create it if necessary
274 appdir <- getAppUserDataDirectory "ghc"
277 subdir = targetARCH ++ '-':targetOS ++ '-':version
278 archdir = appdir `joinFileName` subdir
279 user_conf = archdir `joinFileName` "package.conf"
280 user_exists <- doesFileExist user_conf
283 -- The semantics here are slightly strange. If we are
284 -- *modifying* the database, then the default is to modify
285 -- the global database by default, unless you say --user.
286 -- If we are not modifying (eg. list, describe etc.) then
287 -- the user database is included by default.
289 | modify = foldl addDB [global_conf] flags
290 | not user_exists = foldl addDB [global_conf] flags
291 | otherwise = foldl addDB [user_conf,global_conf] flags
293 -- implement the following rules:
294 -- --user means overlap with the user database
295 -- --global means reset to just the global database
296 -- -f <file> means overlap with <file>
298 | user_conf `elem` dbs = dbs
299 | modify || user_exists = user_conf : dbs
300 addDB dbs FlagGlobal = [global_conf]
301 addDB dbs (FlagConfig f) = f : dbs
304 -- we create the user database iff (a) we're modifying, and (b) the
305 -- user asked to use it by giving the --user flag.
306 when (not user_exists && user_conf `elem` databases) $ do
307 putStrLn ("Creating user package database in " ++ user_conf)
308 createDirectoryIfMissing True archdir
309 writeFile user_conf emptyPackageConfig
311 db_stack <- mapM readParseDatabase databases
314 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
315 readParseDatabase filename = do
316 str <- readFile filename
317 let packages = read str
318 Exception.evaluate packages
319 `Exception.catch` \_ ->
320 die (filename ++ ": parse error in package config file")
321 return (filename,packages)
323 emptyPackageConfig :: String
324 emptyPackageConfig = "[]"
326 -- -----------------------------------------------------------------------------
329 registerPackage :: FilePath
330 -> [(String,String)] -- defines
332 -> Bool -- auto_ghci_libs
336 registerPackage input defines flags auto_ghci_libs update force = do
337 db_stack <- getPkgDatabases True flags
339 db_to_operate_on = my_head "db" db_stack
340 db_filename = fst db_to_operate_on
342 checkConfigAccess db_filename
347 putStr "Reading package info from stdin ... "
350 putStr ("Reading package info from " ++ show f ++ " ... ")
353 expanded <- expandEnvVars s defines force
355 pkg0 <- parsePackageInfo expanded defines force
358 let pkg = resolveDeps db_stack pkg0
359 overlaps <- validatePackageConfig pkg db_stack auto_ghci_libs update force
360 new_details <- updatePackageDB db_stack overlaps (snd db_to_operate_on) pkg
361 savePackageConfig db_filename
362 maybeRestoreOldConfig db_filename $
363 writeNewConfig db_filename new_details
369 -> IO InstalledPackageInfo
370 parsePackageInfo str defines force =
371 case parseInstalledPackageInfo str of
372 ParseOk ok -> return ok
373 ParseFailed err -> die (showError err)
375 -- -----------------------------------------------------------------------------
376 -- Exposing, Hiding, Unregistering are all similar
378 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
379 exposePackage = modifyPackage (\p -> [p{exposed=True}])
381 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
382 hidePackage = modifyPackage (\p -> [p{exposed=False}])
384 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
385 unregisterPackage = modifyPackage (\p -> [])
388 :: (InstalledPackageInfo -> [InstalledPackageInfo])
392 modifyPackage fn pkgid flags = do
393 db_stack <- getPkgDatabases True{-modify-} flags
394 let ((db_name, pkgs) : _) = db_stack
395 checkConfigAccess db_name
396 ps <- findPackages [(db_name,pkgs)] pkgid
397 let pids = map package ps
398 savePackageConfig db_name
399 let new_config = concat (map modify pkgs)
401 | package pkg `elem` pids = fn pkg
403 maybeRestoreOldConfig db_name $
404 writeNewConfig db_name new_config
406 -- -----------------------------------------------------------------------------
409 listPackages :: [Flag] -> IO ()
410 listPackages flags = do
411 db_stack <- getPkgDatabases False flags
412 mapM_ show_pkgconf (reverse db_stack)
413 where show_pkgconf (db_name,pkg_confs) =
414 hPutStrLn stdout (render $
415 text (db_name ++ ":") $$ nest 4 packages
417 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
420 | otherwise = parens doc
421 where doc = text (showPackageId (package p))
423 -- -----------------------------------------------------------------------------
426 describePackage :: [Flag] -> PackageIdentifier -> IO ()
427 describePackage flags pkgid = do
428 db_stack <- getPkgDatabases False flags
429 ps <- findPackages db_stack pkgid
430 mapM_ (putStrLn . showInstalledPackageInfo) ps
432 -- PackageId is can have globVersion for the version
433 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
434 findPackages db_stack pkgid
435 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
436 [] -> die ("cannot find package " ++ showPackageId pkgid)
438 -- if the version is globVersion, then we are allowed to match
439 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
440 -- but "Cabal" matches just one Cabal package - if there are more,
442 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
445 -> die ("package " ++ showPackageId pkgid ++
446 " matches multiple packages: " ++
447 concat (intersperse ", " (
448 map (showPackageId.package) ps)))
451 = (pkgName pid == pkgName p)
452 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
453 where p = package pkg
455 all_pkgs = concat (map snd db_stack)
457 -- -----------------------------------------------------------------------------
460 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
461 describeField flags pkgid field = do
462 db_stack <- getPkgDatabases False flags
463 case toField field of
464 Nothing -> die ("unknown field: " ++ field)
466 ps <- findPackages db_stack pkgid
467 mapM_ (putStrLn.fn) ps
469 toField :: String -> Maybe (InstalledPackageInfo -> String)
470 -- backwards compatibility:
471 toField "import_dirs" = Just $ strList . importDirs
472 toField "source_dirs" = Just $ strList . importDirs
473 toField "library_dirs" = Just $ strList . libraryDirs
474 toField "hs_libraries" = Just $ strList . hsLibraries
475 toField "extra_libraries" = Just $ strList . extraLibraries
476 toField "include_dirs" = Just $ strList . includeDirs
477 toField "c_includes" = Just $ strList . includes
478 toField "package_deps" = Just $ strList . map showPackageId. depends
479 toField "extra_cc_opts" = Just $ strList . ccOptions
480 toField "extra_ld_opts" = Just $ strList . ldOptions
481 toField "framework_dirs" = Just $ strList . frameworkDirs
482 toField "extra_frameworks"= Just $ strList . frameworks
483 toField s = showInstalledPackageInfoField s
485 strList :: [String] -> String
488 -- -----------------------------------------------------------------------------
489 -- Manipulating package.conf files
491 checkConfigAccess :: FilePath -> IO ()
492 checkConfigAccess filename = do
493 access <- getPermissions filename
494 when (not (writable access))
495 (die (filename ++ ": you don't have permission to modify this file"))
497 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
498 maybeRestoreOldConfig filename io
499 = io `catch` \e -> do
500 hPutStrLn stderr (show e)
501 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
502 "configuration was being written. Attempting to \n"++
503 "restore the old configuration... ")
504 renameFile (filename ++ ".old") filename
505 hPutStrLn stdout "done."
508 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
509 writeNewConfig filename packages = do
510 hPutStr stdout "Writing new package config file... "
511 h <- openFile filename WriteMode
512 hPutStrLn h (show packages)
514 hPutStrLn stdout "done."
516 savePackageConfig :: FilePath -> IO ()
517 savePackageConfig filename = do
518 hPutStr stdout "Saving old package config file... "
519 -- mv rather than cp because we've already done an hGetContents
520 -- on this file so we won't be able to open it for writing
521 -- unless we move the old one out of the way...
522 let oldFile = filename ++ ".old"
523 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
524 when doesExist (removeFile oldFile `catch` (const $ return ()))
525 catch (renameFile filename oldFile)
527 hPutStrLn stderr (unwords [ "Unable to rename "
533 hPutStrLn stdout "done."
535 -----------------------------------------------------------------------------
536 -- Sanity-check a new package config, and automatically build GHCi libs
539 validatePackageConfig :: InstalledPackageInfo
541 -> Bool -- auto-ghc-libs
544 -> IO [PackageIdentifier]
545 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
547 overlaps <- checkDuplicates db_stack pkg update force
548 mapM_ (checkDep db_stack force) (depends pkg)
549 mapM_ (checkDir force) (importDirs pkg)
550 mapM_ (checkDir force) (libraryDirs pkg)
551 mapM_ (checkDir force) (includeDirs pkg)
552 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
554 -- ToDo: check these somehow?
555 -- extra_libraries :: [String],
556 -- c_includes :: [String],
558 -- When the package name and version are put together, sometimes we can
559 -- end up with a package id that cannot be parsed. This will lead to
560 -- difficulties when the user wants to refer to the package later, so
561 -- we check that the package id can be parsed properly here.
562 checkPackageId :: InstalledPackageInfo -> IO ()
564 let str = showPackageId (package ipi) in
565 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
567 [] -> die ("invalid package identifier: " ++ str)
568 _ -> die ("ambiguous package identifier: " ++ str)
570 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
571 resolveDeps db_stack p = updateDeps p
573 -- The input package spec is allowed to give a package dependency
574 -- without a version number; e.g.
576 -- Here, we update these dependencies without version numbers to
577 -- match the actual versions of the relevant packages installed.
578 updateDeps p = p{depends = map resolveDep (depends p)}
581 | realVersion dep_pkgid = dep_pkgid
582 | otherwise = lookupDep dep_pkgid
586 name = pkgName dep_pkgid
588 case [ pid | p <- concat (map snd db_stack),
590 pkgName pid == name ] of
591 (pid:_) -> pid -- Found installed package,
592 -- replete with its version
593 [] -> dep_pkgid -- No installed package; use
594 -- the version-less one
596 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
597 -> IO [PackageIdentifier]
598 checkDuplicates db_stack pkg update force = do
601 (_top_db_name, pkgs) : _ = db_stack
603 -- Check whether this package id already exists in this DB
605 when (not update && (pkgid `elem` map package pkgs)) $
606 die ("package " ++ showPackageId pkgid ++ " is already installed")
609 -- Check whether any of the dependencies of the current package
610 -- conflict with each other.
613 all_pkgs = concat (map snd db_stack)
615 allModules p = exposedModules p ++ hiddenModules p
617 our_dependencies = closePackageDeps all_pkgs [pkg]
618 all_dep_modules = concat (map (\p -> zip (allModules p) (repeat p))
621 overlaps = [ (m, map snd group)
622 | group@((m,_):_) <- groupBy eqfst (sortBy cmpfst all_dep_modules),
624 where eqfst (a,_) (b,_) = a == b
625 cmpfst (a,_) (b,_) = a `compare` b
627 when (not (null overlaps)) $
628 diePrettyOrForce force $ vcat [
629 text "package" <+> text (showPackageId (package pkg)) <+>
630 text "has conflicting dependencies:",
631 let complain_about (mod,ps) =
632 text mod <+> text "is in the following packages:" <+>
633 sep (map (text.showPackageId.package) ps)
635 nest 3 (vcat (map complain_about overlaps))
639 -- Now check whether exposing this package will result in conflicts, and
640 -- Figure out which packages we need to hide to resolve the conflicts.
643 closure_exposed_pkgs = closePackageDeps pkgs (filter exposed pkgs)
645 new_dep_modules = concat $ map allModules $
646 filter (\p -> package p `notElem`
647 map package closure_exposed_pkgs) $
650 pkgs_with_overlapping_modules =
651 [ (p, overlapping_mods)
652 | p <- closure_exposed_pkgs,
653 let overlapping_mods =
654 filter (`elem` new_dep_modules) (allModules p),
655 (_:_) <- [overlapping_mods] --trick to get the non-empty ones
658 to_hide = map package
660 $ closePackageDepsUpward pkgs
661 $ map fst pkgs_with_overlapping_modules
663 when (not update && exposed pkg && not (null pkgs_with_overlapping_modules)) $ do
665 text "package" <+> text (showPackageId (package pkg)) <+>
666 text "conflicts with the following packages, which are",
667 text "either exposed or a dependency (direct or indirect) of an exposed package:",
668 let complain_about (p, mods)
669 = text (showPackageId (package p)) <+> text "contains modules" <+>
670 sep (punctuate comma (map text mods)) in
671 nest 3 (vcat (map complain_about pkgs_with_overlapping_modules)),
672 text "Using 'update' instead of 'register' will cause the following packages",
673 text "to be hidden, which will eliminate the conflict:",
674 nest 3 (sep (map (text.showPackageId) to_hide))
677 when (not (null to_hide)) $ do
678 hPutStrLn stderr $ render $
679 sep [text "Warning: hiding the following packages to avoid conflict: ",
680 nest 2 (sep (map (text.showPackageId) to_hide))]
685 closure :: (a->[a]->Bool) -> (a -> [a]) -> [a] -> [a] -> [a]
686 closure pred more [] res = res
687 closure pred more (p:ps) res
688 | p `pred` res = closure pred more ps res
689 | otherwise = closure pred more (more p ++ ps) (p:res)
691 closePackageDeps :: [InstalledPackageInfo] -> [InstalledPackageInfo]
692 -> [InstalledPackageInfo]
693 closePackageDeps db start
694 = closure (\p ps -> package p `elem` map package ps) getDepends start []
696 getDepends p = [ pkg | dep <- depends p, pkg <- lookupPkg dep ]
697 lookupPkg p = [ q | q <- db, p == package q ]
699 closePackageDepsUpward :: [InstalledPackageInfo] -> [InstalledPackageInfo]
700 -> [InstalledPackageInfo]
701 closePackageDepsUpward db start
702 = closure (\p ps -> package p `elem` map package ps) getUpwardDepends start []
704 getUpwardDepends p = [ pkg | pkg <- db, package p `elem` depends pkg ]
707 checkDir :: Bool -> String -> IO ()
709 | "$topdir" `isPrefixOf` d = return ()
710 -- can't check this, because we don't know what $topdir is
712 there <- doesDirectoryExist d
714 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
716 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
717 checkDep db_stack force pkgid
718 | not real_version || pkgid `elem` pkgids = return ()
719 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
722 -- for backwards compat, we treat 0.0 as a special version,
723 -- and don't check that it actually exists.
724 real_version = realVersion pkgid
726 all_pkgs = concat (map snd db_stack)
727 pkgids = map package all_pkgs
729 realVersion :: PackageIdentifier -> Bool
730 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
732 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
733 checkHSLib dirs auto_ghci_libs force lib = do
734 let batch_lib_file = "lib" ++ lib ++ ".a"
735 bs <- mapM (doesLibExistIn batch_lib_file) dirs
736 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
737 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
739 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
741 doesLibExistIn :: String -> String -> IO Bool
743 | "$topdir" `isPrefixOf` d = return True
744 | otherwise = doesFileExist (d ++ '/':lib)
746 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
747 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
748 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
750 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
751 case [dir | (exists,dir) <- zip bs dirs, exists] of
752 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
755 ghci_lib_file = lib ++ ".o"
757 -- automatically build the GHCi version of a batch lib,
758 -- using ld --whole-archive.
760 autoBuildGHCiLib :: String -> String -> String -> IO ()
761 autoBuildGHCiLib dir batch_file ghci_file = do
762 let ghci_lib_file = dir ++ '/':ghci_file
763 batch_lib_file = dir ++ '/':batch_file
764 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
765 #if defined(darwin_HOST_OS)
766 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
767 #elif defined(mingw32_HOST_OS)
768 execDir <- getExecDir "/bin/ghc-pkg.exe"
769 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
771 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
773 when (r /= ExitSuccess) $ exitWith r
774 hPutStrLn stderr (" done.")
776 -- -----------------------------------------------------------------------------
777 -- Updating the DB with the new package.
780 :: PackageDBStack -- the full stack
781 -> [PackageIdentifier] -- packages to hide
782 -> [InstalledPackageInfo] -- packages in *this* DB
783 -> InstalledPackageInfo -- the new package
784 -> IO [InstalledPackageInfo]
785 updatePackageDB db_stack to_hide pkgs new_pkg = do
787 pkgid = package new_pkg
789 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
791 -- When update is on, and we're exposing the new package,
792 -- we hide any packages which conflict (see checkDuplicates)
793 -- in the current DB.
795 | exposed new_pkg && package p `elem` to_hide = p{ exposed = False }
798 return (pkgs'++ [new_pkg])
800 -- -----------------------------------------------------------------------------
801 -- Searching for modules
805 findModules :: [FilePath] -> IO [String]
807 mms <- mapM searchDir paths
810 searchDir path prefix = do
811 fs <- getDirectoryEntries path `catch` \_ -> return []
812 searchEntries path prefix fs
814 searchEntries path prefix [] = return []
815 searchEntries path prefix (f:fs)
816 | looks_like_a_module = do
817 ms <- searchEntries path prefix fs
818 return (prefix `joinModule` f : ms)
819 | looks_like_a_component = do
820 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
821 ms' <- searchEntries path prefix fs
824 searchEntries path prefix fs
827 (base,suffix) = splitFileExt f
828 looks_like_a_module =
829 suffix `elem` haskell_suffixes &&
830 all okInModuleName base
831 looks_like_a_component =
832 null suffix && all okInModuleName base
838 -- -----------------------------------------------------------------------------
839 -- The old command-line syntax, supported for backwards compatibility
846 | OF_Add Bool {- True => replace existing info -}
847 | OF_Remove String | OF_Show String
848 | OF_Field String | OF_AutoGHCiLibs | OF_Force
849 | OF_DefinedName String String
850 | OF_GlobalConfig FilePath
853 isAction :: OldFlag -> Bool
854 isAction OF_Config{} = False
855 isAction OF_Field{} = False
856 isAction OF_Input{} = False
857 isAction OF_AutoGHCiLibs{} = False
858 isAction OF_Force{} = False
859 isAction OF_DefinedName{} = False
860 isAction OF_GlobalConfig{} = False
863 oldFlags :: [OptDescr OldFlag]
865 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
866 "use the specified package config file",
867 Option ['l'] ["list-packages"] (NoArg OF_List)
868 "list packages in all config files",
869 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
870 "list packages in the specified config file",
871 Option ['a'] ["add-package"] (NoArg (OF_Add False))
873 Option ['u'] ["update-package"] (NoArg (OF_Add True))
874 "update package with new configuration",
875 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
876 "read new package info from specified file",
877 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
878 "show the configuration for package NAME",
879 Option [] ["field"] (ReqArg OF_Field "FIELD")
880 "(with --show-package) Show field FIELD only",
881 Option [] ["force"] (NoArg OF_Force)
882 "ignore missing directories/libraries",
883 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
884 "remove an installed package",
885 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
886 "automatically build libs for GHCi (with -a)",
887 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
888 "define NAME as VALUE",
889 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
890 "location of the global package config"
894 case break (=='=') str of
895 (nm,[]) -> OF_DefinedName nm []
896 (nm,_:val) -> OF_DefinedName nm val
898 oldRunit :: [OldFlag] -> IO ()
900 let new_flags = [ f | Just f <- map conv clis ]
902 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
903 conv (OF_Config f) = Just (FlagConfig f)
908 let fields = [ f | OF_Field f <- clis ]
910 let auto_ghci_libs = any isAuto clis
911 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
912 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
914 force = OF_Force `elem` clis
916 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
918 case [ c | c <- clis, isAction c ] of
919 [ OF_List ] -> listPackages new_flags
920 [ OF_ListLocal ] -> listPackages new_flags
922 registerPackage input_file defines new_flags auto_ghci_libs upd force
923 [ OF_Remove pkgid_str ] -> do
924 pkgid <- readPkgId pkgid_str
925 unregisterPackage pkgid new_flags
926 [ OF_Show pkgid_str ]
928 pkgid <- readPkgId pkgid_str
929 describePackage new_flags pkgid
931 pkgid <- readPkgId pkgid_str
932 mapM_ (describeField new_flags pkgid) fields
934 prog <- getProgramName
935 die (usageInfo (usageHeader prog) flags)
937 my_head :: String -> [a] -> a
938 my_head s [] = error s
941 -- ---------------------------------------------------------------------------
942 -- expanding environment variables in the package configuration
944 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
945 expandEnvVars str defines force = go str ""
947 go "" acc = return $! reverse acc
948 go ('$':'{':str) acc | (var, '}':rest) <- break close str
949 = do value <- lookupEnvVar var
950 go rest (reverse value ++ acc)
951 where close c = c == '}' || c == '\n' -- don't span newlines
955 lookupEnvVar :: String -> IO String
957 case lookup nm defines of
958 Just x | not (null x) -> return x
960 catch (System.getEnv nm)
961 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
965 -----------------------------------------------------------------------------
967 getProgramName :: IO String
968 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
969 where str `withoutSuffix` suff
970 | suff `isSuffixOf` str = take (length str - length suff) str
973 bye :: String -> IO a
974 bye s = putStr s >> exitWith ExitSuccess
976 die :: String -> IO a
979 prog <- getProgramName
980 hPutStrLn stderr (prog ++ ": " ++ s)
981 exitWith (ExitFailure 1)
983 dieOrForce :: Bool -> String -> IO ()
985 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
986 | otherwise = die (s ++ " (use --force to override)")
988 diePretty :: Doc -> IO ()
991 prog <- getProgramName
992 hPutStrLn stderr $ render $ (text prog <> colon $$ nest 2 doc)
993 exitWith (ExitFailure 1)
995 diePrettyOrForce :: Bool -> Doc -> IO ()
996 diePrettyOrForce force doc
997 | force = do hFlush stdout; hPutStrLn stderr (render (doc $$ text "(ignoring)"))
998 | otherwise = diePretty (doc $$ text "(use --force to override)")
1000 -----------------------------------------
1001 -- Cut and pasted from ghc/compiler/SysTools
1003 #if defined(mingw32_HOST_OS)
1004 subst a b ls = map (\ x -> if x == a then b else x) ls
1005 unDosifyPath xs = subst '\\' '/' xs
1007 getExecDir :: String -> IO (Maybe String)
1008 -- (getExecDir cmd) returns the directory in which the current
1009 -- executable, which should be called 'cmd', is running
1010 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1011 -- you'll get "/a/b/c" back as the result
1013 = allocaArray len $ \buf -> do
1014 ret <- getModuleFileName nullPtr buf len
1015 if ret == 0 then return Nothing
1016 else do s <- peekCString buf
1017 return (Just (reverse (drop (length cmd)
1018 (reverse (unDosifyPath s)))))
1020 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1022 foreign import stdcall unsafe "GetModuleFileNameA"
1023 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1025 getExecDir :: String -> IO (Maybe String)
1026 getExecDir _ = return Nothing
1029 -- -----------------------------------------------------------------------------
1032 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1033 -- It joins directory and file names to form a complete file path.
1035 -- The general rule is:
1037 -- > dir `joinFileName` basename == path
1039 -- > (dir,basename) = splitFileName path
1041 -- There might be an exceptions to the rule but in any case the
1042 -- reconstructed path will refer to the same object (file or directory).
1043 -- An example exception is that on Windows some slashes might be converted
1045 joinFileName :: String -> String -> FilePath
1046 joinFileName "" fname = fname
1047 joinFileName "." fname = fname
1048 joinFileName dir "" = dir
1049 joinFileName dir fname
1050 | isPathSeparator (last dir) = dir++fname
1051 | otherwise = dir++pathSeparator:fname
1053 -- | Checks whether the character is a valid path separator for the host
1054 -- platform. The valid character is a 'pathSeparator' but since the Windows
1055 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1056 -- checks for it on this platform, too.
1057 isPathSeparator :: Char -> Bool
1058 isPathSeparator ch = ch == pathSeparator || ch == '/'
1060 -- | Provides a platform-specific character used to separate directory levels in
1061 -- a path string that reflects a hierarchical file system organization. The
1062 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1063 -- (@\"\\\"@) on the Windows operating system.
1064 pathSeparator :: Char
1065 #ifdef mingw32_HOST_OS
1066 pathSeparator = '\\'