[project @ 2005-03-05 13:48:42 by panne]
[ghc-hetmet.git] / ghc / utils / ghc-pkg / Main.hs
1 {-# OPTIONS -fglasgow-exts #-}
2 -----------------------------------------------------------------------------
3 --
4 -- (c) The University of Glasgow 2004.
5 --
6 -- Package management tool
7 --
8 -----------------------------------------------------------------------------
9
10 -- TODO:
11 --      - validate modules
12 --      - expanding of variables in new-style package conf
13 --      - version manipulation (checking whether old version exists,
14 --        hiding old version?)
15
16 module Main (main) where
17
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 )
26
27 import Prelude
28
29 #include "../../includes/ghcconfig.h"
30
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
35 #else
36 import GetOpt
37 import Pretty
38 import qualified Exception
39 #endif
40
41 import Data.Char        ( isSpace )
42 import Monad
43 import Directory
44 import System   ( getArgs, getProgName,
45                   exitWith, ExitCode(..)
46                 )
47 import System.IO
48 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
49
50 #ifdef mingw32_HOST_OS
51 import Foreign
52
53 #if __GLASGOW_HASKELL__ >= 504
54 import Foreign.C.String
55 #else
56 import CString
57 #endif
58 #endif
59
60 -- -----------------------------------------------------------------------------
61 -- Entry point
62
63 main :: IO ()
64 main = do
65   args <- getArgs
66
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 ->
72            bye ourCopyright
73         (cli,nonopts,[]) ->
74            runit cli nonopts
75         (_,_,errors) -> tryOldCmdLine errors args
76
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
83         (cli@(_:_),[],[]) -> 
84            oldRunit cli
85         _failed -> do
86            prog <- getProgramName
87            die (concat errors ++ usageInfo (usageHeader prog) flags)
88
89 -- -----------------------------------------------------------------------------
90 -- Command-line syntax
91
92 data Flag
93   = FlagUser
94   | FlagGlobal
95   | FlagHelp
96   | FlagVersion
97   | FlagConfig  FilePath
98   | FlagGlobalConfig FilePath
99   | FlagForce
100   | FlagAutoGHCiLibs
101   deriving Eq
102
103 flags :: [OptDescr Flag]
104 flags = [
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"
121   ]
122
123 ourCopyright :: String
124 ourCopyright = "GHC package manager version " ++ version ++ "\n"
125
126 usageHeader :: String -> String
127 usageHeader prog = substProg prog $
128   "Usage:\n" ++
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" ++
133   "\n" ++
134   "  $p update {filename | -}\n" ++
135   "    Register the package, overwriting any other package with the\n" ++
136   "    same name.\n" ++
137   "\n" ++
138   "  $p unregister {pkg-id}\n" ++
139   "    Unregister the specified package.\n" ++
140   "\n" ++
141   "  $p expose {pkg-id}\n" ++
142   "    Expose the specified package.\n" ++
143   "\n" ++
144   "  $p hide {pkg-id}\n" ++
145   "    Hide the specified package.\n" ++
146   "\n" ++
147   "  $p list\n" ++
148   "    List registered packages in the global database, and also the" ++
149   "    user database if --user is given.\n" ++
150   "\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" ++
154   "    register.\n" ++
155   "\n" ++
156   "  $p field {pkg-id} {field}\n" ++
157   "    Extract the specified field of the package description for the\n" ++
158   "    specified package.\n" ++
159   "\n" ++
160   " The following optional flags are also accepted:\n"
161
162 substProg :: String -> String -> String
163 substProg _ [] = []
164 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
165 substProg prog (c:xs) = c : substProg prog xs
166
167 -- -----------------------------------------------------------------------------
168 -- Do the business
169
170 runit :: [Flag] -> [String] -> IO ()
171 runit cli nonopts = do
172   prog <- getProgramName
173   let
174         force = FlagForce `elem` cli
175         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
176   --
177   -- first, parse the command
178   case nonopts of
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
192     ["list"] -> do
193         listPackages 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
200     [] -> do
201         die ("missing command\n" ++ 
202                 usageInfo (usageHeader prog) flags)
203     (_cmd:_) -> do
204         die ("command-line syntax error\n" ++ 
205                 usageInfo (usageHeader prog) flags)
206
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
210     [x] -> return x
211     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
212
213 readPkgId :: String -> IO PackageIdentifier
214 readPkgId str = parseCheck parsePackageId str "package identifier"
215
216 readGlobPkgId :: String -> IO PackageIdentifier
217 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
218
219 parseGlobPackageId :: ReadP r PackageIdentifier
220 parseGlobPackageId = 
221   parsePackageId
222      +++
223   (do n <- parsePackageName; string "-*"
224       return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
225
226 -- globVersion means "all versions"
227 globVersion :: Version
228 globVersion = Version{ versionBranch=[], versionTags=["*"] }
229
230 -- -----------------------------------------------------------------------------
231 -- Package databases
232
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.
238 --
239 -- Some commands operate  on multiple databases, with overlapping semantics:
240 --      list, describe, field
241
242 type PackageDBName  = FilePath
243 type PackageDB      = [InstalledPackageInfo]
244
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.
248
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
254   -- wrapper script.
255   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
256   global_conf <- 
257      case [ f | FlagGlobalConfig f <- flags ] of
258         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
259                  case mb_dir of
260                         Nothing  -> die err_msg
261                         Just dir -> return (dir `joinFileName` "package.conf")
262         fs -> return (last fs)
263
264   -- get the location of the user package database, and create it if necessary
265   appdir <- getAppUserDataDirectory "ghc"
266
267   let
268         subdir = targetARCH ++ '-':targetOS ++ '-':version
269         archdir   = appdir `joinFileName` subdir
270         user_conf = archdir `joinFileName` "package.conf"
271   b <- doesFileExist user_conf
272   when (not b) $ do
273         putStrLn ("Creating user package database in " ++ user_conf)
274         createDirectoryIfMissing True archdir
275         writeFile user_conf emptyPackageConfig
276
277   let
278         -- The semantics here are slightly strange.  If we are
279         -- *modifying* the database, then the default is to modify
280         -- the global database by default, unless you say --user.
281         -- If we are not modifying (eg. list, describe etc.) then
282         -- the user database is included by default.
283         databases
284           | modify    = foldl addDB [global_conf] flags
285           | otherwise = foldl addDB [user_conf,global_conf] flags
286
287         -- implement the following rules:
288         --      --user means overlap with the user database
289         --      --global means reset to just the global database
290         --      -f <file> means overlap with <file>
291         addDB dbs FlagUser       = if user_conf `elem` dbs 
292                                         then dbs 
293                                         else user_conf : dbs
294         addDB dbs FlagGlobal     = [global_conf]
295         addDB dbs (FlagConfig f) = f : dbs
296         addDB dbs _              = dbs
297
298   db_stack <- mapM readParseDatabase databases
299   return db_stack
300
301 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
302 readParseDatabase filename = do
303   str <- readFile filename
304   let packages = read str
305   Exception.evaluate packages
306     `Exception.catch` \_ -> 
307         die (filename ++ ": parse error in package config file")
308   return (filename,packages)
309
310 emptyPackageConfig :: String
311 emptyPackageConfig = "[]"
312
313 -- -----------------------------------------------------------------------------
314 -- Registering
315
316 registerPackage :: FilePath
317                 -> [(String,String)] --  defines, ToDo: maybe remove?
318                 -> [Flag]
319                 -> Bool         -- auto_ghci_libs
320                 -> Bool         -- update
321                 -> Bool         -- force
322                 -> IO ()
323 registerPackage input defines flags auto_ghci_libs update force = do
324   db_stack <- getPkgDatabases True flags
325   let
326         db_to_operate_on = my_head "db" db_stack
327         db_filename      = fst db_to_operate_on
328   --
329   checkConfigAccess db_filename
330
331   s <-
332     case input of
333       "-" -> do
334         putStr "Reading package info from stdin... "
335         getContents
336       f   -> do
337         putStr ("Reading package info from " ++ show f ++ " ")
338         readFile f
339
340   pkg <- parsePackageInfo s defines force
341   putStrLn "done."
342
343   validatePackageConfig pkg db_stack auto_ghci_libs update force
344   new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
345   savePackageConfig db_filename
346   maybeRestoreOldConfig db_filename $
347     writeNewConfig db_filename new_details
348
349 parsePackageInfo
350         :: String
351         -> [(String,String)]
352         -> Bool
353         -> IO InstalledPackageInfo
354 parsePackageInfo str defines force =
355   case parseInstalledPackageInfo str of
356     ParseOk ok -> return ok
357     ParseFailed err -> die (showError err)
358
359 -- -----------------------------------------------------------------------------
360 -- Exposing, Hiding, Unregistering are all similar
361
362 exposePackage :: PackageIdentifier ->  [Flag] -> IO ()
363 exposePackage = modifyPackage (\p -> [p{exposed=True}])
364
365 hidePackage :: PackageIdentifier ->  [Flag] -> IO ()
366 hidePackage = modifyPackage (\p -> [p{exposed=False}])
367
368 unregisterPackage :: PackageIdentifier ->  [Flag] -> IO ()
369 unregisterPackage = modifyPackage (\p -> [])
370
371 modifyPackage
372   :: (InstalledPackageInfo -> [InstalledPackageInfo])
373   -> PackageIdentifier
374   -> [Flag]
375   -> IO ()
376 modifyPackage fn pkgid flags  = do
377   db_stack <- getPkgDatabases True{-modify-} flags
378   let ((db_name, pkgs) : _) = db_stack
379   checkConfigAccess db_name
380   ps <- findPackages [(db_name,pkgs)] pkgid
381   let pids = map package ps
382   savePackageConfig db_name
383   let new_config = concat (map modify pkgs)
384       modify pkg
385           | package pkg `elem` pids = fn pkg
386           | otherwise               = [pkg]
387   maybeRestoreOldConfig db_name $
388       writeNewConfig db_name new_config
389
390 -- -----------------------------------------------------------------------------
391 -- Listing packages
392
393 listPackages ::  [Flag] -> IO ()
394 listPackages flags = do
395   db_stack <- getPkgDatabases False flags
396   mapM_ show_pkgconf (reverse db_stack)
397   where show_pkgconf (db_name,pkg_confs) =
398           hPutStrLn stdout (render $
399                 text (db_name ++ ":") $$ nest 4 packages
400                 )
401            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
402                  pp_pkg p
403                    | exposed p = doc
404                    | otherwise = parens doc
405                    where doc = text (showPackageId (package p))
406
407 -- -----------------------------------------------------------------------------
408 -- Describe
409
410 describePackage :: [Flag] -> PackageIdentifier -> IO ()
411 describePackage flags pkgid = do
412   db_stack <- getPkgDatabases False flags
413   ps <- findPackages db_stack pkgid
414   mapM_ (putStrLn . showInstalledPackageInfo) ps
415
416 -- PackageId is can have globVersion for the version
417 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
418 findPackages db_stack pkgid
419   = case [ p | p <- all_pkgs, pkgid `matches` p ] of
420         []  -> die ("cannot find package " ++ showPackageId pkgid)
421         [p] -> return [p]
422          -- if the version is globVersion, then we are allowed to match
423          -- multiple packages.  So eg. "Cabal-*" matches all Cabal packages,
424          -- but "Cabal" matches just one Cabal package - if there are more,
425          -- you get an error.
426         ps | versionTags (pkgVersion pkgid) == versionTags globVersion
427            -> return ps
428            | otherwise
429            -> die ("package " ++ showPackageId pkgid ++ 
430                         " matches multiple packages: " ++ 
431                         concat (intersperse ", " (
432                                  map (showPackageId.package) ps)))
433   where
434         pid `matches` pkg
435           = (pkgName pid == pkgName p)
436             && (pkgVersion pid == pkgVersion p || not (realVersion pid))
437           where p = package pkg
438
439         all_pkgs = concat (map snd db_stack)
440
441 -- -----------------------------------------------------------------------------
442 -- Field
443
444 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
445 describeField flags pkgid field = do
446   db_stack <- getPkgDatabases False flags
447   case toField field of
448     Nothing -> die ("unknown field: " ++ field)
449     Just fn -> do
450         ps <- findPackages db_stack pkgid 
451         mapM_ (putStrLn.fn) ps
452
453 toField :: String -> Maybe (InstalledPackageInfo -> String)
454 -- backwards compatibility:
455 toField "import_dirs"     = Just $ strList . importDirs
456 toField "source_dirs"     = Just $ strList . importDirs
457 toField "library_dirs"    = Just $ strList . libraryDirs
458 toField "hs_libraries"    = Just $ strList . hsLibraries
459 toField "extra_libraries" = Just $ strList . extraLibraries
460 toField "include_dirs"    = Just $ strList . includeDirs
461 toField "c_includes"      = Just $ strList . includes
462 toField "package_deps"    = Just $ strList . map showPackageId. depends
463 toField "extra_cc_opts"   = Just $ strList . ccOptions
464 toField "extra_ld_opts"   = Just $ strList . ldOptions
465 toField "framework_dirs"  = Just $ strList . frameworkDirs  
466 toField "extra_frameworks"= Just $ strList . frameworks  
467 toField s                 = showInstalledPackageInfoField s
468
469 strList :: [String] -> String
470 strList = show
471
472 -- -----------------------------------------------------------------------------
473 -- Manipulating package.conf files
474
475 checkConfigAccess :: FilePath -> IO ()
476 checkConfigAccess filename = do
477   access <- getPermissions filename
478   when (not (writable access))
479       (die (filename ++ ": you don't have permission to modify this file"))
480
481 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
482 maybeRestoreOldConfig filename io
483   = io `catch` \e -> do
484         hPutStrLn stderr (show e)
485         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
486                           "configuration was being written.  Attempting to \n"++
487                           "restore the old configuration... ")
488         renameFile (filename ++ ".old")  filename
489         hPutStrLn stdout "done."
490         ioError e
491
492 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
493 writeNewConfig filename packages = do
494   hPutStr stdout "Writing new package config file... "
495   h <- openFile filename WriteMode
496   hPutStrLn h (show packages)
497   hClose h
498   hPutStrLn stdout "done."
499
500 savePackageConfig :: FilePath -> IO ()
501 savePackageConfig filename = do
502   hPutStr stdout "Saving old package config file... "
503     -- mv rather than cp because we've already done an hGetContents
504     -- on this file so we won't be able to open it for writing
505     -- unless we move the old one out of the way...
506   let oldFile = filename ++ ".old"
507   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
508   when doesExist (removeFile oldFile `catch` (const $ return ()))
509   catch (renameFile filename oldFile)
510         (\ err -> do
511                 hPutStrLn stderr (unwords [ "Unable to rename "
512                                           , show filename
513                                           , " to "
514                                           , show oldFile
515                                           ])
516                 ioError err)
517   hPutStrLn stdout "done."
518
519 -----------------------------------------------------------------------------
520 -- Sanity-check a new package config, and automatically build GHCi libs
521 -- if requested.
522
523 validatePackageConfig :: InstalledPackageInfo
524                       -> PackageDBStack
525                       -> Bool   -- auto-ghc-libs
526                       -> Bool   -- update
527                       -> Bool   -- force
528                       -> IO ()
529 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
530   checkPackageId pkg
531   checkDuplicates db_stack pkg update
532   mapM_ (checkDep db_stack force) (depends pkg)
533   mapM_ (checkDir force) (importDirs pkg)
534   mapM_ (checkDir force) (libraryDirs pkg)
535   mapM_ (checkDir force) (includeDirs pkg)
536   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
537   -- ToDo: check these somehow?
538   --    extra_libraries :: [String],
539   --    c_includes      :: [String],
540
541 -- When the package name and version are put together, sometimes we can
542 -- end up with a package id that cannot be parsed.  This will lead to 
543 -- difficulties when the user wants to refer to the package later, so
544 -- we check that the package id can be parsed properly here.
545 checkPackageId :: InstalledPackageInfo -> IO ()
546 checkPackageId ipi =
547   let str = showPackageId (package ipi) in
548   case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
549     [_] -> return ()
550     []  -> die ("invalid package identifier: " ++ str)
551     _   -> die ("ambiguous package identifier: " ++ str)
552
553 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
554 checkDuplicates db_stack pkg update = do
555   let
556         pkgid = package pkg
557
558         (_top_db_name, pkgs) : _  = db_stack
559
560         pkgs_with_same_name = 
561                 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
562         exposed_pkgs_with_same_name =
563                 filter exposed pkgs_with_same_name
564   --
565   -- Check whether this package id already exists in this DB
566   --
567   when (not update && (package pkg `elem` map package pkgs)) $
568        die ("package " ++ showPackageId pkgid ++ " is already installed")
569   --
570   -- if we are exposing this new package, then check that
571   -- there are no other exposed packages with the same name.
572   --
573   when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
574         die ("trying to register " ++ showPackageId pkgid 
575                   ++ " as exposed, but "
576                   ++ showPackageId (package (my_head "when" exposed_pkgs_with_same_name))
577                   ++ " is also exposed.")
578
579
580 checkDir :: Bool -> String -> IO ()
581 checkDir force d
582  | "$topdir" `isPrefixOf` d = return ()
583         -- can't check this, because we don't know what $topdir is
584  | otherwise = do
585    there <- doesDirectoryExist d
586    when (not there)
587        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
588
589 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
590 checkDep db_stack force pkgid
591   | real_version && pkgid `elem` pkgids = return ()
592   | not real_version && pkgName pkgid `elem` pkg_names = return ()
593   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
594                                         ++ " doesn't exist")
595   where
596         -- for backwards compat, we treat 0.0 as a special version,
597         -- and don't check that it actually exists.
598         real_version = realVersion pkgid
599         
600         all_pkgs = concat (map snd db_stack)
601         pkgids = map package all_pkgs
602         pkg_names = map pkgName pkgids
603
604 realVersion :: PackageIdentifier -> Bool
605 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
606
607 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
608 checkHSLib dirs auto_ghci_libs force lib = do
609   let batch_lib_file = "lib" ++ lib ++ ".a"
610   bs <- mapM (doesLibExistIn batch_lib_file) dirs
611   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
612         [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
613                                  " on library path") 
614         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
615
616 doesLibExistIn :: String -> String -> IO Bool
617 doesLibExistIn lib d
618  | "$topdir" `isPrefixOf` d = return True
619  | otherwise                = doesFileExist (d ++ '/':lib)
620
621 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
622 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
623   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
624   | otherwise  = do
625       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
626       case [dir | (exists,dir) <- zip bs dirs, exists] of
627         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
628         (_:_) -> return ()
629   where
630     ghci_lib_file = lib ++ ".o"
631
632 -- automatically build the GHCi version of a batch lib, 
633 -- using ld --whole-archive.
634
635 autoBuildGHCiLib :: String -> String -> String -> IO ()
636 autoBuildGHCiLib dir batch_file ghci_file = do
637   let ghci_lib_file  = dir ++ '/':ghci_file
638       batch_lib_file = dir ++ '/':batch_file
639   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
640 #if defined(darwin_HOST_OS)
641   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
642 #elif defined(mingw32_HOST_OS)
643   execDir <- getExecDir "/bin/ghc-pkg.exe"
644   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
645 #else
646   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
647 #endif
648   when (r /= ExitSuccess) $ exitWith r
649   hPutStrLn stderr (" done.")
650
651 -- -----------------------------------------------------------------------------
652 -- Updating the DB with the new package.
653
654 updatePackageDB
655         :: PackageDBStack
656         -> [InstalledPackageInfo]
657         -> InstalledPackageInfo
658         -> IO [InstalledPackageInfo]
659 updatePackageDB db_stack pkgs new_pkg = do
660   let
661         -- The input package spec is allowed to give a package dependency
662         -- without a version number; e.g.
663         --      depends: base
664         -- Here, we update these dependencies without version numbers to
665         -- match the actual versions of the relevant packages installed.
666         updateDeps p = p{depends = map resolveDep (depends p)}
667
668         resolveDep dep_pkgid
669            | realVersion dep_pkgid  = dep_pkgid
670            | otherwise              = lookupDep dep_pkgid
671
672         lookupDep dep_pkgid
673            = let 
674                 name = pkgName dep_pkgid
675              in
676              case [ pid | p <- concat (map snd db_stack), 
677                           let pid = package p,
678                           pkgName pid == name ] of
679                 (pid:_) -> pid          -- Found installed package,
680                                         -- replete with its version
681                 []      -> dep_pkgid    -- No installed package; use 
682                                         -- the version-less one
683
684         is_exposed = exposed new_pkg
685         pkgid      = package new_pkg
686         name       = pkgName pkgid
687
688         pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
689         
690         -- When update is on, and we're exposing the new package,
691         -- we hide any packages with the same name (different versions)
692         -- in the current DB.  Earlier checks will have failed if
693         -- update isn't on.
694         maybe_hide p
695           | is_exposed && pkgName (package p) == name = p{ exposed = False }
696           | otherwise = p
697   --
698   return (pkgs'++[updateDeps new_pkg])
699
700 -- -----------------------------------------------------------------------------
701 -- Searching for modules
702
703 #if not_yet
704
705 findModules :: [FilePath] -> IO [String]
706 findModules paths = 
707   mms <- mapM searchDir paths
708   return (concat mms)
709
710 searchDir path prefix = do
711   fs <- getDirectoryEntries path `catch` \_ -> return []
712   searchEntries path prefix fs
713
714 searchEntries path prefix [] = return []
715 searchEntries path prefix (f:fs)
716   | looks_like_a_module  =  do
717         ms <- searchEntries path prefix fs
718         return (prefix `joinModule` f : ms)
719   | looks_like_a_component  =  do
720         ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
721         ms' <- searchEntries path prefix fs
722         return (ms ++ ms')      
723   | otherwise
724         searchEntries path prefix fs
725
726   where
727         (base,suffix) = splitFileExt f
728         looks_like_a_module = 
729                 suffix `elem` haskell_suffixes && 
730                 all okInModuleName base
731         looks_like_a_component =
732                 null suffix && all okInModuleName base
733
734 okInModuleName c
735
736 #endif
737
738 -- -----------------------------------------------------------------------------
739 -- The old command-line syntax, supported for backwards compatibility
740
741 data OldFlag 
742   = OF_Config FilePath
743   | OF_Input FilePath
744   | OF_List
745   | OF_ListLocal
746   | OF_Add Bool {- True => replace existing info -}
747   | OF_Remove String | OF_Show String 
748   | OF_Field String | OF_AutoGHCiLibs | OF_Force
749   | OF_DefinedName String String
750   | OF_GlobalConfig FilePath
751   deriving (Eq)
752
753 isAction :: OldFlag -> Bool
754 isAction OF_Config{}        = False
755 isAction OF_Field{}         = False
756 isAction OF_Input{}         = False
757 isAction OF_AutoGHCiLibs{}  = False
758 isAction OF_Force{}         = False
759 isAction OF_DefinedName{}   = False
760 isAction OF_GlobalConfig{}  = False
761 isAction _                  = True
762
763 oldFlags :: [OptDescr OldFlag]
764 oldFlags = [
765   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
766         "use the specified package config file",
767   Option ['l'] ["list-packages"] (NoArg OF_List)
768         "list packages in all config files",
769   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
770         "list packages in the specified config file",
771   Option ['a'] ["add-package"] (NoArg (OF_Add False))
772         "add a new package",
773   Option ['u'] ["update-package"] (NoArg (OF_Add True))
774         "update package with new configuration",
775   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
776         "read new package info from specified file",
777   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
778         "show the configuration for package NAME",
779   Option [] ["field"] (ReqArg OF_Field "FIELD")
780         "(with --show-package) Show field FIELD only",
781   Option [] ["force"] (NoArg OF_Force)
782         "ignore missing directories/libraries",
783   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
784         "remove an installed package",
785   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
786         "automatically build libs for GHCi (with -a)",
787   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
788         "define NAME as VALUE",
789   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
790         "location of the global package config"
791   ]
792  where
793   toDefined str = 
794     case break (=='=') str of
795       (nm,[]) -> OF_DefinedName nm []
796       (nm,_:val) -> OF_DefinedName nm val
797
798 oldRunit :: [OldFlag] -> IO ()
799 oldRunit clis = do
800   let new_flags = [ f | Just f <- map conv clis ]
801
802       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
803       conv (OF_Config f)       = Just (FlagConfig f)
804       conv _                   = Nothing
805
806   
807
808   let fields = [ f | OF_Field f <- clis ]
809
810   let auto_ghci_libs = any isAuto clis 
811          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
812       input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
813
814       force = OF_Force `elem` clis
815       
816       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
817
818   case [ c | c <- clis, isAction c ] of
819     [ OF_List ]      -> listPackages new_flags
820     [ OF_ListLocal ] -> listPackages new_flags
821     [ OF_Add upd ]   -> 
822         registerPackage input_file defines new_flags auto_ghci_libs upd force
823     [ OF_Remove pkgid_str ]  -> do
824         pkgid <- readPkgId pkgid_str
825         unregisterPackage pkgid new_flags
826     [ OF_Show pkgid_str ]
827         | null fields -> do
828                 pkgid <- readPkgId pkgid_str
829                 describePackage new_flags pkgid
830         | otherwise   -> do
831                 pkgid <- readPkgId pkgid_str
832                 mapM_ (describeField new_flags pkgid) fields
833     _ -> do 
834         prog <- getProgramName
835         die (usageInfo (usageHeader prog) flags)
836
837 my_head :: String -> [a] -> a
838 my_head s [] = error s
839 my_head s (x:xs) = x
840
841 -- ---------------------------------------------------------------------------
842
843 #ifdef OLD_STUFF
844 -- ToDo: reinstate
845 expandEnvVars :: PackageConfig -> [(String, String)]
846         -> Bool -> IO PackageConfig
847 expandEnvVars pkg defines force = do
848    -- permit _all_ strings to contain ${..} environment variable references,
849    -- arguably too flexible.
850   nm       <- expandString  (name pkg)
851   imp_dirs <- expandStrings (import_dirs pkg) 
852   src_dirs <- expandStrings (source_dirs pkg) 
853   lib_dirs <- expandStrings (library_dirs pkg) 
854   hs_libs  <- expandStrings (hs_libraries pkg)
855   ex_libs  <- expandStrings (extra_libraries pkg)
856   inc_dirs <- expandStrings (include_dirs pkg)
857   c_incs   <- expandStrings (c_includes pkg)
858   p_deps   <- expandStrings (package_deps pkg)
859   e_g_opts <- expandStrings (extra_ghc_opts pkg)
860   e_c_opts <- expandStrings (extra_cc_opts pkg)
861   e_l_opts <- expandStrings (extra_ld_opts pkg)
862   f_dirs   <- expandStrings (framework_dirs pkg)
863   e_frames <- expandStrings (extra_frameworks pkg)
864   return (pkg { name            = nm
865               , import_dirs     = imp_dirs
866               , source_dirs     = src_dirs
867               , library_dirs    = lib_dirs
868               , hs_libraries    = hs_libs
869               , extra_libraries = ex_libs
870               , include_dirs    = inc_dirs
871               , c_includes      = c_incs
872               , package_deps    = p_deps
873               , extra_ghc_opts  = e_g_opts
874               , extra_cc_opts   = e_c_opts
875               , extra_ld_opts   = e_l_opts
876               , framework_dirs  = f_dirs
877               , extra_frameworks= e_frames
878               })
879   where
880    expandStrings :: [String] -> IO [String]
881    expandStrings = liftM concat . mapM expandSpecial
882
883    -- Permit substitutions for list-valued variables (but only when
884    -- they occur alone), e.g., package_deps["${deps}"] where env var
885    -- (say) 'deps' is "base,haskell98,network"
886    expandSpecial :: String -> IO [String]
887    expandSpecial str =
888       let expand f = liftM f $ expandString str
889       in case splitString str of
890          [Var _] -> expand (wordsBy (== ','))
891          _ -> expand (\x -> [x])
892
893    expandString :: String -> IO String
894    expandString = liftM concat . mapM expandElem . splitString
895
896    expandElem :: Elem -> IO String
897    expandElem (String s) = return s
898    expandElem (Var v)    = lookupEnvVar v
899
900    lookupEnvVar :: String -> IO String
901    lookupEnvVar nm = 
902      case lookup nm defines of
903        Just x | not (null x) -> return x
904        _      -> 
905         catch (System.getEnv nm)
906            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
907                                         show nm)
908                       return "")
909
910 data Elem = String String | Var String
911
912 splitString :: String -> [Elem]
913 splitString "" = []
914 splitString str =
915    case break (== '$') str of
916       (pre, _:'{':xs) ->
917          case span (/= '}') xs of
918             (var, _:suf) ->
919                (if null pre then id else (String pre :)) (Var var : splitString suf)
920             _ -> [String str]   -- no closing brace
921       _ -> [String str]   -- no dollar/opening brace combo
922
923 -- wordsBy isSpace == words
924 wordsBy :: (Char -> Bool) -> String -> [String]
925 wordsBy p s = case dropWhile p s of
926   "" -> []
927   s' -> w : wordsBy p s'' where (w,s'') = break p s'
928 #endif
929
930 -----------------------------------------------------------------------------
931
932 getProgramName :: IO String
933 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
934    where str `withoutSuffix` suff
935             | suff `isSuffixOf` str = take (length str - length suff) str
936             | otherwise             = str
937
938 bye :: String -> IO a
939 bye s = putStr s >> exitWith ExitSuccess
940
941 die :: String -> IO a
942 die s = do 
943   hFlush stdout
944   prog <- getProgramName
945   hPutStrLn stderr (prog ++ ": " ++ s)
946   exitWith (ExitFailure 1)
947
948 dieOrForce :: Bool -> String -> IO ()
949 dieOrForce force s 
950   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
951   | otherwise = die s
952
953
954 -----------------------------------------
955 --      Cut and pasted from ghc/compiler/SysTools
956
957 #if defined(mingw32_HOST_OS)
958 subst a b ls = map (\ x -> if x == a then b else x) ls
959 unDosifyPath xs = subst '\\' '/' xs
960
961 getExecDir :: String -> IO (Maybe String)
962 -- (getExecDir cmd) returns the directory in which the current
963 --                  executable, which should be called 'cmd', is running
964 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
965 -- you'll get "/a/b/c" back as the result
966 getExecDir cmd
967   = allocaArray len $ \buf -> do
968         ret <- getModuleFileName nullPtr buf len
969         if ret == 0 then return Nothing
970                     else do s <- peekCString buf
971                             return (Just (reverse (drop (length cmd) 
972                                                         (reverse (unDosifyPath s)))))
973   where
974     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
975
976 foreign import stdcall unsafe  "GetModuleFileNameA"
977   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
978 #else
979 getExecDir :: String -> IO (Maybe String) 
980 getExecDir _ = return Nothing
981 #endif
982
983 -- -----------------------------------------------------------------------------
984 -- FilePath utils
985
986 -- | The 'joinFileName' function is the opposite of 'splitFileName'. 
987 -- It joins directory and file names to form a complete file path.
988 --
989 -- The general rule is:
990 --
991 -- > dir `joinFileName` basename == path
992 -- >   where
993 -- >     (dir,basename) = splitFileName path
994 --
995 -- There might be an exceptions to the rule but in any case the
996 -- reconstructed path will refer to the same object (file or directory).
997 -- An example exception is that on Windows some slashes might be converted
998 -- to backslashes.
999 joinFileName :: String -> String -> FilePath
1000 joinFileName ""  fname = fname
1001 joinFileName "." fname = fname
1002 joinFileName dir ""    = dir
1003 joinFileName dir fname
1004   | isPathSeparator (last dir) = dir++fname
1005   | otherwise                  = dir++pathSeparator:fname
1006
1007 -- | Checks whether the character is a valid path separator for the host
1008 -- platform. The valid character is a 'pathSeparator' but since the Windows
1009 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1010 -- checks for it on this platform, too.
1011 isPathSeparator :: Char -> Bool
1012 isPathSeparator ch = ch == pathSeparator || ch == '/'
1013
1014 -- | Provides a platform-specific character used to separate directory levels in
1015 -- a path string that reflects a hierarchical file system organization. The
1016 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1017 -- (@\"\\\"@) on the Windows operating system.
1018 pathSeparator :: Char
1019 #ifdef mingw32_HOST_OS
1020 pathSeparator = '\\'
1021 #else
1022 pathSeparator = '/'
1023 #endif