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 ++ deprecFlags) 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 ['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",
127 Option [] ["names-only"] (NoArg FlagNamesOnly)
128 "only print package names, not versions; can only be used with list --simple-output"
131 deprecFlags :: [OptDescr Flag]
133 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
134 "define NAME as VALUE"
138 case break (=='=') str of
139 (nm,[]) -> FlagDefinedName nm []
140 (nm,_:val) -> FlagDefinedName nm val
142 ourCopyright :: String
143 ourCopyright = "GHC package manager version " ++ version ++ "\n"
145 usageHeader :: String -> String
146 usageHeader prog = substProg prog $
148 " $p register {filename | -}\n" ++
149 " Register the package using the specified installed package\n" ++
150 " description. The syntax for the latter is given in the $p\n" ++
151 " documentation.\n" ++
153 " $p update {filename | -}\n" ++
154 " Register the package, overwriting any other package with the\n" ++
157 " $p unregister {pkg-id}\n" ++
158 " Unregister the specified package.\n" ++
160 " $p expose {pkg-id}\n" ++
161 " Expose the specified package.\n" ++
163 " $p hide {pkg-id}\n" ++
164 " Hide the specified package.\n" ++
166 " $p list [pkg]\n" ++
167 " List registered packages in the global database, and also the\n" ++
168 " user database if --user is given. If a package name is given\n" ++
169 " all the registered versions will be listed in ascending order.\n" ++
170 " Accepts the --simple-output flag.\n" ++
172 " $p latest pkg\n" ++
173 " Prints the highest registered version of a package.\n" ++
176 " Check the consistency of package depenencies and list broken packages.\n" ++
177 " Accepts the --simple-output flag.\n" ++
179 " $p describe {pkg-id}\n" ++
180 " Give the registered description for the specified package. The\n" ++
181 " description is returned in precisely the syntax required by $p\n" ++
184 " $p field {pkg-id} {field}\n" ++
185 " Extract the specified field of the package description for the\n" ++
186 " specified package.\n" ++
188 " The following optional flags are also accepted:\n"
190 substProg :: String -> String -> String
192 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
193 substProg prog (c:xs) = c : substProg prog xs
195 -- -----------------------------------------------------------------------------
198 data Force = ForceAll | ForceFiles | NoForce
200 runit :: [Flag] -> [String] -> IO ()
201 runit cli nonopts = do
202 prog <- getProgramName
205 | FlagForce `elem` cli = ForceAll
206 | FlagForceFiles `elem` cli = ForceFiles
207 | otherwise = NoForce
208 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
209 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
211 -- first, parse the command
213 ["register", filename] ->
214 registerPackage filename defines cli auto_ghci_libs False force
215 ["update", filename] ->
216 registerPackage filename defines cli auto_ghci_libs True force
217 ["unregister", pkgid_str] -> do
218 pkgid <- readGlobPkgId pkgid_str
219 unregisterPackage pkgid cli
220 ["expose", pkgid_str] -> do
221 pkgid <- readGlobPkgId pkgid_str
222 exposePackage pkgid cli
223 ["hide", pkgid_str] -> do
224 pkgid <- readGlobPkgId pkgid_str
225 hidePackage pkgid cli
227 listPackages cli Nothing
228 ["list", pkgid_str] -> do
229 pkgid <- readGlobPkgId pkgid_str
230 listPackages cli (Just pkgid)
231 ["latest", pkgid_str] -> do
232 pkgid <- readGlobPkgId pkgid_str
233 latestPackage cli pkgid
234 ["describe", pkgid_str] -> do
235 pkgid <- readGlobPkgId pkgid_str
236 describePackage cli pkgid
237 ["field", pkgid_str, field] -> do
238 pkgid <- readGlobPkgId pkgid_str
239 describeField cli pkgid field
243 die ("missing command\n" ++
244 usageInfo (usageHeader prog) flags)
246 die ("command-line syntax error\n" ++
247 usageInfo (usageHeader prog) flags)
249 parseCheck :: ReadP a a -> String -> String -> IO a
250 parseCheck parser str what =
251 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
253 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
255 readPkgId :: String -> IO PackageIdentifier
256 readPkgId str = parseCheck parsePackageId str "package identifier"
258 readGlobPkgId :: String -> IO PackageIdentifier
259 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
261 parseGlobPackageId :: ReadP r PackageIdentifier
265 (do n <- parsePackageName; string "-*"
266 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
268 -- globVersion means "all versions"
269 globVersion :: Version
270 globVersion = Version{ versionBranch=[], versionTags=["*"] }
272 -- -----------------------------------------------------------------------------
275 -- Some commands operate on a single database:
276 -- register, unregister, expose, hide
277 -- however these commands also check the union of the available databases
278 -- in order to check consistency. For example, register will check that
279 -- dependencies exist before registering a package.
281 -- Some commands operate on multiple databases, with overlapping semantics:
282 -- list, describe, field
284 type PackageDBName = FilePath
285 type PackageDB = [InstalledPackageInfo]
287 type PackageDBStack = [(PackageDBName,PackageDB)]
288 -- A stack of package databases. Convention: head is the topmost
289 -- in the stack. Earlier entries override later one.
291 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
292 getPkgDatabases modify flags = do
293 -- first we determine the location of the global package config. On Windows,
294 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
295 -- location is passed to the binary using the --global-config flag by the
297 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
299 case [ f | FlagGlobalConfig f <- flags ] of
300 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
302 Nothing -> die err_msg
303 Just dir -> return (dir </> "package.conf")
304 fs -> return (last fs)
306 let global_conf_dir = global_conf ++ ".d"
307 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
309 if global_conf_dir_exists
310 then do files <- getDirectoryContents global_conf_dir
311 return [ global_conf_dir ++ '/' : file
313 , isSuffixOf ".conf" file]
316 -- get the location of the user package database, and create it if necessary
317 appdir <- getAppUserDataDirectory "ghc"
320 subdir = targetARCH ++ '-':targetOS ++ '-':version
321 archdir = appdir </> subdir
322 user_conf = archdir </> "package.conf"
323 user_exists <- doesFileExist user_conf
325 -- If the user database doesn't exist, and this command isn't a
326 -- "modify" command, then we won't attempt to create or use it.
328 | modify || user_exists = user_conf : global_confs ++ [global_conf]
329 | otherwise = global_confs ++ [global_conf]
331 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
334 Left _ -> sys_databases
336 | last cs == "" -> init cs ++ sys_databases
338 where cs = splitSearchPath path
340 -- The "global" database is always the one at the bottom of the stack.
341 -- This is the database we modify by default.
342 virt_global_conf = last env_stack
344 -- -f flags on the command line add to the database stack, unless any
345 -- of them are present in the stack already.
346 let flag_stack = filter (`notElem` env_stack)
347 [ f | FlagConfig f <- reverse flags ] ++ env_stack
349 -- Now we have the full stack of databases. Next, if the current
350 -- command is a "modify" type command, then we truncate the stack
351 -- so that the topmost element is the database being modified.
354 then return flag_stack
356 go (FlagUser : fs) = modifying user_conf
357 go (FlagGlobal : fs) = modifying virt_global_conf
358 go (FlagConfig f : fs) = modifying f
360 go [] = modifying virt_global_conf
363 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
364 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
368 db_stack <- mapM readParseDatabase final_stack
371 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
372 readParseDatabase filename = do
373 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
374 let packages = read str
375 Exception.evaluate packages
376 `Exception.catch` \_ ->
377 die (filename ++ ": parse error in package config file")
378 return (filename,packages)
380 emptyPackageConfig :: String
381 emptyPackageConfig = "[]"
383 -- -----------------------------------------------------------------------------
386 registerPackage :: FilePath
387 -> [(String,String)] -- defines
389 -> Bool -- auto_ghci_libs
393 registerPackage input defines flags auto_ghci_libs update force = do
394 db_stack <- getPkgDatabases True flags
396 db_to_operate_on = my_head "db" db_stack
397 db_filename = fst db_to_operate_on
403 putStr "Reading package info from stdin ... "
406 putStr ("Reading package info from " ++ show f ++ " ... ")
409 expanded <- expandEnvVars s defines force
411 pkg0 <- parsePackageInfo expanded defines
414 pkg <- resolveDeps db_stack pkg0
415 validatePackageConfig pkg db_stack auto_ghci_libs update force
416 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
417 not_this p = package p /= package pkg
418 savingOldConfig db_filename $
419 writeNewConfig db_filename new_details
424 -> IO InstalledPackageInfo
425 parsePackageInfo str defines =
426 case parseInstalledPackageInfo str of
427 ParseOk _warns ok -> return ok
428 ParseFailed err -> case locatedErrorMsg err of
429 (Nothing, s) -> die s
430 (Just l, s) -> die (show l ++ ": " ++ s)
432 -- -----------------------------------------------------------------------------
433 -- Exposing, Hiding, Unregistering are all similar
435 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
436 exposePackage = modifyPackage (\p -> [p{exposed=True}])
438 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
439 hidePackage = modifyPackage (\p -> [p{exposed=False}])
441 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
442 unregisterPackage = modifyPackage (\p -> [])
445 :: (InstalledPackageInfo -> [InstalledPackageInfo])
449 modifyPackage fn pkgid flags = do
450 db_stack <- getPkgDatabases True{-modify-} flags
451 let ((db_name, pkgs) : _) = db_stack
452 ps <- findPackages [(db_name,pkgs)] pkgid
453 let pids = map package ps
454 let new_config = concat (map modify pkgs)
456 | package pkg `elem` pids = fn pkg
458 savingOldConfig db_name $
459 writeNewConfig db_name new_config
461 -- -----------------------------------------------------------------------------
464 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
465 listPackages flags mPackageName = do
466 let simple_output = FlagSimpleOutput `elem` flags
467 db_stack <- getPkgDatabases False flags
468 let db_stack_filtered -- if a package is given, filter out all other packages
469 | Just this <- mPackageName =
470 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
472 | otherwise = db_stack
475 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
476 where sort_pkgs = sortBy cmpPkgIds
477 cmpPkgIds pkg1 pkg2 =
478 case pkgName p1 `compare` pkgName p2 of
481 EQ -> pkgVersion p1 `compare` pkgVersion p2
482 where (p1,p2) = (package pkg1, package pkg2)
484 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
485 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
487 show_func (reverse db_stack_sorted)
489 where show_normal pkg_map (db_name,pkg_confs) =
490 hPutStrLn stdout (render $
491 text db_name <> colon $$ nest 4 packages
493 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
495 | isBrokenPackage p pkg_map = braces doc
497 | otherwise = parens doc
498 where doc = text (showPackageId (package p))
500 show_simple db_stack = do
501 let showPkg = if FlagNamesOnly `elem` flags then pkgName
503 pkgs = map showPkg $ sortBy compPkgIdVer $
504 map package (concatMap snd db_stack)
505 when (null pkgs) $ die "no matches"
506 hPutStrLn stdout $ concat $ intersperse " " pkgs
508 -- -----------------------------------------------------------------------------
509 -- Prints the highest (hidden or exposed) version of a package
511 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
512 latestPackage flags pkgid = do
513 db_stack <- getPkgDatabases False flags
514 ps <- findPackages db_stack pkgid
515 show_pkg (sortBy compPkgIdVer (map package ps))
517 show_pkg [] = die "no matches"
518 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
520 -- -----------------------------------------------------------------------------
523 describePackage :: [Flag] -> PackageIdentifier -> IO ()
524 describePackage flags pkgid = do
525 db_stack <- getPkgDatabases False flags
526 ps <- findPackages db_stack pkgid
527 mapM_ (putStrLn . showInstalledPackageInfo) ps
529 -- PackageId is can have globVersion for the version
530 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
531 findPackages db_stack pkgid
532 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
533 [] -> die ("cannot find package " ++ showPackageId pkgid)
536 all_pkgs = concat (map snd db_stack)
538 matches :: PackageIdentifier -> PackageIdentifier -> Bool
540 = (pkgName pid == pkgName pid')
541 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
543 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
544 pid `matchesPkg` pkg = pid `matches` package pkg
546 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
547 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
549 -- -----------------------------------------------------------------------------
552 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
553 describeField flags pkgid field = do
554 db_stack <- getPkgDatabases False flags
555 case toField field of
556 Nothing -> die ("unknown field: " ++ field)
558 ps <- findPackages db_stack pkgid
559 let top_dir = takeDirectory (fst (last db_stack))
560 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
562 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
563 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
564 -- with the current topdir (obtained from the -B option).
565 mungePackagePaths top_dir ps = map munge_pkg ps
567 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
568 includeDirs = munge_paths (includeDirs p),
569 libraryDirs = munge_paths (libraryDirs p),
570 frameworkDirs = munge_paths (frameworkDirs p),
571 haddockInterfaces = munge_paths (haddockInterfaces p),
572 haddockHTMLs = munge_paths (haddockHTMLs p)
575 munge_paths = map munge_path
578 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
579 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
582 toHttpPath p = "file:///" ++ p
584 maybePrefixMatch :: String -> String -> Maybe String
585 maybePrefixMatch [] rest = Just rest
586 maybePrefixMatch (_:_) [] = Nothing
587 maybePrefixMatch (p:pat) (r:rest)
588 | p == r = maybePrefixMatch pat rest
589 | otherwise = Nothing
591 toField :: String -> Maybe (InstalledPackageInfo -> String)
592 -- backwards compatibility:
593 toField "import_dirs" = Just $ strList . importDirs
594 toField "source_dirs" = Just $ strList . importDirs
595 toField "library_dirs" = Just $ strList . libraryDirs
596 toField "hs_libraries" = Just $ strList . hsLibraries
597 toField "extra_libraries" = Just $ strList . extraLibraries
598 toField "include_dirs" = Just $ strList . includeDirs
599 toField "c_includes" = Just $ strList . includes
600 toField "package_deps" = Just $ strList . map showPackageId. depends
601 toField "extra_cc_opts" = Just $ strList . ccOptions
602 toField "extra_ld_opts" = Just $ strList . ldOptions
603 toField "framework_dirs" = Just $ strList . frameworkDirs
604 toField "extra_frameworks"= Just $ strList . frameworks
605 toField s = showInstalledPackageInfoField s
607 strList :: [String] -> String
611 -- -----------------------------------------------------------------------------
612 -- Check: Check consistency of installed packages
614 checkConsistency :: [Flag] -> IO ()
615 checkConsistency flags = do
616 db_stack <- getPkgDatabases False flags
617 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
620 let broken_deps = missingPackageDeps p pkgs
621 guard (not . null $ broken_deps)
622 return (pid, broken_deps)
623 mapM_ (putStrLn . render . show_func) broken_pkgs
625 show_func | FlagSimpleOutput `elem` flags = show_simple
626 | otherwise = show_normal
627 show_simple (pid,deps) =
628 text (showPackageId pid) <> colon
629 <+> fsep (punctuate comma (map (text . showPackageId) deps))
630 show_normal (pid,deps) =
631 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
632 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
634 missingPackageDeps :: InstalledPackageInfo
635 -> [(PackageIdentifier, InstalledPackageInfo)]
636 -> [PackageIdentifier]
637 missingPackageDeps pkg pkg_map =
638 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
639 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
641 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
642 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
645 -- -----------------------------------------------------------------------------
646 -- Manipulating package.conf files
648 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
649 writeNewConfig filename packages = do
650 hPutStr stdout "Writing new package config file... "
651 createDirectoryIfMissing True $ takeDirectory filename
652 h <- openFile filename WriteMode `catch` \e ->
653 if isPermissionError e
654 then die (filename ++ ": you don't have permission to modify this file")
656 let shown = concat $ intersperse ",\n " $ map show packages
657 fileContents = "[" ++ shown ++ "\n]"
658 hPutStrLn h fileContents
660 hPutStrLn stdout "done."
662 savingOldConfig :: FilePath -> IO () -> IO ()
663 savingOldConfig filename io = Exception.block $ do
664 hPutStr stdout "Saving old package config file... "
665 -- mv rather than cp because we've already done an hGetContents
666 -- on this file so we won't be able to open it for writing
667 -- unless we move the old one out of the way...
668 let oldFile = filename ++ ".old"
669 restore_on_error <- catch (renameFile filename oldFile >> return True) $
671 unless (isDoesNotExistError err) $ do
672 hPutStrLn stderr (unwords ["Unable to rename", show filename,
676 hPutStrLn stdout "done."
678 hPutStrLn stderr (show e)
679 hPutStr stdout ("\nWARNING: an error was encountered while writing"
680 ++ "the new configuration.\n")
681 when restore_on_error $ do
682 hPutStr stdout "Attempting to restore the old configuration..."
683 do renameFile oldFile filename
684 hPutStrLn stdout "done."
685 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
688 -----------------------------------------------------------------------------
689 -- Sanity-check a new package config, and automatically build GHCi libs
692 validatePackageConfig :: InstalledPackageInfo
694 -> Bool -- auto-ghc-libs
698 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
700 checkDuplicates db_stack pkg update
701 mapM_ (checkDep db_stack force) (depends pkg)
702 mapM_ (checkDir force) (importDirs pkg)
703 mapM_ (checkDir force) (libraryDirs pkg)
704 mapM_ (checkDir force) (includeDirs pkg)
705 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
706 -- ToDo: check these somehow?
707 -- extra_libraries :: [String],
708 -- c_includes :: [String],
710 -- When the package name and version are put together, sometimes we can
711 -- end up with a package id that cannot be parsed. This will lead to
712 -- difficulties when the user wants to refer to the package later, so
713 -- we check that the package id can be parsed properly here.
714 checkPackageId :: InstalledPackageInfo -> IO ()
716 let str = showPackageId (package ipi) in
717 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
719 [] -> die ("invalid package identifier: " ++ str)
720 _ -> die ("ambiguous package identifier: " ++ str)
722 -- ToDo: remove this (see #1837)
723 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> IO InstalledPackageInfo
724 resolveDeps db_stack p = do
725 when (not (null unversioned_deps)) $
726 hPutStr stderr ("WARNING: unversioned dependencies are deprecated, "++
727 "and will NOT be accepted by GHC 6.10: " ++
728 unwords (map showPackageId unversioned_deps) ++ "\n")
729 return (updateDeps p)
731 unversioned_deps = filter (not.realVersion) (depends p)
733 -- The input package spec is allowed to give a package dependency
734 -- without a version number; e.g.
736 -- Here, we update these dependencies without version numbers to
737 -- match the actual versions of the relevant packages installed.
738 updateDeps p = p{depends = map resolveDep (depends p)}
741 | realVersion dep_pkgid = dep_pkgid
742 | otherwise = lookupDep dep_pkgid
746 name = pkgName dep_pkgid
748 case [ pid | p <- concat (map snd db_stack),
750 pkgName pid == name ] of
751 (pid:_) -> pid -- Found installed package,
752 -- replete with its version
753 [] -> dep_pkgid -- No installed package; use
754 -- the version-less one
756 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
757 checkDuplicates db_stack pkg update = do
760 (_top_db_name, pkgs) : _ = db_stack
762 -- Check whether this package id already exists in this DB
764 when (not update && (pkgid `elem` map package pkgs)) $
765 die ("package " ++ showPackageId pkgid ++ " is already installed")
769 checkDir :: Force -> String -> IO ()
771 | "$topdir" `isPrefixOf` d = return ()
772 | "$httptopdir" `isPrefixOf` d = return ()
773 -- can't check these, because we don't know what $(http)topdir is
775 there <- doesDirectoryExist d
777 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
779 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
780 checkDep db_stack force pkgid
781 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
782 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
785 -- for backwards compat, we treat 0.0 as a special version,
786 -- and don't check that it actually exists.
787 real_version = realVersion pkgid
789 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
792 all_pkgs = concat (map snd db_stack)
793 pkgids = map package all_pkgs
795 realVersion :: PackageIdentifier -> Bool
796 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
798 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
799 checkHSLib dirs auto_ghci_libs force lib = do
800 let batch_lib_file = "lib" ++ lib ++ ".a"
801 bs <- mapM (doesLibExistIn batch_lib_file) dirs
802 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
803 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
805 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
807 doesLibExistIn :: String -> String -> IO Bool
809 | "$topdir" `isPrefixOf` d = return True
810 | "$httptopdir" `isPrefixOf` d = return True
811 | otherwise = doesFileExist (d ++ '/':lib)
813 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
814 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
815 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
817 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
818 case [dir | (exists,dir) <- zip bs dirs, exists] of
819 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
822 ghci_lib_file = lib ++ ".o"
824 -- automatically build the GHCi version of a batch lib,
825 -- using ld --whole-archive.
827 autoBuildGHCiLib :: String -> String -> String -> IO ()
828 autoBuildGHCiLib dir batch_file ghci_file = do
829 let ghci_lib_file = dir ++ '/':ghci_file
830 batch_lib_file = dir ++ '/':batch_file
831 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
832 #if defined(darwin_HOST_OS)
833 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
834 #elif defined(mingw32_HOST_OS)
835 execDir <- getExecDir "/bin/ghc-pkg.exe"
836 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
838 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
840 when (r /= ExitSuccess) $ exitWith r
841 hPutStrLn stderr (" done.")
843 -- -----------------------------------------------------------------------------
844 -- Searching for modules
848 findModules :: [FilePath] -> IO [String]
850 mms <- mapM searchDir paths
853 searchDir path prefix = do
854 fs <- getDirectoryEntries path `catch` \_ -> return []
855 searchEntries path prefix fs
857 searchEntries path prefix [] = return []
858 searchEntries path prefix (f:fs)
859 | looks_like_a_module = do
860 ms <- searchEntries path prefix fs
861 return (prefix `joinModule` f : ms)
862 | looks_like_a_component = do
863 ms <- searchDir (path </> f) (prefix `joinModule` f)
864 ms' <- searchEntries path prefix fs
867 searchEntries path prefix fs
870 (base,suffix) = splitFileExt f
871 looks_like_a_module =
872 suffix `elem` haskell_suffixes &&
873 all okInModuleName base
874 looks_like_a_component =
875 null suffix && all okInModuleName base
881 -- -----------------------------------------------------------------------------
882 -- The old command-line syntax, supported for backwards compatibility
889 | OF_Add Bool {- True => replace existing info -}
890 | OF_Remove String | OF_Show String
891 | OF_Field String | OF_AutoGHCiLibs | OF_Force
892 | OF_DefinedName String String
893 | OF_GlobalConfig FilePath
896 isAction :: OldFlag -> Bool
897 isAction OF_Config{} = False
898 isAction OF_Field{} = False
899 isAction OF_Input{} = False
900 isAction OF_AutoGHCiLibs{} = False
901 isAction OF_Force{} = False
902 isAction OF_DefinedName{} = False
903 isAction OF_GlobalConfig{} = False
906 oldFlags :: [OptDescr OldFlag]
908 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
909 "use the specified package config file",
910 Option ['l'] ["list-packages"] (NoArg OF_List)
911 "list packages in all config files",
912 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
913 "list packages in the specified config file",
914 Option ['a'] ["add-package"] (NoArg (OF_Add False))
916 Option ['u'] ["update-package"] (NoArg (OF_Add True))
917 "update package with new configuration",
918 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
919 "read new package info from specified file",
920 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
921 "show the configuration for package NAME",
922 Option [] ["field"] (ReqArg OF_Field "FIELD")
923 "(with --show-package) Show field FIELD only",
924 Option [] ["force"] (NoArg OF_Force)
925 "ignore missing directories/libraries",
926 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
927 "remove an installed package",
928 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
929 "automatically build libs for GHCi (with -a)",
930 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
931 "define NAME as VALUE",
932 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
933 "location of the global package config"
937 case break (=='=') str of
938 (nm,[]) -> OF_DefinedName nm []
939 (nm,_:val) -> OF_DefinedName nm val
941 oldRunit :: [OldFlag] -> IO ()
943 let new_flags = [ f | Just f <- map conv clis ]
945 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
946 conv (OF_Config f) = Just (FlagConfig f)
951 let fields = [ f | OF_Field f <- clis ]
953 let auto_ghci_libs = any isAuto clis
954 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
955 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
957 force = if OF_Force `elem` clis then ForceAll else NoForce
959 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
961 case [ c | c <- clis, isAction c ] of
962 [ OF_List ] -> listPackages new_flags Nothing
963 [ OF_ListLocal ] -> listPackages new_flags Nothing
965 registerPackage input_file defines new_flags auto_ghci_libs upd force
966 [ OF_Remove pkgid_str ] -> do
967 pkgid <- readPkgId pkgid_str
968 unregisterPackage pkgid new_flags
969 [ OF_Show pkgid_str ]
971 pkgid <- readPkgId pkgid_str
972 describePackage new_flags pkgid
974 pkgid <- readPkgId pkgid_str
975 mapM_ (describeField new_flags pkgid) fields
977 prog <- getProgramName
978 die (usageInfo (usageHeader prog) flags)
980 my_head :: String -> [a] -> a
981 my_head s [] = error s
984 -- ---------------------------------------------------------------------------
985 -- expanding environment variables in the package configuration
987 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
988 expandEnvVars str defines force = go str ""
990 go "" acc = return $! reverse acc
991 go ('$':'{':str) acc | (var, '}':rest) <- break close str
992 = do value <- lookupEnvVar var
993 go rest (reverse value ++ acc)
994 where close c = c == '}' || c == '\n' -- don't span newlines
998 lookupEnvVar :: String -> IO String
1000 case lookup nm defines of
1001 Just x | not (null x) -> return x
1003 catch (System.getEnv nm)
1004 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1008 -----------------------------------------------------------------------------
1010 getProgramName :: IO String
1011 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1012 where str `withoutSuffix` suff
1013 | suff `isSuffixOf` str = take (length str - length suff) str
1016 bye :: String -> IO a
1017 bye s = putStr s >> exitWith ExitSuccess
1019 die :: String -> IO a
1022 prog <- getProgramName
1023 hPutStrLn stderr (prog ++ ": " ++ s)
1024 exitWith (ExitFailure 1)
1026 dieOrForceAll :: Force -> String -> IO ()
1027 dieOrForceAll ForceAll s = ignoreError s
1028 dieOrForceAll _other s = dieForcible s
1030 dieOrForceFile :: Force -> String -> IO ()
1031 dieOrForceFile ForceAll s = ignoreError s
1032 dieOrForceFile ForceFiles s = ignoreError s
1033 dieOrForceFile _other s = dieForcible s
1035 ignoreError :: String -> IO ()
1036 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1038 dieForcible :: String -> IO ()
1039 dieForcible s = die (s ++ " (use --force to override)")
1041 -----------------------------------------
1042 -- Cut and pasted from ghc/compiler/SysTools
1044 #if defined(mingw32_HOST_OS)
1045 subst :: Char -> Char -> String -> String
1046 subst a b ls = map (\ x -> if x == a then b else x) ls
1048 unDosifyPath :: FilePath -> FilePath
1049 unDosifyPath xs = subst '\\' '/' xs
1051 getExecDir :: String -> IO (Maybe String)
1052 -- (getExecDir cmd) returns the directory in which the current
1053 -- executable, which should be called 'cmd', is running
1054 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1055 -- you'll get "/a/b/c" back as the result
1057 = allocaArray len $ \buf -> do
1058 ret <- getModuleFileName nullPtr buf len
1059 if ret == 0 then return Nothing
1060 else do s <- peekCString buf
1061 return (Just (reverse (drop (length cmd)
1062 (reverse (unDosifyPath s)))))
1064 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1066 foreign import stdcall unsafe "GetModuleFileNameA"
1067 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1069 getExecDir :: String -> IO (Maybe String)
1070 getExecDir _ = return Nothing