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 List ( isPrefixOf, isSuffixOf )
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\n")
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 ++ "\n")
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 when (pkgid `notElem` map package pkgs)
354 (die (db_name ++ ": package '" ++ showPackageId pkgid
356 savePackageConfig db_name
357 maybeRestoreOldConfig db_name $
358 writeNewConfig db_name (filter ((/= pkgid) . package) pkgs)
360 -- -----------------------------------------------------------------------------
363 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
364 exposePackage = error "TODO"
366 -- -----------------------------------------------------------------------------
369 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
370 hidePackage = error "TODO"
372 -- -----------------------------------------------------------------------------
375 listPackages :: PackageDBStack -> IO ()
376 listPackages db_confs = do
377 mapM_ show_pkgconf (reverse db_confs)
378 where show_pkgconf (db_name,pkg_confs) =
379 hPutStrLn stdout (render $
380 text (db_name ++ ":") $$ nest 4 packages
382 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
383 pp_pkg = text . showPackageId . package
386 -- -----------------------------------------------------------------------------
389 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
390 describePackage db_stack pkgid = do
391 p <- findPackage db_stack pkgid
392 putStrLn (showInstalledPackageInfo p)
394 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
395 findPackage db_stack pkgid
396 = case [ p | p <- all_pkgs, pkgid == package p ] of
397 [] -> die ("cannot find package " ++ showPackageId pkgid)
400 all_pkgs = concat (map snd db_stack)
402 -- -----------------------------------------------------------------------------
405 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
406 describeField db_stack pkgid field = do
407 case toField field of
408 Nothing -> die ("unknown field: " ++ field)
410 p <- findPackage db_stack pkgid
413 toField :: String -> Maybe (InstalledPackageInfo -> String)
414 -- backwards compatibility:
415 toField "import_dirs" = Just $ strList . importDirs
416 toField "source_dirs" = Just $ strList . importDirs
417 toField "library_dirs" = Just $ strList . libraryDirs
418 toField "hs_libraries" = Just $ strList . hsLibraries
419 toField "extra_libraries" = Just $ strList . extraLibraries
420 toField "include_dirs" = Just $ strList . includeDirs
421 toField "c_includes" = Just $ strList . includes
422 toField "package_deps" = Just $ strList . map showPackageId. depends
423 toField "extra_cc_opts" = Just $ strList . extraCcOpts
424 toField "extra_ld_opts" = Just $ strList . extraLdOpts
425 toField "framework_dirs" = Just $ strList . frameworkDirs
426 toField "extra_frameworks"= Just $ strList . extraFrameworks
427 toField s = showInstalledPackageInfoField s
429 strList :: [String] -> String
432 -- -----------------------------------------------------------------------------
433 -- Manipulating package.conf files
435 checkConfigAccess :: FilePath -> IO ()
436 checkConfigAccess filename = do
437 access <- getPermissions filename
438 when (not (writable access))
439 (die (filename ++ ": you don't have permission to modify this file\n"))
441 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
442 maybeRestoreOldConfig filename io
443 = io `catch` \e -> do
444 hPutStrLn stderr (show e)
445 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
446 "configuration was being written. Attempting to \n"++
447 "restore the old configuration... ")
448 renameFile (filename ++ ".old") filename
449 hPutStrLn stdout "done."
452 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
453 writeNewConfig filename packages = do
454 hPutStr stdout "Writing new package config file... "
455 h <- openFile filename WriteMode
456 hPutStrLn h (show packages)
458 hPutStrLn stdout "done."
460 savePackageConfig :: FilePath -> IO ()
461 savePackageConfig filename = do
462 hPutStr stdout "Saving old package config file... "
463 -- mv rather than cp because we've already done an hGetContents
464 -- on this file so we won't be able to open it for writing
465 -- unless we move the old one out of the way...
466 let oldFile = filename ++ ".old"
467 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
468 when doesExist (removeFile oldFile `catch` (const $ return ()))
469 catch (renameFile filename oldFile)
471 hPutStrLn stderr (unwords [ "Unable to rename "
477 hPutStrLn stdout "done."
479 -----------------------------------------------------------------------------
480 -- Sanity-check a new package config, and automatically build GHCi libs
483 validatePackageConfig :: InstalledPackageInfo
485 -> Bool -- auto-ghc-libs
489 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
490 checkDuplicates db_stack pkg update
491 mapM_ (checkDep db_stack force) (depends pkg)
492 mapM_ (checkDir force) (importDirs pkg)
493 mapM_ (checkDir force) (libraryDirs pkg)
494 mapM_ (checkDir force) (includeDirs pkg)
495 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
496 -- ToDo: check these somehow?
497 -- extra_libraries :: [String],
498 -- c_includes :: [String],
501 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
502 checkDuplicates db_stack pkg update = do
506 (_top_db_name, pkgs) : _ = db_stack
508 pkgs_with_same_name =
509 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
510 exposed_pkgs_with_same_name =
511 filter exposed pkgs_with_same_name
513 -- Check whether this package id already exists in this DB
515 when (not update && (package pkg `elem` map package pkgs)) $
516 die ("package " ++ showPackageId pkgid ++ " is already installed\n")
518 -- if we are exposing this new package, then check that
519 -- there are no other exposed packages with the same name.
521 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
522 die ("trying to register " ++ showPackageId pkgid
523 ++ " as exposed, but "
524 ++ showPackageId (package (head exposed_pkgs_with_same_name))
525 ++ " is also exposed.")
528 checkDir :: Bool -> String -> IO ()
530 | "$libdir" `isPrefixOf` d = return ()
531 -- can't check this, because we don't know what $libdir is
533 there <- doesDirectoryExist d
535 (dieOrForce force (d ++ " doesn't exist or isn't a directory\n"))
537 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
538 checkDep db_stack force pkgid
539 | real_version && pkgid `elem` pkgids = return ()
540 | not real_version && pkgName pkgid `elem` pkg_names = return ()
541 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
542 ++ " doesn't exist\n")
544 -- for backwards compat, we treat 0.0 as a special version,
545 -- and don't check that it actually exists.
546 real_version = realVersion pkgid
548 all_pkgs = concat (map snd db_stack)
549 pkgids = map package all_pkgs
550 pkg_names = map pkgName pkgids
552 realVersion :: PackageIdentifier -> Bool
553 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
555 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
556 checkHSLib dirs auto_ghci_libs force lib = do
557 let batch_lib_file = "lib" ++ lib ++ ".a"
558 bs <- mapM (doesLibExistIn batch_lib_file) dirs
559 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
560 [] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
562 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
564 doesLibExistIn :: String -> String -> IO Bool
566 | "$libdir" `isPrefixOf` d = return True
567 | otherwise = doesFileExist (d ++ '/':lib)
569 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
570 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
571 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
573 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
574 case [dir | (exists,dir) <- zip bs dirs, exists] of
575 [] -> hPutStrLn stderr ("warning: can't find GHCi lib `" ++ ghci_lib_file ++ "'")
578 ghci_lib_file = lib ++ ".o"
580 -- automatically build the GHCi version of a batch lib,
581 -- using ld --whole-archive.
583 autoBuildGHCiLib :: String -> String -> String -> IO ()
584 autoBuildGHCiLib dir batch_file ghci_file = do
585 let ghci_lib_file = dir ++ '/':ghci_file
586 batch_lib_file = dir ++ '/':batch_file
587 hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
588 #if defined(darwin_TARGET_OS)
589 r <- system("ld -r -x -o " ++ ghci_lib_file ++
590 " -all_load " ++ batch_lib_file)
591 #elif defined(mingw32_HOST_OS)
592 execDir <- getExecDir "/bin/ghc-pkg.exe"
593 r <- system (maybe "" (++"/gcc-lib/") execDir++"ld -r -x -o " ++
594 ghci_lib_file ++ " --whole-archive " ++ batch_lib_file)
596 r <- system("ld -r -x -o " ++ ghci_lib_file ++
597 " --whole-archive " ++ batch_lib_file)
599 when (r /= ExitSuccess) $ exitWith r
600 hPutStrLn stderr (" done.")
602 -- -----------------------------------------------------------------------------
603 -- Updating the DB with the new package.
607 -> [InstalledPackageInfo]
608 -> InstalledPackageInfo
609 -> IO [InstalledPackageInfo]
610 updatePackageDB db_stack pkgs new_pkg = do
612 -- we update dependencies without version numbers to
613 -- match the actual versions of the relevant packages instaled.
614 updateDeps p = p{depends = map resolveDep (depends p)}
617 | realVersion pkgid = pkgid
618 | otherwise = lookupDep (pkgName pkgid)
621 = head [ pid | p <- concat (map snd db_stack),
623 pkgName pid == name ]
625 is_exposed = exposed new_pkg
626 pkgid = package new_pkg
629 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
631 -- When update is on, and we're exposing the new package,
632 -- we hide any packages with the same name (different versions)
633 -- in the current DB. Earlier checks will have failed if
636 | is_exposed && pkgName (package p) == name = p{ exposed = False }
639 return (pkgs'++[updateDeps new_pkg])
641 -- -----------------------------------------------------------------------------
642 -- Searching for modules
646 findModules :: [FilePath] -> IO [String]
648 mms <- mapM searchDir paths
651 searchDir path prefix = do
652 fs <- getDirectoryEntries path `catch` \_ -> return []
653 searchEntries path prefix fs
655 searchEntries path prefix [] = return []
656 searchEntries path prefix (f:fs)
657 | looks_like_a_module = do
658 ms <- searchEntries path prefix fs
659 return (prefix `joinModule` f : ms)
660 | looks_like_a_component = do
661 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
662 ms' <- searchEntries path prefix fs
665 searchEntries path prefix fs
668 (base,suffix) = splitFileExt f
669 looks_like_a_module =
670 suffix `elem` haskell_suffixes &&
671 all okInModuleName base
672 looks_like_a_component =
673 null suffix && all okInModuleName base
679 -- -----------------------------------------------------------------------------
680 -- The old command-line syntax, supported for backwards compatibility
687 | OF_Add Bool {- True => replace existing info -}
688 | OF_Remove String | OF_Show String
689 | OF_Field String | OF_AutoGHCiLibs | OF_Force
690 | OF_DefinedName String String
691 | OF_GlobalConfig FilePath
694 isAction :: OldFlag -> Bool
695 isAction OF_Config{} = False
696 isAction OF_Field{} = False
697 isAction OF_Input{} = False
698 isAction OF_AutoGHCiLibs{} = False
699 isAction OF_Force{} = False
700 isAction OF_DefinedName{} = False
701 isAction OF_GlobalConfig{} = False
704 oldFlags :: [OptDescr OldFlag]
706 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
707 "use the specified package config file",
708 Option ['l'] ["list-packages"] (NoArg OF_List)
709 "list packages in all config files",
710 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
711 "list packages in the specified config file",
712 Option ['a'] ["add-package"] (NoArg (OF_Add False))
714 Option ['u'] ["update-package"] (NoArg (OF_Add True))
715 "update package with new configuration",
716 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
717 "read new package info from specified file",
718 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
719 "show the configuration for package NAME",
720 Option [] ["field"] (ReqArg OF_Field "FIELD")
721 "(with --show-package) Show field FIELD only",
722 Option [] ["force"] (NoArg OF_Force)
723 "ignore missing directories/libraries",
724 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
725 "remove an installed package",
726 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
727 "automatically build libs for GHCi (with -a)",
728 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
729 "define NAME as VALUE",
730 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
731 "location of the global package config"
735 case break (=='=') str of
736 (nm,[]) -> OF_DefinedName nm []
737 (nm,_:val) -> OF_DefinedName nm val
739 oldRunit :: [OldFlag] -> IO ()
741 let config_flags = [ f | Just f <- map conv clis ]
743 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
744 conv (OF_Config f) = Just (FlagConfig f)
747 db_names <- getPkgDatabases config_flags
748 db_stack <- mapM readParseDatabase db_names
750 let fields = [ f | OF_Field f <- clis ]
752 let auto_ghci_libs = any isAuto clis
753 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
754 input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
756 force = OF_Force `elem` clis
758 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
760 case [ c | c <- clis, isAction c ] of
761 [ OF_List ] -> listPackages db_stack
762 [ OF_ListLocal ] -> listPackages db_stack
763 [ OF_Add upd ] -> registerPackage input_file defines db_stack
764 auto_ghci_libs upd force
765 [ OF_Remove p ] -> unregisterPackage db_stack (pkgNameToId p)
767 | null fields -> describePackage db_stack (pkgNameToId p)
768 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
769 _ -> do prog <- getProgramName
770 die (usageInfo (usageHeader prog) flags)
772 -- ---------------------------------------------------------------------------
776 expandEnvVars :: PackageConfig -> [(String, String)]
777 -> Bool -> IO PackageConfig
778 expandEnvVars pkg defines force = do
779 -- permit _all_ strings to contain ${..} environment variable references,
780 -- arguably too flexible.
781 nm <- expandString (name pkg)
782 imp_dirs <- expandStrings (import_dirs pkg)
783 src_dirs <- expandStrings (source_dirs pkg)
784 lib_dirs <- expandStrings (library_dirs pkg)
785 hs_libs <- expandStrings (hs_libraries pkg)
786 ex_libs <- expandStrings (extra_libraries pkg)
787 inc_dirs <- expandStrings (include_dirs pkg)
788 c_incs <- expandStrings (c_includes pkg)
789 p_deps <- expandStrings (package_deps pkg)
790 e_g_opts <- expandStrings (extra_ghc_opts pkg)
791 e_c_opts <- expandStrings (extra_cc_opts pkg)
792 e_l_opts <- expandStrings (extra_ld_opts pkg)
793 f_dirs <- expandStrings (framework_dirs pkg)
794 e_frames <- expandStrings (extra_frameworks pkg)
795 return (pkg { name = nm
796 , import_dirs = imp_dirs
797 , source_dirs = src_dirs
798 , library_dirs = lib_dirs
799 , hs_libraries = hs_libs
800 , extra_libraries = ex_libs
801 , include_dirs = inc_dirs
802 , c_includes = c_incs
803 , package_deps = p_deps
804 , extra_ghc_opts = e_g_opts
805 , extra_cc_opts = e_c_opts
806 , extra_ld_opts = e_l_opts
807 , framework_dirs = f_dirs
808 , extra_frameworks= e_frames
811 expandStrings :: [String] -> IO [String]
812 expandStrings = liftM concat . mapM expandSpecial
814 -- Permit substitutions for list-valued variables (but only when
815 -- they occur alone), e.g., package_deps["${deps}"] where env var
816 -- (say) 'deps' is "base,haskell98,network"
817 expandSpecial :: String -> IO [String]
819 let expand f = liftM f $ expandString str
820 in case splitString str of
821 [Var _] -> expand (wordsBy (== ','))
822 _ -> expand (\x -> [x])
824 expandString :: String -> IO String
825 expandString = liftM concat . mapM expandElem . splitString
827 expandElem :: Elem -> IO String
828 expandElem (String s) = return s
829 expandElem (Var v) = lookupEnvVar v
831 lookupEnvVar :: String -> IO String
833 case lookup nm defines of
834 Just x | not (null x) -> return x
836 catch (System.getEnv nm)
837 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
841 data Elem = String String | Var String
843 splitString :: String -> [Elem]
846 case break (== '$') str of
848 case span (/= '}') xs of
850 (if null pre then id else (String pre :)) (Var var : splitString suf)
851 _ -> [String str] -- no closing brace
852 _ -> [String str] -- no dollar/opening brace combo
854 -- wordsBy isSpace == words
855 wordsBy :: (Char -> Bool) -> String -> [String]
856 wordsBy p s = case dropWhile p s of
858 s' -> w : wordsBy p s'' where (w,s'') = break p s'
861 -----------------------------------------------------------------------------
863 getProgramName :: IO String
864 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
865 where str `withoutSuffix` suff
866 | suff `isSuffixOf` str = take (length str - length suff) str
869 bye :: String -> IO a
870 bye s = putStr s >> exitWith ExitSuccess
872 die :: String -> IO a
875 prog <- getProgramName
876 hPutStr stderr (prog ++ ": " ++ s)
877 exitWith (ExitFailure 1)
879 dieOrForce :: Bool -> String -> IO ()
881 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
882 | otherwise = die (s ++ "\n")
885 -----------------------------------------------------------------------------
886 -- Create a hierarchy of directories
888 createParents :: FilePath -> IO ()
889 createParents dir = do
890 let parent = directoryOf dir
891 b <- doesDirectoryExist parent
894 createDirectory parent
896 -----------------------------------------
897 -- Cut and pasted from ghc/compiler/SysTools
899 #if defined(mingw32_HOST_OS)
900 subst a b ls = map (\ x -> if x == a then b else x) ls
901 unDosifyPath xs = subst '\\' '/' xs
903 getExecDir :: String -> IO (Maybe String)
904 -- (getExecDir cmd) returns the directory in which the current
905 -- executable, which should be called 'cmd', is running
906 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
907 -- you'll get "/a/b/c" back as the result
909 = allocaArray len $ \buf -> do
910 ret <- getModuleFileName nullPtr buf len
911 if ret == 0 then return Nothing
912 else do s <- peekCString buf
913 return (Just (reverse (drop (length cmd)
914 (reverse (unDosifyPath s)))))
916 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
918 foreign import stdcall unsafe "GetModuleFileNameA"
919 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
921 getExecDir :: String -> IO (Maybe String)
922 getExecDir _ = return Nothing
925 -- -----------------------------------------------------------------------------
926 -- Utils from Krasimir's FilePath library, copied here for now
928 directoryOf :: FilePath -> FilePath
929 directoryOf = fst.splitFileName
931 splitFileName :: FilePath -> (String, String)
932 splitFileName p = (reverse (path2++drive), reverse fname)
934 #ifdef mingw32_TARGET_OS
935 (path,drive) = break (== ':') (reverse p)
937 (path,drive) = (reverse p,"")
939 (fname,path1) = break isPathSeparator path
940 path2 = case path1 of
942 [_] -> path1 -- don't remove the trailing slash if
943 -- there is only one character
944 (c:path) | isPathSeparator c -> path
947 joinFileName :: String -> String -> FilePath
948 joinFileName "" fname = fname
949 joinFileName "." fname = fname
950 joinFileName dir fname
951 | isPathSeparator (last dir) = dir++fname
952 | otherwise = dir++pathSeparator:fname
954 isPathSeparator :: Char -> Bool
956 #ifdef mingw32_TARGET_OS
957 ch == '/' || ch == '\\'
962 pathSeparator :: Char
963 #ifdef mingw32_TARGET_OS