[project @ 2005-01-21 11:04:39 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 register {filename | -}\n" ++
135   "    Register the package using the specified installed package\n" ++
136   "    description. The syntax for the latter is given in the $p\n" ++
137   "    documentation.\n" ++
138   "\n" ++
139   "  $p update {filename | -}\n" ++
140   "    Register the package, overwriting any other package with the\n" ++
141   "    same name.\n" ++
142   "\n" ++
143   "  $p unregister {pkg-id}\n" ++
144   "    Unregister the specified package.\n" ++
145   "\n" ++
146   "  $p expose {pkg-id}\n" ++
147   "    Expose the specified package.\n" ++
148   "\n" ++
149   "  $p hide {pkg-id}\n" ++
150   "    Hide the specified package.\n" ++
151   "\n" ++
152   "  $p list\n" ++
153   "    List all registered packages, both global and user (unless either\n" ++
154   "    --global or --user is specified), and both hidden and exposed.\n" ++
155   "\n" ++
156   "  $p describe {pkg-id}\n" ++
157   "    Give the registered description for the specified package. The\n" ++
158   "    description is returned in precisely the syntax required by $p\n" ++
159   "    register.\n" ++
160   "\n" ++
161   "  $p field {pkg-id} {field}\n" ++
162   "    Extract the specified field of the package description for the\n" ++
163   "    specified package.\n" ++
164   "\n" ++
165   " The following optional flags are also accepted:\n"
166
167 substProg :: String -> String -> String
168 substProg _ [] = []
169 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
170 substProg prog (c:xs) = c : substProg prog xs
171
172 -- -----------------------------------------------------------------------------
173 -- Do the business
174
175 runit :: [Flag] -> [String] -> IO ()
176 runit cli nonopts = do
177   prog <- getProgramName
178   dbs <- getPkgDatabases cli
179   db_stack <- mapM readParseDatabase dbs
180   let
181         force = FlagForce `elem` cli
182         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
183   --
184   -- first, parse the command
185   case nonopts of
186     ["register", filename] -> 
187         registerPackage filename [] db_stack auto_ghci_libs False force
188     ["update", filename] -> 
189         registerPackage filename [] db_stack auto_ghci_libs True force
190     ["unregister", pkgid_str] -> do
191         pkgid <- readPkgId pkgid_str
192         unregisterPackage pkgid db_stack
193     ["expose", pkgid_str] -> do
194         pkgid <- readPkgId pkgid_str
195         exposePackage pkgid db_stack
196     ["hide",   pkgid_str] -> do
197         pkgid <- readPkgId pkgid_str
198         hidePackage pkgid db_stack
199     ["list"] -> do
200         listPackages db_stack
201     ["describe", pkgid_str] -> do
202         pkgid <- readPkgId pkgid_str
203         describePackage db_stack pkgid
204     ["field", pkgid_str, field] -> do
205         pkgid <- readPkgId pkgid_str
206         describeField db_stack pkgid field
207     [] -> do
208         die ("missing command\n" ++ 
209                 usageInfo (usageHeader prog) flags)
210     (_cmd:_) -> do
211         die ("command-line syntax error\n" ++ 
212                 usageInfo (usageHeader prog) flags)
213
214 parseCheck :: ReadP a a -> String -> String -> IO a
215 parseCheck parser str what = 
216   case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
217     [x] -> return x
218     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
219
220 readPkgId :: String -> IO PackageIdentifier
221 readPkgId str = parseCheck parsePackageId str "package identifier"
222
223 -- -----------------------------------------------------------------------------
224 -- Package databases
225
226 -- Some commands operate on a single database:
227 --      register, unregister, expose, hide
228 -- however these commands also check the union of the available databases
229 -- in order to check consistency.  For example, register will check that
230 -- dependencies exist before registering a package.
231 --
232 -- Some commands operate  on multiple databases, with overlapping semantics:
233 --      list, describe, field
234
235 type PackageDBName  = FilePath
236 type PackageDB      = [InstalledPackageInfo]
237
238 type PackageDBStack = [(PackageDBName,PackageDB)]
239         -- A stack of package databases.  Convention: head is the topmost
240         -- in the stack.  Earlier entries override later one.
241
242 -- The output of this function is the list of databases to act upon, with
243 -- the "topmost" overlapped database last.  The commands which operate on a
244 -- single database will use the last one.  Commands which operate on multiple
245 -- databases will interpret the databases as overlapping.
246 getPkgDatabases :: [Flag] -> IO [PackageDBName]
247 getPkgDatabases flags = do
248   -- first we determine the location of the global package config.  On Windows,
249   -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
250   -- location is passed to the binary using the --global-config flag by the
251   -- wrapper script.
252   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
253   global_conf <- 
254      case [ f | FlagGlobalConfig f <- flags ] of
255         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
256                  case mb_dir of
257                         Nothing  -> die err_msg
258                         Just dir -> return (dir `joinFileName` "package.conf")
259         fs -> return (last fs)
260
261   -- get the location of the user package database, and create it if necessary
262   appdir <- getAppUserDataDirectory "ghc"
263
264   let
265         subdir = targetARCH ++ '-':targetOS ++ '-':version
266         archdir   = appdir `joinFileName` subdir
267         user_conf = archdir `joinFileName` "package.conf"
268   b <- doesFileExist user_conf
269   when (not b) $ do
270         putStrLn ("Creating user package database in " ++ user_conf)
271         createDirectoryIfMissing True archdir
272         writeFile user_conf emptyPackageConfig
273
274   let
275         databases = foldl addDB [global_conf] flags
276
277         -- implement the following rules:
278         --      global database is the default
279         --      --user means overlap with the user database
280         --      --global means reset to just the global database
281         --      -f <file> means overlap with <file>
282         addDB dbs FlagUser       = user_conf : dbs
283         addDB dbs FlagGlobal     = [global_conf]
284         addDB dbs (FlagConfig f) = f : dbs
285         addDB dbs _              = dbs
286
287   return databases
288
289 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
290 readParseDatabase filename = do
291   str <- readFile filename
292   let packages = read str
293   evaluate packages
294     `Exception.catch` \_ -> 
295         die (filename ++ ": parse error in package config file")
296   return (filename,packages)
297
298 emptyPackageConfig :: String
299 emptyPackageConfig = "[]"
300
301 -- -----------------------------------------------------------------------------
302 -- Registering
303
304 registerPackage :: FilePath
305                 -> [(String,String)] --  defines, ToDo: maybe remove?
306                 -> PackageDBStack
307                 -> Bool         -- auto_ghci_libs
308                 -> Bool         -- update
309                 -> Bool         -- force
310                 -> IO ()
311 registerPackage input defines db_stack auto_ghci_libs update force = do
312   let
313         db_to_operate_on = head db_stack
314         db_filename      = fst db_to_operate_on
315   --
316   checkConfigAccess db_filename
317
318   s <-
319     case input of
320       "-" -> do
321         putStr "Reading package info from stdin... "
322         getContents
323       f   -> do
324         putStr ("Reading package info from " ++ show f ++ " ")
325         readFile f
326
327   pkg <- parsePackageInfo s defines force
328   putStrLn "done."
329
330   validatePackageConfig pkg db_stack auto_ghci_libs update force
331   new_details <- updatePackageDB db_stack (snd db_to_operate_on) pkg
332   savePackageConfig db_filename
333   maybeRestoreOldConfig db_filename $
334     writeNewConfig db_filename new_details
335
336 parsePackageInfo
337         :: String
338         -> [(String,String)]
339         -> Bool
340         -> IO InstalledPackageInfo
341 parsePackageInfo str defines force =
342   case parseInstalledPackageInfo str of
343     ParseOk ok -> return ok
344     ParseFailed err -> die (showError err)
345
346 -- Used for converting versionless package names to new
347 -- PackageIdentifiers.  "Version [] []" is special: it means "no
348 -- version" or "any version"
349 pkgNameToId :: String -> PackageIdentifier
350 pkgNameToId name = PackageIdentifier name (Version [] [])
351
352 -- -----------------------------------------------------------------------------
353 -- Exposing, Hiding, Unregistering are all similar
354
355 exposePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
356 exposePackage = modifyPackage (\p -> [p{exposed=True}])
357
358 hidePackage :: PackageIdentifier ->  PackageDBStack -> IO ()
359 hidePackage = modifyPackage (\p -> [p{exposed=False}])
360
361 unregisterPackage :: PackageIdentifier ->  PackageDBStack -> IO ()
362 unregisterPackage = modifyPackage (\p -> [])
363
364 modifyPackage
365   :: (InstalledPackageInfo -> [InstalledPackageInfo])
366   -> PackageIdentifier
367   -> PackageDBStack
368   -> IO ()
369 modifyPackage _ _ [] = error "modifyPackage"
370 modifyPackage fn pkgid ((db_name, pkgs) : _) = do
371   checkConfigAccess db_name
372   p <- findPackage [(db_name,pkgs)] pkgid
373   let pid = package p
374   savePackageConfig db_name
375   let new_config = concat (map modify pkgs)
376       modify pkg
377         | package pkg == pid = fn pkg
378         | otherwise          = [pkg]
379   maybeRestoreOldConfig db_name $
380     writeNewConfig db_name new_config
381
382 -- -----------------------------------------------------------------------------
383 -- Listing packages
384
385 listPackages ::  PackageDBStack -> IO ()
386 listPackages db_confs = do
387   mapM_ show_pkgconf (reverse db_confs)
388   where show_pkgconf (db_name,pkg_confs) =
389           hPutStrLn stdout (render $
390                 text (db_name ++ ":") $$ nest 4 packages
391                 )
392            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
393                  pp_pkg p
394                    | exposed p = doc
395                    | otherwise = parens doc
396                    where doc = text (showPackageId (package p))
397
398 -- -----------------------------------------------------------------------------
399 -- Describe
400
401 describePackage :: PackageDBStack -> PackageIdentifier -> IO ()
402 describePackage db_stack pkgid = do
403   p <- findPackage db_stack pkgid
404   putStrLn (showInstalledPackageInfo p)
405
406 findPackage :: PackageDBStack -> PackageIdentifier -> IO InstalledPackageInfo
407 findPackage db_stack pkgid
408   = case [ p | p <- all_pkgs, pkgid `matches` p ] of
409         []  -> die ("cannot find package " ++ showPackageId pkgid)
410         [p] -> return p
411         ps  -> die ("package " ++ showPackageId pkgid ++ 
412                         " matches multiple packages: " ++ 
413                         concat (intersperse ", " (
414                                  map (showPackageId.package) ps)))
415   where
416         all_pkgs = concat (map snd db_stack)
417
418 matches :: PackageIdentifier -> InstalledPackageInfo -> Bool
419 pid `matches` p = 
420  pid == package p || 
421  not (realVersion pid) && pkgName pid == pkgName (package p)
422
423 -- -----------------------------------------------------------------------------
424 -- Field
425
426 describeField :: PackageDBStack -> PackageIdentifier -> String -> IO ()
427 describeField db_stack pkgid field = do
428   case toField field of
429     Nothing -> die ("unknown field: " ++ field)
430     Just fn -> do
431         p <- findPackage db_stack pkgid 
432         putStrLn (fn p)
433
434 toField :: String -> Maybe (InstalledPackageInfo -> String)
435 -- backwards compatibility:
436 toField "import_dirs"     = Just $ strList . importDirs
437 toField "source_dirs"     = Just $ strList . importDirs
438 toField "library_dirs"    = Just $ strList . libraryDirs
439 toField "hs_libraries"    = Just $ strList . hsLibraries
440 toField "extra_libraries" = Just $ strList . extraLibraries
441 toField "include_dirs"    = Just $ strList . includeDirs
442 toField "c_includes"      = Just $ strList . includes
443 toField "package_deps"    = Just $ strList . map showPackageId. depends
444 toField "extra_cc_opts"   = Just $ strList . extraCcOpts
445 toField "extra_ld_opts"   = Just $ strList . extraLdOpts  
446 toField "framework_dirs"  = Just $ strList . frameworkDirs  
447 toField "extra_frameworks"= Just $ strList . extraFrameworks  
448 toField s                 = showInstalledPackageInfoField s
449
450 strList :: [String] -> String
451 strList = show
452
453 -- -----------------------------------------------------------------------------
454 -- Manipulating package.conf files
455
456 checkConfigAccess :: FilePath -> IO ()
457 checkConfigAccess filename = do
458   access <- getPermissions filename
459   when (not (writable access))
460       (die (filename ++ ": you don't have permission to modify this file"))
461
462 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
463 maybeRestoreOldConfig filename io
464   = io `catch` \e -> do
465         hPutStrLn stderr (show e)
466         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
467                           "configuration was being written.  Attempting to \n"++
468                           "restore the old configuration... ")
469         renameFile (filename ++ ".old")  filename
470         hPutStrLn stdout "done."
471         ioError e
472
473 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
474 writeNewConfig filename packages = do
475   hPutStr stdout "Writing new package config file... "
476   h <- openFile filename WriteMode
477   hPutStrLn h (show packages)
478   hClose h
479   hPutStrLn stdout "done."
480
481 savePackageConfig :: FilePath -> IO ()
482 savePackageConfig filename = do
483   hPutStr stdout "Saving old package config file... "
484     -- mv rather than cp because we've already done an hGetContents
485     -- on this file so we won't be able to open it for writing
486     -- unless we move the old one out of the way...
487   let oldFile = filename ++ ".old"
488   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
489   when doesExist (removeFile oldFile `catch` (const $ return ()))
490   catch (renameFile filename oldFile)
491         (\ err -> do
492                 hPutStrLn stderr (unwords [ "Unable to rename "
493                                           , show filename
494                                           , " to "
495                                           , show oldFile
496                                           ])
497                 ioError err)
498   hPutStrLn stdout "done."
499
500 -----------------------------------------------------------------------------
501 -- Sanity-check a new package config, and automatically build GHCi libs
502 -- if requested.
503
504 validatePackageConfig :: InstalledPackageInfo
505                       -> PackageDBStack
506                       -> Bool   -- auto-ghc-libs
507                       -> Bool   -- update
508                       -> Bool   -- force
509                       -> IO ()
510 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
511   checkDuplicates db_stack pkg update
512   mapM_ (checkDep db_stack force) (depends pkg)
513   mapM_ (checkDir force) (importDirs pkg)
514   mapM_ (checkDir force) (libraryDirs pkg)
515   mapM_ (checkDir force) (includeDirs pkg)
516   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
517   -- ToDo: check these somehow?
518   --    extra_libraries :: [String],
519   --    c_includes      :: [String],
520
521
522 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> IO ()
523 checkDuplicates db_stack pkg update = do
524   let
525         pkgid = package pkg
526
527         (_top_db_name, pkgs) : _  = db_stack
528
529         pkgs_with_same_name = 
530                 [ p | p <- pkgs, pkgName (package p) == pkgName pkgid]
531         exposed_pkgs_with_same_name =
532                 filter exposed pkgs_with_same_name
533   --
534   -- Check whether this package id already exists in this DB
535   --
536   when (not update && (package pkg `elem` map package pkgs)) $
537        die ("package " ++ showPackageId pkgid ++ " is already installed")
538   --
539   -- if we are exposing this new package, then check that
540   -- there are no other exposed packages with the same name.
541   --
542   when (not update && exposed pkg && not (null exposed_pkgs_with_same_name)) $
543         die ("trying to register " ++ showPackageId pkgid 
544                   ++ " as exposed, but "
545                   ++ showPackageId (package (head exposed_pkgs_with_same_name))
546                   ++ " is also exposed.")
547
548
549 checkDir :: Bool -> String -> IO ()
550 checkDir force d
551  | "$topdir" `isPrefixOf` d = return ()
552         -- can't check this, because we don't know what $topdir is
553  | otherwise = do
554    there <- doesDirectoryExist d
555    when (not there)
556        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
557
558 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
559 checkDep db_stack force pkgid
560   | real_version && pkgid `elem` pkgids = return ()
561   | not real_version && pkgName pkgid `elem` pkg_names = return ()
562   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
563                                         ++ " doesn't exist")
564   where
565         -- for backwards compat, we treat 0.0 as a special version,
566         -- and don't check that it actually exists.
567         real_version = realVersion pkgid
568         
569         all_pkgs = concat (map snd db_stack)
570         pkgids = map package all_pkgs
571         pkg_names = map pkgName pkgids
572
573 realVersion :: PackageIdentifier -> Bool
574 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
575
576 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
577 checkHSLib dirs auto_ghci_libs force lib = do
578   let batch_lib_file = "lib" ++ lib ++ ".a"
579   bs <- mapM (doesLibExistIn batch_lib_file) dirs
580   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
581         [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
582                                  " on library path") 
583         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
584
585 doesLibExistIn :: String -> String -> IO Bool
586 doesLibExistIn lib d
587  | "$topdir" `isPrefixOf` d = return True
588  | otherwise                = doesFileExist (d ++ '/':lib)
589
590 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
591 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
592   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
593   | otherwise  = do
594       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
595       case [dir | (exists,dir) <- zip bs dirs, exists] of
596         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
597         (_:_) -> return ()
598   where
599     ghci_lib_file = lib ++ ".o"
600
601 -- automatically build the GHCi version of a batch lib, 
602 -- using ld --whole-archive.
603
604 autoBuildGHCiLib :: String -> String -> String -> IO ()
605 autoBuildGHCiLib dir batch_file ghci_file = do
606   let ghci_lib_file  = dir ++ '/':ghci_file
607       batch_lib_file = dir ++ '/':batch_file
608   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
609 #if defined(darwin_TARGET_OS)
610   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
611 #elif defined(mingw32_HOST_OS)
612   execDir <- getExecDir "/bin/ghc-pkg.exe"
613   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
614 #else
615   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
616 #endif
617   when (r /= ExitSuccess) $ exitWith r
618   hPutStrLn stderr (" done.")
619
620 -- -----------------------------------------------------------------------------
621 -- Updating the DB with the new package.
622
623 updatePackageDB
624         :: PackageDBStack
625         -> [InstalledPackageInfo]
626         -> InstalledPackageInfo
627         -> IO [InstalledPackageInfo]
628 updatePackageDB db_stack pkgs new_pkg = do
629   let
630         -- we update dependencies without version numbers to
631         -- match the actual versions of the relevant packages instaled.
632         updateDeps p = p{depends = map resolveDep (depends p)}
633
634         resolveDep pkgid
635            | realVersion pkgid  = pkgid
636            | otherwise          = lookupDep (pkgName pkgid)
637         
638         lookupDep name
639            = head [ 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 = head ([ 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 -- ---------------------------------------------------------------------------
791
792 #ifdef OLD_STUFF
793 -- ToDo: reinstate
794 expandEnvVars :: PackageConfig -> [(String, String)]
795         -> Bool -> IO PackageConfig
796 expandEnvVars pkg defines force = do
797    -- permit _all_ strings to contain ${..} environment variable references,
798    -- arguably too flexible.
799   nm       <- expandString  (name pkg)
800   imp_dirs <- expandStrings (import_dirs pkg) 
801   src_dirs <- expandStrings (source_dirs pkg) 
802   lib_dirs <- expandStrings (library_dirs pkg) 
803   hs_libs  <- expandStrings (hs_libraries pkg)
804   ex_libs  <- expandStrings (extra_libraries pkg)
805   inc_dirs <- expandStrings (include_dirs pkg)
806   c_incs   <- expandStrings (c_includes pkg)
807   p_deps   <- expandStrings (package_deps pkg)
808   e_g_opts <- expandStrings (extra_ghc_opts pkg)
809   e_c_opts <- expandStrings (extra_cc_opts pkg)
810   e_l_opts <- expandStrings (extra_ld_opts pkg)
811   f_dirs   <- expandStrings (framework_dirs pkg)
812   e_frames <- expandStrings (extra_frameworks pkg)
813   return (pkg { name            = nm
814               , import_dirs     = imp_dirs
815               , source_dirs     = src_dirs
816               , library_dirs    = lib_dirs
817               , hs_libraries    = hs_libs
818               , extra_libraries = ex_libs
819               , include_dirs    = inc_dirs
820               , c_includes      = c_incs
821               , package_deps    = p_deps
822               , extra_ghc_opts  = e_g_opts
823               , extra_cc_opts   = e_c_opts
824               , extra_ld_opts   = e_l_opts
825               , framework_dirs  = f_dirs
826               , extra_frameworks= e_frames
827               })
828   where
829    expandStrings :: [String] -> IO [String]
830    expandStrings = liftM concat . mapM expandSpecial
831
832    -- Permit substitutions for list-valued variables (but only when
833    -- they occur alone), e.g., package_deps["${deps}"] where env var
834    -- (say) 'deps' is "base,haskell98,network"
835    expandSpecial :: String -> IO [String]
836    expandSpecial str =
837       let expand f = liftM f $ expandString str
838       in case splitString str of
839          [Var _] -> expand (wordsBy (== ','))
840          _ -> expand (\x -> [x])
841
842    expandString :: String -> IO String
843    expandString = liftM concat . mapM expandElem . splitString
844
845    expandElem :: Elem -> IO String
846    expandElem (String s) = return s
847    expandElem (Var v)    = lookupEnvVar v
848
849    lookupEnvVar :: String -> IO String
850    lookupEnvVar nm = 
851      case lookup nm defines of
852        Just x | not (null x) -> return x
853        _      -> 
854         catch (System.getEnv nm)
855            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
856                                         show nm)
857                       return "")
858
859 data Elem = String String | Var String
860
861 splitString :: String -> [Elem]
862 splitString "" = []
863 splitString str =
864    case break (== '$') str of
865       (pre, _:'{':xs) ->
866          case span (/= '}') xs of
867             (var, _:suf) ->
868                (if null pre then id else (String pre :)) (Var var : splitString suf)
869             _ -> [String str]   -- no closing brace
870       _ -> [String str]   -- no dollar/opening brace combo
871
872 -- wordsBy isSpace == words
873 wordsBy :: (Char -> Bool) -> String -> [String]
874 wordsBy p s = case dropWhile p s of
875   "" -> []
876   s' -> w : wordsBy p s'' where (w,s'') = break p s'
877 #endif
878
879 -----------------------------------------------------------------------------
880
881 getProgramName :: IO String
882 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
883    where str `withoutSuffix` suff
884             | suff `isSuffixOf` str = take (length str - length suff) str
885             | otherwise             = str
886
887 bye :: String -> IO a
888 bye s = putStr s >> exitWith ExitSuccess
889
890 die :: String -> IO a
891 die s = do 
892   hFlush stdout
893   prog <- getProgramName
894   hPutStrLn stderr (prog ++ ": " ++ s)
895   exitWith (ExitFailure 1)
896
897 dieOrForce :: Bool -> String -> IO ()
898 dieOrForce force s 
899   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
900   | otherwise = die s
901
902
903 -----------------------------------------
904 --      Cut and pasted from ghc/compiler/SysTools
905
906 #if defined(mingw32_TARGET_OS)
907 subst a b ls = map (\ x -> if x == a then b else x) ls
908 unDosifyPath xs = subst '\\' '/' xs
909
910 getExecDir :: String -> IO (Maybe String)
911 -- (getExecDir cmd) returns the directory in which the current
912 --                  executable, which should be called 'cmd', is running
913 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
914 -- you'll get "/a/b/c" back as the result
915 getExecDir cmd
916   = allocaArray len $ \buf -> do
917         ret <- getModuleFileName nullPtr buf len
918         if ret == 0 then return Nothing
919                     else do s <- peekCString buf
920                             return (Just (reverse (drop (length cmd) 
921                                                         (reverse (unDosifyPath s)))))
922   where
923     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
924
925 foreign import stdcall unsafe  "GetModuleFileNameA"
926   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
927 #else
928 getExecDir :: String -> IO (Maybe String) 
929 getExecDir _ = return Nothing
930 #endif