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 Nothing
228 ["list", pkgid_str] -> do
229 pkgid <- readGlobPkgId pkgid_str
230 listPackages cli (Just pkgid) Nothing
231 ["find-module", moduleName] -> do
232 listPackages cli Nothing (Just moduleName)
233 ["latest", pkgid_str] -> do
234 pkgid <- readGlobPkgId pkgid_str
235 latestPackage cli pkgid
236 ["describe", pkgid_str] -> do
237 pkgid <- readGlobPkgId pkgid_str
238 describePackage cli pkgid
239 ["field", pkgid_str, field] -> do
240 pkgid <- readGlobPkgId pkgid_str
241 describeField cli pkgid field
245 die ("missing command\n" ++
246 usageInfo (usageHeader prog) flags)
248 die ("command-line syntax error\n" ++
249 usageInfo (usageHeader prog) flags)
251 parseCheck :: ReadP a a -> String -> String -> IO a
252 parseCheck parser str what =
253 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
255 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
257 readPkgId :: String -> IO PackageIdentifier
258 readPkgId str = parseCheck parsePackageId str "package identifier"
260 readGlobPkgId :: String -> IO PackageIdentifier
261 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
263 parseGlobPackageId :: ReadP r PackageIdentifier
267 (do n <- parsePackageName; string "-*"
268 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
270 -- globVersion means "all versions"
271 globVersion :: Version
272 globVersion = Version{ versionBranch=[], versionTags=["*"] }
274 -- -----------------------------------------------------------------------------
277 -- Some commands operate on a single database:
278 -- register, unregister, expose, hide
279 -- however these commands also check the union of the available databases
280 -- in order to check consistency. For example, register will check that
281 -- dependencies exist before registering a package.
283 -- Some commands operate on multiple databases, with overlapping semantics:
284 -- list, describe, field
286 type PackageDBName = FilePath
287 type PackageDB = [InstalledPackageInfo]
289 type PackageDBStack = [(PackageDBName,PackageDB)]
290 -- A stack of package databases. Convention: head is the topmost
291 -- in the stack. Earlier entries override later one.
293 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
294 getPkgDatabases modify flags = do
295 -- first we determine the location of the global package config. On Windows,
296 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
297 -- location is passed to the binary using the --global-config flag by the
299 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
301 case [ f | FlagGlobalConfig f <- flags ] of
302 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
304 Nothing -> die err_msg
305 Just dir -> return (dir </> "package.conf")
306 fs -> return (last fs)
308 let global_conf_dir = global_conf ++ ".d"
309 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
311 if global_conf_dir_exists
312 then do files <- getDirectoryContents global_conf_dir
313 return [ global_conf_dir ++ '/' : file
315 , isSuffixOf ".conf" file]
318 -- get the location of the user package database, and create it if necessary
319 appdir <- getAppUserDataDirectory "ghc"
322 subdir = targetARCH ++ '-':targetOS ++ '-':version
323 archdir = appdir </> subdir
324 user_conf = archdir </> "package.conf"
325 user_exists <- doesFileExist user_conf
327 -- If the user database doesn't exist, and this command isn't a
328 -- "modify" command, then we won't attempt to create or use it.
330 | modify || user_exists = user_conf : global_confs ++ [global_conf]
331 | otherwise = global_confs ++ [global_conf]
333 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
336 Left _ -> sys_databases
338 | last cs == "" -> init cs ++ sys_databases
340 where cs = splitSearchPath path
342 -- The "global" database is always the one at the bottom of the stack.
343 -- This is the database we modify by default.
344 virt_global_conf = last env_stack
346 -- -f flags on the command line add to the database stack, unless any
347 -- of them are present in the stack already.
348 let flag_stack = filter (`notElem` env_stack)
349 [ f | FlagConfig f <- reverse flags ] ++ env_stack
351 -- Now we have the full stack of databases. Next, if the current
352 -- command is a "modify" type command, then we truncate the stack
353 -- so that the topmost element is the database being modified.
356 then return flag_stack
358 go (FlagUser : fs) = modifying user_conf
359 go (FlagGlobal : fs) = modifying virt_global_conf
360 go (FlagConfig f : fs) = modifying f
362 go [] = modifying virt_global_conf
365 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
366 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
370 db_stack <- mapM readParseDatabase final_stack
373 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
374 readParseDatabase filename = do
375 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
376 let packages = read str
377 Exception.evaluate packages
378 `Exception.catch` \_ ->
379 die (filename ++ ": parse error in package config file")
380 return (filename,packages)
382 emptyPackageConfig :: String
383 emptyPackageConfig = "[]"
385 -- -----------------------------------------------------------------------------
388 registerPackage :: FilePath
389 -> [(String,String)] -- defines
391 -> Bool -- auto_ghci_libs
395 registerPackage input defines flags auto_ghci_libs update force = do
396 db_stack <- getPkgDatabases True flags
398 db_to_operate_on = my_head "db" db_stack
399 db_filename = fst db_to_operate_on
405 putStr "Reading package info from stdin ... "
408 putStr ("Reading package info from " ++ show f ++ " ... ")
411 expanded <- expandEnvVars s defines force
413 pkg0 <- parsePackageInfo expanded defines
416 pkg <- resolveDeps db_stack pkg0
417 validatePackageConfig pkg db_stack auto_ghci_libs update force
418 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
419 not_this p = package p /= package pkg
420 savingOldConfig db_filename $
421 writeNewConfig db_filename new_details
426 -> IO InstalledPackageInfo
427 parsePackageInfo str defines =
428 case parseInstalledPackageInfo str of
429 ParseOk _warns ok -> return ok
430 ParseFailed err -> case locatedErrorMsg err of
431 (Nothing, s) -> die s
432 (Just l, s) -> die (show l ++ ": " ++ s)
434 -- -----------------------------------------------------------------------------
435 -- Exposing, Hiding, Unregistering are all similar
437 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
438 exposePackage = modifyPackage (\p -> [p{exposed=True}])
440 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
441 hidePackage = modifyPackage (\p -> [p{exposed=False}])
443 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
444 unregisterPackage = modifyPackage (\p -> [])
447 :: (InstalledPackageInfo -> [InstalledPackageInfo])
451 modifyPackage fn pkgid flags = do
452 db_stack <- getPkgDatabases True{-modify-} flags
453 let ((db_name, pkgs) : _) = db_stack
454 ps <- findPackages [(db_name,pkgs)] pkgid
455 let pids = map package ps
456 let new_config = concat (map modify pkgs)
458 | package pkg `elem` pids = fn pkg
460 savingOldConfig db_name $
461 writeNewConfig db_name new_config
463 -- -----------------------------------------------------------------------------
466 listPackages :: [Flag] -> Maybe PackageIdentifier -> Maybe String -> IO ()
467 listPackages flags mPackageName mModuleName = do
468 let simple_output = FlagSimpleOutput `elem` flags
469 db_stack <- getPkgDatabases False flags
470 let db_stack_filtered -- if a package is given, filter out all other packages
471 | Just this <- mPackageName =
472 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
474 | Just this <- mModuleName = -- packages which expose mModuleName
475 map (\(conf,pkgs) -> (conf, filter (this `exposedInPkg`) pkgs))
477 | otherwise = db_stack
480 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
481 where sort_pkgs = sortBy cmpPkgIds
482 cmpPkgIds pkg1 pkg2 =
483 case pkgName p1 `compare` pkgName p2 of
486 EQ -> pkgVersion p1 `compare` pkgVersion p2
487 where (p1,p2) = (package pkg1, package pkg2)
489 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
490 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
492 show_func (reverse db_stack_sorted)
494 where show_normal pkg_map (db_name,pkg_confs) =
495 hPutStrLn stdout (render $
496 text db_name <> colon $$ nest 4 packages
498 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
500 | isBrokenPackage p pkg_map = braces doc
502 | otherwise = parens doc
503 where doc = text (showPackageId (package p))
505 show_simple db_stack = do
506 let showPkg = if FlagNamesOnly `elem` flags then pkgName
508 pkgs = map showPkg $ sortBy compPkgIdVer $
509 map package (concatMap snd db_stack)
510 when (null pkgs) $ die "no matches"
511 hPutStrLn stdout $ concat $ intersperse " " pkgs
513 -- -----------------------------------------------------------------------------
514 -- Prints the highest (hidden or exposed) version of a package
516 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
517 latestPackage flags pkgid = do
518 db_stack <- getPkgDatabases False flags
519 ps <- findPackages db_stack pkgid
520 show_pkg (sortBy compPkgIdVer (map package ps))
522 show_pkg [] = die "no matches"
523 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
525 -- -----------------------------------------------------------------------------
528 describePackage :: [Flag] -> PackageIdentifier -> IO ()
529 describePackage flags pkgid = do
530 db_stack <- getPkgDatabases False flags
531 ps <- findPackages db_stack pkgid
532 mapM_ (putStrLn . showInstalledPackageInfo) ps
534 -- PackageId is can have globVersion for the version
535 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
536 findPackages db_stack pkgid
537 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
538 [] -> die ("cannot find package " ++ showPackageId pkgid)
541 all_pkgs = concat (map snd db_stack)
543 matches :: PackageIdentifier -> PackageIdentifier -> Bool
545 = (pkgName pid == pkgName pid')
546 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
548 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
549 pid `matchesPkg` pkg = pid `matches` package pkg
551 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
552 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
554 exposedInPkg :: String -> InstalledPackageInfo -> Bool
555 moduleName `exposedInPkg` pkg = moduleName `elem` exposedModules pkg
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 = takeDirectory (fst (last db_stack))
568 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
570 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
571 -- Replace the strings "$topdir" and "$httptopdir" 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'
587 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
590 toHttpPath p = "file:///" ++ p
592 maybePrefixMatch :: String -> String -> Maybe String
593 maybePrefixMatch [] rest = Just rest
594 maybePrefixMatch (_:_) [] = Nothing
595 maybePrefixMatch (p:pat) (r:rest)
596 | p == r = maybePrefixMatch pat rest
597 | otherwise = Nothing
599 toField :: String -> Maybe (InstalledPackageInfo -> String)
600 -- backwards compatibility:
601 toField "import_dirs" = Just $ strList . importDirs
602 toField "source_dirs" = Just $ strList . importDirs
603 toField "library_dirs" = Just $ strList . libraryDirs
604 toField "hs_libraries" = Just $ strList . hsLibraries
605 toField "extra_libraries" = Just $ strList . extraLibraries
606 toField "include_dirs" = Just $ strList . includeDirs
607 toField "c_includes" = Just $ strList . includes
608 toField "package_deps" = Just $ strList . map showPackageId. depends
609 toField "extra_cc_opts" = Just $ strList . ccOptions
610 toField "extra_ld_opts" = Just $ strList . ldOptions
611 toField "framework_dirs" = Just $ strList . frameworkDirs
612 toField "extra_frameworks"= Just $ strList . frameworks
613 toField s = showInstalledPackageInfoField s
615 strList :: [String] -> String
619 -- -----------------------------------------------------------------------------
620 -- Check: Check consistency of installed packages
622 checkConsistency :: [Flag] -> IO ()
623 checkConsistency flags = do
624 db_stack <- getPkgDatabases False flags
625 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
628 let broken_deps = missingPackageDeps p pkgs
629 guard (not . null $ broken_deps)
630 return (pid, broken_deps)
631 mapM_ (putStrLn . render . show_func) broken_pkgs
633 show_func | FlagSimpleOutput `elem` flags = show_simple
634 | otherwise = show_normal
635 show_simple (pid,deps) =
636 text (showPackageId pid) <> colon
637 <+> fsep (punctuate comma (map (text . showPackageId) deps))
638 show_normal (pid,deps) =
639 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
640 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
642 missingPackageDeps :: InstalledPackageInfo
643 -> [(PackageIdentifier, InstalledPackageInfo)]
644 -> [PackageIdentifier]
645 missingPackageDeps pkg pkg_map =
646 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
647 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
649 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
650 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
653 -- -----------------------------------------------------------------------------
654 -- Manipulating package.conf files
656 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
657 writeNewConfig filename packages = do
658 hPutStr stdout "Writing new package config file... "
659 createDirectoryIfMissing True $ takeDirectory filename
660 h <- openFile filename WriteMode `catch` \e ->
661 if isPermissionError e
662 then die (filename ++ ": you don't have permission to modify this file")
664 let shown = concat $ intersperse ",\n " $ map show packages
665 fileContents = "[" ++ shown ++ "\n]"
666 hPutStrLn h fileContents
668 hPutStrLn stdout "done."
670 savingOldConfig :: FilePath -> IO () -> IO ()
671 savingOldConfig filename io = Exception.block $ do
672 hPutStr stdout "Saving old package config file... "
673 -- mv rather than cp because we've already done an hGetContents
674 -- on this file so we won't be able to open it for writing
675 -- unless we move the old one out of the way...
676 let oldFile = filename ++ ".old"
677 restore_on_error <- catch (renameFile filename oldFile >> return True) $
679 unless (isDoesNotExistError err) $ do
680 hPutStrLn stderr (unwords ["Unable to rename", show filename,
684 hPutStrLn stdout "done."
686 hPutStrLn stderr (show e)
687 hPutStr stdout ("\nWARNING: an error was encountered while writing"
688 ++ "the new configuration.\n")
689 when restore_on_error $ do
690 hPutStr stdout "Attempting to restore the old configuration..."
691 do renameFile oldFile filename
692 hPutStrLn stdout "done."
693 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
696 -----------------------------------------------------------------------------
697 -- Sanity-check a new package config, and automatically build GHCi libs
700 validatePackageConfig :: InstalledPackageInfo
702 -> Bool -- auto-ghc-libs
706 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
708 checkDuplicates db_stack pkg update
709 mapM_ (checkDep db_stack force) (depends pkg)
710 mapM_ (checkDir force) (importDirs pkg)
711 mapM_ (checkDir force) (libraryDirs pkg)
712 mapM_ (checkDir force) (includeDirs pkg)
713 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
714 -- ToDo: check these somehow?
715 -- extra_libraries :: [String],
716 -- c_includes :: [String],
718 -- When the package name and version are put together, sometimes we can
719 -- end up with a package id that cannot be parsed. This will lead to
720 -- difficulties when the user wants to refer to the package later, so
721 -- we check that the package id can be parsed properly here.
722 checkPackageId :: InstalledPackageInfo -> IO ()
724 let str = showPackageId (package ipi) in
725 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
727 [] -> die ("invalid package identifier: " ++ str)
728 _ -> die ("ambiguous package identifier: " ++ str)
730 -- ToDo: remove this (see #1837)
731 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> IO InstalledPackageInfo
732 resolveDeps db_stack p = do
733 when (not (null unversioned_deps)) $
734 hPutStr stderr ("WARNING: unversioned dependencies are deprecated, "++
735 "and will NOT be accepted by GHC 6.10: " ++
736 unwords (map showPackageId unversioned_deps) ++ "\n")
737 return (updateDeps p)
739 unversioned_deps = filter (not.realVersion) (depends p)
741 -- The input package spec is allowed to give a package dependency
742 -- without a version number; e.g.
744 -- Here, we update these dependencies without version numbers to
745 -- match the actual versions of the relevant packages installed.
746 updateDeps p = p{depends = map resolveDep (depends p)}
749 | realVersion dep_pkgid = dep_pkgid
750 | otherwise = lookupDep dep_pkgid
754 name = pkgName dep_pkgid
756 case [ pid | p <- concat (map snd db_stack),
758 pkgName pid == name ] of
759 (pid:_) -> pid -- Found installed package,
760 -- replete with its version
761 [] -> dep_pkgid -- No installed package; use
762 -- the version-less one
764 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
765 checkDuplicates db_stack pkg update = do
768 (_top_db_name, pkgs) : _ = db_stack
770 -- Check whether this package id already exists in this DB
772 when (not update && (pkgid `elem` map package pkgs)) $
773 die ("package " ++ showPackageId pkgid ++ " is already installed")
777 checkDir :: Force -> String -> IO ()
779 | "$topdir" `isPrefixOf` d = return ()
780 | "$httptopdir" `isPrefixOf` d = return ()
781 -- can't check these, because we don't know what $(http)topdir is
783 there <- doesDirectoryExist d
785 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
787 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
788 checkDep db_stack force pkgid
789 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
790 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
793 -- for backwards compat, we treat 0.0 as a special version,
794 -- and don't check that it actually exists.
795 real_version = realVersion pkgid
797 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
800 all_pkgs = concat (map snd db_stack)
801 pkgids = map package all_pkgs
803 realVersion :: PackageIdentifier -> Bool
804 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
806 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
807 checkHSLib dirs auto_ghci_libs force lib = do
808 let batch_lib_file = "lib" ++ lib ++ ".a"
809 bs <- mapM (doesLibExistIn batch_lib_file) dirs
810 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
811 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
813 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
815 doesLibExistIn :: String -> String -> IO Bool
817 | "$topdir" `isPrefixOf` d = return True
818 | "$httptopdir" `isPrefixOf` d = return True
819 | otherwise = doesFileExist (d ++ '/':lib)
821 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
822 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
823 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
825 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
826 case [dir | (exists,dir) <- zip bs dirs, exists] of
827 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
830 ghci_lib_file = lib ++ ".o"
832 -- automatically build the GHCi version of a batch lib,
833 -- using ld --whole-archive.
835 autoBuildGHCiLib :: String -> String -> String -> IO ()
836 autoBuildGHCiLib dir batch_file ghci_file = do
837 let ghci_lib_file = dir ++ '/':ghci_file
838 batch_lib_file = dir ++ '/':batch_file
839 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
840 #if defined(darwin_HOST_OS)
841 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
842 #elif defined(mingw32_HOST_OS)
843 execDir <- getExecDir "/bin/ghc-pkg.exe"
844 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
846 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
848 when (r /= ExitSuccess) $ exitWith r
849 hPutStrLn stderr (" done.")
851 -- -----------------------------------------------------------------------------
852 -- Searching for modules
856 findModules :: [FilePath] -> IO [String]
858 mms <- mapM searchDir paths
861 searchDir path prefix = do
862 fs <- getDirectoryEntries path `catch` \_ -> return []
863 searchEntries path prefix fs
865 searchEntries path prefix [] = return []
866 searchEntries path prefix (f:fs)
867 | looks_like_a_module = do
868 ms <- searchEntries path prefix fs
869 return (prefix `joinModule` f : ms)
870 | looks_like_a_component = do
871 ms <- searchDir (path </> f) (prefix `joinModule` f)
872 ms' <- searchEntries path prefix fs
875 searchEntries path prefix fs
878 (base,suffix) = splitFileExt f
879 looks_like_a_module =
880 suffix `elem` haskell_suffixes &&
881 all okInModuleName base
882 looks_like_a_component =
883 null suffix && all okInModuleName base
889 -- -----------------------------------------------------------------------------
890 -- The old command-line syntax, supported for backwards compatibility
897 | OF_Add Bool {- True => replace existing info -}
898 | OF_Remove String | OF_Show String
899 | OF_Field String | OF_AutoGHCiLibs | OF_Force
900 | OF_DefinedName String String
901 | OF_GlobalConfig FilePath
904 isAction :: OldFlag -> Bool
905 isAction OF_Config{} = False
906 isAction OF_Field{} = False
907 isAction OF_Input{} = False
908 isAction OF_AutoGHCiLibs{} = False
909 isAction OF_Force{} = False
910 isAction OF_DefinedName{} = False
911 isAction OF_GlobalConfig{} = False
914 oldFlags :: [OptDescr OldFlag]
916 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
917 "use the specified package config file",
918 Option ['l'] ["list-packages"] (NoArg OF_List)
919 "list packages in all config files",
920 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
921 "list packages in the specified config file",
922 Option ['a'] ["add-package"] (NoArg (OF_Add False))
924 Option ['u'] ["update-package"] (NoArg (OF_Add True))
925 "update package with new configuration",
926 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
927 "read new package info from specified file",
928 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
929 "show the configuration for package NAME",
930 Option [] ["field"] (ReqArg OF_Field "FIELD")
931 "(with --show-package) Show field FIELD only",
932 Option [] ["force"] (NoArg OF_Force)
933 "ignore missing directories/libraries",
934 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
935 "remove an installed package",
936 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
937 "automatically build libs for GHCi (with -a)",
938 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
939 "define NAME as VALUE",
940 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
941 "location of the global package config"
945 case break (=='=') str of
946 (nm,[]) -> OF_DefinedName nm []
947 (nm,_:val) -> OF_DefinedName nm val
949 oldRunit :: [OldFlag] -> IO ()
951 let new_flags = [ f | Just f <- map conv clis ]
953 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
954 conv (OF_Config f) = Just (FlagConfig f)
959 let fields = [ f | OF_Field f <- clis ]
961 let auto_ghci_libs = any isAuto clis
962 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
963 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
965 force = if OF_Force `elem` clis then ForceAll else NoForce
967 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
969 case [ c | c <- clis, isAction c ] of
970 [ OF_List ] -> listPackages new_flags Nothing Nothing
971 [ OF_ListLocal ] -> listPackages new_flags Nothing Nothing
973 registerPackage input_file defines new_flags auto_ghci_libs upd force
974 [ OF_Remove pkgid_str ] -> do
975 pkgid <- readPkgId pkgid_str
976 unregisterPackage pkgid new_flags
977 [ OF_Show pkgid_str ]
979 pkgid <- readPkgId pkgid_str
980 describePackage new_flags pkgid
982 pkgid <- readPkgId pkgid_str
983 mapM_ (describeField new_flags pkgid) fields
985 prog <- getProgramName
986 die (usageInfo (usageHeader prog) flags)
988 my_head :: String -> [a] -> a
989 my_head s [] = error s
992 -- ---------------------------------------------------------------------------
993 -- expanding environment variables in the package configuration
995 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
996 expandEnvVars str defines force = go str ""
998 go "" acc = return $! reverse acc
999 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1000 = do value <- lookupEnvVar var
1001 go rest (reverse value ++ acc)
1002 where close c = c == '}' || c == '\n' -- don't span newlines
1006 lookupEnvVar :: String -> IO String
1008 case lookup nm defines of
1009 Just x | not (null x) -> return x
1011 catch (System.getEnv nm)
1012 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1016 -----------------------------------------------------------------------------
1018 getProgramName :: IO String
1019 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1020 where str `withoutSuffix` suff
1021 | suff `isSuffixOf` str = take (length str - length suff) str
1024 bye :: String -> IO a
1025 bye s = putStr s >> exitWith ExitSuccess
1027 die :: String -> IO a
1030 prog <- getProgramName
1031 hPutStrLn stderr (prog ++ ": " ++ s)
1032 exitWith (ExitFailure 1)
1034 dieOrForceAll :: Force -> String -> IO ()
1035 dieOrForceAll ForceAll s = ignoreError s
1036 dieOrForceAll _other s = dieForcible s
1038 dieOrForceFile :: Force -> String -> IO ()
1039 dieOrForceFile ForceAll s = ignoreError s
1040 dieOrForceFile ForceFiles s = ignoreError s
1041 dieOrForceFile _other s = dieForcible s
1043 ignoreError :: String -> IO ()
1044 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1046 dieForcible :: String -> IO ()
1047 dieForcible s = die (s ++ " (use --force to override)")
1049 -----------------------------------------
1050 -- Cut and pasted from ghc/compiler/SysTools
1052 #if defined(mingw32_HOST_OS)
1053 subst :: Char -> Char -> String -> String
1054 subst a b ls = map (\ x -> if x == a then b else x) ls
1056 unDosifyPath :: FilePath -> FilePath
1057 unDosifyPath xs = subst '\\' '/' xs
1059 getExecDir :: String -> IO (Maybe String)
1060 -- (getExecDir cmd) returns the directory in which the current
1061 -- executable, which should be called 'cmd', is running
1062 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1063 -- you'll get "/a/b/c" back as the result
1065 = allocaArray len $ \buf -> do
1066 ret <- getModuleFileName nullPtr buf len
1067 if ret == 0 then return Nothing
1068 else do s <- peekCString buf
1069 return (Just (reverse (drop (length cmd)
1070 (reverse (unDosifyPath s)))))
1072 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1074 foreign import stdcall unsafe "GetModuleFileNameA"
1075 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1077 getExecDir :: String -> IO (Maybe String)
1078 getExecDir _ = return Nothing