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, getEnv,
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
101 | FlagDefinedName String String
104 flags :: [OptDescr Flag]
106 Option [] ["user"] (NoArg FlagUser)
107 "use the current user's package database",
108 Option [] ["global"] (NoArg FlagGlobal)
109 "(default) use the global package database",
110 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
111 "act upon specified package config file (only)",
112 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
113 "location of the global package config",
114 Option [] ["force"] (NoArg FlagForce)
115 "ignore missing dependencies, directories, and libraries",
116 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
117 "automatically build libs for GHCi (with register)",
118 Option ['?'] ["help"] (NoArg FlagHelp)
119 "display this help and exit",
120 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
121 "define NAME as VALUE",
122 Option ['V'] ["version"] (NoArg FlagVersion)
123 "output version information and exit"
127 case break (=='=') str of
128 (nm,[]) -> FlagDefinedName nm []
129 (nm,_:val) -> FlagDefinedName nm val
131 ourCopyright :: String
132 ourCopyright = "GHC package manager version " ++ version ++ "\n"
134 usageHeader :: String -> String
135 usageHeader prog = substProg prog $
137 " $p register {filename | -}\n" ++
138 " Register the package using the specified installed package\n" ++
139 " description. The syntax for the latter is given in the $p\n" ++
140 " documentation.\n" ++
142 " $p update {filename | -}\n" ++
143 " Register the package, overwriting any other package with the\n" ++
146 " $p unregister {pkg-id}\n" ++
147 " Unregister the specified package.\n" ++
149 " $p expose {pkg-id}\n" ++
150 " Expose the specified package.\n" ++
152 " $p hide {pkg-id}\n" ++
153 " Hide the specified package.\n" ++
156 " List registered packages in the global database, and also the" ++
157 " user database if --user is given.\n" ++
159 " $p describe {pkg-id}\n" ++
160 " Give the registered description for the specified package. The\n" ++
161 " description is returned in precisely the syntax required by $p\n" ++
164 " $p field {pkg-id} {field}\n" ++
165 " Extract the specified field of the package description for the\n" ++
166 " specified package.\n" ++
168 " The following optional flags are also accepted:\n"
170 substProg :: String -> String -> String
172 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
173 substProg prog (c:xs) = c : substProg prog xs
175 -- -----------------------------------------------------------------------------
178 runit :: [Flag] -> [String] -> IO ()
179 runit cli nonopts = do
180 prog <- getProgramName
182 force = FlagForce `elem` cli
183 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
184 defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
186 -- first, parse the command
188 ["register", filename] ->
189 registerPackage filename defines cli auto_ghci_libs False force
190 ["update", filename] ->
191 registerPackage filename defines cli auto_ghci_libs True force
192 ["unregister", pkgid_str] -> do
193 pkgid <- readGlobPkgId pkgid_str
194 unregisterPackage pkgid cli
195 ["expose", pkgid_str] -> do
196 pkgid <- readGlobPkgId pkgid_str
197 exposePackage pkgid cli
198 ["hide", pkgid_str] -> do
199 pkgid <- readGlobPkgId pkgid_str
200 hidePackage pkgid cli
203 ["describe", pkgid_str] -> do
204 pkgid <- readGlobPkgId pkgid_str
205 describePackage cli pkgid
206 ["field", pkgid_str, field] -> do
207 pkgid <- readGlobPkgId pkgid_str
208 describeField cli pkgid field
210 die ("missing command\n" ++
211 usageInfo (usageHeader prog) flags)
213 die ("command-line syntax error\n" ++
214 usageInfo (usageHeader prog) flags)
216 parseCheck :: ReadP a a -> String -> String -> IO a
217 parseCheck parser str what =
218 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
220 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
222 readPkgId :: String -> IO PackageIdentifier
223 readPkgId str = parseCheck parsePackageId str "package identifier"
225 readGlobPkgId :: String -> IO PackageIdentifier
226 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
228 parseGlobPackageId :: ReadP r PackageIdentifier
232 (do n <- parsePackageName; string "-*"
233 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
235 -- globVersion means "all versions"
236 globVersion :: Version
237 globVersion = Version{ versionBranch=[], versionTags=["*"] }
239 -- -----------------------------------------------------------------------------
242 -- Some commands operate on a single database:
243 -- register, unregister, expose, hide
244 -- however these commands also check the union of the available databases
245 -- in order to check consistency. For example, register will check that
246 -- dependencies exist before registering a package.
248 -- Some commands operate on multiple databases, with overlapping semantics:
249 -- list, describe, field
251 type PackageDBName = FilePath
252 type PackageDB = [InstalledPackageInfo]
254 type PackageDBStack = [(PackageDBName,PackageDB)]
255 -- A stack of package databases. Convention: head is the topmost
256 -- in the stack. Earlier entries override later one.
258 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
259 getPkgDatabases modify flags = do
260 -- first we determine the location of the global package config. On Windows,
261 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
262 -- location is passed to the binary using the --global-config flag by the
264 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
266 case [ f | FlagGlobalConfig f <- flags ] of
267 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
269 Nothing -> die err_msg
270 Just dir -> return (dir `joinFileName` "package.conf")
271 fs -> return (last fs)
273 -- get the location of the user package database, and create it if necessary
274 appdir <- getAppUserDataDirectory "ghc"
277 subdir = targetARCH ++ '-':targetOS ++ '-':version
278 archdir = appdir `joinFileName` subdir
279 user_conf = archdir `joinFileName` "package.conf"
280 user_exists <- doesFileExist user_conf
283 -- The semantics here are slightly strange. If we are
284 -- *modifying* the database, then the default is to modify
285 -- the global database by default, unless you say --user.
286 -- If we are not modifying (eg. list, describe etc.) then
287 -- the user database is included by default.
289 | modify = foldl addDB [global_conf] flags
290 | not user_exists = foldl addDB [global_conf] flags
291 | otherwise = foldl addDB [user_conf,global_conf] flags
293 -- implement the following rules:
294 -- --user means overlap with the user database
295 -- --global means reset to just the global database
296 -- -f <file> means overlap with <file>
298 | user_conf `elem` dbs = dbs
299 | modify || user_exists = user_conf : dbs
300 addDB dbs FlagGlobal = [global_conf]
301 addDB dbs (FlagConfig f) = f : dbs
304 -- we create the user database iff (a) we're modifying, and (b) the
305 -- user asked to use it by giving the --user flag.
306 when (not user_exists && user_conf `elem` databases) $ do
307 putStrLn ("Creating user package database in " ++ user_conf)
308 createDirectoryIfMissing True archdir
309 writeFile user_conf emptyPackageConfig
311 db_stack <- mapM readParseDatabase databases
314 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
315 readParseDatabase filename = do
316 str <- readFile filename
317 let packages = read str
318 Exception.evaluate packages
319 `Exception.catch` \_ ->
320 die (filename ++ ": parse error in package config file")
321 return (filename,packages)
323 emptyPackageConfig :: String
324 emptyPackageConfig = "[]"
326 -- -----------------------------------------------------------------------------
329 registerPackage :: FilePath
330 -> [(String,String)] -- defines
332 -> Bool -- auto_ghci_libs
336 registerPackage input defines flags auto_ghci_libs update force = do
337 db_stack <- getPkgDatabases True flags
339 db_to_operate_on = my_head "db" db_stack
340 db_filename = fst db_to_operate_on
342 checkConfigAccess db_filename
347 putStr "Reading package info from stdin ... "
350 putStr ("Reading package info from " ++ show f ++ " ... ")
353 expanded <- expandEnvVars s defines force
355 pkg <- parsePackageInfo expanded defines force
358 validatePackageConfig pkg db_stack auto_ghci_libs update force
359 new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
360 savePackageConfig db_filename
361 maybeRestoreOldConfig db_filename $
362 writeNewConfig db_filename new_details
368 -> IO InstalledPackageInfo
369 parsePackageInfo str defines force =
370 case parseInstalledPackageInfo str of
371 ParseOk ok -> return ok
372 ParseFailed err -> die (showError err)
374 -- -----------------------------------------------------------------------------
375 -- Exposing, Hiding, Unregistering are all similar
377 exposePackage :: PackageIdentifier -> [Flag] -> IO ()
378 exposePackage = modifyPackage (\p -> [p{exposed=True}])
380 hidePackage :: PackageIdentifier -> [Flag] -> IO ()
381 hidePackage = modifyPackage (\p -> [p{exposed=False}])
383 unregisterPackage :: PackageIdentifier -> [Flag] -> IO ()
384 unregisterPackage = modifyPackage (\p -> [])
387 :: (InstalledPackageInfo -> [InstalledPackageInfo])
391 modifyPackage fn pkgid flags = do
392 db_stack <- getPkgDatabases True{-modify-} flags
393 let ((db_name, pkgs) : _) = db_stack
394 checkConfigAccess db_name
395 ps <- findPackages [(db_name,pkgs)] pkgid
396 let pids = map package ps
397 savePackageConfig db_name
398 let new_config = concat (map modify pkgs)
400 | package pkg `elem` pids = fn pkg
402 maybeRestoreOldConfig db_name $
403 writeNewConfig db_name new_config
405 -- -----------------------------------------------------------------------------
408 listPackages :: [Flag] -> IO ()
409 listPackages flags = do
410 db_stack <- getPkgDatabases False flags
411 mapM_ show_pkgconf (reverse db_stack)
412 where show_pkgconf (db_name,pkg_confs) =
413 hPutStrLn stdout (render $
414 text (db_name ++ ":") $$ nest 4 packages
416 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
419 | otherwise = parens doc
420 where doc = text (showPackageId (package p))
422 -- -----------------------------------------------------------------------------
425 describePackage :: [Flag] -> PackageIdentifier -> IO ()
426 describePackage flags pkgid = do
427 db_stack <- getPkgDatabases False flags
428 ps <- findPackages db_stack pkgid
429 mapM_ (putStrLn . showInstalledPackageInfo) ps
431 -- PackageId is can have globVersion for the version
432 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
433 findPackages db_stack pkgid
434 = case [ p | p <- all_pkgs, pkgid `matches` p ] of
435 [] -> die ("cannot find package " ++ showPackageId pkgid)
437 -- if the version is globVersion, then we are allowed to match
438 -- multiple packages. So eg. "Cabal-*" matches all Cabal packages,
439 -- but "Cabal" matches just one Cabal package - if there are more,
441 ps | versionTags (pkgVersion pkgid) == versionTags globVersion
444 -> die ("package " ++ showPackageId pkgid ++
445 " matches multiple packages: " ++
446 concat (intersperse ", " (
447 map (showPackageId.package) ps)))
450 = (pkgName pid == pkgName p)
451 && (pkgVersion pid == pkgVersion p || not (realVersion pid))
452 where p = package pkg
454 all_pkgs = concat (map snd db_stack)
456 -- -----------------------------------------------------------------------------
459 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
460 describeField flags pkgid field = do
461 db_stack <- getPkgDatabases False flags
462 case toField field of
463 Nothing -> die ("unknown field: " ++ field)
465 ps <- findPackages db_stack pkgid
466 mapM_ (putStrLn.fn) ps
468 toField :: String -> Maybe (InstalledPackageInfo -> String)
469 -- backwards compatibility:
470 toField "import_dirs" = Just $ strList . importDirs
471 toField "source_dirs" = Just $ strList . importDirs
472 toField "library_dirs" = Just $ strList . libraryDirs
473 toField "hs_libraries" = Just $ strList . hsLibraries
474 toField "extra_libraries" = Just $ strList . extraLibraries
475 toField "include_dirs" = Just $ strList . includeDirs
476 toField "c_includes" = Just $ strList . includes
477 toField "package_deps" = Just $ strList . map showPackageId. depends
478 toField "extra_cc_opts" = Just $ strList . ccOptions
479 toField "extra_ld_opts" = Just $ strList . ldOptions
480 toField "framework_dirs" = Just $ strList . frameworkDirs
481 toField "extra_frameworks"= Just $ strList . frameworks
482 toField s = showInstalledPackageInfoField s
484 strList :: [String] -> String
487 -- -----------------------------------------------------------------------------
488 -- Manipulating package.conf files
490 checkConfigAccess :: FilePath -> IO ()
491 checkConfigAccess filename = do
492 access <- getPermissions filename
493 when (not (writable access))
494 (die (filename ++ ": you don't have permission to modify this file"))
496 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
497 maybeRestoreOldConfig filename io
498 = io `catch` \e -> do
499 hPutStrLn stderr (show e)
500 hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
501 "configuration was being written. Attempting to \n"++
502 "restore the old configuration... ")
503 renameFile (filename ++ ".old") filename
504 hPutStrLn stdout "done."
507 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
508 writeNewConfig filename packages = do
509 hPutStr stdout "Writing new package config file... "
510 h <- openFile filename WriteMode
511 hPutStrLn h (show packages)
513 hPutStrLn stdout "done."
515 savePackageConfig :: FilePath -> IO ()
516 savePackageConfig filename = do
517 hPutStr stdout "Saving old package config file... "
518 -- mv rather than cp because we've already done an hGetContents
519 -- on this file so we won't be able to open it for writing
520 -- unless we move the old one out of the way...
521 let oldFile = filename ++ ".old"
522 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
523 when doesExist (removeFile oldFile `catch` (const $ return ()))
524 catch (renameFile filename oldFile)
526 hPutStrLn stderr (unwords [ "Unable to rename "
532 hPutStrLn stdout "done."
534 -----------------------------------------------------------------------------
535 -- Sanity-check a new package config, and automatically build GHCi libs
538 validatePackageConfig :: InstalledPackageInfo
540 -> Bool -- auto-ghc-libs
544 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
546 checkDuplicates db_stack pkg update
547 mapM_ (checkDep db_stack force) (depends pkg)
548 mapM_ (checkDir force) (importDirs pkg)
549 mapM_ (checkDir force) (libraryDirs pkg)
550 mapM_ (checkDir force) (includeDirs pkg)
551 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
552 -- ToDo: check these somehow?
553 -- extra_libraries :: [String],
554 -- c_includes :: [String],
556 -- When the package name and version are put together, sometimes we can
557 -- end up with a package id that cannot be parsed. This will lead to
558 -- difficulties when the user wants to refer to the package later, so
559 -- we check that the package id can be parsed properly here.
560 checkPackageId :: InstalledPackageInfo -> IO ()
562 let str = showPackageId (package ipi) in
563 case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
565 [] -> die ("invalid package identifier: " ++ str)
566 _ -> die ("ambiguous package identifier: " ++ str)
568 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
569 checkDuplicates db_stack pkg update = do
573 (_top_db_name, pkgs) : _ = db_stack
575 pkgs_with_same_name =
576 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
577 exposed_pkgs_with_same_name =
578 filter exposed pkgs_with_same_name
580 -- Check whether this package id already exists in this DB
582 when (not update && (package pkg `elem` map package pkgs)) $
583 die ("package " ++ showPackageId pkgid ++ " is already installed")
585 -- if we are exposing this new package, then check that
586 -- there are no other exposed packages with the same name.
588 when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
589 die ("trying to register " ++ showPackageId pkgid
590 ++ " as exposed, but "
591 ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
592 ++ " is also exposed.")
595 checkDir :: Bool -> String -> IO ()
597 | "$topdir" `isPrefixOf` d = return ()
598 -- can't check this, because we don't know what $topdir is
600 there <- doesDirectoryExist d
602 (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
604 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
605 checkDep db_stack force pkgid
606 | real_version && pkgid `elem` pkgids = return ()
607 | not real_version && pkgName pkgid `elem` pkg_names = return ()
608 | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
611 -- for backwards compat, we treat 0.0 as a special version,
612 -- and don't check that it actually exists.
613 real_version = realVersion pkgid
615 all_pkgs = concat (map snd db_stack)
616 pkgids = map package all_pkgs
617 pkg_names = map pkgName pkgids
619 realVersion :: PackageIdentifier -> Bool
620 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
622 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
623 checkHSLib dirs auto_ghci_libs force lib = do
624 let batch_lib_file = "lib" ++ lib ++ ".a"
625 bs <- mapM (doesLibExistIn batch_lib_file) dirs
626 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
627 [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
629 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
631 doesLibExistIn :: String -> String -> IO Bool
633 | "$topdir" `isPrefixOf` d = return True
634 | otherwise = doesFileExist (d ++ '/':lib)
636 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
637 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
638 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
640 bs <- mapM (doesLibExistIn ghci_lib_file) dirs
641 case [dir | (exists,dir) <- zip bs dirs, exists] of
642 [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
645 ghci_lib_file = lib ++ ".o"
647 -- automatically build the GHCi version of a batch lib,
648 -- using ld --whole-archive.
650 autoBuildGHCiLib :: String -> String -> String -> IO ()
651 autoBuildGHCiLib dir batch_file ghci_file = do
652 let ghci_lib_file = dir ++ '/':ghci_file
653 batch_lib_file = dir ++ '/':batch_file
654 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
655 #if defined(darwin_HOST_OS)
656 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
657 #elif defined(mingw32_HOST_OS)
658 execDir <- getExecDir "/bin/ghc-pkg.exe"
659 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
661 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
663 when (r /= ExitSuccess) $ exitWith r
664 hPutStrLn stderr (" done.")
666 -- -----------------------------------------------------------------------------
667 -- Updating the DB with the new package.
671 -> [InstalledPackageInfo]
672 -> InstalledPackageInfo
673 -> IO [InstalledPackageInfo]
674 updatePackageDB db_stack pkgs new_pkg = do
676 -- The input package spec is allowed to give a package dependency
677 -- without a version number; e.g.
679 -- Here, we update these dependencies without version numbers to
680 -- match the actual versions of the relevant packages installed.
681 updateDeps p = p{depends = map resolveDep (depends p)}
684 | realVersion dep_pkgid = dep_pkgid
685 | otherwise = lookupDep dep_pkgid
689 name = pkgName dep_pkgid
691 case [ pid | p <- concat (map snd db_stack),
693 pkgName pid == name ] of
694 (pid:_) -> pid -- Found installed package,
695 -- replete with its version
696 [] -> dep_pkgid -- No installed package; use
697 -- the version-less one
699 is_exposed = exposed new_pkg
700 pkgid = package new_pkg
703 pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
705 -- When update is on, and we're exposing the new package,
706 -- we hide any packages with the same name (different versions)
707 -- in the current DB. Earlier checks will have failed if
710 | is_exposed && pkgName (package p) == name = p{ exposed = False }
713 return (pkgs'++[updateDeps new_pkg])
715 -- -----------------------------------------------------------------------------
716 -- Searching for modules
720 findModules :: [FilePath] -> IO [String]
722 mms <- mapM searchDir paths
725 searchDir path prefix = do
726 fs <- getDirectoryEntries path `catch` \_ -> return []
727 searchEntries path prefix fs
729 searchEntries path prefix [] = return []
730 searchEntries path prefix (f:fs)
731 | looks_like_a_module = do
732 ms <- searchEntries path prefix fs
733 return (prefix `joinModule` f : ms)
734 | looks_like_a_component = do
735 ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
736 ms' <- searchEntries path prefix fs
739 searchEntries path prefix fs
742 (base,suffix) = splitFileExt f
743 looks_like_a_module =
744 suffix `elem` haskell_suffixes &&
745 all okInModuleName base
746 looks_like_a_component =
747 null suffix && all okInModuleName base
753 -- -----------------------------------------------------------------------------
754 -- The old command-line syntax, supported for backwards compatibility
761 | OF_Add Bool {- True => replace existing info -}
762 | OF_Remove String | OF_Show String
763 | OF_Field String | OF_AutoGHCiLibs | OF_Force
764 | OF_DefinedName String String
765 | OF_GlobalConfig FilePath
768 isAction :: OldFlag -> Bool
769 isAction OF_Config{} = False
770 isAction OF_Field{} = False
771 isAction OF_Input{} = False
772 isAction OF_AutoGHCiLibs{} = False
773 isAction OF_Force{} = False
774 isAction OF_DefinedName{} = False
775 isAction OF_GlobalConfig{} = False
778 oldFlags :: [OptDescr OldFlag]
780 Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
781 "use the specified package config file",
782 Option ['l'] ["list-packages"] (NoArg OF_List)
783 "list packages in all config files",
784 Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
785 "list packages in the specified config file",
786 Option ['a'] ["add-package"] (NoArg (OF_Add False))
788 Option ['u'] ["update-package"] (NoArg (OF_Add True))
789 "update package with new configuration",
790 Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
791 "read new package info from specified file",
792 Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
793 "show the configuration for package NAME",
794 Option [] ["field"] (ReqArg OF_Field "FIELD")
795 "(with --show-package) Show field FIELD only",
796 Option [] ["force"] (NoArg OF_Force)
797 "ignore missing directories/libraries",
798 Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
799 "remove an installed package",
800 Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
801 "automatically build libs for GHCi (with -a)",
802 Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
803 "define NAME as VALUE",
804 Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
805 "location of the global package config"
809 case break (=='=') str of
810 (nm,[]) -> OF_DefinedName nm []
811 (nm,_:val) -> OF_DefinedName nm val
813 oldRunit :: [OldFlag] -> IO ()
815 let new_flags = [ f | Just f <- map conv clis ]
817 conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
818 conv (OF_Config f) = Just (FlagConfig f)
823 let fields = [ f | OF_Field f <- clis ]
825 let auto_ghci_libs = any isAuto clis
826 where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
827 input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
829 force = OF_Force `elem` clis
831 defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
833 case [ c | c <- clis, isAction c ] of
834 [ OF_List ] -> listPackages new_flags
835 [ OF_ListLocal ] -> listPackages new_flags
837 registerPackage input_file defines new_flags auto_ghci_libs upd force
838 [ OF_Remove pkgid_str ] -> do
839 pkgid <- readPkgId pkgid_str
840 unregisterPackage pkgid new_flags
841 [ OF_Show pkgid_str ]
843 pkgid <- readPkgId pkgid_str
844 describePackage new_flags pkgid
846 pkgid <- readPkgId pkgid_str
847 mapM_ (describeField new_flags pkgid) fields
849 prog <- getProgramName
850 die (usageInfo (usageHeader prog) flags)
852 my_head :: String -> [a] -> a
853 my_head s [] = error s
856 -- ---------------------------------------------------------------------------
857 -- expanding environment variables in the package configuration
859 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
860 expandEnvVars str defines force = go str ""
862 go "" acc = return $! reverse acc
863 go ('$':'{':str) acc | (var, '}':rest) <- break close str
864 = do value <- lookupEnvVar var
865 go rest (reverse value ++ acc)
866 where close c = c == '}' || c == '\n' -- don't span newlines
870 lookupEnvVar :: String -> IO String
872 case lookup nm defines of
873 Just x | not (null x) -> return x
875 catch (System.getEnv nm)
876 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
880 -----------------------------------------------------------------------------
882 getProgramName :: IO String
883 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
884 where str `withoutSuffix` suff
885 | suff `isSuffixOf` str = take (length str - length suff) str
888 bye :: String -> IO a
889 bye s = putStr s >> exitWith ExitSuccess
891 die :: String -> IO a
894 prog <- getProgramName
895 hPutStrLn stderr (prog ++ ": " ++ s)
896 exitWith (ExitFailure 1)
898 dieOrForce :: Bool -> String -> IO ()
900 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
904 -----------------------------------------
905 -- Cut and pasted from ghc/compiler/SysTools
907 #if defined(mingw32_HOST_OS)
908 subst a b ls = map (\ x -> if x == a then b else x) ls
909 unDosifyPath xs = subst '\\' '/' xs
911 getExecDir :: String -> IO (Maybe String)
912 -- (getExecDir cmd) returns the directory in which the current
913 -- executable, which should be called 'cmd', is running
914 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
915 -- you'll get "/a/b/c" back as the result
917 = allocaArray len $ \buf -> do
918 ret <- getModuleFileName nullPtr buf len
919 if ret == 0 then return Nothing
920 else do s <- peekCString buf
921 return (Just (reverse (drop (length cmd)
922 (reverse (unDosifyPath s)))))
924 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
926 foreign import stdcall unsafe "GetModuleFileNameA"
927 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
929 getExecDir :: String -> IO (Maybe String)
930 getExecDir _ = return Nothing
933 -- -----------------------------------------------------------------------------
936 -- | The 'joinFileName' function is the opposite of 'splitFileName'.
937 -- It joins directory and file names to form a complete file path.
939 -- The general rule is:
941 -- > dir `joinFileName` basename == path
943 -- > (dir,basename) = splitFileName path
945 -- There might be an exceptions to the rule but in any case the
946 -- reconstructed path will refer to the same object (file or directory).
947 -- An example exception is that on Windows some slashes might be converted
949 joinFileName :: String -> String -> FilePath
950 joinFileName "" fname = fname
951 joinFileName "." fname = fname
952 joinFileName dir "" = dir
953 joinFileName dir fname
954 | isPathSeparator (last dir) = dir++fname
955 | otherwise = dir++pathSeparator:fname
957 -- | Checks whether the character is a valid path separator for the host
958 -- platform. The valid character is a 'pathSeparator' but since the Windows
959 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
960 -- checks for it on this platform, too.
961 isPathSeparator :: Char -> Bool
962 isPathSeparator ch = ch == pathSeparator || ch == '/'
964 -- | Provides a platform-specific character used to separate directory levels in
965 -- a path string that reflects a hierarchical file system organization. The
966 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
967 -- (@\"\\\"@) on the Windows operating system.
968 pathSeparator :: Char
969 #ifdef mingw32_HOST_OS