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 pkg <- parsePackageInfo expanded defines
416 validatePackageConfig pkg db_stack auto_ghci_libs update force
417 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
418 not_this p = package p /= package pkg
419 savingOldConfig db_filename $
420 writeNewConfig db_filename new_details
425 -> IO InstalledPackageInfo
426 parsePackageInfo str defines =
427 case parseInstalledPackageInfo str of
428 ParseOk _warns ok -> return ok
429 ParseFailed err -> case locatedErrorMsg err of
430 (Nothing, s) -> die s
431 (Just l, s) -> die (show l ++ ": " ++ s)
433 -- -----------------------------------------------------------------------------
434 -- Exposing, Hiding, Unregistering are all similar
436 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
437 exposePackage = modifyPackage (\p -> [p{exposed=True}])
439 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
440 hidePackage = modifyPackage (\p -> [p{exposed=False}])
442 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
443 unregisterPackage = modifyPackage (\p -> [])
446 :: (InstalledPackageInfo -> [InstalledPackageInfo])
450 modifyPackage fn pkgid flags = do
451 db_stack <- getPkgDatabases True{-modify-} flags
452 let ((db_name, pkgs) : _) = db_stack
453 ps <- findPackages [(db_name,pkgs)] pkgid
454 let pids = map package ps
455 let new_config = concat (map modify pkgs)
457 | package pkg `elem` pids = fn pkg
459 savingOldConfig db_name $
460 writeNewConfig db_name new_config
462 -- -----------------------------------------------------------------------------
465 listPackages :: [Flag] -> Maybe PackageIdentifier -> Maybe String -> IO ()
466 listPackages flags mPackageName mModuleName = do
467 let simple_output = FlagSimpleOutput `elem` flags
468 db_stack <- getPkgDatabases False flags
469 let db_stack_filtered -- if a package is given, filter out all other packages
470 | Just this <- mPackageName =
471 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
473 | Just this <- mModuleName = -- packages which expose mModuleName
474 map (\(conf,pkgs) -> (conf, filter (this `exposedInPkg`) pkgs))
476 | otherwise = db_stack
479 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
480 where sort_pkgs = sortBy cmpPkgIds
481 cmpPkgIds pkg1 pkg2 =
482 case pkgName p1 `compare` pkgName p2 of
485 EQ -> pkgVersion p1 `compare` pkgVersion p2
486 where (p1,p2) = (package pkg1, package pkg2)
488 pkg_map = map (\p -> (package p, p)) $ concatMap snd db_stack
489 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
491 show_func (reverse db_stack_sorted)
493 where show_normal pkg_map (db_name,pkg_confs) =
494 hPutStrLn stdout (render $
495 text db_name <> colon $$ nest 4 packages
497 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
499 | isBrokenPackage p pkg_map = braces doc
501 | otherwise = parens doc
502 where doc = text (showPackageId (package p))
504 show_simple db_stack = do
505 let showPkg = if FlagNamesOnly `elem` flags then pkgName
507 pkgs = map showPkg $ sortBy compPkgIdVer $
508 map package (concatMap snd db_stack)
509 when (null pkgs) $ die "no matches"
510 hPutStrLn stdout $ concat $ intersperse " " pkgs
512 -- -----------------------------------------------------------------------------
513 -- Prints the highest (hidden or exposed) version of a package
515 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
516 latestPackage flags pkgid = do
517 db_stack <- getPkgDatabases False flags
518 ps <- findPackages db_stack pkgid
519 show_pkg (sortBy compPkgIdVer (map package ps))
521 show_pkg [] = die "no matches"
522 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
524 -- -----------------------------------------------------------------------------
527 describePackage :: [Flag] -> PackageIdentifier -> IO ()
528 describePackage flags pkgid = do
529 db_stack <- getPkgDatabases False flags
530 ps <- findPackages db_stack pkgid
531 mapM_ (putStrLn . showInstalledPackageInfo) ps
533 -- PackageId is can have globVersion for the version
534 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
535 findPackages db_stack pkgid
536 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
537 [] -> die ("cannot find package " ++ showPackageId pkgid)
540 all_pkgs = concat (map snd db_stack)
542 matches :: PackageIdentifier -> PackageIdentifier -> Bool
544 = (pkgName pid == pkgName pid')
545 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
547 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
548 pid `matchesPkg` pkg = pid `matches` package pkg
550 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
551 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
553 exposedInPkg :: String -> InstalledPackageInfo -> Bool
554 moduleName `exposedInPkg` pkg = moduleName `elem` exposedModules pkg
556 -- -----------------------------------------------------------------------------
559 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
560 describeField flags pkgid field = do
561 db_stack <- getPkgDatabases False flags
562 case toField field of
563 Nothing -> die ("unknown field: " ++ field)
565 ps <- findPackages db_stack pkgid
566 let top_dir = takeDirectory (fst (last db_stack))
567 mapM_ (putStrLn . fn) (mungePackagePaths top_dir ps)
569 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
570 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
571 -- with the current topdir (obtained from the -B option).
572 mungePackagePaths top_dir ps = map munge_pkg ps
574 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
575 includeDirs = munge_paths (includeDirs p),
576 libraryDirs = munge_paths (libraryDirs p),
577 frameworkDirs = munge_paths (frameworkDirs p),
578 haddockInterfaces = munge_paths (haddockInterfaces p),
579 haddockHTMLs = munge_paths (haddockHTMLs p)
582 munge_paths = map munge_path
585 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
586 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
589 toHttpPath p = "file:///" ++ p
591 maybePrefixMatch :: String -> String -> Maybe String
592 maybePrefixMatch [] rest = Just rest
593 maybePrefixMatch (_:_) [] = Nothing
594 maybePrefixMatch (p:pat) (r:rest)
595 | p == r = maybePrefixMatch pat rest
596 | otherwise = Nothing
598 toField :: String -> Maybe (InstalledPackageInfo -> String)
599 -- backwards compatibility:
600 toField "import_dirs" = Just $ strList . importDirs
601 toField "source_dirs" = Just $ strList . importDirs
602 toField "library_dirs" = Just $ strList . libraryDirs
603 toField "hs_libraries" = Just $ strList . hsLibraries
604 toField "extra_libraries" = Just $ strList . extraLibraries
605 toField "include_dirs" = Just $ strList . includeDirs
606 toField "c_includes" = Just $ strList . includes
607 toField "package_deps" = Just $ strList . map showPackageId. depends
608 toField "extra_cc_opts" = Just $ strList . ccOptions
609 toField "extra_ld_opts" = Just $ strList . ldOptions
610 toField "framework_dirs" = Just $ strList . frameworkDirs
611 toField "extra_frameworks"= Just $ strList . frameworks
612 toField s = showInstalledPackageInfoField s
614 strList :: [String] -> String
618 -- -----------------------------------------------------------------------------
619 -- Check: Check consistency of installed packages
621 checkConsistency :: [Flag] -> IO ()
622 checkConsistency flags = do
623 db_stack <- getPkgDatabases False flags
624 let pkgs = map (\p -> (package p, p)) $ concatMap snd db_stack
627 let broken_deps = missingPackageDeps p pkgs
628 guard (not . null $ broken_deps)
629 return (pid, broken_deps)
630 mapM_ (putStrLn . render . show_func) broken_pkgs
632 show_func | FlagSimpleOutput `elem` flags = show_simple
633 | otherwise = show_normal
634 show_simple (pid,deps) =
635 text (showPackageId pid) <> colon
636 <+> fsep (punctuate comma (map (text . showPackageId) deps))
637 show_normal (pid,deps) =
638 text "package" <+> text (showPackageId pid) <+> text "has missing dependencies:"
639 $$ nest 4 (fsep (punctuate comma (map (text . showPackageId) deps)))
641 missingPackageDeps :: InstalledPackageInfo
642 -> [(PackageIdentifier, InstalledPackageInfo)]
643 -> [PackageIdentifier]
644 missingPackageDeps pkg pkg_map =
645 [ d | d <- depends pkg, isNothing (lookup d pkg_map)] ++
646 [ d | d <- depends pkg, Just p <- return (lookup d pkg_map), isBrokenPackage p pkg_map]
648 isBrokenPackage :: InstalledPackageInfo -> [(PackageIdentifier, InstalledPackageInfo)] -> Bool
649 isBrokenPackage pkg pkg_map = not . null $ missingPackageDeps pkg pkg_map
652 -- -----------------------------------------------------------------------------
653 -- Manipulating package.conf files
655 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
656 writeNewConfig filename packages = do
657 hPutStr stdout "Writing new package config file... "
658 createDirectoryIfMissing True $ takeDirectory filename
659 h <- openFile filename WriteMode `catch` \e ->
660 if isPermissionError e
661 then die (filename ++ ": you don't have permission to modify this file")
663 let shown = concat $ intersperse ",\n " $ map show packages
664 fileContents = "[" ++ shown ++ "\n]"
665 hPutStrLn h fileContents
667 hPutStrLn stdout "done."
669 savingOldConfig :: FilePath -> IO () -> IO ()
670 savingOldConfig filename io = Exception.block $ do
671 hPutStr stdout "Saving old package config file... "
672 -- mv rather than cp because we've already done an hGetContents
673 -- on this file so we won't be able to open it for writing
674 -- unless we move the old one out of the way...
675 let oldFile = filename ++ ".old"
676 restore_on_error <- catch (renameFile filename oldFile >> return True) $
678 unless (isDoesNotExistError err) $ do
679 hPutStrLn stderr (unwords ["Unable to rename", show filename,
683 hPutStrLn stdout "done."
685 hPutStrLn stderr (show e)
686 hPutStr stdout ("\nWARNING: an error was encountered while writing"
687 ++ "the new configuration.\n")
688 when restore_on_error $ do
689 hPutStr stdout "Attempting to restore the old configuration..."
690 do renameFile oldFile filename
691 hPutStrLn stdout "done."
692 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
695 -----------------------------------------------------------------------------
696 -- Sanity-check a new package config, and automatically build GHCi libs
699 validatePackageConfig :: InstalledPackageInfo
701 -> Bool -- auto-ghc-libs
705 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
707 checkDuplicates db_stack pkg update
708 mapM_ (checkDep db_stack force) (depends pkg)
709 mapM_ (checkDir force) (importDirs pkg)
710 mapM_ (checkDir force) (libraryDirs pkg)
711 mapM_ (checkDir force) (includeDirs pkg)
712 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
713 -- ToDo: check these somehow?
714 -- extra_libraries :: [String],
715 -- c_includes :: [String],
717 -- When the package name and version are put together, sometimes we can
718 -- end up with a package id that cannot be parsed. This will lead to
719 -- difficulties when the user wants to refer to the package later, so
720 -- we check that the package id can be parsed properly here.
721 checkPackageId :: InstalledPackageInfo -> IO ()
723 let str = showPackageId (package ipi) in
724 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
726 [] -> die ("invalid package identifier: " ++ str)
727 _ -> die ("ambiguous package identifier: " ++ str)
729 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
730 checkDuplicates db_stack pkg update = do
733 (_top_db_name, pkgs) : _ = db_stack
735 -- Check whether this package id already exists in this DB
737 when (not update && (pkgid `elem` map package pkgs)) $
738 die ("package " ++ showPackageId pkgid ++ " is already installed")
742 checkDir :: Force -> String -> IO ()
744 | "$topdir" `isPrefixOf` d = return ()
745 | "$httptopdir" `isPrefixOf` d = return ()
746 -- can't check these, because we don't know what $(http)topdir is
748 there <- doesDirectoryExist d
750 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
752 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
753 checkDep db_stack force pkgid
754 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
755 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
758 -- for backwards compat, we treat 0.0 as a special version,
759 -- and don't check that it actually exists.
760 real_version = realVersion pkgid
762 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
765 all_pkgs = concat (map snd db_stack)
766 pkgids = map package all_pkgs
768 realVersion :: PackageIdentifier -> Bool
769 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
771 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
772 checkHSLib dirs auto_ghci_libs force lib = do
773 let batch_lib_file = "lib" ++ lib ++ ".a"
774 bs <- mapM (doesLibExistIn batch_lib_file) dirs
775 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
776 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
778 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
780 doesLibExistIn :: String -> String -> IO Bool
782 | "$topdir" `isPrefixOf` d = return True
783 | "$httptopdir" `isPrefixOf` d = return True
784 | otherwise = doesFileExist (d ++ '/':lib)
786 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
787 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
788 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
790 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
791 case [dir | (exists,dir) <- zip bs dirs, exists] of
792 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
795 ghci_lib_file = lib ++ ".o"
797 -- automatically build the GHCi version of a batch lib,
798 -- using ld --whole-archive.
800 autoBuildGHCiLib :: String -> String -> String -> IO ()
801 autoBuildGHCiLib dir batch_file ghci_file = do
802 let ghci_lib_file = dir ++ '/':ghci_file
803 batch_lib_file = dir ++ '/':batch_file
804 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
805 #if defined(darwin_HOST_OS)
806 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
807 #elif defined(mingw32_HOST_OS)
808 execDir <- getExecDir "/bin/ghc-pkg.exe"
809 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
811 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
813 when (r /= ExitSuccess) $ exitWith r
814 hPutStrLn stderr (" done.")
816 -- -----------------------------------------------------------------------------
817 -- Searching for modules
821 findModules :: [FilePath] -> IO [String]
823 mms <- mapM searchDir paths
826 searchDir path prefix = do
827 fs <- getDirectoryEntries path `catch` \_ -> return []
828 searchEntries path prefix fs
830 searchEntries path prefix [] = return []
831 searchEntries path prefix (f:fs)
832 | looks_like_a_module = do
833 ms <- searchEntries path prefix fs
834 return (prefix `joinModule` f : ms)
835 | looks_like_a_component = do
836 ms <- searchDir (path </> f) (prefix `joinModule` f)
837 ms' <- searchEntries path prefix fs
840 searchEntries path prefix fs
843 (base,suffix) = splitFileExt f
844 looks_like_a_module =
845 suffix `elem` haskell_suffixes &&
846 all okInModuleName base
847 looks_like_a_component =
848 null suffix && all okInModuleName base
854 -- -----------------------------------------------------------------------------
855 -- The old command-line syntax, supported for backwards compatibility
862 | OF_Add Bool {- True => replace existing info -}
863 | OF_Remove String | OF_Show String
864 | OF_Field String | OF_AutoGHCiLibs | OF_Force
865 | OF_DefinedName String String
866 | OF_GlobalConfig FilePath
869 isAction :: OldFlag -> Bool
870 isAction OF_Config{} = False
871 isAction OF_Field{} = False
872 isAction OF_Input{} = False
873 isAction OF_AutoGHCiLibs{} = False
874 isAction OF_Force{} = False
875 isAction OF_DefinedName{} = False
876 isAction OF_GlobalConfig{} = False
879 oldFlags :: [OptDescr OldFlag]
881 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
882 "use the specified package config file",
883 Option ['l'] ["list-packages"] (NoArg OF_List)
884 "list packages in all config files",
885 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
886 "list packages in the specified config file",
887 Option ['a'] ["add-package"] (NoArg (OF_Add False))
889 Option ['u'] ["update-package"] (NoArg (OF_Add True))
890 "update package with new configuration",
891 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
892 "read new package info from specified file",
893 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
894 "show the configuration for package NAME",
895 Option [] ["field"] (ReqArg OF_Field "FIELD")
896 "(with --show-package) Show field FIELD only",
897 Option [] ["force"] (NoArg OF_Force)
898 "ignore missing directories/libraries",
899 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
900 "remove an installed package",
901 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
902 "automatically build libs for GHCi (with -a)",
903 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
904 "define NAME as VALUE",
905 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
906 "location of the global package config"
910 case break (=='=') str of
911 (nm,[]) -> OF_DefinedName nm []
912 (nm,_:val) -> OF_DefinedName nm val
914 oldRunit :: [OldFlag] -> IO ()
916 let new_flags = [ f | Just f <- map conv clis ]
918 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
919 conv (OF_Config f) = Just (FlagConfig f)
924 let fields = [ f | OF_Field f <- clis ]
926 let auto_ghci_libs = any isAuto clis
927 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
928 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
930 force = if OF_Force `elem` clis then ForceAll else NoForce
932 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
934 case [ c | c <- clis, isAction c ] of
935 [ OF_List ] -> listPackages new_flags Nothing Nothing
936 [ OF_ListLocal ] -> listPackages new_flags Nothing Nothing
938 registerPackage input_file defines new_flags auto_ghci_libs upd force
939 [ OF_Remove pkgid_str ] -> do
940 pkgid <- readPkgId pkgid_str
941 unregisterPackage pkgid new_flags
942 [ OF_Show pkgid_str ]
944 pkgid <- readPkgId pkgid_str
945 describePackage new_flags pkgid
947 pkgid <- readPkgId pkgid_str
948 mapM_ (describeField new_flags pkgid) fields
950 prog <- getProgramName
951 die (usageInfo (usageHeader prog) flags)
953 my_head :: String -> [a] -> a
954 my_head s [] = error s
957 -- ---------------------------------------------------------------------------
958 -- expanding environment variables in the package configuration
960 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
961 expandEnvVars str defines force = go str ""
963 go "" acc = return $! reverse acc
964 go ('$':'{':str) acc | (var, '}':rest) <- break close str
965 = do value <- lookupEnvVar var
966 go rest (reverse value ++ acc)
967 where close c = c == '}' || c == '\n' -- don't span newlines
971 lookupEnvVar :: String -> IO String
973 case lookup nm defines of
974 Just x | not (null x) -> return x
976 catch (System.getEnv nm)
977 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
981 -----------------------------------------------------------------------------
983 getProgramName :: IO String
984 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
985 where str `withoutSuffix` suff
986 | suff `isSuffixOf` str = take (length str - length suff) str
989 bye :: String -> IO a
990 bye s = putStr s >> exitWith ExitSuccess
992 die :: String -> IO a
995 prog <- getProgramName
996 hPutStrLn stderr (prog ++ ": " ++ s)
997 exitWith (ExitFailure 1)
999 dieOrForceAll :: Force -> String -> IO ()
1000 dieOrForceAll ForceAll s = ignoreError s
1001 dieOrForceAll _other s = dieForcible s
1003 dieOrForceFile :: Force -> String -> IO ()
1004 dieOrForceFile ForceAll s = ignoreError s
1005 dieOrForceFile ForceFiles s = ignoreError s
1006 dieOrForceFile _other s = dieForcible s
1008 ignoreError :: String -> IO ()
1009 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
1011 dieForcible :: String -> IO ()
1012 dieForcible s = die (s ++ " (use --force to override)")
1014 -----------------------------------------
1015 -- Cut and pasted from ghc/compiler/SysTools
1017 #if defined(mingw32_HOST_OS)
1018 subst :: Char -> Char -> String -> String
1019 subst a b ls = map (\ x -> if x == a then b else x) ls
1021 unDosifyPath :: FilePath -> FilePath
1022 unDosifyPath xs = subst '\\' '/' xs
1024 getExecDir :: String -> IO (Maybe String)
1025 -- (getExecDir cmd) returns the directory in which the current
1026 -- executable, which should be called 'cmd', is running
1027 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1028 -- you'll get "/a/b/c" back as the result
1030 = allocaArray len $ \buf -> do
1031 ret <- getModuleFileName nullPtr buf len
1032 if ret == 0 then return Nothing
1033 else do s <- peekCString buf
1034 return (Just (reverse (drop (length cmd)
1035 (reverse (unDosifyPath s)))))
1037 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
1039 foreign import stdcall unsafe "GetModuleFileNameA"
1040 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1042 getExecDir :: String -> IO (Maybe String)
1043 getExecDir _ = return Nothing