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 ( showError )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem ( rawSystem )
29 #include "../../includes/ghcconfig.h"
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
39 import qualified Exception
43 import Data.Char ( isSpace )
46 import System ( getArgs, getProgName, getEnv,
47 exitWith, ExitCode(..)
50 #if __GLASGOW_HASKELL__ >= 600
51 import System.IO.Error (try)
53 import System.IO (try)
55 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy )
57 #ifdef mingw32_HOST_OS
60 #if __GLASGOW_HASKELL__ >= 504
61 import Foreign.C.String
67 import IO ( isPermissionError, isDoesNotExistError )
69 -- -----------------------------------------------------------------------------
76 case getOpt Permute flags args of
77 (cli,_,[]) | FlagHelp `elem` cli -> do
78 prog <- getProgramName
79 bye (usageInfo (usageHeader prog) flags)
80 (cli,_,[]) | FlagVersion `elem` cli ->
84 (_,_,errors) -> tryOldCmdLine errors args
86 -- If the new command-line syntax fails, then we try the old. If that
87 -- fails too, then we output the original errors and the new syntax
88 -- (so the old syntax is still available, but hidden).
89 tryOldCmdLine :: [String] -> [String] -> IO ()
90 tryOldCmdLine errors args = do
91 case getOpt Permute oldFlags args of
95 prog <- getProgramName
96 die (concat errors ++ usageInfo (usageHeader prog) flags)
98 -- -----------------------------------------------------------------------------
99 -- Command-line syntax
106 | FlagConfig FilePath
107 | FlagGlobalConfig FilePath
111 | FlagDefinedName String String
115 flags :: [OptDescr Flag]
117 Option [] ["user"] (NoArg FlagUser)
118 "use the current user's package database",
119 Option [] ["global"] (NoArg FlagGlobal)
120 "(default) use the global package database",
121 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
122 "act upon specified package config file (only)",
123 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
124 "location of the global package config",
125 Option [] ["force"] (NoArg FlagForce)
126 "ignore missing dependencies, directories, and libraries",
127 Option [] ["force-files"] (NoArg FlagForceFiles)
128 "ignore missing directories and libraries only",
129 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
130 "automatically build libs for GHCi (with register)",
131 Option ['?'] ["help"] (NoArg FlagHelp)
132 "display this help and exit",
133 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
134 "define NAME as VALUE",
135 Option ['V'] ["version"] (NoArg FlagVersion)
136 "output version information and exit",
137 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
138 "print output in easy-to-parse format when running command 'list'"
142 case break (=='=') str of
143 (nm,[]) -> FlagDefinedName nm []
144 (nm,_:val) -> FlagDefinedName nm val
146 ourCopyright :: String
147 ourCopyright = "GHC package manager version " ++ version ++ "\n"
149 usageHeader :: String -> String
150 usageHeader prog = substProg prog $
152 " $p register {filename | -}\n" ++
153 " Register the package using the specified installed package\n" ++
154 " description. The syntax for the latter is given in the $p\n" ++
155 " documentation.\n" ++
157 " $p update {filename | -}\n" ++
158 " Register the package, overwriting any other package with the\n" ++
161 " $p unregister {pkg-id}\n" ++
162 " Unregister the specified package.\n" ++
164 " $p expose {pkg-id}\n" ++
165 " Expose the specified package.\n" ++
167 " $p hide {pkg-id}\n" ++
168 " Hide the specified package.\n" ++
170 " $p list [pkg]\n" ++
171 " List registered packages in the global database, and also the\n" ++
172 " user database if --user is given. If a package name is given\n" ++
173 " all the registered versions will be listed in ascending order.\n" ++
175 " $p latest pkg\n" ++
176 " Prints the highest registered version of a package.\n" ++
178 " $p describe {pkg-id}\n" ++
179 " Give the registered description for the specified package. The\n" ++
180 " description is returned in precisely the syntax required by $p\n" ++
183 " $p field {pkg-id} {field}\n" ++
184 " Extract the specified field of the package description for the\n" ++
185 " specified package.\n" ++
187 " The following optional flags are also accepted:\n"
189 substProg :: String -> String -> String
191 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
192 substProg prog (c:xs) = c : substProg prog xs
194 -- -----------------------------------------------------------------------------
197 data Force = ForceAll | ForceFiles | NoForce
199 runit :: [Flag] -> [String] -> IO ()
200 runit cli nonopts = do
201 prog <- getProgramName
204 | FlagForce `elem` cli = ForceAll
205 | FlagForceFiles `elem` cli = ForceFiles
206 | otherwise = NoForce
207 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
208 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
210 -- first, parse the command
212 ["register", filename] ->
213 registerPackage filename defines cli auto_ghci_libs False force
214 ["update", filename] ->
215 registerPackage filename defines cli auto_ghci_libs True force
216 ["unregister", pkgid_str] -> do
217 pkgid <- readGlobPkgId pkgid_str
218 unregisterPackage pkgid cli
219 ["expose", pkgid_str] -> do
220 pkgid <- readGlobPkgId pkgid_str
221 exposePackage pkgid cli
222 ["hide", pkgid_str] -> do
223 pkgid <- readGlobPkgId pkgid_str
224 hidePackage pkgid cli
226 listPackages cli Nothing
227 ["list", pkgid_str] -> do
228 pkgid <- readGlobPkgId pkgid_str
229 listPackages cli (Just pkgid)
230 ["latest", pkgid_str] -> do
231 pkgid <- readGlobPkgId pkgid_str
232 latestPackage cli pkgid
233 ["describe", pkgid_str] -> do
234 pkgid <- readGlobPkgId pkgid_str
235 describePackage cli pkgid
236 ["field", pkgid_str, field] -> do
237 pkgid <- readGlobPkgId pkgid_str
238 describeField cli pkgid field
240 die ("missing command\n" ++
241 usageInfo (usageHeader prog) flags)
243 die ("command-line syntax error\n" ++
244 usageInfo (usageHeader prog) flags)
246 parseCheck :: ReadP a a -> String -> String -> IO a
247 parseCheck parser str what =
248 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
250 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
252 readPkgId :: String -> IO PackageIdentifier
253 readPkgId str = parseCheck parsePackageId str "package identifier"
255 readGlobPkgId :: String -> IO PackageIdentifier
256 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
258 parseGlobPackageId :: ReadP r PackageIdentifier
262 (do n <- parsePackageName; string "-*"
263 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
265 -- globVersion means "all versions"
266 globVersion :: Version
267 globVersion = Version{ versionBranch=[], versionTags=["*"] }
269 -- -----------------------------------------------------------------------------
272 -- Some commands operate on a single database:
273 -- register, unregister, expose, hide
274 -- however these commands also check the union of the available databases
275 -- in order to check consistency. For example, register will check that
276 -- dependencies exist before registering a package.
278 -- Some commands operate on multiple databases, with overlapping semantics:
279 -- list, describe, field
281 type PackageDBName = FilePath
282 type PackageDB = [InstalledPackageInfo]
284 type PackageDBStack = [(PackageDBName,PackageDB)]
285 -- A stack of package databases. Convention: head is the topmost
286 -- in the stack. Earlier entries override later one.
288 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
289 getPkgDatabases modify flags = do
290 -- first we determine the location of the global package config. On Windows,
291 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
292 -- location is passed to the binary using the --global-config flag by the
294 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
296 case [ f | FlagGlobalConfig f <- flags ] of
297 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
299 Nothing -> die err_msg
300 Just dir -> return (dir `joinFileName` "package.conf")
301 fs -> return (last fs)
303 let global_conf_dir = global_conf ++ ".d"
304 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
306 if global_conf_dir_exists
307 then do files <- getDirectoryContents global_conf_dir
308 return [ global_conf_dir ++ '/' : file
310 , isSuffixOf ".conf" file]
313 -- get the location of the user package database, and create it if necessary
314 appdir <- getAppUserDataDirectory "ghc"
317 subdir = targetARCH ++ '-':targetOS ++ '-':version
318 archdir = appdir `joinFileName` subdir
319 user_conf = archdir `joinFileName` "package.conf"
320 user_exists <- doesFileExist user_conf
322 -- If the user database doesn't exist, and this command isn't a
323 -- "modify" command, then we won't attempt to create or use it.
325 | modify || user_exists = user_conf : global_confs ++ [global_conf]
326 | otherwise = global_confs ++ [global_conf]
328 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
331 Left _ -> sys_databases
333 | last cs == "" -> init cs ++ sys_databases
335 where cs = parseSearchPath path
337 -- The "global" database is always the one at the bottom of the stack.
338 -- This is the database we modify by default.
339 virt_global_conf = last env_stack
341 -- -f flags on the command line add to the database stack, unless any
342 -- of them are present in the stack already.
343 let flag_stack = filter (`notElem` env_stack)
344 [ f | FlagConfig f <- reverse flags ] ++ env_stack
346 -- Now we have the full stack of databases. Next, if the current
347 -- command is a "modify" type command, then we truncate the stack
348 -- so that the topmost element is the database being modified.
351 then return flag_stack
353 go (FlagUser : fs) = modifying user_conf
354 go (FlagGlobal : fs) = modifying virt_global_conf
355 go (FlagConfig f : fs) = modifying f
357 go [] = modifying virt_global_conf
360 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
361 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
365 db_stack <- mapM readParseDatabase final_stack
368 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
369 readParseDatabase filename = do
370 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
371 let packages = read str
372 Exception.evaluate packages
373 `Exception.catch` \_ ->
374 die (filename ++ ": parse error in package config file")
375 return (filename,packages)
377 emptyPackageConfig :: String
378 emptyPackageConfig = "[]"
380 -- -----------------------------------------------------------------------------
383 registerPackage :: FilePath
384 -> [(String,String)] -- defines
386 -> Bool -- auto_ghci_libs
390 registerPackage input defines flags auto_ghci_libs update force = do
391 db_stack <- getPkgDatabases True flags
393 db_to_operate_on = my_head "db" db_stack
394 db_filename = fst db_to_operate_on
400 putStr "Reading package info from stdin ... "
403 putStr ("Reading package info from " ++ show f ++ " ... ")
406 expanded <- expandEnvVars s defines force
408 pkg0 <- parsePackageInfo expanded defines
411 let pkg = resolveDeps db_stack pkg0
412 validatePackageConfig pkg db_stack auto_ghci_libs update force
413 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
414 not_this p = package p /= package pkg
415 savingOldConfig db_filename $
416 writeNewConfig db_filename new_details
421 -> IO InstalledPackageInfo
422 parsePackageInfo str defines =
423 case parseInstalledPackageInfo str of
424 ParseOk _warns ok -> return ok
425 ParseFailed err -> die (showError err)
427 -- -----------------------------------------------------------------------------
428 -- Exposing, Hiding, Unregistering are all similar
430 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
431 exposePackage = modifyPackage (\p -> [p{exposed=True}])
433 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
434 hidePackage = modifyPackage (\p -> [p{exposed=False}])
436 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
437 unregisterPackage = modifyPackage (\p -> [])
440 :: (InstalledPackageInfo -> [InstalledPackageInfo])
444 modifyPackage fn pkgid flags = do
445 db_stack <- getPkgDatabases True{-modify-} flags
446 let ((db_name, pkgs) : _) = db_stack
447 ps <- findPackages [(db_name,pkgs)] pkgid
448 let pids = map package ps
449 let new_config = concat (map modify pkgs)
451 | package pkg `elem` pids = fn pkg
453 savingOldConfig db_name $
454 writeNewConfig db_name new_config
456 -- -----------------------------------------------------------------------------
459 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
460 listPackages flags mPackageName = do
461 let simple_output = FlagSimpleOutput `elem` flags
462 db_stack <- getPkgDatabases False flags
463 let db_stack_filtered -- if a package is given, filter out all other packages
464 | Just this <- mPackageName =
465 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
467 | otherwise = db_stack
470 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
471 where sort_pkgs = sortBy cmpPkgIds
472 cmpPkgIds pkg1 pkg2 =
473 case pkgName p1 `compare` pkgName p2 of
476 EQ -> pkgVersion p1 `compare` pkgVersion p2
477 where (p1,p2) = (package pkg1, package pkg2)
479 show_func = if simple_output then show_easy else mapM_ show_regular
481 show_func (reverse db_stack_sorted)
483 where show_regular (db_name,pkg_confs) =
484 hPutStrLn stdout (render $
485 text (db_name ++ ":") $$ nest 4 packages
487 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
490 | otherwise = parens doc
491 where doc = text (showPackageId (package p))
493 show_easy db_stack = do
494 let pkgs = map showPackageId $ sortBy compPkgIdVer $
495 map package (concatMap snd db_stack)
496 when (null pkgs) $ die "no matches"
497 hPutStrLn stdout $ concat $ intersperse " " pkgs
499 -- -----------------------------------------------------------------------------
500 -- Prints the highest (hidden or exposed) version of a package
502 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
503 latestPackage flags pkgid = do
504 db_stack <- getPkgDatabases False flags
505 ps <- findPackages db_stack pkgid
506 show_pkg (sortBy compPkgIdVer (map package ps))
508 show_pkg [] = die "no matches"
509 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
511 -- -----------------------------------------------------------------------------
514 describePackage :: [Flag] -> PackageIdentifier -> IO ()
515 describePackage flags pkgid = do
516 db_stack <- getPkgDatabases False flags
517 ps <- findPackages db_stack pkgid
518 mapM_ (putStrLn . showInstalledPackageInfo) ps
520 -- PackageId is can have globVersion for the version
521 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
522 findPackages db_stack pkgid
523 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
524 [] -> die ("cannot find package " ++ showPackageId pkgid)
527 all_pkgs = concat (map snd db_stack)
529 matches :: PackageIdentifier -> PackageIdentifier -> Bool
531 = (pkgName pid == pkgName pid')
532 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
534 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
535 pid `matchesPkg` pkg = pid `matches` package pkg
537 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
538 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
540 -- -----------------------------------------------------------------------------
543 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
544 describeField flags pkgid field = do
545 db_stack <- getPkgDatabases False flags
546 case toField field of
547 Nothing -> die ("unknown field: " ++ field)
549 ps <- findPackages db_stack pkgid
550 mapM_ (putStrLn.fn) ps
552 toField :: String -> Maybe (InstalledPackageInfo -> String)
553 -- backwards compatibility:
554 toField "import_dirs" = Just $ strList . importDirs
555 toField "source_dirs" = Just $ strList . importDirs
556 toField "library_dirs" = Just $ strList . libraryDirs
557 toField "hs_libraries" = Just $ strList . hsLibraries
558 toField "extra_libraries" = Just $ strList . extraLibraries
559 toField "include_dirs" = Just $ strList . includeDirs
560 toField "c_includes" = Just $ strList . includes
561 toField "package_deps" = Just $ strList . map showPackageId. depends
562 toField "extra_cc_opts" = Just $ strList . ccOptions
563 toField "extra_ld_opts" = Just $ strList . ldOptions
564 toField "framework_dirs" = Just $ strList . frameworkDirs
565 toField "extra_frameworks"= Just $ strList . frameworks
566 toField s = showInstalledPackageInfoField s
568 strList :: [String] -> String
571 -- -----------------------------------------------------------------------------
572 -- Manipulating package.conf files
574 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
575 writeNewConfig filename packages = do
576 hPutStr stdout "Writing new package config file... "
577 createDirectoryIfMissing True $ getFilenameDir filename
578 h <- openFile filename WriteMode `catch` \e ->
579 if isPermissionError e
580 then die (filename ++ ": you don't have permission to modify this file")
582 hPutStrLn h (show packages)
584 hPutStrLn stdout "done."
586 savingOldConfig :: FilePath -> IO () -> IO ()
587 savingOldConfig filename io = Exception.block $ do
588 hPutStr stdout "Saving old package config file... "
589 -- mv rather than cp because we've already done an hGetContents
590 -- on this file so we won't be able to open it for writing
591 -- unless we move the old one out of the way...
592 let oldFile = filename ++ ".old"
593 restore_on_error <- catch (renameFile filename oldFile >> return True) $
595 unless (isDoesNotExistError err) $ do
596 hPutStrLn stderr (unwords ["Unable to rename", show filename,
600 hPutStrLn stdout "done."
602 hPutStrLn stderr (show e)
603 hPutStr stdout ("\nWARNING: an error was encountered while writing"
604 ++ "the new configuration.\n")
605 when restore_on_error $ do
606 hPutStr stdout "Attempting to restore the old configuration..."
607 do renameFile oldFile filename
608 hPutStrLn stdout "done."
609 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
612 -----------------------------------------------------------------------------
613 -- Sanity-check a new package config, and automatically build GHCi libs
616 validatePackageConfig :: InstalledPackageInfo
618 -> Bool -- auto-ghc-libs
622 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
624 checkDuplicates db_stack pkg update
625 mapM_ (checkDep db_stack force) (depends pkg)
626 mapM_ (checkDir force) (importDirs pkg)
627 mapM_ (checkDir force) (libraryDirs pkg)
628 mapM_ (checkDir force) (includeDirs pkg)
629 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
630 -- ToDo: check these somehow?
631 -- extra_libraries :: [String],
632 -- c_includes :: [String],
634 -- When the package name and version are put together, sometimes we can
635 -- end up with a package id that cannot be parsed. This will lead to
636 -- difficulties when the user wants to refer to the package later, so
637 -- we check that the package id can be parsed properly here.
638 checkPackageId :: InstalledPackageInfo -> IO ()
640 let str = showPackageId (package ipi) in
641 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
643 [] -> die ("invalid package identifier: " ++ str)
644 _ -> die ("ambiguous package identifier: " ++ str)
646 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
647 resolveDeps db_stack p = updateDeps p
649 -- The input package spec is allowed to give a package dependency
650 -- without a version number; e.g.
652 -- Here, we update these dependencies without version numbers to
653 -- match the actual versions of the relevant packages installed.
654 updateDeps p = p{depends = map resolveDep (depends p)}
657 | realVersion dep_pkgid = dep_pkgid
658 | otherwise = lookupDep dep_pkgid
662 name = pkgName dep_pkgid
664 case [ pid | p <- concat (map snd db_stack),
666 pkgName pid == name ] of
667 (pid:_) -> pid -- Found installed package,
668 -- replete with its version
669 [] -> dep_pkgid -- No installed package; use
670 -- the version-less one
672 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
673 checkDuplicates db_stack pkg update = do
676 (_top_db_name, pkgs) : _ = db_stack
678 -- Check whether this package id already exists in this DB
680 when (not update && (pkgid `elem` map package pkgs)) $
681 die ("package " ++ showPackageId pkgid ++ " is already installed")
685 checkDir :: Force -> String -> IO ()
687 | "$topdir" `isPrefixOf` d = return ()
688 -- can't check this, because we don't know what $topdir is
690 there <- doesDirectoryExist d
692 (dieOrForceFile force (d ++ " doesn't exist or isn't a directory"))
694 checkDep :: PackageDBStack -> Force -> PackageIdentifier -> IO ()
695 checkDep db_stack force pkgid
696 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
697 | otherwise = dieOrForceAll force ("dependency " ++ showPackageId pkgid
700 -- for backwards compat, we treat 0.0 as a special version,
701 -- and don't check that it actually exists.
702 real_version = realVersion pkgid
704 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
707 all_pkgs = concat (map snd db_stack)
708 pkgids = map package all_pkgs
710 realVersion :: PackageIdentifier -> Bool
711 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
713 checkHSLib :: [String] -> Bool -> Force -> String -> IO ()
714 checkHSLib dirs auto_ghci_libs force lib = do
715 let batch_lib_file = "lib" ++ lib ++ ".a"
716 bs <- mapM (doesLibExistIn batch_lib_file) dirs
717 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
718 [] -> dieOrForceFile force ("cannot find " ++ batch_lib_file ++
720 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
722 doesLibExistIn :: String -> String -> IO Bool
724 | "$topdir" `isPrefixOf` d = return True
725 | otherwise = doesFileExist (d ++ '/':lib)
727 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
728 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
729 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
731 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
732 case [dir | (exists,dir) <- zip bs dirs, exists] of
733 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
736 ghci_lib_file = lib ++ ".o"
738 -- automatically build the GHCi version of a batch lib,
739 -- using ld --whole-archive.
741 autoBuildGHCiLib :: String -> String -> String -> IO ()
742 autoBuildGHCiLib dir batch_file ghci_file = do
743 let ghci_lib_file = dir ++ '/':ghci_file
744 batch_lib_file = dir ++ '/':batch_file
745 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
746 #if defined(darwin_HOST_OS)
747 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
748 #elif defined(mingw32_HOST_OS)
749 execDir <- getExecDir "/bin/ghc-pkg.exe"
750 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
752 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
754 when (r /= ExitSuccess) $ exitWith r
755 hPutStrLn stderr (" done.")
757 -- -----------------------------------------------------------------------------
758 -- Searching for modules
762 findModules :: [FilePath] -> IO [String]
764 mms <- mapM searchDir paths
767 searchDir path prefix = do
768 fs <- getDirectoryEntries path `catch` \_ -> return []
769 searchEntries path prefix fs
771 searchEntries path prefix [] = return []
772 searchEntries path prefix (f:fs)
773 | looks_like_a_module = do
774 ms <- searchEntries path prefix fs
775 return (prefix `joinModule` f : ms)
776 | looks_like_a_component = do
777 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
778 ms' <- searchEntries path prefix fs
781 searchEntries path prefix fs
784 (base,suffix) = splitFileExt f
785 looks_like_a_module =
786 suffix `elem` haskell_suffixes &&
787 all okInModuleName base
788 looks_like_a_component =
789 null suffix && all okInModuleName base
795 -- -----------------------------------------------------------------------------
796 -- The old command-line syntax, supported for backwards compatibility
803 | OF_Add Bool {- True => replace existing info -}
804 | OF_Remove String | OF_Show String
805 | OF_Field String | OF_AutoGHCiLibs | OF_Force
806 | OF_DefinedName String String
807 | OF_GlobalConfig FilePath
810 isAction :: OldFlag -> Bool
811 isAction OF_Config{} = False
812 isAction OF_Field{} = False
813 isAction OF_Input{} = False
814 isAction OF_AutoGHCiLibs{} = False
815 isAction OF_Force{} = False
816 isAction OF_DefinedName{} = False
817 isAction OF_GlobalConfig{} = False
820 oldFlags :: [OptDescr OldFlag]
822 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
823 "use the specified package config file",
824 Option ['l'] ["list-packages"] (NoArg OF_List)
825 "list packages in all config files",
826 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
827 "list packages in the specified config file",
828 Option ['a'] ["add-package"] (NoArg (OF_Add False))
830 Option ['u'] ["update-package"] (NoArg (OF_Add True))
831 "update package with new configuration",
832 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
833 "read new package info from specified file",
834 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
835 "show the configuration for package NAME",
836 Option [] ["field"] (ReqArg OF_Field "FIELD")
837 "(with --show-package) Show field FIELD only",
838 Option [] ["force"] (NoArg OF_Force)
839 "ignore missing directories/libraries",
840 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
841 "remove an installed package",
842 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
843 "automatically build libs for GHCi (with -a)",
844 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
845 "define NAME as VALUE",
846 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
847 "location of the global package config"
851 case break (=='=') str of
852 (nm,[]) -> OF_DefinedName nm []
853 (nm,_:val) -> OF_DefinedName nm val
855 oldRunit :: [OldFlag] -> IO ()
857 let new_flags = [ f | Just f <- map conv clis ]
859 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
860 conv (OF_Config f) = Just (FlagConfig f)
865 let fields = [ f | OF_Field f <- clis ]
867 let auto_ghci_libs = any isAuto clis
868 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
869 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
871 force = if OF_Force `elem` clis then ForceAll else NoForce
873 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
875 case [ c | c <- clis, isAction c ] of
876 [ OF_List ] -> listPackages new_flags Nothing
877 [ OF_ListLocal ] -> listPackages new_flags Nothing
879 registerPackage input_file defines new_flags auto_ghci_libs upd force
880 [ OF_Remove pkgid_str ] -> do
881 pkgid <- readPkgId pkgid_str
882 unregisterPackage pkgid new_flags
883 [ OF_Show pkgid_str ]
885 pkgid <- readPkgId pkgid_str
886 describePackage new_flags pkgid
888 pkgid <- readPkgId pkgid_str
889 mapM_ (describeField new_flags pkgid) fields
891 prog <- getProgramName
892 die (usageInfo (usageHeader prog) flags)
894 my_head :: String -> [a] -> a
895 my_head s [] = error s
898 -- ---------------------------------------------------------------------------
899 -- expanding environment variables in the package configuration
901 expandEnvVars :: String -> [(String, String)] -> Force -> IO String
902 expandEnvVars str defines force = go str ""
904 go "" acc = return $! reverse acc
905 go ('$':'{':str) acc | (var, '}':rest) <- break close str
906 = do value <- lookupEnvVar var
907 go rest (reverse value ++ acc)
908 where close c = c == '}' || c == '\n' -- don't span newlines
912 lookupEnvVar :: String -> IO String
914 case lookup nm defines of
915 Just x | not (null x) -> return x
917 catch (System.getEnv nm)
918 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
922 -----------------------------------------------------------------------------
924 getProgramName :: IO String
925 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
926 where str `withoutSuffix` suff
927 | suff `isSuffixOf` str = take (length str - length suff) str
930 bye :: String -> IO a
931 bye s = putStr s >> exitWith ExitSuccess
933 die :: String -> IO a
936 prog <- getProgramName
937 hPutStrLn stderr (prog ++ ": " ++ s)
938 exitWith (ExitFailure 1)
940 dieOrForceAll :: Force -> String -> IO ()
941 dieOrForceAll ForceAll s = ignoreError s
942 dieOrForceAll _other s = dieForcible s
944 dieOrForceFile :: Force -> String -> IO ()
945 dieOrForceFile ForceAll s = ignoreError s
946 dieOrForceFile ForceFiles s = ignoreError s
947 dieOrForceFile _other s = dieForcible s
949 ignoreError :: String -> IO ()
950 ignoreError s = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
952 dieForcible :: String -> IO ()
953 dieForcible s = die (s ++ " (use --force to override)")
955 -----------------------------------------
956 -- Cut and pasted from ghc/compiler/SysTools
958 #if defined(mingw32_HOST_OS)
959 subst a b ls = map (\ x -> if x == a then b else x) ls
960 unDosifyPath xs = subst '\\' '/' xs
962 getExecDir :: String -> IO (Maybe String)
963 -- (getExecDir cmd) returns the directory in which the current
964 -- executable, which should be called 'cmd', is running
965 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
966 -- you'll get "/a/b/c" back as the result
968 = allocaArray len $ \buf -> do
969 ret <- getModuleFileName nullPtr buf len
970 if ret == 0 then return Nothing
971 else do s <- peekCString buf
972 return (Just (reverse (drop (length cmd)
973 (reverse (unDosifyPath s)))))
975 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
977 foreign import stdcall unsafe "GetModuleFileNameA"
978 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
980 getExecDir :: String -> IO (Maybe String)
981 getExecDir _ = return Nothing
984 -- -----------------------------------------------------------------------------
987 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
988 -- It joins directory and file names to form a complete file path.
990 -- The general rule is:
992 -- > dir `joinFileName` basename == path
994 -- > (dir,basename) = splitFileName path
996 -- There might be an exceptions to the rule but in any case the
997 -- reconstructed path will refer to the same object (file or directory).
998 -- An example exception is that on Windows some slashes might be converted
1000 joinFileName :: String -> String -> FilePath
1001 joinFileName "" fname = fname
1002 joinFileName "." fname = fname
1003 joinFileName dir "" = dir
1004 joinFileName dir fname
1005 | isPathSeparator (last dir) = dir++fname
1006 | otherwise = dir++pathSeparator:fname
1008 -- | Checks whether the character is a valid path separator for the host
1009 -- platform. The valid character is a 'pathSeparator' but since the Windows
1010 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1011 -- checks for it on this platform, too.
1012 isPathSeparator :: Char -> Bool
1013 isPathSeparator ch = ch == pathSeparator || ch == '/'
1015 -- | Provides a platform-specific character used to separate directory levels in
1016 -- a path string that reflects a hierarchical file system organization. The
1017 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1018 -- (@\"\\\"@) on the Windows operating system.
1019 pathSeparator :: Char
1020 #ifdef mingw32_HOST_OS
1021 pathSeparator = '\\'
1026 getFilenameDir :: FilePath -> FilePath
1027 getFilenameDir fn = case break isPathSeparator (reverse fn) of
1029 (_, sep:ys) -> reverse ys
1031 -- | The function splits the given string to substrings
1032 -- using the 'searchPathSeparator'.
1033 parseSearchPath :: String -> [FilePath]
1034 parseSearchPath path = split path
1036 split :: String -> [String]
1040 _:rest -> chunk : split rest
1044 #ifdef mingw32_HOST_OS
1045 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1049 (chunk', rest') = break (==searchPathSeparator) s
1051 -- | A platform-specific character used to separate search path strings in
1052 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh,
1053 -- and a semicolon (\";\") on the Windows operating system.
1054 searchPathSeparator :: Char
1055 #if mingw32_HOST_OS || mingw32_TARGET_OS
1056 searchPathSeparator = ';'
1058 searchPathSeparator = ':'