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 )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem ( rawSystem )
29 #include "../../includes/ghcconfig.h"
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
38 import qualified Exception
41 import Data.Char ( isSpace )
44 import System ( getArgs, getProgName,
45 exitWith, ExitCode(..)
48 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
50 #ifdef mingw32_HOST_OS
53 #if __GLASGOW_HASKELL__ >= 504
54 import Foreign.C.String
60 -- -----------------------------------------------------------------------------
67 case getOpt Permute flags args of
68 (cli,_,[]) | FlagHelp `elem` cli -> do
69 prog <- getProgramName
70 bye (usageInfo (usageHeader prog) flags)
71 (cli,_,[]) | FlagVersion `elem` cli ->
75 (_,_,errors) -> tryOldCmdLine errors args
77 -- If the new command-line syntax fails, then we try the old. If that
78 -- fails too, then we output the original errors and the new syntax
79 -- (so the old syntax is still available, but hidden).
80 tryOldCmdLine :: [String] -> [String] -> IO ()
81 tryOldCmdLine errors args = do
82 case getOpt Permute oldFlags args of
86 prog <- getProgramName
87 die (concat errors ++ usageInfo (usageHeader prog) flags)
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
98 | FlagGlobalConfig FilePath
103 flags :: [OptDescr Flag]
105 Option [] ["user"] (NoArg FlagUser)
106 "use the current user's package database",
107 Option [] ["global"] (NoArg FlagGlobal)
108 "(default) use the global package database",
109 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
110 "act upon specified package config file (only)",
111 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
112 "location of the global package config",
113 Option [] ["force"] (NoArg FlagForce)
114 "ignore missing dependencies, directories, and libraries",
115 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
116 "automatically build libs for GHCi (with register)",
117 Option ['?'] ["help"] (NoArg FlagHelp)
118 "display this help and exit",
119 Option ['V'] ["version"] (NoArg FlagVersion)
120 "output version information and exit"
123 ourCopyright :: String
124 ourCopyright = "GHC package manager version " ++ version ++ "\n"
126 usageHeader :: String -> String
127 usageHeader prog = substProg prog $
129 " $p register {filename | -}\n" ++
130 " Register the package using the specified installed package\n" ++
131 " description. The syntax for the latter is given in the $p\n" ++
132 " documentation.\n" ++
134 " $p update {filename | -}\n" ++
135 " Register the package, overwriting any other package with the\n" ++
138 " $p unregister {pkg-id}\n" ++
139 " Unregister the specified package.\n" ++
141 " $p expose {pkg-id}\n" ++
142 " Expose the specified package.\n" ++
144 " $p hide {pkg-id}\n" ++
145 " Hide the specified package.\n" ++
148 " List registered packages in the global database, and also the" ++
149 " user database if --user is given.\n" ++
151 " $p describe {pkg-id}\n" ++
152 " Give the registered description for the specified package. The\n" ++
153 " description is returned in precisely the syntax required by $p\n" ++
156 " $p field {pkg-id} {field}\n" ++
157 " Extract the specified field of the package description for the\n" ++
158 " specified package.\n" ++
160 " The following optional flags are also accepted:\n"
162 substProg :: String -> String -> String
164 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
165 substProg prog (c:xs) = c : substProg prog xs
167 -- -----------------------------------------------------------------------------
170 runit :: [Flag] -> [String] -> IO ()
171 runit cli nonopts = do
172 prog <- getProgramName
174 force = FlagForce `elem` cli
175 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
177 -- first, parse the command
179 ["register", filename] ->
180 registerPackage filename [] cli auto_ghci_libs False force
181 ["update", filename] ->
182 registerPackage filename [] cli auto_ghci_libs True force
183 ["unregister", pkgid_str] -> do
184 pkgid <- readGlobPkgId pkgid_str
185 unregisterPackage pkgid cli
186 ["expose", pkgid_str] -> do
187 pkgid <- readGlobPkgId pkgid_str
188 exposePackage pkgid cli
189 ["hide", pkgid_str] -> do
190 pkgid <- readGlobPkgId pkgid_str
191 hidePackage pkgid cli
194 ["describe", pkgid_str] -> do
195 pkgid <- readGlobPkgId pkgid_str
196 describePackage cli pkgid
197 ["field", pkgid_str, field] -> do
198 pkgid <- readGlobPkgId pkgid_str
199 describeField cli pkgid field
201 die ("missing command\n" ++
202 usageInfo (usageHeader prog) flags)
204 die ("command-line syntax error\n" ++
205 usageInfo (usageHeader prog) flags)
207 parseCheck :: ReadP a a -> String -> String -> IO a
208 parseCheck parser str what =
209 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
211 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
213 readPkgId :: String -> IO PackageIdentifier
214 readPkgId str = parseCheck parsePackageId str "package identifier"
216 readGlobPkgId :: String -> IO PackageIdentifier
217 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
219 parseGlobPackageId :: ReadP r PackageIdentifier
223 (do n <- parsePackageName; string "-*"
224 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
226 -- globVersion means "all versions"
227 globVersion :: Version
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 user_exists <- doesFileExist user_conf
274 -- The semantics here are slightly strange. If we are
275 -- *modifying* the database, then the default is to modify
276 -- the global database by default, unless you say --user.
277 -- If we are not modifying (eg. list, describe etc.) then
278 -- the user database is included by default.
280 | modify = foldl addDB [global_conf] flags
281 | not user_exists = foldl addDB [global_conf] flags
282 | otherwise = foldl addDB [user_conf,global_conf] flags
284 -- implement the following rules:
285 -- --user means overlap with the user database
286 -- --global means reset to just the global database
287 -- -f <file> means overlap with <file>
289 | user_conf `elem` dbs = dbs
290 | modify || user_exists = user_conf : dbs
291 addDB dbs FlagGlobal = [global_conf]
292 addDB dbs (FlagConfig f) = f : dbs
295 -- we create the user database iff (a) we're modifying, and (b) the
296 -- user asked to use it by giving the --user flag.
297 when (not user_exists && user_conf `elem` databases) $ do
298 putStrLn ("Creating user package database in " ++ user_conf)
299 createDirectoryIfMissing True archdir
300 writeFile user_conf emptyPackageConfig
302 db_stack <- mapM readParseDatabase databases
305 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
306 readParseDatabase filename = do
307 str <- readFile filename
308 let packages = read str
309 Exception.evaluate packages
310 `Exception.catch` \_ ->
311 die (filename ++ ": parse error in package config file")
312 return (filename,packages)
314 emptyPackageConfig :: String
315 emptyPackageConfig = "[]"
317 -- -----------------------------------------------------------------------------
320 registerPackage :: FilePath
321 -> [(String,String)] -- defines, ToDo: maybe remove?
323 -> Bool -- auto_ghci_libs
327 registerPackage input defines flags auto_ghci_libs update force = do
328 db_stack <- getPkgDatabases True flags
330 db_to_operate_on = my_head "db" db_stack
331 db_filename = fst db_to_operate_on
333 checkConfigAccess db_filename
338 putStr "Reading package info from stdin... "
341 putStr ("Reading package info from " ++ show f ++ " ")
344 pkg <- parsePackageInfo s defines force
347 validatePackageConfig pkg db_stack auto_ghci_libs update force
348 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
349 savePackageConfig db_filename
350 maybeRestoreOldConfig db_filename $
351 writeNewConfig db_filename new_details
357 -> IO InstalledPackageInfo
358 parsePackageInfo str defines force =
359 case parseInstalledPackageInfo str of
360 ParseOk ok -> return ok
361 ParseFailed err -> die (showError err)
363 -- -----------------------------------------------------------------------------
364 -- Exposing, Hiding, Unregistering are all similar
366 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
367 exposePackage = modifyPackage (\p -> [p{exposed=True}])
369 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
370 hidePackage = modifyPackage (\p -> [p{exposed=False}])
372 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
373 unregisterPackage = modifyPackage (\p -> [])
376 :: (InstalledPackageInfo -> [InstalledPackageInfo])
380 modifyPackage fn pkgid flags = do
381 db_stack <- getPkgDatabases True{-modify-} flags
382 let ((db_name, pkgs) : _) = db_stack
383 checkConfigAccess db_name
384 ps <- findPackages [(db_name,pkgs)] pkgid
385 let pids = map package ps
386 savePackageConfig db_name
387 let new_config = concat (map modify pkgs)
389 | package pkg `elem` pids = fn pkg
391 maybeRestoreOldConfig db_name $
392 writeNewConfig db_name new_config
394 -- -----------------------------------------------------------------------------
397 listPackages :: [Flag] -> IO ()
398 listPackages flags = do
399 db_stack <- getPkgDatabases False flags
400 mapM_ show_pkgconf (reverse db_stack)
401 where show_pkgconf (db_name,pkg_confs) =
402 hPutStrLn stdout (render $
403 text (db_name ++ ":") $$ nest 4 packages
405 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
408 | otherwise = parens doc
409 where doc = text (showPackageId (package p))
411 -- -----------------------------------------------------------------------------
414 describePackage :: [Flag] -> PackageIdentifier -> IO ()
415 describePackage flags pkgid = do
416 db_stack <- getPkgDatabases False flags
417 ps <- findPackages db_stack pkgid
418 mapM_ (putStrLn . showInstalledPackageInfo) ps
420 -- PackageId is can have globVersion for the version
421 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
422 findPackages db_stack pkgid
423 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
424 [] -> die ("cannot find package " ++ showPackageId pkgid)
426 -- if the version is globVersion, then we are allowed to match
427 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
428 -- but "Cabal" matches just one Cabal package - if there are more,
430 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
433 -> die ("package " ++ showPackageId pkgid ++
434 " matches multiple packages: " ++
435 concat (intersperse ", " (
436 map (showPackageId.package) ps)))
439 = (pkgName pid == pkgName p)
440 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
441 where p = package pkg
443 all_pkgs = concat (map snd db_stack)
445 -- -----------------------------------------------------------------------------
448 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
449 describeField flags pkgid field = do
450 db_stack <- getPkgDatabases False flags
451 case toField field of
452 Nothing -> die ("unknown field: " ++ field)
454 ps <- findPackages db_stack pkgid
455 mapM_ (putStrLn.fn) ps
457 toField :: String -> Maybe (InstalledPackageInfo -> String)
458 -- backwards compatibility:
459 toField "import_dirs" = Just $ strList . importDirs
460 toField "source_dirs" = Just $ strList . importDirs
461 toField "library_dirs" = Just $ strList . libraryDirs
462 toField "hs_libraries" = Just $ strList . hsLibraries
463 toField "extra_libraries" = Just $ strList . extraLibraries
464 toField "include_dirs" = Just $ strList . includeDirs
465 toField "c_includes" = Just $ strList . includes
466 toField "package_deps" = Just $ strList . map showPackageId. depends
467 toField "extra_cc_opts" = Just $ strList . ccOptions
468 toField "extra_ld_opts" = Just $ strList . ldOptions
469 toField "framework_dirs" = Just $ strList . frameworkDirs
470 toField "extra_frameworks"= Just $ strList . frameworks
471 toField s = showInstalledPackageInfoField s
473 strList :: [String] -> String
476 -- -----------------------------------------------------------------------------
477 -- Manipulating package.conf files
479 checkConfigAccess :: FilePath -> IO ()
480 checkConfigAccess filename = do
481 access <- getPermissions filename
482 when (not (writable access))
483 (die (filename ++ ": you don't have permission to modify this file"))
485 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
486 maybeRestoreOldConfig filename io
487 = io `catch` \e -> do
488 hPutStrLn stderr (show e)
489 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
490 "configuration was being written. Attempting to \n"++
491 "restore the old configuration... ")
492 renameFile (filename ++ ".old") filename
493 hPutStrLn stdout "done."
496 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
497 writeNewConfig filename packages = do
498 hPutStr stdout "Writing new package config file... "
499 h <- openFile filename WriteMode
500 hPutStrLn h (show packages)
502 hPutStrLn stdout "done."
504 savePackageConfig :: FilePath -> IO ()
505 savePackageConfig filename = do
506 hPutStr stdout "Saving old package config file... "
507 -- mv rather than cp because we've already done an hGetContents
508 -- on this file so we won't be able to open it for writing
509 -- unless we move the old one out of the way...
510 let oldFile = filename ++ ".old"
511 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
512 when doesExist (removeFile oldFile `catch` (const $ return ()))
513 catch (renameFile filename oldFile)
515 hPutStrLn stderr (unwords [ "Unable to rename "
521 hPutStrLn stdout "done."
523 -----------------------------------------------------------------------------
524 -- Sanity-check a new package config, and automatically build GHCi libs
527 validatePackageConfig :: InstalledPackageInfo
529 -> Bool -- auto-ghc-libs
533 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
535 checkDuplicates db_stack pkg update
536 mapM_ (checkDep db_stack force) (depends pkg)
537 mapM_ (checkDir force) (importDirs pkg)
538 mapM_ (checkDir force) (libraryDirs pkg)
539 mapM_ (checkDir force) (includeDirs pkg)
540 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
541 -- ToDo: check these somehow?
542 -- extra_libraries :: [String],
543 -- c_includes :: [String],
545 -- When the package name and version are put together, sometimes we can
546 -- end up with a package id that cannot be parsed. This will lead to
547 -- difficulties when the user wants to refer to the package later, so
548 -- we check that the package id can be parsed properly here.
549 checkPackageId :: InstalledPackageInfo -> IO ()
551 let str = showPackageId (package ipi) in
552 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
554 [] -> die ("invalid package identifier: " ++ str)
555 _ -> die ("ambiguous package identifier: " ++ str)
557 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
558 checkDuplicates db_stack pkg update = do
562 (_top_db_name, pkgs) : _ = db_stack
564 pkgs_with_same_name =
565 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
566 exposed_pkgs_with_same_name =
567 filter exposed pkgs_with_same_name
569 -- Check whether this package id already exists in this DB
571 when (not update && (package pkg `elem` map package pkgs)) $
572 die ("package " ++ showPackageId pkgid ++ " is already installed")
574 -- if we are exposing this new package, then check that
575 -- there are no other exposed packages with the same name.
577 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
578 die ("trying to register " ++ showPackageId pkgid
579 ++ " as exposed, but "
580 ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
581 ++ " is also exposed.")
584 checkDir :: Bool -> String -> IO ()
586 | "$topdir" `isPrefixOf` d = return ()
587 -- can't check this, because we don't know what $topdir is
589 there <- doesDirectoryExist d
591 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
593 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
594 checkDep db_stack force pkgid
595 | real_version && pkgid `elem` pkgids = return ()
596 | not real_version && pkgName pkgid `elem` pkg_names = return ()
597 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
600 -- for backwards compat, we treat 0.0 as a special version,
601 -- and don't check that it actually exists.
602 real_version = realVersion pkgid
604 all_pkgs = concat (map snd db_stack)
605 pkgids = map package all_pkgs
606 pkg_names = map pkgName pkgids
608 realVersion :: PackageIdentifier -> Bool
609 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
611 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
612 checkHSLib dirs auto_ghci_libs force lib = do
613 let batch_lib_file = "lib" ++ lib ++ ".a"
614 bs <- mapM (doesLibExistIn batch_lib_file) dirs
615 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
616 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
618 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
620 doesLibExistIn :: String -> String -> IO Bool
622 | "$topdir" `isPrefixOf` d = return True
623 | otherwise = doesFileExist (d ++ '/':lib)
625 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
626 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
627 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
629 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
630 case [dir | (exists,dir) <- zip bs dirs, exists] of
631 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
634 ghci_lib_file = lib ++ ".o"
636 -- automatically build the GHCi version of a batch lib,
637 -- using ld --whole-archive.
639 autoBuildGHCiLib :: String -> String -> String -> IO ()
640 autoBuildGHCiLib dir batch_file ghci_file = do
641 let ghci_lib_file = dir ++ '/':ghci_file
642 batch_lib_file = dir ++ '/':batch_file
643 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
644 #if defined(darwin_HOST_OS)
645 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
646 #elif defined(mingw32_HOST_OS)
647 execDir <- getExecDir "/bin/ghc-pkg.exe"
648 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
650 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
652 when (r /= ExitSuccess) $ exitWith r
653 hPutStrLn stderr (" done.")
655 -- -----------------------------------------------------------------------------
656 -- Updating the DB with the new package.
660 -> [InstalledPackageInfo]
661 -> InstalledPackageInfo
662 -> IO [InstalledPackageInfo]
663 updatePackageDB db_stack pkgs new_pkg = do
665 -- The input package spec is allowed to give a package dependency
666 -- without a version number; e.g.
668 -- Here, we update these dependencies without version numbers to
669 -- match the actual versions of the relevant packages installed.
670 updateDeps p = p{depends = map resolveDep (depends p)}
673 | realVersion dep_pkgid = dep_pkgid
674 | otherwise = lookupDep dep_pkgid
678 name = pkgName dep_pkgid
680 case [ pid | p <- concat (map snd db_stack),
682 pkgName pid == name ] of
683 (pid:_) -> pid -- Found installed package,
684 -- replete with its version
685 [] -> dep_pkgid -- No installed package; use
686 -- the version-less one
688 is_exposed = exposed new_pkg
689 pkgid = package new_pkg
692 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
694 -- When update is on, and we're exposing the new package,
695 -- we hide any packages with the same name (different versions)
696 -- in the current DB. Earlier checks will have failed if
699 | is_exposed && pkgName (package p) == name = p{ exposed = False }
702 return (pkgs'++[updateDeps new_pkg])
704 -- -----------------------------------------------------------------------------
705 -- Searching for modules
709 findModules :: [FilePath] -> IO [String]
711 mms <- mapM searchDir paths
714 searchDir path prefix = do
715 fs <- getDirectoryEntries path `catch` \_ -> return []
716 searchEntries path prefix fs
718 searchEntries path prefix [] = return []
719 searchEntries path prefix (f:fs)
720 | looks_like_a_module = do
721 ms <- searchEntries path prefix fs
722 return (prefix `joinModule` f : ms)
723 | looks_like_a_component = do
724 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
725 ms' <- searchEntries path prefix fs
728 searchEntries path prefix fs
731 (base,suffix) = splitFileExt f
732 looks_like_a_module =
733 suffix `elem` haskell_suffixes &&
734 all okInModuleName base
735 looks_like_a_component =
736 null suffix && all okInModuleName base
742 -- -----------------------------------------------------------------------------
743 -- The old command-line syntax, supported for backwards compatibility
750 | OF_Add Bool {- True => replace existing info -}
751 | OF_Remove String | OF_Show String
752 | OF_Field String | OF_AutoGHCiLibs | OF_Force
753 | OF_DefinedName String String
754 | OF_GlobalConfig FilePath
757 isAction :: OldFlag -> Bool
758 isAction OF_Config{} = False
759 isAction OF_Field{} = False
760 isAction OF_Input{} = False
761 isAction OF_AutoGHCiLibs{} = False
762 isAction OF_Force{} = False
763 isAction OF_DefinedName{} = False
764 isAction OF_GlobalConfig{} = False
767 oldFlags :: [OptDescr OldFlag]
769 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
770 "use the specified package config file",
771 Option ['l'] ["list-packages"] (NoArg OF_List)
772 "list packages in all config files",
773 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
774 "list packages in the specified config file",
775 Option ['a'] ["add-package"] (NoArg (OF_Add False))
777 Option ['u'] ["update-package"] (NoArg (OF_Add True))
778 "update package with new configuration",
779 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
780 "read new package info from specified file",
781 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
782 "show the configuration for package NAME",
783 Option [] ["field"] (ReqArg OF_Field "FIELD")
784 "(with --show-package) Show field FIELD only",
785 Option [] ["force"] (NoArg OF_Force)
786 "ignore missing directories/libraries",
787 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
788 "remove an installed package",
789 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
790 "automatically build libs for GHCi (with -a)",
791 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
792 "define NAME as VALUE",
793 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
794 "location of the global package config"
798 case break (=='=') str of
799 (nm,[]) -> OF_DefinedName nm []
800 (nm,_:val) -> OF_DefinedName nm val
802 oldRunit :: [OldFlag] -> IO ()
804 let new_flags = [ f | Just f <- map conv clis ]
806 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
807 conv (OF_Config f) = Just (FlagConfig f)
812 let fields = [ f | OF_Field f <- clis ]
814 let auto_ghci_libs = any isAuto clis
815 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
816 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
818 force = OF_Force `elem` clis
820 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
822 case [ c | c <- clis, isAction c ] of
823 [ OF_List ] -> listPackages new_flags
824 [ OF_ListLocal ] -> listPackages new_flags
826 registerPackage input_file defines new_flags auto_ghci_libs upd force
827 [ OF_Remove pkgid_str ] -> do
828 pkgid <- readPkgId pkgid_str
829 unregisterPackage pkgid new_flags
830 [ OF_Show pkgid_str ]
832 pkgid <- readPkgId pkgid_str
833 describePackage new_flags pkgid
835 pkgid <- readPkgId pkgid_str
836 mapM_ (describeField new_flags pkgid) fields
838 prog <- getProgramName
839 die (usageInfo (usageHeader prog) flags)
841 my_head :: String -> [a] -> a
842 my_head s [] = error s
845 -- ---------------------------------------------------------------------------
849 expandEnvVars :: PackageConfig -> [(String, String)]
850 -> Bool -> IO PackageConfig
851 expandEnvVars pkg defines force = do
852 -- permit _all_ strings to contain ${..} environment variable references,
853 -- arguably too flexible.
854 nm <- expandString (name pkg)
855 imp_dirs <- expandStrings (import_dirs pkg)
856 src_dirs <- expandStrings (source_dirs pkg)
857 lib_dirs <- expandStrings (library_dirs pkg)
858 hs_libs <- expandStrings (hs_libraries pkg)
859 ex_libs <- expandStrings (extra_libraries pkg)
860 inc_dirs <- expandStrings (include_dirs pkg)
861 c_incs <- expandStrings (c_includes pkg)
862 p_deps <- expandStrings (package_deps pkg)
863 e_g_opts <- expandStrings (extra_ghc_opts pkg)
864 e_c_opts <- expandStrings (extra_cc_opts pkg)
865 e_l_opts <- expandStrings (extra_ld_opts pkg)
866 f_dirs <- expandStrings (framework_dirs pkg)
867 e_frames <- expandStrings (extra_frameworks pkg)
868 return (pkg { name = nm
869 , import_dirs = imp_dirs
870 , source_dirs = src_dirs
871 , library_dirs = lib_dirs
872 , hs_libraries = hs_libs
873 , extra_libraries = ex_libs
874 , include_dirs = inc_dirs
875 , c_includes = c_incs
876 , package_deps = p_deps
877 , extra_ghc_opts = e_g_opts
878 , extra_cc_opts = e_c_opts
879 , extra_ld_opts = e_l_opts
880 , framework_dirs = f_dirs
881 , extra_frameworks= e_frames
884 expandStrings :: [String] -> IO [String]
885 expandStrings = liftM concat . mapM expandSpecial
887 -- Permit substitutions for list-valued variables (but only when
888 -- they occur alone), e.g., package_deps["${deps}"] where env var
889 -- (say) 'deps' is "base,haskell98,network"
890 expandSpecial :: String -> IO [String]
892 let expand f = liftM f $ expandString str
893 in case splitString str of
894 [Var _] -> expand (wordsBy (== ','))
895 _ -> expand (\x -> [x])
897 expandString :: String -> IO String
898 expandString = liftM concat . mapM expandElem . splitString
900 expandElem :: Elem -> IO String
901 expandElem (String s) = return s
902 expandElem (Var v) = lookupEnvVar v
904 lookupEnvVar :: String -> IO String
906 case lookup nm defines of
907 Just x | not (null x) -> return x
909 catch (System.getEnv nm)
910 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
914 data Elem = String String | Var String
916 splitString :: String -> [Elem]
919 case break (== '$') str of
921 case span (/= '}') xs of
923 (if null pre then id else (String pre :)) (Var var : splitString suf)
924 _ -> [String str] -- no closing brace
925 _ -> [String str] -- no dollar/opening brace combo
927 -- wordsBy isSpace == words
928 wordsBy :: (Char -> Bool) -> String -> [String]
929 wordsBy p s = case dropWhile p s of
931 s' -> w : wordsBy p s'' where (w,s'') = break p s'
934 -----------------------------------------------------------------------------
936 getProgramName :: IO String
937 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
938 where str `withoutSuffix` suff
939 | suff `isSuffixOf` str = take (length str - length suff) str
942 bye :: String -> IO a
943 bye s = putStr s >> exitWith ExitSuccess
945 die :: String -> IO a
948 prog <- getProgramName
949 hPutStrLn stderr (prog ++ ": " ++ s)
950 exitWith (ExitFailure 1)
952 dieOrForce :: Bool -> String -> IO ()
954 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
958 -----------------------------------------
959 -- Cut and pasted from ghc/compiler/SysTools
961 #if defined(mingw32_HOST_OS)
962 subst a b ls = map (\ x -> if x == a then b else x) ls
963 unDosifyPath xs = subst '\\' '/' xs
965 getExecDir :: String -> IO (Maybe String)
966 -- (getExecDir cmd) returns the directory in which the current
967 -- executable, which should be called 'cmd', is running
968 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
969 -- you'll get "/a/b/c" back as the result
971 = allocaArray len $ \buf -> do
972 ret <- getModuleFileName nullPtr buf len
973 if ret == 0 then return Nothing
974 else do s <- peekCString buf
975 return (Just (reverse (drop (length cmd)
976 (reverse (unDosifyPath s)))))
978 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
980 foreign import stdcall unsafe "GetModuleFileNameA"
981 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
983 getExecDir :: String -> IO (Maybe String)
984 getExecDir _ = return Nothing
987 -- -----------------------------------------------------------------------------
990 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
991 -- It joins directory and file names to form a complete file path.
993 -- The general rule is:
995 -- > dir `joinFileName` basename == path
997 -- > (dir,basename) = splitFileName path
999 -- There might be an exceptions to the rule but in any case the
1000 -- reconstructed path will refer to the same object (file or directory).
1001 -- An example exception is that on Windows some slashes might be converted
1003 joinFileName :: String -> String -> FilePath
1004 joinFileName "" fname = fname
1005 joinFileName "." fname = fname
1006 joinFileName dir "" = dir
1007 joinFileName dir fname
1008 | isPathSeparator (last dir) = dir++fname
1009 | otherwise = dir++pathSeparator:fname
1011 -- | Checks whether the character is a valid path separator for the host
1012 -- platform. The valid character is a 'pathSeparator' but since the Windows
1013 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1014 -- checks for it on this platform, too.
1015 isPathSeparator :: Char -> Bool
1016 isPathSeparator ch = ch == pathSeparator || ch == '/'
1018 -- | Provides a platform-specific character used to separate directory levels in
1019 -- a path string that reflects a hierarchical file system organization. The
1020 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1021 -- (@\"\\\"@) on the Windows operating system.
1022 pathSeparator :: Char
1023 #ifdef mingw32_HOST_OS
1024 pathSeparator = '\\'