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, isDoesNotExistError )
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,pkgs) | (nm,pkgs) <- db_stack, nm /= db_name ]
567 new_stack = (db_name,new_config) : rest_of_stack
568 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
569 newly_broken = filter (`notElem` map package old_broken) new_broken
571 when (not (null newly_broken)) $
572 dieOrForceAll force ("unregistering " ++ display pkgid ++
573 " would break the following packages: "
574 ++ unwords (map display newly_broken))
576 writeNewConfig db_name new_config
578 -- -----------------------------------------------------------------------------
581 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
582 listPackages my_flags mPackageName mModuleName = do
583 let simple_output = FlagSimpleOutput `elem` my_flags
584 (db_stack, _) <- getPkgDatabases False my_flags
585 let db_stack_filtered -- if a package is given, filter out all other packages
586 | Just this <- mPackageName =
587 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
589 | Just match <- mModuleName = -- packages which expose mModuleName
590 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
592 | otherwise = db_stack
595 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
596 where sort_pkgs = sortBy cmpPkgIds
597 cmpPkgIds pkg1 pkg2 =
598 case pkgName p1 `compare` pkgName p2 of
601 EQ -> pkgVersion p1 `compare` pkgVersion p2
602 where (p1,p2) = (package pkg1, package pkg2)
604 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
606 pkg_map = allPackagesInStack db_stack
607 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
609 show_func (reverse db_stack_sorted)
611 where show_normal pkg_map (db_name,pkg_confs) =
612 hPutStrLn stdout (render $
613 text db_name <> colon $$ nest 4 packages
615 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
616 broken = map package (brokenPackages pkg_map)
618 | package p `elem` broken = braces doc
620 | otherwise = parens doc
621 where doc = text (display (package p))
623 show_simple db_stack = do
624 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
626 pkgs = map showPkg $ sortBy compPkgIdVer $
627 map package (allPackagesInStack db_stack)
628 when (not (null pkgs)) $
629 hPutStrLn stdout $ concat $ intersperse " " pkgs
631 -- -----------------------------------------------------------------------------
632 -- Prints the highest (hidden or exposed) version of a package
634 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
635 latestPackage my_flags pkgid = do
636 (db_stack, _) <- getPkgDatabases False my_flags
637 ps <- findPackages db_stack (Id pkgid)
638 show_pkg (sortBy compPkgIdVer (map package ps))
640 show_pkg [] = die "no matches"
641 show_pkg pids = hPutStrLn stdout (display (last pids))
643 -- -----------------------------------------------------------------------------
646 describePackage :: [Flag] -> PackageArg -> IO ()
647 describePackage my_flags pkgarg = do
648 (db_stack, _) <- getPkgDatabases False my_flags
649 ps <- findPackages db_stack pkgarg
652 dumpPackages :: [Flag] -> IO ()
653 dumpPackages my_flags = do
654 (db_stack, _) <- getPkgDatabases False my_flags
655 doDump (allPackagesInStack db_stack)
657 doDump :: [InstalledPackageInfo] -> IO ()
658 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
660 -- PackageId is can have globVersion for the version
661 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
662 findPackages db_stack pkgarg
663 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
665 findPackagesByDB :: PackageDBStack -> PackageArg
666 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
667 findPackagesByDB db_stack pkgarg
668 = case [ (db, matched)
669 | db@(db_name,pkgs) <- db_stack,
670 let matched = filter (pkgarg `matchesPkg`) pkgs,
671 not (null matched) ] of
672 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
675 pkg_msg (Id pkgid) = display pkgid
676 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
678 matches :: PackageIdentifier -> PackageIdentifier -> Bool
680 = (pkgName pid == pkgName pid')
681 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
683 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
684 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
685 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
687 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
688 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
690 -- -----------------------------------------------------------------------------
693 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
694 describeField my_flags pkgarg fields = do
695 (db_stack, _) <- getPkgDatabases False my_flags
696 fns <- toFields fields
697 ps <- findPackages db_stack pkgarg
698 let top_dir = takeDirectory (fst (last db_stack))
699 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
700 where toFields [] = return []
701 toFields (f:fs) = case toField f of
702 Nothing -> die ("unknown field: " ++ f)
703 Just fn -> do fns <- toFields fs
705 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
707 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
708 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
709 -- with the current topdir (obtained from the -B option).
710 mungePackagePaths top_dir ps = map munge_pkg ps
712 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
713 includeDirs = munge_paths (includeDirs p),
714 libraryDirs = munge_paths (libraryDirs p),
715 frameworkDirs = munge_paths (frameworkDirs p),
716 haddockInterfaces = munge_paths (haddockInterfaces p),
717 haddockHTMLs = munge_paths (haddockHTMLs p)
720 munge_paths = map munge_path
723 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
724 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
727 toHttpPath p = "file:///" ++ p
729 maybePrefixMatch :: String -> String -> Maybe String
730 maybePrefixMatch [] rest = Just rest
731 maybePrefixMatch (_:_) [] = Nothing
732 maybePrefixMatch (p:pat) (r:rest)
733 | p == r = maybePrefixMatch pat rest
734 | otherwise = Nothing
736 toField :: String -> Maybe (InstalledPackageInfo -> String)
737 -- backwards compatibility:
738 toField "import_dirs" = Just $ strList . importDirs
739 toField "source_dirs" = Just $ strList . importDirs
740 toField "library_dirs" = Just $ strList . libraryDirs
741 toField "hs_libraries" = Just $ strList . hsLibraries
742 toField "extra_libraries" = Just $ strList . extraLibraries
743 toField "include_dirs" = Just $ strList . includeDirs
744 toField "c_includes" = Just $ strList . includes
745 toField "package_deps" = Just $ strList . map display. depends
746 toField "extra_cc_opts" = Just $ strList . ccOptions
747 toField "extra_ld_opts" = Just $ strList . ldOptions
748 toField "framework_dirs" = Just $ strList . frameworkDirs
749 toField "extra_frameworks"= Just $ strList . frameworks
750 toField s = showInstalledPackageInfoField s
752 strList :: [String] -> String
756 -- -----------------------------------------------------------------------------
757 -- Check: Check consistency of installed packages
759 checkConsistency :: [Flag] -> IO ()
760 checkConsistency my_flags = do
761 (db_stack, _) <- getPkgDatabases True my_flags
762 -- check behaves like modify for the purposes of deciding which
763 -- databases to use, because ordering is important.
764 let pkgs = allPackagesInStack db_stack
765 broken_pkgs = brokenPackages pkgs
766 broken_ids = map package broken_pkgs
767 broken_why = [ (package p, filter (`elem` broken_ids) (depends p))
769 mapM_ (putStrLn . render . show_func) broken_why
771 show_func | FlagSimpleOutput `elem` my_flags = show_simple
772 | otherwise = show_normal
773 show_simple (pid,deps) =
774 text (display pid) <> colon
775 <+> fsep (punctuate comma (map (text . display) deps))
776 show_normal (pid,deps) =
777 text "package" <+> text (display pid) <+> text "has missing dependencies:"
778 $$ nest 4 (fsep (punctuate comma (map (text . display) deps)))
781 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
782 brokenPackages pkgs = go [] pkgs
785 case partition (depsAvailable avail) not_avail of
786 ([], not_avail) -> not_avail
787 (new_avail, not_avail) -> go (new_avail ++ avail) not_avail
789 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
791 depsAvailable pkgs_ok pkg = null dangling
792 where dangling = filter (`notElem` pids) (depends pkg)
793 pids = map package pkgs_ok
795 -- we want mutually recursive groups of package to show up
796 -- as broken. (#1750)
798 -- -----------------------------------------------------------------------------
799 -- Manipulating package.conf files
801 type InstalledPackageInfoString = InstalledPackageInfo_ String
803 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
804 convertPackageInfoOut
805 (pkgconf@(InstalledPackageInfo { exposedModules = e,
806 hiddenModules = h })) =
807 pkgconf{ exposedModules = map display e,
808 hiddenModules = map display h }
810 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
812 (pkgconf@(InstalledPackageInfo { exposedModules = e,
813 hiddenModules = h })) =
814 pkgconf{ exposedModules = map convert e,
815 hiddenModules = map convert h }
816 where convert = fromJust . simpleParse
818 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
819 writeNewConfig filename packages = do
820 hPutStr stdout "Writing new package config file... "
821 createDirectoryIfMissing True $ takeDirectory filename
822 let shown = concat $ intersperse ",\n "
823 $ map (show . convertPackageInfoOut) packages
824 fileContents = "[" ++ shown ++ "\n]"
825 writeFileAtomic filename fileContents
827 if isPermissionError e
828 then die (filename ++ ": you don't have permission to modify this file")
830 hPutStrLn stdout "done."
832 -----------------------------------------------------------------------------
833 -- Sanity-check a new package config, and automatically build GHCi libs
836 validatePackageConfig :: InstalledPackageInfo
838 -> Bool -- auto-ghc-libs
842 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
844 checkDuplicates db_stack pkg update force
845 mapM_ (checkDep db_stack force) (depends pkg)
846 checkDuplicateDepends force (depends pkg)
847 mapM_ (checkDir force) (importDirs pkg)
848 mapM_ (checkDir force) (libraryDirs pkg)
849 mapM_ (checkDir force) (includeDirs pkg)
850 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
851 -- ToDo: check these somehow?
852 -- extra_libraries :: [String],
853 -- c_includes :: [String],
855 -- When the package name and version are put together, sometimes we can
856 -- end up with a package id that cannot be parsed. This will lead to
857 -- difficulties when the user wants to refer to the package later, so
858 -- we check that the package id can be parsed properly here.
859 checkPackageId :: InstalledPackageInfo -> IO ()
861 let str = display (package ipi) in
862 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
864 [] -> die ("invalid package identifier: " ++ str)
865 _ -> die ("ambiguous package identifier: " ++ str)
867 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Force -> IO ()
868 checkDuplicates db_stack pkg update force = do
871 (_top_db_name, pkgs) : _ = db_stack
873 -- Check whether this package id already exists in this DB
875 when (not update && (pkgid `elem` map package pkgs)) $
876 die ("package " ++ display pkgid ++ " is already installed")
879 uncasep = map toLower . display
880 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
882 when (not update && not (null dups)) $ dieOrForceAll force $
883 "Package names may be treated case-insensitively in the future.\n"++
884 "Package " ++ display pkgid ++
885 " overlaps with: " ++ unwords (map display dups)
888 checkDir :: Force -> String -> IO ()
890 | "$topdir" `isPrefixOf` d = return ()
891 | "$httptopdir" `isPrefixOf` d = return ()
892 -- can't check these, because we don't know what $(http)topdir is
894 there <- doesDirectoryExist d
896 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
898 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
899 checkDep db_stack force pkgid
900 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
901 | otherwise = dieOrForceAll force ("dependency " ++ display pkgid
904 -- for backwards compat, we treat 0.0 as a special version,
905 -- and don't check that it actually exists.
906 real_version = realVersion pkgid
908 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
911 all_pkgs = allPackagesInStack db_stack
912 pkgids = map package all_pkgs
914 checkDuplicateDepends :: Force -> [PackageIdentifier] -> IO ()
915 checkDuplicateDepends force deps
916 | null dups = return ()
917 | otherwise = dieOrForceAll force ("package has duplicate dependencies: " ++
918 unwords (map display dups))
920 dups = [ p | (p:_:_) <- group (sort deps) ]
922 realVersion :: PackageIdentifier -> Bool
923 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
925 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
926 checkHSLib dirs auto_ghci_libs force lib = do
927 let batch_lib_file = "lib" ++ lib ++ ".a"
928 bs <- mapM (doesLibExistIn batch_lib_file) dirs
929 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
930 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
932 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
934 doesLibExistIn :: String -> String -> IO Bool
936 | "$topdir" `isPrefixOf` d = return True
937 | "$httptopdir" `isPrefixOf` d = return True
938 | otherwise = doesFileExist (d ++ '/':lib)
940 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
941 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
942 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
944 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
945 case [dir | (exists,dir) <- zip bs dirs, exists] of
946 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
949 ghci_lib_file = lib ++ ".o"
951 -- automatically build the GHCi version of a batch lib,
952 -- using ld --whole-archive.
954 autoBuildGHCiLib :: String -> String -> String -> IO ()
955 autoBuildGHCiLib dir batch_file ghci_file = do
956 let ghci_lib_file = dir ++ '/':ghci_file
957 batch_lib_file = dir ++ '/':batch_file
958 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
959 #if defined(darwin_HOST_OS)
960 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
961 #elif defined(mingw32_HOST_OS)
962 execDir <- getExecDir "/bin/ghc-pkg.exe"
963 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
965 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
967 when (r /= ExitSuccess) $ exitWith r
968 hPutStrLn stderr (" done.")
970 -- -----------------------------------------------------------------------------
971 -- Searching for modules
975 findModules :: [FilePath] -> IO [String]
977 mms <- mapM searchDir paths
980 searchDir path prefix = do
981 fs <- getDirectoryEntries path `catch` \_ -> return []
982 searchEntries path prefix fs
984 searchEntries path prefix [] = return []
985 searchEntries path prefix (f:fs)
986 | looks_like_a_module = do
987 ms <- searchEntries path prefix fs
988 return (prefix `joinModule` f : ms)
989 | looks_like_a_component = do
990 ms <- searchDir (path </> f) (prefix `joinModule` f)
991 ms' <- searchEntries path prefix fs
994 searchEntries path prefix fs
997 (base,suffix) = splitFileExt f
998 looks_like_a_module =
999 suffix `elem` haskell_suffixes &&
1000 all okInModuleName base
1001 looks_like_a_component =
1002 null suffix && all okInModuleName base
1008 -- ---------------------------------------------------------------------------
1009 -- expanding environment variables in the package configuration
1011 expandEnvVars :: String -> Force -> IO String
1012 expandEnvVars str0 force = go str0 ""
1014 go "" acc = return $! reverse acc
1015 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1016 = do value <- lookupEnvVar var
1017 go rest (reverse value ++ acc)
1018 where close c = c == '}' || c == '\n' -- don't span newlines
1022 lookupEnvVar :: String -> IO String
1024 catch (System.Environment.getEnv nm)
1025 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1029 -----------------------------------------------------------------------------
1031 getProgramName :: IO String
1032 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1033 where str `withoutSuffix` suff
1034 | suff `isSuffixOf` str = take (length str - length suff) str
1037 bye :: String -> IO a
1038 bye s = putStr s >> exitWith ExitSuccess
1040 die :: String -> IO a
1043 dieWith :: Int -> String -> IO a
1046 prog <- getProgramName
1047 hPutStrLn stderr (prog ++ ": " ++ s)
1048 exitWith (ExitFailure ec)
1050 dieOrForceAll :: Force -> String -> IO ()
1051 dieOrForceAll ForceAll s = ignoreError s
1052 dieOrForceAll _other s = dieForcible s
1054 dieOrForceFile :: Force -> String -> IO ()
1055 dieOrForceFile ForceAll s = ignoreError s
1056 dieOrForceFile ForceFiles s = ignoreError s
1057 dieOrForceFile _other s = dieForcible s
1059 ignoreError :: String -> IO ()
1060 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1062 dieForcible :: String -> IO ()
1063 dieForcible s = die (s ++ " (use --force to override)")
1065 my_head :: String -> [a] -> a
1066 my_head s [] = error s
1067 my_head _ (x : _) = x
1069 -----------------------------------------
1070 -- Cut and pasted from ghc/compiler/main/SysTools
1072 #if defined(mingw32_HOST_OS)
1073 subst :: Char -> Char -> String -> String
1074 subst a b ls = map (\ x -> if x == a then b else x) ls
1076 unDosifyPath :: FilePath -> FilePath
1077 unDosifyPath xs = subst '\\' '/' xs
1079 getExecDir :: String -> IO (Maybe String)
1080 -- (getExecDir cmd) returns the directory in which the current
1081 -- executable, which should be called 'cmd', is running
1082 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1083 -- you'll get "/a/b/c" back as the result
1085 = allocaArray len $ \buf -> do
1086 ret <- getModuleFileName nullPtr buf len
1087 if ret == 0 then return Nothing
1088 else do s <- peekCString buf
1089 return (Just (reverse (drop (length cmd)
1090 (reverse (unDosifyPath s)))))
1092 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1094 foreign import stdcall unsafe "GetModuleFileNameA"
1095 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1097 getExecDir :: String -> IO (Maybe String)
1098 getExecDir _ = return Nothing
1101 -----------------------------------------
1102 -- Adapted from ghc/compiler/utils/Panic
1104 installSignalHandlers :: IO ()
1105 installSignalHandlers = do
1106 threadid <- myThreadId
1108 interrupt = throwTo threadid (Exception.ErrorCall "interrupted")
1110 #if !defined(mingw32_HOST_OS)
1111 installHandler sigQUIT (Catch interrupt) Nothing
1112 installHandler sigINT (Catch interrupt) Nothing
1114 #elif __GLASGOW_HASKELL__ >= 603
1115 -- GHC 6.3+ has support for console events on Windows
1116 -- NOTE: running GHCi under a bash shell for some reason requires
1117 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1118 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1119 -- why --SDM 17/12/2004
1120 let sig_handler ControlC = interrupt
1121 sig_handler Break = interrupt
1122 sig_handler _ = return ()
1124 installHandler (Catch sig_handler)
1127 return () -- nothing
1130 #if __GLASGOW_HASKELL__ <= 604
1131 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1132 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1135 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1136 #if __GLASGOW_HASKELL__ >= 609
1137 catchIO = Exception.catch
1139 catchIO io handler = io `Exception.catch` handler'
1140 where handler' (Exception.IOException ioe) = handler ioe
1141 handler' e = Exception.throw e
1144 throwIOIO :: Exception.IOException -> IO a
1145 #if __GLASGOW_HASKELL__ >= 609
1146 throwIOIO = Exception.throwIO
1148 throwIOIO ioe = Exception.throwIO (Exception.IOException ioe)
1151 catchError :: IO a -> (String -> IO a) -> IO a
1152 #if __GLASGOW_HASKELL__ >= 609
1153 catchError io handler = io `Exception.catch` handler'
1154 where handler' (Exception.ErrorCall err) = handler err
1156 catchError io handler = io `Exception.catch` handler'
1157 where handler' (Exception.ErrorCall err) = handler err
1158 handler' e = Exception.throw e
1161 onException :: IO a -> IO () -> IO a
1162 #if __GLASGOW_HASKELL__ >= 609
1163 onException = Exception.onException
1165 onException io what = io `Exception.catch` \e -> do what
1170 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1171 -- to use text files here, rather than binary files.
1172 writeFileAtomic :: FilePath -> String -> IO ()
1173 writeFileAtomic targetFile content = do
1174 (tmpFile, tmpHandle) <- openTempFile targetDir template
1175 do hPutStr tmpHandle content
1177 #if mingw32_HOST_OS || mingw32_TARGET_OS
1178 renameFile tmpFile targetFile
1179 -- If the targetFile exists then renameFile will fail
1180 `catchIO` \err -> do
1181 exists <- doesFileExist targetFile
1183 then do removeFile targetFile
1184 -- Big fat hairy race condition
1185 renameFile tmpFile targetFile
1186 -- If the removeFile succeeds and the renameFile fails
1187 -- then we've lost the atomic property.
1190 renameFile tmpFile targetFile
1192 `onException` do hClose tmpHandle
1195 template = targetName <.> "tmp"
1196 targetDir | null targetDir_ = "."
1197 | otherwise = targetDir_
1198 --TODO: remove this when takeDirectory/splitFileName is fixed
1199 -- to always return a valid dir
1200 (targetDir_,targetName) = splitFileName targetFile
1202 -- | The function splits the given string to substrings
1203 -- using 'isSearchPathSeparator'.
1204 parseSearchPath :: String -> [FilePath]
1205 parseSearchPath path = split path
1207 split :: String -> [String]
1211 _:rest -> chunk : split rest
1215 #ifdef mingw32_HOST_OS
1216 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1220 (chunk', rest') = break isSearchPathSeparator s