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