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