oops, remove old packages when updating
[ghc-hetmet.git] / 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 )
22 import Distribution.Package
23 import Distribution.Version
24 import Compat.Directory         ( getAppUserDataDirectory, createDirectoryIfMissing )
25 import Compat.RawSystem         ( rawSystem )
26
27 import Prelude
28
29 #include "../../includes/ghcconfig.h"
30
31 #if __GLASGOW_HASKELL__ >= 504
32 import System.Console.GetOpt
33 import Text.PrettyPrint
34 import qualified Control.Exception as Exception
35 import Data.Maybe
36 #else
37 import GetOpt
38 import Pretty
39 import qualified Exception
40 import Maybe
41 #endif
42
43 import Data.Char        ( isSpace )
44 import Monad
45 import Directory
46 import System   ( getArgs, getProgName, getEnv,
47                   exitWith, ExitCode(..)
48                 )
49 import System.IO
50 #if __GLASGOW_HASKELL__ >= 600
51 import System.IO.Error (try)
52 #else
53 import System.IO (try)
54 #endif
55 import Data.List ( isPrefixOf, isSuffixOf, intersperse, sortBy )
56
57 #ifdef mingw32_HOST_OS
58 import Foreign
59
60 #if __GLASGOW_HASKELL__ >= 504
61 import Foreign.C.String
62 #else
63 import CString
64 #endif
65 #endif
66
67 -- -----------------------------------------------------------------------------
68 -- Entry point
69
70 main :: IO ()
71 main = do
72   args <- getArgs
73
74   case getOpt Permute flags args of
75         (cli,_,[]) | FlagHelp `elem` cli -> do
76            prog <- getProgramName
77            bye (usageInfo (usageHeader prog) flags)
78         (cli,_,[]) | FlagVersion `elem` cli ->
79            bye ourCopyright
80         (cli,nonopts,[]) ->
81            runit cli nonopts
82         (_,_,errors) -> tryOldCmdLine errors args
83
84 -- If the new command-line syntax fails, then we try the old.  If that
85 -- fails too, then we output the original errors and the new syntax
86 -- (so the old syntax is still available, but hidden).
87 tryOldCmdLine :: [String] -> [String] -> IO ()
88 tryOldCmdLine errors args = do
89   case getOpt Permute oldFlags args of
90         (cli@(_:_),[],[]) -> 
91            oldRunit cli
92         _failed -> do
93            prog <- getProgramName
94            die (concat errors ++ usageInfo (usageHeader prog) flags)
95
96 -- -----------------------------------------------------------------------------
97 -- Command-line syntax
98
99 data Flag
100   = FlagUser
101   | FlagGlobal
102   | FlagHelp
103   | FlagVersion
104   | FlagConfig  FilePath
105   | FlagGlobalConfig FilePath
106   | FlagForce
107   | FlagAutoGHCiLibs
108   | FlagDefinedName String String
109   | FlagSimpleOutput
110   deriving Eq
111
112 flags :: [OptDescr Flag]
113 flags = [
114   Option [] ["user"] (NoArg FlagUser)
115         "use the current user's package database",
116   Option [] ["global"] (NoArg FlagGlobal)
117         "(default) use the global package database",
118   Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
119         "act upon specified package config file (only)",
120   Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
121         "location of the global package config",
122   Option [] ["force"] (NoArg FlagForce)
123         "ignore missing dependencies, directories, and libraries",
124   Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
125         "automatically build libs for GHCi (with register)",
126   Option ['?'] ["help"] (NoArg FlagHelp)
127         "display this help and exit",
128   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
129         "define NAME as VALUE",
130   Option ['V'] ["version"] (NoArg FlagVersion)
131         "output version information and exit",
132   Option [] ["simple-output"] (NoArg FlagSimpleOutput)
133         "print output in easy-to-parse format when running command 'list'"
134   ]
135  where
136   toDefined str = 
137     case break (=='=') str of
138       (nm,[])    -> FlagDefinedName nm []
139       (nm,_:val) -> FlagDefinedName nm val
140
141 ourCopyright :: String
142 ourCopyright = "GHC package manager version " ++ version ++ "\n"
143
144 usageHeader :: String -> String
145 usageHeader prog = substProg prog $
146   "Usage:\n" ++
147   "  $p register {filename | -}\n" ++
148   "    Register the package using the specified installed package\n" ++
149   "    description. The syntax for the latter is given in the $p\n" ++
150   "    documentation.\n" ++
151   "\n" ++
152   "  $p update {filename | -}\n" ++
153   "    Register the package, overwriting any other package with the\n" ++
154   "    same name.\n" ++
155   "\n" ++
156   "  $p unregister {pkg-id}\n" ++
157   "    Unregister the specified package.\n" ++
158   "\n" ++
159   "  $p expose {pkg-id}\n" ++
160   "    Expose the specified package.\n" ++
161   "\n" ++
162   "  $p hide {pkg-id}\n" ++
163   "    Hide the specified package.\n" ++
164   "\n" ++
165   "  $p list [pkg]\n" ++
166   "    List registered packages in the global database, and also the\n" ++
167   "    user database if --user is given. If a package name is given\n" ++
168   "    all the registered versions will be listed in ascending order.\n" ++
169   "\n" ++
170   "  $p latest pkg\n" ++
171   "    Prints the highest registered version of a package.\n" ++
172   "\n" ++
173   "  $p describe {pkg-id}\n" ++
174   "    Give the registered description for the specified package. The\n" ++
175   "    description is returned in precisely the syntax required by $p\n" ++
176   "    register.\n" ++
177   "\n" ++
178   "  $p field {pkg-id} {field}\n" ++
179   "    Extract the specified field of the package description for the\n" ++
180   "    specified package.\n" ++
181   "\n" ++
182   " The following optional flags are also accepted:\n"
183
184 substProg :: String -> String -> String
185 substProg _ [] = []
186 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
187 substProg prog (c:xs) = c : substProg prog xs
188
189 -- -----------------------------------------------------------------------------
190 -- Do the business
191
192 runit :: [Flag] -> [String] -> IO ()
193 runit cli nonopts = do
194   prog <- getProgramName
195   let
196         force = FlagForce `elem` cli
197         auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
198         defines = [ (nm,val) | FlagDefinedName nm val <- cli ]
199   --
200   -- first, parse the command
201   case nonopts of
202     ["register", filename] -> 
203         registerPackage filename defines cli auto_ghci_libs False force
204     ["update", filename] -> 
205         registerPackage filename defines cli auto_ghci_libs True force
206     ["unregister", pkgid_str] -> do
207         pkgid <- readGlobPkgId pkgid_str
208         unregisterPackage pkgid cli
209     ["expose", pkgid_str] -> do
210         pkgid <- readGlobPkgId pkgid_str
211         exposePackage pkgid cli
212     ["hide",   pkgid_str] -> do
213         pkgid <- readGlobPkgId pkgid_str
214         hidePackage pkgid cli
215     ["list"] -> do
216         listPackages cli Nothing
217     ["list", pkgid_str] -> do
218         pkgid <- readGlobPkgId pkgid_str
219         listPackages cli (Just pkgid)
220     ["latest", pkgid_str] -> do
221         pkgid <- readGlobPkgId pkgid_str
222         latestPackage cli pkgid
223     ["describe", pkgid_str] -> do
224         pkgid <- readGlobPkgId pkgid_str
225         describePackage cli pkgid
226     ["field", pkgid_str, field] -> do
227         pkgid <- readGlobPkgId pkgid_str
228         describeField cli pkgid field
229     [] -> do
230         die ("missing command\n" ++ 
231                 usageInfo (usageHeader prog) flags)
232     (_cmd:_) -> do
233         die ("command-line syntax error\n" ++ 
234                 usageInfo (usageHeader prog) flags)
235
236 parseCheck :: ReadP a a -> String -> String -> IO a
237 parseCheck parser str what = 
238   case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
239     [x] -> return x
240     _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
241
242 readPkgId :: String -> IO PackageIdentifier
243 readPkgId str = parseCheck parsePackageId str "package identifier"
244
245 readGlobPkgId :: String -> IO PackageIdentifier
246 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
247
248 parseGlobPackageId :: ReadP r PackageIdentifier
249 parseGlobPackageId = 
250   parsePackageId
251      +++
252   (do n <- parsePackageName; string "-*"
253       return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
254
255 -- globVersion means "all versions"
256 globVersion :: Version
257 globVersion = Version{ versionBranch=[], versionTags=["*"] }
258
259 -- -----------------------------------------------------------------------------
260 -- Package databases
261
262 -- Some commands operate on a single database:
263 --      register, unregister, expose, hide
264 -- however these commands also check the union of the available databases
265 -- in order to check consistency.  For example, register will check that
266 -- dependencies exist before registering a package.
267 --
268 -- Some commands operate  on multiple databases, with overlapping semantics:
269 --      list, describe, field
270
271 type PackageDBName  = FilePath
272 type PackageDB      = [InstalledPackageInfo]
273
274 type PackageDBStack = [(PackageDBName,PackageDB)]
275         -- A stack of package databases.  Convention: head is the topmost
276         -- in the stack.  Earlier entries override later one.
277
278 getPkgDatabases :: Bool -> [Flag] -> IO PackageDBStack
279 getPkgDatabases modify flags = do
280   -- first we determine the location of the global package config.  On Windows,
281   -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
282   -- location is passed to the binary using the --global-config flag by the
283   -- wrapper script.
284   let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
285   global_conf <- 
286      case [ f | FlagGlobalConfig f <- flags ] of
287         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
288                  case mb_dir of
289                         Nothing  -> die err_msg
290                         Just dir -> return (dir `joinFileName` "package.conf")
291         fs -> return (last fs)
292
293   let global_conf_dir = global_conf ++ ".d"
294   global_conf_dir_exists <- doesDirectoryExist global_conf_dir
295   global_confs <-
296     if global_conf_dir_exists
297       then do files <- getDirectoryContents global_conf_dir
298               return [ global_conf_dir ++ '/' : file
299                      | file <- files
300                      , isSuffixOf ".conf" file]
301       else return []
302
303   -- get the location of the user package database, and create it if necessary
304   appdir <- getAppUserDataDirectory "ghc"
305
306   let
307         subdir = targetARCH ++ '-':targetOS ++ '-':version
308         archdir   = appdir `joinFileName` subdir
309         user_conf = archdir `joinFileName` "package.conf"
310   user_exists <- doesFileExist user_conf
311
312   -- If the user database doesn't exist, and this command isn't a
313   -- "modify" command, then we won't attempt to create or use it.
314   let sys_databases
315         | modify || user_exists = user_conf : global_confs ++ [global_conf]
316         | otherwise             = global_confs ++ [global_conf]
317
318   e_pkg_path <- try (getEnv "GHC_PACKAGE_PATH")
319   let env_stack =
320         case e_pkg_path of
321                 Left  _ -> sys_databases
322                 Right path
323                   | last cs == ""  -> init cs ++ sys_databases
324                   | otherwise      -> cs
325                   where cs = parseSearchPath path
326
327         -- The "global" database is always the one at the bottom of the stack.
328         -- This is the database we modify by default.
329       virt_global_conf = last env_stack
330
331   -- -f flags on the command line add to the database stack, unless any
332   -- of them are present in the stack already.
333   let flag_stack = filter (`notElem` env_stack) 
334                         [ f | FlagConfig f <- reverse flags ] ++ env_stack
335
336   -- Now we have the full stack of databases.  Next, if the current
337   -- command is a "modify" type command, then we truncate the stack
338   -- so that the topmost element is the database being modified.
339   final_stack <-
340      if not modify 
341         then return flag_stack
342         else let
343                 go (FlagUser : fs)     = modifying user_conf
344                 go (FlagGlobal : fs)   = modifying virt_global_conf
345                 go (FlagConfig f : fs) = modifying f
346                 go (_ : fs)            = go fs
347                 go []                  = modifying virt_global_conf
348                 
349                 modifying f 
350                   | f `elem` flag_stack = return (dropWhile (/= f) flag_stack)
351                   | otherwise           = die ("requesting modification of database:\n\t" ++ f ++ "\n\twhich is not in the database stack.")
352              in
353                 go flags
354
355   db_stack <- mapM readParseDatabase final_stack
356   return db_stack
357
358 readParseDatabase :: PackageDBName -> IO (PackageDBName,PackageDB)
359 readParseDatabase filename = do
360   str <- readFile filename `Exception.catch` \_ -> return emptyPackageConfig
361   let packages = read str
362   Exception.evaluate packages
363     `Exception.catch` \_ -> 
364         die (filename ++ ": parse error in package config file")
365   return (filename,packages)
366
367 emptyPackageConfig :: String
368 emptyPackageConfig = "[]"
369
370 -- -----------------------------------------------------------------------------
371 -- Registering
372
373 registerPackage :: FilePath
374                 -> [(String,String)] -- defines
375                 -> [Flag]
376                 -> Bool         -- auto_ghci_libs
377                 -> Bool         -- update
378                 -> Bool         -- force
379                 -> IO ()
380 registerPackage input defines flags auto_ghci_libs update force = do
381   db_stack <- getPkgDatabases True flags
382   let
383         db_to_operate_on = my_head "db" db_stack
384         db_filename      = fst db_to_operate_on
385   --
386   checkConfigAccess db_filename
387
388   s <-
389     case input of
390       "-" -> do
391         putStr "Reading package info from stdin ... "
392         getContents
393       f   -> do
394         putStr ("Reading package info from " ++ show f ++ " ... ")
395         readFile f
396
397   expanded <- expandEnvVars s defines force
398
399   pkg0 <- parsePackageInfo expanded defines force
400   putStrLn "done."
401
402   let pkg = resolveDeps db_stack pkg0
403   validatePackageConfig pkg db_stack auto_ghci_libs update force
404   let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
405       not_this p = package p /= package pkg
406   savePackageConfig db_filename
407   maybeRestoreOldConfig db_filename $
408     writeNewConfig db_filename new_details
409
410 parsePackageInfo
411         :: String
412         -> [(String,String)]
413         -> Bool
414         -> IO InstalledPackageInfo
415 parsePackageInfo str defines force =
416   case parseInstalledPackageInfo str of
417     ParseOk _warns ok -> return ok
418     ParseFailed err -> die (showError err)
419
420 -- -----------------------------------------------------------------------------
421 -- Exposing, Hiding, Unregistering are all similar
422
423 exposePackage :: PackageIdentifier ->  [Flag] -> IO ()
424 exposePackage = modifyPackage (\p -> [p{exposed=True}])
425
426 hidePackage :: PackageIdentifier ->  [Flag] -> IO ()
427 hidePackage = modifyPackage (\p -> [p{exposed=False}])
428
429 unregisterPackage :: PackageIdentifier ->  [Flag] -> IO ()
430 unregisterPackage = modifyPackage (\p -> [])
431
432 modifyPackage
433   :: (InstalledPackageInfo -> [InstalledPackageInfo])
434   -> PackageIdentifier
435   -> [Flag]
436   -> IO ()
437 modifyPackage fn pkgid flags  = do
438   db_stack <- getPkgDatabases True{-modify-} flags
439   let ((db_name, pkgs) : _) = db_stack
440   checkConfigAccess db_name
441   ps <- findPackages [(db_name,pkgs)] pkgid
442   let pids = map package ps
443   savePackageConfig db_name
444   let new_config = concat (map modify pkgs)
445       modify pkg
446           | package pkg `elem` pids = fn pkg
447           | otherwise               = [pkg]
448   maybeRestoreOldConfig db_name $
449       writeNewConfig db_name new_config
450
451 -- -----------------------------------------------------------------------------
452 -- Listing packages
453
454 listPackages ::  [Flag] -> Maybe PackageIdentifier -> IO ()
455 listPackages flags mPackageName = do
456   let simple_output = FlagSimpleOutput `elem` flags
457   db_stack <- getPkgDatabases False flags
458   let db_stack_filtered -- if a package is given, filter out all other packages
459         | Just this <- mPackageName =
460             map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs)) 
461                 db_stack
462         | otherwise = db_stack
463
464       db_stack_sorted 
465           = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
466           where sort_pkgs = sortBy cmpPkgIds
467                 cmpPkgIds pkg1 pkg2 = 
468                    case pkgName p1 `compare` pkgName p2 of
469                         LT -> LT
470                         GT -> GT
471                         EQ -> pkgVersion p1 `compare` pkgVersion p2
472                    where (p1,p2) = (package pkg1, package pkg2)
473
474       show_func = if simple_output then show_easy else mapM_ show_regular
475
476   show_func (reverse db_stack_sorted)
477
478   where show_regular (db_name,pkg_confs) =
479           hPutStrLn stdout (render $
480                 text (db_name ++ ":") $$ nest 4 packages
481                 )
482            where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
483                  pp_pkg p
484                    | exposed p = doc
485                    | otherwise = parens doc
486                    where doc = text (showPackageId (package p))
487
488         show_easy db_stack = do
489           let pkgs = map showPackageId $ sortBy compPkgIdVer $
490                           map package (concatMap snd db_stack)
491           when (null pkgs) $ die "no matches"
492           hPutStrLn stdout $ concat $ intersperse " " pkgs
493
494 -- -----------------------------------------------------------------------------
495 -- Prints the highest (hidden or exposed) version of a package
496
497 latestPackage ::  [Flag] -> PackageIdentifier -> IO ()
498 latestPackage flags pkgid = do
499   db_stack <- getPkgDatabases False flags
500   ps <- findPackages db_stack pkgid
501   show_pkg (sortBy compPkgIdVer (map package ps))
502   where
503     show_pkg [] = die "no matches"
504     show_pkg pids = hPutStrLn stdout (showPackageId (last pids))
505
506 -- -----------------------------------------------------------------------------
507 -- Describe
508
509 describePackage :: [Flag] -> PackageIdentifier -> IO ()
510 describePackage flags pkgid = do
511   db_stack <- getPkgDatabases False flags
512   ps <- findPackages db_stack pkgid
513   mapM_ (putStrLn . showInstalledPackageInfo) ps
514
515 -- PackageId is can have globVersion for the version
516 findPackages :: PackageDBStack -> PackageIdentifier -> IO [InstalledPackageInfo]
517 findPackages db_stack pkgid
518   = case [ p | p <- all_pkgs, pkgid `matchesPkg` p ] of
519         []  -> die ("cannot find package " ++ showPackageId pkgid)
520         ps -> return ps
521   where
522         all_pkgs = concat (map snd db_stack)
523
524 matches :: PackageIdentifier -> PackageIdentifier -> Bool
525 pid `matches` pid'
526   = (pkgName pid == pkgName pid')
527     && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
528
529 matchesPkg :: PackageIdentifier -> InstalledPackageInfo -> Bool
530 pid `matchesPkg` pkg = pid `matches` package pkg
531
532 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
533 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
534
535 -- -----------------------------------------------------------------------------
536 -- Field
537
538 describeField :: [Flag] -> PackageIdentifier -> String -> IO ()
539 describeField flags pkgid field = do
540   db_stack <- getPkgDatabases False flags
541   case toField field of
542     Nothing -> die ("unknown field: " ++ field)
543     Just fn -> do
544         ps <- findPackages db_stack pkgid 
545         mapM_ (putStrLn.fn) ps
546
547 toField :: String -> Maybe (InstalledPackageInfo -> String)
548 -- backwards compatibility:
549 toField "import_dirs"     = Just $ strList . importDirs
550 toField "source_dirs"     = Just $ strList . importDirs
551 toField "library_dirs"    = Just $ strList . libraryDirs
552 toField "hs_libraries"    = Just $ strList . hsLibraries
553 toField "extra_libraries" = Just $ strList . extraLibraries
554 toField "include_dirs"    = Just $ strList . includeDirs
555 toField "c_includes"      = Just $ strList . includes
556 toField "package_deps"    = Just $ strList . map showPackageId. depends
557 toField "extra_cc_opts"   = Just $ strList . ccOptions
558 toField "extra_ld_opts"   = Just $ strList . ldOptions
559 toField "framework_dirs"  = Just $ strList . frameworkDirs  
560 toField "extra_frameworks"= Just $ strList . frameworks  
561 toField s                 = showInstalledPackageInfoField s
562
563 strList :: [String] -> String
564 strList = show
565
566 -- -----------------------------------------------------------------------------
567 -- Manipulating package.conf files
568
569 checkConfigAccess :: FilePath -> IO ()
570 checkConfigAccess filename = do
571   access <- getPermissions filename
572   when (not (writable access))
573       (die (filename ++ ": you don't have permission to modify this file"))
574
575 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
576 maybeRestoreOldConfig filename io
577   = io `catch` \e -> do
578         hPutStrLn stderr (show e)
579         hPutStr stdout ("\nWARNING: an error was encountered while the new \n"++
580                           "configuration was being written.  Attempting to \n"++
581                           "restore the old configuration... ")
582         renameFile (filename ++ ".old")  filename
583         hPutStrLn stdout "done."
584         ioError e
585
586 writeNewConfig :: FilePath -> [InstalledPackageInfo] -> IO ()
587 writeNewConfig filename packages = do
588   hPutStr stdout "Writing new package config file... "
589   h <- openFile filename WriteMode
590   hPutStrLn h (show packages)
591   hClose h
592   hPutStrLn stdout "done."
593
594 savePackageConfig :: FilePath -> IO ()
595 savePackageConfig filename = do
596   hPutStr stdout "Saving old package config file... "
597     -- mv rather than cp because we've already done an hGetContents
598     -- on this file so we won't be able to open it for writing
599     -- unless we move the old one out of the way...
600   let oldFile = filename ++ ".old"
601   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
602   when doesExist (removeFile oldFile `catch` (const $ return ()))
603   catch (renameFile filename oldFile)
604         (\ err -> do
605                 hPutStrLn stderr (unwords [ "Unable to rename "
606                                           , show filename
607                                           , " to "
608                                           , show oldFile
609                                           ])
610                 ioError err)
611   hPutStrLn stdout "done."
612
613 -----------------------------------------------------------------------------
614 -- Sanity-check a new package config, and automatically build GHCi libs
615 -- if requested.
616
617 validatePackageConfig :: InstalledPackageInfo
618                       -> PackageDBStack
619                       -> Bool   -- auto-ghc-libs
620                       -> Bool   -- update
621                       -> Bool   -- force
622                       -> IO ()
623 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
624   checkPackageId pkg
625   checkDuplicates db_stack pkg update force
626   mapM_ (checkDep db_stack force) (depends pkg)
627   mapM_ (checkDir force) (importDirs pkg)
628   mapM_ (checkDir force) (libraryDirs pkg)
629   mapM_ (checkDir force) (includeDirs pkg)
630   mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
631   -- ToDo: check these somehow?
632   --    extra_libraries :: [String],
633   --    c_includes      :: [String],
634
635 -- When the package name and version are put together, sometimes we can
636 -- end up with a package id that cannot be parsed.  This will lead to 
637 -- difficulties when the user wants to refer to the package later, so
638 -- we check that the package id can be parsed properly here.
639 checkPackageId :: InstalledPackageInfo -> IO ()
640 checkPackageId ipi =
641   let str = showPackageId (package ipi) in
642   case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
643     [_] -> return ()
644     []  -> die ("invalid package identifier: " ++ str)
645     _   -> die ("ambiguous package identifier: " ++ str)
646
647 resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
648 resolveDeps db_stack p = updateDeps p
649   where
650         -- The input package spec is allowed to give a package dependency
651         -- without a version number; e.g.
652         --      depends: base
653         -- Here, we update these dependencies without version numbers to
654         -- match the actual versions of the relevant packages installed.
655         updateDeps p = p{depends = map resolveDep (depends p)}
656
657         resolveDep dep_pkgid
658            | realVersion dep_pkgid  = dep_pkgid
659            | otherwise              = lookupDep dep_pkgid
660
661         lookupDep dep_pkgid
662            = let 
663                 name = pkgName dep_pkgid
664              in
665              case [ pid | p <- concat (map snd db_stack), 
666                           let pid = package p,
667                           pkgName pid == name ] of
668                 (pid:_) -> pid          -- Found installed package,
669                                         -- replete with its version
670                 []      -> dep_pkgid    -- No installed package; use 
671                                         -- the version-less one
672
673 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
674          -> IO ()
675 checkDuplicates db_stack pkg update force = do
676   let
677         pkgid = package pkg
678         (_top_db_name, pkgs) : _  = db_stack
679   --
680   -- Check whether this package id already exists in this DB
681   --
682   when (not update && (pkgid `elem` map package pkgs)) $
683        die ("package " ++ showPackageId pkgid ++ " is already installed")
684
685
686
687 checkDir :: Bool -> String -> IO ()
688 checkDir force d
689  | "$topdir" `isPrefixOf` d = return ()
690         -- can't check this, because we don't know what $topdir is
691  | otherwise = do
692    there <- doesDirectoryExist d
693    when (not there)
694        (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
695
696 checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
697 checkDep db_stack force pkgid
698   | not real_version || pkgid `elem` pkgids = return ()
699   | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
700                                         ++ " doesn't exist")
701   where
702         -- for backwards compat, we treat 0.0 as a special version,
703         -- and don't check that it actually exists.
704         real_version = realVersion pkgid
705         
706         all_pkgs = concat (map snd db_stack)
707         pkgids = map package all_pkgs
708
709 realVersion :: PackageIdentifier -> Bool
710 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
711
712 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
713 checkHSLib dirs auto_ghci_libs force lib = do
714   let batch_lib_file = "lib" ++ lib ++ ".a"
715   bs <- mapM (doesLibExistIn batch_lib_file) dirs
716   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
717         [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
718                                  " on library path") 
719         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
720
721 doesLibExistIn :: String -> String -> IO Bool
722 doesLibExistIn lib d
723  | "$topdir" `isPrefixOf` d = return True
724  | otherwise                = doesFileExist (d ++ '/':lib)
725
726 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
727 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
728   | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
729   | otherwise  = do
730       bs <- mapM (doesLibExistIn ghci_lib_file) dirs
731       case [dir | (exists,dir) <- zip bs dirs, exists] of
732         []    -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
733         (_:_) -> return ()
734   where
735     ghci_lib_file = lib ++ ".o"
736
737 -- automatically build the GHCi version of a batch lib, 
738 -- using ld --whole-archive.
739
740 autoBuildGHCiLib :: String -> String -> String -> IO ()
741 autoBuildGHCiLib dir batch_file ghci_file = do
742   let ghci_lib_file  = dir ++ '/':ghci_file
743       batch_lib_file = dir ++ '/':batch_file
744   hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
745 #if defined(darwin_HOST_OS)
746   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
747 #elif defined(mingw32_HOST_OS)
748   execDir <- getExecDir "/bin/ghc-pkg.exe"
749   r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
750 #else
751   r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
752 #endif
753   when (r /= ExitSuccess) $ exitWith r
754   hPutStrLn stderr (" done.")
755
756 -- -----------------------------------------------------------------------------
757 -- Searching for modules
758
759 #if not_yet
760
761 findModules :: [FilePath] -> IO [String]
762 findModules paths = 
763   mms <- mapM searchDir paths
764   return (concat mms)
765
766 searchDir path prefix = do
767   fs <- getDirectoryEntries path `catch` \_ -> return []
768   searchEntries path prefix fs
769
770 searchEntries path prefix [] = return []
771 searchEntries path prefix (f:fs)
772   | looks_like_a_module  =  do
773         ms <- searchEntries path prefix fs
774         return (prefix `joinModule` f : ms)
775   | looks_like_a_component  =  do
776         ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
777         ms' <- searchEntries path prefix fs
778         return (ms ++ ms')      
779   | otherwise
780         searchEntries path prefix fs
781
782   where
783         (base,suffix) = splitFileExt f
784         looks_like_a_module = 
785                 suffix `elem` haskell_suffixes && 
786                 all okInModuleName base
787         looks_like_a_component =
788                 null suffix && all okInModuleName base
789
790 okInModuleName c
791
792 #endif
793
794 -- -----------------------------------------------------------------------------
795 -- The old command-line syntax, supported for backwards compatibility
796
797 data OldFlag 
798   = OF_Config FilePath
799   | OF_Input FilePath
800   | OF_List
801   | OF_ListLocal
802   | OF_Add Bool {- True => replace existing info -}
803   | OF_Remove String | OF_Show String 
804   | OF_Field String | OF_AutoGHCiLibs | OF_Force
805   | OF_DefinedName String String
806   | OF_GlobalConfig FilePath
807   deriving (Eq)
808
809 isAction :: OldFlag -> Bool
810 isAction OF_Config{}        = False
811 isAction OF_Field{}         = False
812 isAction OF_Input{}         = False
813 isAction OF_AutoGHCiLibs{}  = False
814 isAction OF_Force{}         = False
815 isAction OF_DefinedName{}   = False
816 isAction OF_GlobalConfig{}  = False
817 isAction _                  = True
818
819 oldFlags :: [OptDescr OldFlag]
820 oldFlags = [
821   Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
822         "use the specified package config file",
823   Option ['l'] ["list-packages"] (NoArg OF_List)
824         "list packages in all config files",
825   Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
826         "list packages in the specified config file",
827   Option ['a'] ["add-package"] (NoArg (OF_Add False))
828         "add a new package",
829   Option ['u'] ["update-package"] (NoArg (OF_Add True))
830         "update package with new configuration",
831   Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
832         "read new package info from specified file",
833   Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
834         "show the configuration for package NAME",
835   Option [] ["field"] (ReqArg OF_Field "FIELD")
836         "(with --show-package) Show field FIELD only",
837   Option [] ["force"] (NoArg OF_Force)
838         "ignore missing directories/libraries",
839   Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
840         "remove an installed package",
841   Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
842         "automatically build libs for GHCi (with -a)",
843   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
844         "define NAME as VALUE",
845   Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
846         "location of the global package config"
847   ]
848  where
849   toDefined str = 
850     case break (=='=') str of
851       (nm,[]) -> OF_DefinedName nm []
852       (nm,_:val) -> OF_DefinedName nm val
853
854 oldRunit :: [OldFlag] -> IO ()
855 oldRunit clis = do
856   let new_flags = [ f | Just f <- map conv clis ]
857
858       conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
859       conv (OF_Config f)       = Just (FlagConfig f)
860       conv _                   = Nothing
861
862   
863
864   let fields = [ f | OF_Field f <- clis ]
865
866   let auto_ghci_libs = any isAuto clis 
867          where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
868       input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
869
870       force = OF_Force `elem` clis
871       
872       defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
873
874   case [ c | c <- clis, isAction c ] of
875     [ OF_List ]      -> listPackages new_flags Nothing
876     [ OF_ListLocal ] -> listPackages new_flags Nothing
877     [ OF_Add upd ]   -> 
878         registerPackage input_file defines new_flags auto_ghci_libs upd force
879     [ OF_Remove pkgid_str ]  -> do
880         pkgid <- readPkgId pkgid_str
881         unregisterPackage pkgid new_flags
882     [ OF_Show pkgid_str ]
883         | null fields -> do
884                 pkgid <- readPkgId pkgid_str
885                 describePackage new_flags pkgid
886         | otherwise   -> do
887                 pkgid <- readPkgId pkgid_str
888                 mapM_ (describeField new_flags pkgid) fields
889     _ -> do 
890         prog <- getProgramName
891         die (usageInfo (usageHeader prog) flags)
892
893 my_head :: String -> [a] -> a
894 my_head s [] = error s
895 my_head s (x:xs) = x
896
897 -- ---------------------------------------------------------------------------
898 -- expanding environment variables in the package configuration
899
900 expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
901 expandEnvVars str defines force = go str ""
902  where
903    go "" acc = return $! reverse acc
904    go ('$':'{':str) acc | (var, '}':rest) <- break close str
905         = do value <- lookupEnvVar var
906              go rest (reverse value ++ acc)
907         where close c = c == '}' || c == '\n' -- don't span newlines
908    go (c:str) acc
909         = go str (c:acc)
910
911    lookupEnvVar :: String -> IO String
912    lookupEnvVar nm = 
913      case lookup nm defines of
914        Just x | not (null x) -> return x
915        _      -> 
916         catch (System.getEnv nm)
917            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
918                                         show nm)
919                       return "")
920
921 -----------------------------------------------------------------------------
922
923 getProgramName :: IO String
924 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
925    where str `withoutSuffix` suff
926             | suff `isSuffixOf` str = take (length str - length suff) str
927             | otherwise             = str
928
929 bye :: String -> IO a
930 bye s = putStr s >> exitWith ExitSuccess
931
932 die :: String -> IO a
933 die s = do 
934   hFlush stdout
935   prog <- getProgramName
936   hPutStrLn stderr (prog ++ ": " ++ s)
937   exitWith (ExitFailure 1)
938
939 dieOrForce :: Bool -> String -> IO ()
940 dieOrForce force s 
941   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
942   | otherwise = die (s ++ " (use --force to override)")
943
944 -----------------------------------------
945 --      Cut and pasted from ghc/compiler/SysTools
946
947 #if defined(mingw32_HOST_OS)
948 subst a b ls = map (\ x -> if x == a then b else x) ls
949 unDosifyPath xs = subst '\\' '/' xs
950
951 getExecDir :: String -> IO (Maybe String)
952 -- (getExecDir cmd) returns the directory in which the current
953 --                  executable, which should be called 'cmd', is running
954 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
955 -- you'll get "/a/b/c" back as the result
956 getExecDir cmd
957   = allocaArray len $ \buf -> do
958         ret <- getModuleFileName nullPtr buf len
959         if ret == 0 then return Nothing
960                     else do s <- peekCString buf
961                             return (Just (reverse (drop (length cmd) 
962                                                         (reverse (unDosifyPath s)))))
963   where
964     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
965
966 foreign import stdcall unsafe  "GetModuleFileNameA"
967   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
968 #else
969 getExecDir :: String -> IO (Maybe String) 
970 getExecDir _ = return Nothing
971 #endif
972
973 -- -----------------------------------------------------------------------------
974 -- FilePath utils
975
976 -- | The 'joinFileName' function is the opposite of 'splitFileName'. 
977 -- It joins directory and file names to form a complete file path.
978 --
979 -- The general rule is:
980 --
981 -- > dir `joinFileName` basename == path
982 -- >   where
983 -- >     (dir,basename) = splitFileName path
984 --
985 -- There might be an exceptions to the rule but in any case the
986 -- reconstructed path will refer to the same object (file or directory).
987 -- An example exception is that on Windows some slashes might be converted
988 -- to backslashes.
989 joinFileName :: String -> String -> FilePath
990 joinFileName ""  fname = fname
991 joinFileName "." fname = fname
992 joinFileName dir ""    = dir
993 joinFileName dir fname
994   | isPathSeparator (last dir) = dir++fname
995   | otherwise                  = dir++pathSeparator:fname
996
997 -- | Checks whether the character is a valid path separator for the host
998 -- platform. The valid character is a 'pathSeparator' but since the Windows
999 -- operating system also accepts a slash (\"\/\") since DOS 2, the function
1000 -- checks for it on this platform, too.
1001 isPathSeparator :: Char -> Bool
1002 isPathSeparator ch = ch == pathSeparator || ch == '/'
1003
1004 -- | Provides a platform-specific character used to separate directory levels in
1005 -- a path string that reflects a hierarchical file system organization. The
1006 -- separator is a slash (@\"\/\"@) on Unix and Macintosh, and a backslash
1007 -- (@\"\\\"@) on the Windows operating system.
1008 pathSeparator :: Char
1009 #ifdef mingw32_HOST_OS
1010 pathSeparator = '\\'
1011 #else
1012 pathSeparator = '/'
1013 #endif
1014
1015 -- | The function splits the given string to substrings
1016 -- using the 'searchPathSeparator'.
1017 parseSearchPath :: String -> [FilePath]
1018 parseSearchPath path = split path
1019   where
1020     split :: String -> [String]
1021     split s =
1022       case rest' of
1023         []     -> [chunk] 
1024         _:rest -> chunk : split rest
1025       where
1026         chunk = 
1027           case chunk' of
1028 #ifdef mingw32_HOST_OS
1029             ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1030 #endif
1031             _                                 -> chunk'
1032
1033         (chunk', rest') = break (==searchPathSeparator) s
1034
1035 -- | A platform-specific character used to separate search path strings in 
1036 -- environment variables. The separator is a colon (\":\") on Unix and Macintosh, 
1037 -- and a semicolon (\";\") on the Windows operating system.
1038 searchPathSeparator :: Char
1039 #if mingw32_HOST_OS || mingw32_TARGET_OS
1040 searchPathSeparator = ';'
1041 #else
1042 searchPathSeparator = ':'
1043 #endif
1044