[project @ 2005-01-20 14:22:19 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 --      - 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 import System.FilePath          ( joinFileName )
29
30 import Prelude
31
32 #if __GLASGOW_HASKELL__ < 603
33 #include "config.h"
34 #endif
35
36 #if __GLASGOW_HASKELL__ >= 504
37 import System.Console.GetOpt
38 import Text.PrettyPrint
39 import qualified Control.Exception as Exception
40 #else
41 import GetOpt
42 import Pretty
43 import qualified Exception
44 #endif
45
46 import Data.Char        ( isSpace )
47 import Monad
48 import Directory
49 import System   ( getArgs, getProgName,
50                   exitWith, ExitCode(..)
51                 )
52 import System.IO
53 import Data.List ( isPrefixOf, isSuffixOf, intersperse )
54
55 #ifdef mingw32_TARGET_OS
56 import Foreign
57
58 #if __GLASGOW_HASKELL__ >= 504
59 import Foreign.C.String
60 #else
61 import CString
62 #endif
63 #endif
64
65 -- -----------------------------------------------------------------------------
66 -- Entry point
67
68 main :: IO ()
69 main = do
70   args <- getArgs
71
72   case getOpt Permute flags args of
73         (cli,_,[]) | FlagHelp `elem` cli -> do
74            prog <- getProgramName
75            bye (usageInfo (usageHeader prog) flags)
76         (cli,_,[]) | FlagVersion `elem` cli ->
77            bye ourCopyright
78         (cli,nonopts,[]) ->
79            runit cli nonopts
80         (_,_,errors) -> tryOldCmdLine errors args
81
82 -- If the new command-line syntax fails, then we try the old.  If that
83 -- fails too, then we output the original errors and the new syntax
84 -- (so the old syntax is still available, but hidden).
85 tryOldCmdLine :: [String] -> [String] -> IO ()
86 tryOldCmdLine errors args = do
87   case getOpt Permute oldFlags args of
88         (cli@(_:_),[],[]) -> 
89            oldRunit cli
90         _failed -> do
91            prog <- getProgramName
92            die (concat errors ++ usageInfo (usageHeader prog) flags)
93
94 -- -----------------------------------------------------------------------------
95 -- Command-line syntax
96
97 data Flag
98   = FlagUser
99   | FlagGlobal
100   | FlagHelp
101   | FlagVersion
102   | FlagConfig  FilePath
103   | FlagGlobalConfig FilePath
104   | FlagForce
105   | FlagAutoGHCiLibs
106   deriving Eq
107
108 flags :: [OptDescr Flag]
109 flags = [
110   Option [] ["user"] (NoArg FlagUser)
111         "use the current user's package database",
112   Option [] ["global"] (NoArg FlagGlobal)
113         "(default) use the global package database",
114   Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
115         "act upon specified package config file (only)",
116   Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
117         "location of the global package config",
118   Option [] ["force"] (NoArg FlagForce)
119         "ignore missing dependencies, directories, and libraries",
120   Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
121         "automatically build libs for GHCi (with register)",
122   Option ['?'] ["help"] (NoArg FlagHelp)
123         "display this help and exit",
124    Option ['V'] ["version"] (NoArg FlagVersion)
125         "output version information and exit"
126   ]
127
128 ourCopyright :: String
129 ourCopyright = "GHC package manager version " ++ version ++ "\n"
130
131 usageHeader :: String -> String
132 usageHeader prog = substProg prog $
133   "Usage:\n" ++
134   "  $p {--help | -?}\n" ++
135   "    Produce this usage message.\n" ++
136   "\n" ++
137   "  $p register {filename | -} [--user | --global]\n" ++
138   "    Register the package using the specified installed package\n" ++
139   "    description. The syntax for the latter is given in the $p\n" ++
140   "    documentation.\n" ++
141   "\n" ++
142   "  $p unregister {pkg-id}\n" ++
143   "    Unregister the specified package.\n" ++
144   "\n" ++
145   "  $p expose {pkg-id}\n" ++
146   "    Expose the specified package.\n" ++
147   "\n" ++
148   "  $p hide {pkg-id}\n" ++
149   "    Hide the specified package.\n" ++
150   "\n" ++
151   "  $p list [--global | --user]\n" ++
152   "    List all registered packages, both global and user (unless either\n" ++
153   "    --global or --user is specified), and both hidden and exposed.\n" ++
154   "\n" ++
155   "  $p describe {pkg-id}\n" ++
156   "    Give the registered description for the specified package. The\n" ++
157   "    description is returned in precisely the syntax required by $p\n" ++
158   "    register.\n" ++
159   "\n" ++
160   "  $p field {pkg-id} {field}\n" ++
161   "    Extract the specified field of the package description for the\n" ++
162   "    specified package.\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 = head 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 -- Used for converting versionless package names to new
344 -- PackageIdentifiers.  "Version [] []" is special: it means "no
345 -- version" or "any version"
346 pkgNameToId :: String -> PackageIdentifier
347 pkgNameToId name = PackageIdentifier name (Version [] [])
348
349 -- -----------------------------------------------------------------------------
350 -- Exposing, Hiding, Unregistering are all similar
351
352 exposePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
353 exposePackage = modifyPackage (\p -> [p{exposed=True}])
354
355 hidePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
356 hidePackage = modifyPackage (\p -> [p{exposed=False}])
357
358 unregisterPackage :: PackageIdentifier ->  PackageDBStack -> IO ()
359 unregisterPackage = modifyPackage (\p -> [])
360
361 modifyPackage
362   :: (InstalledPackageInfo -> [InstalledPackageInfo])
363   -> PackageIdentifier
364   -> PackageDBStack
365   -> IO ()
366 modifyPackage _ _ [] = error "modifyPackage"
367 modifyPackage fn pkgid ((db_name, pkgs) : _) = do
368   checkConfigAccess db_name
369   p <- findPackage [(db_name,pkgs)] pkgid
370   let pid = package p
371   savePackageConfig db_name
372   let new_config = concat (map modify pkgs)
373       modify pkg
374         | package pkg == pid = fn pkg
375         | otherwise          = [pkg]
376   maybeRestoreOldConfig db_name $
377     writeNewConfig db_name new_config
378
379 -- -----------------------------------------------------------------------------
380 -- Listing packages
381
382 listPackages ::  PackageDBStack -> IO ()
383 listPackages db_confs = do
384   mapM_ show_pkgconf (reverse db_confs)
385   where show_pkgconf (db_name,pkg_confs) =
386           hPutStrLn stdout (render $
387                 text (db_name ++ ":") $$ nest 4 packages
388                 )
389            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
390                  pp_pkg = text . showPackageId . package
391
392
393 -- -----------------------------------------------------------------------------
394 -- Describe
395
396 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
397 describePackage db_stack pkgid = do
398   p <- findPackage db_stack pkgid
399   putStrLn (showInstalledPackageInfo p)
400
401 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
402 findPackage db_stack pkgid
403   = case [ p | p <- all_pkgs, pkgid `matches` p ] of
404         []  -> die ("cannot find package " ++ showPackageId pkgid)
405         [p] -> return p
406         ps  -> die ("package " ++ showPackageId pkgid ++ 
407                         " matches multiple packages: " ++ 
408                         concat (intersperse ", " (
409                                  map (showPackageId.package) ps)))
410   where
411         all_pkgs = concat (map snd db_stack)
412
413 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
414 pid `matches` p = 
415  pid == package p || 
416  not (realVersion pid) && pkgName pid == pkgName (package p)
417
418 -- -----------------------------------------------------------------------------
419 -- Field
420
421 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
422 describeField db_stack pkgid field = do
423   case toField field of
424     Nothing -> die ("unknown field: " ++ field)
425     Just fn -> do
426         p <- findPackage db_stack pkgid 
427         putStrLn (fn p)
428
429 toField :: String -> Maybe (InstalledPackageInfo -> String)
430 -- backwards compatibility:
431 toField "import_dirs"     = Just $ strList . importDirs
432 toField "source_dirs"     = Just $ strList . importDirs
433 toField "library_dirs"    = Just $ strList . libraryDirs
434 toField "hs_libraries"    = Just $ strList . hsLibraries
435 toField "extra_libraries" = Just $ strList . extraLibraries
436 toField "include_dirs"    = Just $ strList . includeDirs
437 toField "c_includes"      = Just $ strList . includes
438 toField "package_deps"    = Just $ strList . map showPackageId. depends
439 toField "extra_cc_opts"   = Just $ strList . extraCcOpts
440 toField "extra_ld_opts"   = Just $ strList . extraLdOpts  
441 toField "framework_dirs"  = Just $ strList . frameworkDirs  
442 toField "extra_frameworks"= Just $ strList . extraFrameworks  
443 toField s                 = showInstalledPackageInfoField s
444
445 strList :: [String] -> String
446 strList = show
447
448 -- -----------------------------------------------------------------------------
449 -- Manipulating package.conf files
450
451 checkConfigAccess :: FilePath -> IO ()
452 checkConfigAccess filename = do
453   access <- getPermissions filename
454   when (not (writable access))
455       (die (filename ++ ": you don't have permission to modify this file"))
456
457 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
458 maybeRestoreOldConfig filename io
459   = io `catch` \e -> do
460         hPutStrLn stderr (show e)
461         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
462                           "configuration was being written.  Attempting to \n"++
463                           "restore the old configuration... ")
464         renameFile (filename ++ ".old")  filename
465         hPutStrLn stdout "done."
466         ioError e
467
468 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
469 writeNewConfig filename packages = do
470   hPutStr stdout "Writing new package config file... "
471   h <- openFile filename WriteMode
472   hPutStrLn h (show packages)
473   hClose h
474   hPutStrLn stdout "done."
475
476 savePackageConfig :: FilePath -> IO ()
477 savePackageConfig filename = do
478   hPutStr stdout "Saving old package config file... "
479     -- mv rather than cp because we've already done an hGetContents
480     -- on this file so we won't be able to open it for writing
481     -- unless we move the old one out of the way...
482   let oldFile = filename ++ ".old"
483   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
484   when doesExist (removeFile oldFile `catch` (const $ return ()))
485   catch (renameFile filename oldFile)
486         (\ err -> do
487                 hPutStrLn stderr (unwords [ "Unable to rename "
488                                           , show filename
489                                           , " to "
490                                           , show oldFile
491                                           ])
492                 ioError err)
493   hPutStrLn stdout "done."
494
495 -----------------------------------------------------------------------------
496 -- Sanity-check a new package config, and automatically build GHCi libs
497 -- if requested.
498
499 validatePackageConfig :: InstalledPackageInfo
500                       -> PackageDBStack
501                       -> Bool   -- auto-ghc-libs
502                       -> Bool   -- update
503                       -> Bool   -- force
504                       -> IO ()
505 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
506   checkDuplicates db_stack pkg update
507   mapM_ (checkDep db_stack force) (depends pkg)
508   mapM_ (checkDir force) (importDirs pkg)
509   mapM_ (checkDir force) (libraryDirs pkg)
510   mapM_ (checkDir force) (includeDirs pkg)
511   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
512   -- ToDo: check these somehow?
513   --    extra_libraries :: [String],
514   --    c_includes      :: [String],
515
516
517 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
518 checkDuplicates db_stack pkg update = do
519   let
520         pkgid = package pkg
521
522         (_top_db_name, pkgs) : _  = db_stack
523
524         pkgs_with_same_name = 
525                 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
526         exposed_pkgs_with_same_name =
527                 filter exposed pkgs_with_same_name
528   --
529   -- Check whether this package id already exists in this DB
530   --
531   when (not update && (package pkg `elem` map package pkgs)) $
532        die ("package " ++ showPackageId pkgid ++ " is already installed")
533   --
534   -- if we are exposing this new package, then check that
535   -- there are no other exposed packages with the same name.
536   --
537   when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
538         die ("trying to register " ++ showPackageId pkgid 
539                   ++ " as exposed, but "
540                   ++ showPackageId (package (head exposed_pkgs_with_same_name))
541                   ++ " is also exposed.")
542
543
544 checkDir :: Bool -> String -> IO ()
545 checkDir force d
546  | "$topdir" `isPrefixOf` d = return ()
547         -- can't check this, because we don't know what $topdir is
548  | otherwise = do
549    there <- doesDirectoryExist d
550    when (not there)
551        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
552
553 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
554 checkDep db_stack force pkgid
555   | real_version && pkgid `elem` pkgids = return ()
556   | not real_version && pkgName pkgid `elem` pkg_names = return ()
557   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
558                                         ++ " doesn't exist")
559   where
560         -- for backwards compat, we treat 0.0 as a special version,
561         -- and don't check that it actually exists.
562         real_version = realVersion pkgid
563         
564         all_pkgs = concat (map snd db_stack)
565         pkgids = map package all_pkgs
566         pkg_names = map pkgName pkgids
567
568 realVersion :: PackageIdentifier -> Bool
569 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
570
571 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
572 checkHSLib dirs auto_ghci_libs force lib = do
573   let batch_lib_file = "lib" ++ lib ++ ".a"
574   bs <- mapM (doesLibExistIn batch_lib_file) dirs
575   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
576         [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
577                                  " on library path") 
578         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
579
580 doesLibExistIn :: String -> String -> IO Bool
581 doesLibExistIn lib d
582  | "$topdir" `isPrefixOf` d = return True
583  | otherwise                = doesFileExist (d ++ '/':lib)
584
585 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
586 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
587   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
588   | otherwise  = do
589       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
590       case [dir | (exists,dir) <- zip bs dirs, exists] of
591         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
592         (_:_) -> return ()
593   where
594     ghci_lib_file = lib ++ ".o"
595
596 -- automatically build the GHCi version of a batch lib, 
597 -- using ld --whole-archive.
598
599 autoBuildGHCiLib :: String -> String -> String -> IO ()
600 autoBuildGHCiLib dir batch_file ghci_file = do
601   let ghci_lib_file  = dir ++ '/':ghci_file
602       batch_lib_file = dir ++ '/':batch_file
603   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
604 #if defined(darwin_TARGET_OS)
605   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
606 #elif defined(mingw32_HOST_OS)
607   execDir <- getExecDir "/bin/ghc-pkg.exe"
608   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
609 #else
610   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
611 #endif
612   when (r /= ExitSuccess) $ exitWith r
613   hPutStrLn stderr (" done.")
614
615 -- -----------------------------------------------------------------------------
616 -- Updating the DB with the new package.
617
618 updatePackageDB
619         :: PackageDBStack
620         -> [InstalledPackageInfo]
621         -> InstalledPackageInfo
622         -> IO [InstalledPackageInfo]
623 updatePackageDB db_stack pkgs new_pkg = do
624   let
625         -- we update dependencies without version numbers to
626         -- match the actual versions of the relevant packages instaled.
627         updateDeps p = p{depends = map resolveDep (depends p)}
628
629         resolveDep pkgid
630            | realVersion pkgid  = pkgid
631            | otherwise          = lookupDep (pkgName pkgid)
632         
633         lookupDep name
634            = head [ pid | p <- concat (map snd db_stack), 
635                           let pid = package p,
636                           pkgName pid == name ]
637
638         is_exposed = exposed new_pkg
639         pkgid      = package new_pkg
640         name       = pkgName pkgid
641
642         pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
643         
644         -- When update is on, and we're exposing the new package,
645         -- we hide any packages with the same name (different versions)
646         -- in the current DB.  Earlier checks will have failed if
647         -- update isn't on.
648         maybe_hide p
649           | is_exposed && pkgName (package p) == name = p{ exposed = False }
650           | otherwise = p
651   --
652   return (pkgs'++[updateDeps new_pkg])
653
654 -- -----------------------------------------------------------------------------
655 -- Searching for modules
656
657 #if not_yet
658
659 findModules :: [FilePath] -> IO [String]
660 findModules paths = 
661   mms <- mapM searchDir paths
662   return (concat mms)
663
664 searchDir path prefix = do
665   fs <- getDirectoryEntries path `catch` \_ -> return []
666   searchEntries path prefix fs
667
668 searchEntries path prefix [] = return []
669 searchEntries path prefix (f:fs)
670   | looks_like_a_module  =  do
671         ms <- searchEntries path prefix fs
672         return (prefix `joinModule` f : ms)
673   | looks_like_a_component  =  do
674         ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
675         ms' <- searchEntries path prefix fs
676         return (ms ++ ms')      
677   | otherwise
678         searchEntries path prefix fs
679
680   where
681         (base,suffix) = splitFileExt f
682         looks_like_a_module = 
683                 suffix `elem` haskell_suffixes && 
684                 all okInModuleName base
685         looks_like_a_component =
686                 null suffix && all okInModuleName base
687
688 okInModuleName c
689
690 #endif
691
692 -- -----------------------------------------------------------------------------
693 -- The old command-line syntax, supported for backwards compatibility
694
695 data OldFlag 
696   = OF_Config FilePath
697   | OF_Input FilePath
698   | OF_List
699   | OF_ListLocal
700   | OF_Add Bool {- True => replace existing info -}
701   | OF_Remove String | OF_Show String 
702   | OF_Field String | OF_AutoGHCiLibs | OF_Force
703   | OF_DefinedName String String
704   | OF_GlobalConfig FilePath
705   deriving (Eq)
706
707 isAction :: OldFlag -> Bool
708 isAction OF_Config{}        = False
709 isAction OF_Field{}         = False
710 isAction OF_Input{}         = False
711 isAction OF_AutoGHCiLibs{}  = False
712 isAction OF_Force{}         = False
713 isAction OF_DefinedName{}   = False
714 isAction OF_GlobalConfig{}  = False
715 isAction _                  = True
716
717 oldFlags :: [OptDescr OldFlag]
718 oldFlags = [
719   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
720         "use the specified package config file",
721   Option ['l'] ["list-packages"] (NoArg OF_List)
722         "list packages in all config files",
723   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
724         "list packages in the specified config file",
725   Option ['a'] ["add-package"] (NoArg (OF_Add False))
726         "add a new package",
727   Option ['u'] ["update-package"] (NoArg (OF_Add True))
728         "update package with new configuration",
729   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
730         "read new package info from specified file",
731   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
732         "show the configuration for package NAME",
733   Option [] ["field"] (ReqArg OF_Field "FIELD")
734         "(with --show-package) Show field FIELD only",
735   Option [] ["force"] (NoArg OF_Force)
736         "ignore missing directories/libraries",
737   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
738         "remove an installed package",
739   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
740         "automatically build libs for GHCi (with -a)",
741   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
742         "define NAME as VALUE",
743   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
744         "location of the global package config"
745   ]
746  where
747   toDefined str = 
748     case break (=='=') str of
749       (nm,[]) -> OF_DefinedName nm []
750       (nm,_:val) -> OF_DefinedName nm val
751
752 oldRunit :: [OldFlag] -> IO ()
753 oldRunit clis = do
754   let config_flags = [ f | Just f <- map conv clis ]
755
756       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
757       conv (OF_Config f)       = Just (FlagConfig f)
758       conv _                   = Nothing
759
760   db_names <- getPkgDatabases config_flags
761   db_stack <- mapM readParseDatabase db_names
762
763   let fields = [ f | OF_Field f <- clis ]
764
765   let auto_ghci_libs = any isAuto clis 
766          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
767       input_file = head ([ f | (OF_Input f) <- clis] ++ ["-"])
768
769       force = OF_Force `elem` clis
770       
771       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
772
773   case [ c | c <- clis, isAction c ] of
774     [ OF_List ]      -> listPackages db_stack
775     [ OF_ListLocal ] -> listPackages db_stack
776     [ OF_Add upd ]   -> registerPackage input_file defines db_stack
777                                 auto_ghci_libs upd force
778     [ OF_Remove p ]  -> unregisterPackage (pkgNameToId p) db_stack
779     [ OF_Show p ]
780         | null fields -> describePackage db_stack (pkgNameToId p)
781         | otherwise   -> mapM_ (describeField db_stack (pkgNameToId p)) fields
782     _            -> do prog <- getProgramName
783                        die (usageInfo (usageHeader prog) flags)
784
785 -- ---------------------------------------------------------------------------
786
787 #ifdef OLD_STUFF
788 -- ToDo: reinstate
789 expandEnvVars :: PackageConfig -> [(String, String)]
790         -> Bool -> IO PackageConfig
791 expandEnvVars pkg defines force = do
792    -- permit _all_ strings to contain ${..} environment variable references,
793    -- arguably too flexible.
794   nm       <- expandString  (name pkg)
795   imp_dirs <- expandStrings (import_dirs pkg) 
796   src_dirs <- expandStrings (source_dirs pkg) 
797   lib_dirs <- expandStrings (library_dirs pkg) 
798   hs_libs  <- expandStrings (hs_libraries pkg)
799   ex_libs  <- expandStrings (extra_libraries pkg)
800   inc_dirs <- expandStrings (include_dirs pkg)
801   c_incs   <- expandStrings (c_includes pkg)
802   p_deps   <- expandStrings (package_deps pkg)
803   e_g_opts <- expandStrings (extra_ghc_opts pkg)
804   e_c_opts <- expandStrings (extra_cc_opts pkg)
805   e_l_opts <- expandStrings (extra_ld_opts pkg)
806   f_dirs   <- expandStrings (framework_dirs pkg)
807   e_frames <- expandStrings (extra_frameworks pkg)
808   return (pkg { name            = nm
809               , import_dirs     = imp_dirs
810               , source_dirs     = src_dirs
811               , library_dirs    = lib_dirs
812               , hs_libraries    = hs_libs
813               , extra_libraries = ex_libs
814               , include_dirs    = inc_dirs
815               , c_includes      = c_incs
816               , package_deps    = p_deps
817               , extra_ghc_opts  = e_g_opts
818               , extra_cc_opts   = e_c_opts
819               , extra_ld_opts   = e_l_opts
820               , framework_dirs  = f_dirs
821               , extra_frameworks= e_frames
822               })
823   where
824    expandStrings :: [String] -> IO [String]
825    expandStrings = liftM concat . mapM expandSpecial
826
827    -- Permit substitutions for list-valued variables (but only when
828    -- they occur alone), e.g., package_deps["${deps}"] where env var
829    -- (say) 'deps' is "base,haskell98,network"
830    expandSpecial :: String -> IO [String]
831    expandSpecial str =
832       let expand f = liftM f $ expandString str
833       in case splitString str of
834          [Var _] -> expand (wordsBy (== ','))
835          _ -> expand (\x -> [x])
836
837    expandString :: String -> IO String
838    expandString = liftM concat . mapM expandElem . splitString
839
840    expandElem :: Elem -> IO String
841    expandElem (String s) = return s
842    expandElem (Var v)    = lookupEnvVar v
843
844    lookupEnvVar :: String -> IO String
845    lookupEnvVar nm = 
846      case lookup nm defines of
847        Just x | not (null x) -> return x
848        _      -> 
849         catch (System.getEnv nm)
850            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
851                                         show nm)
852                       return "")
853
854 data Elem = String String | Var String
855
856 splitString :: String -> [Elem]
857 splitString "" = []
858 splitString str =
859    case break (== '$') str of
860       (pre, _:'{':xs) ->
861          case span (/= '}') xs of
862             (var, _:suf) ->
863                (if null pre then id else (String pre :)) (Var var : splitString suf)
864             _ -> [String str]   -- no closing brace
865       _ -> [String str]   -- no dollar/opening brace combo
866
867 -- wordsBy isSpace == words
868 wordsBy :: (Char -> Bool) -> String -> [String]
869 wordsBy p s = case dropWhile p s of
870   "" -> []
871   s' -> w : wordsBy p s'' where (w,s'') = break p s'
872 #endif
873
874 -----------------------------------------------------------------------------
875
876 getProgramName :: IO String
877 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
878    where str `withoutSuffix` suff
879             | suff `isSuffixOf` str = take (length str - length suff) str
880             | otherwise             = str
881
882 bye :: String -> IO a
883 bye s = putStr s >> exitWith ExitSuccess
884
885 die :: String -> IO a
886 die s = do 
887   hFlush stdout
888   prog <- getProgramName
889   hPutStrLn stderr (prog ++ ": " ++ s)
890   exitWith (ExitFailure 1)
891
892 dieOrForce :: Bool -> String -> IO ()
893 dieOrForce force s 
894   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
895   | otherwise = die s
896
897
898 -----------------------------------------
899 --      Cut and pasted from ghc/compiler/SysTools
900
901 #if defined(mingw32_TARGET_OS)
902 subst a b ls = map (\ x -> if x == a then b else x) ls
903 unDosifyPath xs = subst '\\' '/' xs
904
905 getExecDir :: String -> IO (Maybe String)
906 -- (getExecDir cmd) returns the directory in which the current
907 --                  executable, which should be called 'cmd', is running
908 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
909 -- you'll get "/a/b/c" back as the result
910 getExecDir cmd
911   = allocaArray len $ \buf -> do
912         ret <- getModuleFileName nullPtr buf len
913         if ret == 0 then return Nothing
914                     else do s <- peekCString buf
915                             return (Just (reverse (drop (length cmd) 
916                                                         (reverse (unDosifyPath s)))))
917   where
918     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
919
920 foreign import stdcall unsafe  "GetModuleFileNameA"
921   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
922 #else
923 getExecDir :: String -> IO (Maybe String) 
924 getExecDir _ = return Nothing
925 #endif