1 {-# OPTIONS -fglasgow-exts #-}
2 -----------------------------------------------------------------------------
4 -- (c) The University of Glasgow 2004.
6 -- Package management tool
8 -----------------------------------------------------------------------------
12 -- - expanding of variables in new-style package conf
13 -- - version manipulation (checking whether old version exists,
14 -- hiding old version?)
16 module Main (main) where
18 import Version ( version, targetOS, targetARCH )
19 import Distribution.InstalledPackageInfo
20 import Distribution.Compat.ReadP
21 import Distribution.ParseUtils ( showError, ParseResult(..) )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem ( rawSystem )
26 import Control.Exception ( evaluate )
27 import qualified Control.Exception as Exception
31 #include "../../includes/ghcconfig.h"
33 #if __GLASGOW_HASKELL__ >= 504
34 import System.Console.GetOpt
35 import Text.PrettyPrint
36 import qualified Control.Exception as Exception
40 import qualified Exception
43 import Data.Char ( isSpace )
46 import System ( getArgs, getProgName,
47 exitWith, ExitCode(..)
50 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
52 #ifdef mingw32_HOST_OS
55 #if __GLASGOW_HASKELL__ >= 504
56 import Foreign.C.String
62 -- -----------------------------------------------------------------------------
69 case getOpt Permute flags args of
70 (cli,_,[]) | FlagHelp `elem` cli -> do
71 prog <- getProgramName
72 bye (usageInfo (usageHeader prog) flags)
73 (cli,_,[]) | FlagVersion `elem` cli ->
77 (_,_,errors) -> tryOldCmdLine errors args
79 -- If the new command-line syntax fails, then we try the old. If that
80 -- fails too, then we output the original errors and the new syntax
81 -- (so the old syntax is still available, but hidden).
82 tryOldCmdLine :: [String] -> [String] -> IO ()
83 tryOldCmdLine errors args = do
84 case getOpt Permute oldFlags args of
88 prog <- getProgramName
89 die (concat errors ++ usageInfo (usageHeader prog) flags)
91 -- -----------------------------------------------------------------------------
92 -- Command-line syntax
100 | FlagGlobalConfig FilePath
105 flags :: [OptDescr Flag]
107 Option [] ["user"] (NoArg FlagUser)
108 "use the current user's package database",
109 Option [] ["global"] (NoArg FlagGlobal)
110 "(default) use the global package database",
111 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
112 "act upon specified package config file (only)",
113 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
114 "location of the global package config",
115 Option [] ["force"] (NoArg FlagForce)
116 "ignore missing dependencies, directories, and libraries",
117 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
118 "automatically build libs for GHCi (with register)",
119 Option ['?'] ["help"] (NoArg FlagHelp)
120 "display this help and exit",
121 Option ['V'] ["version"] (NoArg FlagVersion)
122 "output version information and exit"
125 ourCopyright :: String
126 ourCopyright = "GHC package manager version " ++ version ++ "\n"
128 usageHeader :: String -> String
129 usageHeader prog = substProg prog $
131 " $p register {filename | -}\n" ++
132 " Register the package using the specified installed package\n" ++
133 " description. The syntax for the latter is given in the $p\n" ++
134 " documentation.\n" ++
136 " $p update {filename | -}\n" ++
137 " Register the package, overwriting any other package with the\n" ++
140 " $p unregister {pkg-id}\n" ++
141 " Unregister the specified package.\n" ++
143 " $p expose {pkg-id}\n" ++
144 " Expose the specified package.\n" ++
146 " $p hide {pkg-id}\n" ++
147 " Hide the specified package.\n" ++
150 " List all registered packages, both global and user (unless either\n" ++
151 " --global or --user is specified), and both hidden and exposed.\n" ++
153 " $p describe {pkg-id}\n" ++
154 " Give the registered description for the specified package. The\n" ++
155 " description is returned in precisely the syntax required by $p\n" ++
158 " $p field {pkg-id} {field}\n" ++
159 " Extract the specified field of the package description for the\n" ++
160 " specified package.\n" ++
162 " The following optional flags are also accepted:\n"
164 substProg :: String -> String -> String
166 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
167 substProg prog (c:xs) = c : substProg prog xs
169 -- -----------------------------------------------------------------------------
172 runit :: [Flag] -> [String] -> IO ()
173 runit cli nonopts = do
174 prog <- getProgramName
175 dbs <- getPkgDatabases cli
176 db_stack <- mapM readParseDatabase dbs
178 force = FlagForce `elem` cli
179 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
181 -- first, parse the command
183 ["register", filename] ->
184 registerPackage filename [] db_stack auto_ghci_libs False force
185 ["update", filename] ->
186 registerPackage filename [] db_stack auto_ghci_libs True force
187 ["unregister", pkgid_str] -> do
188 pkgid <- readPkgId pkgid_str
189 unregisterPackage pkgid db_stack
190 ["expose", pkgid_str] -> do
191 pkgid <- readPkgId pkgid_str
192 exposePackage pkgid db_stack
193 ["hide", pkgid_str] -> do
194 pkgid <- readPkgId pkgid_str
195 hidePackage pkgid db_stack
197 listPackages db_stack
198 ["describe", pkgid_str] -> do
199 pkgid <- readPkgId pkgid_str
200 describePackage db_stack pkgid
201 ["field", pkgid_str, field] -> do
202 pkgid <- readPkgId pkgid_str
203 describeField db_stack pkgid field
205 die ("missing command\n" ++
206 usageInfo (usageHeader prog) flags)
208 die ("command-line syntax error\n" ++
209 usageInfo (usageHeader prog) flags)
211 parseCheck :: ReadP a a -> String -> String -> IO a
212 parseCheck parser str what =
213 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
215 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
217 readPkgId :: String -> IO PackageIdentifier
218 readPkgId str = parseCheck parsePackageId str "package identifier"
220 -- -----------------------------------------------------------------------------
223 -- Some commands operate on a single database:
224 -- register, unregister, expose, hide
225 -- however these commands also check the union of the available databases
226 -- in order to check consistency. For example, register will check that
227 -- dependencies exist before registering a package.
229 -- Some commands operate on multiple databases, with overlapping semantics:
230 -- list, describe, field
232 type PackageDBName = FilePath
233 type PackageDB = [InstalledPackageInfo]
235 type PackageDBStack = [(PackageDBName,PackageDB)]
236 -- A stack of package databases. Convention: head is the topmost
237 -- in the stack. Earlier entries override later one.
239 -- The output of this function is the list of databases to act upon, with
240 -- the "topmost" overlapped database last. The commands which operate on a
241 -- single database will use the last one. Commands which operate on multiple
242 -- databases will interpret the databases as overlapping.
243 getPkgDatabases :: [Flag] -> IO [PackageDBName]
244 getPkgDatabases flags = do
245 -- first we determine the location of the global package config. On Windows,
246 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
247 -- location is passed to the binary using the --global-config flag by the
249 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
251 case [ f | FlagGlobalConfig f <- flags ] of
252 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
254 Nothing -> die err_msg
255 Just dir -> return (dir `joinFileName` "package.conf")
256 fs -> return (last fs)
258 -- get the location of the user package database, and create it if necessary
259 appdir <- getAppUserDataDirectory "ghc"
262 subdir = targetARCH ++ '-':targetOS ++ '-':version
263 archdir = appdir `joinFileName` subdir
264 user_conf = archdir `joinFileName` "package.conf"
265 b <- doesFileExist user_conf
267 putStrLn ("Creating user package database in " ++ user_conf)
268 createDirectoryIfMissing True archdir
269 writeFile user_conf emptyPackageConfig
272 databases = foldl addDB [global_conf] flags
274 -- implement the following rules:
275 -- global database is the default
276 -- --user means overlap with the user database
277 -- --global means reset to just the global database
278 -- -f <file> means overlap with <file>
279 addDB dbs FlagUser = user_conf : dbs
280 addDB dbs FlagGlobal = [global_conf]
281 addDB dbs (FlagConfig f) = f : dbs
286 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
287 readParseDatabase filename = do
288 str <- readFile filename
289 let packages = read str
291 `Exception.catch` \_ ->
292 die (filename ++ ": parse error in package config file")
293 return (filename,packages)
295 emptyPackageConfig :: String
296 emptyPackageConfig = "[]"
298 -- -----------------------------------------------------------------------------
301 registerPackage :: FilePath
302 -> [(String,String)] -- defines, ToDo: maybe remove?
304 -> Bool -- auto_ghci_libs
308 registerPackage input defines db_stack auto_ghci_libs update force = do
310 db_to_operate_on = my_head "db" db_stack
311 db_filename = fst db_to_operate_on
313 checkConfigAccess db_filename
318 putStr "Reading package info from stdin... "
321 putStr ("Reading package info from " ++ show f ++ " ")
324 pkg <- parsePackageInfo s defines force
327 validatePackageConfig pkg db_stack auto_ghci_libs update force
328 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
329 savePackageConfig db_filename
330 maybeRestoreOldConfig db_filename $
331 writeNewConfig db_filename new_details
337 -> IO InstalledPackageInfo
338 parsePackageInfo str defines force =
339 case parseInstalledPackageInfo str of
340 ParseOk ok -> return ok
341 ParseFailed err -> die (showError err)
343 -- Used for converting versionless package names to new
344 -- PackageIdentifiers. "Version [] []" is special: it means "no
345 -- version" or "any version"
346 pkgNameToId :: String -> PackageIdentifier
347 pkgNameToId name = PackageIdentifier name (Version [] [])
349 -- -----------------------------------------------------------------------------
350 -- Exposing, Hiding, Unregistering are all similar
352 exposePackage :: PackageIdentifier -> PackageDBStack -> IO ()
353 exposePackage = modifyPackage (\p -> [p{exposed=True}])
355 hidePackage :: PackageIdentifier -> PackageDBStack -> IO ()
356 hidePackage = modifyPackage (\p -> [p{exposed=False}])
358 unregisterPackage :: PackageIdentifier -> PackageDBStack -> IO ()
359 unregisterPackage = modifyPackage (\p -> [])
362 :: (InstalledPackageInfo -> [InstalledPackageInfo])
366 modifyPackage _ _ [] = error "modifyPackage"
367 modifyPackage fn pkgid ((db_name, pkgs) : _) = do
368 checkConfigAccess db_name
369 p <- findPackage [(db_name,pkgs)] pkgid
371 savePackageConfig db_name
372 let new_config = concat (map modify pkgs)
374 | package pkg == pid = fn pkg
376 maybeRestoreOldConfig db_name $
377 writeNewConfig db_name new_config
379 -- -----------------------------------------------------------------------------
382 listPackages :: PackageDBStack -> IO ()
383 listPackages db_confs = do
384 mapM_ show_pkgconf (reverse db_confs)
385 where show_pkgconf (db_name,pkg_confs) =
386 hPutStrLn stdout (render $
387 text (db_name ++ ":") $$ nest 4 packages
389 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
392 | otherwise = parens doc
393 where doc = text (showPackageId (package p))
395 -- -----------------------------------------------------------------------------
398 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
399 describePackage db_stack pkgid = do
400 p <- findPackage db_stack pkgid
401 putStrLn (showInstalledPackageInfo p)
403 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
404 findPackage db_stack pkgid
405 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
406 [] -> die ("cannot find package " ++ showPackageId pkgid)
408 ps -> die ("package " ++ showPackageId pkgid ++
409 " matches multiple packages: " ++
410 concat (intersperse ", " (
411 map (showPackageId.package) ps)))
413 all_pkgs = concat (map snd db_stack)
415 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
418 not (realVersion pid) && pkgName pid == pkgName (package p)
420 -- -----------------------------------------------------------------------------
423 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
424 describeField db_stack pkgid field = do
425 case toField field of
426 Nothing -> die ("unknown field: " ++ field)
428 p <- findPackage db_stack pkgid
431 toField :: String -> Maybe (InstalledPackageInfo -> String)
432 -- backwards compatibility:
433 toField "import_dirs" = Just $ strList . importDirs
434 toField "source_dirs" = Just $ strList . importDirs
435 toField "library_dirs" = Just $ strList . libraryDirs
436 toField "hs_libraries" = Just $ strList . hsLibraries
437 toField "extra_libraries" = Just $ strList . extraLibraries
438 toField "include_dirs" = Just $ strList . includeDirs
439 toField "c_includes" = Just $ strList . includes
440 toField "package_deps" = Just $ strList . map showPackageId. depends
441 toField "extra_cc_opts" = Just $ strList . extraCcOpts
442 toField "extra_ld_opts" = Just $ strList . extraLdOpts
443 toField "framework_dirs" = Just $ strList . frameworkDirs
444 toField "extra_frameworks"= Just $ strList . extraFrameworks
445 toField s = showInstalledPackageInfoField s
447 strList :: [String] -> String
450 -- -----------------------------------------------------------------------------
451 -- Manipulating package.conf files
453 checkConfigAccess :: FilePath -> IO ()
454 checkConfigAccess filename = do
455 access <- getPermissions filename
456 when (not (writable access))
457 (die (filename ++ ": you don't have permission to modify this file"))
459 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
460 maybeRestoreOldConfig filename io
461 = io `catch` \e -> do
462 hPutStrLn stderr (show e)
463 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
464 "configuration was being written. Attempting to \n"++
465 "restore the old configuration... ")
466 renameFile (filename ++ ".old") filename
467 hPutStrLn stdout "done."
470 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
471 writeNewConfig filename packages = do
472 hPutStr stdout "Writing new package config file... "
473 h <- openFile filename WriteMode
474 hPutStrLn h (show packages)
476 hPutStrLn stdout "done."
478 savePackageConfig :: FilePath -> IO ()
479 savePackageConfig filename = do
480 hPutStr stdout "Saving old package config file... "
481 -- mv rather than cp because we've already done an hGetContents
482 -- on this file so we won't be able to open it for writing
483 -- unless we move the old one out of the way...
484 let oldFile = filename ++ ".old"
485 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
486 when doesExist (removeFile oldFile `catch` (const $ return ()))
487 catch (renameFile filename oldFile)
489 hPutStrLn stderr (unwords [ "Unable to rename "
495 hPutStrLn stdout "done."
497 -----------------------------------------------------------------------------
498 -- Sanity-check a new package config, and automatically build GHCi libs
501 validatePackageConfig :: InstalledPackageInfo
503 -> Bool -- auto-ghc-libs
507 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
509 checkDuplicates db_stack pkg update
510 mapM_ (checkDep db_stack force) (depends pkg)
511 mapM_ (checkDir force) (importDirs pkg)
512 mapM_ (checkDir force) (libraryDirs pkg)
513 mapM_ (checkDir force) (includeDirs pkg)
514 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
515 -- ToDo: check these somehow?
516 -- extra_libraries :: [String],
517 -- c_includes :: [String],
519 -- When the package name and version are put together, sometimes we can
520 -- end up with a package id that cannot be parsed. This will lead to
521 -- difficulties when the user wants to refer to the package later, so
522 -- we check that the package id can be parsed properly here.
523 checkPackageId :: InstalledPackageInfo -> IO ()
525 let str = showPackageId (package ipi) in
526 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
528 [] -> die ("invalid package identifier: " ++ str)
529 _ -> die ("ambiguous package identifier: " ++ str)
531 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
532 checkDuplicates db_stack pkg update = do
536 (_top_db_name, pkgs) : _ = db_stack
538 pkgs_with_same_name =
539 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
540 exposed_pkgs_with_same_name =
541 filter exposed pkgs_with_same_name
543 -- Check whether this package id already exists in this DB
545 when (not update && (package pkg `elem` map package pkgs)) $
546 die ("package " ++ showPackageId pkgid ++ " is already installed")
548 -- if we are exposing this new package, then check that
549 -- there are no other exposed packages with the same name.
551 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
552 die ("trying to register " ++ showPackageId pkgid
553 ++ " as exposed, but "
554 ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
555 ++ " is also exposed.")
558 checkDir :: Bool -> String -> IO ()
560 | "$topdir" `isPrefixOf` d = return ()
561 -- can't check this, because we don't know what $topdir is
563 there <- doesDirectoryExist d
565 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
567 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
568 checkDep db_stack force pkgid
569 | real_version && pkgid `elem` pkgids = return ()
570 | not real_version && pkgName pkgid `elem` pkg_names = return ()
571 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
574 -- for backwards compat, we treat 0.0 as a special version,
575 -- and don't check that it actually exists.
576 real_version = realVersion pkgid
578 all_pkgs = concat (map snd db_stack)
579 pkgids = map package all_pkgs
580 pkg_names = map pkgName pkgids
582 realVersion :: PackageIdentifier -> Bool
583 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
585 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
586 checkHSLib dirs auto_ghci_libs force lib = do
587 let batch_lib_file = "lib" ++ lib ++ ".a"
588 bs <- mapM (doesLibExistIn batch_lib_file) dirs
589 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
590 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
592 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
594 doesLibExistIn :: String -> String -> IO Bool
596 | "$topdir" `isPrefixOf` d = return True
597 | otherwise = doesFileExist (d ++ '/':lib)
599 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
600 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
601 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
603 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
604 case [dir | (exists,dir) <- zip bs dirs, exists] of
605 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
608 ghci_lib_file = lib ++ ".o"
610 -- automatically build the GHCi version of a batch lib,
611 -- using ld --whole-archive.
613 autoBuildGHCiLib :: String -> String -> String -> IO ()
614 autoBuildGHCiLib dir batch_file ghci_file = do
615 let ghci_lib_file = dir ++ '/':ghci_file
616 batch_lib_file = dir ++ '/':batch_file
617 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
618 #if defined(darwin_HOST_OS)
619 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
620 #elif defined(mingw32_HOST_OS)
621 execDir <- getExecDir "/bin/ghc-pkg.exe"
622 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
624 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
626 when (r /= ExitSuccess) $ exitWith r
627 hPutStrLn stderr (" done.")
629 -- -----------------------------------------------------------------------------
630 -- Updating the DB with the new package.
634 -> [InstalledPackageInfo]
635 -> InstalledPackageInfo
636 -> IO [InstalledPackageInfo]
637 updatePackageDB db_stack pkgs new_pkg = do
639 -- The input package spec is allowed to give a package dependency
640 -- without a version number; e.g.
642 -- Here, we update these dependencies without version numbers to
643 -- match the actual versions of the relevant packages installed.
644 updateDeps p = p{depends = map resolveDep (depends p)}
647 | realVersion dep_pkgid = dep_pkgid
648 | otherwise = lookupDep dep_pkgid
652 name = pkgName dep_pkgid
654 case [ pid | p <- concat (map snd db_stack),
656 pkgName pid == name ] of
657 (pid:_) -> pid -- Found installed package,
658 -- replete with its version
659 [] -> dep_pkgid -- No installed package; use
660 -- the version-less one
662 is_exposed = exposed new_pkg
663 pkgid = package new_pkg
666 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
668 -- When update is on, and we're exposing the new package,
669 -- we hide any packages with the same name (different versions)
670 -- in the current DB. Earlier checks will have failed if
673 | is_exposed && pkgName (package p) == name = p{ exposed = False }
676 return (pkgs'++[updateDeps new_pkg])
678 -- -----------------------------------------------------------------------------
679 -- Searching for modules
683 findModules :: [FilePath] -> IO [String]
685 mms <- mapM searchDir paths
688 searchDir path prefix = do
689 fs <- getDirectoryEntries path `catch` \_ -> return []
690 searchEntries path prefix fs
692 searchEntries path prefix [] = return []
693 searchEntries path prefix (f:fs)
694 | looks_like_a_module = do
695 ms <- searchEntries path prefix fs
696 return (prefix `joinModule` f : ms)
697 | looks_like_a_component = do
698 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
699 ms' <- searchEntries path prefix fs
702 searchEntries path prefix fs
705 (base,suffix) = splitFileExt f
706 looks_like_a_module =
707 suffix `elem` haskell_suffixes &&
708 all okInModuleName base
709 looks_like_a_component =
710 null suffix && all okInModuleName base
716 -- -----------------------------------------------------------------------------
717 -- The old command-line syntax, supported for backwards compatibility
724 | OF_Add Bool {- True => replace existing info -}
725 | OF_Remove String | OF_Show String
726 | OF_Field String | OF_AutoGHCiLibs | OF_Force
727 | OF_DefinedName String String
728 | OF_GlobalConfig FilePath
731 isAction :: OldFlag -> Bool
732 isAction OF_Config{} = False
733 isAction OF_Field{} = False
734 isAction OF_Input{} = False
735 isAction OF_AutoGHCiLibs{} = False
736 isAction OF_Force{} = False
737 isAction OF_DefinedName{} = False
738 isAction OF_GlobalConfig{} = False
741 oldFlags :: [OptDescr OldFlag]
743 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
744 "use the specified package config file",
745 Option ['l'] ["list-packages"] (NoArg OF_List)
746 "list packages in all config files",
747 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
748 "list packages in the specified config file",
749 Option ['a'] ["add-package"] (NoArg (OF_Add False))
751 Option ['u'] ["update-package"] (NoArg (OF_Add True))
752 "update package with new configuration",
753 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
754 "read new package info from specified file",
755 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
756 "show the configuration for package NAME",
757 Option [] ["field"] (ReqArg OF_Field "FIELD")
758 "(with --show-package) Show field FIELD only",
759 Option [] ["force"] (NoArg OF_Force)
760 "ignore missing directories/libraries",
761 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
762 "remove an installed package",
763 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
764 "automatically build libs for GHCi (with -a)",
765 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
766 "define NAME as VALUE",
767 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
768 "location of the global package config"
772 case break (=='=') str of
773 (nm,[]) -> OF_DefinedName nm []
774 (nm,_:val) -> OF_DefinedName nm val
776 oldRunit :: [OldFlag] -> IO ()
778 let config_flags = [ f | Just f <- map conv clis ]
780 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
781 conv (OF_Config f) = Just (FlagConfig f)
784 db_names <- getPkgDatabases config_flags
785 db_stack <- mapM readParseDatabase db_names
787 let fields = [ f | OF_Field f <- clis ]
789 let auto_ghci_libs = any isAuto clis
790 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
791 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
793 force = OF_Force `elem` clis
795 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
797 case [ c | c <- clis, isAction c ] of
798 [ OF_List ] -> listPackages db_stack
799 [ OF_ListLocal ] -> listPackages db_stack
800 [ OF_Add upd ] -> registerPackage input_file defines db_stack
801 auto_ghci_libs upd force
802 [ OF_Remove p ] -> unregisterPackage (pkgNameToId p) db_stack
804 | null fields -> describePackage db_stack (pkgNameToId p)
805 | otherwise -> mapM_ (describeField db_stack (pkgNameToId p)) fields
806 _ -> do prog <- getProgramName
807 die (usageInfo (usageHeader prog) flags)
809 my_head s [] = error s
812 -- ---------------------------------------------------------------------------
816 expandEnvVars :: PackageConfig -> [(String, String)]
817 -> Bool -> IO PackageConfig
818 expandEnvVars pkg defines force = do
819 -- permit _all_ strings to contain ${..} environment variable references,
820 -- arguably too flexible.
821 nm <- expandString (name pkg)
822 imp_dirs <- expandStrings (import_dirs pkg)
823 src_dirs <- expandStrings (source_dirs pkg)
824 lib_dirs <- expandStrings (library_dirs pkg)
825 hs_libs <- expandStrings (hs_libraries pkg)
826 ex_libs <- expandStrings (extra_libraries pkg)
827 inc_dirs <- expandStrings (include_dirs pkg)
828 c_incs <- expandStrings (c_includes pkg)
829 p_deps <- expandStrings (package_deps pkg)
830 e_g_opts <- expandStrings (extra_ghc_opts pkg)
831 e_c_opts <- expandStrings (extra_cc_opts pkg)
832 e_l_opts <- expandStrings (extra_ld_opts pkg)
833 f_dirs <- expandStrings (framework_dirs pkg)
834 e_frames <- expandStrings (extra_frameworks pkg)
835 return (pkg { name = nm
836 , import_dirs = imp_dirs
837 , source_dirs = src_dirs
838 , library_dirs = lib_dirs
839 , hs_libraries = hs_libs
840 , extra_libraries = ex_libs
841 , include_dirs = inc_dirs
842 , c_includes = c_incs
843 , package_deps = p_deps
844 , extra_ghc_opts = e_g_opts
845 , extra_cc_opts = e_c_opts
846 , extra_ld_opts = e_l_opts
847 , framework_dirs = f_dirs
848 , extra_frameworks= e_frames
851 expandStrings :: [String] -> IO [String]
852 expandStrings = liftM concat . mapM expandSpecial
854 -- Permit substitutions for list-valued variables (but only when
855 -- they occur alone), e.g., package_deps["${deps}"] where env var
856 -- (say) 'deps' is "base,haskell98,network"
857 expandSpecial :: String -> IO [String]
859 let expand f = liftM f $ expandString str
860 in case splitString str of
861 [Var _] -> expand (wordsBy (== ','))
862 _ -> expand (\x -> [x])
864 expandString :: String -> IO String
865 expandString = liftM concat . mapM expandElem . splitString
867 expandElem :: Elem -> IO String
868 expandElem (String s) = return s
869 expandElem (Var v) = lookupEnvVar v
871 lookupEnvVar :: String -> IO String
873 case lookup nm defines of
874 Just x | not (null x) -> return x
876 catch (System.getEnv nm)
877 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
881 data Elem = String String | Var String
883 splitString :: String -> [Elem]
886 case break (== '$') str of
888 case span (/= '}') xs of
890 (if null pre then id else (String pre :)) (Var var : splitString suf)
891 _ -> [String str] -- no closing brace
892 _ -> [String str] -- no dollar/opening brace combo
894 -- wordsBy isSpace == words
895 wordsBy :: (Char -> Bool) -> String -> [String]
896 wordsBy p s = case dropWhile p s of
898 s' -> w : wordsBy p s'' where (w,s'') = break p s'
901 -----------------------------------------------------------------------------
903 getProgramName :: IO String
904 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
905 where str `withoutSuffix` suff
906 | suff `isSuffixOf` str = take (length str - length suff) str
909 bye :: String -> IO a
910 bye s = putStr s >> exitWith ExitSuccess
912 die :: String -> IO a
915 prog <- getProgramName
916 hPutStrLn stderr (prog ++ ": " ++ s)
917 exitWith (ExitFailure 1)
919 dieOrForce :: Bool -> String -> IO ()
921 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
925 -----------------------------------------
926 -- Cut and pasted from ghc/compiler/SysTools
928 #if defined(mingw32_HOST_OS)
929 subst a b ls = map (\ x -> if x == a then b else x) ls
930 unDosifyPath xs = subst '\\' '/' xs
932 getExecDir :: String -> IO (Maybe String)
933 -- (getExecDir cmd) returns the directory in which the current
934 -- executable, which should be called 'cmd', is running
935 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
936 -- you'll get "/a/b/c" back as the result
938 = allocaArray len $ \buf -> do
939 ret <- getModuleFileName nullPtr buf len
940 if ret == 0 then return Nothing
941 else do s <- peekCString buf
942 return (Just (reverse (drop (length cmd)
943 (reverse (unDosifyPath s)))))
945 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
947 foreign import stdcall unsafe "GetModuleFileNameA"
948 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
950 getExecDir :: String -> IO (Maybe String)
951 getExecDir _ = return Nothing
954 -- -----------------------------------------------------------------------------
957 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
958 -- It joins directory and file names to form a complete file path.
960 -- The general rule is:
962 -- > dir `joinFileName` basename == path
964 -- > (dir,basename) = splitFileName path
966 -- There might be an exceptions to the rule but in any case the
967 -- reconstructed path will refer to the same object (file or directory).
968 -- An example exception is that on Windows some slashes might be converted
970 joinFileName :: String -> String -> FilePath
971 joinFileName "" fname = fname
972 joinFileName "." fname = fname
973 joinFileName dir "" = dir
974 joinFileName dir fname
975 | isPathSeparator (last dir) = dir++fname
976 | otherwise = dir++pathSeparator:fname
978 -- | Checks whether the character is a valid path separator for the host
979 -- platform. The valid character is a 'pathSeparator' but since the Windows
980 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
981 -- checks for it on this platform, too.
982 isPathSeparator :: Char -> Bool
983 isPathSeparator ch = ch == pathSeparator || ch == '/'
985 -- | Provides a platform-specific character used to separate directory levels in
986 -- a path string that reflects a hierarchical file system organization. The
987 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
988 -- (@\"\\\"@) on the Windows operating system.
989 pathSeparator :: Char
990 #ifdef mingw32_HOST_OS