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