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 #if __GLASGOW_HASKELL__ >= 504
38 import System.Console.GetOpt
39 import Text.PrettyPrint
40 import qualified Control.Exception as Exception
45 import qualified Exception
49 import Data.Char ( isSpace )
52 import System ( getArgs, getProgName, getEnv,
53 exitWith, ExitCode(..)
56 #if __GLASGOW_HASKELL__ >= 600
57 import System.IO.Error (try)
59 import System.IO (try)
61 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy )
63 #ifdef mingw32_HOST_OS
66 #if __GLASGOW_HASKELL__ >= 504
67 import Foreign.C.String
73 import IO ( isPermissionError, isDoesNotExistError )
75 -- -----------------------------------------------------------------------------
82 case getOpt Permute flags args of
83 (cli,_,[]) | FlagHelp `elem` cli -> do
84 prog <- getProgramName
85 bye (usageInfo (usageHeader prog) flags)
86 (cli,_,[]) | FlagVersion `elem` cli ->
90 (_,_,errors) -> tryOldCmdLine errors args
92 -- If the new command-line syntax fails, then we try the old. If that
93 -- fails too, then we output the original errors and the new syntax
94 -- (so the old syntax is still available, but hidden).
95 tryOldCmdLine :: [String] -> [String] -> IO ()
96 tryOldCmdLine errors args = do
97 case getOpt Permute oldFlags args of
101 prog <- getProgramName
102 die (concat errors ++ usageInfo (usageHeader prog) flags)
104 -- -----------------------------------------------------------------------------
105 -- Command-line syntax
112 | FlagConfig FilePath
113 | FlagGlobalConfig FilePath
117 | FlagDefinedName String String
121 flags :: [OptDescr Flag]
123 Option [] ["user"] (NoArg FlagUser)
124 "use the current user's package database",
125 Option [] ["global"] (NoArg FlagGlobal)
126 "(default) use the global package database",
127 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
128 "act upon specified package config file (only)",
129 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
130 "location of the global package config",
131 Option [] ["force"] (NoArg FlagForce)
132 "ignore missing dependencies, directories, and libraries",
133 Option [] ["force-files"] (NoArg FlagForceFiles)
134 "ignore missing directories and libraries only",
135 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
136 "automatically build libs for GHCi (with register)",
137 Option ['?'] ["help"] (NoArg FlagHelp)
138 "display this help and exit",
139 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
140 "define NAME as VALUE",
141 Option ['V'] ["version"] (NoArg FlagVersion)
142 "output version information and exit",
143 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
144 "print output in easy-to-parse format for some commands"
148 case break (=='=') str of
149 (nm,[]) -> FlagDefinedName nm []
150 (nm,_:val) -> FlagDefinedName nm val
152 ourCopyright :: String
153 ourCopyright = "GHC package manager version " ++ version ++ "\n"
155 usageHeader :: String -> String
156 usageHeader prog = substProg prog $
158 " $p register {filename | -}\n" ++
159 " Register the package using the specified installed package\n" ++
160 " description. The syntax for the latter is given in the $p\n" ++
161 " documentation.\n" ++
163 " $p update {filename | -}\n" ++
164 " Register the package, overwriting any other package with the\n" ++
167 " $p unregister {pkg-id}\n" ++
168 " Unregister the specified package.\n" ++
170 " $p expose {pkg-id}\n" ++
171 " Expose the specified package.\n" ++
173 " $p hide {pkg-id}\n" ++
174 " Hide the specified package.\n" ++
176 " $p list [pkg]\n" ++
177 " List registered packages in the global database, and also the\n" ++
178 " user database if --user is given. If a package name is given\n" ++
179 " all the registered versions will be listed in ascending order.\n" ++
180 " Accepts the --simple-output flag.\n" ++
182 " $p latest pkg\n" ++
183 " Prints the highest registered version of a package.\n" ++
186 " Check the consistency of package depenencies and list broken packages.\n" ++
187 " Accepts the --simple-output flag.\n" ++
189 " $p describe {pkg-id}\n" ++
190 " Give the registered description for the specified package. The\n" ++
191 " description is returned in precisely the syntax required by $p\n" ++
194 " $p field {pkg-id} {field}\n" ++
195 " Extract the specified field of the package description for the\n" ++
196 " specified package.\n" ++
198 " The following optional flags are also accepted:\n"
200 substProg :: String -> String -> String
202 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
203 substProg prog (c:xs) = c : substProg prog xs
205 -- -----------------------------------------------------------------------------
208 data Force = ForceAll | ForceFiles | NoForce
210 runit :: [Flag] -> [String] -> IO ()
211 runit cli nonopts = do
212 prog <- getProgramName
215 | FlagForce `elem` cli = ForceAll
216 | FlagForceFiles `elem` cli = ForceFiles
217 | otherwise = NoForce
218 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
219 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
221 -- first, parse the command
223 ["register", filename] ->
224 registerPackage filename defines cli auto_ghci_libs False force
225 ["update", filename] ->
226 registerPackage filename defines cli auto_ghci_libs True force
227 ["unregister", pkgid_str] -> do
228 pkgid <- readGlobPkgId pkgid_str
229 unregisterPackage pkgid cli
230 ["expose", pkgid_str] -> do
231 pkgid <- readGlobPkgId pkgid_str
232 exposePackage pkgid cli
233 ["hide", pkgid_str] -> do
234 pkgid <- readGlobPkgId pkgid_str
235 hidePackage pkgid cli
237 listPackages cli Nothing
238 ["list", pkgid_str] -> do
239 pkgid <- readGlobPkgId pkgid_str
240 listPackages cli (Just pkgid)
241 ["latest", pkgid_str] -> do
242 pkgid <- readGlobPkgId pkgid_str
243 latestPackage cli pkgid
244 ["describe", pkgid_str] -> do
245 pkgid <- readGlobPkgId pkgid_str
246 describePackage cli pkgid
247 ["field", pkgid_str, field] -> do
248 pkgid <- readGlobPkgId pkgid_str
249 describeField cli pkgid field
253 die ("missing command\n" ++
254 usageInfo (usageHeader prog) flags)
256 die ("command-line syntax error\n" ++
257 usageInfo (usageHeader prog) flags)
259 parseCheck :: ReadP a a -> String -> String -> IO a
260 parseCheck parser str what =
261 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
263 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
265 readPkgId :: String -> IO PackageIdentifier
266 readPkgId str = parseCheck parsePackageId str "package identifier"
268 readGlobPkgId :: String -> IO PackageIdentifier
269 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
271 parseGlobPackageId :: ReadP r PackageIdentifier
275 (do n <- parsePackageName; string "-*"
276 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
278 -- globVersion means "all versions"
279 globVersion :: Version
280 globVersion = Version{ versionBranch=[], versionTags=["*"] }
282 -- -----------------------------------------------------------------------------
285 -- Some commands operate on a single database:
286 -- register, unregister, expose, hide
287 -- however these commands also check the union of the available databases
288 -- in order to check consistency. For example, register will check that
289 -- dependencies exist before registering a package.
291 -- Some commands operate on multiple databases, with overlapping semantics:
292 -- list, describe, field
294 type PackageDBName = FilePath
295 type PackageDB = [InstalledPackageInfo]
297 type PackageDBStack = [(PackageDBName,PackageDB)]
298 -- A stack of package databases. Convention: head is the topmost
299 -- in the stack. Earlier entries override later one.
301 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
302 getPkgDatabases modify flags = do
303 -- first we determine the location of the global package config. On Windows,
304 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
305 -- location is passed to the binary using the --global-config flag by the
307 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
309 case [ f | FlagGlobalConfig f <- flags ] of
310 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
312 Nothing -> die err_msg
313 Just dir -> return (dir `joinFileName` "package.conf")
314 fs -> return (last fs)
316 let global_conf_dir = global_conf ++ ".d"
317 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
319 if global_conf_dir_exists
320 then do files <- getDirectoryContents global_conf_dir
321 return [ global_conf_dir ++ '/' : file
323 , isSuffixOf ".conf" file]
326 -- get the location of the user package database, and create it if necessary
327 appdir <- getAppUserDataDirectory "ghc"
330 subdir = targetARCH ++ '-':targetOS ++ '-':version
331 archdir = appdir `joinFileName` subdir
332 user_conf = archdir `joinFileName` "package.conf"
333 user_exists <- doesFileExist user_conf
335 -- If the user database doesn't exist, and this command isn't a
336 -- "modify" command, then we won't attempt to create or use it.
338 | modify || user_exists = user_conf : global_confs ++ [global_conf]
339 | otherwise = global_confs ++ [global_conf]
341 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
344 Left _ -> sys_databases
346 | last cs == "" -> init cs ++ sys_databases
348 where cs = parseSearchPath path
350 -- The "global" database is always the one at the bottom of the stack.
351 -- This is the database we modify by default.
352 virt_global_conf = last env_stack
354 -- -f flags on the command line add to the database stack, unless any
355 -- of them are present in the stack already.
356 let flag_stack = filter (`notElem` env_stack)
357 [ f | FlagConfig f <- reverse flags ] ++ env_stack
359 -- Now we have the full stack of databases. Next, if the current
360 -- command is a "modify" type command, then we truncate the stack
361 -- so that the topmost element is the database being modified.
364 then return flag_stack
366 go (FlagUser : fs) = modifying user_conf
367 go (FlagGlobal : fs) = modifying virt_global_conf
368 go (FlagConfig f : fs) = modifying f
370 go [] = modifying virt_global_conf
373 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
374 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
378 db_stack <- mapM readParseDatabase final_stack
381 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
382 readParseDatabase filename = do
383 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
384 let packages = read str
385 Exception.evaluate packages
386 `Exception.catch` \_ ->
387 die (filename ++ ": parse error in package config file")
388 return (filename,packages)
390 emptyPackageConfig :: String
391 emptyPackageConfig = "[]"
393 -- -----------------------------------------------------------------------------
396 registerPackage :: FilePath
397 -> [(String,String)] -- defines
399 -> Bool -- auto_ghci_libs
403 registerPackage input defines flags auto_ghci_libs update force = do
404 db_stack <- getPkgDatabases True flags
406 db_to_operate_on = my_head "db" db_stack
407 db_filename = fst db_to_operate_on
413 putStr "Reading package info from stdin ... "
416 putStr ("Reading package info from " ++ show f ++ " ... ")
419 expanded <- expandEnvVars s defines force
421 pkg0 <- parsePackageInfo expanded defines
424 let pkg = resolveDeps db_stack pkg0
425 validatePackageConfig pkg db_stack auto_ghci_libs update force
426 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
427 not_this p = package p /= package pkg
428 savingOldConfig db_filename $
429 writeNewConfig db_filename new_details
434 -> IO InstalledPackageInfo
435 parsePackageInfo str defines =
436 case parseInstalledPackageInfo str of
437 ParseOk _warns ok -> return ok
438 ParseFailed err -> case locatedErrorMsg err of
439 (Nothing, s) -> die s
440 (Just l, s) -> die (show l ++ ": " ++ s)
442 -- -----------------------------------------------------------------------------
443 -- Exposing, Hiding, Unregistering are all similar
445 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
446 exposePackage = modifyPackage (\p -> [p{exposed=True}])
448 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
449 hidePackage = modifyPackage (\p -> [p{exposed=False}])
451 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
452 unregisterPackage = modifyPackage (\p -> [])
455 :: (InstalledPackageInfo -> [InstalledPackageInfo])
459 modifyPackage fn pkgid flags = do
460 db_stack <- getPkgDatabases True{-modify-} flags
461 let ((db_name, pkgs) : _) = db_stack
462 ps <- findPackages [(db_name,pkgs)] pkgid
463 let pids = map package ps
464 let new_config = concat (map modify pkgs)
466 | package pkg `elem` pids = fn pkg
468 savingOldConfig db_name $
469 writeNewConfig db_name new_config
471 -- -----------------------------------------------------------------------------
474 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
475 listPackages flags mPackageName = do
476 let simple_output = FlagSimpleOutput `elem` flags
477 db_stack <- getPkgDatabases False flags
478 let db_stack_filtered -- if a package is given, filter out all other packages
479 | Just this <- mPackageName =
480 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
482 | otherwise = db_stack
485 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
486 where sort_pkgs = sortBy cmpPkgIds
487 cmpPkgIds pkg1 pkg2 =
488 case pkgName p1 `compare` pkgName p2 of
491 EQ -> pkgVersion p1 `compare` pkgVersion p2
492 where (p1,p2) = (package pkg1, package pkg2)
494 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
495 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
497 show_func (reverse db_stack_sorted)
499 where show_normal pkg_map (db_name,pkg_confs) =
500 hPutStrLn stdout (render $
501 text db_name <> colon $$ nest 4 packages
503 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
505 | isBrokenPackage p pkg_map = braces doc
507 | otherwise = parens doc
508 where doc = text (showPackageId (package p))
510 show_simple db_stack = do
511 let pkgs = map showPackageId $ sortBy compPkgIdVer $
512 map package (concatMap snd db_stack)
513 when (null pkgs) $ die "no matches"
514 hPutStrLn stdout $ concat $ intersperse " " pkgs
516 -- -----------------------------------------------------------------------------
517 -- Prints the highest (hidden or exposed) version of a package
519 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
520 latestPackage flags pkgid = do
521 db_stack <- getPkgDatabases False flags
522 ps <- findPackages db_stack pkgid
523 show_pkg (sortBy compPkgIdVer (map package ps))
525 show_pkg [] = die "no matches"
526 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
528 -- -----------------------------------------------------------------------------
531 describePackage :: [Flag] -> PackageIdentifier -> IO ()
532 describePackage flags pkgid = do
533 db_stack <- getPkgDatabases False flags
534 ps <- findPackages db_stack pkgid
535 mapM_ (putStrLn . showInstalledPackageInfo) ps
537 -- PackageId is can have globVersion for the version
538 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
539 findPackages db_stack pkgid
540 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
541 [] -> die ("cannot find package " ++ showPackageId pkgid)
544 all_pkgs = concat (map snd db_stack)
546 matches :: PackageIdentifier -> PackageIdentifier -> Bool
548 = (pkgName pid == pkgName pid')
549 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
551 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
552 pid `matchesPkg` pkg = pid `matches` package pkg
554 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
555 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
557 -- -----------------------------------------------------------------------------
560 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
561 describeField flags pkgid field = do
562 db_stack <- getPkgDatabases False flags
563 case toField field of
564 Nothing -> die ("unknown field: " ++ field)
566 ps <- findPackages db_stack pkgid
567 let top_dir = getFilenameDir (fst (last db_stack))
568 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
570 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
571 -- Replace the string "$topdir" at the beginning of a path
572 -- with the current topdir (obtained from the -B option).
573 mungePackagePaths top_dir ps = map munge_pkg ps
575 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
576 includeDirs = munge_paths (includeDirs p),
577 libraryDirs = munge_paths (libraryDirs p),
578 frameworkDirs = munge_paths (frameworkDirs p),
579 haddockInterfaces = munge_paths (haddockInterfaces p),
580 haddockHTMLs = munge_paths (haddockHTMLs p)
583 munge_paths = map munge_path
586 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
589 maybePrefixMatch :: String -> String -> Maybe String
590 maybePrefixMatch [] rest = Just rest
591 maybePrefixMatch (_:_) [] = Nothing
592 maybePrefixMatch (p:pat) (r:rest)
593 | p == r = maybePrefixMatch pat rest
594 | otherwise = Nothing
596 toField :: String -> Maybe (InstalledPackageInfo -> String)
597 -- backwards compatibility:
598 toField "import_dirs" = Just $ strList . importDirs
599 toField "source_dirs" = Just $ strList . importDirs
600 toField "library_dirs" = Just $ strList . libraryDirs
601 toField "hs_libraries" = Just $ strList . hsLibraries
602 toField "extra_libraries" = Just $ strList . extraLibraries
603 toField "include_dirs" = Just $ strList . includeDirs
604 toField "c_includes" = Just $ strList . includes
605 toField "package_deps" = Just $ strList . map showPackageId. depends
606 toField "extra_cc_opts" = Just $ strList . ccOptions
607 toField "extra_ld_opts" = Just $ strList . ldOptions
608 toField "framework_dirs" = Just $ strList . frameworkDirs
609 toField "extra_frameworks"= Just $ strList . frameworks
610 toField s = showInstalledPackageInfoField s
612 strList :: [String] -> String
616 -- -----------------------------------------------------------------------------
617 -- Check: Check consistency of installed packages
619 checkConsistency :: [Flag] -> IO ()
620 checkConsistency flags = do
621 db_stack <- getPkgDatabases False flags
622 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
625 let broken_deps = missingPackageDeps p pkgs
626 guard (not . null $ broken_deps)
627 return (pid, broken_deps)
628 mapM_ (putStrLn . render . show_func) broken_pkgs
630 show_func | FlagSimpleOutput `elem` flags = show_simple
631 | otherwise = show_normal
632 show_simple (pid,deps) =
633 text (showPackageId pid) <> colon
634 <+> fsep (punctuate comma (map (text . showPackageId) deps))
635 show_normal (pid,deps) =
636 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
637 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
639 missingPackageDeps :: InstalledPackageInfo
640 -> [(PackageIdentifier, InstalledPackageInfo)]
641 -> [PackageIdentifier]
642 missingPackageDeps pkg pkg_map =
643 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
644 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
646 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
647 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
650 -- -----------------------------------------------------------------------------
651 -- Manipulating package.conf files
653 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
654 writeNewConfig filename packages = do
655 hPutStr stdout "Writing new package config file... "
656 createDirectoryIfMissing True $ getFilenameDir filename
657 h <- openFile filename WriteMode `catch` \e ->
658 if isPermissionError e
659 then die (filename ++ ": you don't have permission to modify this file")
661 hPutStrLn h (show packages)
663 hPutStrLn stdout "done."
665 savingOldConfig :: FilePath -> IO () -> IO ()
666 savingOldConfig filename io = Exception.block $ do
667 hPutStr stdout "Saving old package config file... "
668 -- mv rather than cp because we've already done an hGetContents
669 -- on this file so we won't be able to open it for writing
670 -- unless we move the old one out of the way...
671 let oldFile = filename ++ ".old"
672 restore_on_error <- catch (renameFile filename oldFile >> return True) $
674 unless (isDoesNotExistError err) $ do
675 hPutStrLn stderr (unwords ["Unable to rename", show filename,
679 hPutStrLn stdout "done."
681 hPutStrLn stderr (show e)
682 hPutStr stdout ("\nWARNING: an error was encountered while writing"
683 ++ "the new configuration.\n")
684 when restore_on_error $ do
685 hPutStr stdout "Attempting to restore the old configuration..."
686 do renameFile oldFile filename
687 hPutStrLn stdout "done."
688 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
691 -----------------------------------------------------------------------------
692 -- Sanity-check a new package config, and automatically build GHCi libs
695 validatePackageConfig :: InstalledPackageInfo
697 -> Bool -- auto-ghc-libs
701 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
703 checkDuplicates db_stack pkg update
704 mapM_ (checkDep db_stack force) (depends pkg)
705 mapM_ (checkDir force) (importDirs pkg)
706 mapM_ (checkDir force) (libraryDirs pkg)
707 mapM_ (checkDir force) (includeDirs pkg)
708 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
709 -- ToDo: check these somehow?
710 -- extra_libraries :: [String],
711 -- c_includes :: [String],
713 -- When the package name and version are put together, sometimes we can
714 -- end up with a package id that cannot be parsed. This will lead to
715 -- difficulties when the user wants to refer to the package later, so
716 -- we check that the package id can be parsed properly here.
717 checkPackageId :: InstalledPackageInfo -> IO ()
719 let str = showPackageId (package ipi) in
720 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
722 [] -> die ("invalid package identifier: " ++ str)
723 _ -> die ("ambiguous package identifier: " ++ str)
725 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
726 resolveDeps db_stack p = updateDeps p
728 -- The input package spec is allowed to give a package dependency
729 -- without a version number; e.g.
731 -- Here, we update these dependencies without version numbers to
732 -- match the actual versions of the relevant packages installed.
733 updateDeps p = p{depends = map resolveDep (depends p)}
736 | realVersion dep_pkgid = dep_pkgid
737 | otherwise = lookupDep dep_pkgid
741 name = pkgName dep_pkgid
743 case [ pid | p <- concat (map snd db_stack),
745 pkgName pid == name ] of
746 (pid:_) -> pid -- Found installed package,
747 -- replete with its version
748 [] -> dep_pkgid -- No installed package; use
749 -- the version-less one
751 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
752 checkDuplicates db_stack pkg update = do
755 (_top_db_name, pkgs) : _ = db_stack
757 -- Check whether this package id already exists in this DB
759 when (not update && (pkgid `elem` map package pkgs)) $
760 die ("package " ++ showPackageId pkgid ++ " is already installed")
764 checkDir :: Force -> String -> IO ()
766 | "$topdir" `isPrefixOf` d = return ()
767 -- can't check this, because we don't know what $topdir is
769 there <- doesDirectoryExist d
771 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
773 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
774 checkDep db_stack force pkgid
775 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
776 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
779 -- for backwards compat, we treat 0.0 as a special version,
780 -- and don't check that it actually exists.
781 real_version = realVersion pkgid
783 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
786 all_pkgs = concat (map snd db_stack)
787 pkgids = map package all_pkgs
789 realVersion :: PackageIdentifier -> Bool
790 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
792 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
793 checkHSLib dirs auto_ghci_libs force lib = do
794 let batch_lib_file = "lib" ++ lib ++ ".a"
795 bs <- mapM (doesLibExistIn batch_lib_file) dirs
796 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
797 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
799 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
801 doesLibExistIn :: String -> String -> IO Bool
803 | "$topdir" `isPrefixOf` d = return True
804 | otherwise = doesFileExist (d ++ '/':lib)
806 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
807 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
808 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
810 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
811 case [dir | (exists,dir) <- zip bs dirs, exists] of
812 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
815 ghci_lib_file = lib ++ ".o"
817 -- automatically build the GHCi version of a batch lib,
818 -- using ld --whole-archive.
820 autoBuildGHCiLib :: String -> String -> String -> IO ()
821 autoBuildGHCiLib dir batch_file ghci_file = do
822 let ghci_lib_file = dir ++ '/':ghci_file
823 batch_lib_file = dir ++ '/':batch_file
824 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
825 #if defined(darwin_HOST_OS)
826 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
827 #elif defined(mingw32_HOST_OS)
828 execDir <- getExecDir "/bin/ghc-pkg.exe"
829 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
831 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
833 when (r /= ExitSuccess) $ exitWith r
834 hPutStrLn stderr (" done.")
836 -- -----------------------------------------------------------------------------
837 -- Searching for modules
841 findModules :: [FilePath] -> IO [String]
843 mms <- mapM searchDir paths
846 searchDir path prefix = do
847 fs <- getDirectoryEntries path `catch` \_ -> return []
848 searchEntries path prefix fs
850 searchEntries path prefix [] = return []
851 searchEntries path prefix (f:fs)
852 | looks_like_a_module = do
853 ms <- searchEntries path prefix fs
854 return (prefix `joinModule` f : ms)
855 | looks_like_a_component = do
856 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
857 ms' <- searchEntries path prefix fs
860 searchEntries path prefix fs
863 (base,suffix) = splitFileExt f
864 looks_like_a_module =
865 suffix `elem` haskell_suffixes &&
866 all okInModuleName base
867 looks_like_a_component =
868 null suffix && all okInModuleName base
874 -- -----------------------------------------------------------------------------
875 -- The old command-line syntax, supported for backwards compatibility
882 | OF_Add Bool {- True => replace existing info -}
883 | OF_Remove String | OF_Show String
884 | OF_Field String | OF_AutoGHCiLibs | OF_Force
885 | OF_DefinedName String String
886 | OF_GlobalConfig FilePath
889 isAction :: OldFlag -> Bool
890 isAction OF_Config{} = False
891 isAction OF_Field{} = False
892 isAction OF_Input{} = False
893 isAction OF_AutoGHCiLibs{} = False
894 isAction OF_Force{} = False
895 isAction OF_DefinedName{} = False
896 isAction OF_GlobalConfig{} = False
899 oldFlags :: [OptDescr OldFlag]
901 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
902 "use the specified package config file",
903 Option ['l'] ["list-packages"] (NoArg OF_List)
904 "list packages in all config files",
905 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
906 "list packages in the specified config file",
907 Option ['a'] ["add-package"] (NoArg (OF_Add False))
909 Option ['u'] ["update-package"] (NoArg (OF_Add True))
910 "update package with new configuration",
911 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
912 "read new package info from specified file",
913 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
914 "show the configuration for package NAME",
915 Option [] ["field"] (ReqArg OF_Field "FIELD")
916 "(with --show-package) Show field FIELD only",
917 Option [] ["force"] (NoArg OF_Force)
918 "ignore missing directories/libraries",
919 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
920 "remove an installed package",
921 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
922 "automatically build libs for GHCi (with -a)",
923 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
924 "define NAME as VALUE",
925 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
926 "location of the global package config"
930 case break (=='=') str of
931 (nm,[]) -> OF_DefinedName nm []
932 (nm,_:val) -> OF_DefinedName nm val
934 oldRunit :: [OldFlag] -> IO ()
936 let new_flags = [ f | Just f <- map conv clis ]
938 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
939 conv (OF_Config f) = Just (FlagConfig f)
944 let fields = [ f | OF_Field f <- clis ]
946 let auto_ghci_libs = any isAuto clis
947 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
948 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
950 force = if OF_Force `elem` clis then ForceAll else NoForce
952 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
954 case [ c | c <- clis, isAction c ] of
955 [ OF_List ] -> listPackages new_flags Nothing
956 [ OF_ListLocal ] -> listPackages new_flags Nothing
958 registerPackage input_file defines new_flags auto_ghci_libs upd force
959 [ OF_Remove pkgid_str ] -> do
960 pkgid <- readPkgId pkgid_str
961 unregisterPackage pkgid new_flags
962 [ OF_Show pkgid_str ]
964 pkgid <- readPkgId pkgid_str
965 describePackage new_flags pkgid
967 pkgid <- readPkgId pkgid_str
968 mapM_ (describeField new_flags pkgid) fields
970 prog <- getProgramName
971 die (usageInfo (usageHeader prog) flags)
973 my_head :: String -> [a] -> a
974 my_head s [] = error s
977 -- ---------------------------------------------------------------------------
978 -- expanding environment variables in the package configuration
980 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
981 expandEnvVars str defines force = go str ""
983 go "" acc = return $! reverse acc
984 go ('$':'{':str) acc | (var, '}':rest) <- break close str
985 = do value <- lookupEnvVar var
986 go rest (reverse value ++ acc)
987 where close c = c == '}' || c == '\n' -- don't span newlines
991 lookupEnvVar :: String -> IO String
993 case lookup nm defines of
994 Just x | not (null x) -> return x
996 catch (System.getEnv nm)
997 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1001 -----------------------------------------------------------------------------
1003 getProgramName :: IO String
1004 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1005 where str `withoutSuffix` suff
1006 | suff `isSuffixOf` str = take (length str - length suff) str
1009 bye :: String -> IO a
1010 bye s = putStr s >> exitWith ExitSuccess
1012 die :: String -> IO a
1015 prog <- getProgramName
1016 hPutStrLn stderr (prog ++ ": " ++ s)
1017 exitWith (ExitFailure 1)
1019 dieOrForceAll :: Force -> String -> IO ()
1020 dieOrForceAll ForceAll s = ignoreError s
1021 dieOrForceAll _other s = dieForcible s
1023 dieOrForceFile :: Force -> String -> IO ()
1024 dieOrForceFile ForceAll s = ignoreError s
1025 dieOrForceFile ForceFiles s = ignoreError s
1026 dieOrForceFile _other s = dieForcible s
1028 ignoreError :: String -> IO ()
1029 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1031 dieForcible :: String -> IO ()
1032 dieForcible s = die (s ++ " (use --force to override)")
1034 -----------------------------------------
1035 -- Cut and pasted from ghc/compiler/SysTools
1037 #if defined(mingw32_HOST_OS)
1038 subst a b ls = map (\ x -> if x == a then b else x) ls
1039 unDosifyPath xs = subst '\\' '/' xs
1041 getExecDir :: String -> IO (Maybe String)
1042 -- (getExecDir cmd) returns the directory in which the current
1043 -- executable, which should be called 'cmd', is running
1044 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1045 -- you'll get "/a/b/c" back as the result
1047 = allocaArray len $ \buf -> do
1048 ret <- getModuleFileName nullPtr buf len
1049 if ret == 0 then return Nothing
1050 else do s <- peekCString buf
1051 return (Just (reverse (drop (length cmd)
1052 (reverse (unDosifyPath s)))))
1054 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1056 foreign import stdcall unsafe "GetModuleFileNameA"
1057 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1059 getExecDir :: String -> IO (Maybe String)
1060 getExecDir _ = return Nothing
1063 -- -----------------------------------------------------------------------------
1066 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
1067 -- It joins directory and file names to form a complete file path.
1069 -- The general rule is:
1071 -- > dir `joinFileName` basename == path
1073 -- > (dir,basename) = splitFileName path
1075 -- There might be an exceptions to the rule but in any case the
1076 -- reconstructed path will refer to the same object (file or directory).
1077 -- An example exception is that on Windows some slashes might be converted
1079 joinFileName :: String -> String -> FilePath
1080 joinFileName "" fname = fname
1081 joinFileName "." fname = fname
1082 joinFileName dir "" = dir
1083 joinFileName dir fname
1084 | isPathSeparator (last dir) = dir++fname
1085 | otherwise = dir++pathSeparator:fname
1087 -- | Checks whether the character is a valid path separator for the host
1088 -- platform. The valid character is a 'pathSeparator' but since the Windows
1089 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1090 -- checks for it on this platform, too.
1091 isPathSeparator :: Char -> Bool
1092 isPathSeparator ch = ch == pathSeparator || ch == '/'
1094 -- | Provides a platform-specific character used to separate directory levels in
1095 -- a path string that reflects a hierarchical file system organization. The
1096 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1097 -- (@\"\\\"@) on the Windows operating system.
1098 pathSeparator :: Char
1099 #ifdef mingw32_HOST_OS
1100 pathSeparator = '\\'
1105 getFilenameDir :: FilePath -> FilePath
1106 getFilenameDir fn = case break isPathSeparator (reverse fn) of
1108 (_, sep:ys) -> reverse ys
1110 -- | The function splits the given string to substrings
1111 -- using the 'searchPathSeparator'.
1112 parseSearchPath :: String -> [FilePath]
1113 parseSearchPath path = split path
1115 split :: String -> [String]
1119 _:rest -> chunk : split rest
1123 #ifdef mingw32_HOST_OS
1124 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1128 (chunk', rest') = break (==searchPathSeparator) s
1130 -- | A platform-specific character used to separate search path strings in
1131 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh,
1132 -- and a semicolon (\";\") on the Windows operating system.
1133 searchPathSeparator :: Char
1134 #if mingw32_HOST_OS || mingw32_TARGET_OS
1135 searchPathSeparator = ';'
1137 searchPathSeparator = ':'