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