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