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.Package
23 import Distribution.License
24 import Distribution.Version
25 import Compat.Directory ( getAppUserDataDirectory )
26 import Control.Exception ( catch, throw, evaluate )
28 import Prelude hiding ( catch )
30 import Package -- the old package config type
32 #if __GLASGOW_HASKELL__ < 603
36 #if __GLASGOW_HASKELL__ >= 504
37 import System.Console.GetOpt
38 import Text.PrettyPrint
39 import qualified Control.Exception as Exception
43 import qualified Exception
46 import Data.Char ( isSpace )
49 import System ( getEnv, getArgs, getProgName,
53 import IO hiding ( catch )
54 import List ( isPrefixOf, isSuffixOf )
56 import ParsePkgConfLite
58 #include "../../includes/ghcconfig.h"
60 #ifdef mingw32_HOST_OS
63 #if __GLASGOW_HASKELL__ >= 504
64 import Foreign.C.String
70 -- -----------------------------------------------------------------------------
77 case getOpt Permute flags args of
78 (cli,_,[]) | FlagHelp `elem` cli -> do
79 prog <- getProgramName
80 bye (usageInfo (usageHeader prog) flags)
81 (cli,_,[]) | FlagVersion `elem` cli ->
83 (cli@(_:_),nonopts,[]) ->
85 (_,_,errors) -> tryOldCmdLine errors args
87 -- If the new command-line syntax fails, then we try the old. If that
88 -- fails too, then we output the original errors and the new syntax
89 -- (so the old syntax is still available, but hidden).
90 tryOldCmdLine :: [String] -> [String] -> IO ()
91 tryOldCmdLine errors args = do
92 case getOpt Permute oldFlags args of
96 prog <- getProgramName
97 die (concat errors ++ usageInfo (usageHeader prog) flags)
99 -- -----------------------------------------------------------------------------
100 -- Command-line syntax
107 | FlagConfig FilePath
108 | FlagGlobalConfig FilePath
112 flags :: [OptDescr Flag]
114 Option [] ["user"] (NoArg FlagUser)
115 "use the current user's package database",
116 Option [] ["global"] (NoArg FlagGlobal)
117 "(default) use the global package database",
118 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
119 "act upon specified package config file (only)",
120 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
121 "location of the global package config",
122 Option [] ["force"] (NoArg FlagForce)
123 "ignore missing dependencies, directories, and libraries",
124 Option ['?'] ["help"] (NoArg FlagHelp)
125 "display this help and exit",
126 Option ['V'] ["version"] (NoArg FlagVersion)
127 "output version information and exit"
130 ourCopyright :: String
131 ourCopyright = "GHC package manager version " ++ version ++ "\n"
133 usageHeader :: String -> String
134 usageHeader prog = substProg prog $
136 " $p {--help | -?}\n" ++
137 " Produce this usage message.\n" ++
139 " $p register {filename | -} [--user | --global]\n" ++
140 " Register the package using the specified installed package\n" ++
141 " description. The syntax for the latter is given in the $p\n" ++
142 " documentation.\n" ++
144 " $p unregister {pkg-id}\n" ++
145 " Unregister the specified package.\n" ++
147 " $p expose {pkg-id}\n" ++
148 " Expose the specified package.\n" ++
150 " $p hide {pkg-id}\n" ++
151 " Hide the specified package.\n" ++
153 " $p list [--global | --user]\n" ++
154 " List all registered packages, both global and user (unless either\n" ++
155 " --global or --user is specified), and both hidden and exposed.\n" ++
157 " $p describe {pkg-id}\n" ++
158 " Give the registered description for the specified package. The\n" ++
159 " description is returned in precisely the syntax required by $p\n" ++
162 " $p field {pkg-id} {field}\n" ++
163 " Extract the specified field of the package description for the\n" ++
164 " specified package.\n"
166 substProg :: String -> String -> String
168 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
169 substProg prog (c:xs) = c : substProg prog xs
171 -- -----------------------------------------------------------------------------
174 runit :: [Flag] -> [String] -> IO ()
175 runit cli nonopts = do
176 prog <- getProgramName
177 dbs <- getPkgDatabases cli
178 db_stack <- mapM readParseDatabase dbs
180 force = FlagForce `elem` cli
182 -- first, parse the command
184 ["register", filename] ->
185 registerPackage filename [] db_stack False False force
186 ["update", filename] ->
187 registerPackage filename [] db_stack False True force
188 ["unregister", pkgid_str] -> do
189 pkgid <- readPkgId pkgid_str
190 unregisterPackage db_stack pkgid
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 readP_to_S parser str of
215 [(x,ys)] | all isSpace ys -> return x
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 `catch` \_ -> die (filename ++ ": parse error in package config file\n")
292 return (filename,packages)
294 emptyPackageConfig :: String
295 emptyPackageConfig = "[]"
297 -- -----------------------------------------------------------------------------
300 registerPackage :: FilePath
301 -> [(String,String)] -- defines, ToDo: maybe remove?
303 -> Bool -- auto_ghci_libs
307 registerPackage input defines db_stack auto_ghci_libs update force = do
309 db_to_operate_on = head db_stack
310 db_filename = fst db_to_operate_on
312 checkConfigAccess db_filename
317 putStr "Reading package info from stdin... "
320 putStr ("Reading package info from " ++ show f)
323 pkg <- parsePackageInfo s defines force
326 validatePackageConfig pkg db_stack auto_ghci_libs update force
327 new_details <- updatePackageDB (snd db_to_operate_on) pkg
328 savePackageConfig db_filename
329 maybeRestoreOldConfig db_filename $
330 writeNewConfig db_filename new_details
336 -> IO InstalledPackageInfo
337 parsePackageInfo str defines force =
338 case parseInstalledPackageInfo str of
339 Right ok -> return ok
341 old_pkg <- evaluate (parseOnePackageConfig str)
342 `catch` \_ -> parse_failed
343 putStr "Expanding embedded variables... "
344 new_old_pkg <- expandEnvVars old_pkg defines force
345 return (convertOldPackage old_pkg)
347 parse_failed = die "parse error in package info\n"
349 convertOldPackage :: PackageConfig -> InstalledPackageInfo
354 import_dirs = import_dirs,
355 source_dirs = source_dirs,
356 library_dirs = library_dirs,
357 hs_libraries = hs_libraries,
358 extra_libraries = extra_libraries,
359 include_dirs = include_dirs,
360 c_includes = c_includes,
361 package_deps = package_deps,
362 extra_ghc_opts = extra_ghc_opts,
363 extra_cc_opts = extra_cc_opts,
364 extra_ld_opts = extra_ld_opts,
365 framework_dirs = framework_dirs,
366 extra_frameworks= extra_frameworks
368 = InstalledPackageInfo {
369 package = pkgNameToId name,
370 license = AllRightsReserved,
382 importDirs = import_dirs,
383 libraryDirs = library_dirs,
384 hsLibraries = hs_libraries,
385 extraLibraries = extra_libraries,
386 includeDirs = include_dirs,
387 includes = c_includes,
388 depends = map pkgNameToId package_deps,
390 extraCcOpts = extra_cc_opts,
391 extraLdOpts = extra_ld_opts,
392 frameworkDirs = framework_dirs,
393 extraFrameworks = extra_frameworks,
394 haddockInterfaces = [],
399 -- Used for converting old versionless package names to new PackageIdentifiers.
400 -- "Version [] []" is special: it means "no version" or "any version"
401 pkgNameToId :: String -> PackageIdentifier
402 pkgNameToId name = PackageIdentifier name (Version [] [])
404 -- -----------------------------------------------------------------------------
407 unregisterPackage :: PackageDBStack -> PackageIdentifier -> IO ()
408 unregisterPackage [] _ = error "unregisterPackage"
409 unregisterPackage ((db_name, pkgs) : _) pkgid = do
410 checkConfigAccess db_name
411 when (pkgid `notElem` map package pkgs)
412 (die (db_name ++ ": package '" ++ showPackageId pkgid
414 savePackageConfig db_name
415 maybeRestoreOldConfig db_name $
416 writeNewConfig db_name (filter ((/= pkgid) . package) pkgs)
418 -- -----------------------------------------------------------------------------
421 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
422 exposePackage = error "TODO"
424 -- -----------------------------------------------------------------------------
427 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
428 hidePackage = error "TODO"
430 -- -----------------------------------------------------------------------------
433 listPackages :: PackageDBStack -> IO ()
434 listPackages db_confs = do
435 mapM_ show_pkgconf (reverse db_confs)
436 where show_pkgconf (db_name,pkg_confs) =
437 hPutStrLn stdout (render $
438 text (db_name ++ ":") $$ nest 4 packages
440 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
441 pp_pkg = text . showPackageId . package
444 -- -----------------------------------------------------------------------------
447 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
448 describePackage db_stack pkgid = do
449 p <- findPackage db_stack pkgid
450 putStrLn (showInstalledPackageInfo p)
452 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
453 findPackage db_stack pkgid
454 = case [ p | p <- all_pkgs, pkgid == package p ] of
455 [] -> die ("cannot find package " ++ showPackageId pkgid)
458 all_pkgs = concat (map snd db_stack)
460 -- -----------------------------------------------------------------------------
463 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
464 describeField db_stack pkgid field = do
465 case toField field of
466 Nothing -> die ("unknown field: " ++ field)
468 p <- findPackage db_stack pkgid
471 toField :: String -> Maybe (InstalledPackageInfo -> String)
472 -- backwards compatibility:
473 toField "import_dirs" = Just $ strList . importDirs
474 toField "source_dirs" = Just $ strList . importDirs
475 toField "library_dirs" = Just $ strList . libraryDirs
476 toField "hs_libraries" = Just $ strList . hsLibraries
477 toField "extra_libraries" = Just $ strList . extraLibraries
478 toField "include_dirs" = Just $ strList . includeDirs
479 toField "c_includes" = Just $ strList . includes
480 toField "package_deps" = Just $ strList . map showPackageId. depends
481 toField "extra_cc_opts" = Just $ strList . extraCcOpts
482 toField "extra_ld_opts" = Just $ strList . extraLdOpts
483 toField "framework_dirs" = Just $ strList . frameworkDirs
484 toField "extra_frameworks"= Just $ strList . extraFrameworks
485 toField s = showInstalledPackageInfoField s
487 strList :: [String] -> String
490 -- -----------------------------------------------------------------------------
491 -- Manipulating package.conf files
493 checkConfigAccess :: FilePath -> IO ()
494 checkConfigAccess filename = do
495 access <- getPermissions filename
496 when (not (writable access))
497 (die (filename ++ ": you don't have permission to modify this file\n"))
499 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
500 maybeRestoreOldConfig filename io
501 = io `catch` \e -> do
502 hPutStrLn stderr (show e)
503 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
504 "configuration was being written. Attempting to \n"++
505 "restore the old configuration... ")
506 renameFile (filename ++ ".old") filename
507 hPutStrLn stdout "done."
510 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
511 writeNewConfig filename packages = do
512 hPutStr stdout "Writing new package config file... "
513 h <- openFile filename WriteMode
514 hPutStrLn h (show packages)
516 hPutStrLn stdout "done."
518 savePackageConfig :: FilePath -> IO ()
519 savePackageConfig filename = do
520 hPutStr stdout "Saving old package config file... "
521 -- mv rather than cp because we've already done an hGetContents
522 -- on this file so we won't be able to open it for writing
523 -- unless we move the old one out of the way...
524 let oldFile = filename ++ ".old"
525 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
526 when doesExist (removeFile oldFile `catch` (const $ return ()))
527 catch (renameFile filename oldFile)
529 hPutStrLn stderr (unwords [ "Unable to rename "
535 hPutStrLn stdout "done."
537 -----------------------------------------------------------------------------
538 -- Sanity-check a new package config, and automatically build GHCi libs
541 validatePackageConfig :: InstalledPackageInfo
543 -> Bool -- auto-ghc-libs
547 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
548 checkDuplicates db_stack pkg update
549 mapM_ (checkDep db_stack force) (depends pkg)
550 mapM_ (checkDir force) (importDirs pkg)
551 mapM_ (checkDir force) (libraryDirs pkg)
552 mapM_ (checkDir force) (includeDirs pkg)
553 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
554 -- ToDo: check these somehow?
555 -- extra_libraries :: [String],
556 -- c_includes :: [String],
559 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
560 checkDuplicates db_stack pkg update = do
564 (_top_db_name, pkgs) : _ = db_stack
566 pkgs_with_same_name =
567 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
568 exposed_pkgs_with_same_name =
569 filter exposed pkgs_with_same_name
571 -- Check whether this package id already exists in this DB
573 when (not update && (package pkg `elem` map package pkgs)) $
574 die ("package " ++ showPackageId pkgid ++ " is already installed\n")
576 -- if we are exposing this new package, then check that
577 -- there are no other exposed packages with the same name.
579 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
580 die ("trying to register " ++ showPackageId pkgid
581 ++ " as exposed, but "
582 ++ showPackageId (package (head exposed_pkgs_with_same_name))
583 ++ " is also exposed.")
586 checkDir :: Bool -> String -> IO ()
588 | "$libdir" `isPrefixOf` d = return ()
589 -- can't check this, because we don't know what $libdir is
591 there <- doesDirectoryExist d
593 (dieOrForce force (d ++ " doesn't exist or isn't a directory\n"))
595 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
596 checkDep db_stack force pkgid
597 | real_version && pkgid `elem` pkgids = return ()
598 | not real_version && pkgName pkgid `elem` pkg_names = return ()
599 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
600 ++ " doesn't exist\n")
602 -- for backwards compat, we treat 0.0 as a special version,
603 -- and don't check that it actually exists.
604 real_version = versionBranch (pkgVersion pkgid) /= []
606 all_pkgs = concat (map snd db_stack)
607 pkgids = map package all_pkgs
608 pkg_names = map pkgName pkgids
610 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
611 checkHSLib dirs auto_ghci_libs force lib = do
612 let batch_lib_file = "lib" ++ lib ++ ".a"
613 bs <- mapM (doesLibExistIn batch_lib_file) dirs
614 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
615 [] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
617 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
619 doesLibExistIn :: String -> String -> IO Bool
621 | "$libdir" `isPrefixOf` d = return True
622 | otherwise = doesFileExist (d ++ '/':lib)
624 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
625 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
626 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
628 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
629 case [dir | (exists,dir) <- zip bs dirs, exists] of
630 [] -> hPutStrLn stderr ("warning: can't find GHCi lib `" ++ ghci_lib_file ++ "'")
633 ghci_lib_file = lib ++ ".o"
635 -- automatically build the GHCi version of a batch lib,
636 -- using ld --whole-archive.
638 autoBuildGHCiLib :: String -> String -> String -> IO ()
639 autoBuildGHCiLib dir batch_file ghci_file = do
640 let ghci_lib_file = dir ++ '/':ghci_file
641 batch_lib_file = dir ++ '/':batch_file
642 hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
643 #ifdef darwin_TARGET_OS
644 system("ld -r -x -o " ++ ghci_lib_file ++
645 " -all_load " ++ batch_lib_file)
647 #ifdef mingw32_HOST_OS
648 execDir <- getExecDir "/bin/ghc-pkg.exe"
649 system (maybe "" (++"/gcc-lib/") execDir++"ld -r -x -o " ++ ghci_lib_file ++
650 " --whole-archive " ++ batch_lib_file)
652 system("ld -r -x -o " ++ ghci_lib_file ++
653 " --whole-archive " ++ batch_lib_file)
656 hPutStrLn stderr (" done.")
658 -- -----------------------------------------------------------------------------
659 -- Updating the DB with the new package.
662 :: [InstalledPackageInfo]
663 -> InstalledPackageInfo
664 -> IO [InstalledPackageInfo]
665 updatePackageDB pkgs new_pkg = do
667 is_exposed = exposed new_pkg
668 pkgid = package new_pkg
671 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
673 -- When update is on, and we're exposing the new package,
674 -- we hide any packages with the same name (different versions)
675 -- in the current DB. Earlier checks will have failed if
678 | is_exposed && pkgName (package p) == name = p{ exposed = False }
681 return (pkgs'++[new_pkg])
683 -- -----------------------------------------------------------------------------
684 -- The old command-line syntax, supported for backwards compatibility
691 | OF_Add Bool {- True => replace existing info -}
692 | OF_Remove String | OF_Show String
693 | OF_Field String | OF_AutoGHCiLibs | OF_Force
694 | OF_DefinedName String String
695 | OF_GlobalConfig FilePath
698 isAction :: OldFlag -> Bool
699 isAction OF_Config{} = False
700 isAction OF_Field{} = False
701 isAction OF_Input{} = False
702 isAction OF_AutoGHCiLibs{} = False
703 isAction OF_Force{} = False
704 isAction OF_DefinedName{} = False
705 isAction OF_GlobalConfig{} = False
708 oldFlags :: [OptDescr OldFlag]
710 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
711 "use the specified package config file",
712 Option ['l'] ["list-packages"] (NoArg OF_List)
713 "list packages in all config files",
714 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
715 "list packages in the specified config file",
716 Option ['a'] ["add-package"] (NoArg (OF_Add False))
718 Option ['u'] ["update-package"] (NoArg (OF_Add True))
719 "update package with new configuration",
720 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
721 "read new package info from specified file",
722 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
723 "show the configuration for package NAME",
724 Option [] ["field"] (ReqArg OF_Field "FIELD")
725 "(with --show-package) Show field FIELD only",
726 Option [] ["force"] (NoArg OF_Force)
727 "ignore missing directories/libraries",
728 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
729 "remove an installed package",
730 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
731 "automatically build libs for GHCi (with -a)",
732 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
733 "define NAME as VALUE",
734 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
735 "location of the global package config"
739 case break (=='=') str of
740 (nm,[]) -> OF_DefinedName nm []
741 (nm,_:val) -> OF_DefinedName nm val
743 oldRunit :: [OldFlag] -> IO ()
745 let config_flags = [ f | Just f <- map conv clis ]
747 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
748 conv (OF_Config f) = Just (FlagConfig f)
751 db_names <- getPkgDatabases config_flags
752 db_stack <- mapM readParseDatabase db_names
754 let fields = [ f | OF_Field f <- clis ]
756 let auto_ghci_libs = any isAuto clis
757 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
758 input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
760 force = OF_Force `elem` clis
762 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
764 case [ c | c <- clis, isAction c ] of
765 [ OF_List ] -> listPackages db_stack
766 [ OF_ListLocal ] -> listPackages db_stack
767 [ OF_Add upd ] -> registerPackage input_file defines db_stack
768 auto_ghci_libs upd force
769 [ OF_Remove p ] -> unregisterPackage db_stack (pkgNameToId p)
771 | null fields -> describePackage db_stack (pkgNameToId p)
772 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
773 _ -> do prog <- getProgramName
774 die (usageInfo (usageHeader prog) flags)
776 -- ---------------------------------------------------------------------------
778 expandEnvVars :: PackageConfig -> [(String, String)]
779 -> Bool -> IO PackageConfig
780 expandEnvVars pkg defines force = do
781 -- permit _all_ strings to contain ${..} environment variable references,
782 -- arguably too flexible.
783 nm <- expandString (name pkg)
784 imp_dirs <- expandStrings (import_dirs pkg)
785 src_dirs <- expandStrings (source_dirs pkg)
786 lib_dirs <- expandStrings (library_dirs pkg)
787 hs_libs <- expandStrings (hs_libraries pkg)
788 ex_libs <- expandStrings (extra_libraries pkg)
789 inc_dirs <- expandStrings (include_dirs pkg)
790 c_incs <- expandStrings (c_includes pkg)
791 p_deps <- expandStrings (package_deps pkg)
792 e_g_opts <- expandStrings (extra_ghc_opts pkg)
793 e_c_opts <- expandStrings (extra_cc_opts pkg)
794 e_l_opts <- expandStrings (extra_ld_opts pkg)
795 f_dirs <- expandStrings (framework_dirs pkg)
796 e_frames <- expandStrings (extra_frameworks pkg)
797 return (pkg { name = nm
798 , import_dirs = imp_dirs
799 , source_dirs = src_dirs
800 , library_dirs = lib_dirs
801 , hs_libraries = hs_libs
802 , extra_libraries = ex_libs
803 , include_dirs = inc_dirs
804 , c_includes = c_incs
805 , package_deps = p_deps
806 , extra_ghc_opts = e_g_opts
807 , extra_cc_opts = e_c_opts
808 , extra_ld_opts = e_l_opts
809 , framework_dirs = f_dirs
810 , extra_frameworks= e_frames
813 expandStrings :: [String] -> IO [String]
814 expandStrings = liftM concat . mapM expandSpecial
816 -- Permit substitutions for list-valued variables (but only when
817 -- they occur alone), e.g., package_deps["${deps}"] where env var
818 -- (say) 'deps' is "base,haskell98,network"
819 expandSpecial :: String -> IO [String]
821 let expand f = liftM f $ expandString str
822 in case splitString str of
823 [Var _] -> expand (wordsBy (== ','))
824 _ -> expand (\x -> [x])
826 expandString :: String -> IO String
827 expandString = liftM concat . mapM expandElem . splitString
829 expandElem :: Elem -> IO String
830 expandElem (String s) = return s
831 expandElem (Var v) = lookupEnvVar v
833 lookupEnvVar :: String -> IO String
835 case lookup nm defines of
836 Just x | not (null x) -> return x
838 catch (System.getEnv nm)
839 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
843 data Elem = String String | Var String
845 splitString :: String -> [Elem]
848 case break (== '$') str of
850 case span (/= '}') xs of
852 (if null pre then id else (String pre :)) (Var var : splitString suf)
853 _ -> [String str] -- no closing brace
854 _ -> [String str] -- no dollar/opening brace combo
856 -- wordsBy isSpace == words
857 wordsBy :: (Char -> Bool) -> String -> [String]
858 wordsBy p s = case dropWhile p s of
860 s' -> w : wordsBy p s'' where (w,s'') = break p s'
862 -----------------------------------------------------------------------------
864 getProgramName :: IO String
865 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
866 where str `withoutSuffix` suff
867 | suff `isSuffixOf` str = take (length str - length suff) str
870 bye :: String -> IO a
871 bye s = putStr s >> exitWith ExitSuccess
873 die :: String -> IO a
876 prog <- getProgramName
877 hPutStr stderr (prog ++ ": " ++ s)
878 exitWith (ExitFailure 1)
880 dieOrForce :: Bool -> String -> IO ()
882 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
883 | otherwise = die (s ++ "\n")
886 -----------------------------------------------------------------------------
887 -- Create a hierarchy of directories
889 createParents :: FilePath -> IO ()
890 createParents dir = do
891 let parent = directoryOf dir
892 b <- doesDirectoryExist parent
895 createDirectory parent
897 -----------------------------------------
898 -- Cut and pasted from ghc/compiler/SysTools
900 #if defined(mingw32_HOST_OS)
901 subst a b ls = map (\ x -> if x == a then b else x) ls
902 unDosifyPath xs = subst '\\' '/' xs
904 getExecDir :: String -> IO (Maybe String)
905 -- (getExecDir cmd) returns the directory in which the current
906 -- executable, which should be called 'cmd', is running
907 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
908 -- you'll get "/a/b/c" back as the result
910 = allocaArray len $ \buf -> do
911 ret <- getModuleFileName nullPtr buf len
912 if ret == 0 then return Nothing
913 else do s <- peekCString buf
914 return (Just (reverse (drop (length cmd)
915 (reverse (unDosifyPath s)))))
917 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
919 foreign import stdcall unsafe "GetModuleFileNameA"
920 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
922 getExecDir :: String -> IO (Maybe String)
923 getExecDir _ = return Nothing
926 -- -----------------------------------------------------------------------------
927 -- Utils from Krasimir's FilePath library, copied here for now
929 directoryOf :: FilePath -> FilePath
930 directoryOf = fst.splitFileName
932 splitFileName :: FilePath -> (String, String)
933 splitFileName p = (reverse (path2++drive), reverse fname)
935 #ifdef mingw32_TARGET_OS
936 (path,drive) = break (== ':') (reverse p)
938 (path,drive) = (reverse p,"")
940 (fname,path1) = break isPathSeparator path
941 path2 = case path1 of
943 [_] -> path1 -- don't remove the trailing slash if
944 -- there is only one character
945 (c:path) | isPathSeparator c -> path
948 joinFileName :: String -> String -> FilePath
949 joinFileName "" fname = fname
950 joinFileName "." fname = fname
951 joinFileName dir fname
952 | isPathSeparator (last dir) = dir++fname
953 | otherwise = dir++pathSeparator:fname
955 isPathSeparator :: Char -> Bool
957 #ifdef mingw32_TARGET_OS
958 ch == '/' || ch == '\\'
963 pathSeparator :: Char
964 #ifdef mingw32_TARGET_OS