1 {-# OPTIONS -fglasgow-exts -cpp #-}
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 hiding (depends)
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils
22 import Distribution.Package
23 import Distribution.Text
24 import Distribution.Version
25 import System.FilePath
26 import System.Cmd ( rawSystem )
27 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
31 #include "../../includes/ghcconfig.h"
33 import System.Console.GetOpt
34 import Text.PrettyPrint
35 import qualified Control.Exception as Exception
38 import Data.Char ( isSpace, toLower )
40 import System.Directory ( doesDirectoryExist, getDirectoryContents,
41 doesFileExist, renameFile, removeFile )
42 import System.Exit ( exitWith, ExitCode(..) )
43 import System.Environment ( getArgs, getProgName, getEnv )
45 import System.IO.Error (try)
47 import Control.Concurrent
49 #ifdef mingw32_HOST_OS
51 import Foreign.C.String
52 import GHC.ConsoleHandler
57 import IO ( isPermissionError )
60 import System.Process(runInteractiveCommand)
61 import qualified System.Info(os)
64 -- -----------------------------------------------------------------------------
71 case getOpt Permute (flags ++ deprecFlags) args of
72 (cli,_,[]) | FlagHelp `elem` cli -> do
73 prog <- getProgramName
74 bye (usageInfo (usageHeader prog) flags)
75 (cli,_,[]) | FlagVersion `elem` cli ->
80 prog <- getProgramName
81 die (concat errors ++ usageInfo (usageHeader prog) flags)
83 -- -----------------------------------------------------------------------------
84 -- Command-line syntax
92 | FlagGlobalConfig FilePath
102 flags :: [OptDescr Flag]
104 Option [] ["user"] (NoArg FlagUser)
105 "use the current user's package database",
106 Option [] ["global"] (NoArg FlagGlobal)
107 "use the global package database",
108 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
109 "use the specified package config file",
110 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
111 "location of the global package config",
112 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
113 "never read the user package database",
114 Option [] ["force"] (NoArg FlagForce)
115 "ignore missing dependencies, directories, and libraries",
116 Option [] ["force-files"] (NoArg FlagForceFiles)
117 "ignore missing directories and libraries only",
118 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
119 "automatically build libs for GHCi (with register)",
120 Option ['?'] ["help"] (NoArg FlagHelp)
121 "display this help and exit",
122 Option ['V'] ["version"] (NoArg FlagVersion)
123 "output version information and exit",
124 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
125 "print output in easy-to-parse format for some commands",
126 Option [] ["names-only"] (NoArg FlagNamesOnly)
127 "only print package names, not versions; can only be used with list --simple-output",
128 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
129 "ignore case for substring matching"
132 deprecFlags :: [OptDescr Flag]
134 -- put deprecated flags here
137 ourCopyright :: String
138 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
140 usageHeader :: String -> String
141 usageHeader prog = substProg prog $
143 " $p register {filename | -}\n" ++
144 " Register the package using the specified installed package\n" ++
145 " description. The syntax for the latter is given in the $p\n" ++
146 " documentation.\n" ++
148 " $p update {filename | -}\n" ++
149 " Register the package, overwriting any other package with the\n" ++
152 " $p unregister {pkg-id}\n" ++
153 " Unregister the specified package.\n" ++
155 " $p expose {pkg-id}\n" ++
156 " Expose the specified package.\n" ++
158 " $p hide {pkg-id}\n" ++
159 " Hide the specified package.\n" ++
161 " $p list [pkg]\n" ++
162 " List registered packages in the global database, and also the\n" ++
163 " user database if --user is given. If a package name is given\n" ++
164 " all the registered versions will be listed in ascending order.\n" ++
165 " Accepts the --simple-output flag.\n" ++
167 " $p find-module {module}\n" ++
168 " List registered packages exposing module {module} in the global\n" ++
169 " database, and also the user database if --user is given.\n" ++
170 " All the registered versions will be listed in ascending order.\n" ++
171 " Accepts the --simple-output flag.\n" ++
173 " $p latest {pkg-id}\n" ++
174 " Prints the highest registered version of a package.\n" ++
177 " Check the consistency of package depenencies and list broken packages.\n" ++
178 " Accepts the --simple-output flag.\n" ++
180 " $p describe {pkg}\n" ++
181 " Give the registered description for the specified package. The\n" ++
182 " description is returned in precisely the syntax required by $p\n" ++
185 " $p field {pkg} {field}\n" ++
186 " Extract the specified field of the package description for the\n" ++
187 " specified package. Accepts comma-separated multiple fields.\n" ++
190 " Dump the registered description for every package. This is like\n" ++
191 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
192 " by tools that parse the results, rather than humans.\n" ++
194 " Substring matching is supported for {module} in find-module and\n" ++
195 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
196 " open substring ends (prefix*, *suffix, *infix*).\n" ++
198 " When asked to modify a database (register, unregister, update,\n"++
199 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
200 " default. Specifying --user causes it to act on the user database,\n"++
201 " or --package-conf can be used to act on another database\n"++
202 " entirely. When multiple of these options are given, the rightmost\n"++
203 " one is used as the database to act upon.\n"++
205 " Commands that query the package database (list, latest, describe,\n"++
206 " field) operate on the list of databases specified by the flags\n"++
207 " --user, --global, and --package-conf. If none of these flags are\n"++
208 " given, the default is --global --user.\n"++
210 " The following optional flags are also accepted:\n"
212 substProg :: String -> String -> String
214 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
215 substProg prog (c:xs) = c : substProg prog xs
217 -- -----------------------------------------------------------------------------
220 data Force = ForceAll | ForceFiles | NoForce
222 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
224 runit :: [Flag] -> [String] -> IO ()
225 runit cli nonopts = do
226 installSignalHandlers -- catch ^C and clean up
227 prog <- getProgramName
230 | FlagForce `elem` cli = ForceAll
231 | FlagForceFiles `elem` cli = ForceFiles
232 | otherwise = NoForce
233 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
234 splitFields fields = unfoldr splitComma (',':fields)
235 where splitComma "" = Nothing
236 splitComma fs = Just $ break (==',') (tail fs)
238 substringCheck :: String -> Maybe (String -> Bool)
239 substringCheck "" = Nothing
240 substringCheck "*" = Just (const True)
241 substringCheck [_] = Nothing
242 substringCheck (h:t) =
243 case (h, init t, last t) of
244 ('*',s,'*') -> Just (isInfixOf (f s) . f)
245 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
246 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
248 where f | FlagIgnoreCase `elem` cli = map toLower
251 glob x | System.Info.os=="mingw32" = do
252 -- glob echoes its argument, after win32 filename globbing
253 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
254 txt <- hGetContents o
256 glob x | otherwise = return [x]
259 -- first, parse the command
262 -- dummy command to demonstrate usage and permit testing
263 -- without messing things up; use glob to selectively enable
264 -- windows filename globbing for file parameters
265 -- register, update, FlagGlobalConfig, FlagConfig; others?
266 ["glob", filename] -> do
268 glob filename >>= print
270 ["register", filename] ->
271 registerPackage filename cli auto_ghci_libs False force
272 ["update", filename] ->
273 registerPackage filename cli auto_ghci_libs True force
274 ["unregister", pkgid_str] -> do
275 pkgid <- readGlobPkgId pkgid_str
276 unregisterPackage pkgid cli force
277 ["expose", pkgid_str] -> do
278 pkgid <- readGlobPkgId pkgid_str
279 exposePackage pkgid cli force
280 ["hide", pkgid_str] -> do
281 pkgid <- readGlobPkgId pkgid_str
282 hidePackage pkgid cli force
284 listPackages cli Nothing Nothing
285 ["list", pkgid_str] ->
286 case substringCheck pkgid_str of
287 Nothing -> do pkgid <- readGlobPkgId pkgid_str
288 listPackages cli (Just (Id pkgid)) Nothing
289 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
290 ["find-module", moduleName] -> do
291 let match = maybe (==moduleName) id (substringCheck moduleName)
292 listPackages cli Nothing (Just match)
293 ["latest", pkgid_str] -> do
294 pkgid <- readGlobPkgId pkgid_str
295 latestPackage cli pkgid
296 ["describe", pkgid_str] ->
297 case substringCheck pkgid_str of
298 Nothing -> do pkgid <- readGlobPkgId pkgid_str
299 describePackage cli (Id pkgid)
300 Just m -> describePackage cli (Substring pkgid_str m)
301 ["field", pkgid_str, fields] ->
302 case substringCheck pkgid_str of
303 Nothing -> do pkgid <- readGlobPkgId pkgid_str
304 describeField cli (Id pkgid) (splitFields fields)
305 Just m -> describeField cli (Substring pkgid_str m)
314 die ("missing command\n" ++
315 usageInfo (usageHeader prog) flags)
317 die ("command-line syntax error\n" ++
318 usageInfo (usageHeader prog) flags)
320 parseCheck :: ReadP a a -> String -> String -> IO a
321 parseCheck parser str what =
322 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
324 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
326 readGlobPkgId :: String -> IO PackageIdentifier
327 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
329 parseGlobPackageId :: ReadP r PackageIdentifier
335 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
337 -- globVersion means "all versions"
338 globVersion :: Version
339 globVersion = Version{ versionBranch=[], versionTags=["*"] }
341 -- -----------------------------------------------------------------------------
344 -- Some commands operate on a single database:
345 -- register, unregister, expose, hide
346 -- however these commands also check the union of the available databases
347 -- in order to check consistency. For example, register will check that
348 -- dependencies exist before registering a package.
350 -- Some commands operate on multiple databases, with overlapping semantics:
351 -- list, describe, field
353 type PackageDBName = FilePath
354 type PackageDB = [InstalledPackageInfo]
356 type NamedPackageDB = (PackageDBName, PackageDB)
357 type PackageDBStack = [NamedPackageDB]
358 -- A stack of package databases. Convention: head is the topmost
359 -- in the stack. Earlier entries override later one.
361 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
362 allPackagesInStack = concatMap snd
364 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
365 getPkgDatabases modify my_flags = do
366 -- first we determine the location of the global package config. On Windows,
367 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
368 -- location is passed to the binary using the --global-config flag by the
370 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
372 case [ f | FlagGlobalConfig f <- my_flags ] of
373 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
375 Nothing -> die err_msg
377 do let path1 = dir </> "package.conf"
378 path2 = dir </> ".." </> ".." </> ".."
379 </> "inplace-datadir"
381 exists1 <- doesFileExist path1
382 exists2 <- doesFileExist path2
383 if exists1 then return path1
384 else if exists2 then return path2
385 else die "Can't find package.conf"
386 fs -> return (last fs)
388 let global_conf_dir = global_conf ++ ".d"
389 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
391 if global_conf_dir_exists
392 then do files <- getDirectoryContents global_conf_dir
393 return [ global_conf_dir ++ '/' : file
395 , isSuffixOf ".conf" file]
398 let no_user_db = FlagNoUserDb `elem` my_flags
400 -- get the location of the user package database, and create it if necessary
401 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
402 appdir <- try $ getAppUserDataDirectory "ghc"
405 if no_user_db then return Nothing else
408 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
409 user_conf = dir </> subdir </> "package.conf"
410 user_exists <- doesFileExist user_conf
411 return (Just (user_conf,user_exists))
415 -- If the user database doesn't exist, and this command isn't a
416 -- "modify" command, then we won't attempt to create or use it.
418 | Just (user_conf,user_exists) <- mb_user_conf,
419 modify || user_exists = user_conf : global_confs ++ [global_conf]
420 | otherwise = global_confs ++ [global_conf]
422 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
425 Left _ -> sys_databases
427 | last cs == "" -> init cs ++ sys_databases
429 where cs = parseSearchPath path
431 -- The "global" database is always the one at the bottom of the stack.
432 -- This is the database we modify by default.
433 virt_global_conf = last env_stack
435 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
436 where is_db_flag FlagUser
437 | Just (user_conf, _user_exists) <- mb_user_conf
439 is_db_flag FlagGlobal = Just virt_global_conf
440 is_db_flag (FlagConfig f) = Just f
441 is_db_flag _ = Nothing
443 (final_stack, to_modify) <-
445 then -- For a "read" command, we use all the databases
446 -- specified on the command line. If there are no
447 -- command-line flags specifying databases, the default
448 -- is to use all the ones we know about.
449 if null db_flags then return (env_stack, Nothing)
450 else return (reverse (nub db_flags), Nothing)
452 -- For a "modify" command, treat all the databases as
453 -- a stack, where we are modifying the top one, but it
454 -- can refer to packages in databases further down the
457 -- -f flags on the command line add to the database
458 -- stack, unless any of them are present in the stack
460 flag_stack = filter (`notElem` env_stack)
461 [ f | FlagConfig f <- reverse my_flags ]
464 -- the database we actually modify is the one mentioned
465 -- rightmost on the command-line.
466 to_modify = if null db_flags
467 then Just virt_global_conf
468 else Just (last db_flags)
470 return (flag_stack, to_modify)
472 db_stack <- mapM readParseDatabase final_stack
473 return (db_stack, to_modify)
475 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
476 readParseDatabase filename = do
477 str <- readFile filename `catchIO` \_ -> return emptyPackageConfig
478 let packages = map convertPackageInfoIn $ read str
479 Exception.evaluate packages
481 die ("error while parsing " ++ filename ++ ": " ++ show e)
482 return (filename,packages)
484 emptyPackageConfig :: String
485 emptyPackageConfig = "[]"
487 -- -----------------------------------------------------------------------------
490 registerPackage :: FilePath
492 -> Bool -- auto_ghci_libs
496 registerPackage input my_flags auto_ghci_libs update force = do
497 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
499 db_to_operate_on = my_head "register" $
500 filter ((== to_modify).fst) db_stack
505 putStr "Reading package info from stdin ... "
508 putStr ("Reading package info from " ++ show f ++ " ... ")
511 expanded <- expandEnvVars s force
513 pkg <- parsePackageInfo expanded
516 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
517 -- truncate the stack for validation, because we don't allow
518 -- packages lower in the stack to refer to those higher up.
519 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
520 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
521 not_this p = package p /= package pkg
522 writeNewConfig to_modify new_details
526 -> IO InstalledPackageInfo
527 parsePackageInfo str =
528 case parseInstalledPackageInfo str of
529 ParseOk _warns ok -> return ok
530 ParseFailed err -> case locatedErrorMsg err of
531 (Nothing, s) -> die s
532 (Just l, s) -> die (show l ++ ": " ++ s)
534 -- -----------------------------------------------------------------------------
535 -- Exposing, Hiding, Unregistering are all similar
537 exposePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
538 exposePackage = modifyPackage (\p -> [p{exposed=True}])
540 hidePackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
541 hidePackage = modifyPackage (\p -> [p{exposed=False}])
543 unregisterPackage :: PackageIdentifier -> [Flag] -> Force -> IO ()
544 unregisterPackage = modifyPackage (\_ -> [])
547 :: (InstalledPackageInfo -> [InstalledPackageInfo])
552 modifyPackage fn pkgid my_flags force = do
553 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
554 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
555 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
556 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
558 pids = map package ps
560 | package pkg `elem` pids = fn pkg
562 new_config = concat (map modify pkgs)
565 old_broken = brokenPackages (allPackagesInStack db_stack)
566 rest_of_stack = [ (nm, mypkgs)
567 | (nm, mypkgs) <- db_stack, nm /= db_name ]
568 new_stack = (db_name,new_config) : rest_of_stack
569 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
570 newly_broken = filter (`notElem` map package old_broken) new_broken
572 when (not (null newly_broken)) $
573 dieOrForceAll force ("unregistering " ++ display pkgid ++
574 " would break the following packages: "
575 ++ unwords (map display newly_broken))
577 writeNewConfig db_name new_config
579 -- -----------------------------------------------------------------------------
582 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
583 listPackages my_flags mPackageName mModuleName = do
584 let simple_output = FlagSimpleOutput `elem` my_flags
585 (db_stack, _) <- getPkgDatabases False my_flags
586 let db_stack_filtered -- if a package is given, filter out all other packages
587 | Just this <- mPackageName =
588 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
590 | Just match <- mModuleName = -- packages which expose mModuleName
591 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
593 | otherwise = db_stack
596 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
597 where sort_pkgs = sortBy cmpPkgIds
598 cmpPkgIds pkg1 pkg2 =
599 case pkgName p1 `compare` pkgName p2 of
602 EQ -> pkgVersion p1 `compare` pkgVersion p2
603 where (p1,p2) = (package pkg1, package pkg2)
605 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
607 pkg_map = allPackagesInStack db_stack
608 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
610 show_func (reverse db_stack_sorted)
612 where show_normal pkg_map (db_name,pkg_confs) =
613 hPutStrLn stdout (render $
614 text db_name <> colon $$ nest 4 packages
616 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
617 broken = map package (brokenPackages pkg_map)
619 | package p `elem` broken = braces doc
621 | otherwise = parens doc
622 where doc = text (display (package p))
624 show_simple db_stack = do
625 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
627 pkgs = map showPkg $ sortBy compPkgIdVer $
628 map package (allPackagesInStack db_stack)
629 when (not (null pkgs)) $
630 hPutStrLn stdout $ concat $ intersperse " " pkgs
632 -- -----------------------------------------------------------------------------
633 -- Prints the highest (hidden or exposed) version of a package
635 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
636 latestPackage my_flags pkgid = do
637 (db_stack, _) <- getPkgDatabases False my_flags
638 ps <- findPackages db_stack (Id pkgid)
639 show_pkg (sortBy compPkgIdVer (map package ps))
641 show_pkg [] = die "no matches"
642 show_pkg pids = hPutStrLn stdout (display (last pids))
644 -- -----------------------------------------------------------------------------
647 describePackage :: [Flag] -> PackageArg -> IO ()
648 describePackage my_flags pkgarg = do
649 (db_stack, _) <- getPkgDatabases False my_flags
650 ps <- findPackages db_stack pkgarg
653 dumpPackages :: [Flag] -> IO ()
654 dumpPackages my_flags = do
655 (db_stack, _) <- getPkgDatabases False my_flags
656 doDump (allPackagesInStack db_stack)
658 doDump :: [InstalledPackageInfo] -> IO ()
659 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
661 -- PackageId is can have globVersion for the version
662 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
663 findPackages db_stack pkgarg
664 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
666 findPackagesByDB :: PackageDBStack -> PackageArg
667 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
668 findPackagesByDB db_stack pkgarg
669 = case [ (db, matched)
670 | db@(_, pkgs) <- db_stack,
671 let matched = filter (pkgarg `matchesPkg`) pkgs,
672 not (null matched) ] of
673 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
676 pkg_msg (Id pkgid) = display pkgid
677 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
679 matches :: PackageIdentifier -> PackageIdentifier -> Bool
681 = (pkgName pid == pkgName pid')
682 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
684 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
685 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
686 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
688 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
689 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
691 -- -----------------------------------------------------------------------------
694 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
695 describeField my_flags pkgarg fields = do
696 (db_stack, _) <- getPkgDatabases False my_flags
697 fns <- toFields fields
698 ps <- findPackages db_stack pkgarg
699 let top_dir = takeDirectory (fst (last db_stack))
700 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
701 where toFields [] = return []
702 toFields (f:fs) = case toField f of
703 Nothing -> die ("unknown field: " ++ f)
704 Just fn -> do fns <- toFields fs
706 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
708 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
709 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
710 -- with the current topdir (obtained from the -B option).
711 mungePackagePaths top_dir ps = map munge_pkg ps
713 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
714 includeDirs = munge_paths (includeDirs p),
715 libraryDirs = munge_paths (libraryDirs p),
716 frameworkDirs = munge_paths (frameworkDirs p),
717 haddockInterfaces = munge_paths (haddockInterfaces p),
718 haddockHTMLs = munge_paths (haddockHTMLs p)
721 munge_paths = map munge_path
724 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
725 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
728 toHttpPath p = "file:///" ++ p
730 maybePrefixMatch :: String -> String -> Maybe String
731 maybePrefixMatch [] rest = Just rest
732 maybePrefixMatch (_:_) [] = Nothing
733 maybePrefixMatch (p:pat) (r:rest)
734 | p == r = maybePrefixMatch pat rest
735 | otherwise = Nothing
737 toField :: String -> Maybe (InstalledPackageInfo -> String)
738 -- backwards compatibility:
739 toField "import_dirs" = Just $ strList . importDirs
740 toField "source_dirs" = Just $ strList . importDirs
741 toField "library_dirs" = Just $ strList . libraryDirs
742 toField "hs_libraries" = Just $ strList . hsLibraries
743 toField "extra_libraries" = Just $ strList . extraLibraries
744 toField "include_dirs" = Just $ strList . includeDirs
745 toField "c_includes" = Just $ strList . includes
746 toField "package_deps" = Just $ strList . map display. depends
747 toField "extra_cc_opts" = Just $ strList . ccOptions
748 toField "extra_ld_opts" = Just $ strList . ldOptions
749 toField "framework_dirs" = Just $ strList . frameworkDirs
750 toField "extra_frameworks"= Just $ strList . frameworks
751 toField s = showInstalledPackageInfoField s
753 strList :: [String] -> String
757 -- -----------------------------------------------------------------------------
758 -- Check: Check consistency of installed packages
760 checkConsistency :: [Flag] -> IO ()
761 checkConsistency my_flags = do
762 (db_stack, _) <- getPkgDatabases True my_flags
763 -- check behaves like modify for the purposes of deciding which
764 -- databases to use, because ordering is important.
765 let pkgs = allPackagesInStack db_stack
766 broken_pkgs = brokenPackages pkgs
767 broken_ids = map package broken_pkgs
768 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
770 mapM_ (putStrLn . render . show_func) broken_why
772 show_func | FlagSimpleOutput `elem` my_flags = show_simple
773 | otherwise = show_normal
774 show_simple (pid,deps) =
775 text (display pid) <> colon
776 <+> fsep (punctuate comma (map (text . display) deps))
777 show_normal (pid,deps) =
778 text "package" <+> text (display pid) <+> text "has missing dependencies:"
779 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
782 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
783 brokenPackages pkgs = go [] pkgs
786 case partition (depsAvailable avail) not_avail of
787 ([], not_avail') -> not_avail'
788 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
790 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
792 depsAvailable pkgs_ok pkg = null dangling
793 where dangling = filter (`notElem` pids) (depends pkg)
794 pids = map package pkgs_ok
796 -- we want mutually recursive groups of package to show up
797 -- as broken. (#1750)
799 -- -----------------------------------------------------------------------------
800 -- Manipulating package.conf files
802 type InstalledPackageInfoString = InstalledPackageInfo_ String
804 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
805 convertPackageInfoOut
806 (pkgconf@(InstalledPackageInfo { exposedModules = e,
807 hiddenModules = h })) =
808 pkgconf{ exposedModules = map display e,
809 hiddenModules = map display h }
811 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
813 (pkgconf@(InstalledPackageInfo { exposedModules = e,
814 hiddenModules = h })) =
815 pkgconf{ exposedModules = map convert e,
816 hiddenModules = map convert h }
817 where convert = fromJust . simpleParse
819 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
820 writeNewConfig filename packages = do
821 hPutStr stdout "Writing new package config file... "
822 createDirectoryIfMissing True $ takeDirectory filename
823 let shown = concat $ intersperse ",\n "
824 $ map (show . convertPackageInfoOut) packages
825 fileContents = "[" ++ shown ++ "\n]"
826 writeFileAtomic filename fileContents
828 if isPermissionError e
829 then die (filename ++ ": you don't have permission to modify this file")
831 hPutStrLn stdout "done."
833 -----------------------------------------------------------------------------
834 -- Sanity-check a new package config, and automatically build GHCi libs
837 validatePackageConfig :: InstalledPackageInfo
839 -> Bool -- auto-ghc-libs
843 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
845 checkDuplicates db_stack pkg update force
846 mapM_ (checkDep db_stack force) (depends pkg)
847 checkDuplicateDepends force (depends pkg)
848 mapM_ (checkDir force) (importDirs pkg)
849 mapM_ (checkDir force) (libraryDirs pkg)
850 mapM_ (checkDir force) (includeDirs pkg)
851 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
852 -- ToDo: check these somehow?
853 -- extra_libraries :: [String],
854 -- c_includes :: [String],
856 -- When the package name and version are put together, sometimes we can
857 -- end up with a package id that cannot be parsed. This will lead to
858 -- difficulties when the user wants to refer to the package later, so
859 -- we check that the package id can be parsed properly here.
860 checkPackageId :: InstalledPackageInfo -> IO ()
862 let str = display (package ipi) in
863 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
865 [] -> die ("invalid package identifier: " ++ str)
866 _ -> die ("ambiguous package identifier: " ++ str)
868 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
869 checkDuplicates db_stack pkg update force = do
872 (_top_db_name, pkgs) : _ = db_stack
874 -- Check whether this package id already exists in this DB
876 when (not update && (pkgid `elem` map package pkgs)) $
877 die ("package " ++ display pkgid ++ " is already installed")
880 uncasep = map toLower . display
881 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
883 when (not update && not (null dups)) $ dieOrForceAll force $
884 "Package names may be treated case-insensitively in the future.\n"++
885 "Package " ++ display pkgid ++
886 " overlaps with: " ++ unwords (map display dups)
889 checkDir :: Force -> String -> IO ()
891 | "$topdir" `isPrefixOf` d = return ()
892 | "$httptopdir" `isPrefixOf` d = return ()
893 -- can't check these, because we don't know what $(http)topdir is
895 there <- doesDirectoryExist d
897 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
899 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
900 checkDep db_stack force pkgid
901 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
902 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
905 -- for backwards compat, we treat 0.0 as a special version,
906 -- and don't check that it actually exists.
907 real_version = realVersion pkgid
909 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
912 all_pkgs = allPackagesInStack db_stack
913 pkgids = map package all_pkgs
915 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
916 checkDuplicateDepends force deps
917 | null dups = return ()
918 | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
919 unwords (map display dups))
921 dups = [ p | (p:_:_) <- group (sort deps) ]
923 realVersion :: PackageIdentifier -> Bool
924 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
926 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
927 checkHSLib dirs auto_ghci_libs force lib = do
928 let batch_lib_file = "lib" ++ lib ++ ".a"
929 bs <- mapM (doesLibExistIn batch_lib_file) dirs
930 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
931 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
933 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
935 doesLibExistIn :: String -> String -> IO Bool
937 | "$topdir" `isPrefixOf` d = return True
938 | "$httptopdir" `isPrefixOf` d = return True
939 | otherwise = doesFileExist (d ++ '/':lib)
941 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
942 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
943 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
945 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
946 case [dir | (exists,dir) <- zip bs dirs, exists] of
947 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
950 ghci_lib_file = lib ++ ".o"
952 -- automatically build the GHCi version of a batch lib,
953 -- using ld --whole-archive.
955 autoBuildGHCiLib :: String -> String -> String -> IO ()
956 autoBuildGHCiLib dir batch_file ghci_file = do
957 let ghci_lib_file = dir ++ '/':ghci_file
958 batch_lib_file = dir ++ '/':batch_file
959 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
960 #if defined(darwin_HOST_OS)
961 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
962 #elif defined(mingw32_HOST_OS)
963 execDir <- getExecDir "/bin/ghc-pkg.exe"
964 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
966 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
968 when (r /= ExitSuccess) $ exitWith r
969 hPutStrLn stderr (" done.")
971 -- -----------------------------------------------------------------------------
972 -- Searching for modules
976 findModules :: [FilePath] -> IO [String]
978 mms <- mapM searchDir paths
981 searchDir path prefix = do
982 fs <- getDirectoryEntries path `catch` \_ -> return []
983 searchEntries path prefix fs
985 searchEntries path prefix [] = return []
986 searchEntries path prefix (f:fs)
987 | looks_like_a_module = do
988 ms <- searchEntries path prefix fs
989 return (prefix `joinModule` f : ms)
990 | looks_like_a_component = do
991 ms <- searchDir (path </> f) (prefix `joinModule` f)
992 ms' <- searchEntries path prefix fs
995 searchEntries path prefix fs
998 (base,suffix) = splitFileExt f
999 looks_like_a_module =
1000 suffix `elem` haskell_suffixes &&
1001 all okInModuleName base
1002 looks_like_a_component =
1003 null suffix && all okInModuleName base
1009 -- ---------------------------------------------------------------------------
1010 -- expanding environment variables in the package configuration
1012 expandEnvVars :: String -> Force -> IO String
1013 expandEnvVars str0 force = go str0 ""
1015 go "" acc = return $! reverse acc
1016 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1017 = do value <- lookupEnvVar var
1018 go rest (reverse value ++ acc)
1019 where close c = c == '}' || c == '\n' -- don't span newlines
1023 lookupEnvVar :: String -> IO String
1025 catch (System.Environment.getEnv nm)
1026 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1030 -----------------------------------------------------------------------------
1032 getProgramName :: IO String
1033 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1034 where str `withoutSuffix` suff
1035 | suff `isSuffixOf` str = take (length str - length suff) str
1038 bye :: String -> IO a
1039 bye s = putStr s >> exitWith ExitSuccess
1041 die :: String -> IO a
1044 dieWith :: Int -> String -> IO a
1047 prog <- getProgramName
1048 hPutStrLn stderr (prog ++ ": " ++ s)
1049 exitWith (ExitFailure ec)
1051 dieOrForceAll :: Force -> String -> IO ()
1052 dieOrForceAll ForceAll s = ignoreError s
1053 dieOrForceAll _other s = dieForcible s
1055 dieOrForceFile :: Force -> String -> IO ()
1056 dieOrForceFile ForceAll s = ignoreError s
1057 dieOrForceFile ForceFiles s = ignoreError s
1058 dieOrForceFile _other s = dieForcible s
1060 ignoreError :: String -> IO ()
1061 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1063 dieForcible :: String -> IO ()
1064 dieForcible s = die (s ++ " (use --force to override)")
1066 my_head :: String -> [a] -> a
1067 my_head s [] = error s
1068 my_head _ (x : _) = x
1070 -----------------------------------------
1071 -- Cut and pasted from ghc/compiler/main/SysTools
1073 #if defined(mingw32_HOST_OS)
1074 subst :: Char -> Char -> String -> String
1075 subst a b ls = map (\ x -> if x == a then b else x) ls
1077 unDosifyPath :: FilePath -> FilePath
1078 unDosifyPath xs = subst '\\' '/' xs
1080 getExecDir :: String -> IO (Maybe String)
1081 -- (getExecDir cmd) returns the directory in which the current
1082 -- executable, which should be called 'cmd', is running
1083 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1084 -- you'll get "/a/b/c" back as the result
1086 = allocaArray len $ \buf -> do
1087 ret <- getModuleFileName nullPtr buf len
1088 if ret == 0 then return Nothing
1089 else do s <- peekCString buf
1090 return (Just (reverse (drop (length cmd)
1091 (reverse (unDosifyPath s)))))
1093 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1095 foreign import stdcall unsafe "GetModuleFileNameA"
1096 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1098 getExecDir :: String -> IO (Maybe String)
1099 getExecDir _ = return Nothing
1102 -----------------------------------------
1103 -- Adapted from ghc/compiler/utils/Panic
1105 installSignalHandlers :: IO ()
1106 installSignalHandlers = do
1107 threadid <- myThreadId
1109 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1111 #if !defined(mingw32_HOST_OS)
1112 installHandler sigQUIT (Catch interrupt) Nothing
1113 installHandler sigINT (Catch interrupt) Nothing
1115 #elif __GLASGOW_HASKELL__ >= 603
1116 -- GHC 6.3+ has support for console events on Windows
1117 -- NOTE: running GHCi under a bash shell for some reason requires
1118 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1119 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1120 -- why --SDM 17/12/2004
1121 let sig_handler ControlC = interrupt
1122 sig_handler Break = interrupt
1123 sig_handler _ = return ()
1125 installHandler (Catch sig_handler)
1128 return () -- nothing
1131 #if __GLASGOW_HASKELL__ <= 604
1132 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1133 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1136 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1137 #if __GLASGOW_HASKELL__ >= 609
1138 catchIO = Exception.catch
1140 catchIO io handler = io `Exception.catch` handler'
1141 where handler' (Exception.IOException ioe) = handler ioe
1142 handler' e = Exception.throw e
1145 #if mingw32_HOST_OS || mingw32_TARGET_OS
1146 throwIOIO :: Exception.IOException -> IO a
1147 #if __GLASGOW_HASKELL__ >= 609
1148 throwIOIO = Exception.throwIO
1150 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1154 catchError :: IO a -> (String -> IO a) -> IO a
1155 #if __GLASGOW_HASKELL__ >= 609
1156 catchError io handler = io `Exception.catch` handler'
1157 where handler' (Exception.ErrorCall err) = handler err
1159 catchError io handler = io `Exception.catch` handler'
1160 where handler' (Exception.ErrorCall err) = handler err
1161 handler' e = Exception.throw e
1164 onException :: IO a -> IO () -> IO a
1165 #if __GLASGOW_HASKELL__ >= 609
1166 onException = Exception.onException
1168 onException io what = io `Exception.catch` \e -> do what
1173 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1174 -- to use text files here, rather than binary files.
1175 writeFileAtomic :: FilePath -> String -> IO ()
1176 writeFileAtomic targetFile content = do
1177 (tmpFile, tmpHandle) <- openTempFile targetDir template
1178 do hPutStr tmpHandle content
1180 #if mingw32_HOST_OS || mingw32_TARGET_OS
1181 renameFile tmpFile targetFile
1182 -- If the targetFile exists then renameFile will fail
1183 `catchIO` \err -> do
1184 exists <- doesFileExist targetFile
1186 then do removeFile targetFile
1187 -- Big fat hairy race condition
1188 renameFile tmpFile targetFile
1189 -- If the removeFile succeeds and the renameFile fails
1190 -- then we've lost the atomic property.
1193 renameFile tmpFile targetFile
1195 `onException` do hClose tmpHandle
1198 template = targetName <.> "tmp"
1199 targetDir | null targetDir_ = "."
1200 | otherwise = targetDir_
1201 --TODO: remove this when takeDirectory/splitFileName is fixed
1202 -- to always return a valid dir
1203 (targetDir_,targetName) = splitFileName targetFile
1205 -- | The function splits the given string to substrings
1206 -- using 'isSearchPathSeparator'.
1207 parseSearchPath :: String -> [FilePath]
1208 parseSearchPath path = split path
1210 split :: String -> [String]
1214 _:rest -> chunk : split rest
1218 #ifdef mingw32_HOST_OS
1219 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1223 (chunk', rest') = break isSearchPathSeparator s