[project @ 2004-11-11 16:07:14 by simonmar]
[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 --      - expose/hide
13 --      - expanding of variables in new-style package conf
14 --      - version manipulation (checking whether old version exists,
15 --        hiding old version?)
16
17 module Main (main) where
18
19 import Version  ( version, targetOS, targetARCH )
20 import Distribution.InstalledPackageInfo
21 import Distribution.Compat.ReadP
22 import Distribution.Package
23 import Distribution.License
24 import Distribution.Version
25 import Compat.Directory         ( getAppUserDataDirectory )
26 import Control.Exception        ( catch, throw, evaluate )
27
28 import Prelude hiding ( catch )
29
30 import Package -- the old package config type
31
32 #if __GLASGOW_HASKELL__ < 603
33 #include "config.h"
34 #endif
35
36 #if __GLASGOW_HASKELL__ >= 504
37 import System.Console.GetOpt
38 import Text.PrettyPrint
39 import qualified Control.Exception as Exception
40 #else
41 import GetOpt
42 import Pretty
43 import qualified Exception
44 #endif
45
46 import Data.Char        ( isSpace )
47 import Monad
48 import Directory
49 import System   ( getEnv, getArgs, getProgName,
50                   system, exitWith,
51                   ExitCode(..)
52                 )
53 import IO hiding ( catch )
54 import List ( isPrefixOf, isSuffixOf )
55
56 import ParsePkgConfLite
57
58 #include "../../includes/ghcconfig.h"
59
60 #ifdef mingw32_HOST_OS
61 import Foreign
62
63 #if __GLASGOW_HASKELL__ >= 504
64 import Foreign.C.String
65 #else
66 import CString
67 #endif
68 #endif
69
70 -- -----------------------------------------------------------------------------
71 -- Entry point
72
73 main :: IO ()
74 main = do
75   args <- getArgs
76
77   case getOpt Permute flags args of
78         (cli,_,[]) | FlagHelp `elem` cli -> do
79            prog <- getProgramName
80            bye (usageInfo (usageHeader prog) flags)
81         (cli,_,[]) | FlagVersion `elem` cli ->
82            bye ourCopyright
83         (cli@(_:_),nonopts,[]) ->
84            runit cli nonopts
85         (_,_,errors) -> tryOldCmdLine errors args
86
87 -- If the new command-line syntax fails, then we try the old.  If that
88 -- fails too, then we output the original errors and the new syntax
89 -- (so the old syntax is still available, but hidden).
90 tryOldCmdLine :: [String] -> [String] -> IO ()
91 tryOldCmdLine errors args = do
92   case getOpt Permute oldFlags args of
93         (cli@(_:_),[],[]) -> 
94            oldRunit cli
95         _failed -> do
96            prog <- getProgramName
97            die (concat errors ++ usageInfo (usageHeader prog) flags)
98
99 -- -----------------------------------------------------------------------------
100 -- Command-line syntax
101
102 data Flag
103   = FlagUser
104   | FlagGlobal
105   | FlagHelp
106   | FlagVersion
107   | FlagConfig  FilePath
108   | FlagGlobalConfig FilePath
109   | FlagForce
110   deriving Eq
111
112 flags :: [OptDescr Flag]
113 flags = [
114   Option [] ["user"] (NoArg FlagUser)
115         "use the current user's package database",
116   Option [] ["global"] (NoArg FlagGlobal)
117         "(default) use the global package database",
118   Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
119         "act upon specified package config file (only)",
120   Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
121         "location of the global package config",
122   Option [] ["force"] (NoArg FlagForce)
123         "ignore missing dependencies, directories, and libraries",
124   Option ['?'] ["help"] (NoArg FlagHelp)
125         "display this help and exit",
126    Option ['V'] ["version"] (NoArg FlagVersion)
127         "output version information and exit"
128   ]
129
130 ourCopyright :: String
131 ourCopyright = "GHC package manager version " ++ version ++ "\n"
132
133 usageHeader :: String -> String
134 usageHeader prog = substProg prog $
135   "Usage:\n" ++
136   "  $p {--help | -?}\n" ++
137   "    Produce this usage message.\n" ++
138   "\n" ++
139   "  $p register {filename | -} [--user | --global]\n" ++
140   "    Register the package using the specified installed package\n" ++
141   "    description. The syntax for the latter is given in the $p\n" ++
142   "    documentation.\n" ++
143   "\n" ++
144   "  $p unregister {pkg-id}\n" ++
145   "    Unregister the specified package.\n" ++
146   "\n" ++
147   "  $p expose {pkg-id}\n" ++
148   "    Expose the specified package.\n" ++
149   "\n" ++
150   "  $p hide {pkg-id}\n" ++
151   "    Hide the specified package.\n" ++
152   "\n" ++
153   "  $p list [--global | --user]\n" ++
154   "    List all registered packages, both global and user (unless either\n" ++
155   "    --global or --user is specified), and both hidden and exposed.\n" ++
156   "\n" ++
157   "  $p describe {pkg-id}\n" ++
158   "    Give the registered description for the specified package. The\n" ++
159   "    description is returned in precisely the syntax required by $p\n" ++
160   "    register.\n" ++
161   "\n" ++
162   "  $p field {pkg-id} {field}\n" ++
163   "    Extract the specified field of the package description for the\n" ++
164   "    specified package.\n"
165
166 substProg :: String -> String -> String
167 substProg _ [] = []
168 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
169 substProg prog (c:xs) = c : substProg prog xs
170
171 -- -----------------------------------------------------------------------------
172 -- Do the business
173
174 runit :: [Flag] -> [String] -> IO ()
175 runit cli nonopts = do
176   prog <- getProgramName
177   dbs <- getPkgDatabases cli
178   db_stack <- mapM readParseDatabase dbs
179   let
180         force = FlagForce `elem` cli
181   --
182   -- first, parse the command
183   case nonopts of
184     ["register", filename] -> 
185         registerPackage filename [] db_stack False False force
186     ["update", filename] -> 
187         registerPackage filename [] db_stack False True force
188     ["unregister", pkgid_str] -> do
189         pkgid <- readPkgId pkgid_str
190         unregisterPackage db_stack pkgid
191     ["expose", pkgid_str] -> do
192         pkgid <- readPkgId pkgid_str
193         exposePackage pkgid db_stack
194     ["hide",   pkgid_str] -> do
195         pkgid <- readPkgId pkgid_str
196         hidePackage pkgid db_stack
197     ["list"] -> do
198         listPackages db_stack
199     ["describe", pkgid_str] -> do
200         pkgid <- readPkgId pkgid_str
201         describePackage db_stack pkgid
202     ["field", pkgid_str, field] -> do
203         pkgid <- readPkgId pkgid_str
204         describeField db_stack pkgid field
205     [] -> do
206         die ("missing command\n" ++ 
207                 usageInfo (usageHeader prog) flags)
208     (_cmd:_) -> do
209         die ("command-line syntax error\n" ++ 
210                 usageInfo (usageHeader prog) flags)
211
212 parseCheck :: ReadP a a -> String -> String -> IO a
213 parseCheck parser str what = 
214   case readP_to_S parser str of
215     [(x,ys)] | all isSpace ys -> return x
216     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
217
218 readPkgId :: String -> IO PackageIdentifier
219 readPkgId str = parseCheck parsePackageId str "package identifier"
220
221 -- -----------------------------------------------------------------------------
222 -- Package databases
223
224 -- Some commands operate on a single database:
225 --      register, unregister, expose, hide
226 -- however these commands also check the union of the available databases
227 -- in order to check consistency.  For example, register will check that
228 -- dependencies exist before registering a package.
229 --
230 -- Some commands operate  on multiple databases, with overlapping semantics:
231 --      list, describe, field
232
233 type PackageDBName  = FilePath
234 type PackageDB      = [InstalledPackageInfo]
235
236 type PackageDBStack = [(PackageDBName,PackageDB)]
237         -- A stack of package databases.  Convention: head is the topmost
238         -- in the stack.  Earlier entries override later one.
239
240 -- The output of this function is the list of databases to act upon, with
241 -- the "topmost" overlapped database last.  The commands which operate on a
242 -- single database will use the last one.  Commands which operate on multiple
243 -- databases will interpret the databases as overlapping.
244 getPkgDatabases :: [Flag] -> IO [PackageDBName]
245 getPkgDatabases flags = do
246   -- first we determine the location of the global package config.  On Windows,
247   -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
248   -- location is passed to the binary using the --global-config flag by the
249   -- wrapper script.
250   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
251   global_conf <- 
252      case [ f | FlagGlobalConfig f <- flags ] of
253         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
254                  case mb_dir of
255                         Nothing  -> die err_msg
256                         Just dir -> return (dir `joinFileName` "package.conf")
257         fs -> return (last fs)
258
259   -- get the location of the user package database, and create it if necessary
260   appdir <- getAppUserDataDirectory "ghc"
261
262   let
263         subdir = targetARCH ++ '-':targetOS ++ '-':version
264         user_conf = appdir `joinFileName` subdir `joinFileName` "package.conf"
265   b <- doesFileExist user_conf
266   when (not b) $ do
267         putStrLn ("Creating user package database in " ++ user_conf)
268         createParents user_conf
269         writeFile user_conf emptyPackageConfig
270
271   let
272         databases = foldl addDB [global_conf] flags
273
274         -- implement the following rules:
275         --      global database is the default
276         --      --user means overlap with the user database
277         --      --global means reset to just the global database
278         --      -f <file> means overlap with <file>
279         addDB dbs FlagUser       = user_conf : dbs
280         addDB dbs FlagGlobal     = [global_conf]
281         addDB dbs (FlagConfig f) = f : dbs
282         addDB dbs _              = dbs
283
284   return databases
285
286 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
287 readParseDatabase filename = do
288   str <- readFile filename
289   let packages = read str
290   evaluate packages
291     `catch` \_ -> die (filename ++ ": parse error in package config file\n")
292   return (filename,packages)
293
294 emptyPackageConfig :: String
295 emptyPackageConfig = "[]"
296
297 -- -----------------------------------------------------------------------------
298 -- Registering
299
300 registerPackage :: FilePath
301                 -> [(String,String)] --  defines, ToDo: maybe remove?
302                 -> PackageDBStack
303                 -> Bool         -- auto_ghci_libs
304                 -> Bool         -- update
305                 -> Bool         -- force
306                 -> IO ()
307 registerPackage input defines db_stack auto_ghci_libs update force = do
308   let
309         db_to_operate_on = head db_stack
310         db_filename      = fst db_to_operate_on
311   --
312   checkConfigAccess db_filename
313
314   s <-
315     case input of
316       "-" -> do
317         putStr "Reading package info from stdin... "
318         getContents
319       f   -> do
320         putStr ("Reading package info from " ++ show f)
321         readFile f
322
323   pkg <- parsePackageInfo s defines force
324   putStrLn "done."
325
326   validatePackageConfig pkg db_stack auto_ghci_libs update force
327   new_details <- updatePackageDB (snd db_to_operate_on) pkg
328   savePackageConfig db_filename
329   maybeRestoreOldConfig db_filename $
330     writeNewConfig db_filename new_details
331
332 parsePackageInfo
333         :: String
334         -> [(String,String)]
335         -> Bool
336         -> IO InstalledPackageInfo
337 parsePackageInfo str defines force =
338   case parseInstalledPackageInfo str of
339     Right ok -> return ok
340     Left err -> do
341         old_pkg <- evaluate (parseOnePackageConfig str)
342                             `catch` \_ -> parse_failed
343         putStr "Expanding embedded variables... "
344         new_old_pkg <- expandEnvVars old_pkg defines force
345         return (convertOldPackage old_pkg)
346  where
347    parse_failed = die "parse error in package info\n"
348
349 convertOldPackage :: PackageConfig -> InstalledPackageInfo
350 convertOldPackage
351    Package {
352         name            = name,
353         auto            = auto,
354         import_dirs     = import_dirs,
355         source_dirs     = source_dirs,
356         library_dirs    = library_dirs,
357         hs_libraries    = hs_libraries,
358         extra_libraries = extra_libraries,
359         include_dirs    = include_dirs,
360         c_includes      = c_includes,
361         package_deps    = package_deps,
362         extra_ghc_opts  = extra_ghc_opts,
363         extra_cc_opts   = extra_cc_opts,
364         extra_ld_opts   = extra_ld_opts,
365         framework_dirs  = framework_dirs,
366         extra_frameworks= extra_frameworks
367     }
368    = InstalledPackageInfo {
369         package          = pkgNameToId name,
370         license          = AllRightsReserved,
371         copyright        = "",
372         maintainer       = "",
373         author           = "",
374         stability        = "",
375         homepage         = "",
376         pkgUrl           = "",
377         description      = "",
378         category         = "",
379         exposed          = auto,
380         exposedModules   = [],
381         hiddenModules    = [],
382         importDirs       = import_dirs,
383         libraryDirs      = library_dirs,
384         hsLibraries      = hs_libraries,
385         extraLibraries   = extra_libraries,
386         includeDirs      = include_dirs,
387         includes         = c_includes,
388         depends          = map pkgNameToId package_deps,
389         extraHugsOpts    = [],
390         extraCcOpts      = extra_cc_opts,
391         extraLdOpts      = extra_ld_opts,
392         frameworkDirs    = framework_dirs,
393         extraFrameworks  = extra_frameworks,
394         haddockInterfaces = [],
395         haddockHTMLs      = []
396     }
397
398
399 -- Used for converting old versionless package names to new PackageIdentifiers.
400 -- "Version [] []" is special: it means "no version" or "any version"
401 pkgNameToId :: String -> PackageIdentifier
402 pkgNameToId name = PackageIdentifier name (Version [] [])
403
404 -- -----------------------------------------------------------------------------
405 -- Unregistering
406
407 unregisterPackage :: PackageDBStack -> PackageIdentifier -> IO ()
408 unregisterPackage [] _ = error "unregisterPackage"
409 unregisterPackage ((db_name, pkgs) : _) pkgid = do  
410   checkConfigAccess db_name
411   when (pkgid `notElem` map package pkgs)
412        (die (db_name ++ ": package '" ++ showPackageId pkgid
413                  ++ "' not found\n"))
414   savePackageConfig db_name
415   maybeRestoreOldConfig db_name $
416     writeNewConfig db_name (filter ((/= pkgid) . package) pkgs)
417
418 -- -----------------------------------------------------------------------------
419 -- Exposing
420
421 exposePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
422 exposePackage = error "TODO"
423
424 -- -----------------------------------------------------------------------------
425 -- Hiding
426
427 hidePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
428 hidePackage = error "TODO"
429
430 -- -----------------------------------------------------------------------------
431 -- Listing packages
432
433 listPackages ::  PackageDBStack -> IO ()
434 listPackages db_confs = do
435   mapM_ show_pkgconf (reverse db_confs)
436   where show_pkgconf (db_name,pkg_confs) =
437           hPutStrLn stdout (render $
438                 text (db_name ++ ":") $$ nest 4 packages
439                 )
440            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
441                  pp_pkg = text . showPackageId . package
442
443
444 -- -----------------------------------------------------------------------------
445 -- Describe
446
447 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
448 describePackage db_stack pkgid = do
449   p <- findPackage db_stack pkgid
450   putStrLn (showInstalledPackageInfo p)
451
452 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
453 findPackage db_stack pkgid
454   = case [ p | p <- all_pkgs, pkgid == package p ] of
455         [] -> die ("cannot find package " ++ showPackageId pkgid)
456         (p:ps) -> return p
457   where
458         all_pkgs = concat (map snd db_stack)
459
460 -- -----------------------------------------------------------------------------
461 -- Field
462
463 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
464 describeField db_stack pkgid field = do
465   case toField field of
466     Nothing -> die ("unknown field: " ++ field)
467     Just fn -> do
468         p <- findPackage db_stack pkgid 
469         putStrLn (fn p)
470
471 toField :: String -> Maybe (InstalledPackageInfo -> String)
472 -- backwards compatibility:
473 toField "import_dirs"     = Just $ strList . importDirs
474 toField "source_dirs"     = Just $ strList . importDirs
475 toField "library_dirs"    = Just $ strList . libraryDirs
476 toField "hs_libraries"    = Just $ strList . hsLibraries
477 toField "extra_libraries" = Just $ strList . extraLibraries
478 toField "include_dirs"    = Just $ strList . includeDirs
479 toField "c_includes"      = Just $ strList . includes
480 toField "package_deps"    = Just $ strList . map showPackageId. depends
481 toField "extra_cc_opts"   = Just $ strList . extraCcOpts
482 toField "extra_ld_opts"   = Just $ strList . extraLdOpts  
483 toField "framework_dirs"  = Just $ strList . frameworkDirs  
484 toField "extra_frameworks"= Just $ strList . extraFrameworks  
485 toField s                 = showInstalledPackageInfoField s
486
487 strList :: [String] -> String
488 strList = show
489
490 -- -----------------------------------------------------------------------------
491 -- Manipulating package.conf files
492
493 checkConfigAccess :: FilePath -> IO ()
494 checkConfigAccess filename = do
495   access <- getPermissions filename
496   when (not (writable access))
497       (die (filename ++ ": you don't have permission to modify this file\n"))
498
499 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
500 maybeRestoreOldConfig filename io
501   = io `catch` \e -> do
502         hPutStrLn stderr (show e)
503         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
504                           "configuration was being written.  Attempting to \n"++
505                           "restore the old configuration... ")
506         renameFile (filename ++ ".old")  filename
507         hPutStrLn stdout "done."
508         throw e
509
510 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
511 writeNewConfig filename packages = do
512   hPutStr stdout "Writing new package config file... "
513   h <- openFile filename WriteMode
514   hPutStrLn h (show packages)
515   hClose h
516   hPutStrLn stdout "done."
517
518 savePackageConfig :: FilePath -> IO ()
519 savePackageConfig filename = do
520   hPutStr stdout "Saving old package config file... "
521     -- mv rather than cp because we've already done an hGetContents
522     -- on this file so we won't be able to open it for writing
523     -- unless we move the old one out of the way...
524   let oldFile = filename ++ ".old"
525   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
526   when doesExist (removeFile oldFile `catch` (const $ return ()))
527   catch (renameFile filename oldFile)
528         (\ err -> do
529                 hPutStrLn stderr (unwords [ "Unable to rename "
530                                           , show filename
531                                           , " to "
532                                           , show oldFile
533                                           ])
534                 ioError err)
535   hPutStrLn stdout "done."
536
537 -----------------------------------------------------------------------------
538 -- Sanity-check a new package config, and automatically build GHCi libs
539 -- if requested.
540
541 validatePackageConfig :: InstalledPackageInfo
542                       -> PackageDBStack
543                       -> Bool   -- auto-ghc-libs
544                       -> Bool   -- update
545                       -> Bool   -- force
546                       -> IO ()
547 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
548   checkDuplicates db_stack pkg update
549   mapM_ (checkDep db_stack force) (depends pkg)
550   mapM_ (checkDir force) (importDirs pkg)
551   mapM_ (checkDir force) (libraryDirs pkg)
552   mapM_ (checkDir force) (includeDirs pkg)
553   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
554   -- ToDo: check these somehow?
555   --    extra_libraries :: [String],
556   --    c_includes      :: [String],
557
558
559 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
560 checkDuplicates db_stack pkg update = do
561   let
562         pkgid = package pkg
563
564         (_top_db_name, pkgs) : _  = db_stack
565
566         pkgs_with_same_name = 
567                 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
568         exposed_pkgs_with_same_name =
569                 filter exposed pkgs_with_same_name
570   --
571   -- Check whether this package id already exists in this DB
572   --
573   when (not update && (package pkg `elem` map package pkgs)) $
574        die ("package " ++ showPackageId pkgid ++ " is already installed\n")
575   --
576   -- if we are exposing this new package, then check that
577   -- there are no other exposed packages with the same name.
578   --
579   when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
580         die ("trying to register " ++ showPackageId pkgid 
581                   ++ " as exposed, but "
582                   ++ showPackageId (package (head exposed_pkgs_with_same_name))
583                   ++ " is also exposed.")
584
585
586 checkDir :: Bool -> String -> IO ()
587 checkDir force d
588  | "$libdir" `isPrefixOf` d = return ()
589         -- can't check this, because we don't know what $libdir is
590  | otherwise = do
591    there <- doesDirectoryExist d
592    when (not there)
593        (dieOrForce force (d ++ " doesn't exist or isn't a directory\n"))
594
595 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
596 checkDep db_stack force pkgid
597   | real_version && pkgid `elem` pkgids = return ()
598   | not real_version && pkgName pkgid `elem` pkg_names = return ()
599   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
600                                         ++ " doesn't exist\n")
601   where
602         -- for backwards compat, we treat 0.0 as a special version,
603         -- and don't check that it actually exists.
604         real_version = versionBranch (pkgVersion pkgid) /= []
605         
606         all_pkgs = concat (map snd db_stack)
607         pkgids = map package all_pkgs
608         pkg_names = map pkgName pkgids
609
610 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
611 checkHSLib dirs auto_ghci_libs force lib = do
612   let batch_lib_file = "lib" ++ lib ++ ".a"
613   bs <- mapM (doesLibExistIn batch_lib_file) dirs
614   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
615         [] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
616                                  "' on library path") 
617         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
618
619 doesLibExistIn :: String -> String -> IO Bool
620 doesLibExistIn lib d
621  | "$libdir" `isPrefixOf` d = return True
622  | otherwise                = doesFileExist (d ++ '/':lib)
623
624 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
625 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
626   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
627   | otherwise  = do
628       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
629       case [dir | (exists,dir) <- zip bs dirs, exists] of
630         []    -> hPutStrLn stderr ("warning: can't find GHCi lib `" ++ ghci_lib_file ++ "'")
631         (_:_) -> return ()
632   where
633     ghci_lib_file = lib ++ ".o"
634
635 -- automatically build the GHCi version of a batch lib, 
636 -- using ld --whole-archive.
637
638 autoBuildGHCiLib :: String -> String -> String -> IO ()
639 autoBuildGHCiLib dir batch_file ghci_file = do
640   let ghci_lib_file  = dir ++ '/':ghci_file
641       batch_lib_file = dir ++ '/':batch_file
642   hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
643 #ifdef darwin_TARGET_OS
644   system("ld -r -x -o " ++ ghci_lib_file ++ 
645          " -all_load " ++ batch_lib_file)
646 #else
647 #ifdef mingw32_HOST_OS
648   execDir <- getExecDir "/bin/ghc-pkg.exe"
649   system (maybe "" (++"/gcc-lib/") execDir++"ld -r -x -o " ++ ghci_lib_file ++ 
650          " --whole-archive " ++ batch_lib_file)
651 #else
652   system("ld -r -x -o " ++ ghci_lib_file ++ 
653          " --whole-archive " ++ batch_lib_file)
654 #endif
655 #endif
656   hPutStrLn stderr (" done.")
657
658 -- -----------------------------------------------------------------------------
659 -- Updating the DB with the new package.
660
661 updatePackageDB
662         :: [InstalledPackageInfo]
663         -> InstalledPackageInfo
664         -> IO [InstalledPackageInfo]
665 updatePackageDB pkgs new_pkg = do
666   let
667         is_exposed = exposed new_pkg
668         pkgid      = package new_pkg
669         name       = pkgName pkgid
670
671         pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
672         
673         -- When update is on, and we're exposing the new package,
674         -- we hide any packages with the same name (different versions)
675         -- in the current DB.  Earlier checks will have failed if
676         -- update isn't on.
677         maybe_hide p
678           | is_exposed && pkgName (package p) == name = p{ exposed = False }
679           | otherwise = p
680   --
681   return (pkgs'++[new_pkg])
682
683 -- -----------------------------------------------------------------------------
684 -- The old command-line syntax, supported for backwards compatibility
685
686 data OldFlag 
687   = OF_Config FilePath
688   | OF_Input FilePath
689   | OF_List
690   | OF_ListLocal
691   | OF_Add Bool {- True => replace existing info -}
692   | OF_Remove String | OF_Show String 
693   | OF_Field String | OF_AutoGHCiLibs | OF_Force
694   | OF_DefinedName String String
695   | OF_GlobalConfig FilePath
696   deriving (Eq)
697
698 isAction :: OldFlag -> Bool
699 isAction OF_Config{}        = False
700 isAction OF_Field{}         = False
701 isAction OF_Input{}         = False
702 isAction OF_AutoGHCiLibs{}  = False
703 isAction OF_Force{}         = False
704 isAction OF_DefinedName{}   = False
705 isAction OF_GlobalConfig{}  = False
706 isAction _                  = True
707
708 oldFlags :: [OptDescr OldFlag]
709 oldFlags = [
710   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
711         "use the specified package config file",
712   Option ['l'] ["list-packages"] (NoArg OF_List)
713         "list packages in all config files",
714   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
715         "list packages in the specified config file",
716   Option ['a'] ["add-package"] (NoArg (OF_Add False))
717         "add a new package",
718   Option ['u'] ["update-package"] (NoArg (OF_Add True))
719         "update package with new configuration",
720   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
721         "read new package info from specified file",
722   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
723         "show the configuration for package NAME",
724   Option [] ["field"] (ReqArg OF_Field "FIELD")
725         "(with --show-package) Show field FIELD only",
726   Option [] ["force"] (NoArg OF_Force)
727         "ignore missing directories/libraries",
728   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
729         "remove an installed package",
730   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
731         "automatically build libs for GHCi (with -a)",
732   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
733         "define NAME as VALUE",
734   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
735         "location of the global package config"
736   ]
737  where
738   toDefined str = 
739     case break (=='=') str of
740       (nm,[]) -> OF_DefinedName nm []
741       (nm,_:val) -> OF_DefinedName nm val
742
743 oldRunit :: [OldFlag] -> IO ()
744 oldRunit clis = do
745   let config_flags = [ f | Just f <- map conv clis ]
746
747       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
748       conv (OF_Config f)       = Just (FlagConfig f)
749       conv _                   = Nothing
750
751   db_names <- getPkgDatabases config_flags
752   db_stack <- mapM readParseDatabase db_names
753
754   let fields = [ f | OF_Field f <- clis ]
755
756   let auto_ghci_libs = any isAuto clis 
757          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
758       input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
759
760       force = OF_Force `elem` clis
761       
762       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
763
764   case [ c | c <- clis, isAction c ] of
765     [ OF_List ]      -> listPackages db_stack
766     [ OF_ListLocal ] -> listPackages db_stack
767     [ OF_Add upd ]   -> registerPackage input_file defines db_stack
768                                 auto_ghci_libs upd force
769     [ OF_Remove p ]  -> unregisterPackage db_stack (pkgNameToId p)
770     [ OF_Show p ]
771         | null fields -> describePackage db_stack (pkgNameToId p)
772         | otherwise   -> mapM_ (describeField db_stack (pkgNameToId p)) fields
773     _            -> do prog <- getProgramName
774                        die (usageInfo (usageHeader prog) flags)
775
776 -- ---------------------------------------------------------------------------
777
778 expandEnvVars :: PackageConfig -> [(String, String)]
779         -> Bool -> IO PackageConfig
780 expandEnvVars pkg defines force = do
781    -- permit _all_ strings to contain ${..} environment variable references,
782    -- arguably too flexible.
783   nm       <- expandString  (name pkg)
784   imp_dirs <- expandStrings (import_dirs pkg) 
785   src_dirs <- expandStrings (source_dirs pkg) 
786   lib_dirs <- expandStrings (library_dirs pkg) 
787   hs_libs  <- expandStrings (hs_libraries pkg)
788   ex_libs  <- expandStrings (extra_libraries pkg)
789   inc_dirs <- expandStrings (include_dirs pkg)
790   c_incs   <- expandStrings (c_includes pkg)
791   p_deps   <- expandStrings (package_deps pkg)
792   e_g_opts <- expandStrings (extra_ghc_opts pkg)
793   e_c_opts <- expandStrings (extra_cc_opts pkg)
794   e_l_opts <- expandStrings (extra_ld_opts pkg)
795   f_dirs   <- expandStrings (framework_dirs pkg)
796   e_frames <- expandStrings (extra_frameworks pkg)
797   return (pkg { name            = nm
798               , import_dirs     = imp_dirs
799               , source_dirs     = src_dirs
800               , library_dirs    = lib_dirs
801               , hs_libraries    = hs_libs
802               , extra_libraries = ex_libs
803               , include_dirs    = inc_dirs
804               , c_includes      = c_incs
805               , package_deps    = p_deps
806               , extra_ghc_opts  = e_g_opts
807               , extra_cc_opts   = e_c_opts
808               , extra_ld_opts   = e_l_opts
809               , framework_dirs  = f_dirs
810               , extra_frameworks= e_frames
811               })
812   where
813    expandStrings :: [String] -> IO [String]
814    expandStrings = liftM concat . mapM expandSpecial
815
816    -- Permit substitutions for list-valued variables (but only when
817    -- they occur alone), e.g., package_deps["${deps}"] where env var
818    -- (say) 'deps' is "base,haskell98,network"
819    expandSpecial :: String -> IO [String]
820    expandSpecial str =
821       let expand f = liftM f $ expandString str
822       in case splitString str of
823          [Var _] -> expand (wordsBy (== ','))
824          _ -> expand (\x -> [x])
825
826    expandString :: String -> IO String
827    expandString = liftM concat . mapM expandElem . splitString
828
829    expandElem :: Elem -> IO String
830    expandElem (String s) = return s
831    expandElem (Var v)    = lookupEnvVar v
832
833    lookupEnvVar :: String -> IO String
834    lookupEnvVar nm = 
835      case lookup nm defines of
836        Just x | not (null x) -> return x
837        _      -> 
838         catch (System.getEnv nm)
839            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
840                                         show nm)
841                       return "")
842
843 data Elem = String String | Var String
844
845 splitString :: String -> [Elem]
846 splitString "" = []
847 splitString str =
848    case break (== '$') str of
849       (pre, _:'{':xs) ->
850          case span (/= '}') xs of
851             (var, _:suf) ->
852                (if null pre then id else (String pre :)) (Var var : splitString suf)
853             _ -> [String str]   -- no closing brace
854       _ -> [String str]   -- no dollar/opening brace combo
855
856 -- wordsBy isSpace == words
857 wordsBy :: (Char -> Bool) -> String -> [String]
858 wordsBy p s = case dropWhile p s of
859   "" -> []
860   s' -> w : wordsBy p s'' where (w,s'') = break p s'
861
862 -----------------------------------------------------------------------------
863
864 getProgramName :: IO String
865 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
866    where str `withoutSuffix` suff
867             | suff `isSuffixOf` str = take (length str - length suff) str
868             | otherwise             = str
869
870 bye :: String -> IO a
871 bye s = putStr s >> exitWith ExitSuccess
872
873 die :: String -> IO a
874 die s = do 
875   hFlush stdout
876   prog <- getProgramName
877   hPutStr stderr (prog ++ ": " ++ s)
878   exitWith (ExitFailure 1)
879
880 dieOrForce :: Bool -> String -> IO ()
881 dieOrForce force s 
882   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
883   | otherwise = die (s ++ "\n")
884
885
886 -----------------------------------------------------------------------------
887 -- Create a hierarchy of directories
888
889 createParents :: FilePath -> IO ()
890 createParents dir = do
891   let parent = directoryOf dir
892   b <- doesDirectoryExist parent
893   when (not b) $ do
894         createParents parent
895         createDirectory parent
896
897 -----------------------------------------
898 --      Cut and pasted from ghc/compiler/SysTools
899
900 #if defined(mingw32_HOST_OS)
901 subst a b ls = map (\ x -> if x == a then b else x) ls
902 unDosifyPath xs = subst '\\' '/' xs
903
904 getExecDir :: String -> IO (Maybe String)
905 -- (getExecDir cmd) returns the directory in which the current
906 --                  executable, which should be called 'cmd', is running
907 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
908 -- you'll get "/a/b/c" back as the result
909 getExecDir cmd
910   = allocaArray len $ \buf -> do
911         ret <- getModuleFileName nullPtr buf len
912         if ret == 0 then return Nothing
913                     else do s <- peekCString buf
914                             return (Just (reverse (drop (length cmd) 
915                                                         (reverse (unDosifyPath s)))))
916   where
917     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
918
919 foreign import stdcall unsafe  "GetModuleFileNameA"
920   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
921 #else
922 getExecDir :: String -> IO (Maybe String) 
923 getExecDir _ = return Nothing
924 #endif
925
926 -- -----------------------------------------------------------------------------
927 -- Utils from Krasimir's FilePath library, copied here for now
928
929 directoryOf :: FilePath -> FilePath
930 directoryOf = fst.splitFileName
931
932 splitFileName :: FilePath -> (String, String)
933 splitFileName p = (reverse (path2++drive), reverse fname)
934   where
935 #ifdef mingw32_TARGET_OS
936     (path,drive) = break (== ':') (reverse p)
937 #else
938     (path,drive) = (reverse p,"")
939 #endif
940     (fname,path1) = break isPathSeparator path
941     path2 = case path1 of
942       []                           -> "."
943       [_]                          -> path1   -- don't remove the trailing slash if 
944                                               -- there is only one character
945       (c:path) | isPathSeparator c -> path
946       _                            -> path1
947
948 joinFileName :: String -> String -> FilePath
949 joinFileName ""  fname = fname
950 joinFileName "." fname = fname
951 joinFileName dir fname
952   | isPathSeparator (last dir) = dir++fname
953   | otherwise                  = dir++pathSeparator:fname
954
955 isPathSeparator :: Char -> Bool
956 isPathSeparator ch =
957 #ifdef mingw32_TARGET_OS
958   ch == '/' || ch == '\\'
959 #else
960   ch == '/'
961 #endif
962
963 pathSeparator :: Char
964 #ifdef mingw32_TARGET_OS
965 pathSeparator = '\\'
966 #else
967 pathSeparator = '/'
968 #endif