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