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
22 import Distribution.Package
23 import Distribution.Version
24 import System.FilePath
27 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
28 import Compat.RawSystem ( rawSystem )
30 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
31 import System.Cmd ( rawSystem )
36 #include "../../includes/ghcconfig.h"
38 import System.Console.GetOpt
39 import Text.PrettyPrint
40 import qualified Control.Exception as Exception
43 import Data.Char ( isSpace )
46 import System ( getArgs, getProgName, getEnv, exitWith, ExitCode(..) )
48 import System.IO.Error (try)
49 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy )
51 #ifdef mingw32_HOST_OS
53 import Foreign.C.String
56 import IO ( isPermissionError, isDoesNotExistError )
58 -- -----------------------------------------------------------------------------
65 case getOpt Permute flags args of
66 (cli,_,[]) | FlagHelp `elem` cli -> do
67 prog <- getProgramName
68 bye (usageInfo (usageHeader prog) flags)
69 (cli,_,[]) | FlagVersion `elem` cli ->
73 (_,_,errors) -> tryOldCmdLine errors args
75 -- If the new command-line syntax fails, then we try the old. If that
76 -- fails too, then we output the original errors and the new syntax
77 -- (so the old syntax is still available, but hidden).
78 tryOldCmdLine :: [String] -> [String] -> IO ()
79 tryOldCmdLine errors args = do
80 case getOpt Permute oldFlags args of
84 prog <- getProgramName
85 die (concat errors ++ usageInfo (usageHeader prog) flags)
87 -- -----------------------------------------------------------------------------
88 -- Command-line syntax
96 | FlagGlobalConfig FilePath
100 | FlagDefinedName String String
105 flags :: [OptDescr Flag]
107 Option [] ["user"] (NoArg FlagUser)
108 "use the current user's package database",
109 Option [] ["global"] (NoArg FlagGlobal)
110 "(default) use the global package database",
111 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
112 "act upon specified package config file (only)",
113 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
114 "location of the global package config",
115 Option [] ["force"] (NoArg FlagForce)
116 "ignore missing dependencies, directories, and libraries",
117 Option [] ["force-files"] (NoArg FlagForceFiles)
118 "ignore missing directories and libraries only",
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 for some commands",
129 Option [] ["names-only"] (NoArg FlagNamesOnly)
130 "only print package names, not versions; can only be used with list --simple-output"
134 case break (=='=') str of
135 (nm,[]) -> FlagDefinedName nm []
136 (nm,_:val) -> FlagDefinedName nm val
138 ourCopyright :: String
139 ourCopyright = "GHC package manager version " ++ version ++ "\n"
141 usageHeader :: String -> String
142 usageHeader prog = substProg prog $
144 " $p register {filename | -}\n" ++
145 " Register the package using the specified installed package\n" ++
146 " description. The syntax for the latter is given in the $p\n" ++
147 " documentation.\n" ++
149 " $p update {filename | -}\n" ++
150 " Register the package, overwriting any other package with the\n" ++
153 " $p unregister {pkg-id}\n" ++
154 " Unregister the specified package.\n" ++
156 " $p expose {pkg-id}\n" ++
157 " Expose the specified package.\n" ++
159 " $p hide {pkg-id}\n" ++
160 " Hide the specified package.\n" ++
162 " $p list [pkg]\n" ++
163 " List registered packages in the global database, and also the\n" ++
164 " user database if --user is given. If a package name is given\n" ++
165 " all the registered versions will be listed in ascending order.\n" ++
166 " Accepts the --simple-output flag.\n" ++
168 " $p latest pkg\n" ++
169 " Prints the highest registered version of a package.\n" ++
172 " Check the consistency of package depenencies and list broken packages.\n" ++
173 " Accepts the --simple-output flag.\n" ++
175 " $p describe {pkg-id}\n" ++
176 " Give the registered description for the specified package. The\n" ++
177 " description is returned in precisely the syntax required by $p\n" ++
180 " $p field {pkg-id} {field}\n" ++
181 " Extract the specified field of the package description for the\n" ++
182 " specified package.\n" ++
184 " The following optional flags are also accepted:\n"
186 substProg :: String -> String -> String
188 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
189 substProg prog (c:xs) = c : substProg prog xs
191 -- -----------------------------------------------------------------------------
194 data Force = ForceAll | ForceFiles | NoForce
196 runit :: [Flag] -> [String] -> IO ()
197 runit cli nonopts = do
198 prog <- getProgramName
201 | FlagForce `elem` cli = ForceAll
202 | FlagForceFiles `elem` cli = ForceFiles
203 | otherwise = NoForce
204 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
205 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
207 -- first, parse the command
209 ["register", filename] ->
210 registerPackage filename defines cli auto_ghci_libs False force
211 ["update", filename] ->
212 registerPackage filename defines cli auto_ghci_libs True force
213 ["unregister", pkgid_str] -> do
214 pkgid <- readGlobPkgId pkgid_str
215 unregisterPackage pkgid cli
216 ["expose", pkgid_str] -> do
217 pkgid <- readGlobPkgId pkgid_str
218 exposePackage pkgid cli
219 ["hide", pkgid_str] -> do
220 pkgid <- readGlobPkgId pkgid_str
221 hidePackage pkgid cli
223 listPackages cli Nothing
224 ["list", pkgid_str] -> do
225 pkgid <- readGlobPkgId pkgid_str
226 listPackages cli (Just pkgid)
227 ["latest", pkgid_str] -> do
228 pkgid <- readGlobPkgId pkgid_str
229 latestPackage cli pkgid
230 ["describe", pkgid_str] -> do
231 pkgid <- readGlobPkgId pkgid_str
232 describePackage cli pkgid
233 ["field", pkgid_str, field] -> do
234 pkgid <- readGlobPkgId pkgid_str
235 describeField cli pkgid field
239 die ("missing command\n" ++
240 usageInfo (usageHeader prog) flags)
242 die ("command-line syntax error\n" ++
243 usageInfo (usageHeader prog) flags)
245 parseCheck :: ReadP a a -> String -> String -> IO a
246 parseCheck parser str what =
247 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
249 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
251 readPkgId :: String -> IO PackageIdentifier
252 readPkgId str = parseCheck parsePackageId str "package identifier"
254 readGlobPkgId :: String -> IO PackageIdentifier
255 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
257 parseGlobPackageId :: ReadP r PackageIdentifier
261 (do n <- parsePackageName; string "-*"
262 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
264 -- globVersion means "all versions"
265 globVersion :: Version
266 globVersion = Version{ versionBranch=[], versionTags=["*"] }
268 -- -----------------------------------------------------------------------------
271 -- Some commands operate on a single database:
272 -- register, unregister, expose, hide
273 -- however these commands also check the union of the available databases
274 -- in order to check consistency. For example, register will check that
275 -- dependencies exist before registering a package.
277 -- Some commands operate on multiple databases, with overlapping semantics:
278 -- list, describe, field
280 type PackageDBName = FilePath
281 type PackageDB = [InstalledPackageInfo]
283 type PackageDBStack = [(PackageDBName,PackageDB)]
284 -- A stack of package databases. Convention: head is the topmost
285 -- in the stack. Earlier entries override later one.
287 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
288 getPkgDatabases modify flags = do
289 -- first we determine the location of the global package config. On Windows,
290 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
291 -- location is passed to the binary using the --global-config flag by the
293 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
295 case [ f | FlagGlobalConfig f <- flags ] of
296 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
298 Nothing -> die err_msg
299 Just dir -> return (dir </> "package.conf")
300 fs -> return (last fs)
302 let global_conf_dir = global_conf ++ ".d"
303 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
305 if global_conf_dir_exists
306 then do files <- getDirectoryContents global_conf_dir
307 return [ global_conf_dir ++ '/' : file
309 , isSuffixOf ".conf" file]
312 -- get the location of the user package database, and create it if necessary
313 appdir <- getAppUserDataDirectory "ghc"
316 subdir = targetARCH ++ '-':targetOS ++ '-':version
317 archdir = appdir </> subdir
318 user_conf = archdir </> "package.conf"
319 user_exists <- doesFileExist user_conf
321 -- If the user database doesn't exist, and this command isn't a
322 -- "modify" command, then we won't attempt to create or use it.
324 | modify || user_exists = user_conf : global_confs ++ [global_conf]
325 | otherwise = global_confs ++ [global_conf]
327 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
330 Left _ -> sys_databases
332 | last cs == "" -> init cs ++ sys_databases
334 where cs = splitSearchPath path
336 -- The "global" database is always the one at the bottom of the stack.
337 -- This is the database we modify by default.
338 virt_global_conf = last env_stack
340 -- -f flags on the command line add to the database stack, unless any
341 -- of them are present in the stack already.
342 let flag_stack = filter (`notElem` env_stack)
343 [ f | FlagConfig f <- reverse flags ] ++ env_stack
345 -- Now we have the full stack of databases. Next, if the current
346 -- command is a "modify" type command, then we truncate the stack
347 -- so that the topmost element is the database being modified.
350 then return flag_stack
352 go (FlagUser : fs) = modifying user_conf
353 go (FlagGlobal : fs) = modifying virt_global_conf
354 go (FlagConfig f : fs) = modifying f
356 go [] = modifying virt_global_conf
359 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
360 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
364 db_stack <- mapM readParseDatabase final_stack
367 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
368 readParseDatabase filename = do
369 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
370 let packages = read str
371 Exception.evaluate packages
372 `Exception.catch` \_ ->
373 die (filename ++ ": parse error in package config file")
374 return (filename,packages)
376 emptyPackageConfig :: String
377 emptyPackageConfig = "[]"
379 -- -----------------------------------------------------------------------------
382 registerPackage :: FilePath
383 -> [(String,String)] -- defines
385 -> Bool -- auto_ghci_libs
389 registerPackage input defines flags auto_ghci_libs update force = do
390 db_stack <- getPkgDatabases True flags
392 db_to_operate_on = my_head "db" db_stack
393 db_filename = fst db_to_operate_on
399 putStr "Reading package info from stdin ... "
402 putStr ("Reading package info from " ++ show f ++ " ... ")
405 expanded <- expandEnvVars s defines force
407 pkg0 <- parsePackageInfo expanded defines
410 let pkg = resolveDeps db_stack pkg0
411 validatePackageConfig pkg db_stack auto_ghci_libs update force
412 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
413 not_this p = package p /= package pkg
414 savingOldConfig db_filename $
415 writeNewConfig db_filename new_details
420 -> IO InstalledPackageInfo
421 parsePackageInfo str defines =
422 case parseInstalledPackageInfo str of
423 ParseOk _warns ok -> return ok
424 ParseFailed err -> case locatedErrorMsg err of
425 (Nothing, s) -> die s
426 (Just l, s) -> die (show l ++ ": " ++ s)
428 -- -----------------------------------------------------------------------------
429 -- Exposing, Hiding, Unregistering are all similar
431 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
432 exposePackage = modifyPackage (\p -> [p{exposed=True}])
434 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
435 hidePackage = modifyPackage (\p -> [p{exposed=False}])
437 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
438 unregisterPackage = modifyPackage (\p -> [])
441 :: (InstalledPackageInfo -> [InstalledPackageInfo])
445 modifyPackage fn pkgid flags = do
446 db_stack <- getPkgDatabases True{-modify-} flags
447 let ((db_name, pkgs) : _) = db_stack
448 ps <- findPackages [(db_name,pkgs)] pkgid
449 let pids = map package ps
450 let new_config = concat (map modify pkgs)
452 | package pkg `elem` pids = fn pkg
454 savingOldConfig db_name $
455 writeNewConfig db_name new_config
457 -- -----------------------------------------------------------------------------
460 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
461 listPackages flags mPackageName = do
462 let simple_output = FlagSimpleOutput `elem` flags
463 db_stack <- getPkgDatabases False flags
464 let db_stack_filtered -- if a package is given, filter out all other packages
465 | Just this <- mPackageName =
466 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
468 | otherwise = db_stack
471 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
472 where sort_pkgs = sortBy cmpPkgIds
473 cmpPkgIds pkg1 pkg2 =
474 case pkgName p1 `compare` pkgName p2 of
477 EQ -> pkgVersion p1 `compare` pkgVersion p2
478 where (p1,p2) = (package pkg1, package pkg2)
480 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
481 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
483 show_func (reverse db_stack_sorted)
485 where show_normal pkg_map (db_name,pkg_confs) =
486 hPutStrLn stdout (render $
487 text db_name <> colon $$ nest 4 packages
489 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
491 | isBrokenPackage p pkg_map = braces doc
493 | otherwise = parens doc
494 where doc = text (showPackageId (package p))
496 show_simple db_stack = do
497 let showPkg = if FlagNamesOnly `elem` flags then pkgName
499 pkgs = map showPkg $ sortBy compPkgIdVer $
500 map package (concatMap snd db_stack)
501 when (null pkgs) $ die "no matches"
502 hPutStrLn stdout $ concat $ intersperse " " pkgs
504 -- -----------------------------------------------------------------------------
505 -- Prints the highest (hidden or exposed) version of a package
507 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
508 latestPackage flags pkgid = do
509 db_stack <- getPkgDatabases False flags
510 ps <- findPackages db_stack pkgid
511 show_pkg (sortBy compPkgIdVer (map package ps))
513 show_pkg [] = die "no matches"
514 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
516 -- -----------------------------------------------------------------------------
519 describePackage :: [Flag] -> PackageIdentifier -> IO ()
520 describePackage flags pkgid = do
521 db_stack <- getPkgDatabases False flags
522 ps <- findPackages db_stack pkgid
523 mapM_ (putStrLn . showInstalledPackageInfo) ps
525 -- PackageId is can have globVersion for the version
526 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
527 findPackages db_stack pkgid
528 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
529 [] -> die ("cannot find package " ++ showPackageId pkgid)
532 all_pkgs = concat (map snd db_stack)
534 matches :: PackageIdentifier -> PackageIdentifier -> Bool
536 = (pkgName pid == pkgName pid')
537 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
539 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
540 pid `matchesPkg` pkg = pid `matches` package pkg
542 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
543 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
545 -- -----------------------------------------------------------------------------
548 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
549 describeField flags pkgid field = do
550 db_stack <- getPkgDatabases False flags
551 case toField field of
552 Nothing -> die ("unknown field: " ++ field)
554 ps <- findPackages db_stack pkgid
555 let top_dir = takeDirectory (fst (last db_stack))
556 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
558 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
559 -- Replace the string "$topdir" at the beginning of a path
560 -- with the current topdir (obtained from the -B option).
561 mungePackagePaths top_dir ps = map munge_pkg ps
563 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
564 includeDirs = munge_paths (includeDirs p),
565 libraryDirs = munge_paths (libraryDirs p),
566 frameworkDirs = munge_paths (frameworkDirs p),
567 haddockInterfaces = munge_paths (haddockInterfaces p),
568 haddockHTMLs = munge_paths (haddockHTMLs p)
571 munge_paths = map munge_path
574 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
577 maybePrefixMatch :: String -> String -> Maybe String
578 maybePrefixMatch [] rest = Just rest
579 maybePrefixMatch (_:_) [] = Nothing
580 maybePrefixMatch (p:pat) (r:rest)
581 | p == r = maybePrefixMatch pat rest
582 | otherwise = Nothing
584 toField :: String -> Maybe (InstalledPackageInfo -> String)
585 -- backwards compatibility:
586 toField "import_dirs" = Just $ strList . importDirs
587 toField "source_dirs" = Just $ strList . importDirs
588 toField "library_dirs" = Just $ strList . libraryDirs
589 toField "hs_libraries" = Just $ strList . hsLibraries
590 toField "extra_libraries" = Just $ strList . extraLibraries
591 toField "include_dirs" = Just $ strList . includeDirs
592 toField "c_includes" = Just $ strList . includes
593 toField "package_deps" = Just $ strList . map showPackageId. depends
594 toField "extra_cc_opts" = Just $ strList . ccOptions
595 toField "extra_ld_opts" = Just $ strList . ldOptions
596 toField "framework_dirs" = Just $ strList . frameworkDirs
597 toField "extra_frameworks"= Just $ strList . frameworks
598 toField s = showInstalledPackageInfoField s
600 strList :: [String] -> String
604 -- -----------------------------------------------------------------------------
605 -- Check: Check consistency of installed packages
607 checkConsistency :: [Flag] -> IO ()
608 checkConsistency flags = do
609 db_stack <- getPkgDatabases False flags
610 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
613 let broken_deps = missingPackageDeps p pkgs
614 guard (not . null $ broken_deps)
615 return (pid, broken_deps)
616 mapM_ (putStrLn . render . show_func) broken_pkgs
618 show_func | FlagSimpleOutput `elem` flags = show_simple
619 | otherwise = show_normal
620 show_simple (pid,deps) =
621 text (showPackageId pid) <> colon
622 <+> fsep (punctuate comma (map (text . showPackageId) deps))
623 show_normal (pid,deps) =
624 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
625 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
627 missingPackageDeps :: InstalledPackageInfo
628 -> [(PackageIdentifier, InstalledPackageInfo)]
629 -> [PackageIdentifier]
630 missingPackageDeps pkg pkg_map =
631 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
632 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
634 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
635 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
638 -- -----------------------------------------------------------------------------
639 -- Manipulating package.conf files
641 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
642 writeNewConfig filename packages = do
643 hPutStr stdout "Writing new package config file... "
644 createDirectoryIfMissing True $ takeDirectory filename
645 h <- openFile filename WriteMode `catch` \e ->
646 if isPermissionError e
647 then die (filename ++ ": you don't have permission to modify this file")
649 let shown = concat $ intersperse ",\n " $ map show packages
650 fileContents = "[" ++ shown ++ "\n]"
651 hPutStrLn h fileContents
653 hPutStrLn stdout "done."
655 savingOldConfig :: FilePath -> IO () -> IO ()
656 savingOldConfig filename io = Exception.block $ do
657 hPutStr stdout "Saving old package config file... "
658 -- mv rather than cp because we've already done an hGetContents
659 -- on this file so we won't be able to open it for writing
660 -- unless we move the old one out of the way...
661 let oldFile = filename ++ ".old"
662 restore_on_error <- catch (renameFile filename oldFile >> return True) $
664 unless (isDoesNotExistError err) $ do
665 hPutStrLn stderr (unwords ["Unable to rename", show filename,
669 hPutStrLn stdout "done."
671 hPutStrLn stderr (show e)
672 hPutStr stdout ("\nWARNING: an error was encountered while writing"
673 ++ "the new configuration.\n")
674 when restore_on_error $ do
675 hPutStr stdout "Attempting to restore the old configuration..."
676 do renameFile oldFile filename
677 hPutStrLn stdout "done."
678 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
681 -----------------------------------------------------------------------------
682 -- Sanity-check a new package config, and automatically build GHCi libs
685 validatePackageConfig :: InstalledPackageInfo
687 -> Bool -- auto-ghc-libs
691 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
693 checkDuplicates db_stack pkg update
694 mapM_ (checkDep db_stack force) (depends pkg)
695 mapM_ (checkDir force) (importDirs pkg)
696 mapM_ (checkDir force) (libraryDirs pkg)
697 mapM_ (checkDir force) (includeDirs pkg)
698 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
699 -- ToDo: check these somehow?
700 -- extra_libraries :: [String],
701 -- c_includes :: [String],
703 -- When the package name and version are put together, sometimes we can
704 -- end up with a package id that cannot be parsed. This will lead to
705 -- difficulties when the user wants to refer to the package later, so
706 -- we check that the package id can be parsed properly here.
707 checkPackageId :: InstalledPackageInfo -> IO ()
709 let str = showPackageId (package ipi) in
710 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
712 [] -> die ("invalid package identifier: " ++ str)
713 _ -> die ("ambiguous package identifier: " ++ str)
715 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
716 resolveDeps db_stack p = updateDeps p
718 -- The input package spec is allowed to give a package dependency
719 -- without a version number; e.g.
721 -- Here, we update these dependencies without version numbers to
722 -- match the actual versions of the relevant packages installed.
723 updateDeps p = p{depends = map resolveDep (depends p)}
726 | realVersion dep_pkgid = dep_pkgid
727 | otherwise = lookupDep dep_pkgid
731 name = pkgName dep_pkgid
733 case [ pid | p <- concat (map snd db_stack),
735 pkgName pid == name ] of
736 (pid:_) -> pid -- Found installed package,
737 -- replete with its version
738 [] -> dep_pkgid -- No installed package; use
739 -- the version-less one
741 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
742 checkDuplicates db_stack pkg update = do
745 (_top_db_name, pkgs) : _ = db_stack
747 -- Check whether this package id already exists in this DB
749 when (not update && (pkgid `elem` map package pkgs)) $
750 die ("package " ++ showPackageId pkgid ++ " is already installed")
754 checkDir :: Force -> String -> IO ()
756 | "$topdir" `isPrefixOf` d = return ()
757 -- can't check this, because we don't know what $topdir is
759 there <- doesDirectoryExist d
761 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
763 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
764 checkDep db_stack force pkgid
765 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
766 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
769 -- for backwards compat, we treat 0.0 as a special version,
770 -- and don't check that it actually exists.
771 real_version = realVersion pkgid
773 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
776 all_pkgs = concat (map snd db_stack)
777 pkgids = map package all_pkgs
779 realVersion :: PackageIdentifier -> Bool
780 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
782 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
783 checkHSLib dirs auto_ghci_libs force lib = do
784 let batch_lib_file = "lib" ++ lib ++ ".a"
785 bs <- mapM (doesLibExistIn batch_lib_file) dirs
786 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
787 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
789 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
791 doesLibExistIn :: String -> String -> IO Bool
793 | "$topdir" `isPrefixOf` d = return True
794 | otherwise = doesFileExist (d ++ '/':lib)
796 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
797 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
798 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
800 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
801 case [dir | (exists,dir) <- zip bs dirs, exists] of
802 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
805 ghci_lib_file = lib ++ ".o"
807 -- automatically build the GHCi version of a batch lib,
808 -- using ld --whole-archive.
810 autoBuildGHCiLib :: String -> String -> String -> IO ()
811 autoBuildGHCiLib dir batch_file ghci_file = do
812 let ghci_lib_file = dir ++ '/':ghci_file
813 batch_lib_file = dir ++ '/':batch_file
814 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
815 #if defined(darwin_HOST_OS)
816 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
817 #elif defined(mingw32_HOST_OS)
818 execDir <- getExecDir "/bin/ghc-pkg.exe"
819 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
821 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
823 when (r /= ExitSuccess) $ exitWith r
824 hPutStrLn stderr (" done.")
826 -- -----------------------------------------------------------------------------
827 -- Searching for modules
831 findModules :: [FilePath] -> IO [String]
833 mms <- mapM searchDir paths
836 searchDir path prefix = do
837 fs <- getDirectoryEntries path `catch` \_ -> return []
838 searchEntries path prefix fs
840 searchEntries path prefix [] = return []
841 searchEntries path prefix (f:fs)
842 | looks_like_a_module = do
843 ms <- searchEntries path prefix fs
844 return (prefix `joinModule` f : ms)
845 | looks_like_a_component = do
846 ms <- searchDir (path </> f) (prefix `joinModule` f)
847 ms' <- searchEntries path prefix fs
850 searchEntries path prefix fs
853 (base,suffix) = splitFileExt f
854 looks_like_a_module =
855 suffix `elem` haskell_suffixes &&
856 all okInModuleName base
857 looks_like_a_component =
858 null suffix && all okInModuleName base
864 -- -----------------------------------------------------------------------------
865 -- The old command-line syntax, supported for backwards compatibility
872 | OF_Add Bool {- True => replace existing info -}
873 | OF_Remove String | OF_Show String
874 | OF_Field String | OF_AutoGHCiLibs | OF_Force
875 | OF_DefinedName String String
876 | OF_GlobalConfig FilePath
879 isAction :: OldFlag -> Bool
880 isAction OF_Config{} = False
881 isAction OF_Field{} = False
882 isAction OF_Input{} = False
883 isAction OF_AutoGHCiLibs{} = False
884 isAction OF_Force{} = False
885 isAction OF_DefinedName{} = False
886 isAction OF_GlobalConfig{} = False
889 oldFlags :: [OptDescr OldFlag]
891 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
892 "use the specified package config file",
893 Option ['l'] ["list-packages"] (NoArg OF_List)
894 "list packages in all config files",
895 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
896 "list packages in the specified config file",
897 Option ['a'] ["add-package"] (NoArg (OF_Add False))
899 Option ['u'] ["update-package"] (NoArg (OF_Add True))
900 "update package with new configuration",
901 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
902 "read new package info from specified file",
903 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
904 "show the configuration for package NAME",
905 Option [] ["field"] (ReqArg OF_Field "FIELD")
906 "(with --show-package) Show field FIELD only",
907 Option [] ["force"] (NoArg OF_Force)
908 "ignore missing directories/libraries",
909 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
910 "remove an installed package",
911 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
912 "automatically build libs for GHCi (with -a)",
913 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
914 "define NAME as VALUE",
915 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
916 "location of the global package config"
920 case break (=='=') str of
921 (nm,[]) -> OF_DefinedName nm []
922 (nm,_:val) -> OF_DefinedName nm val
924 oldRunit :: [OldFlag] -> IO ()
926 let new_flags = [ f | Just f <- map conv clis ]
928 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
929 conv (OF_Config f) = Just (FlagConfig f)
934 let fields = [ f | OF_Field f <- clis ]
936 let auto_ghci_libs = any isAuto clis
937 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
938 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
940 force = if OF_Force `elem` clis then ForceAll else NoForce
942 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
944 case [ c | c <- clis, isAction c ] of
945 [ OF_List ] -> listPackages new_flags Nothing
946 [ OF_ListLocal ] -> listPackages new_flags Nothing
948 registerPackage input_file defines new_flags auto_ghci_libs upd force
949 [ OF_Remove pkgid_str ] -> do
950 pkgid <- readPkgId pkgid_str
951 unregisterPackage pkgid new_flags
952 [ OF_Show pkgid_str ]
954 pkgid <- readPkgId pkgid_str
955 describePackage new_flags pkgid
957 pkgid <- readPkgId pkgid_str
958 mapM_ (describeField new_flags pkgid) fields
960 prog <- getProgramName
961 die (usageInfo (usageHeader prog) flags)
963 my_head :: String -> [a] -> a
964 my_head s [] = error s
967 -- ---------------------------------------------------------------------------
968 -- expanding environment variables in the package configuration
970 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
971 expandEnvVars str defines force = go str ""
973 go "" acc = return $! reverse acc
974 go ('$':'{':str) acc | (var, '}':rest) <- break close str
975 = do value <- lookupEnvVar var
976 go rest (reverse value ++ acc)
977 where close c = c == '}' || c == '\n' -- don't span newlines
981 lookupEnvVar :: String -> IO String
983 case lookup nm defines of
984 Just x | not (null x) -> return x
986 catch (System.getEnv nm)
987 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
991 -----------------------------------------------------------------------------
993 getProgramName :: IO String
994 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
995 where str `withoutSuffix` suff
996 | suff `isSuffixOf` str = take (length str - length suff) str
999 bye :: String -> IO a
1000 bye s = putStr s >> exitWith ExitSuccess
1002 die :: String -> IO a
1005 prog <- getProgramName
1006 hPutStrLn stderr (prog ++ ": " ++ s)
1007 exitWith (ExitFailure 1)
1009 dieOrForceAll :: Force -> String -> IO ()
1010 dieOrForceAll ForceAll s = ignoreError s
1011 dieOrForceAll _other s = dieForcible s
1013 dieOrForceFile :: Force -> String -> IO ()
1014 dieOrForceFile ForceAll s = ignoreError s
1015 dieOrForceFile ForceFiles s = ignoreError s
1016 dieOrForceFile _other s = dieForcible s
1018 ignoreError :: String -> IO ()
1019 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1021 dieForcible :: String -> IO ()
1022 dieForcible s = die (s ++ " (use --force to override)")
1024 -----------------------------------------
1025 -- Cut and pasted from ghc/compiler/SysTools
1027 #if defined(mingw32_HOST_OS)
1028 subst :: Char -> Char -> String -> String
1029 subst a b ls = map (\ x -> if x == a then b else x) ls
1031 unDosifyPath :: FilePath -> FilePath
1032 unDosifyPath xs = subst '\\' '/' xs
1034 getExecDir :: String -> IO (Maybe String)
1035 -- (getExecDir cmd) returns the directory in which the current
1036 -- executable, which should be called 'cmd', is running
1037 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1038 -- you'll get "/a/b/c" back as the result
1040 = allocaArray len $ \buf -> do
1041 ret <- getModuleFileName nullPtr buf len
1042 if ret == 0 then return Nothing
1043 else do s <- peekCString buf
1044 return (Just (reverse (drop (length cmd)
1045 (reverse (unDosifyPath s)))))
1047 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1049 foreign import stdcall unsafe "GetModuleFileNameA"
1050 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1052 getExecDir :: String -> IO (Maybe String)
1053 getExecDir _ = return Nothing