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
42 import Data.Char ( isSpace )
45 import System ( getArgs, getProgName, getEnv, exitWith, ExitCode(..) )
47 import System.IO.Error (try)
48 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy )
50 #ifdef mingw32_HOST_OS
52 import Foreign.C.String
55 import IO ( isPermissionError, isDoesNotExistError )
57 -- -----------------------------------------------------------------------------
64 case getOpt Permute flags args of
65 (cli,_,[]) | FlagHelp `elem` cli -> do
66 prog <- getProgramName
67 bye (usageInfo (usageHeader prog) flags)
68 (cli,_,[]) | FlagVersion `elem` cli ->
72 (_,_,errors) -> tryOldCmdLine errors args
74 -- If the new command-line syntax fails, then we try the old. If that
75 -- fails too, then we output the original errors and the new syntax
76 -- (so the old syntax is still available, but hidden).
77 tryOldCmdLine :: [String] -> [String] -> IO ()
78 tryOldCmdLine errors args = do
79 case getOpt Permute oldFlags args of
83 prog <- getProgramName
84 die (concat errors ++ usageInfo (usageHeader prog) flags)
86 -- -----------------------------------------------------------------------------
87 -- Command-line syntax
95 | FlagGlobalConfig FilePath
99 | FlagDefinedName String String
103 flags :: [OptDescr Flag]
105 Option [] ["user"] (NoArg FlagUser)
106 "use the current user's package database",
107 Option [] ["global"] (NoArg FlagGlobal)
108 "(default) use the global package database",
109 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
110 "act upon specified package config file (only)",
111 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
112 "location of the global package config",
113 Option [] ["force"] (NoArg FlagForce)
114 "ignore missing dependencies, directories, and libraries",
115 Option [] ["force-files"] (NoArg FlagForceFiles)
116 "ignore missing directories and libraries only",
117 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
118 "automatically build libs for GHCi (with register)",
119 Option ['?'] ["help"] (NoArg FlagHelp)
120 "display this help and exit",
121 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
122 "define NAME as VALUE",
123 Option ['V'] ["version"] (NoArg FlagVersion)
124 "output version information and exit",
125 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
126 "print output in easy-to-parse format for some commands"
130 case break (=='=') str of
131 (nm,[]) -> FlagDefinedName nm []
132 (nm,_:val) -> FlagDefinedName nm val
134 ourCopyright :: String
135 ourCopyright = "GHC package manager version " ++ version ++ "\n"
137 usageHeader :: String -> String
138 usageHeader prog = substProg prog $
140 " $p register {filename | -}\n" ++
141 " Register the package using the specified installed package\n" ++
142 " description. The syntax for the latter is given in the $p\n" ++
143 " documentation.\n" ++
145 " $p update {filename | -}\n" ++
146 " Register the package, overwriting any other package with the\n" ++
149 " $p unregister {pkg-id}\n" ++
150 " Unregister the specified package.\n" ++
152 " $p expose {pkg-id}\n" ++
153 " Expose the specified package.\n" ++
155 " $p hide {pkg-id}\n" ++
156 " Hide the specified package.\n" ++
158 " $p list [pkg]\n" ++
159 " List registered packages in the global database, and also the\n" ++
160 " user database if --user is given. If a package name is given\n" ++
161 " all the registered versions will be listed in ascending order.\n" ++
162 " Accepts the --simple-output flag.\n" ++
164 " $p latest pkg\n" ++
165 " Prints the highest registered version of a package.\n" ++
168 " Check the consistency of package depenencies and list broken packages.\n" ++
169 " Accepts the --simple-output flag.\n" ++
171 " $p describe {pkg-id}\n" ++
172 " Give the registered description for the specified package. The\n" ++
173 " description is returned in precisely the syntax required by $p\n" ++
176 " $p field {pkg-id} {field}\n" ++
177 " Extract the specified field of the package description for the\n" ++
178 " specified package.\n" ++
180 " The following optional flags are also accepted:\n"
182 substProg :: String -> String -> String
184 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
185 substProg prog (c:xs) = c : substProg prog xs
187 -- -----------------------------------------------------------------------------
190 data Force = ForceAll | ForceFiles | NoForce
192 runit :: [Flag] -> [String] -> IO ()
193 runit cli nonopts = do
194 prog <- getProgramName
197 | FlagForce `elem` cli = ForceAll
198 | FlagForceFiles `elem` cli = ForceFiles
199 | otherwise = NoForce
200 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
201 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
203 -- first, parse the command
205 ["register", filename] ->
206 registerPackage filename defines cli auto_ghci_libs False force
207 ["update", filename] ->
208 registerPackage filename defines cli auto_ghci_libs True force
209 ["unregister", pkgid_str] -> do
210 pkgid <- readGlobPkgId pkgid_str
211 unregisterPackage pkgid cli
212 ["expose", pkgid_str] -> do
213 pkgid <- readGlobPkgId pkgid_str
214 exposePackage pkgid cli
215 ["hide", pkgid_str] -> do
216 pkgid <- readGlobPkgId pkgid_str
217 hidePackage pkgid cli
219 listPackages cli Nothing
220 ["list", pkgid_str] -> do
221 pkgid <- readGlobPkgId pkgid_str
222 listPackages cli (Just pkgid)
223 ["latest", pkgid_str] -> do
224 pkgid <- readGlobPkgId pkgid_str
225 latestPackage cli pkgid
226 ["describe", pkgid_str] -> do
227 pkgid <- readGlobPkgId pkgid_str
228 describePackage cli pkgid
229 ["field", pkgid_str, field] -> do
230 pkgid <- readGlobPkgId pkgid_str
231 describeField cli pkgid field
235 die ("missing command\n" ++
236 usageInfo (usageHeader prog) flags)
238 die ("command-line syntax error\n" ++
239 usageInfo (usageHeader prog) flags)
241 parseCheck :: ReadP a a -> String -> String -> IO a
242 parseCheck parser str what =
243 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
245 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
247 readPkgId :: String -> IO PackageIdentifier
248 readPkgId str = parseCheck parsePackageId str "package identifier"
250 readGlobPkgId :: String -> IO PackageIdentifier
251 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
253 parseGlobPackageId :: ReadP r PackageIdentifier
257 (do n <- parsePackageName; string "-*"
258 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
260 -- globVersion means "all versions"
261 globVersion :: Version
262 globVersion = Version{ versionBranch=[], versionTags=["*"] }
264 -- -----------------------------------------------------------------------------
267 -- Some commands operate on a single database:
268 -- register, unregister, expose, hide
269 -- however these commands also check the union of the available databases
270 -- in order to check consistency. For example, register will check that
271 -- dependencies exist before registering a package.
273 -- Some commands operate on multiple databases, with overlapping semantics:
274 -- list, describe, field
276 type PackageDBName = FilePath
277 type PackageDB = [InstalledPackageInfo]
279 type PackageDBStack = [(PackageDBName,PackageDB)]
280 -- A stack of package databases. Convention: head is the topmost
281 -- in the stack. Earlier entries override later one.
283 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
284 getPkgDatabases modify flags = do
285 -- first we determine the location of the global package config. On Windows,
286 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
287 -- location is passed to the binary using the --global-config flag by the
289 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
291 case [ f | FlagGlobalConfig f <- flags ] of
292 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
294 Nothing -> die err_msg
295 Just dir -> return (dir `joinFileName` "package.conf")
296 fs -> return (last fs)
298 let global_conf_dir = global_conf ++ ".d"
299 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
301 if global_conf_dir_exists
302 then do files <- getDirectoryContents global_conf_dir
303 return [ global_conf_dir ++ '/' : file
305 , isSuffixOf ".conf" file]
308 -- get the location of the user package database, and create it if necessary
309 appdir <- getAppUserDataDirectory "ghc"
312 subdir = targetARCH ++ '-':targetOS ++ '-':version
313 archdir = appdir `joinFileName` subdir
314 user_conf = archdir `joinFileName` "package.conf"
315 user_exists <- doesFileExist user_conf
317 -- If the user database doesn't exist, and this command isn't a
318 -- "modify" command, then we won't attempt to create or use it.
320 | modify || user_exists = user_conf : global_confs ++ [global_conf]
321 | otherwise = global_confs ++ [global_conf]
323 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
326 Left _ -> sys_databases
328 | last cs == "" -> init cs ++ sys_databases
330 where cs = parseSearchPath path
332 -- The "global" database is always the one at the bottom of the stack.
333 -- This is the database we modify by default.
334 virt_global_conf = last env_stack
336 -- -f flags on the command line add to the database stack, unless any
337 -- of them are present in the stack already.
338 let flag_stack = filter (`notElem` env_stack)
339 [ f | FlagConfig f <- reverse flags ] ++ env_stack
341 -- Now we have the full stack of databases. Next, if the current
342 -- command is a "modify" type command, then we truncate the stack
343 -- so that the topmost element is the database being modified.
346 then return flag_stack
348 go (FlagUser : fs) = modifying user_conf
349 go (FlagGlobal : fs) = modifying virt_global_conf
350 go (FlagConfig f : fs) = modifying f
352 go [] = modifying virt_global_conf
355 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
356 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
360 db_stack <- mapM readParseDatabase final_stack
363 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
364 readParseDatabase filename = do
365 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
366 let packages = read str
367 Exception.evaluate packages
368 `Exception.catch` \_ ->
369 die (filename ++ ": parse error in package config file")
370 return (filename,packages)
372 emptyPackageConfig :: String
373 emptyPackageConfig = "[]"
375 -- -----------------------------------------------------------------------------
378 registerPackage :: FilePath
379 -> [(String,String)] -- defines
381 -> Bool -- auto_ghci_libs
385 registerPackage input defines flags auto_ghci_libs update force = do
386 db_stack <- getPkgDatabases True flags
388 db_to_operate_on = my_head "db" db_stack
389 db_filename = fst db_to_operate_on
395 putStr "Reading package info from stdin ... "
398 putStr ("Reading package info from " ++ show f ++ " ... ")
401 expanded <- expandEnvVars s defines force
403 pkg0 <- parsePackageInfo expanded defines
406 let pkg = resolveDeps db_stack pkg0
407 validatePackageConfig pkg db_stack auto_ghci_libs update force
408 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
409 not_this p = package p /= package pkg
410 savingOldConfig db_filename $
411 writeNewConfig db_filename new_details
416 -> IO InstalledPackageInfo
417 parsePackageInfo str defines =
418 case parseInstalledPackageInfo str of
419 ParseOk _warns ok -> return ok
420 ParseFailed err -> case locatedErrorMsg err of
421 (Nothing, s) -> die s
422 (Just l, s) -> die (show l ++ ": " ++ s)
424 -- -----------------------------------------------------------------------------
425 -- Exposing, Hiding, Unregistering are all similar
427 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
428 exposePackage = modifyPackage (\p -> [p{exposed=True}])
430 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
431 hidePackage = modifyPackage (\p -> [p{exposed=False}])
433 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
434 unregisterPackage = modifyPackage (\p -> [])
437 :: (InstalledPackageInfo -> [InstalledPackageInfo])
441 modifyPackage fn pkgid flags = do
442 db_stack <- getPkgDatabases True{-modify-} flags
443 let ((db_name, pkgs) : _) = db_stack
444 ps <- findPackages [(db_name,pkgs)] pkgid
445 let pids = map package ps
446 let new_config = concat (map modify pkgs)
448 | package pkg `elem` pids = fn pkg
450 savingOldConfig db_name $
451 writeNewConfig db_name new_config
453 -- -----------------------------------------------------------------------------
456 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
457 listPackages flags mPackageName = do
458 let simple_output = FlagSimpleOutput `elem` flags
459 db_stack <- getPkgDatabases False flags
460 let db_stack_filtered -- if a package is given, filter out all other packages
461 | Just this <- mPackageName =
462 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
464 | otherwise = db_stack
467 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
468 where sort_pkgs = sortBy cmpPkgIds
469 cmpPkgIds pkg1 pkg2 =
470 case pkgName p1 `compare` pkgName p2 of
473 EQ -> pkgVersion p1 `compare` pkgVersion p2
474 where (p1,p2) = (package pkg1, package pkg2)
476 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
477 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
479 show_func (reverse db_stack_sorted)
481 where show_normal pkg_map (db_name,pkg_confs) =
482 hPutStrLn stdout (render $
483 text db_name <> colon $$ nest 4 packages
485 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
487 | isBrokenPackage p pkg_map = braces doc
489 | otherwise = parens doc
490 where doc = text (showPackageId (package p))
492 show_simple db_stack = do
493 let pkgs = map showPackageId $ sortBy compPkgIdVer $
494 map package (concatMap snd db_stack)
495 when (null pkgs) $ die "no matches"
496 hPutStrLn stdout $ concat $ intersperse " " pkgs
498 -- -----------------------------------------------------------------------------
499 -- Prints the highest (hidden or exposed) version of a package
501 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
502 latestPackage flags pkgid = do
503 db_stack <- getPkgDatabases False flags
504 ps <- findPackages db_stack pkgid
505 show_pkg (sortBy compPkgIdVer (map package ps))
507 show_pkg [] = die "no matches"
508 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
510 -- -----------------------------------------------------------------------------
513 describePackage :: [Flag] -> PackageIdentifier -> IO ()
514 describePackage flags pkgid = do
515 db_stack <- getPkgDatabases False flags
516 ps <- findPackages db_stack pkgid
517 mapM_ (putStrLn . showInstalledPackageInfo) ps
519 -- PackageId is can have globVersion for the version
520 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
521 findPackages db_stack pkgid
522 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
523 [] -> die ("cannot find package " ++ showPackageId pkgid)
526 all_pkgs = concat (map snd db_stack)
528 matches :: PackageIdentifier -> PackageIdentifier -> Bool
530 = (pkgName pid == pkgName pid')
531 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
533 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
534 pid `matchesPkg` pkg = pid `matches` package pkg
536 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
537 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
539 -- -----------------------------------------------------------------------------
542 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
543 describeField flags pkgid field = do
544 db_stack <- getPkgDatabases False flags
545 case toField field of
546 Nothing -> die ("unknown field: " ++ field)
548 ps <- findPackages db_stack pkgid
549 let top_dir = getFilenameDir (fst (last db_stack))
550 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
552 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
553 -- Replace the string "$topdir" at the beginning of a path
554 -- with the current topdir (obtained from the -B option).
555 mungePackagePaths top_dir ps = map munge_pkg ps
557 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
558 includeDirs = munge_paths (includeDirs p),
559 libraryDirs = munge_paths (libraryDirs p),
560 frameworkDirs = munge_paths (frameworkDirs p),
561 haddockInterfaces = munge_paths (haddockInterfaces p),
562 haddockHTMLs = munge_paths (haddockHTMLs p)
565 munge_paths = map munge_path
568 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
571 maybePrefixMatch :: String -> String -> Maybe String
572 maybePrefixMatch [] rest = Just rest
573 maybePrefixMatch (_:_) [] = Nothing
574 maybePrefixMatch (p:pat) (r:rest)
575 | p == r = maybePrefixMatch pat rest
576 | otherwise = Nothing
578 toField :: String -> Maybe (InstalledPackageInfo -> String)
579 -- backwards compatibility:
580 toField "import_dirs" = Just $ strList . importDirs
581 toField "source_dirs" = Just $ strList . importDirs
582 toField "library_dirs" = Just $ strList . libraryDirs
583 toField "hs_libraries" = Just $ strList . hsLibraries
584 toField "extra_libraries" = Just $ strList . extraLibraries
585 toField "include_dirs" = Just $ strList . includeDirs
586 toField "c_includes" = Just $ strList . includes
587 toField "package_deps" = Just $ strList . map showPackageId. depends
588 toField "extra_cc_opts" = Just $ strList . ccOptions
589 toField "extra_ld_opts" = Just $ strList . ldOptions
590 toField "framework_dirs" = Just $ strList . frameworkDirs
591 toField "extra_frameworks"= Just $ strList . frameworks
592 toField s = showInstalledPackageInfoField s
594 strList :: [String] -> String
598 -- -----------------------------------------------------------------------------
599 -- Check: Check consistency of installed packages
601 checkConsistency :: [Flag] -> IO ()
602 checkConsistency flags = do
603 db_stack <- getPkgDatabases False flags
604 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
607 let broken_deps = missingPackageDeps p pkgs
608 guard (not . null $ broken_deps)
609 return (pid, broken_deps)
610 mapM_ (putStrLn . render . show_func) broken_pkgs
612 show_func | FlagSimpleOutput `elem` flags = show_simple
613 | otherwise = show_normal
614 show_simple (pid,deps) =
615 text (showPackageId pid) <> colon
616 <+> fsep (punctuate comma (map (text . showPackageId) deps))
617 show_normal (pid,deps) =
618 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
619 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
621 missingPackageDeps :: InstalledPackageInfo
622 -> [(PackageIdentifier, InstalledPackageInfo)]
623 -> [PackageIdentifier]
624 missingPackageDeps pkg pkg_map =
625 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
626 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
628 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
629 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
632 -- -----------------------------------------------------------------------------
633 -- Manipulating package.conf files
635 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
636 writeNewConfig filename packages = do
637 hPutStr stdout "Writing new package config file... "
638 createDirectoryIfMissing True $ getFilenameDir filename
639 h <- openFile filename WriteMode `catch` \e ->
640 if isPermissionError e
641 then die (filename ++ ": you don't have permission to modify this file")
643 let shown = concat $ intersperse ",\n " $ map show packages
644 fileContents = "[" ++ shown ++ "\n]"
645 hPutStrLn h fileContents
647 hPutStrLn stdout "done."
649 savingOldConfig :: FilePath -> IO () -> IO ()
650 savingOldConfig filename io = Exception.block $ do
651 hPutStr stdout "Saving old package config file... "
652 -- mv rather than cp because we've already done an hGetContents
653 -- on this file so we won't be able to open it for writing
654 -- unless we move the old one out of the way...
655 let oldFile = filename ++ ".old"
656 restore_on_error <- catch (renameFile filename oldFile >> return True) $
658 unless (isDoesNotExistError err) $ do
659 hPutStrLn stderr (unwords ["Unable to rename", show filename,
663 hPutStrLn stdout "done."
665 hPutStrLn stderr (show e)
666 hPutStr stdout ("\nWARNING: an error was encountered while writing"
667 ++ "the new configuration.\n")
668 when restore_on_error $ do
669 hPutStr stdout "Attempting to restore the old configuration..."
670 do renameFile oldFile filename
671 hPutStrLn stdout "done."
672 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
675 -----------------------------------------------------------------------------
676 -- Sanity-check a new package config, and automatically build GHCi libs
679 validatePackageConfig :: InstalledPackageInfo
681 -> Bool -- auto-ghc-libs
685 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
687 checkDuplicates db_stack pkg update
688 mapM_ (checkDep db_stack force) (depends pkg)
689 mapM_ (checkDir force) (importDirs pkg)
690 mapM_ (checkDir force) (libraryDirs pkg)
691 mapM_ (checkDir force) (includeDirs pkg)
692 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
693 -- ToDo: check these somehow?
694 -- extra_libraries :: [String],
695 -- c_includes :: [String],
697 -- When the package name and version are put together, sometimes we can
698 -- end up with a package id that cannot be parsed. This will lead to
699 -- difficulties when the user wants to refer to the package later, so
700 -- we check that the package id can be parsed properly here.
701 checkPackageId :: InstalledPackageInfo -> IO ()
703 let str = showPackageId (package ipi) in
704 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
706 [] -> die ("invalid package identifier: " ++ str)
707 _ -> die ("ambiguous package identifier: " ++ str)
709 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
710 resolveDeps db_stack p = updateDeps p
712 -- The input package spec is allowed to give a package dependency
713 -- without a version number; e.g.
715 -- Here, we update these dependencies without version numbers to
716 -- match the actual versions of the relevant packages installed.
717 updateDeps p = p{depends = map resolveDep (depends p)}
720 | realVersion dep_pkgid = dep_pkgid
721 | otherwise = lookupDep dep_pkgid
725 name = pkgName dep_pkgid
727 case [ pid | p <- concat (map snd db_stack),
729 pkgName pid == name ] of
730 (pid:_) -> pid -- Found installed package,
731 -- replete with its version
732 [] -> dep_pkgid -- No installed package; use
733 -- the version-less one
735 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
736 checkDuplicates db_stack pkg update = do
739 (_top_db_name, pkgs) : _ = db_stack
741 -- Check whether this package id already exists in this DB
743 when (not update && (pkgid `elem` map package pkgs)) $
744 die ("package " ++ showPackageId pkgid ++ " is already installed")
748 checkDir :: Force -> String -> IO ()
750 | "$topdir" `isPrefixOf` d = return ()
751 -- can't check this, because we don't know what $topdir is
753 there <- doesDirectoryExist d
755 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
757 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
758 checkDep db_stack force pkgid
759 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
760 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
763 -- for backwards compat, we treat 0.0 as a special version,
764 -- and don't check that it actually exists.
765 real_version = realVersion pkgid
767 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
770 all_pkgs = concat (map snd db_stack)
771 pkgids = map package all_pkgs
773 realVersion :: PackageIdentifier -> Bool
774 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
776 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
777 checkHSLib dirs auto_ghci_libs force lib = do
778 let batch_lib_file = "lib" ++ lib ++ ".a"
779 bs <- mapM (doesLibExistIn batch_lib_file) dirs
780 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
781 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
783 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
785 doesLibExistIn :: String -> String -> IO Bool
787 | "$topdir" `isPrefixOf` d = return True
788 | otherwise = doesFileExist (d ++ '/':lib)
790 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
791 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
792 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
794 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
795 case [dir | (exists,dir) <- zip bs dirs, exists] of
796 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
799 ghci_lib_file = lib ++ ".o"
801 -- automatically build the GHCi version of a batch lib,
802 -- using ld --whole-archive.
804 autoBuildGHCiLib :: String -> String -> String -> IO ()
805 autoBuildGHCiLib dir batch_file ghci_file = do
806 let ghci_lib_file = dir ++ '/':ghci_file
807 batch_lib_file = dir ++ '/':batch_file
808 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
809 #if defined(darwin_HOST_OS)
810 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
811 #elif defined(mingw32_HOST_OS)
812 execDir <- getExecDir "/bin/ghc-pkg.exe"
813 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
815 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
817 when (r /= ExitSuccess) $ exitWith r
818 hPutStrLn stderr (" done.")
820 -- -----------------------------------------------------------------------------
821 -- Searching for modules
825 findModules :: [FilePath] -> IO [String]
827 mms <- mapM searchDir paths
830 searchDir path prefix = do
831 fs <- getDirectoryEntries path `catch` \_ -> return []
832 searchEntries path prefix fs
834 searchEntries path prefix [] = return []
835 searchEntries path prefix (f:fs)
836 | looks_like_a_module = do
837 ms <- searchEntries path prefix fs
838 return (prefix `joinModule` f : ms)
839 | looks_like_a_component = do
840 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
841 ms' <- searchEntries path prefix fs
844 searchEntries path prefix fs
847 (base,suffix) = splitFileExt f
848 looks_like_a_module =
849 suffix `elem` haskell_suffixes &&
850 all okInModuleName base
851 looks_like_a_component =
852 null suffix && all okInModuleName base
858 -- -----------------------------------------------------------------------------
859 -- The old command-line syntax, supported for backwards compatibility
866 | OF_Add Bool {- True => replace existing info -}
867 | OF_Remove String | OF_Show String
868 | OF_Field String | OF_AutoGHCiLibs | OF_Force
869 | OF_DefinedName String String
870 | OF_GlobalConfig FilePath
873 isAction :: OldFlag -> Bool
874 isAction OF_Config{} = False
875 isAction OF_Field{} = False
876 isAction OF_Input{} = False
877 isAction OF_AutoGHCiLibs{} = False
878 isAction OF_Force{} = False
879 isAction OF_DefinedName{} = False
880 isAction OF_GlobalConfig{} = False
883 oldFlags :: [OptDescr OldFlag]
885 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
886 "use the specified package config file",
887 Option ['l'] ["list-packages"] (NoArg OF_List)
888 "list packages in all config files",
889 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
890 "list packages in the specified config file",
891 Option ['a'] ["add-package"] (NoArg (OF_Add False))
893 Option ['u'] ["update-package"] (NoArg (OF_Add True))
894 "update package with new configuration",
895 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
896 "read new package info from specified file",
897 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
898 "show the configuration for package NAME",
899 Option [] ["field"] (ReqArg OF_Field "FIELD")
900 "(with --show-package) Show field FIELD only",
901 Option [] ["force"] (NoArg OF_Force)
902 "ignore missing directories/libraries",
903 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
904 "remove an installed package",
905 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
906 "automatically build libs for GHCi (with -a)",
907 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
908 "define NAME as VALUE",
909 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
910 "location of the global package config"
914 case break (=='=') str of
915 (nm,[]) -> OF_DefinedName nm []
916 (nm,_:val) -> OF_DefinedName nm val
918 oldRunit :: [OldFlag] -> IO ()
920 let new_flags = [ f | Just f <- map conv clis ]
922 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
923 conv (OF_Config f) = Just (FlagConfig f)
928 let fields = [ f | OF_Field f <- clis ]
930 let auto_ghci_libs = any isAuto clis
931 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
932 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
934 force = if OF_Force `elem` clis then ForceAll else NoForce
936 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
938 case [ c | c <- clis, isAction c ] of
939 [ OF_List ] -> listPackages new_flags Nothing
940 [ OF_ListLocal ] -> listPackages new_flags Nothing
942 registerPackage input_file defines new_flags auto_ghci_libs upd force
943 [ OF_Remove pkgid_str ] -> do
944 pkgid <- readPkgId pkgid_str
945 unregisterPackage pkgid new_flags
946 [ OF_Show pkgid_str ]
948 pkgid <- readPkgId pkgid_str
949 describePackage new_flags pkgid
951 pkgid <- readPkgId pkgid_str
952 mapM_ (describeField new_flags pkgid) fields
954 prog <- getProgramName
955 die (usageInfo (usageHeader prog) flags)
957 my_head :: String -> [a] -> a
958 my_head s [] = error s
961 -- ---------------------------------------------------------------------------
962 -- expanding environment variables in the package configuration
964 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
965 expandEnvVars str defines force = go str ""
967 go "" acc = return $! reverse acc
968 go ('$':'{':str) acc | (var, '}':rest) <- break close str
969 = do value <- lookupEnvVar var
970 go rest (reverse value ++ acc)
971 where close c = c == '}' || c == '\n' -- don't span newlines
975 lookupEnvVar :: String -> IO String
977 case lookup nm defines of
978 Just x | not (null x) -> return x
980 catch (System.getEnv nm)
981 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
985 -----------------------------------------------------------------------------
987 getProgramName :: IO String
988 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
989 where str `withoutSuffix` suff
990 | suff `isSuffixOf` str = take (length str - length suff) str
993 bye :: String -> IO a
994 bye s = putStr s >> exitWith ExitSuccess
996 die :: String -> IO a
999 prog <- getProgramName
1000 hPutStrLn stderr (prog ++ ": " ++ s)
1001 exitWith (ExitFailure 1)
1003 dieOrForceAll :: Force -> String -> IO ()
1004 dieOrForceAll ForceAll s = ignoreError s
1005 dieOrForceAll _other s = dieForcible s
1007 dieOrForceFile :: Force -> String -> IO ()
1008 dieOrForceFile ForceAll s = ignoreError s
1009 dieOrForceFile ForceFiles s = ignoreError s
1010 dieOrForceFile _other s = dieForcible s
1012 ignoreError :: String -> IO ()
1013 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1015 dieForcible :: String -> IO ()
1016 dieForcible s = die (s ++ " (use --force to override)")
1018 -----------------------------------------
1019 -- Cut and pasted from ghc/compiler/SysTools
1021 #if defined(mingw32_HOST_OS)
1022 subst a b ls = map (\ x -> if x == a then b else x) ls
1023 unDosifyPath xs = subst '\\' '/' xs
1025 getExecDir :: String -> IO (Maybe String)
1026 -- (getExecDir cmd) returns the directory in which the current
1027 -- executable, which should be called 'cmd', is running
1028 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1029 -- you'll get "/a/b/c" back as the result
1031 = allocaArray len $ \buf -> do
1032 ret <- getModuleFileName nullPtr buf len
1033 if ret == 0 then return Nothing
1034 else do s <- peekCString buf
1035 return (Just (reverse (drop (length cmd)
1036 (reverse (unDosifyPath s)))))
1038 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1040 foreign import stdcall unsafe "GetModuleFileNameA"
1041 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1043 getExecDir :: String -> IO (Maybe String)
1044 getExecDir _ = return Nothing
1047 -- -----------------------------------------------------------------------------
1050 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1051 -- It joins directory and file names to form a complete file path.
1053 -- The general rule is:
1055 -- > dir `joinFileName` basename == path
1057 -- > (dir,basename) = splitFileName path
1059 -- There might be an exceptions to the rule but in any case the
1060 -- reconstructed path will refer to the same object (file or directory).
1061 -- An example exception is that on Windows some slashes might be converted
1063 joinFileName :: String -> String -> FilePath
1064 joinFileName "" fname = fname
1065 joinFileName "." fname = fname
1066 joinFileName dir "" = dir
1067 joinFileName dir fname
1068 | isPathSeparator (last dir) = dir++fname
1069 | otherwise = dir++pathSeparator:fname
1071 -- | Checks whether the character is a valid path separator for the host
1072 -- platform. The valid character is a 'pathSeparator' but since the Windows
1073 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1074 -- checks for it on this platform, too.
1075 isPathSeparator :: Char -> Bool
1076 isPathSeparator ch = ch == pathSeparator || ch == '/'
1078 -- | Provides a platform-specific character used to separate directory levels in
1079 -- a path string that reflects a hierarchical file system organization. The
1080 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1081 -- (@\"\\\"@) on the Windows operating system.
1082 pathSeparator :: Char
1083 #ifdef mingw32_HOST_OS
1084 pathSeparator = '\\'
1089 getFilenameDir :: FilePath -> FilePath
1090 getFilenameDir fn = case break isPathSeparator (reverse fn) of
1092 (_, sep:ys) -> reverse ys
1094 -- | The function splits the given string to substrings
1095 -- using the 'searchPathSeparator'.
1096 parseSearchPath :: String -> [FilePath]
1097 parseSearchPath path = split path
1099 split :: String -> [String]
1103 _:rest -> chunk : split rest
1107 #ifdef mingw32_HOST_OS
1108 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1112 (chunk', rest') = break (==searchPathSeparator) s
1114 -- | A platform-specific character used to separate search path strings
1115 -- in environment variables. The separator is a colon (\":\") on Unix
1116 -- and Macintosh, and a semicolon (\";\") on the Windows operating system.
1117 searchPathSeparator :: Char
1118 #if mingw32_HOST_OS || mingw32_TARGET_OS
1119 searchPathSeparator = ';'
1121 searchPathSeparator = ':'