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 )
30 #include "../../includes/ghcconfig.h"
32 #if __GLASGOW_HASKELL__ >= 504
33 import System.Console.GetOpt
34 import Text.PrettyPrint
35 import qualified Control.Exception as Exception
39 import qualified Exception
42 import Data.Char ( isSpace )
45 import System ( getArgs, getProgName,
46 exitWith, ExitCode(..)
49 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
51 #ifdef mingw32_HOST_OS
54 #if __GLASGOW_HASKELL__ >= 504
55 import Foreign.C.String
61 -- -----------------------------------------------------------------------------
68 case getOpt Permute flags args of
69 (cli,_,[]) | FlagHelp `elem` cli -> do
70 prog <- getProgramName
71 bye (usageInfo (usageHeader prog) flags)
72 (cli,_,[]) | FlagVersion `elem` cli ->
76 (_,_,errors) -> tryOldCmdLine errors args
78 -- If the new command-line syntax fails, then we try the old. If that
79 -- fails too, then we output the original errors and the new syntax
80 -- (so the old syntax is still available, but hidden).
81 tryOldCmdLine :: [String] -> [String] -> IO ()
82 tryOldCmdLine errors args = do
83 case getOpt Permute oldFlags args of
87 prog <- getProgramName
88 die (concat errors ++ usageInfo (usageHeader prog) flags)
90 -- -----------------------------------------------------------------------------
91 -- Command-line syntax
99 | FlagGlobalConfig FilePath
104 flags :: [OptDescr Flag]
106 Option [] ["user"] (NoArg FlagUser)
107 "use the current user's package database",
108 Option [] ["global"] (NoArg FlagGlobal)
109 "(default) use the global package database",
110 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
111 "act upon specified package config file (only)",
112 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
113 "location of the global package config",
114 Option [] ["force"] (NoArg FlagForce)
115 "ignore missing dependencies, directories, and libraries",
116 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
117 "automatically build libs for GHCi (with register)",
118 Option ['?'] ["help"] (NoArg FlagHelp)
119 "display this help and exit",
120 Option ['V'] ["version"] (NoArg FlagVersion)
121 "output version information and exit"
124 ourCopyright :: String
125 ourCopyright = "GHC package manager version " ++ version ++ "\n"
127 usageHeader :: String -> String
128 usageHeader prog = substProg prog $
130 " $p register {filename | -}\n" ++
131 " Register the package using the specified installed package\n" ++
132 " description. The syntax for the latter is given in the $p\n" ++
133 " documentation.\n" ++
135 " $p update {filename | -}\n" ++
136 " Register the package, overwriting any other package with the\n" ++
139 " $p unregister {pkg-id}\n" ++
140 " Unregister the specified package.\n" ++
142 " $p expose {pkg-id}\n" ++
143 " Expose the specified package.\n" ++
145 " $p hide {pkg-id}\n" ++
146 " Hide the specified package.\n" ++
149 " List registered packages in the global database, and also the" ++
150 " user database if --user is given.\n" ++
152 " $p describe {pkg-id}\n" ++
153 " Give the registered description for the specified package. The\n" ++
154 " description is returned in precisely the syntax required by $p\n" ++
157 " $p field {pkg-id} {field}\n" ++
158 " Extract the specified field of the package description for the\n" ++
159 " specified package.\n" ++
161 " The following optional flags are also accepted:\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
175 force = FlagForce `elem` cli
176 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
178 -- first, parse the command
180 ["register", filename] ->
181 registerPackage filename [] cli auto_ghci_libs False force
182 ["update", filename] ->
183 registerPackage filename [] cli auto_ghci_libs True force
184 ["unregister", pkgid_str] -> do
185 pkgid <- readGlobPkgId pkgid_str
186 unregisterPackage pkgid cli
187 ["expose", pkgid_str] -> do
188 pkgid <- readGlobPkgId pkgid_str
189 exposePackage pkgid cli
190 ["hide", pkgid_str] -> do
191 pkgid <- readGlobPkgId pkgid_str
192 hidePackage pkgid cli
195 ["describe", pkgid_str] -> do
196 pkgid <- readGlobPkgId pkgid_str
197 describePackage cli pkgid
198 ["field", pkgid_str, field] -> do
199 pkgid <- readGlobPkgId pkgid_str
200 describeField cli pkgid field
202 die ("missing command\n" ++
203 usageInfo (usageHeader prog) flags)
205 die ("command-line syntax error\n" ++
206 usageInfo (usageHeader prog) flags)
208 parseCheck :: ReadP a a -> String -> String -> IO a
209 parseCheck parser str what =
210 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
212 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
214 readPkgId :: String -> IO PackageIdentifier
215 readPkgId str = parseCheck parsePackageId str "package identifier"
217 readGlobPkgId :: String -> IO PackageIdentifier
218 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
220 parseGlobPackageId :: ReadP r PackageIdentifier
224 (do n <- parsePackageName; string "-*"
225 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
227 -- globVersion means "all versions"
228 globVersion = Version{ versionBranch=[], versionTags=["*"] }
230 -- -----------------------------------------------------------------------------
233 -- Some commands operate on a single database:
234 -- register, unregister, expose, hide
235 -- however these commands also check the union of the available databases
236 -- in order to check consistency. For example, register will check that
237 -- dependencies exist before registering a package.
239 -- Some commands operate on multiple databases, with overlapping semantics:
240 -- list, describe, field
242 type PackageDBName = FilePath
243 type PackageDB = [InstalledPackageInfo]
245 type PackageDBStack = [(PackageDBName,PackageDB)]
246 -- A stack of package databases. Convention: head is the topmost
247 -- in the stack. Earlier entries override later one.
249 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
250 getPkgDatabases modify flags = do
251 -- first we determine the location of the global package config. On Windows,
252 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
253 -- location is passed to the binary using the --global-config flag by the
255 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
257 case [ f | FlagGlobalConfig f <- flags ] of
258 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
260 Nothing -> die err_msg
261 Just dir -> return (dir `joinFileName` "package.conf")
262 fs -> return (last fs)
264 -- get the location of the user package database, and create it if necessary
265 appdir <- getAppUserDataDirectory "ghc"
268 subdir = targetARCH ++ '-':targetOS ++ '-':version
269 archdir = appdir `joinFileName` subdir
270 user_conf = archdir `joinFileName` "package.conf"
271 b <- doesFileExist user_conf
273 putStrLn ("Creating user package database in " ++ user_conf)
274 createDirectoryIfMissing True archdir
275 writeFile user_conf emptyPackageConfig
278 -- The semantics here are slightly strange. If we are
279 -- *modifying* the database, then the default is to modify
280 -- the global database by default, unless you say --user.
281 -- If we are not modifying (eg. list, describe etc.) then
282 -- the user database is included by default.
284 | modify = foldl addDB [global_conf] flags
285 | not modify = foldl addDB [user_conf,global_conf] flags
287 -- implement the following rules:
288 -- --user means overlap with the user database
289 -- --global means reset to just the global database
290 -- -f <file> means overlap with <file>
291 addDB dbs FlagUser = if user_conf `elem` dbs
294 addDB dbs FlagGlobal = [global_conf]
295 addDB dbs (FlagConfig f) = f : dbs
298 db_stack <- mapM readParseDatabase databases
301 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
302 readParseDatabase filename = do
303 str <- readFile filename
304 let packages = read str
306 `Exception.catch` \_ ->
307 die (filename ++ ": parse error in package config file")
308 return (filename,packages)
310 emptyPackageConfig :: String
311 emptyPackageConfig = "[]"
313 -- -----------------------------------------------------------------------------
316 registerPackage :: FilePath
317 -> [(String,String)] -- defines, ToDo: maybe remove?
319 -> Bool -- auto_ghci_libs
323 registerPackage input defines flags auto_ghci_libs update force = do
324 db_stack <- getPkgDatabases True flags
326 db_to_operate_on = my_head "db" db_stack
327 db_filename = fst db_to_operate_on
329 checkConfigAccess db_filename
334 putStr "Reading package info from stdin... "
337 putStr ("Reading package info from " ++ show f ++ " ")
340 pkg <- parsePackageInfo s defines force
343 validatePackageConfig pkg db_stack auto_ghci_libs update force
344 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
345 savePackageConfig db_filename
346 maybeRestoreOldConfig db_filename $
347 writeNewConfig db_filename new_details
353 -> IO InstalledPackageInfo
354 parsePackageInfo str defines force =
355 case parseInstalledPackageInfo str of
356 ParseOk ok -> return ok
357 ParseFailed err -> die (showError err)
359 -- -----------------------------------------------------------------------------
360 -- Exposing, Hiding, Unregistering are all similar
362 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
363 exposePackage = modifyPackage (\p -> [p{exposed=True}])
365 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
366 hidePackage = modifyPackage (\p -> [p{exposed=False}])
368 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
369 unregisterPackage = modifyPackage (\p -> [])
372 :: (InstalledPackageInfo -> [InstalledPackageInfo])
376 modifyPackage fn pkgid flags = do
377 db_stack <- getPkgDatabases True{-modify-} flags
378 let ((db_name, pkgs) : _) = db_stack
379 checkConfigAccess db_name
380 ps <- findPackages [(db_name,pkgs)] pkgid
381 let pids = map package ps
382 savePackageConfig db_name
383 let new_config = concat (map modify pkgs)
385 | package pkg `elem` pids = fn pkg
387 maybeRestoreOldConfig db_name $
388 writeNewConfig db_name new_config
390 -- -----------------------------------------------------------------------------
393 listPackages :: [Flag] -> IO ()
394 listPackages flags = do
395 db_stack <- getPkgDatabases False flags
396 mapM_ show_pkgconf (reverse db_stack)
397 where show_pkgconf (db_name,pkg_confs) =
398 hPutStrLn stdout (render $
399 text (db_name ++ ":") $$ nest 4 packages
401 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
404 | otherwise = parens doc
405 where doc = text (showPackageId (package p))
407 -- -----------------------------------------------------------------------------
410 describePackage :: [Flag] -> PackageIdentifier -> IO ()
411 describePackage flags pkgid = do
412 db_stack <- getPkgDatabases False flags
413 ps <- findPackages db_stack pkgid
414 mapM_ (putStrLn . showInstalledPackageInfo) ps
416 -- PackageId is can have globVersion for the version
417 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
418 findPackages db_stack pkgid
419 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
420 [] -> die ("cannot find package " ++ showPackageId pkgid)
422 -- if the version is globVersion, then we are allowed to match
423 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
424 -- but "Cabal" matches just one Cabal package - if there are more,
426 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
429 -> die ("package " ++ showPackageId pkgid ++
430 " matches multiple packages: " ++
431 concat (intersperse ", " (
432 map (showPackageId.package) ps)))
435 = (pkgName pid == pkgName p)
436 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
437 where p = package pkg
439 all_pkgs = concat (map snd db_stack)
441 -- -----------------------------------------------------------------------------
444 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
445 describeField flags pkgid field = do
446 db_stack <- getPkgDatabases False flags
447 case toField field of
448 Nothing -> die ("unknown field: " ++ field)
450 ps <- findPackages db_stack pkgid
451 mapM_ (putStrLn.fn) ps
453 toField :: String -> Maybe (InstalledPackageInfo -> String)
454 -- backwards compatibility:
455 toField "import_dirs" = Just $ strList . importDirs
456 toField "source_dirs" = Just $ strList . importDirs
457 toField "library_dirs" = Just $ strList . libraryDirs
458 toField "hs_libraries" = Just $ strList . hsLibraries
459 toField "extra_libraries" = Just $ strList . extraLibraries
460 toField "include_dirs" = Just $ strList . includeDirs
461 toField "c_includes" = Just $ strList . includes
462 toField "package_deps" = Just $ strList . map showPackageId. depends
463 toField "extra_cc_opts" = Just $ strList . ccOptions
464 toField "extra_ld_opts" = Just $ strList . ldOptions
465 toField "framework_dirs" = Just $ strList . frameworkDirs
466 toField "extra_frameworks"= Just $ strList . frameworks
467 toField s = showInstalledPackageInfoField s
469 strList :: [String] -> String
472 -- -----------------------------------------------------------------------------
473 -- Manipulating package.conf files
475 checkConfigAccess :: FilePath -> IO ()
476 checkConfigAccess filename = do
477 access <- getPermissions filename
478 when (not (writable access))
479 (die (filename ++ ": you don't have permission to modify this file"))
481 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
482 maybeRestoreOldConfig filename io
483 = io `catch` \e -> do
484 hPutStrLn stderr (show e)
485 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
486 "configuration was being written. Attempting to \n"++
487 "restore the old configuration... ")
488 renameFile (filename ++ ".old") filename
489 hPutStrLn stdout "done."
492 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
493 writeNewConfig filename packages = do
494 hPutStr stdout "Writing new package config file... "
495 h <- openFile filename WriteMode
496 hPutStrLn h (show packages)
498 hPutStrLn stdout "done."
500 savePackageConfig :: FilePath -> IO ()
501 savePackageConfig filename = do
502 hPutStr stdout "Saving old package config file... "
503 -- mv rather than cp because we've already done an hGetContents
504 -- on this file so we won't be able to open it for writing
505 -- unless we move the old one out of the way...
506 let oldFile = filename ++ ".old"
507 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
508 when doesExist (removeFile oldFile `catch` (const $ return ()))
509 catch (renameFile filename oldFile)
511 hPutStrLn stderr (unwords [ "Unable to rename "
517 hPutStrLn stdout "done."
519 -----------------------------------------------------------------------------
520 -- Sanity-check a new package config, and automatically build GHCi libs
523 validatePackageConfig :: InstalledPackageInfo
525 -> Bool -- auto-ghc-libs
529 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
531 checkDuplicates db_stack pkg update
532 mapM_ (checkDep db_stack force) (depends pkg)
533 mapM_ (checkDir force) (importDirs pkg)
534 mapM_ (checkDir force) (libraryDirs pkg)
535 mapM_ (checkDir force) (includeDirs pkg)
536 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
537 -- ToDo: check these somehow?
538 -- extra_libraries :: [String],
539 -- c_includes :: [String],
541 -- When the package name and version are put together, sometimes we can
542 -- end up with a package id that cannot be parsed. This will lead to
543 -- difficulties when the user wants to refer to the package later, so
544 -- we check that the package id can be parsed properly here.
545 checkPackageId :: InstalledPackageInfo -> IO ()
547 let str = showPackageId (package ipi) in
548 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
550 [] -> die ("invalid package identifier: " ++ str)
551 _ -> die ("ambiguous package identifier: " ++ str)
553 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
554 checkDuplicates db_stack pkg update = do
558 (_top_db_name, pkgs) : _ = db_stack
560 pkgs_with_same_name =
561 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
562 exposed_pkgs_with_same_name =
563 filter exposed pkgs_with_same_name
565 -- Check whether this package id already exists in this DB
567 when (not update && (package pkg `elem` map package pkgs)) $
568 die ("package " ++ showPackageId pkgid ++ " is already installed")
570 -- if we are exposing this new package, then check that
571 -- there are no other exposed packages with the same name.
573 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
574 die ("trying to register " ++ showPackageId pkgid
575 ++ " as exposed, but "
576 ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
577 ++ " is also exposed.")
580 checkDir :: Bool -> String -> IO ()
582 | "$topdir" `isPrefixOf` d = return ()
583 -- can't check this, because we don't know what $topdir is
585 there <- doesDirectoryExist d
587 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
589 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
590 checkDep db_stack force pkgid
591 | real_version && pkgid `elem` pkgids = return ()
592 | not real_version && pkgName pkgid `elem` pkg_names = return ()
593 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
596 -- for backwards compat, we treat 0.0 as a special version,
597 -- and don't check that it actually exists.
598 real_version = realVersion pkgid
600 all_pkgs = concat (map snd db_stack)
601 pkgids = map package all_pkgs
602 pkg_names = map pkgName pkgids
604 realVersion :: PackageIdentifier -> Bool
605 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
607 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
608 checkHSLib dirs auto_ghci_libs force lib = do
609 let batch_lib_file = "lib" ++ lib ++ ".a"
610 bs <- mapM (doesLibExistIn batch_lib_file) dirs
611 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
612 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
614 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
616 doesLibExistIn :: String -> String -> IO Bool
618 | "$topdir" `isPrefixOf` d = return True
619 | otherwise = doesFileExist (d ++ '/':lib)
621 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
622 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
623 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
625 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
626 case [dir | (exists,dir) <- zip bs dirs, exists] of
627 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
630 ghci_lib_file = lib ++ ".o"
632 -- automatically build the GHCi version of a batch lib,
633 -- using ld --whole-archive.
635 autoBuildGHCiLib :: String -> String -> String -> IO ()
636 autoBuildGHCiLib dir batch_file ghci_file = do
637 let ghci_lib_file = dir ++ '/':ghci_file
638 batch_lib_file = dir ++ '/':batch_file
639 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
640 #if defined(darwin_HOST_OS)
641 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
642 #elif defined(mingw32_HOST_OS)
643 execDir <- getExecDir "/bin/ghc-pkg.exe"
644 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
646 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
648 when (r /= ExitSuccess) $ exitWith r
649 hPutStrLn stderr (" done.")
651 -- -----------------------------------------------------------------------------
652 -- Updating the DB with the new package.
656 -> [InstalledPackageInfo]
657 -> InstalledPackageInfo
658 -> IO [InstalledPackageInfo]
659 updatePackageDB db_stack pkgs new_pkg = do
661 -- The input package spec is allowed to give a package dependency
662 -- without a version number; e.g.
664 -- Here, we update these dependencies without version numbers to
665 -- match the actual versions of the relevant packages installed.
666 updateDeps p = p{depends = map resolveDep (depends p)}
669 | realVersion dep_pkgid = dep_pkgid
670 | otherwise = lookupDep dep_pkgid
674 name = pkgName dep_pkgid
676 case [ pid | p <- concat (map snd db_stack),
678 pkgName pid == name ] of
679 (pid:_) -> pid -- Found installed package,
680 -- replete with its version
681 [] -> dep_pkgid -- No installed package; use
682 -- the version-less one
684 is_exposed = exposed new_pkg
685 pkgid = package new_pkg
688 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
690 -- When update is on, and we're exposing the new package,
691 -- we hide any packages with the same name (different versions)
692 -- in the current DB. Earlier checks will have failed if
695 | is_exposed && pkgName (package p) == name = p{ exposed = False }
698 return (pkgs'++[updateDeps new_pkg])
700 -- -----------------------------------------------------------------------------
701 -- Searching for modules
705 findModules :: [FilePath] -> IO [String]
707 mms <- mapM searchDir paths
710 searchDir path prefix = do
711 fs <- getDirectoryEntries path `catch` \_ -> return []
712 searchEntries path prefix fs
714 searchEntries path prefix [] = return []
715 searchEntries path prefix (f:fs)
716 | looks_like_a_module = do
717 ms <- searchEntries path prefix fs
718 return (prefix `joinModule` f : ms)
719 | looks_like_a_component = do
720 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
721 ms' <- searchEntries path prefix fs
724 searchEntries path prefix fs
727 (base,suffix) = splitFileExt f
728 looks_like_a_module =
729 suffix `elem` haskell_suffixes &&
730 all okInModuleName base
731 looks_like_a_component =
732 null suffix && all okInModuleName base
738 -- -----------------------------------------------------------------------------
739 -- The old command-line syntax, supported for backwards compatibility
746 | OF_Add Bool {- True => replace existing info -}
747 | OF_Remove String | OF_Show String
748 | OF_Field String | OF_AutoGHCiLibs | OF_Force
749 | OF_DefinedName String String
750 | OF_GlobalConfig FilePath
753 isAction :: OldFlag -> Bool
754 isAction OF_Config{} = False
755 isAction OF_Field{} = False
756 isAction OF_Input{} = False
757 isAction OF_AutoGHCiLibs{} = False
758 isAction OF_Force{} = False
759 isAction OF_DefinedName{} = False
760 isAction OF_GlobalConfig{} = False
763 oldFlags :: [OptDescr OldFlag]
765 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
766 "use the specified package config file",
767 Option ['l'] ["list-packages"] (NoArg OF_List)
768 "list packages in all config files",
769 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
770 "list packages in the specified config file",
771 Option ['a'] ["add-package"] (NoArg (OF_Add False))
773 Option ['u'] ["update-package"] (NoArg (OF_Add True))
774 "update package with new configuration",
775 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
776 "read new package info from specified file",
777 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
778 "show the configuration for package NAME",
779 Option [] ["field"] (ReqArg OF_Field "FIELD")
780 "(with --show-package) Show field FIELD only",
781 Option [] ["force"] (NoArg OF_Force)
782 "ignore missing directories/libraries",
783 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
784 "remove an installed package",
785 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
786 "automatically build libs for GHCi (with -a)",
787 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
788 "define NAME as VALUE",
789 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
790 "location of the global package config"
794 case break (=='=') str of
795 (nm,[]) -> OF_DefinedName nm []
796 (nm,_:val) -> OF_DefinedName nm val
798 oldRunit :: [OldFlag] -> IO ()
800 let new_flags = [ f | Just f <- map conv clis ]
802 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
803 conv (OF_Config f) = Just (FlagConfig f)
808 let fields = [ f | OF_Field f <- clis ]
810 let auto_ghci_libs = any isAuto clis
811 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
812 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
814 force = OF_Force `elem` clis
816 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
818 case [ c | c <- clis, isAction c ] of
819 [ OF_List ] -> listPackages new_flags
820 [ OF_ListLocal ] -> listPackages new_flags
822 registerPackage input_file defines new_flags auto_ghci_libs upd force
823 [ OF_Remove pkgid_str ] -> do
824 pkgid <- readPkgId pkgid_str
825 unregisterPackage pkgid new_flags
826 [ OF_Show pkgid_str ]
828 pkgid <- readPkgId pkgid_str
829 describePackage new_flags pkgid
831 pkgid <- readPkgId pkgid_str
832 mapM_ (describeField new_flags pkgid) fields
834 prog <- getProgramName
835 die (usageInfo (usageHeader prog) flags)
837 my_head s [] = error s
840 -- ---------------------------------------------------------------------------
844 expandEnvVars :: PackageConfig -> [(String, String)]
845 -> Bool -> IO PackageConfig
846 expandEnvVars pkg defines force = do
847 -- permit _all_ strings to contain ${..} environment variable references,
848 -- arguably too flexible.
849 nm <- expandString (name pkg)
850 imp_dirs <- expandStrings (import_dirs pkg)
851 src_dirs <- expandStrings (source_dirs pkg)
852 lib_dirs <- expandStrings (library_dirs pkg)
853 hs_libs <- expandStrings (hs_libraries pkg)
854 ex_libs <- expandStrings (extra_libraries pkg)
855 inc_dirs <- expandStrings (include_dirs pkg)
856 c_incs <- expandStrings (c_includes pkg)
857 p_deps <- expandStrings (package_deps pkg)
858 e_g_opts <- expandStrings (extra_ghc_opts pkg)
859 e_c_opts <- expandStrings (extra_cc_opts pkg)
860 e_l_opts <- expandStrings (extra_ld_opts pkg)
861 f_dirs <- expandStrings (framework_dirs pkg)
862 e_frames <- expandStrings (extra_frameworks pkg)
863 return (pkg { name = nm
864 , import_dirs = imp_dirs
865 , source_dirs = src_dirs
866 , library_dirs = lib_dirs
867 , hs_libraries = hs_libs
868 , extra_libraries = ex_libs
869 , include_dirs = inc_dirs
870 , c_includes = c_incs
871 , package_deps = p_deps
872 , extra_ghc_opts = e_g_opts
873 , extra_cc_opts = e_c_opts
874 , extra_ld_opts = e_l_opts
875 , framework_dirs = f_dirs
876 , extra_frameworks= e_frames
879 expandStrings :: [String] -> IO [String]
880 expandStrings = liftM concat . mapM expandSpecial
882 -- Permit substitutions for list-valued variables (but only when
883 -- they occur alone), e.g., package_deps["${deps}"] where env var
884 -- (say) 'deps' is "base,haskell98,network"
885 expandSpecial :: String -> IO [String]
887 let expand f = liftM f $ expandString str
888 in case splitString str of
889 [Var _] -> expand (wordsBy (== ','))
890 _ -> expand (\x -> [x])
892 expandString :: String -> IO String
893 expandString = liftM concat . mapM expandElem . splitString
895 expandElem :: Elem -> IO String
896 expandElem (String s) = return s
897 expandElem (Var v) = lookupEnvVar v
899 lookupEnvVar :: String -> IO String
901 case lookup nm defines of
902 Just x | not (null x) -> return x
904 catch (System.getEnv nm)
905 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
909 data Elem = String String | Var String
911 splitString :: String -> [Elem]
914 case break (== '$') str of
916 case span (/= '}') xs of
918 (if null pre then id else (String pre :)) (Var var : splitString suf)
919 _ -> [String str] -- no closing brace
920 _ -> [String str] -- no dollar/opening brace combo
922 -- wordsBy isSpace == words
923 wordsBy :: (Char -> Bool) -> String -> [String]
924 wordsBy p s = case dropWhile p s of
926 s' -> w : wordsBy p s'' where (w,s'') = break p s'
929 -----------------------------------------------------------------------------
931 getProgramName :: IO String
932 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
933 where str `withoutSuffix` suff
934 | suff `isSuffixOf` str = take (length str - length suff) str
937 bye :: String -> IO a
938 bye s = putStr s >> exitWith ExitSuccess
940 die :: String -> IO a
943 prog <- getProgramName
944 hPutStrLn stderr (prog ++ ": " ++ s)
945 exitWith (ExitFailure 1)
947 dieOrForce :: Bool -> String -> IO ()
949 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
953 -----------------------------------------
954 -- Cut and pasted from ghc/compiler/SysTools
956 #if defined(mingw32_HOST_OS)
957 subst a b ls = map (\ x -> if x == a then b else x) ls
958 unDosifyPath xs = subst '\\' '/' xs
960 getExecDir :: String -> IO (Maybe String)
961 -- (getExecDir cmd) returns the directory in which the current
962 -- executable, which should be called 'cmd', is running
963 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
964 -- you'll get "/a/b/c" back as the result
966 = allocaArray len $ \buf -> do
967 ret <- getModuleFileName nullPtr buf len
968 if ret == 0 then return Nothing
969 else do s <- peekCString buf
970 return (Just (reverse (drop (length cmd)
971 (reverse (unDosifyPath s)))))
973 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
975 foreign import stdcall unsafe "GetModuleFileNameA"
976 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
978 getExecDir :: String -> IO (Maybe String)
979 getExecDir _ = return Nothing
982 -- -----------------------------------------------------------------------------
985 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
986 -- It joins directory and file names to form a complete file path.
988 -- The general rule is:
990 -- > dir `joinFileName` basename == path
992 -- > (dir,basename) = splitFileName path
994 -- There might be an exceptions to the rule but in any case the
995 -- reconstructed path will refer to the same object (file or directory).
996 -- An example exception is that on Windows some slashes might be converted
998 joinFileName :: String -> String -> FilePath
999 joinFileName "" fname = fname
1000 joinFileName "." fname = fname
1001 joinFileName dir "" = dir
1002 joinFileName dir fname
1003 | isPathSeparator (last dir) = dir++fname
1004 | otherwise = dir++pathSeparator:fname
1006 -- | Checks whether the character is a valid path separator for the host
1007 -- platform. The valid character is a 'pathSeparator' but since the Windows
1008 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1009 -- checks for it on this platform, too.
1010 isPathSeparator :: Char -> Bool
1011 isPathSeparator ch = ch == pathSeparator || ch == '/'
1013 -- | Provides a platform-specific character used to separate directory levels in
1014 -- a path string that reflects a hierarchical file system organization. The
1015 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1016 -- (@\"\\\"@) on the Windows operating system.
1017 pathSeparator :: Char
1018 #ifdef mingw32_HOST_OS
1019 pathSeparator = '\\'