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
110 | FlagDefinedName String String
114 flags :: [OptDescr Flag]
116 Option [] ["user"] (NoArg FlagUser)
117 "use the current user's package database",
118 Option [] ["global"] (NoArg FlagGlobal)
119 "(default) use the global package database",
120 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
121 "act upon specified package config file (only)",
122 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
123 "location of the global package config",
124 Option [] ["force"] (NoArg FlagForce)
125 "ignore missing dependencies, directories, and libraries",
126 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
127 "automatically build libs for GHCi (with register)",
128 Option ['?'] ["help"] (NoArg FlagHelp)
129 "display this help and exit",
130 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
131 "define NAME as VALUE",
132 Option ['V'] ["version"] (NoArg FlagVersion)
133 "output version information and exit",
134 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
135 "print output in easy-to-parse format when running command 'list'"
139 case break (=='=') str of
140 (nm,[]) -> FlagDefinedName nm []
141 (nm,_:val) -> FlagDefinedName nm val
143 ourCopyright :: String
144 ourCopyright = "GHC package manager version " ++ version ++ "\n"
146 usageHeader :: String -> String
147 usageHeader prog = substProg prog $
149 " $p register {filename | -}\n" ++
150 " Register the package using the specified installed package\n" ++
151 " description. The syntax for the latter is given in the $p\n" ++
152 " documentation.\n" ++
154 " $p update {filename | -}\n" ++
155 " Register the package, overwriting any other package with the\n" ++
158 " $p unregister {pkg-id}\n" ++
159 " Unregister the specified package.\n" ++
161 " $p expose {pkg-id}\n" ++
162 " Expose the specified package.\n" ++
164 " $p hide {pkg-id}\n" ++
165 " Hide the specified package.\n" ++
167 " $p list [pkg]\n" ++
168 " List registered packages in the global database, and also the\n" ++
169 " user database if --user is given. If a package name is given\n" ++
170 " all the registered versions will be listed in ascending order.\n" ++
172 " $p latest pkg\n" ++
173 " Prints the highest registered version of a package.\n" ++
175 " $p describe {pkg-id}\n" ++
176 " Give the registered description for the specified package. The\n" ++
177 " description is returned in precisely the syntax required by $p\n" ++
180 " $p field {pkg-id} {field}\n" ++
181 " Extract the specified field of the package description for the\n" ++
182 " specified package.\n" ++
184 " The following optional flags are also accepted:\n"
186 substProg :: String -> String -> String
188 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
189 substProg prog (c:xs) = c : substProg prog xs
191 -- -----------------------------------------------------------------------------
194 runit :: [Flag] -> [String] -> IO ()
195 runit cli nonopts = do
196 prog <- getProgramName
198 force = FlagForce `elem` cli
199 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
200 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
202 -- first, parse the command
204 ["register", filename] ->
205 registerPackage filename defines cli auto_ghci_libs False force
206 ["update", filename] ->
207 registerPackage filename defines cli auto_ghci_libs True force
208 ["unregister", pkgid_str] -> do
209 pkgid <- readGlobPkgId pkgid_str
210 unregisterPackage pkgid cli
211 ["expose", pkgid_str] -> do
212 pkgid <- readGlobPkgId pkgid_str
213 exposePackage pkgid cli
214 ["hide", pkgid_str] -> do
215 pkgid <- readGlobPkgId pkgid_str
216 hidePackage pkgid cli
218 listPackages cli Nothing
219 ["list", pkgid_str] -> do
220 pkgid <- readGlobPkgId pkgid_str
221 listPackages cli (Just pkgid)
222 ["latest", pkgid_str] -> do
223 pkgid <- readGlobPkgId pkgid_str
224 latestPackage cli pkgid
225 ["describe", pkgid_str] -> do
226 pkgid <- readGlobPkgId pkgid_str
227 describePackage cli pkgid
228 ["field", pkgid_str, field] -> do
229 pkgid <- readGlobPkgId pkgid_str
230 describeField cli pkgid field
232 die ("missing command\n" ++
233 usageInfo (usageHeader prog) flags)
235 die ("command-line syntax error\n" ++
236 usageInfo (usageHeader prog) flags)
238 parseCheck :: ReadP a a -> String -> String -> IO a
239 parseCheck parser str what =
240 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
242 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
244 readPkgId :: String -> IO PackageIdentifier
245 readPkgId str = parseCheck parsePackageId str "package identifier"
247 readGlobPkgId :: String -> IO PackageIdentifier
248 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
250 parseGlobPackageId :: ReadP r PackageIdentifier
254 (do n <- parsePackageName; string "-*"
255 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
257 -- globVersion means "all versions"
258 globVersion :: Version
259 globVersion = Version{ versionBranch=[], versionTags=["*"] }
261 -- -----------------------------------------------------------------------------
264 -- Some commands operate on a single database:
265 -- register, unregister, expose, hide
266 -- however these commands also check the union of the available databases
267 -- in order to check consistency. For example, register will check that
268 -- dependencies exist before registering a package.
270 -- Some commands operate on multiple databases, with overlapping semantics:
271 -- list, describe, field
273 type PackageDBName = FilePath
274 type PackageDB = [InstalledPackageInfo]
276 type PackageDBStack = [(PackageDBName,PackageDB)]
277 -- A stack of package databases. Convention: head is the topmost
278 -- in the stack. Earlier entries override later one.
280 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
281 getPkgDatabases modify flags = do
282 -- first we determine the location of the global package config. On Windows,
283 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
284 -- location is passed to the binary using the --global-config flag by the
286 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
288 case [ f | FlagGlobalConfig f <- flags ] of
289 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
291 Nothing -> die err_msg
292 Just dir -> return (dir `joinFileName` "package.conf")
293 fs -> return (last fs)
295 let global_conf_dir = global_conf ++ ".d"
296 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
298 if global_conf_dir_exists
299 then do files <- getDirectoryContents global_conf_dir
300 return [ global_conf_dir ++ '/' : file
302 , isSuffixOf ".conf" file]
305 -- get the location of the user package database, and create it if necessary
306 appdir <- getAppUserDataDirectory "ghc"
309 subdir = targetARCH ++ '-':targetOS ++ '-':version
310 archdir = appdir `joinFileName` subdir
311 user_conf = archdir `joinFileName` "package.conf"
312 user_exists <- doesFileExist user_conf
314 -- If the user database doesn't exist, and this command isn't a
315 -- "modify" command, then we won't attempt to create or use it.
317 | modify || user_exists = user_conf : global_confs ++ [global_conf]
318 | otherwise = global_confs ++ [global_conf]
320 e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
323 Left _ -> sys_databases
325 | last cs == "" -> init cs ++ sys_databases
327 where cs = parseSearchPath path
329 -- The "global" database is always the one at the bottom of the stack.
330 -- This is the database we modify by default.
331 virt_global_conf = last env_stack
333 -- -f flags on the command line add to the database stack, unless any
334 -- of them are present in the stack already.
335 let flag_stack = filter (`notElem` env_stack)
336 [ f | FlagConfig f <- reverse flags ] ++ env_stack
338 -- Now we have the full stack of databases. Next, if the current
339 -- command is a "modify" type command, then we truncate the stack
340 -- so that the topmost element is the database being modified.
343 then return flag_stack
345 go (FlagUser : fs) = modifying user_conf
346 go (FlagGlobal : fs) = modifying virt_global_conf
347 go (FlagConfig f : fs) = modifying f
349 go [] = modifying virt_global_conf
352 | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
353 | otherwise = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
357 db_stack <- mapM readParseDatabase final_stack
360 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
361 readParseDatabase filename = do
362 str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
363 let packages = read str
364 Exception.evaluate packages
365 `Exception.catch` \_ ->
366 die (filename ++ ": parse error in package config file")
367 return (filename,packages)
369 emptyPackageConfig :: String
370 emptyPackageConfig = "[]"
372 -- -----------------------------------------------------------------------------
375 registerPackage :: FilePath
376 -> [(String,String)] -- defines
378 -> Bool -- auto_ghci_libs
382 registerPackage input defines flags auto_ghci_libs update force = do
383 db_stack <- getPkgDatabases True flags
385 db_to_operate_on = my_head "db" db_stack
386 db_filename = fst db_to_operate_on
392 putStr "Reading package info from stdin ... "
395 putStr ("Reading package info from " ++ show f ++ " ... ")
398 expanded <- expandEnvVars s defines force
400 pkg0 <- parsePackageInfo expanded defines force
403 let pkg = resolveDeps db_stack pkg0
404 validatePackageConfig pkg db_stack auto_ghci_libs update force
405 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
406 not_this p = package p /= package pkg
407 savingOldConfig db_filename $
408 writeNewConfig db_filename new_details
414 -> IO InstalledPackageInfo
415 parsePackageInfo str defines force =
416 case parseInstalledPackageInfo str of
417 ParseOk _warns ok -> return ok
418 ParseFailed err -> die (showError err)
420 -- -----------------------------------------------------------------------------
421 -- Exposing, Hiding, Unregistering are all similar
423 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
424 exposePackage = modifyPackage (\p -> [p{exposed=True}])
426 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
427 hidePackage = modifyPackage (\p -> [p{exposed=False}])
429 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
430 unregisterPackage = modifyPackage (\p -> [])
433 :: (InstalledPackageInfo -> [InstalledPackageInfo])
437 modifyPackage fn pkgid flags = do
438 db_stack <- getPkgDatabases True{-modify-} flags
439 let ((db_name, pkgs) : _) = db_stack
440 ps <- findPackages [(db_name,pkgs)] pkgid
441 let pids = map package ps
442 let new_config = concat (map modify pkgs)
444 | package pkg `elem` pids = fn pkg
446 savingOldConfig db_name $
447 writeNewConfig db_name new_config
449 -- -----------------------------------------------------------------------------
452 listPackages :: [Flag] -> Maybe PackageIdentifier -> IO ()
453 listPackages flags mPackageName = do
454 let simple_output = FlagSimpleOutput `elem` flags
455 db_stack <- getPkgDatabases False flags
456 let db_stack_filtered -- if a package is given, filter out all other packages
457 | Just this <- mPackageName =
458 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
460 | otherwise = db_stack
463 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
464 where sort_pkgs = sortBy cmpPkgIds
465 cmpPkgIds pkg1 pkg2 =
466 case pkgName p1 `compare` pkgName p2 of
469 EQ -> pkgVersion p1 `compare` pkgVersion p2
470 where (p1,p2) = (package pkg1, package pkg2)
472 show_func = if simple_output then show_easy else mapM_ show_regular
474 show_func (reverse db_stack_sorted)
476 where show_regular (db_name,pkg_confs) =
477 hPutStrLn stdout (render $
478 text (db_name ++ ":") $$ nest 4 packages
480 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
483 | otherwise = parens doc
484 where doc = text (showPackageId (package p))
486 show_easy db_stack = do
487 let pkgs = map showPackageId $ sortBy compPkgIdVer $
488 map package (concatMap snd db_stack)
489 when (null pkgs) $ die "no matches"
490 hPutStrLn stdout $ concat $ intersperse " " pkgs
492 -- -----------------------------------------------------------------------------
493 -- Prints the highest (hidden or exposed) version of a package
495 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
496 latestPackage flags pkgid = do
497 db_stack <- getPkgDatabases False flags
498 ps <- findPackages db_stack pkgid
499 show_pkg (sortBy compPkgIdVer (map package ps))
501 show_pkg [] = die "no matches"
502 show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
504 -- -----------------------------------------------------------------------------
507 describePackage :: [Flag] -> PackageIdentifier -> IO ()
508 describePackage flags pkgid = do
509 db_stack <- getPkgDatabases False flags
510 ps <- findPackages db_stack pkgid
511 mapM_ (putStrLn . showInstalledPackageInfo) ps
513 -- PackageId is can have globVersion for the version
514 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
515 findPackages db_stack pkgid
516 = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
517 [] -> die ("cannot find package " ++ showPackageId pkgid)
520 all_pkgs = concat (map snd db_stack)
522 matches :: PackageIdentifier -> PackageIdentifier -> Bool
524 = (pkgName pid == pkgName pid')
525 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
527 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
528 pid `matchesPkg` pkg = pid `matches` package pkg
530 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
531 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
533 -- -----------------------------------------------------------------------------
536 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
537 describeField flags pkgid field = do
538 db_stack <- getPkgDatabases False flags
539 case toField field of
540 Nothing -> die ("unknown field: " ++ field)
542 ps <- findPackages db_stack pkgid
543 mapM_ (putStrLn.fn) ps
545 toField :: String -> Maybe (InstalledPackageInfo -> String)
546 -- backwards compatibility:
547 toField "import_dirs" = Just $ strList . importDirs
548 toField "source_dirs" = Just $ strList . importDirs
549 toField "library_dirs" = Just $ strList . libraryDirs
550 toField "hs_libraries" = Just $ strList . hsLibraries
551 toField "extra_libraries" = Just $ strList . extraLibraries
552 toField "include_dirs" = Just $ strList . includeDirs
553 toField "c_includes" = Just $ strList . includes
554 toField "package_deps" = Just $ strList . map showPackageId. depends
555 toField "extra_cc_opts" = Just $ strList . ccOptions
556 toField "extra_ld_opts" = Just $ strList . ldOptions
557 toField "framework_dirs" = Just $ strList . frameworkDirs
558 toField "extra_frameworks"= Just $ strList . frameworks
559 toField s = showInstalledPackageInfoField s
561 strList :: [String] -> String
564 -- -----------------------------------------------------------------------------
565 -- Manipulating package.conf files
567 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
568 writeNewConfig filename packages = do
569 hPutStr stdout "Writing new package config file... "
570 createDirectoryIfMissing True $ getFilenameDir filename
571 h <- openFile filename WriteMode `catch` \e ->
572 if isPermissionError e
573 then die (filename ++ ": you don't have permission to modify this file")
575 hPutStrLn h (show packages)
577 hPutStrLn stdout "done."
579 savingOldConfig :: FilePath -> IO () -> IO ()
580 savingOldConfig filename io = Exception.block $ do
581 hPutStr stdout "Saving old package config file... "
582 -- mv rather than cp because we've already done an hGetContents
583 -- on this file so we won't be able to open it for writing
584 -- unless we move the old one out of the way...
585 let oldFile = filename ++ ".old"
586 restore_on_error <- catch (renameFile filename oldFile >> return True) $
588 unless (isDoesNotExistError err) $ do
589 hPutStrLn stderr (unwords ["Unable to rename", show filename,
593 hPutStrLn stdout "done."
595 hPutStrLn stderr (show e)
596 hPutStr stdout ("\nWARNING: an error was encountered while writing"
597 ++ "the new configuration.\n")
598 when restore_on_error $ do
599 hPutStr stdout "Attempting to restore the old configuration..."
600 do renameFile oldFile filename
601 hPutStrLn stdout "done."
602 `catch` \err -> hPutStrLn stdout ("Failed: " ++ show err)
605 -----------------------------------------------------------------------------
606 -- Sanity-check a new package config, and automatically build GHCi libs
609 validatePackageConfig :: InstalledPackageInfo
611 -> Bool -- auto-ghc-libs
615 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
617 checkDuplicates db_stack pkg update force
618 mapM_ (checkDep db_stack force) (depends pkg)
619 mapM_ (checkDir force) (importDirs pkg)
620 mapM_ (checkDir force) (libraryDirs pkg)
621 mapM_ (checkDir force) (includeDirs pkg)
622 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
623 -- ToDo: check these somehow?
624 -- extra_libraries :: [String],
625 -- c_includes :: [String],
627 -- When the package name and version are put together, sometimes we can
628 -- end up with a package id that cannot be parsed. This will lead to
629 -- difficulties when the user wants to refer to the package later, so
630 -- we check that the package id can be parsed properly here.
631 checkPackageId :: InstalledPackageInfo -> IO ()
633 let str = showPackageId (package ipi) in
634 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
636 [] -> die ("invalid package identifier: " ++ str)
637 _ -> die ("ambiguous package identifier: " ++ str)
639 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
640 resolveDeps db_stack p = updateDeps p
642 -- The input package spec is allowed to give a package dependency
643 -- without a version number; e.g.
645 -- Here, we update these dependencies without version numbers to
646 -- match the actual versions of the relevant packages installed.
647 updateDeps p = p{depends = map resolveDep (depends p)}
650 | realVersion dep_pkgid = dep_pkgid
651 | otherwise = lookupDep dep_pkgid
655 name = pkgName dep_pkgid
657 case [ pid | p <- concat (map snd db_stack),
659 pkgName pid == name ] of
660 (pid:_) -> pid -- Found installed package,
661 -- replete with its version
662 [] -> dep_pkgid -- No installed package; use
663 -- the version-less one
665 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
667 checkDuplicates db_stack pkg update force = do
670 (_top_db_name, pkgs) : _ = db_stack
672 -- Check whether this package id already exists in this DB
674 when (not update && (pkgid `elem` map package pkgs)) $
675 die ("package " ++ showPackageId pkgid ++ " is already installed")
679 checkDir :: Bool -> String -> IO ()
681 | "$topdir" `isPrefixOf` d = return ()
682 -- can't check this, because we don't know what $topdir is
684 there <- doesDirectoryExist d
686 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
688 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
689 checkDep db_stack force pkgid
690 | not real_version || pkgid `elem` pkgids = return ()
691 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
694 -- for backwards compat, we treat 0.0 as a special version,
695 -- and don't check that it actually exists.
696 real_version = realVersion pkgid
698 all_pkgs = concat (map snd db_stack)
699 pkgids = map package all_pkgs
701 realVersion :: PackageIdentifier -> Bool
702 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
704 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
705 checkHSLib dirs auto_ghci_libs force lib = do
706 let batch_lib_file = "lib" ++ lib ++ ".a"
707 bs <- mapM (doesLibExistIn batch_lib_file) dirs
708 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
709 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
711 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
713 doesLibExistIn :: String -> String -> IO Bool
715 | "$topdir" `isPrefixOf` d = return True
716 | otherwise = doesFileExist (d ++ '/':lib)
718 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
719 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
720 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
722 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
723 case [dir | (exists,dir) <- zip bs dirs, exists] of
724 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
727 ghci_lib_file = lib ++ ".o"
729 -- automatically build the GHCi version of a batch lib,
730 -- using ld --whole-archive.
732 autoBuildGHCiLib :: String -> String -> String -> IO ()
733 autoBuildGHCiLib dir batch_file ghci_file = do
734 let ghci_lib_file = dir ++ '/':ghci_file
735 batch_lib_file = dir ++ '/':batch_file
736 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
737 #if defined(darwin_HOST_OS)
738 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
739 #elif defined(mingw32_HOST_OS)
740 execDir <- getExecDir "/bin/ghc-pkg.exe"
741 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
743 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
745 when (r /= ExitSuccess) $ exitWith r
746 hPutStrLn stderr (" done.")
748 -- -----------------------------------------------------------------------------
749 -- Searching for modules
753 findModules :: [FilePath] -> IO [String]
755 mms <- mapM searchDir paths
758 searchDir path prefix = do
759 fs <- getDirectoryEntries path `catch` \_ -> return []
760 searchEntries path prefix fs
762 searchEntries path prefix [] = return []
763 searchEntries path prefix (f:fs)
764 | looks_like_a_module = do
765 ms <- searchEntries path prefix fs
766 return (prefix `joinModule` f : ms)
767 | looks_like_a_component = do
768 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
769 ms' <- searchEntries path prefix fs
772 searchEntries path prefix fs
775 (base,suffix) = splitFileExt f
776 looks_like_a_module =
777 suffix `elem` haskell_suffixes &&
778 all okInModuleName base
779 looks_like_a_component =
780 null suffix && all okInModuleName base
786 -- -----------------------------------------------------------------------------
787 -- The old command-line syntax, supported for backwards compatibility
794 | OF_Add Bool {- True => replace existing info -}
795 | OF_Remove String | OF_Show String
796 | OF_Field String | OF_AutoGHCiLibs | OF_Force
797 | OF_DefinedName String String
798 | OF_GlobalConfig FilePath
801 isAction :: OldFlag -> Bool
802 isAction OF_Config{} = False
803 isAction OF_Field{} = False
804 isAction OF_Input{} = False
805 isAction OF_AutoGHCiLibs{} = False
806 isAction OF_Force{} = False
807 isAction OF_DefinedName{} = False
808 isAction OF_GlobalConfig{} = False
811 oldFlags :: [OptDescr OldFlag]
813 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
814 "use the specified package config file",
815 Option ['l'] ["list-packages"] (NoArg OF_List)
816 "list packages in all config files",
817 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
818 "list packages in the specified config file",
819 Option ['a'] ["add-package"] (NoArg (OF_Add False))
821 Option ['u'] ["update-package"] (NoArg (OF_Add True))
822 "update package with new configuration",
823 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
824 "read new package info from specified file",
825 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
826 "show the configuration for package NAME",
827 Option [] ["field"] (ReqArg OF_Field "FIELD")
828 "(with --show-package) Show field FIELD only",
829 Option [] ["force"] (NoArg OF_Force)
830 "ignore missing directories/libraries",
831 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
832 "remove an installed package",
833 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
834 "automatically build libs for GHCi (with -a)",
835 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
836 "define NAME as VALUE",
837 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
838 "location of the global package config"
842 case break (=='=') str of
843 (nm,[]) -> OF_DefinedName nm []
844 (nm,_:val) -> OF_DefinedName nm val
846 oldRunit :: [OldFlag] -> IO ()
848 let new_flags = [ f | Just f <- map conv clis ]
850 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
851 conv (OF_Config f) = Just (FlagConfig f)
856 let fields = [ f | OF_Field f <- clis ]
858 let auto_ghci_libs = any isAuto clis
859 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
860 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
862 force = OF_Force `elem` clis
864 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
866 case [ c | c <- clis, isAction c ] of
867 [ OF_List ] -> listPackages new_flags Nothing
868 [ OF_ListLocal ] -> listPackages new_flags Nothing
870 registerPackage input_file defines new_flags auto_ghci_libs upd force
871 [ OF_Remove pkgid_str ] -> do
872 pkgid <- readPkgId pkgid_str
873 unregisterPackage pkgid new_flags
874 [ OF_Show pkgid_str ]
876 pkgid <- readPkgId pkgid_str
877 describePackage new_flags pkgid
879 pkgid <- readPkgId pkgid_str
880 mapM_ (describeField new_flags pkgid) fields
882 prog <- getProgramName
883 die (usageInfo (usageHeader prog) flags)
885 my_head :: String -> [a] -> a
886 my_head s [] = error s
889 -- ---------------------------------------------------------------------------
890 -- expanding environment variables in the package configuration
892 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
893 expandEnvVars str defines force = go str ""
895 go "" acc = return $! reverse acc
896 go ('$':'{':str) acc | (var, '}':rest) <- break close str
897 = do value <- lookupEnvVar var
898 go rest (reverse value ++ acc)
899 where close c = c == '}' || c == '\n' -- don't span newlines
903 lookupEnvVar :: String -> IO String
905 case lookup nm defines of
906 Just x | not (null x) -> return x
908 catch (System.getEnv nm)
909 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
913 -----------------------------------------------------------------------------
915 getProgramName :: IO String
916 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
917 where str `withoutSuffix` suff
918 | suff `isSuffixOf` str = take (length str - length suff) str
921 bye :: String -> IO a
922 bye s = putStr s >> exitWith ExitSuccess
924 die :: String -> IO a
927 prog <- getProgramName
928 hPutStrLn stderr (prog ++ ": " ++ s)
929 exitWith (ExitFailure 1)
931 dieOrForce :: Bool -> String -> IO ()
933 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
934 | otherwise = die (s ++ " (use --force to override)")
936 -----------------------------------------
937 -- Cut and pasted from ghc/compiler/SysTools
939 #if defined(mingw32_HOST_OS)
940 subst a b ls = map (\ x -> if x == a then b else x) ls
941 unDosifyPath xs = subst '\\' '/' xs
943 getExecDir :: String -> IO (Maybe String)
944 -- (getExecDir cmd) returns the directory in which the current
945 -- executable, which should be called 'cmd', is running
946 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
947 -- you'll get "/a/b/c" back as the result
949 = allocaArray len $ \buf -> do
950 ret <- getModuleFileName nullPtr buf len
951 if ret == 0 then return Nothing
952 else do s <- peekCString buf
953 return (Just (reverse (drop (length cmd)
954 (reverse (unDosifyPath s)))))
956 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
958 foreign import stdcall unsafe "GetModuleFileNameA"
959 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
961 getExecDir :: String -> IO (Maybe String)
962 getExecDir _ = return Nothing
965 -- -----------------------------------------------------------------------------
968 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
969 -- It joins directory and file names to form a complete file path.
971 -- The general rule is:
973 -- > dir `joinFileName` basename == path
975 -- > (dir,basename) = splitFileName path
977 -- There might be an exceptions to the rule but in any case the
978 -- reconstructed path will refer to the same object (file or directory).
979 -- An example exception is that on Windows some slashes might be converted
981 joinFileName :: String -> String -> FilePath
982 joinFileName "" fname = fname
983 joinFileName "." fname = fname
984 joinFileName dir "" = dir
985 joinFileName dir fname
986 | isPathSeparator (last dir) = dir++fname
987 | otherwise = dir++pathSeparator:fname
989 -- | Checks whether the character is a valid path separator for the host
990 -- platform. The valid character is a 'pathSeparator' but since the Windows
991 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
992 -- checks for it on this platform, too.
993 isPathSeparator :: Char -> Bool
994 isPathSeparator ch = ch == pathSeparator || ch == '/'
996 -- | Provides a platform-specific character used to separate directory levels in
997 -- a path string that reflects a hierarchical file system organization. The
998 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
999 -- (@\"\\\"@) on the Windows operating system.
1000 pathSeparator :: Char
1001 #ifdef mingw32_HOST_OS
1002 pathSeparator = '\\'
1007 getFilenameDir :: FilePath -> FilePath
1008 getFilenameDir fn = case break isPathSeparator (reverse fn) of
1010 (_, sep:ys) -> reverse ys
1012 -- | The function splits the given string to substrings
1013 -- using the 'searchPathSeparator'.
1014 parseSearchPath :: String -> [FilePath]
1015 parseSearchPath path = split path
1017 split :: String -> [String]
1021 _:rest -> chunk : split rest
1025 #ifdef mingw32_HOST_OS
1026 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1030 (chunk', rest') = break (==searchPathSeparator) s
1032 -- | A platform-specific character used to separate search path strings in
1033 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh,
1034 -- and a semicolon (\";\") on the Windows operating system.
1035 searchPathSeparator :: Char
1036 #if mingw32_HOST_OS || mingw32_TARGET_OS
1037 searchPathSeparator = ';'
1039 searchPathSeparator = ':'