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