1 {-# OPTIONS -fglasgow-exts #-}
2 -----------------------------------------------------------------------------
4 -- (c) The University of Glasgow 2004.
6 -- Package management tool
8 -----------------------------------------------------------------------------
13 -- - expanding of variables in new-style package conf
14 -- - version manipulation (checking whether old version exists,
15 -- hiding old version?)
17 module Main (main) where
19 import Version ( version, targetOS, targetARCH )
20 import Distribution.InstalledPackageInfo
21 import Distribution.Compat.ReadP
22 import Distribution.ParseUtils ( showError )
23 import Distribution.Package
24 import Distribution.Version
25 import Compat.Directory ( getAppUserDataDirectory )
26 import Compat.RawSystem ( rawSystem )
27 import Control.Exception ( evaluate )
28 import qualified Control.Exception as Exception
29 import System.FilePath ( joinFileName, splitFileName )
33 #if __GLASGOW_HASKELL__ < 603
37 #if __GLASGOW_HASKELL__ >= 504
38 import System.Console.GetOpt
39 import Text.PrettyPrint
40 import qualified Control.Exception as Exception
44 import qualified Exception
47 import Data.Char ( isSpace )
50 import System ( getArgs, getProgName,
51 exitWith, ExitCode(..)
54 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
56 #ifdef mingw32_HOST_OS
59 #if __GLASGOW_HASKELL__ >= 504
60 import Foreign.C.String
66 -- -----------------------------------------------------------------------------
73 case getOpt Permute flags args of
74 (cli,_,[]) | FlagHelp `elem` cli -> do
75 prog <- getProgramName
76 bye (usageInfo (usageHeader prog) flags)
77 (cli,_,[]) | FlagVersion `elem` cli ->
81 (_,_,errors) -> tryOldCmdLine errors args
83 -- If the new command-line syntax fails, then we try the old. If that
84 -- fails too, then we output the original errors and the new syntax
85 -- (so the old syntax is still available, but hidden).
86 tryOldCmdLine :: [String] -> [String] -> IO ()
87 tryOldCmdLine errors args = do
88 case getOpt Permute oldFlags args of
92 prog <- getProgramName
93 die (concat errors ++ usageInfo (usageHeader prog) flags)
95 -- -----------------------------------------------------------------------------
96 -- Command-line syntax
103 | FlagConfig FilePath
104 | FlagGlobalConfig FilePath
109 flags :: [OptDescr Flag]
111 Option [] ["user"] (NoArg FlagUser)
112 "use the current user's package database",
113 Option [] ["global"] (NoArg FlagGlobal)
114 "(default) use the global package database",
115 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
116 "act upon specified package config file (only)",
117 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
118 "location of the global package config",
119 Option [] ["force"] (NoArg FlagForce)
120 "ignore missing dependencies, directories, and libraries",
121 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
122 "automatically build libs for GHCi (with register)",
123 Option ['?'] ["help"] (NoArg FlagHelp)
124 "display this help and exit",
125 Option ['V'] ["version"] (NoArg FlagVersion)
126 "output version information and exit"
129 ourCopyright :: String
130 ourCopyright = "GHC package manager version " ++ version ++ "\n"
132 usageHeader :: String -> String
133 usageHeader prog = substProg prog $
135 " $p {--help | -?}\n" ++
136 " Produce this usage message.\n" ++
138 " $p register {filename | -} [--user | --global]\n" ++
139 " Register the package using the specified installed package\n" ++
140 " description. The syntax for the latter is given in the $p\n" ++
141 " documentation.\n" ++
143 " $p unregister {pkg-id}\n" ++
144 " Unregister the specified package.\n" ++
146 " $p expose {pkg-id}\n" ++
147 " Expose the specified package.\n" ++
149 " $p hide {pkg-id}\n" ++
150 " Hide the specified package.\n" ++
152 " $p list [--global | --user]\n" ++
153 " List all registered packages, both global and user (unless either\n" ++
154 " --global or --user is specified), and both hidden and exposed.\n" ++
156 " $p describe {pkg-id}\n" ++
157 " Give the registered description for the specified package. The\n" ++
158 " description is returned in precisely the syntax required by $p\n" ++
161 " $p field {pkg-id} {field}\n" ++
162 " Extract the specified field of the package description for the\n" ++
163 " specified package.\n"
165 substProg :: String -> String -> String
167 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
168 substProg prog (c:xs) = c : substProg prog xs
170 -- -----------------------------------------------------------------------------
173 runit :: [Flag] -> [String] -> IO ()
174 runit cli nonopts = do
175 prog <- getProgramName
176 dbs <- getPkgDatabases cli
177 db_stack <- mapM readParseDatabase dbs
179 force = FlagForce `elem` cli
180 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
182 -- first, parse the command
184 ["register", filename] ->
185 registerPackage filename [] db_stack auto_ghci_libs False force
186 ["update", filename] ->
187 registerPackage filename [] db_stack auto_ghci_libs True force
188 ["unregister", pkgid_str] -> do
189 pkgid <- readPkgId pkgid_str
190 unregisterPackage pkgid db_stack
191 ["expose", pkgid_str] -> do
192 pkgid <- readPkgId pkgid_str
193 exposePackage pkgid db_stack
194 ["hide", pkgid_str] -> do
195 pkgid <- readPkgId pkgid_str
196 hidePackage pkgid db_stack
198 listPackages db_stack
199 ["describe", pkgid_str] -> do
200 pkgid <- readPkgId pkgid_str
201 describePackage db_stack pkgid
202 ["field", pkgid_str, field] -> do
203 pkgid <- readPkgId pkgid_str
204 describeField db_stack pkgid field
206 die ("missing command\n" ++
207 usageInfo (usageHeader prog) flags)
209 die ("command-line syntax error\n" ++
210 usageInfo (usageHeader prog) flags)
212 parseCheck :: ReadP a a -> String -> String -> IO a
213 parseCheck parser str what =
214 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
216 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
218 readPkgId :: String -> IO PackageIdentifier
219 readPkgId str = parseCheck parsePackageId str "package identifier"
221 -- -----------------------------------------------------------------------------
224 -- Some commands operate on a single database:
225 -- register, unregister, expose, hide
226 -- however these commands also check the union of the available databases
227 -- in order to check consistency. For example, register will check that
228 -- dependencies exist before registering a package.
230 -- Some commands operate on multiple databases, with overlapping semantics:
231 -- list, describe, field
233 type PackageDBName = FilePath
234 type PackageDB = [InstalledPackageInfo]
236 type PackageDBStack = [(PackageDBName,PackageDB)]
237 -- A stack of package databases. Convention: head is the topmost
238 -- in the stack. Earlier entries override later one.
240 -- The output of this function is the list of databases to act upon, with
241 -- the "topmost" overlapped database last. The commands which operate on a
242 -- single database will use the last one. Commands which operate on multiple
243 -- databases will interpret the databases as overlapping.
244 getPkgDatabases :: [Flag] -> IO [PackageDBName]
245 getPkgDatabases flags = do
246 -- first we determine the location of the global package config. On Windows,
247 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
248 -- location is passed to the binary using the --global-config flag by the
250 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
252 case [ f | FlagGlobalConfig f <- flags ] of
253 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
255 Nothing -> die err_msg
256 Just dir -> return (dir `joinFileName` "package.conf")
257 fs -> return (last fs)
259 -- get the location of the user package database, and create it if necessary
260 appdir <- getAppUserDataDirectory "ghc"
263 subdir = targetARCH ++ '-':targetOS ++ '-':version
264 user_conf = appdir `joinFileName` subdir `joinFileName` "package.conf"
265 b <- doesFileExist user_conf
267 putStrLn ("Creating user package database in " ++ user_conf)
268 createParents user_conf
269 writeFile user_conf emptyPackageConfig
272 databases = foldl addDB [global_conf] flags
274 -- implement the following rules:
275 -- global database is the default
276 -- --user means overlap with the user database
277 -- --global means reset to just the global database
278 -- -f <file> means overlap with <file>
279 addDB dbs FlagUser = user_conf : dbs
280 addDB dbs FlagGlobal = [global_conf]
281 addDB dbs (FlagConfig f) = f : dbs
286 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
287 readParseDatabase filename = do
288 str <- readFile filename
289 let packages = read str
291 `Exception.catch` \_ ->
292 die (filename ++ ": parse error in package config file")
293 return (filename,packages)
295 emptyPackageConfig :: String
296 emptyPackageConfig = "[]"
298 -- -----------------------------------------------------------------------------
301 registerPackage :: FilePath
302 -> [(String,String)] -- defines, ToDo: maybe remove?
304 -> Bool -- auto_ghci_libs
308 registerPackage input defines db_stack auto_ghci_libs update force = do
310 db_to_operate_on = head db_stack
311 db_filename = fst db_to_operate_on
313 checkConfigAccess db_filename
318 putStr "Reading package info from stdin... "
321 putStr ("Reading package info from " ++ show f ++ " ")
324 pkg <- parsePackageInfo s defines force
327 validatePackageConfig pkg db_stack auto_ghci_libs update force
328 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
329 savePackageConfig db_filename
330 maybeRestoreOldConfig db_filename $
331 writeNewConfig db_filename new_details
337 -> IO InstalledPackageInfo
338 parsePackageInfo str defines force =
339 case parseInstalledPackageInfo str of
340 Right ok -> return ok
341 Left err -> die (showError err)
343 -- Used for converting versionless package names to new
344 -- PackageIdentifiers. "Version [] []" is special: it means "no
345 -- version" or "any version"
346 pkgNameToId :: String -> PackageIdentifier
347 pkgNameToId name = PackageIdentifier name (Version [] [])
349 -- -----------------------------------------------------------------------------
350 -- Exposing, Hiding, Unregistering are all similar
352 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
353 exposePackage = modifyPackage (\p -> [p{exposed=True}])
355 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
356 hidePackage = modifyPackage (\p -> [p{exposed=False}])
358 unregisterPackage :: PackageIdentifier -> PackageDBStack -> IO ()
359 unregisterPackage = modifyPackage (\p -> [])
362 :: (InstalledPackageInfo -> [InstalledPackageInfo])
366 modifyPackage _ _ [] = error "modifyPackage"
367 modifyPackage fn pkgid ((db_name, pkgs) : _) = do
368 checkConfigAccess db_name
369 p <- findPackage [(db_name,pkgs)] pkgid
371 savePackageConfig db_name
372 let new_config = concat (map modify pkgs)
374 | package pkg == pid = fn pkg
376 maybeRestoreOldConfig db_name $
377 writeNewConfig db_name new_config
379 -- -----------------------------------------------------------------------------
382 listPackages :: PackageDBStack -> IO ()
383 listPackages db_confs = do
384 mapM_ show_pkgconf (reverse db_confs)
385 where show_pkgconf (db_name,pkg_confs) =
386 hPutStrLn stdout (render $
387 text (db_name ++ ":") $$ nest 4 packages
389 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
390 pp_pkg = text . showPackageId . package
393 -- -----------------------------------------------------------------------------
396 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
397 describePackage db_stack pkgid = do
398 p <- findPackage db_stack pkgid
399 putStrLn (showInstalledPackageInfo p)
401 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
402 findPackage db_stack pkgid
403 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
404 [] -> die ("cannot find package " ++ showPackageId pkgid)
406 ps -> die ("package " ++ showPackageId pkgid ++
407 " matches multiple packages: " ++
408 concat (intersperse ", " (
409 map (showPackageId.package) ps)))
411 all_pkgs = concat (map snd db_stack)
413 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
416 not (realVersion pid) && pkgName pid == pkgName (package p)
418 -- -----------------------------------------------------------------------------
421 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
422 describeField db_stack pkgid field = do
423 case toField field of
424 Nothing -> die ("unknown field: " ++ field)
426 p <- findPackage db_stack pkgid
429 toField :: String -> Maybe (InstalledPackageInfo -> String)
430 -- backwards compatibility:
431 toField "import_dirs" = Just $ strList . importDirs
432 toField "source_dirs" = Just $ strList . importDirs
433 toField "library_dirs" = Just $ strList . libraryDirs
434 toField "hs_libraries" = Just $ strList . hsLibraries
435 toField "extra_libraries" = Just $ strList . extraLibraries
436 toField "include_dirs" = Just $ strList . includeDirs
437 toField "c_includes" = Just $ strList . includes
438 toField "package_deps" = Just $ strList . map showPackageId. depends
439 toField "extra_cc_opts" = Just $ strList . extraCcOpts
440 toField "extra_ld_opts" = Just $ strList . extraLdOpts
441 toField "framework_dirs" = Just $ strList . frameworkDirs
442 toField "extra_frameworks"= Just $ strList . extraFrameworks
443 toField s = showInstalledPackageInfoField s
445 strList :: [String] -> String
448 -- -----------------------------------------------------------------------------
449 -- Manipulating package.conf files
451 checkConfigAccess :: FilePath -> IO ()
452 checkConfigAccess filename = do
453 access <- getPermissions filename
454 when (not (writable access))
455 (die (filename ++ ": you don't have permission to modify this file"))
457 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
458 maybeRestoreOldConfig filename io
459 = io `catch` \e -> do
460 hPutStrLn stderr (show e)
461 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
462 "configuration was being written. Attempting to \n"++
463 "restore the old configuration... ")
464 renameFile (filename ++ ".old") filename
465 hPutStrLn stdout "done."
468 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
469 writeNewConfig filename packages = do
470 hPutStr stdout "Writing new package config file... "
471 h <- openFile filename WriteMode
472 hPutStrLn h (show packages)
474 hPutStrLn stdout "done."
476 savePackageConfig :: FilePath -> IO ()
477 savePackageConfig filename = do
478 hPutStr stdout "Saving old package config file... "
479 -- mv rather than cp because we've already done an hGetContents
480 -- on this file so we won't be able to open it for writing
481 -- unless we move the old one out of the way...
482 let oldFile = filename ++ ".old"
483 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
484 when doesExist (removeFile oldFile `catch` (const $ return ()))
485 catch (renameFile filename oldFile)
487 hPutStrLn stderr (unwords [ "Unable to rename "
493 hPutStrLn stdout "done."
495 -----------------------------------------------------------------------------
496 -- Sanity-check a new package config, and automatically build GHCi libs
499 validatePackageConfig :: InstalledPackageInfo
501 -> Bool -- auto-ghc-libs
505 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
506 checkDuplicates db_stack pkg update
507 mapM_ (checkDep db_stack force) (depends pkg)
508 mapM_ (checkDir force) (importDirs pkg)
509 mapM_ (checkDir force) (libraryDirs pkg)
510 mapM_ (checkDir force) (includeDirs pkg)
511 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
512 -- ToDo: check these somehow?
513 -- extra_libraries :: [String],
514 -- c_includes :: [String],
517 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
518 checkDuplicates db_stack pkg update = do
522 (_top_db_name, pkgs) : _ = db_stack
524 pkgs_with_same_name =
525 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
526 exposed_pkgs_with_same_name =
527 filter exposed pkgs_with_same_name
529 -- Check whether this package id already exists in this DB
531 when (not update && (package pkg `elem` map package pkgs)) $
532 die ("package " ++ showPackageId pkgid ++ " is already installed")
534 -- if we are exposing this new package, then check that
535 -- there are no other exposed packages with the same name.
537 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
538 die ("trying to register " ++ showPackageId pkgid
539 ++ " as exposed, but "
540 ++ showPackageId (package (head exposed_pkgs_with_same_name))
541 ++ " is also exposed.")
544 checkDir :: Bool -> String -> IO ()
546 | "$libdir" `isPrefixOf` d = return ()
547 -- can't check this, because we don't know what $libdir is
549 there <- doesDirectoryExist d
551 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
553 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
554 checkDep db_stack force pkgid
555 | real_version && pkgid `elem` pkgids = return ()
556 | not real_version && pkgName pkgid `elem` pkg_names = return ()
557 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
560 -- for backwards compat, we treat 0.0 as a special version,
561 -- and don't check that it actually exists.
562 real_version = realVersion pkgid
564 all_pkgs = concat (map snd db_stack)
565 pkgids = map package all_pkgs
566 pkg_names = map pkgName pkgids
568 realVersion :: PackageIdentifier -> Bool
569 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
571 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
572 checkHSLib dirs auto_ghci_libs force lib = do
573 let batch_lib_file = "lib" ++ lib ++ ".a"
574 bs <- mapM (doesLibExistIn batch_lib_file) dirs
575 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
576 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
578 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
580 doesLibExistIn :: String -> String -> IO Bool
582 | "$libdir" `isPrefixOf` d = return True
583 | otherwise = doesFileExist (d ++ '/':lib)
585 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
586 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
587 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
589 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
590 case [dir | (exists,dir) <- zip bs dirs, exists] of
591 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
594 ghci_lib_file = lib ++ ".o"
596 -- automatically build the GHCi version of a batch lib,
597 -- using ld --whole-archive.
599 autoBuildGHCiLib :: String -> String -> String -> IO ()
600 autoBuildGHCiLib dir batch_file ghci_file = do
601 let ghci_lib_file = dir ++ '/':ghci_file
602 batch_lib_file = dir ++ '/':batch_file
603 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
604 #if defined(darwin_TARGET_OS)
605 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
606 #elif defined(mingw32_HOST_OS)
607 execDir <- getExecDir "/bin/ghc-pkg.exe"
608 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
610 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
612 when (r /= ExitSuccess) $ exitWith r
613 hPutStrLn stderr (" done.")
615 -- -----------------------------------------------------------------------------
616 -- Updating the DB with the new package.
620 -> [InstalledPackageInfo]
621 -> InstalledPackageInfo
622 -> IO [InstalledPackageInfo]
623 updatePackageDB db_stack pkgs new_pkg = do
625 -- we update dependencies without version numbers to
626 -- match the actual versions of the relevant packages instaled.
627 updateDeps p = p{depends = map resolveDep (depends p)}
630 | realVersion pkgid = pkgid
631 | otherwise = lookupDep (pkgName pkgid)
634 = head [ pid | p <- concat (map snd db_stack),
636 pkgName pid == name ]
638 is_exposed = exposed new_pkg
639 pkgid = package new_pkg
642 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
644 -- When update is on, and we're exposing the new package,
645 -- we hide any packages with the same name (different versions)
646 -- in the current DB. Earlier checks will have failed if
649 | is_exposed && pkgName (package p) == name = p{ exposed = False }
652 return (pkgs'++[updateDeps new_pkg])
654 -- -----------------------------------------------------------------------------
655 -- Searching for modules
659 findModules :: [FilePath] -> IO [String]
661 mms <- mapM searchDir paths
664 searchDir path prefix = do
665 fs <- getDirectoryEntries path `catch` \_ -> return []
666 searchEntries path prefix fs
668 searchEntries path prefix [] = return []
669 searchEntries path prefix (f:fs)
670 | looks_like_a_module = do
671 ms <- searchEntries path prefix fs
672 return (prefix `joinModule` f : ms)
673 | looks_like_a_component = do
674 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
675 ms' <- searchEntries path prefix fs
678 searchEntries path prefix fs
681 (base,suffix) = splitFileExt f
682 looks_like_a_module =
683 suffix `elem` haskell_suffixes &&
684 all okInModuleName base
685 looks_like_a_component =
686 null suffix && all okInModuleName base
692 -- -----------------------------------------------------------------------------
693 -- The old command-line syntax, supported for backwards compatibility
700 | OF_Add Bool {- True => replace existing info -}
701 | OF_Remove String | OF_Show String
702 | OF_Field String | OF_AutoGHCiLibs | OF_Force
703 | OF_DefinedName String String
704 | OF_GlobalConfig FilePath
707 isAction :: OldFlag -> Bool
708 isAction OF_Config{} = False
709 isAction OF_Field{} = False
710 isAction OF_Input{} = False
711 isAction OF_AutoGHCiLibs{} = False
712 isAction OF_Force{} = False
713 isAction OF_DefinedName{} = False
714 isAction OF_GlobalConfig{} = False
717 oldFlags :: [OptDescr OldFlag]
719 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
720 "use the specified package config file",
721 Option ['l'] ["list-packages"] (NoArg OF_List)
722 "list packages in all config files",
723 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
724 "list packages in the specified config file",
725 Option ['a'] ["add-package"] (NoArg (OF_Add False))
727 Option ['u'] ["update-package"] (NoArg (OF_Add True))
728 "update package with new configuration",
729 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
730 "read new package info from specified file",
731 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
732 "show the configuration for package NAME",
733 Option [] ["field"] (ReqArg OF_Field "FIELD")
734 "(with --show-package) Show field FIELD only",
735 Option [] ["force"] (NoArg OF_Force)
736 "ignore missing directories/libraries",
737 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
738 "remove an installed package",
739 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
740 "automatically build libs for GHCi (with -a)",
741 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
742 "define NAME as VALUE",
743 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
744 "location of the global package config"
748 case break (=='=') str of
749 (nm,[]) -> OF_DefinedName nm []
750 (nm,_:val) -> OF_DefinedName nm val
752 oldRunit :: [OldFlag] -> IO ()
754 let config_flags = [ f | Just f <- map conv clis ]
756 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
757 conv (OF_Config f) = Just (FlagConfig f)
760 db_names <- getPkgDatabases config_flags
761 db_stack <- mapM readParseDatabase db_names
763 let fields = [ f | OF_Field f <- clis ]
765 let auto_ghci_libs = any isAuto clis
766 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
767 input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
769 force = OF_Force `elem` clis
771 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
773 case [ c | c <- clis, isAction c ] of
774 [ OF_List ] -> listPackages db_stack
775 [ OF_ListLocal ] -> listPackages db_stack
776 [ OF_Add upd ] -> registerPackage input_file defines db_stack
777 auto_ghci_libs upd force
778 [ OF_Remove p ] -> unregisterPackage (pkgNameToId p) db_stack
780 | null fields -> describePackage db_stack (pkgNameToId p)
781 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
782 _ -> do prog <- getProgramName
783 die (usageInfo (usageHeader prog) flags)
785 -- ---------------------------------------------------------------------------
789 expandEnvVars :: PackageConfig -> [(String, String)]
790 -> Bool -> IO PackageConfig
791 expandEnvVars pkg defines force = do
792 -- permit _all_ strings to contain ${..} environment variable references,
793 -- arguably too flexible.
794 nm <- expandString (name pkg)
795 imp_dirs <- expandStrings (import_dirs pkg)
796 src_dirs <- expandStrings (source_dirs pkg)
797 lib_dirs <- expandStrings (library_dirs pkg)
798 hs_libs <- expandStrings (hs_libraries pkg)
799 ex_libs <- expandStrings (extra_libraries pkg)
800 inc_dirs <- expandStrings (include_dirs pkg)
801 c_incs <- expandStrings (c_includes pkg)
802 p_deps <- expandStrings (package_deps pkg)
803 e_g_opts <- expandStrings (extra_ghc_opts pkg)
804 e_c_opts <- expandStrings (extra_cc_opts pkg)
805 e_l_opts <- expandStrings (extra_ld_opts pkg)
806 f_dirs <- expandStrings (framework_dirs pkg)
807 e_frames <- expandStrings (extra_frameworks pkg)
808 return (pkg { name = nm
809 , import_dirs = imp_dirs
810 , source_dirs = src_dirs
811 , library_dirs = lib_dirs
812 , hs_libraries = hs_libs
813 , extra_libraries = ex_libs
814 , include_dirs = inc_dirs
815 , c_includes = c_incs
816 , package_deps = p_deps
817 , extra_ghc_opts = e_g_opts
818 , extra_cc_opts = e_c_opts
819 , extra_ld_opts = e_l_opts
820 , framework_dirs = f_dirs
821 , extra_frameworks= e_frames
824 expandStrings :: [String] -> IO [String]
825 expandStrings = liftM concat . mapM expandSpecial
827 -- Permit substitutions for list-valued variables (but only when
828 -- they occur alone), e.g., package_deps["${deps}"] where env var
829 -- (say) 'deps' is "base,haskell98,network"
830 expandSpecial :: String -> IO [String]
832 let expand f = liftM f $ expandString str
833 in case splitString str of
834 [Var _] -> expand (wordsBy (== ','))
835 _ -> expand (\x -> [x])
837 expandString :: String -> IO String
838 expandString = liftM concat . mapM expandElem . splitString
840 expandElem :: Elem -> IO String
841 expandElem (String s) = return s
842 expandElem (Var v) = lookupEnvVar v
844 lookupEnvVar :: String -> IO String
846 case lookup nm defines of
847 Just x | not (null x) -> return x
849 catch (System.getEnv nm)
850 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
854 data Elem = String String | Var String
856 splitString :: String -> [Elem]
859 case break (== '$') str of
861 case span (/= '}') xs of
863 (if null pre then id else (String pre :)) (Var var : splitString suf)
864 _ -> [String str] -- no closing brace
865 _ -> [String str] -- no dollar/opening brace combo
867 -- wordsBy isSpace == words
868 wordsBy :: (Char -> Bool) -> String -> [String]
869 wordsBy p s = case dropWhile p s of
871 s' -> w : wordsBy p s'' where (w,s'') = break p s'
874 -----------------------------------------------------------------------------
876 getProgramName :: IO String
877 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
878 where str `withoutSuffix` suff
879 | suff `isSuffixOf` str = take (length str - length suff) str
882 bye :: String -> IO a
883 bye s = putStr s >> exitWith ExitSuccess
885 die :: String -> IO a
888 prog <- getProgramName
889 hPutStrLn stderr (prog ++ ": " ++ s)
890 exitWith (ExitFailure 1)
892 dieOrForce :: Bool -> String -> IO ()
894 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
898 -----------------------------------------------------------------------------
899 -- Create a hierarchy of directories
901 createParents :: FilePath -> IO ()
902 createParents dir = do
903 let parent = directoryOf dir
904 b <- doesDirectoryExist parent
907 createDirectory parent
909 -----------------------------------------
910 -- Cut and pasted from ghc/compiler/SysTools
912 #if defined(mingw32_HOST_OS)
913 subst a b ls = map (\ x -> if x == a then b else x) ls
914 unDosifyPath xs = subst '\\' '/' xs
916 getExecDir :: String -> IO (Maybe String)
917 -- (getExecDir cmd) returns the directory in which the current
918 -- executable, which should be called 'cmd', is running
919 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
920 -- you'll get "/a/b/c" back as the result
922 = allocaArray len $ \buf -> do
923 ret <- getModuleFileName nullPtr buf len
924 if ret == 0 then return Nothing
925 else do s <- peekCString buf
926 return (Just (reverse (drop (length cmd)
927 (reverse (unDosifyPath s)))))
929 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
931 foreign import stdcall unsafe "GetModuleFileNameA"
932 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
934 getExecDir :: String -> IO (Maybe String)
935 getExecDir _ = return Nothing
938 directoryOf :: FilePath -> FilePath
939 directoryOf = fst.splitFileName