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
26 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
27 import Compat.RawSystem ( rawSystem )
29 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
30 import System.Cmd ( rawSystem )
35 #include "../../includes/ghcconfig.h"
37 import System.Console.GetOpt
38 import Text.PrettyPrint
39 import qualified Control.Exception as Exception
41 import Data.Char ( isSpace )
44 import System ( getArgs, getProgName, getEnv,
45 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
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 [] ["force-files"] (NoArg FlagForceFiles)
117 "ignore missing directories and libraries only",
118 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
119 "automatically build libs for GHCi (with register)",
120 Option ['?'] ["help"] (NoArg FlagHelp)
121 "display this help and exit",
122 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
123 "define NAME as VALUE",
124 Option ['V'] ["version"] (NoArg FlagVersion)
125 "output version information and exit",
126 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
127 "print output in easy-to-parse format for some commands"
131 case break (=='=') str of
132 (nm,[]) -> FlagDefinedName nm []
133 (nm,_:val) -> FlagDefinedName nm val
135 ourCopyright :: String
136 ourCopyright = "GHC package manager version " ++ version ++ "\n"
138 usageHeader :: String -> String
139 usageHeader prog = substProg prog $
141 " $p register {filename | -}\n" ++
142 " Register the package using the specified installed package\n" ++
143 " description. The syntax for the latter is given in the $p\n" ++
144 " documentation.\n" ++
146 " $p update {filename | -}\n" ++
147 " Register the package, overwriting any other package with the\n" ++
150 " $p unregister {pkg-id}\n" ++
151 " Unregister the specified package.\n" ++
153 " $p expose {pkg-id}\n" ++
154 " Expose the specified package.\n" ++
156 " $p hide {pkg-id}\n" ++
157 " Hide the specified package.\n" ++
159 " $p list [pkg]\n" ++
160 " List registered packages in the global database, and also the\n" ++
161 " user database if --user is given. If a package name is given\n" ++
162 " all the registered versions will be listed in ascending order.\n" ++
163 " Accepts the --simple-output flag.\n" ++
165 " $p latest pkg\n" ++
166 " Prints the highest registered version of a package.\n" ++
169 " Check the consistency of package depenencies and list broken packages.\n" ++
170 " Accepts the --simple-output flag.\n" ++
172 " $p describe {pkg-id}\n" ++
173 " Give the registered description for the specified package. The\n" ++
174 " description is returned in precisely the syntax required by $p\n" ++
177 " $p field {pkg-id} {field}\n" ++
178 " Extract the specified field of the package description for the\n" ++
179 " specified package.\n" ++
181 " The following optional flags are also accepted:\n"
183 substProg :: String -> String -> String
185 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
186 substProg prog (c:xs) = c : substProg prog xs
188 -- -----------------------------------------------------------------------------
191 data Force = ForceAll | ForceFiles | NoForce
193 runit :: [Flag] -> [String] -> IO ()
194 runit cli nonopts = do
195 prog <- getProgramName
198 | FlagForce `elem` cli = ForceAll
199 | FlagForceFiles `elem` cli = ForceFiles
200 | otherwise = NoForce
201 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
202 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
204 -- first, parse the command
206 ["register", filename] ->
207 registerPackage filename defines cli auto_ghci_libs False force
208 ["update", filename] ->
209 registerPackage filename defines cli auto_ghci_libs True force
210 ["unregister", pkgid_str] -> do
211 pkgid <- readGlobPkgId pkgid_str
212 unregisterPackage pkgid cli
213 ["expose", pkgid_str] -> do
214 pkgid <- readGlobPkgId pkgid_str
215 exposePackage pkgid cli
216 ["hide", pkgid_str] -> do
217 pkgid <- readGlobPkgId pkgid_str
218 hidePackage pkgid cli
220 listPackages cli Nothing
221 ["list", pkgid_str] -> do
222 pkgid <- readGlobPkgId pkgid_str
223 listPackages cli (Just pkgid)
224 ["latest", pkgid_str] -> do
225 pkgid <- readGlobPkgId pkgid_str
226 latestPackage cli pkgid
227 ["describe", pkgid_str] -> do
228 pkgid <- readGlobPkgId pkgid_str
229 describePackage cli pkgid
230 ["field", pkgid_str, field] -> do
231 pkgid <- readGlobPkgId pkgid_str
232 describeField cli pkgid field
236 die ("missing command\n" ++
237 usageInfo (usageHeader prog) flags)
239 die ("command-line syntax error\n" ++
240 usageInfo (usageHeader prog) flags)
242 parseCheck :: ReadP a a -> String -> String -> IO a
243 parseCheck parser str what =
244 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
246 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
248 readPkgId :: String -> IO PackageIdentifier
249 readPkgId str = parseCheck parsePackageId str "package identifier"
251 readGlobPkgId :: String -> IO PackageIdentifier
252 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
254 parseGlobPackageId :: ReadP r PackageIdentifier
258 (do n <- parsePackageName; string "-*"
259 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
261 -- globVersion means "all versions"
262 globVersion :: Version
263 globVersion = Version{ versionBranch=[], versionTags=["*"] }
265 -- -----------------------------------------------------------------------------
268 -- Some commands operate on a single database:
269 -- register, unregister, expose, hide
270 -- however these commands also check the union of the available databases
271 -- in order to check consistency. For example, register will check that
272 -- dependencies exist before registering a package.
274 -- Some commands operate on multiple databases, with overlapping semantics:
275 -- list, describe, field
277 type PackageDBName = FilePath
278 type PackageDB = [InstalledPackageInfo]
280 type PackageDBStack = [(PackageDBName,PackageDB)]
281 -- A stack of package databases. Convention: head is the topmost
282 -- in the stack. Earlier entries override later one.
284 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
285 getPkgDatabases modify flags = do
286 -- first we determine the location of the global package config. On Windows,
287 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
288 -- location is passed to the binary using the --global-config flag by the
290 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
292 case [ f | FlagGlobalConfig f <- flags ] of
293 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
295 Nothing -> die err_msg
296 Just dir -> return (dir `joinFileName` "package.conf")
297 fs -> return (last fs)
299 let global_conf_dir = global_conf ++ ".d"
300 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
302 if global_conf_dir_exists
303 then do files <- getDirectoryContents global_conf_dir
304 return [ global_conf_dir ++ '/' : file
306 , isSuffixOf ".conf" file]
309 -- get the location of the user package database, and create it if necessary
310 appdir <- getAppUserDataDirectory "ghc"
313 subdir = targetARCH ++ '-':targetOS ++ '-':version
314 archdir = appdir `joinFileName` subdir
315 user_conf = archdir `joinFileName` "package.conf"
316 user_exists <- doesFileExist user_conf
318 -- If the user database doesn't exist, and this command isn't a
319 -- "modify" command, then we won't attempt to create or use it.
321 | modify || user_exists = user_conf : global_confs ++ [global_conf]
322 | otherwise = global_confs ++ [global_conf]
324 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
327 Left _ -> sys_databases
329 | last cs == "" -> init cs ++ sys_databases
331 where cs = parseSearchPath path
333 -- The "global" database is always the one at the bottom of the stack.
334 -- This is the database we modify by default.
335 virt_global_conf = last env_stack
337 -- -f flags on the command line add to the database stack, unless any
338 -- of them are present in the stack already.
339 let flag_stack = filter (`notElem` env_stack)
340 [ f | FlagConfig f <- reverse flags ] ++ env_stack
342 -- Now we have the full stack of databases. Next, if the current
343 -- command is a "modify" type command, then we truncate the stack
344 -- so that the topmost element is the database being modified.
347 then return flag_stack
349 go (FlagUser : fs) = modifying user_conf
350 go (FlagGlobal : fs) = modifying virt_global_conf
351 go (FlagConfig f : fs) = modifying f
353 go [] = modifying virt_global_conf
356 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
357 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
361 db_stack <- mapM readParseDatabase final_stack
364 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
365 readParseDatabase filename = do
366 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
367 let packages = read str
368 Exception.evaluate packages
369 `Exception.catch` \_ ->
370 die (filename ++ ": parse error in package config file")
371 return (filename,packages)
373 emptyPackageConfig :: String
374 emptyPackageConfig = "[]"
376 -- -----------------------------------------------------------------------------
379 registerPackage :: FilePath
380 -> [(String,String)] -- defines
382 -> Bool -- auto_ghci_libs
386 registerPackage input defines flags auto_ghci_libs update force = do
387 db_stack <- getPkgDatabases True flags
389 db_to_operate_on = my_head "db" db_stack
390 db_filename = fst db_to_operate_on
396 putStr "Reading package info from stdin ... "
399 putStr ("Reading package info from " ++ show f ++ " ... ")
402 expanded <- expandEnvVars s defines force
404 pkg0 <- parsePackageInfo expanded defines
407 let pkg = resolveDeps db_stack pkg0
408 validatePackageConfig pkg db_stack auto_ghci_libs update force
409 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
410 not_this p = package p /= package pkg
411 savingOldConfig db_filename $
412 writeNewConfig db_filename new_details
417 -> IO InstalledPackageInfo
418 parsePackageInfo str defines =
419 case parseInstalledPackageInfo str of
420 ParseOk _warns ok -> return ok
421 ParseFailed err -> case locatedErrorMsg err of
422 (Nothing, s) -> die s
423 (Just l, s) -> die (show l ++ ": " ++ s)
425 -- -----------------------------------------------------------------------------
426 -- Exposing, Hiding, Unregistering are all similar
428 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
429 exposePackage = modifyPackage (\p -> [p{exposed=True}])
431 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
432 hidePackage = modifyPackage (\p -> [p{exposed=False}])
434 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
435 unregisterPackage = modifyPackage (\p -> [])
438 :: (InstalledPackageInfo -> [InstalledPackageInfo])
442 modifyPackage fn pkgid flags = do
443 db_stack <- getPkgDatabases True{-modify-} flags
444 let ((db_name, pkgs) : _) = db_stack
445 ps <- findPackages [(db_name,pkgs)] pkgid
446 let pids = map package ps
447 let new_config = concat (map modify pkgs)
449 | package pkg `elem` pids = fn pkg
451 savingOldConfig db_name $
452 writeNewConfig db_name new_config
454 -- -----------------------------------------------------------------------------
457 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
458 listPackages flags mPackageName = do
459 let simple_output = FlagSimpleOutput `elem` flags
460 db_stack <- getPkgDatabases False flags
461 let db_stack_filtered -- if a package is given, filter out all other packages
462 | Just this <- mPackageName =
463 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
465 | otherwise = db_stack
468 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
469 where sort_pkgs = sortBy cmpPkgIds
470 cmpPkgIds pkg1 pkg2 =
471 case pkgName p1 `compare` pkgName p2 of
474 EQ -> pkgVersion p1 `compare` pkgVersion p2
475 where (p1,p2) = (package pkg1, package pkg2)
477 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
478 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
480 show_func (reverse db_stack_sorted)
482 where show_normal pkg_map (db_name,pkg_confs) =
483 hPutStrLn stdout (render $
484 text db_name <> colon $$ nest 4 packages
486 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
488 | isBrokenPackage p pkg_map = braces doc
490 | otherwise = parens doc
491 where doc = text (showPackageId (package p))
493 show_simple db_stack = do
494 let pkgs = map showPackageId $ sortBy compPkgIdVer $
495 map package (concatMap snd db_stack)
496 when (null pkgs) $ die "no matches"
497 hPutStrLn stdout $ concat $ intersperse " " pkgs
499 -- -----------------------------------------------------------------------------
500 -- Prints the highest (hidden or exposed) version of a package
502 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
503 latestPackage flags pkgid = do
504 db_stack <- getPkgDatabases False flags
505 ps <- findPackages db_stack pkgid
506 show_pkg (sortBy compPkgIdVer (map package ps))
508 show_pkg [] = die "no matches"
509 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
511 -- -----------------------------------------------------------------------------
514 describePackage :: [Flag] -> PackageIdentifier -> IO ()
515 describePackage flags pkgid = do
516 db_stack <- getPkgDatabases False flags
517 ps <- findPackages db_stack pkgid
518 mapM_ (putStrLn . showInstalledPackageInfo) ps
520 -- PackageId is can have globVersion for the version
521 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
522 findPackages db_stack pkgid
523 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
524 [] -> die ("cannot find package " ++ showPackageId pkgid)
527 all_pkgs = concat (map snd db_stack)
529 matches :: PackageIdentifier -> PackageIdentifier -> Bool
531 = (pkgName pid == pkgName pid')
532 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
534 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
535 pid `matchesPkg` pkg = pid `matches` package pkg
537 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
538 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
540 -- -----------------------------------------------------------------------------
543 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
544 describeField flags pkgid field = do
545 db_stack <- getPkgDatabases False flags
546 case toField field of
547 Nothing -> die ("unknown field: " ++ field)
549 ps <- findPackages db_stack pkgid
550 let top_dir = getFilenameDir (fst (last db_stack))
551 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
553 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
554 -- Replace the string "$topdir" at the beginning of a path
555 -- with the current topdir (obtained from the -B option).
556 mungePackagePaths top_dir ps = map munge_pkg ps
558 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
559 includeDirs = munge_paths (includeDirs p),
560 libraryDirs = munge_paths (libraryDirs p),
561 frameworkDirs = munge_paths (frameworkDirs p),
562 haddockInterfaces = munge_paths (haddockInterfaces p),
563 haddockHTMLs = munge_paths (haddockHTMLs p)
566 munge_paths = map munge_path
569 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
572 maybePrefixMatch :: String -> String -> Maybe String
573 maybePrefixMatch [] rest = Just rest
574 maybePrefixMatch (_:_) [] = Nothing
575 maybePrefixMatch (p:pat) (r:rest)
576 | p == r = maybePrefixMatch pat rest
577 | otherwise = Nothing
579 toField :: String -> Maybe (InstalledPackageInfo -> String)
580 -- backwards compatibility:
581 toField "import_dirs" = Just $ strList . importDirs
582 toField "source_dirs" = Just $ strList . importDirs
583 toField "library_dirs" = Just $ strList . libraryDirs
584 toField "hs_libraries" = Just $ strList . hsLibraries
585 toField "extra_libraries" = Just $ strList . extraLibraries
586 toField "include_dirs" = Just $ strList . includeDirs
587 toField "c_includes" = Just $ strList . includes
588 toField "package_deps" = Just $ strList . map showPackageId. depends
589 toField "extra_cc_opts" = Just $ strList . ccOptions
590 toField "extra_ld_opts" = Just $ strList . ldOptions
591 toField "framework_dirs" = Just $ strList . frameworkDirs
592 toField "extra_frameworks"= Just $ strList . frameworks
593 toField s = showInstalledPackageInfoField s
595 strList :: [String] -> String
599 -- -----------------------------------------------------------------------------
600 -- Check: Check consistency of installed packages
602 checkConsistency :: [Flag] -> IO ()
603 checkConsistency flags = do
604 db_stack <- getPkgDatabases False flags
605 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
608 let broken_deps = missingPackageDeps p pkgs
609 guard (not . null $ broken_deps)
610 return (pid, broken_deps)
611 mapM_ (putStrLn . render . show_func) broken_pkgs
613 show_func | FlagSimpleOutput `elem` flags = show_simple
614 | otherwise = show_normal
615 show_simple (pid,deps) =
616 text (showPackageId pid) <> colon
617 <+> fsep (punctuate comma (map (text . showPackageId) deps))
618 show_normal (pid,deps) =
619 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
620 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
622 missingPackageDeps :: InstalledPackageInfo
623 -> [(PackageIdentifier, InstalledPackageInfo)]
624 -> [PackageIdentifier]
625 missingPackageDeps pkg pkg_map =
626 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
627 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
629 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
630 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
633 -- -----------------------------------------------------------------------------
634 -- Manipulating package.conf files
636 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
637 writeNewConfig filename packages = do
638 hPutStr stdout "Writing new package config file... "
639 createDirectoryIfMissing True $ getFilenameDir filename
640 h <- openFile filename WriteMode `catch` \e ->
641 if isPermissionError e
642 then die (filename ++ ": you don't have permission to modify this file")
644 hPutStrLn h (show packages)
646 hPutStrLn stdout "done."
648 savingOldConfig :: FilePath -> IO () -> IO ()
649 savingOldConfig filename io = Exception.block $ do
650 hPutStr stdout "Saving old package config file... "
651 -- mv rather than cp because we've already done an hGetContents
652 -- on this file so we won't be able to open it for writing
653 -- unless we move the old one out of the way...
654 let oldFile = filename ++ ".old"
655 restore_on_error <- catch (renameFile filename oldFile >> return True) $
657 unless (isDoesNotExistError err) $ do
658 hPutStrLn stderr (unwords ["Unable to rename", show filename,
662 hPutStrLn stdout "done."
664 hPutStrLn stderr (show e)
665 hPutStr stdout ("\nWARNING: an error was encountered while writing"
666 ++ "the new configuration.\n")
667 when restore_on_error $ do
668 hPutStr stdout "Attempting to restore the old configuration..."
669 do renameFile oldFile filename
670 hPutStrLn stdout "done."
671 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
674 -----------------------------------------------------------------------------
675 -- Sanity-check a new package config, and automatically build GHCi libs
678 validatePackageConfig :: InstalledPackageInfo
680 -> Bool -- auto-ghc-libs
684 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
686 checkDuplicates db_stack pkg update
687 mapM_ (checkDep db_stack force) (depends pkg)
688 mapM_ (checkDir force) (importDirs pkg)
689 mapM_ (checkDir force) (libraryDirs pkg)
690 mapM_ (checkDir force) (includeDirs pkg)
691 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
692 -- ToDo: check these somehow?
693 -- extra_libraries :: [String],
694 -- c_includes :: [String],
696 -- When the package name and version are put together, sometimes we can
697 -- end up with a package id that cannot be parsed. This will lead to
698 -- difficulties when the user wants to refer to the package later, so
699 -- we check that the package id can be parsed properly here.
700 checkPackageId :: InstalledPackageInfo -> IO ()
702 let str = showPackageId (package ipi) in
703 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
705 [] -> die ("invalid package identifier: " ++ str)
706 _ -> die ("ambiguous package identifier: " ++ str)
708 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
709 resolveDeps db_stack p = updateDeps p
711 -- The input package spec is allowed to give a package dependency
712 -- without a version number; e.g.
714 -- Here, we update these dependencies without version numbers to
715 -- match the actual versions of the relevant packages installed.
716 updateDeps p = p{depends = map resolveDep (depends p)}
719 | realVersion dep_pkgid = dep_pkgid
720 | otherwise = lookupDep dep_pkgid
724 name = pkgName dep_pkgid
726 case [ pid | p <- concat (map snd db_stack),
728 pkgName pid == name ] of
729 (pid:_) -> pid -- Found installed package,
730 -- replete with its version
731 [] -> dep_pkgid -- No installed package; use
732 -- the version-less one
734 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
735 checkDuplicates db_stack pkg update = do
738 (_top_db_name, pkgs) : _ = db_stack
740 -- Check whether this package id already exists in this DB
742 when (not update && (pkgid `elem` map package pkgs)) $
743 die ("package " ++ showPackageId pkgid ++ " is already installed")
747 checkDir :: Force -> String -> IO ()
749 | "$topdir" `isPrefixOf` d = return ()
750 -- can't check this, because we don't know what $topdir is
752 there <- doesDirectoryExist d
754 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
756 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
757 checkDep db_stack force pkgid
758 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
759 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
762 -- for backwards compat, we treat 0.0 as a special version,
763 -- and don't check that it actually exists.
764 real_version = realVersion pkgid
766 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
769 all_pkgs = concat (map snd db_stack)
770 pkgids = map package all_pkgs
772 realVersion :: PackageIdentifier -> Bool
773 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
775 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
776 checkHSLib dirs auto_ghci_libs force lib = do
777 let batch_lib_file = "lib" ++ lib ++ ".a"
778 bs <- mapM (doesLibExistIn batch_lib_file) dirs
779 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
780 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
782 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
784 doesLibExistIn :: String -> String -> IO Bool
786 | "$topdir" `isPrefixOf` d = return True
787 | otherwise = doesFileExist (d ++ '/':lib)
789 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
790 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
791 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
793 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
794 case [dir | (exists,dir) <- zip bs dirs, exists] of
795 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
798 ghci_lib_file = lib ++ ".o"
800 -- automatically build the GHCi version of a batch lib,
801 -- using ld --whole-archive.
803 autoBuildGHCiLib :: String -> String -> String -> IO ()
804 autoBuildGHCiLib dir batch_file ghci_file = do
805 let ghci_lib_file = dir ++ '/':ghci_file
806 batch_lib_file = dir ++ '/':batch_file
807 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
808 #if defined(darwin_HOST_OS)
809 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
810 #elif defined(mingw32_HOST_OS)
811 execDir <- getExecDir "/bin/ghc-pkg.exe"
812 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
814 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
816 when (r /= ExitSuccess) $ exitWith r
817 hPutStrLn stderr (" done.")
819 -- -----------------------------------------------------------------------------
820 -- Searching for modules
824 findModules :: [FilePath] -> IO [String]
826 mms <- mapM searchDir paths
829 searchDir path prefix = do
830 fs <- getDirectoryEntries path `catch` \_ -> return []
831 searchEntries path prefix fs
833 searchEntries path prefix [] = return []
834 searchEntries path prefix (f:fs)
835 | looks_like_a_module = do
836 ms <- searchEntries path prefix fs
837 return (prefix `joinModule` f : ms)
838 | looks_like_a_component = do
839 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
840 ms' <- searchEntries path prefix fs
843 searchEntries path prefix fs
846 (base,suffix) = splitFileExt f
847 looks_like_a_module =
848 suffix `elem` haskell_suffixes &&
849 all okInModuleName base
850 looks_like_a_component =
851 null suffix && all okInModuleName base
857 -- -----------------------------------------------------------------------------
858 -- The old command-line syntax, supported for backwards compatibility
865 | OF_Add Bool {- True => replace existing info -}
866 | OF_Remove String | OF_Show String
867 | OF_Field String | OF_AutoGHCiLibs | OF_Force
868 | OF_DefinedName String String
869 | OF_GlobalConfig FilePath
872 isAction :: OldFlag -> Bool
873 isAction OF_Config{} = False
874 isAction OF_Field{} = False
875 isAction OF_Input{} = False
876 isAction OF_AutoGHCiLibs{} = False
877 isAction OF_Force{} = False
878 isAction OF_DefinedName{} = False
879 isAction OF_GlobalConfig{} = False
882 oldFlags :: [OptDescr OldFlag]
884 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
885 "use the specified package config file",
886 Option ['l'] ["list-packages"] (NoArg OF_List)
887 "list packages in all config files",
888 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
889 "list packages in the specified config file",
890 Option ['a'] ["add-package"] (NoArg (OF_Add False))
892 Option ['u'] ["update-package"] (NoArg (OF_Add True))
893 "update package with new configuration",
894 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
895 "read new package info from specified file",
896 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
897 "show the configuration for package NAME",
898 Option [] ["field"] (ReqArg OF_Field "FIELD")
899 "(with --show-package) Show field FIELD only",
900 Option [] ["force"] (NoArg OF_Force)
901 "ignore missing directories/libraries",
902 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
903 "remove an installed package",
904 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
905 "automatically build libs for GHCi (with -a)",
906 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
907 "define NAME as VALUE",
908 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
909 "location of the global package config"
913 case break (=='=') str of
914 (nm,[]) -> OF_DefinedName nm []
915 (nm,_:val) -> OF_DefinedName nm val
917 oldRunit :: [OldFlag] -> IO ()
919 let new_flags = [ f | Just f <- map conv clis ]
921 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
922 conv (OF_Config f) = Just (FlagConfig f)
927 let fields = [ f | OF_Field f <- clis ]
929 let auto_ghci_libs = any isAuto clis
930 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
931 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
933 force = if OF_Force `elem` clis then ForceAll else NoForce
935 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
937 case [ c | c <- clis, isAction c ] of
938 [ OF_List ] -> listPackages new_flags Nothing
939 [ OF_ListLocal ] -> listPackages new_flags Nothing
941 registerPackage input_file defines new_flags auto_ghci_libs upd force
942 [ OF_Remove pkgid_str ] -> do
943 pkgid <- readPkgId pkgid_str
944 unregisterPackage pkgid new_flags
945 [ OF_Show pkgid_str ]
947 pkgid <- readPkgId pkgid_str
948 describePackage new_flags pkgid
950 pkgid <- readPkgId pkgid_str
951 mapM_ (describeField new_flags pkgid) fields
953 prog <- getProgramName
954 die (usageInfo (usageHeader prog) flags)
956 my_head :: String -> [a] -> a
957 my_head s [] = error s
960 -- ---------------------------------------------------------------------------
961 -- expanding environment variables in the package configuration
963 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
964 expandEnvVars str defines force = go str ""
966 go "" acc = return $! reverse acc
967 go ('$':'{':str) acc | (var, '}':rest) <- break close str
968 = do value <- lookupEnvVar var
969 go rest (reverse value ++ acc)
970 where close c = c == '}' || c == '\n' -- don't span newlines
974 lookupEnvVar :: String -> IO String
976 case lookup nm defines of
977 Just x | not (null x) -> return x
979 catch (System.getEnv nm)
980 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
984 -----------------------------------------------------------------------------
986 getProgramName :: IO String
987 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
988 where str `withoutSuffix` suff
989 | suff `isSuffixOf` str = take (length str - length suff) str
992 bye :: String -> IO a
993 bye s = putStr s >> exitWith ExitSuccess
995 die :: String -> IO a
998 prog <- getProgramName
999 hPutStrLn stderr (prog ++ ": " ++ s)
1000 exitWith (ExitFailure 1)
1002 dieOrForceAll :: Force -> String -> IO ()
1003 dieOrForceAll ForceAll s = ignoreError s
1004 dieOrForceAll _other s = dieForcible s
1006 dieOrForceFile :: Force -> String -> IO ()
1007 dieOrForceFile ForceAll s = ignoreError s
1008 dieOrForceFile ForceFiles s = ignoreError s
1009 dieOrForceFile _other s = dieForcible s
1011 ignoreError :: String -> IO ()
1012 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1014 dieForcible :: String -> IO ()
1015 dieForcible s = die (s ++ " (use --force to override)")
1017 -----------------------------------------
1018 -- Cut and pasted from ghc/compiler/SysTools
1020 #if defined(mingw32_HOST_OS)
1021 subst a b ls = map (\ x -> if x == a then b else x) ls
1022 unDosifyPath xs = subst '\\' '/' xs
1024 getExecDir :: String -> IO (Maybe String)
1025 -- (getExecDir cmd) returns the directory in which the current
1026 -- executable, which should be called 'cmd', is running
1027 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1028 -- you'll get "/a/b/c" back as the result
1030 = allocaArray len $ \buf -> do
1031 ret <- getModuleFileName nullPtr buf len
1032 if ret == 0 then return Nothing
1033 else do s <- peekCString buf
1034 return (Just (reverse (drop (length cmd)
1035 (reverse (unDosifyPath s)))))
1037 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1039 foreign import stdcall unsafe "GetModuleFileNameA"
1040 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1042 getExecDir :: String -> IO (Maybe String)
1043 getExecDir _ = return Nothing
1046 -- -----------------------------------------------------------------------------
1049 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1050 -- It joins directory and file names to form a complete file path.
1052 -- The general rule is:
1054 -- > dir `joinFileName` basename == path
1056 -- > (dir,basename) = splitFileName path
1058 -- There might be an exceptions to the rule but in any case the
1059 -- reconstructed path will refer to the same object (file or directory).
1060 -- An example exception is that on Windows some slashes might be converted
1062 joinFileName :: String -> String -> FilePath
1063 joinFileName "" fname = fname
1064 joinFileName "." fname = fname
1065 joinFileName dir "" = dir
1066 joinFileName dir fname
1067 | isPathSeparator (last dir) = dir++fname
1068 | otherwise = dir++pathSeparator:fname
1070 -- | Checks whether the character is a valid path separator for the host
1071 -- platform. The valid character is a 'pathSeparator' but since the Windows
1072 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1073 -- checks for it on this platform, too.
1074 isPathSeparator :: Char -> Bool
1075 isPathSeparator ch = ch == pathSeparator || ch == '/'
1077 -- | Provides a platform-specific character used to separate directory levels in
1078 -- a path string that reflects a hierarchical file system organization. The
1079 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1080 -- (@\"\\\"@) on the Windows operating system.
1081 pathSeparator :: Char
1082 #ifdef mingw32_HOST_OS
1083 pathSeparator = '\\'
1088 getFilenameDir :: FilePath -> FilePath
1089 getFilenameDir fn = case break isPathSeparator (reverse fn) of
1091 (_, sep:ys) -> reverse ys
1093 -- | The function splits the given string to substrings
1094 -- using the 'searchPathSeparator'.
1095 parseSearchPath :: String -> [FilePath]
1096 parseSearchPath path = split path
1098 split :: String -> [String]
1102 _:rest -> chunk : split rest
1106 #ifdef mingw32_HOST_OS
1107 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1111 (chunk', rest') = break (==searchPathSeparator) s
1113 -- | A platform-specific character used to separate search path strings in
1114 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh,
1115 -- and a semicolon (\";\") on the Windows operating system.
1116 searchPathSeparator :: Char
1117 #if mingw32_HOST_OS || mingw32_TARGET_OS
1118 searchPathSeparator = ';'
1120 searchPathSeparator = ':'