90faa8f13e8981d2e0fdda9ec5f9217eeb5597f9
[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, getEnv,
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   | FlagDefinedName String String
102   deriving Eq
103
104 flags :: [OptDescr Flag]
105 flags = [
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"
124   ]
125  where
126   toDefined str = 
127     case break (=='=') str of
128       (nm,[])    -> FlagDefinedName nm []
129       (nm,_:val) -> FlagDefinedName nm val
130
131 ourCopyright :: String
132 ourCopyright = "GHC package manager version " ++ version ++ "\n"
133
134 usageHeader :: String -> String
135 usageHeader prog = substProg prog $
136   "Usage:\n" ++
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" ++
141   "\n" ++
142   "  $p update {filename | -}\n" ++
143   "    Register the package, overwriting any other package with the\n" ++
144   "    same name.\n" ++
145   "\n" ++
146   "  $p unregister {pkg-id}\n" ++
147   "    Unregister the specified package.\n" ++
148   "\n" ++
149   "  $p expose {pkg-id}\n" ++
150   "    Expose the specified package.\n" ++
151   "\n" ++
152   "  $p hide {pkg-id}\n" ++
153   "    Hide the specified package.\n" ++
154   "\n" ++
155   "  $p list\n" ++
156   "    List registered packages in the global database, and also the" ++
157   "    user database if --user is given.\n" ++
158   "\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" ++
162   "    register.\n" ++
163   "\n" ++
164   "  $p field {pkg-id} {field}\n" ++
165   "    Extract the specified field of the package description for the\n" ++
166   "    specified package.\n" ++
167   "\n" ++
168   " The following optional flags are also accepted:\n"
169
170 substProg :: String -> String -> String
171 substProg _ [] = []
172 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
173 substProg prog (c:xs) = c : substProg prog xs
174
175 -- -----------------------------------------------------------------------------
176 -- Do the business
177
178 runit :: [Flag] -> [String] -> IO ()
179 runit cli nonopts = do
180   prog <- getProgramName
181   let
182         force = FlagForce `elem` cli
183         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
184         defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
185   --
186   -- first, parse the command
187   case nonopts of
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
201     ["list"] -> do
202         listPackages 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
209     [] -> do
210         die ("missing command\n" ++ 
211                 usageInfo (usageHeader prog) flags)
212     (_cmd:_) -> do
213         die ("command-line syntax error\n" ++ 
214                 usageInfo (usageHeader prog) flags)
215
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
219     [x] -> return x
220     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
221
222 readPkgId :: String -> IO PackageIdentifier
223 readPkgId str = parseCheck parsePackageId str "package identifier"
224
225 readGlobPkgId :: String -> IO PackageIdentifier
226 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
227
228 parseGlobPackageId :: ReadP r PackageIdentifier
229 parseGlobPackageId = 
230   parsePackageId
231      +++
232   (do n <- parsePackageName; string "-*"
233       return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
234
235 -- globVersion means "all versions"
236 globVersion :: Version
237 globVersion = Version{ versionBranch=[], versionTags=["*"] }
238
239 -- -----------------------------------------------------------------------------
240 -- Package databases
241
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.
247 --
248 -- Some commands operate  on multiple databases, with overlapping semantics:
249 --      list, describe, field
250
251 type PackageDBName  = FilePath
252 type PackageDB      = [InstalledPackageInfo]
253
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.
257
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
263   -- wrapper script.
264   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
265   global_conf <- 
266      case [ f | FlagGlobalConfig f <- flags ] of
267         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
268                  case mb_dir of
269                         Nothing  -> die err_msg
270                         Just dir -> return (dir `joinFileName` "package.conf")
271         fs -> return (last fs)
272
273   -- get the location of the user package database, and create it if necessary
274   appdir <- getAppUserDataDirectory "ghc"
275
276   let
277         subdir = targetARCH ++ '-':targetOS ++ '-':version
278         archdir   = appdir `joinFileName` subdir
279         user_conf = archdir `joinFileName` "package.conf"
280   user_exists <- doesFileExist user_conf
281
282   let
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.
288         databases
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
292
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>
297         addDB dbs FlagUser
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
302         addDB dbs _              = dbs
303
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
310
311   db_stack <- mapM readParseDatabase databases
312   return db_stack
313
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)
322
323 emptyPackageConfig :: String
324 emptyPackageConfig = "[]"
325
326 -- -----------------------------------------------------------------------------
327 -- Registering
328
329 registerPackage :: FilePath
330                 -> [(String,String)] -- defines
331                 -> [Flag]
332                 -> Bool         -- auto_ghci_libs
333                 -> Bool         -- update
334                 -> Bool         -- force
335                 -> IO ()
336 registerPackage input defines flags auto_ghci_libs update force = do
337   db_stack <- getPkgDatabases True flags
338   let
339         db_to_operate_on = my_head "db" db_stack
340         db_filename      = fst db_to_operate_on
341   --
342   checkConfigAccess db_filename
343
344   s <-
345     case input of
346       "-" -> do
347         putStr "Reading package info from stdin ... "
348         getContents
349       f   -> do
350         putStr ("Reading package info from " ++ show f ++ " ... ")
351         readFile f
352
353   expanded <- expandEnvVars s defines force
354
355   pkg <- parsePackageInfo expanded defines force
356   putStrLn "done."
357
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
363
364 parsePackageInfo
365         :: String
366         -> [(String,String)]
367         -> Bool
368         -> IO InstalledPackageInfo
369 parsePackageInfo str defines force =
370   case parseInstalledPackageInfo str of
371     ParseOk ok -> return ok
372     ParseFailed err -> die (showError err)
373
374 -- -----------------------------------------------------------------------------
375 -- Exposing, Hiding, Unregistering are all similar
376
377 exposePackage :: PackageIdentifier ->  [Flag] -> IO ()
378 exposePackage = modifyPackage (\p -> [p{exposed=True}])
379
380 hidePackage :: PackageIdentifier ->  [Flag] -> IO ()
381 hidePackage = modifyPackage (\p -> [p{exposed=False}])
382
383 unregisterPackage :: PackageIdentifier ->  [Flag] -> IO ()
384 unregisterPackage = modifyPackage (\p -> [])
385
386 modifyPackage
387   :: (InstalledPackageInfo -> [InstalledPackageInfo])
388   -> PackageIdentifier
389   -> [Flag]
390   -> IO ()
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)
399       modify pkg
400           | package pkg `elem` pids = fn pkg
401           | otherwise               = [pkg]
402   maybeRestoreOldConfig db_name $
403       writeNewConfig db_name new_config
404
405 -- -----------------------------------------------------------------------------
406 -- Listing packages
407
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
415                 )
416            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
417                  pp_pkg p
418                    | exposed p = doc
419                    | otherwise = parens doc
420                    where doc = text (showPackageId (package p))
421
422 -- -----------------------------------------------------------------------------
423 -- Describe
424
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
430
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)
436         [p] -> return [p]
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,
440          -- you get an error.
441         ps | versionTags (pkgVersion pkgid) == versionTags globVersion
442            -> return ps
443            | otherwise
444            -> die ("package " ++ showPackageId pkgid ++ 
445                         " matches multiple packages: " ++ 
446                         concat (intersperse ", " (
447                                  map (showPackageId.package) ps)))
448   where
449         pid `matches` pkg
450           = (pkgName pid == pkgName p)
451             && (pkgVersion pid == pkgVersion p || not (realVersion pid))
452           where p = package pkg
453
454         all_pkgs = concat (map snd db_stack)
455
456 -- -----------------------------------------------------------------------------
457 -- Field
458
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)
464     Just fn -> do
465         ps <- findPackages db_stack pkgid 
466         mapM_ (putStrLn.fn) ps
467
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
483
484 strList :: [String] -> String
485 strList = show
486
487 -- -----------------------------------------------------------------------------
488 -- Manipulating package.conf files
489
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"))
495
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."
505         ioError e
506
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)
512   hClose h
513   hPutStrLn stdout "done."
514
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)
525         (\ err -> do
526                 hPutStrLn stderr (unwords [ "Unable to rename "
527                                           , show filename
528                                           , " to "
529                                           , show oldFile
530                                           ])
531                 ioError err)
532   hPutStrLn stdout "done."
533
534 -----------------------------------------------------------------------------
535 -- Sanity-check a new package config, and automatically build GHCi libs
536 -- if requested.
537
538 validatePackageConfig :: InstalledPackageInfo
539                       -> PackageDBStack
540                       -> Bool   -- auto-ghc-libs
541                       -> Bool   -- update
542                       -> Bool   -- force
543                       -> IO ()
544 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
545   checkPackageId pkg
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],
555
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 ()
561 checkPackageId ipi =
562   let str = showPackageId (package ipi) in
563   case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
564     [_] -> return ()
565     []  -> die ("invalid package identifier: " ++ str)
566     _   -> die ("ambiguous package identifier: " ++ str)
567
568 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
569 checkDuplicates db_stack pkg update = do
570   let
571         pkgid = package pkg
572
573         (_top_db_name, pkgs) : _  = db_stack
574
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
579   --
580   -- Check whether this package id already exists in this DB
581   --
582   when (not update && (package pkg `elem` map package pkgs)) $
583        die ("package " ++ showPackageId pkgid ++ " is already installed")
584   --
585   -- if we are exposing this new package, then check that
586   -- there are no other exposed packages with the same name.
587   --
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.")
593
594
595 checkDir :: Bool -> String -> IO ()
596 checkDir force d
597  | "$topdir" `isPrefixOf` d = return ()
598         -- can't check this, because we don't know what $topdir is
599  | otherwise = do
600    there <- doesDirectoryExist d
601    when (not there)
602        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
603
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
609                                         ++ " doesn't exist")
610   where
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
614         
615         all_pkgs = concat (map snd db_stack)
616         pkgids = map package all_pkgs
617         pkg_names = map pkgName pkgids
618
619 realVersion :: PackageIdentifier -> Bool
620 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
621
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 ++
628                                  " on library path") 
629         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
630
631 doesLibExistIn :: String -> String -> IO Bool
632 doesLibExistIn lib d
633  | "$topdir" `isPrefixOf` d = return True
634  | otherwise                = doesFileExist (d ++ '/':lib)
635
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
639   | otherwise  = do
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)
643         (_:_) -> return ()
644   where
645     ghci_lib_file = lib ++ ".o"
646
647 -- automatically build the GHCi version of a batch lib, 
648 -- using ld --whole-archive.
649
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]
660 #else
661   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
662 #endif
663   when (r /= ExitSuccess) $ exitWith r
664   hPutStrLn stderr (" done.")
665
666 -- -----------------------------------------------------------------------------
667 -- Updating the DB with the new package.
668
669 updatePackageDB
670         :: PackageDBStack
671         -> [InstalledPackageInfo]
672         -> InstalledPackageInfo
673         -> IO [InstalledPackageInfo]
674 updatePackageDB db_stack pkgs new_pkg = do
675   let
676         -- The input package spec is allowed to give a package dependency
677         -- without a version number; e.g.
678         --      depends: base
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)}
682
683         resolveDep dep_pkgid
684            | realVersion dep_pkgid  = dep_pkgid
685            | otherwise              = lookupDep dep_pkgid
686
687         lookupDep dep_pkgid
688            = let 
689                 name = pkgName dep_pkgid
690              in
691              case [ pid | p <- concat (map snd db_stack), 
692                           let pid = package p,
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
698
699         is_exposed = exposed new_pkg
700         pkgid      = package new_pkg
701         name       = pkgName pkgid
702
703         pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
704         
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
708         -- update isn't on.
709         maybe_hide p
710           | is_exposed && pkgName (package p) == name = p{ exposed = False }
711           | otherwise = p
712   --
713   return (pkgs'++[updateDeps new_pkg])
714
715 -- -----------------------------------------------------------------------------
716 -- Searching for modules
717
718 #if not_yet
719
720 findModules :: [FilePath] -> IO [String]
721 findModules paths = 
722   mms <- mapM searchDir paths
723   return (concat mms)
724
725 searchDir path prefix = do
726   fs <- getDirectoryEntries path `catch` \_ -> return []
727   searchEntries path prefix fs
728
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
737         return (ms ++ ms')      
738   | otherwise
739         searchEntries path prefix fs
740
741   where
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
748
749 okInModuleName c
750
751 #endif
752
753 -- -----------------------------------------------------------------------------
754 -- The old command-line syntax, supported for backwards compatibility
755
756 data OldFlag 
757   = OF_Config FilePath
758   | OF_Input FilePath
759   | OF_List
760   | OF_ListLocal
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
766   deriving (Eq)
767
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
776 isAction _                  = True
777
778 oldFlags :: [OptDescr OldFlag]
779 oldFlags = [
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))
787         "add a new package",
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"
806   ]
807  where
808   toDefined str = 
809     case break (=='=') str of
810       (nm,[]) -> OF_DefinedName nm []
811       (nm,_:val) -> OF_DefinedName nm val
812
813 oldRunit :: [OldFlag] -> IO ()
814 oldRunit clis = do
815   let new_flags = [ f | Just f <- map conv clis ]
816
817       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
818       conv (OF_Config f)       = Just (FlagConfig f)
819       conv _                   = Nothing
820
821   
822
823   let fields = [ f | OF_Field f <- clis ]
824
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] ++ ["-"])
828
829       force = OF_Force `elem` clis
830       
831       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
832
833   case [ c | c <- clis, isAction c ] of
834     [ OF_List ]      -> listPackages new_flags
835     [ OF_ListLocal ] -> listPackages new_flags
836     [ OF_Add upd ]   -> 
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 ]
842         | null fields -> do
843                 pkgid <- readPkgId pkgid_str
844                 describePackage new_flags pkgid
845         | otherwise   -> do
846                 pkgid <- readPkgId pkgid_str
847                 mapM_ (describeField new_flags pkgid) fields
848     _ -> do 
849         prog <- getProgramName
850         die (usageInfo (usageHeader prog) flags)
851
852 my_head :: String -> [a] -> a
853 my_head s [] = error s
854 my_head s (x:xs) = x
855
856 -- ---------------------------------------------------------------------------
857 -- expanding environment variables in the package configuration
858
859 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
860 expandEnvVars str defines force = go str ""
861  where
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
867    go (c:str) acc
868         = go str (c:acc)
869
870    lookupEnvVar :: String -> IO String
871    lookupEnvVar nm = 
872      case lookup nm defines of
873        Just x | not (null x) -> return x
874        _      -> 
875         catch (System.getEnv nm)
876            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
877                                         show nm)
878                       return "")
879
880 -----------------------------------------------------------------------------
881
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
886             | otherwise             = str
887
888 bye :: String -> IO a
889 bye s = putStr s >> exitWith ExitSuccess
890
891 die :: String -> IO a
892 die s = do 
893   hFlush stdout
894   prog <- getProgramName
895   hPutStrLn stderr (prog ++ ": " ++ s)
896   exitWith (ExitFailure 1)
897
898 dieOrForce :: Bool -> String -> IO ()
899 dieOrForce force s 
900   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
901   | otherwise = die s
902
903
904 -----------------------------------------
905 --      Cut and pasted from ghc/compiler/SysTools
906
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
910
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
916 getExecDir cmd
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)))))
923   where
924     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
925
926 foreign import stdcall unsafe  "GetModuleFileNameA"
927   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
928 #else
929 getExecDir :: String -> IO (Maybe String) 
930 getExecDir _ = return Nothing
931 #endif
932
933 -- -----------------------------------------------------------------------------
934 -- FilePath utils
935
936 -- | The 'joinFileName' function is the opposite of 'splitFileName'. 
937 -- It joins directory and file names to form a complete file path.
938 --
939 -- The general rule is:
940 --
941 -- > dir `joinFileName` basename == path
942 -- >   where
943 -- >     (dir,basename) = splitFileName path
944 --
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
948 -- to backslashes.
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
956
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 == '/'
963
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
970 pathSeparator = '\\'
971 #else
972 pathSeparator = '/'
973 #endif