1 {-# OPTIONS -fglasgow-exts #-}
2 -----------------------------------------------------------------------------
4 -- (c) The University of Glasgow 2004.
6 -- Package management tool
8 -----------------------------------------------------------------------------
12 -- - expanding of variables in new-style package conf
13 -- - version manipulation (checking whether old version exists,
14 -- hiding old version?)
16 module Main (main) where
18 import Version ( version, targetOS, targetARCH )
19 import Distribution.InstalledPackageInfo
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils ( showError, ParseResult(..) )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem ( rawSystem )
26 import Control.Exception ( evaluate )
27 import qualified Control.Exception as Exception
28 import System.FilePath ( joinFileName )
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 ( getArgs, getProgName,
50 exitWith, ExitCode(..)
53 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
55 #ifdef mingw32_TARGET_OS
58 #if __GLASGOW_HASKELL__ >= 504
59 import Foreign.C.String
65 -- -----------------------------------------------------------------------------
72 case getOpt Permute flags args of
73 (cli,_,[]) | FlagHelp `elem` cli -> do
74 prog <- getProgramName
75 bye (usageInfo (usageHeader prog) flags)
76 (cli,_,[]) | FlagVersion `elem` cli ->
80 (_,_,errors) -> tryOldCmdLine errors args
82 -- If the new command-line syntax fails, then we try the old. If that
83 -- fails too, then we output the original errors and the new syntax
84 -- (so the old syntax is still available, but hidden).
85 tryOldCmdLine :: [String] -> [String] -> IO ()
86 tryOldCmdLine errors args = do
87 case getOpt Permute oldFlags args of
91 prog <- getProgramName
92 die (concat errors ++ usageInfo (usageHeader prog) flags)
94 -- -----------------------------------------------------------------------------
95 -- Command-line syntax
102 | FlagConfig FilePath
103 | FlagGlobalConfig FilePath
108 flags :: [OptDescr Flag]
110 Option [] ["user"] (NoArg FlagUser)
111 "use the current user's package database",
112 Option [] ["global"] (NoArg FlagGlobal)
113 "(default) use the global package database",
114 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
115 "act upon specified package config file (only)",
116 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
117 "location of the global package config",
118 Option [] ["force"] (NoArg FlagForce)
119 "ignore missing dependencies, directories, and libraries",
120 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
121 "automatically build libs for GHCi (with register)",
122 Option ['?'] ["help"] (NoArg FlagHelp)
123 "display this help and exit",
124 Option ['V'] ["version"] (NoArg FlagVersion)
125 "output version information and exit"
128 ourCopyright :: String
129 ourCopyright = "GHC package manager version " ++ version ++ "\n"
131 usageHeader :: String -> String
132 usageHeader prog = substProg prog $
134 " $p register {filename | -}\n" ++
135 " Register the package using the specified installed package\n" ++
136 " description. The syntax for the latter is given in the $p\n" ++
137 " documentation.\n" ++
139 " $p update {filename | -}\n" ++
140 " Register the package, overwriting any other package with the\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" ++
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 " The following optional flags are also accepted:\n"
167 substProg :: String -> String -> String
169 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
170 substProg prog (c:xs) = c : substProg prog xs
172 -- -----------------------------------------------------------------------------
175 runit :: [Flag] -> [String] -> IO ()
176 runit cli nonopts = do
177 prog <- getProgramName
178 dbs <- getPkgDatabases cli
179 db_stack <- mapM readParseDatabase dbs
181 force = FlagForce `elem` cli
182 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
184 -- first, parse the command
186 ["register", filename] ->
187 registerPackage filename [] db_stack auto_ghci_libs False force
188 ["update", filename] ->
189 registerPackage filename [] db_stack auto_ghci_libs True force
190 ["unregister", pkgid_str] -> do
191 pkgid <- readPkgId pkgid_str
192 unregisterPackage pkgid db_stack
193 ["expose", pkgid_str] -> do
194 pkgid <- readPkgId pkgid_str
195 exposePackage pkgid db_stack
196 ["hide", pkgid_str] -> do
197 pkgid <- readPkgId pkgid_str
198 hidePackage pkgid db_stack
200 listPackages db_stack
201 ["describe", pkgid_str] -> do
202 pkgid <- readPkgId pkgid_str
203 describePackage db_stack pkgid
204 ["field", pkgid_str, field] -> do
205 pkgid <- readPkgId pkgid_str
206 describeField db_stack pkgid field
208 die ("missing command\n" ++
209 usageInfo (usageHeader prog) flags)
211 die ("command-line syntax error\n" ++
212 usageInfo (usageHeader prog) flags)
214 parseCheck :: ReadP a a -> String -> String -> IO a
215 parseCheck parser str what =
216 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
218 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
220 readPkgId :: String -> IO PackageIdentifier
221 readPkgId str = parseCheck parsePackageId str "package identifier"
223 -- -----------------------------------------------------------------------------
226 -- Some commands operate on a single database:
227 -- register, unregister, expose, hide
228 -- however these commands also check the union of the available databases
229 -- in order to check consistency. For example, register will check that
230 -- dependencies exist before registering a package.
232 -- Some commands operate on multiple databases, with overlapping semantics:
233 -- list, describe, field
235 type PackageDBName = FilePath
236 type PackageDB = [InstalledPackageInfo]
238 type PackageDBStack = [(PackageDBName,PackageDB)]
239 -- A stack of package databases. Convention: head is the topmost
240 -- in the stack. Earlier entries override later one.
242 -- The output of this function is the list of databases to act upon, with
243 -- the "topmost" overlapped database last. The commands which operate on a
244 -- single database will use the last one. Commands which operate on multiple
245 -- databases will interpret the databases as overlapping.
246 getPkgDatabases :: [Flag] -> IO [PackageDBName]
247 getPkgDatabases flags = do
248 -- first we determine the location of the global package config. On Windows,
249 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
250 -- location is passed to the binary using the --global-config flag by the
252 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
254 case [ f | FlagGlobalConfig f <- flags ] of
255 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
257 Nothing -> die err_msg
258 Just dir -> return (dir `joinFileName` "package.conf")
259 fs -> return (last fs)
261 -- get the location of the user package database, and create it if necessary
262 appdir <- getAppUserDataDirectory "ghc"
265 subdir = targetARCH ++ '-':targetOS ++ '-':version
266 archdir = appdir `joinFileName` subdir
267 user_conf = archdir `joinFileName` "package.conf"
268 b <- doesFileExist user_conf
270 putStrLn ("Creating user package database in " ++ user_conf)
271 createDirectoryIfMissing True archdir
272 writeFile user_conf emptyPackageConfig
275 databases = foldl addDB [global_conf] flags
277 -- implement the following rules:
278 -- global database is the default
279 -- --user means overlap with the user database
280 -- --global means reset to just the global database
281 -- -f <file> means overlap with <file>
282 addDB dbs FlagUser = user_conf : dbs
283 addDB dbs FlagGlobal = [global_conf]
284 addDB dbs (FlagConfig f) = f : dbs
289 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
290 readParseDatabase filename = do
291 str <- readFile filename
292 let packages = read str
294 `Exception.catch` \_ ->
295 die (filename ++ ": parse error in package config file")
296 return (filename,packages)
298 emptyPackageConfig :: String
299 emptyPackageConfig = "[]"
301 -- -----------------------------------------------------------------------------
304 registerPackage :: FilePath
305 -> [(String,String)] -- defines, ToDo: maybe remove?
307 -> Bool -- auto_ghci_libs
311 registerPackage input defines db_stack auto_ghci_libs update force = do
313 db_to_operate_on = head db_stack
314 db_filename = fst db_to_operate_on
316 checkConfigAccess db_filename
321 putStr "Reading package info from stdin... "
324 putStr ("Reading package info from " ++ show f ++ " ")
327 pkg <- parsePackageInfo s defines force
330 validatePackageConfig pkg db_stack auto_ghci_libs update force
331 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
332 savePackageConfig db_filename
333 maybeRestoreOldConfig db_filename $
334 writeNewConfig db_filename new_details
340 -> IO InstalledPackageInfo
341 parsePackageInfo str defines force =
342 case parseInstalledPackageInfo str of
343 ParseOk ok -> return ok
344 ParseFailed err -> die (showError err)
346 -- Used for converting versionless package names to new
347 -- PackageIdentifiers. "Version [] []" is special: it means "no
348 -- version" or "any version"
349 pkgNameToId :: String -> PackageIdentifier
350 pkgNameToId name = PackageIdentifier name (Version [] [])
352 -- -----------------------------------------------------------------------------
353 -- Exposing, Hiding, Unregistering are all similar
355 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
356 exposePackage = modifyPackage (\p -> [p{exposed=True}])
358 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
359 hidePackage = modifyPackage (\p -> [p{exposed=False}])
361 unregisterPackage :: PackageIdentifier -> PackageDBStack -> IO ()
362 unregisterPackage = modifyPackage (\p -> [])
365 :: (InstalledPackageInfo -> [InstalledPackageInfo])
369 modifyPackage _ _ [] = error "modifyPackage"
370 modifyPackage fn pkgid ((db_name, pkgs) : _) = do
371 checkConfigAccess db_name
372 p <- findPackage [(db_name,pkgs)] pkgid
374 savePackageConfig db_name
375 let new_config = concat (map modify pkgs)
377 | package pkg == pid = fn pkg
379 maybeRestoreOldConfig db_name $
380 writeNewConfig db_name new_config
382 -- -----------------------------------------------------------------------------
385 listPackages :: PackageDBStack -> IO ()
386 listPackages db_confs = do
387 mapM_ show_pkgconf (reverse db_confs)
388 where show_pkgconf (db_name,pkg_confs) =
389 hPutStrLn stdout (render $
390 text (db_name ++ ":") $$ nest 4 packages
392 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
395 | otherwise = parens doc
396 where doc = text (showPackageId (package p))
398 -- -----------------------------------------------------------------------------
401 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
402 describePackage db_stack pkgid = do
403 p <- findPackage db_stack pkgid
404 putStrLn (showInstalledPackageInfo p)
406 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
407 findPackage db_stack pkgid
408 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
409 [] -> die ("cannot find package " ++ showPackageId pkgid)
411 ps -> die ("package " ++ showPackageId pkgid ++
412 " matches multiple packages: " ++
413 concat (intersperse ", " (
414 map (showPackageId.package) ps)))
416 all_pkgs = concat (map snd db_stack)
418 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
421 not (realVersion pid) && pkgName pid == pkgName (package p)
423 -- -----------------------------------------------------------------------------
426 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
427 describeField db_stack pkgid field = do
428 case toField field of
429 Nothing -> die ("unknown field: " ++ field)
431 p <- findPackage db_stack pkgid
434 toField :: String -> Maybe (InstalledPackageInfo -> String)
435 -- backwards compatibility:
436 toField "import_dirs" = Just $ strList . importDirs
437 toField "source_dirs" = Just $ strList . importDirs
438 toField "library_dirs" = Just $ strList . libraryDirs
439 toField "hs_libraries" = Just $ strList . hsLibraries
440 toField "extra_libraries" = Just $ strList . extraLibraries
441 toField "include_dirs" = Just $ strList . includeDirs
442 toField "c_includes" = Just $ strList . includes
443 toField "package_deps" = Just $ strList . map showPackageId. depends
444 toField "extra_cc_opts" = Just $ strList . extraCcOpts
445 toField "extra_ld_opts" = Just $ strList . extraLdOpts
446 toField "framework_dirs" = Just $ strList . frameworkDirs
447 toField "extra_frameworks"= Just $ strList . extraFrameworks
448 toField s = showInstalledPackageInfoField s
450 strList :: [String] -> String
453 -- -----------------------------------------------------------------------------
454 -- Manipulating package.conf files
456 checkConfigAccess :: FilePath -> IO ()
457 checkConfigAccess filename = do
458 access <- getPermissions filename
459 when (not (writable access))
460 (die (filename ++ ": you don't have permission to modify this file"))
462 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
463 maybeRestoreOldConfig filename io
464 = io `catch` \e -> do
465 hPutStrLn stderr (show e)
466 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
467 "configuration was being written. Attempting to \n"++
468 "restore the old configuration... ")
469 renameFile (filename ++ ".old") filename
470 hPutStrLn stdout "done."
473 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
474 writeNewConfig filename packages = do
475 hPutStr stdout "Writing new package config file... "
476 h <- openFile filename WriteMode
477 hPutStrLn h (show packages)
479 hPutStrLn stdout "done."
481 savePackageConfig :: FilePath -> IO ()
482 savePackageConfig filename = do
483 hPutStr stdout "Saving old package config file... "
484 -- mv rather than cp because we've already done an hGetContents
485 -- on this file so we won't be able to open it for writing
486 -- unless we move the old one out of the way...
487 let oldFile = filename ++ ".old"
488 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
489 when doesExist (removeFile oldFile `catch` (const $ return ()))
490 catch (renameFile filename oldFile)
492 hPutStrLn stderr (unwords [ "Unable to rename "
498 hPutStrLn stdout "done."
500 -----------------------------------------------------------------------------
501 -- Sanity-check a new package config, and automatically build GHCi libs
504 validatePackageConfig :: InstalledPackageInfo
506 -> Bool -- auto-ghc-libs
510 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
511 checkDuplicates db_stack pkg update
512 mapM_ (checkDep db_stack force) (depends pkg)
513 mapM_ (checkDir force) (importDirs pkg)
514 mapM_ (checkDir force) (libraryDirs pkg)
515 mapM_ (checkDir force) (includeDirs pkg)
516 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
517 -- ToDo: check these somehow?
518 -- extra_libraries :: [String],
519 -- c_includes :: [String],
522 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
523 checkDuplicates db_stack pkg update = do
527 (_top_db_name, pkgs) : _ = db_stack
529 pkgs_with_same_name =
530 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
531 exposed_pkgs_with_same_name =
532 filter exposed pkgs_with_same_name
534 -- Check whether this package id already exists in this DB
536 when (not update && (package pkg `elem` map package pkgs)) $
537 die ("package " ++ showPackageId pkgid ++ " is already installed")
539 -- if we are exposing this new package, then check that
540 -- there are no other exposed packages with the same name.
542 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
543 die ("trying to register " ++ showPackageId pkgid
544 ++ " as exposed, but "
545 ++ showPackageId (package (head exposed_pkgs_with_same_name))
546 ++ " is also exposed.")
549 checkDir :: Bool -> String -> IO ()
551 | "$topdir" `isPrefixOf` d = return ()
552 -- can't check this, because we don't know what $topdir is
554 there <- doesDirectoryExist d
556 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
558 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
559 checkDep db_stack force pkgid
560 | real_version && pkgid `elem` pkgids = return ()
561 | not real_version && pkgName pkgid `elem` pkg_names = return ()
562 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
565 -- for backwards compat, we treat 0.0 as a special version,
566 -- and don't check that it actually exists.
567 real_version = realVersion pkgid
569 all_pkgs = concat (map snd db_stack)
570 pkgids = map package all_pkgs
571 pkg_names = map pkgName pkgids
573 realVersion :: PackageIdentifier -> Bool
574 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
576 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
577 checkHSLib dirs auto_ghci_libs force lib = do
578 let batch_lib_file = "lib" ++ lib ++ ".a"
579 bs <- mapM (doesLibExistIn batch_lib_file) dirs
580 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
581 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
583 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
585 doesLibExistIn :: String -> String -> IO Bool
587 | "$topdir" `isPrefixOf` d = return True
588 | otherwise = doesFileExist (d ++ '/':lib)
590 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
591 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
592 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
594 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
595 case [dir | (exists,dir) <- zip bs dirs, exists] of
596 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
599 ghci_lib_file = lib ++ ".o"
601 -- automatically build the GHCi version of a batch lib,
602 -- using ld --whole-archive.
604 autoBuildGHCiLib :: String -> String -> String -> IO ()
605 autoBuildGHCiLib dir batch_file ghci_file = do
606 let ghci_lib_file = dir ++ '/':ghci_file
607 batch_lib_file = dir ++ '/':batch_file
608 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
609 #if defined(darwin_TARGET_OS)
610 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
611 #elif defined(mingw32_HOST_OS)
612 execDir <- getExecDir "/bin/ghc-pkg.exe"
613 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
615 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
617 when (r /= ExitSuccess) $ exitWith r
618 hPutStrLn stderr (" done.")
620 -- -----------------------------------------------------------------------------
621 -- Updating the DB with the new package.
625 -> [InstalledPackageInfo]
626 -> InstalledPackageInfo
627 -> IO [InstalledPackageInfo]
628 updatePackageDB db_stack pkgs new_pkg = do
630 -- we update dependencies without version numbers to
631 -- match the actual versions of the relevant packages instaled.
632 updateDeps p = p{depends = map resolveDep (depends p)}
635 | realVersion pkgid = pkgid
636 | otherwise = lookupDep (pkgName pkgid)
639 = head [ pid | p <- concat (map snd db_stack),
641 pkgName pid == name ]
643 is_exposed = exposed new_pkg
644 pkgid = package new_pkg
647 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
649 -- When update is on, and we're exposing the new package,
650 -- we hide any packages with the same name (different versions)
651 -- in the current DB. Earlier checks will have failed if
654 | is_exposed && pkgName (package p) == name = p{ exposed = False }
657 return (pkgs'++[updateDeps new_pkg])
659 -- -----------------------------------------------------------------------------
660 -- Searching for modules
664 findModules :: [FilePath] -> IO [String]
666 mms <- mapM searchDir paths
669 searchDir path prefix = do
670 fs <- getDirectoryEntries path `catch` \_ -> return []
671 searchEntries path prefix fs
673 searchEntries path prefix [] = return []
674 searchEntries path prefix (f:fs)
675 | looks_like_a_module = do
676 ms <- searchEntries path prefix fs
677 return (prefix `joinModule` f : ms)
678 | looks_like_a_component = do
679 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
680 ms' <- searchEntries path prefix fs
683 searchEntries path prefix fs
686 (base,suffix) = splitFileExt f
687 looks_like_a_module =
688 suffix `elem` haskell_suffixes &&
689 all okInModuleName base
690 looks_like_a_component =
691 null suffix && all okInModuleName base
697 -- -----------------------------------------------------------------------------
698 -- The old command-line syntax, supported for backwards compatibility
705 | OF_Add Bool {- True => replace existing info -}
706 | OF_Remove String | OF_Show String
707 | OF_Field String | OF_AutoGHCiLibs | OF_Force
708 | OF_DefinedName String String
709 | OF_GlobalConfig FilePath
712 isAction :: OldFlag -> Bool
713 isAction OF_Config{} = False
714 isAction OF_Field{} = False
715 isAction OF_Input{} = False
716 isAction OF_AutoGHCiLibs{} = False
717 isAction OF_Force{} = False
718 isAction OF_DefinedName{} = False
719 isAction OF_GlobalConfig{} = False
722 oldFlags :: [OptDescr OldFlag]
724 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
725 "use the specified package config file",
726 Option ['l'] ["list-packages"] (NoArg OF_List)
727 "list packages in all config files",
728 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
729 "list packages in the specified config file",
730 Option ['a'] ["add-package"] (NoArg (OF_Add False))
732 Option ['u'] ["update-package"] (NoArg (OF_Add True))
733 "update package with new configuration",
734 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
735 "read new package info from specified file",
736 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
737 "show the configuration for package NAME",
738 Option [] ["field"] (ReqArg OF_Field "FIELD")
739 "(with --show-package) Show field FIELD only",
740 Option [] ["force"] (NoArg OF_Force)
741 "ignore missing directories/libraries",
742 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
743 "remove an installed package",
744 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
745 "automatically build libs for GHCi (with -a)",
746 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
747 "define NAME as VALUE",
748 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
749 "location of the global package config"
753 case break (=='=') str of
754 (nm,[]) -> OF_DefinedName nm []
755 (nm,_:val) -> OF_DefinedName nm val
757 oldRunit :: [OldFlag] -> IO ()
759 let config_flags = [ f | Just f <- map conv clis ]
761 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
762 conv (OF_Config f) = Just (FlagConfig f)
765 db_names <- getPkgDatabases config_flags
766 db_stack <- mapM readParseDatabase db_names
768 let fields = [ f | OF_Field f <- clis ]
770 let auto_ghci_libs = any isAuto clis
771 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
772 input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
774 force = OF_Force `elem` clis
776 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
778 case [ c | c <- clis, isAction c ] of
779 [ OF_List ] -> listPackages db_stack
780 [ OF_ListLocal ] -> listPackages db_stack
781 [ OF_Add upd ] -> registerPackage input_file defines db_stack
782 auto_ghci_libs upd force
783 [ OF_Remove p ] -> unregisterPackage (pkgNameToId p) db_stack
785 | null fields -> describePackage db_stack (pkgNameToId p)
786 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
787 _ -> do prog <- getProgramName
788 die (usageInfo (usageHeader prog) flags)
790 -- ---------------------------------------------------------------------------
794 expandEnvVars :: PackageConfig -> [(String, String)]
795 -> Bool -> IO PackageConfig
796 expandEnvVars pkg defines force = do
797 -- permit _all_ strings to contain ${..} environment variable references,
798 -- arguably too flexible.
799 nm <- expandString (name pkg)
800 imp_dirs <- expandStrings (import_dirs pkg)
801 src_dirs <- expandStrings (source_dirs pkg)
802 lib_dirs <- expandStrings (library_dirs pkg)
803 hs_libs <- expandStrings (hs_libraries pkg)
804 ex_libs <- expandStrings (extra_libraries pkg)
805 inc_dirs <- expandStrings (include_dirs pkg)
806 c_incs <- expandStrings (c_includes pkg)
807 p_deps <- expandStrings (package_deps pkg)
808 e_g_opts <- expandStrings (extra_ghc_opts pkg)
809 e_c_opts <- expandStrings (extra_cc_opts pkg)
810 e_l_opts <- expandStrings (extra_ld_opts pkg)
811 f_dirs <- expandStrings (framework_dirs pkg)
812 e_frames <- expandStrings (extra_frameworks pkg)
813 return (pkg { name = nm
814 , import_dirs = imp_dirs
815 , source_dirs = src_dirs
816 , library_dirs = lib_dirs
817 , hs_libraries = hs_libs
818 , extra_libraries = ex_libs
819 , include_dirs = inc_dirs
820 , c_includes = c_incs
821 , package_deps = p_deps
822 , extra_ghc_opts = e_g_opts
823 , extra_cc_opts = e_c_opts
824 , extra_ld_opts = e_l_opts
825 , framework_dirs = f_dirs
826 , extra_frameworks= e_frames
829 expandStrings :: [String] -> IO [String]
830 expandStrings = liftM concat . mapM expandSpecial
832 -- Permit substitutions for list-valued variables (but only when
833 -- they occur alone), e.g., package_deps["${deps}"] where env var
834 -- (say) 'deps' is "base,haskell98,network"
835 expandSpecial :: String -> IO [String]
837 let expand f = liftM f $ expandString str
838 in case splitString str of
839 [Var _] -> expand (wordsBy (== ','))
840 _ -> expand (\x -> [x])
842 expandString :: String -> IO String
843 expandString = liftM concat . mapM expandElem . splitString
845 expandElem :: Elem -> IO String
846 expandElem (String s) = return s
847 expandElem (Var v) = lookupEnvVar v
849 lookupEnvVar :: String -> IO String
851 case lookup nm defines of
852 Just x | not (null x) -> return x
854 catch (System.getEnv nm)
855 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
859 data Elem = String String | Var String
861 splitString :: String -> [Elem]
864 case break (== '$') str of
866 case span (/= '}') xs of
868 (if null pre then id else (String pre :)) (Var var : splitString suf)
869 _ -> [String str] -- no closing brace
870 _ -> [String str] -- no dollar/opening brace combo
872 -- wordsBy isSpace == words
873 wordsBy :: (Char -> Bool) -> String -> [String]
874 wordsBy p s = case dropWhile p s of
876 s' -> w : wordsBy p s'' where (w,s'') = break p s'
879 -----------------------------------------------------------------------------
881 getProgramName :: IO String
882 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
883 where str `withoutSuffix` suff
884 | suff `isSuffixOf` str = take (length str - length suff) str
887 bye :: String -> IO a
888 bye s = putStr s >> exitWith ExitSuccess
890 die :: String -> IO a
893 prog <- getProgramName
894 hPutStrLn stderr (prog ++ ": " ++ s)
895 exitWith (ExitFailure 1)
897 dieOrForce :: Bool -> String -> IO ()
899 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
903 -----------------------------------------
904 -- Cut and pasted from ghc/compiler/SysTools
906 #if defined(mingw32_TARGET_OS)
907 subst a b ls = map (\ x -> if x == a then b else x) ls
908 unDosifyPath xs = subst '\\' '/' xs
910 getExecDir :: String -> IO (Maybe String)
911 -- (getExecDir cmd) returns the directory in which the current
912 -- executable, which should be called 'cmd', is running
913 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
914 -- you'll get "/a/b/c" back as the result
916 = allocaArray len $ \buf -> do
917 ret <- getModuleFileName nullPtr buf len
918 if ret == 0 then return Nothing
919 else do s <- peekCString buf
920 return (Just (reverse (drop (length cmd)
921 (reverse (unDosifyPath s)))))
923 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
925 foreign import stdcall unsafe "GetModuleFileNameA"
926 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
928 getExecDir :: String -> IO (Maybe String)
929 getExecDir _ = return Nothing