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>
288 addDB dbs FlagUser = if user_conf `elem` dbs
291 addDB dbs FlagGlobal = [global_conf]
292 addDB dbs (FlagConfig f) = f : dbs
295 when (not user_exists && user_conf `elem` databases) $ do
296 putStrLn ("Creating user package database in " ++ user_conf)
297 createDirectoryIfMissing True archdir
298 writeFile user_conf emptyPackageConfig
300 db_stack <- mapM readParseDatabase databases
303 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
304 readParseDatabase filename = do
305 str <- readFile filename
306 let packages = read str
307 Exception.evaluate packages
308 `Exception.catch` \_ ->
309 die (filename ++ ": parse error in package config file")
310 return (filename,packages)
312 emptyPackageConfig :: String
313 emptyPackageConfig = "[]"
315 -- -----------------------------------------------------------------------------
318 registerPackage :: FilePath
319 -> [(String,String)] -- defines, ToDo: maybe remove?
321 -> Bool -- auto_ghci_libs
325 registerPackage input defines flags auto_ghci_libs update force = do
326 db_stack <- getPkgDatabases True flags
328 db_to_operate_on = my_head "db" db_stack
329 db_filename = fst db_to_operate_on
331 checkConfigAccess db_filename
336 putStr "Reading package info from stdin... "
339 putStr ("Reading package info from " ++ show f ++ " ")
342 pkg <- parsePackageInfo s defines force
345 validatePackageConfig pkg db_stack auto_ghci_libs update force
346 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
347 savePackageConfig db_filename
348 maybeRestoreOldConfig db_filename $
349 writeNewConfig db_filename new_details
355 -> IO InstalledPackageInfo
356 parsePackageInfo str defines force =
357 case parseInstalledPackageInfo str of
358 ParseOk ok -> return ok
359 ParseFailed err -> die (showError err)
361 -- -----------------------------------------------------------------------------
362 -- Exposing, Hiding, Unregistering are all similar
364 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
365 exposePackage = modifyPackage (\p -> [p{exposed=True}])
367 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
368 hidePackage = modifyPackage (\p -> [p{exposed=False}])
370 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
371 unregisterPackage = modifyPackage (\p -> [])
374 :: (InstalledPackageInfo -> [InstalledPackageInfo])
378 modifyPackage fn pkgid flags = do
379 db_stack <- getPkgDatabases True{-modify-} flags
380 let ((db_name, pkgs) : _) = db_stack
381 checkConfigAccess db_name
382 ps <- findPackages [(db_name,pkgs)] pkgid
383 let pids = map package ps
384 savePackageConfig db_name
385 let new_config = concat (map modify pkgs)
387 | package pkg `elem` pids = fn pkg
389 maybeRestoreOldConfig db_name $
390 writeNewConfig db_name new_config
392 -- -----------------------------------------------------------------------------
395 listPackages :: [Flag] -> IO ()
396 listPackages flags = do
397 db_stack <- getPkgDatabases False flags
398 mapM_ show_pkgconf (reverse db_stack)
399 where show_pkgconf (db_name,pkg_confs) =
400 hPutStrLn stdout (render $
401 text (db_name ++ ":") $$ nest 4 packages
403 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
406 | otherwise = parens doc
407 where doc = text (showPackageId (package p))
409 -- -----------------------------------------------------------------------------
412 describePackage :: [Flag] -> PackageIdentifier -> IO ()
413 describePackage flags pkgid = do
414 db_stack <- getPkgDatabases False flags
415 ps <- findPackages db_stack pkgid
416 mapM_ (putStrLn . showInstalledPackageInfo) ps
418 -- PackageId is can have globVersion for the version
419 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
420 findPackages db_stack pkgid
421 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
422 [] -> die ("cannot find package " ++ showPackageId pkgid)
424 -- if the version is globVersion, then we are allowed to match
425 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
426 -- but "Cabal" matches just one Cabal package - if there are more,
428 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
431 -> die ("package " ++ showPackageId pkgid ++
432 " matches multiple packages: " ++
433 concat (intersperse ", " (
434 map (showPackageId.package) ps)))
437 = (pkgName pid == pkgName p)
438 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
439 where p = package pkg
441 all_pkgs = concat (map snd db_stack)
443 -- -----------------------------------------------------------------------------
446 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
447 describeField flags pkgid field = do
448 db_stack <- getPkgDatabases False flags
449 case toField field of
450 Nothing -> die ("unknown field: " ++ field)
452 ps <- findPackages db_stack pkgid
453 mapM_ (putStrLn.fn) ps
455 toField :: String -> Maybe (InstalledPackageInfo -> String)
456 -- backwards compatibility:
457 toField "import_dirs" = Just $ strList . importDirs
458 toField "source_dirs" = Just $ strList . importDirs
459 toField "library_dirs" = Just $ strList . libraryDirs
460 toField "hs_libraries" = Just $ strList . hsLibraries
461 toField "extra_libraries" = Just $ strList . extraLibraries
462 toField "include_dirs" = Just $ strList . includeDirs
463 toField "c_includes" = Just $ strList . includes
464 toField "package_deps" = Just $ strList . map showPackageId. depends
465 toField "extra_cc_opts" = Just $ strList . ccOptions
466 toField "extra_ld_opts" = Just $ strList . ldOptions
467 toField "framework_dirs" = Just $ strList . frameworkDirs
468 toField "extra_frameworks"= Just $ strList . frameworks
469 toField s = showInstalledPackageInfoField s
471 strList :: [String] -> String
474 -- -----------------------------------------------------------------------------
475 -- Manipulating package.conf files
477 checkConfigAccess :: FilePath -> IO ()
478 checkConfigAccess filename = do
479 access <- getPermissions filename
480 when (not (writable access))
481 (die (filename ++ ": you don't have permission to modify this file"))
483 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
484 maybeRestoreOldConfig filename io
485 = io `catch` \e -> do
486 hPutStrLn stderr (show e)
487 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
488 "configuration was being written. Attempting to \n"++
489 "restore the old configuration... ")
490 renameFile (filename ++ ".old") filename
491 hPutStrLn stdout "done."
494 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
495 writeNewConfig filename packages = do
496 hPutStr stdout "Writing new package config file... "
497 h <- openFile filename WriteMode
498 hPutStrLn h (show packages)
500 hPutStrLn stdout "done."
502 savePackageConfig :: FilePath -> IO ()
503 savePackageConfig filename = do
504 hPutStr stdout "Saving old package config file... "
505 -- mv rather than cp because we've already done an hGetContents
506 -- on this file so we won't be able to open it for writing
507 -- unless we move the old one out of the way...
508 let oldFile = filename ++ ".old"
509 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
510 when doesExist (removeFile oldFile `catch` (const $ return ()))
511 catch (renameFile filename oldFile)
513 hPutStrLn stderr (unwords [ "Unable to rename "
519 hPutStrLn stdout "done."
521 -----------------------------------------------------------------------------
522 -- Sanity-check a new package config, and automatically build GHCi libs
525 validatePackageConfig :: InstalledPackageInfo
527 -> Bool -- auto-ghc-libs
531 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
533 checkDuplicates db_stack pkg update
534 mapM_ (checkDep db_stack force) (depends pkg)
535 mapM_ (checkDir force) (importDirs pkg)
536 mapM_ (checkDir force) (libraryDirs pkg)
537 mapM_ (checkDir force) (includeDirs pkg)
538 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
539 -- ToDo: check these somehow?
540 -- extra_libraries :: [String],
541 -- c_includes :: [String],
543 -- When the package name and version are put together, sometimes we can
544 -- end up with a package id that cannot be parsed. This will lead to
545 -- difficulties when the user wants to refer to the package later, so
546 -- we check that the package id can be parsed properly here.
547 checkPackageId :: InstalledPackageInfo -> IO ()
549 let str = showPackageId (package ipi) in
550 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
552 [] -> die ("invalid package identifier: " ++ str)
553 _ -> die ("ambiguous package identifier: " ++ str)
555 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
556 checkDuplicates db_stack pkg update = do
560 (_top_db_name, pkgs) : _ = db_stack
562 pkgs_with_same_name =
563 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
564 exposed_pkgs_with_same_name =
565 filter exposed pkgs_with_same_name
567 -- Check whether this package id already exists in this DB
569 when (not update && (package pkg `elem` map package pkgs)) $
570 die ("package " ++ showPackageId pkgid ++ " is already installed")
572 -- if we are exposing this new package, then check that
573 -- there are no other exposed packages with the same name.
575 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
576 die ("trying to register " ++ showPackageId pkgid
577 ++ " as exposed, but "
578 ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
579 ++ " is also exposed.")
582 checkDir :: Bool -> String -> IO ()
584 | "$topdir" `isPrefixOf` d = return ()
585 -- can't check this, because we don't know what $topdir is
587 there <- doesDirectoryExist d
589 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
591 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
592 checkDep db_stack force pkgid
593 | real_version && pkgid `elem` pkgids = return ()
594 | not real_version && pkgName pkgid `elem` pkg_names = return ()
595 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
598 -- for backwards compat, we treat 0.0 as a special version,
599 -- and don't check that it actually exists.
600 real_version = realVersion pkgid
602 all_pkgs = concat (map snd db_stack)
603 pkgids = map package all_pkgs
604 pkg_names = map pkgName pkgids
606 realVersion :: PackageIdentifier -> Bool
607 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
609 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
610 checkHSLib dirs auto_ghci_libs force lib = do
611 let batch_lib_file = "lib" ++ lib ++ ".a"
612 bs <- mapM (doesLibExistIn batch_lib_file) dirs
613 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
614 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
616 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
618 doesLibExistIn :: String -> String -> IO Bool
620 | "$topdir" `isPrefixOf` d = return True
621 | otherwise = doesFileExist (d ++ '/':lib)
623 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
624 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
625 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
627 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
628 case [dir | (exists,dir) <- zip bs dirs, exists] of
629 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
632 ghci_lib_file = lib ++ ".o"
634 -- automatically build the GHCi version of a batch lib,
635 -- using ld --whole-archive.
637 autoBuildGHCiLib :: String -> String -> String -> IO ()
638 autoBuildGHCiLib dir batch_file ghci_file = do
639 let ghci_lib_file = dir ++ '/':ghci_file
640 batch_lib_file = dir ++ '/':batch_file
641 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
642 #if defined(darwin_HOST_OS)
643 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
644 #elif defined(mingw32_HOST_OS)
645 execDir <- getExecDir "/bin/ghc-pkg.exe"
646 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
648 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
650 when (r /= ExitSuccess) $ exitWith r
651 hPutStrLn stderr (" done.")
653 -- -----------------------------------------------------------------------------
654 -- Updating the DB with the new package.
658 -> [InstalledPackageInfo]
659 -> InstalledPackageInfo
660 -> IO [InstalledPackageInfo]
661 updatePackageDB db_stack pkgs new_pkg = do
663 -- The input package spec is allowed to give a package dependency
664 -- without a version number; e.g.
666 -- Here, we update these dependencies without version numbers to
667 -- match the actual versions of the relevant packages installed.
668 updateDeps p = p{depends = map resolveDep (depends p)}
671 | realVersion dep_pkgid = dep_pkgid
672 | otherwise = lookupDep dep_pkgid
676 name = pkgName dep_pkgid
678 case [ pid | p <- concat (map snd db_stack),
680 pkgName pid == name ] of
681 (pid:_) -> pid -- Found installed package,
682 -- replete with its version
683 [] -> dep_pkgid -- No installed package; use
684 -- the version-less one
686 is_exposed = exposed new_pkg
687 pkgid = package new_pkg
690 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
692 -- When update is on, and we're exposing the new package,
693 -- we hide any packages with the same name (different versions)
694 -- in the current DB. Earlier checks will have failed if
697 | is_exposed && pkgName (package p) == name = p{ exposed = False }
700 return (pkgs'++[updateDeps new_pkg])
702 -- -----------------------------------------------------------------------------
703 -- Searching for modules
707 findModules :: [FilePath] -> IO [String]
709 mms <- mapM searchDir paths
712 searchDir path prefix = do
713 fs <- getDirectoryEntries path `catch` \_ -> return []
714 searchEntries path prefix fs
716 searchEntries path prefix [] = return []
717 searchEntries path prefix (f:fs)
718 | looks_like_a_module = do
719 ms <- searchEntries path prefix fs
720 return (prefix `joinModule` f : ms)
721 | looks_like_a_component = do
722 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
723 ms' <- searchEntries path prefix fs
726 searchEntries path prefix fs
729 (base,suffix) = splitFileExt f
730 looks_like_a_module =
731 suffix `elem` haskell_suffixes &&
732 all okInModuleName base
733 looks_like_a_component =
734 null suffix && all okInModuleName base
740 -- -----------------------------------------------------------------------------
741 -- The old command-line syntax, supported for backwards compatibility
748 | OF_Add Bool {- True => replace existing info -}
749 | OF_Remove String | OF_Show String
750 | OF_Field String | OF_AutoGHCiLibs | OF_Force
751 | OF_DefinedName String String
752 | OF_GlobalConfig FilePath
755 isAction :: OldFlag -> Bool
756 isAction OF_Config{} = False
757 isAction OF_Field{} = False
758 isAction OF_Input{} = False
759 isAction OF_AutoGHCiLibs{} = False
760 isAction OF_Force{} = False
761 isAction OF_DefinedName{} = False
762 isAction OF_GlobalConfig{} = False
765 oldFlags :: [OptDescr OldFlag]
767 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
768 "use the specified package config file",
769 Option ['l'] ["list-packages"] (NoArg OF_List)
770 "list packages in all config files",
771 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
772 "list packages in the specified config file",
773 Option ['a'] ["add-package"] (NoArg (OF_Add False))
775 Option ['u'] ["update-package"] (NoArg (OF_Add True))
776 "update package with new configuration",
777 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
778 "read new package info from specified file",
779 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
780 "show the configuration for package NAME",
781 Option [] ["field"] (ReqArg OF_Field "FIELD")
782 "(with --show-package) Show field FIELD only",
783 Option [] ["force"] (NoArg OF_Force)
784 "ignore missing directories/libraries",
785 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
786 "remove an installed package",
787 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
788 "automatically build libs for GHCi (with -a)",
789 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
790 "define NAME as VALUE",
791 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
792 "location of the global package config"
796 case break (=='=') str of
797 (nm,[]) -> OF_DefinedName nm []
798 (nm,_:val) -> OF_DefinedName nm val
800 oldRunit :: [OldFlag] -> IO ()
802 let new_flags = [ f | Just f <- map conv clis ]
804 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
805 conv (OF_Config f) = Just (FlagConfig f)
810 let fields = [ f | OF_Field f <- clis ]
812 let auto_ghci_libs = any isAuto clis
813 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
814 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
816 force = OF_Force `elem` clis
818 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
820 case [ c | c <- clis, isAction c ] of
821 [ OF_List ] -> listPackages new_flags
822 [ OF_ListLocal ] -> listPackages new_flags
824 registerPackage input_file defines new_flags auto_ghci_libs upd force
825 [ OF_Remove pkgid_str ] -> do
826 pkgid <- readPkgId pkgid_str
827 unregisterPackage pkgid new_flags
828 [ OF_Show pkgid_str ]
830 pkgid <- readPkgId pkgid_str
831 describePackage new_flags pkgid
833 pkgid <- readPkgId pkgid_str
834 mapM_ (describeField new_flags pkgid) fields
836 prog <- getProgramName
837 die (usageInfo (usageHeader prog) flags)
839 my_head :: String -> [a] -> a
840 my_head s [] = error s
843 -- ---------------------------------------------------------------------------
847 expandEnvVars :: PackageConfig -> [(String, String)]
848 -> Bool -> IO PackageConfig
849 expandEnvVars pkg defines force = do
850 -- permit _all_ strings to contain ${..} environment variable references,
851 -- arguably too flexible.
852 nm <- expandString (name pkg)
853 imp_dirs <- expandStrings (import_dirs pkg)
854 src_dirs <- expandStrings (source_dirs pkg)
855 lib_dirs <- expandStrings (library_dirs pkg)
856 hs_libs <- expandStrings (hs_libraries pkg)
857 ex_libs <- expandStrings (extra_libraries pkg)
858 inc_dirs <- expandStrings (include_dirs pkg)
859 c_incs <- expandStrings (c_includes pkg)
860 p_deps <- expandStrings (package_deps pkg)
861 e_g_opts <- expandStrings (extra_ghc_opts pkg)
862 e_c_opts <- expandStrings (extra_cc_opts pkg)
863 e_l_opts <- expandStrings (extra_ld_opts pkg)
864 f_dirs <- expandStrings (framework_dirs pkg)
865 e_frames <- expandStrings (extra_frameworks pkg)
866 return (pkg { name = nm
867 , import_dirs = imp_dirs
868 , source_dirs = src_dirs
869 , library_dirs = lib_dirs
870 , hs_libraries = hs_libs
871 , extra_libraries = ex_libs
872 , include_dirs = inc_dirs
873 , c_includes = c_incs
874 , package_deps = p_deps
875 , extra_ghc_opts = e_g_opts
876 , extra_cc_opts = e_c_opts
877 , extra_ld_opts = e_l_opts
878 , framework_dirs = f_dirs
879 , extra_frameworks= e_frames
882 expandStrings :: [String] -> IO [String]
883 expandStrings = liftM concat . mapM expandSpecial
885 -- Permit substitutions for list-valued variables (but only when
886 -- they occur alone), e.g., package_deps["${deps}"] where env var
887 -- (say) 'deps' is "base,haskell98,network"
888 expandSpecial :: String -> IO [String]
890 let expand f = liftM f $ expandString str
891 in case splitString str of
892 [Var _] -> expand (wordsBy (== ','))
893 _ -> expand (\x -> [x])
895 expandString :: String -> IO String
896 expandString = liftM concat . mapM expandElem . splitString
898 expandElem :: Elem -> IO String
899 expandElem (String s) = return s
900 expandElem (Var v) = lookupEnvVar v
902 lookupEnvVar :: String -> IO String
904 case lookup nm defines of
905 Just x | not (null x) -> return x
907 catch (System.getEnv nm)
908 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
912 data Elem = String String | Var String
914 splitString :: String -> [Elem]
917 case break (== '$') str of
919 case span (/= '}') xs of
921 (if null pre then id else (String pre :)) (Var var : splitString suf)
922 _ -> [String str] -- no closing brace
923 _ -> [String str] -- no dollar/opening brace combo
925 -- wordsBy isSpace == words
926 wordsBy :: (Char -> Bool) -> String -> [String]
927 wordsBy p s = case dropWhile p s of
929 s' -> w : wordsBy p s'' where (w,s'') = break p s'
932 -----------------------------------------------------------------------------
934 getProgramName :: IO String
935 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
936 where str `withoutSuffix` suff
937 | suff `isSuffixOf` str = take (length str - length suff) str
940 bye :: String -> IO a
941 bye s = putStr s >> exitWith ExitSuccess
943 die :: String -> IO a
946 prog <- getProgramName
947 hPutStrLn stderr (prog ++ ": " ++ s)
948 exitWith (ExitFailure 1)
950 dieOrForce :: Bool -> String -> IO ()
952 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
956 -----------------------------------------
957 -- Cut and pasted from ghc/compiler/SysTools
959 #if defined(mingw32_HOST_OS)
960 subst a b ls = map (\ x -> if x == a then b else x) ls
961 unDosifyPath xs = subst '\\' '/' xs
963 getExecDir :: String -> IO (Maybe String)
964 -- (getExecDir cmd) returns the directory in which the current
965 -- executable, which should be called 'cmd', is running
966 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
967 -- you'll get "/a/b/c" back as the result
969 = allocaArray len $ \buf -> do
970 ret <- getModuleFileName nullPtr buf len
971 if ret == 0 then return Nothing
972 else do s <- peekCString buf
973 return (Just (reverse (drop (length cmd)
974 (reverse (unDosifyPath s)))))
976 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
978 foreign import stdcall unsafe "GetModuleFileNameA"
979 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
981 getExecDir :: String -> IO (Maybe String)
982 getExecDir _ = return Nothing
985 -- -----------------------------------------------------------------------------
988 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
989 -- It joins directory and file names to form a complete file path.
991 -- The general rule is:
993 -- > dir `joinFileName` basename == path
995 -- > (dir,basename) = splitFileName path
997 -- There might be an exceptions to the rule but in any case the
998 -- reconstructed path will refer to the same object (file or directory).
999 -- An example exception is that on Windows some slashes might be converted
1001 joinFileName :: String -> String -> FilePath
1002 joinFileName "" fname = fname
1003 joinFileName "." fname = fname
1004 joinFileName dir "" = dir
1005 joinFileName dir fname
1006 | isPathSeparator (last dir) = dir++fname
1007 | otherwise = dir++pathSeparator:fname
1009 -- | Checks whether the character is a valid path separator for the host
1010 -- platform. The valid character is a 'pathSeparator' but since the Windows
1011 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1012 -- checks for it on this platform, too.
1013 isPathSeparator :: Char -> Bool
1014 isPathSeparator ch = ch == pathSeparator || ch == '/'
1016 -- | Provides a platform-specific character used to separate directory levels in
1017 -- a path string that reflects a hierarchical file system organization. The
1018 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1019 -- (@\"\\\"@) on the Windows operating system.
1020 pathSeparator :: Char
1021 #ifdef mingw32_HOST_OS
1022 pathSeparator = '\\'