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 Control.Exception ( evaluate )
27 import qualified Control.Exception as Exception
31 #if __GLASGOW_HASKELL__ < 603
35 #if __GLASGOW_HASKELL__ >= 504
36 import System.Console.GetOpt
37 import Text.PrettyPrint
38 import qualified Control.Exception as Exception
42 import qualified Exception
45 import Data.Char ( isSpace )
48 import System ( getArgs, getProgName,
53 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
55 #include "../../includes/ghcconfig.h"
57 #ifdef mingw32_HOST_OS
60 #if __GLASGOW_HASKELL__ >= 504
61 import Foreign.C.String
67 -- -----------------------------------------------------------------------------
74 case getOpt Permute flags args of
75 (cli,_,[]) | FlagHelp `elem` cli -> do
76 prog <- getProgramName
77 bye (usageInfo (usageHeader prog) flags)
78 (cli,_,[]) | FlagVersion `elem` cli ->
80 (cli@(_:_),nonopts,[]) ->
82 (_,_,errors) -> tryOldCmdLine errors args
84 -- If the new command-line syntax fails, then we try the old. If that
85 -- fails too, then we output the original errors and the new syntax
86 -- (so the old syntax is still available, but hidden).
87 tryOldCmdLine :: [String] -> [String] -> IO ()
88 tryOldCmdLine errors args = do
89 case getOpt Permute oldFlags args of
93 prog <- getProgramName
94 die (concat errors ++ usageInfo (usageHeader prog) flags)
96 -- -----------------------------------------------------------------------------
97 -- Command-line syntax
104 | FlagConfig FilePath
105 | 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 ['?'] ["help"] (NoArg FlagHelp)
122 "display this help and exit",
123 Option ['V'] ["version"] (NoArg FlagVersion)
124 "output version information and exit"
127 ourCopyright :: String
128 ourCopyright = "GHC package manager version " ++ version ++ "\n"
130 usageHeader :: String -> String
131 usageHeader prog = substProg prog $
133 " $p {--help | -?}\n" ++
134 " Produce this usage message.\n" ++
136 " $p register {filename | -} [--user | --global]\n" ++
137 " Register the package using the specified installed package\n" ++
138 " description. The syntax for the latter is given in the $p\n" ++
139 " documentation.\n" ++
141 " $p unregister {pkg-id}\n" ++
142 " Unregister the specified package.\n" ++
144 " $p expose {pkg-id}\n" ++
145 " Expose the specified package.\n" ++
147 " $p hide {pkg-id}\n" ++
148 " Hide the specified package.\n" ++
150 " $p list [--global | --user]\n" ++
151 " List all registered packages, both global and user (unless either\n" ++
152 " --global or --user is specified), and both hidden and exposed.\n" ++
154 " $p describe {pkg-id}\n" ++
155 " Give the registered description for the specified package. The\n" ++
156 " description is returned in precisely the syntax required by $p\n" ++
159 " $p field {pkg-id} {field}\n" ++
160 " Extract the specified field of the package description for the\n" ++
161 " specified package.\n"
163 substProg :: String -> String -> String
165 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
166 substProg prog (c:xs) = c : substProg prog xs
168 -- -----------------------------------------------------------------------------
171 runit :: [Flag] -> [String] -> IO ()
172 runit cli nonopts = do
173 prog <- getProgramName
174 dbs <- getPkgDatabases cli
175 db_stack <- mapM readParseDatabase dbs
177 force = FlagForce `elem` cli
179 -- first, parse the command
181 ["register", filename] ->
182 registerPackage filename [] db_stack False False force
183 ["update", filename] ->
184 registerPackage filename [] db_stack False True force
185 ["unregister", pkgid_str] -> do
186 pkgid <- readPkgId pkgid_str
187 unregisterPackage db_stack pkgid
188 ["expose", pkgid_str] -> do
189 pkgid <- readPkgId pkgid_str
190 exposePackage pkgid db_stack
191 ["hide", pkgid_str] -> do
192 pkgid <- readPkgId pkgid_str
193 hidePackage pkgid db_stack
195 listPackages db_stack
196 ["describe", pkgid_str] -> do
197 pkgid <- readPkgId pkgid_str
198 describePackage db_stack pkgid
199 ["field", pkgid_str, field] -> do
200 pkgid <- readPkgId pkgid_str
201 describeField db_stack pkgid field
203 die ("missing command\n" ++
204 usageInfo (usageHeader prog) flags)
206 die ("command-line syntax error\n" ++
207 usageInfo (usageHeader prog) flags)
209 parseCheck :: ReadP a a -> String -> String -> IO a
210 parseCheck parser str what =
211 case readP_to_S parser str of
212 [(x,ys)] | all isSpace ys -> return x
213 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
215 readPkgId :: String -> IO PackageIdentifier
216 readPkgId str = parseCheck parsePackageId str "package identifier"
218 -- -----------------------------------------------------------------------------
221 -- Some commands operate on a single database:
222 -- register, unregister, expose, hide
223 -- however these commands also check the union of the available databases
224 -- in order to check consistency. For example, register will check that
225 -- dependencies exist before registering a package.
227 -- Some commands operate on multiple databases, with overlapping semantics:
228 -- list, describe, field
230 type PackageDBName = FilePath
231 type PackageDB = [InstalledPackageInfo]
233 type PackageDBStack = [(PackageDBName,PackageDB)]
234 -- A stack of package databases. Convention: head is the topmost
235 -- in the stack. Earlier entries override later one.
237 -- The output of this function is the list of databases to act upon, with
238 -- the "topmost" overlapped database last. The commands which operate on a
239 -- single database will use the last one. Commands which operate on multiple
240 -- databases will interpret the databases as overlapping.
241 getPkgDatabases :: [Flag] -> IO [PackageDBName]
242 getPkgDatabases flags = do
243 -- first we determine the location of the global package config. On Windows,
244 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
245 -- location is passed to the binary using the --global-config flag by the
247 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
249 case [ f | FlagGlobalConfig f <- flags ] of
250 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
252 Nothing -> die err_msg
253 Just dir -> return (dir `joinFileName` "package.conf")
254 fs -> return (last fs)
256 -- get the location of the user package database, and create it if necessary
257 appdir <- getAppUserDataDirectory "ghc"
260 subdir = targetARCH ++ '-':targetOS ++ '-':version
261 user_conf = appdir `joinFileName` subdir `joinFileName` "package.conf"
262 b <- doesFileExist user_conf
264 putStrLn ("Creating user package database in " ++ user_conf)
265 createParents user_conf
266 writeFile user_conf emptyPackageConfig
269 databases = foldl addDB [global_conf] flags
271 -- implement the following rules:
272 -- global database is the default
273 -- --user means overlap with the user database
274 -- --global means reset to just the global database
275 -- -f <file> means overlap with <file>
276 addDB dbs FlagUser = user_conf : dbs
277 addDB dbs FlagGlobal = [global_conf]
278 addDB dbs (FlagConfig f) = f : dbs
283 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
284 readParseDatabase filename = do
285 str <- readFile filename
286 let packages = read str
288 `Exception.catch` \_ ->
289 die (filename ++ ": parse error in package config file")
290 return (filename,packages)
292 emptyPackageConfig :: String
293 emptyPackageConfig = "[]"
295 -- -----------------------------------------------------------------------------
298 registerPackage :: FilePath
299 -> [(String,String)] -- defines, ToDo: maybe remove?
301 -> Bool -- auto_ghci_libs
305 registerPackage input defines db_stack auto_ghci_libs update force = do
307 db_to_operate_on = head db_stack
308 db_filename = fst db_to_operate_on
310 checkConfigAccess db_filename
315 putStr "Reading package info from stdin... "
318 putStr ("Reading package info from " ++ show f ++ " ")
321 pkg <- parsePackageInfo s defines force
324 validatePackageConfig pkg db_stack auto_ghci_libs update force
325 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
326 savePackageConfig db_filename
327 maybeRestoreOldConfig db_filename $
328 writeNewConfig db_filename new_details
334 -> IO InstalledPackageInfo
335 parsePackageInfo str defines force =
336 case parseInstalledPackageInfo str of
337 Right ok -> return ok
338 Left err -> die (showError err)
340 -- Used for converting versionless package names to new
341 -- PackageIdentifiers. "Version [] []" is special: it means "no
342 -- version" or "any version"
343 pkgNameToId :: String -> PackageIdentifier
344 pkgNameToId name = PackageIdentifier name (Version [] [])
346 -- -----------------------------------------------------------------------------
349 unregisterPackage :: PackageDBStack -> PackageIdentifier -> IO ()
350 unregisterPackage [] _ = error "unregisterPackage"
351 unregisterPackage ((db_name, pkgs) : _) pkgid = do
352 checkConfigAccess db_name
353 p <- findPackage [(db_name,pkgs)] pkgid
355 savePackageConfig db_name
356 maybeRestoreOldConfig db_name $
357 writeNewConfig db_name (filter ((/= pid) . package) pkgs)
359 -- -----------------------------------------------------------------------------
362 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
363 exposePackage = error "TODO"
365 -- -----------------------------------------------------------------------------
368 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
369 hidePackage = error "TODO"
371 -- -----------------------------------------------------------------------------
374 listPackages :: PackageDBStack -> IO ()
375 listPackages db_confs = do
376 mapM_ show_pkgconf (reverse db_confs)
377 where show_pkgconf (db_name,pkg_confs) =
378 hPutStrLn stdout (render $
379 text (db_name ++ ":") $$ nest 4 packages
381 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
382 pp_pkg = text . showPackageId . package
385 -- -----------------------------------------------------------------------------
388 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
389 describePackage db_stack pkgid = do
390 p <- findPackage db_stack pkgid
391 putStrLn (showInstalledPackageInfo p)
393 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
394 findPackage db_stack pkgid
395 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
396 [] -> die ("cannot find package " ++ showPackageId pkgid)
398 ps -> die ("package " ++ showPackageId pkgid ++
399 " matches multiple packages: " ++
400 concat (intersperse ", " (
401 map (showPackageId.package) ps)))
403 all_pkgs = concat (map snd db_stack)
405 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
408 not (realVersion pid) && pkgName pid == pkgName (package p)
410 -- -----------------------------------------------------------------------------
413 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
414 describeField db_stack pkgid field = do
415 case toField field of
416 Nothing -> die ("unknown field: " ++ field)
418 p <- findPackage db_stack pkgid
421 toField :: String -> Maybe (InstalledPackageInfo -> String)
422 -- backwards compatibility:
423 toField "import_dirs" = Just $ strList . importDirs
424 toField "source_dirs" = Just $ strList . importDirs
425 toField "library_dirs" = Just $ strList . libraryDirs
426 toField "hs_libraries" = Just $ strList . hsLibraries
427 toField "extra_libraries" = Just $ strList . extraLibraries
428 toField "include_dirs" = Just $ strList . includeDirs
429 toField "c_includes" = Just $ strList . includes
430 toField "package_deps" = Just $ strList . map showPackageId. depends
431 toField "extra_cc_opts" = Just $ strList . extraCcOpts
432 toField "extra_ld_opts" = Just $ strList . extraLdOpts
433 toField "framework_dirs" = Just $ strList . frameworkDirs
434 toField "extra_frameworks"= Just $ strList . extraFrameworks
435 toField s = showInstalledPackageInfoField s
437 strList :: [String] -> String
440 -- -----------------------------------------------------------------------------
441 -- Manipulating package.conf files
443 checkConfigAccess :: FilePath -> IO ()
444 checkConfigAccess filename = do
445 access <- getPermissions filename
446 when (not (writable access))
447 (die (filename ++ ": you don't have permission to modify this file"))
449 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
450 maybeRestoreOldConfig filename io
451 = io `catch` \e -> do
452 hPutStrLn stderr (show e)
453 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
454 "configuration was being written. Attempting to \n"++
455 "restore the old configuration... ")
456 renameFile (filename ++ ".old") filename
457 hPutStrLn stdout "done."
460 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
461 writeNewConfig filename packages = do
462 hPutStr stdout "Writing new package config file... "
463 h <- openFile filename WriteMode
464 hPutStrLn h (show packages)
466 hPutStrLn stdout "done."
468 savePackageConfig :: FilePath -> IO ()
469 savePackageConfig filename = do
470 hPutStr stdout "Saving old package config file... "
471 -- mv rather than cp because we've already done an hGetContents
472 -- on this file so we won't be able to open it for writing
473 -- unless we move the old one out of the way...
474 let oldFile = filename ++ ".old"
475 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
476 when doesExist (removeFile oldFile `catch` (const $ return ()))
477 catch (renameFile filename oldFile)
479 hPutStrLn stderr (unwords [ "Unable to rename "
485 hPutStrLn stdout "done."
487 -----------------------------------------------------------------------------
488 -- Sanity-check a new package config, and automatically build GHCi libs
491 validatePackageConfig :: InstalledPackageInfo
493 -> Bool -- auto-ghc-libs
497 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
498 checkDuplicates db_stack pkg update
499 mapM_ (checkDep db_stack force) (depends pkg)
500 mapM_ (checkDir force) (importDirs pkg)
501 mapM_ (checkDir force) (libraryDirs pkg)
502 mapM_ (checkDir force) (includeDirs pkg)
503 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
504 -- ToDo: check these somehow?
505 -- extra_libraries :: [String],
506 -- c_includes :: [String],
509 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
510 checkDuplicates db_stack pkg update = do
514 (_top_db_name, pkgs) : _ = db_stack
516 pkgs_with_same_name =
517 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
518 exposed_pkgs_with_same_name =
519 filter exposed pkgs_with_same_name
521 -- Check whether this package id already exists in this DB
523 when (not update && (package pkg `elem` map package pkgs)) $
524 die ("package " ++ showPackageId pkgid ++ " is already installed")
526 -- if we are exposing this new package, then check that
527 -- there are no other exposed packages with the same name.
529 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
530 die ("trying to register " ++ showPackageId pkgid
531 ++ " as exposed, but "
532 ++ showPackageId (package (head exposed_pkgs_with_same_name))
533 ++ " is also exposed.")
536 checkDir :: Bool -> String -> IO ()
538 | "$libdir" `isPrefixOf` d = return ()
539 -- can't check this, because we don't know what $libdir is
541 there <- doesDirectoryExist d
543 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
545 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
546 checkDep db_stack force pkgid
547 | real_version && pkgid `elem` pkgids = return ()
548 | not real_version && pkgName pkgid `elem` pkg_names = return ()
549 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
552 -- for backwards compat, we treat 0.0 as a special version,
553 -- and don't check that it actually exists.
554 real_version = realVersion pkgid
556 all_pkgs = concat (map snd db_stack)
557 pkgids = map package all_pkgs
558 pkg_names = map pkgName pkgids
560 realVersion :: PackageIdentifier -> Bool
561 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
563 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
564 checkHSLib dirs auto_ghci_libs force lib = do
565 let batch_lib_file = "lib" ++ lib ++ ".a"
566 bs <- mapM (doesLibExistIn batch_lib_file) dirs
567 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
568 [] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
570 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
572 doesLibExistIn :: String -> String -> IO Bool
574 | "$libdir" `isPrefixOf` d = return True
575 | otherwise = doesFileExist (d ++ '/':lib)
577 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
578 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
579 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
581 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
582 case [dir | (exists,dir) <- zip bs dirs, exists] of
583 [] -> hPutStrLn stderr ("warning: can't find GHCi lib `" ++ ghci_lib_file ++ "'")
586 ghci_lib_file = lib ++ ".o"
588 -- automatically build the GHCi version of a batch lib,
589 -- using ld --whole-archive.
591 autoBuildGHCiLib :: String -> String -> String -> IO ()
592 autoBuildGHCiLib dir batch_file ghci_file = do
593 let ghci_lib_file = dir ++ '/':ghci_file
594 batch_lib_file = dir ++ '/':batch_file
595 hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
596 #if defined(darwin_TARGET_OS)
597 r <- system("ld -r -x -o " ++ ghci_lib_file ++
598 " -all_load " ++ batch_lib_file)
599 #elif defined(mingw32_HOST_OS)
600 execDir <- getExecDir "/bin/ghc-pkg.exe"
601 r <- system (maybe "" (++"/gcc-lib/") execDir++"ld -r -x -o " ++
602 ghci_lib_file ++ " --whole-archive " ++ batch_lib_file)
604 r <- system("ld -r -x -o " ++ ghci_lib_file ++
605 " --whole-archive " ++ batch_lib_file)
607 when (r /= ExitSuccess) $ exitWith r
608 hPutStrLn stderr (" done.")
610 -- -----------------------------------------------------------------------------
611 -- Updating the DB with the new package.
615 -> [InstalledPackageInfo]
616 -> InstalledPackageInfo
617 -> IO [InstalledPackageInfo]
618 updatePackageDB db_stack pkgs new_pkg = do
620 -- we update dependencies without version numbers to
621 -- match the actual versions of the relevant packages instaled.
622 updateDeps p = p{depends = map resolveDep (depends p)}
625 | realVersion pkgid = pkgid
626 | otherwise = lookupDep (pkgName pkgid)
629 = head [ pid | p <- concat (map snd db_stack),
631 pkgName pid == name ]
633 is_exposed = exposed new_pkg
634 pkgid = package new_pkg
637 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
639 -- When update is on, and we're exposing the new package,
640 -- we hide any packages with the same name (different versions)
641 -- in the current DB. Earlier checks will have failed if
644 | is_exposed && pkgName (package p) == name = p{ exposed = False }
647 return (pkgs'++[updateDeps new_pkg])
649 -- -----------------------------------------------------------------------------
650 -- Searching for modules
654 findModules :: [FilePath] -> IO [String]
656 mms <- mapM searchDir paths
659 searchDir path prefix = do
660 fs <- getDirectoryEntries path `catch` \_ -> return []
661 searchEntries path prefix fs
663 searchEntries path prefix [] = return []
664 searchEntries path prefix (f:fs)
665 | looks_like_a_module = do
666 ms <- searchEntries path prefix fs
667 return (prefix `joinModule` f : ms)
668 | looks_like_a_component = do
669 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
670 ms' <- searchEntries path prefix fs
673 searchEntries path prefix fs
676 (base,suffix) = splitFileExt f
677 looks_like_a_module =
678 suffix `elem` haskell_suffixes &&
679 all okInModuleName base
680 looks_like_a_component =
681 null suffix && all okInModuleName base
687 -- -----------------------------------------------------------------------------
688 -- The old command-line syntax, supported for backwards compatibility
695 | OF_Add Bool {- True => replace existing info -}
696 | OF_Remove String | OF_Show String
697 | OF_Field String | OF_AutoGHCiLibs | OF_Force
698 | OF_DefinedName String String
699 | OF_GlobalConfig FilePath
702 isAction :: OldFlag -> Bool
703 isAction OF_Config{} = False
704 isAction OF_Field{} = False
705 isAction OF_Input{} = False
706 isAction OF_AutoGHCiLibs{} = False
707 isAction OF_Force{} = False
708 isAction OF_DefinedName{} = False
709 isAction OF_GlobalConfig{} = False
712 oldFlags :: [OptDescr OldFlag]
714 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
715 "use the specified package config file",
716 Option ['l'] ["list-packages"] (NoArg OF_List)
717 "list packages in all config files",
718 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
719 "list packages in the specified config file",
720 Option ['a'] ["add-package"] (NoArg (OF_Add False))
722 Option ['u'] ["update-package"] (NoArg (OF_Add True))
723 "update package with new configuration",
724 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
725 "read new package info from specified file",
726 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
727 "show the configuration for package NAME",
728 Option [] ["field"] (ReqArg OF_Field "FIELD")
729 "(with --show-package) Show field FIELD only",
730 Option [] ["force"] (NoArg OF_Force)
731 "ignore missing directories/libraries",
732 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
733 "remove an installed package",
734 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
735 "automatically build libs for GHCi (with -a)",
736 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
737 "define NAME as VALUE",
738 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
739 "location of the global package config"
743 case break (=='=') str of
744 (nm,[]) -> OF_DefinedName nm []
745 (nm,_:val) -> OF_DefinedName nm val
747 oldRunit :: [OldFlag] -> IO ()
749 let config_flags = [ f | Just f <- map conv clis ]
751 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
752 conv (OF_Config f) = Just (FlagConfig f)
755 db_names <- getPkgDatabases config_flags
756 db_stack <- mapM readParseDatabase db_names
758 let fields = [ f | OF_Field f <- clis ]
760 let auto_ghci_libs = any isAuto clis
761 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
762 input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
764 force = OF_Force `elem` clis
766 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
768 case [ c | c <- clis, isAction c ] of
769 [ OF_List ] -> listPackages db_stack
770 [ OF_ListLocal ] -> listPackages db_stack
771 [ OF_Add upd ] -> registerPackage input_file defines db_stack
772 auto_ghci_libs upd force
773 [ OF_Remove p ] -> unregisterPackage db_stack (pkgNameToId p)
775 | null fields -> describePackage db_stack (pkgNameToId p)
776 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
777 _ -> do prog <- getProgramName
778 die (usageInfo (usageHeader prog) flags)
780 -- ---------------------------------------------------------------------------
784 expandEnvVars :: PackageConfig -> [(String, String)]
785 -> Bool -> IO PackageConfig
786 expandEnvVars pkg defines force = do
787 -- permit _all_ strings to contain ${..} environment variable references,
788 -- arguably too flexible.
789 nm <- expandString (name pkg)
790 imp_dirs <- expandStrings (import_dirs pkg)
791 src_dirs <- expandStrings (source_dirs pkg)
792 lib_dirs <- expandStrings (library_dirs pkg)
793 hs_libs <- expandStrings (hs_libraries pkg)
794 ex_libs <- expandStrings (extra_libraries pkg)
795 inc_dirs <- expandStrings (include_dirs pkg)
796 c_incs <- expandStrings (c_includes pkg)
797 p_deps <- expandStrings (package_deps pkg)
798 e_g_opts <- expandStrings (extra_ghc_opts pkg)
799 e_c_opts <- expandStrings (extra_cc_opts pkg)
800 e_l_opts <- expandStrings (extra_ld_opts pkg)
801 f_dirs <- expandStrings (framework_dirs pkg)
802 e_frames <- expandStrings (extra_frameworks pkg)
803 return (pkg { name = nm
804 , import_dirs = imp_dirs
805 , source_dirs = src_dirs
806 , library_dirs = lib_dirs
807 , hs_libraries = hs_libs
808 , extra_libraries = ex_libs
809 , include_dirs = inc_dirs
810 , c_includes = c_incs
811 , package_deps = p_deps
812 , extra_ghc_opts = e_g_opts
813 , extra_cc_opts = e_c_opts
814 , extra_ld_opts = e_l_opts
815 , framework_dirs = f_dirs
816 , extra_frameworks= e_frames
819 expandStrings :: [String] -> IO [String]
820 expandStrings = liftM concat . mapM expandSpecial
822 -- Permit substitutions for list-valued variables (but only when
823 -- they occur alone), e.g., package_deps["${deps}"] where env var
824 -- (say) 'deps' is "base,haskell98,network"
825 expandSpecial :: String -> IO [String]
827 let expand f = liftM f $ expandString str
828 in case splitString str of
829 [Var _] -> expand (wordsBy (== ','))
830 _ -> expand (\x -> [x])
832 expandString :: String -> IO String
833 expandString = liftM concat . mapM expandElem . splitString
835 expandElem :: Elem -> IO String
836 expandElem (String s) = return s
837 expandElem (Var v) = lookupEnvVar v
839 lookupEnvVar :: String -> IO String
841 case lookup nm defines of
842 Just x | not (null x) -> return x
844 catch (System.getEnv nm)
845 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
849 data Elem = String String | Var String
851 splitString :: String -> [Elem]
854 case break (== '$') str of
856 case span (/= '}') xs of
858 (if null pre then id else (String pre :)) (Var var : splitString suf)
859 _ -> [String str] -- no closing brace
860 _ -> [String str] -- no dollar/opening brace combo
862 -- wordsBy isSpace == words
863 wordsBy :: (Char -> Bool) -> String -> [String]
864 wordsBy p s = case dropWhile p s of
866 s' -> w : wordsBy p s'' where (w,s'') = break p s'
869 -----------------------------------------------------------------------------
871 getProgramName :: IO String
872 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
873 where str `withoutSuffix` suff
874 | suff `isSuffixOf` str = take (length str - length suff) str
877 bye :: String -> IO a
878 bye s = putStr s >> exitWith ExitSuccess
880 die :: String -> IO a
883 prog <- getProgramName
884 hPutStrLn stderr (prog ++ ": " ++ s)
885 exitWith (ExitFailure 1)
887 dieOrForce :: Bool -> String -> IO ()
889 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
893 -----------------------------------------------------------------------------
894 -- Create a hierarchy of directories
896 createParents :: FilePath -> IO ()
897 createParents dir = do
898 let parent = directoryOf dir
899 b <- doesDirectoryExist parent
902 createDirectory parent
904 -----------------------------------------
905 -- Cut and pasted from ghc/compiler/SysTools
907 #if defined(mingw32_HOST_OS)
908 subst a b ls = map (\ x -> if x == a then b else x) ls
909 unDosifyPath xs = subst '\\' '/' xs
911 getExecDir :: String -> IO (Maybe String)
912 -- (getExecDir cmd) returns the directory in which the current
913 -- executable, which should be called 'cmd', is running
914 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
915 -- you'll get "/a/b/c" back as the result
917 = allocaArray len $ \buf -> do
918 ret <- getModuleFileName nullPtr buf len
919 if ret == 0 then return Nothing
920 else do s <- peekCString buf
921 return (Just (reverse (drop (length cmd)
922 (reverse (unDosifyPath s)))))
924 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
926 foreign import stdcall unsafe "GetModuleFileNameA"
927 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
929 getExecDir :: String -> IO (Maybe String)
930 getExecDir _ = return Nothing
933 -- -----------------------------------------------------------------------------
934 -- Utils from Krasimir's FilePath library, copied here for now
936 directoryOf :: FilePath -> FilePath
937 directoryOf = fst.splitFileName
939 splitFileName :: FilePath -> (String, String)
940 splitFileName p = (reverse (path2++drive), reverse fname)
942 #ifdef mingw32_TARGET_OS
943 (path,drive) = break (== ':') (reverse p)
945 (path,drive) = (reverse p,"")
947 (fname,path1) = break isPathSeparator path
948 path2 = case path1 of
950 [_] -> path1 -- don't remove the trailing slash if
951 -- there is only one character
952 (c:path) | isPathSeparator c -> path
955 joinFileName :: String -> String -> FilePath
956 joinFileName "" fname = fname
957 joinFileName "." fname = fname
958 joinFileName dir fname
959 | isPathSeparator (last dir) = dir++fname
960 | otherwise = dir++pathSeparator:fname
962 isPathSeparator :: Char -> Bool
964 #ifdef mingw32_TARGET_OS
965 ch == '/' || ch == '\\'
970 pathSeparator :: Char
971 #ifdef mingw32_TARGET_OS