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