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