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