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