[project @ 2004-01-11 14:43:14 by panne]
[ghc-hetmet.git] / ghc / utils / ghc-pkg / Main.hs
1 {-# OPTIONS -fglasgow-exts #-}
2
3 -----------------------------------------------------------------------------
4 -- Package management tool
5 -----------------------------------------------------------------------------
6
7 module Main where
8
9 import Package
10
11 #if __GLASGOW_HASKELL__ >= 504
12 import System.Console.GetOpt
13 import Text.PrettyPrint
14 import qualified Control.Exception as Exception
15 #else
16 import GetOpt
17 import Pretty
18 import qualified Exception
19 #endif
20
21 import Monad
22 import Directory
23 import System   ( getEnv, getArgs, getProgName,
24                   system, exitWith,
25                   ExitCode(..)
26                 )
27 import IO
28 import List ( isPrefixOf, isSuffixOf )
29
30 import ParsePkgConfLite
31
32 #include "../../includes/config.h"
33
34 #ifdef mingw32_HOST_OS
35 import Foreign
36
37 #if __GLASGOW_HASKELL__ >= 504
38 import Foreign.C.String
39 #else
40 import CString
41 #endif
42 #endif
43
44 main :: IO ()
45 main = do
46   args <- getArgs
47
48   case getOpt Permute flags args of
49         (cli,_,[]) | DumpHelp `elem` cli -> do
50            prog <- getProgramName
51            bye (usageInfo (usageHeader prog) flags)
52         (cli,_,[]) | DumpVersion `elem` cli ->
53            bye copyright
54         (cli@(_:_),[],[]) ->
55            runit cli
56         (_,_,errors) -> do
57            prog <- getProgramName
58            die (concat errors ++ usageInfo (usageHeader prog) flags)
59
60 data Flag 
61   = Config FilePath
62   | Input FilePath
63   | List
64   | ListLocal
65   | Add Bool {- True => replace existing info -}
66   | Remove String | Show String 
67   | Field String | AutoGHCiLibs | Force
68   | DefinedName String String
69   | DumpHelp
70   | DumpVersion
71   deriving (Eq)
72
73 isAction :: Flag -> Bool
74 isAction (Config _)     = False
75 isAction (Field _)      = False
76 isAction (Input _)      = False
77 isAction (AutoGHCiLibs) = False
78 isAction (Force)        = False
79 isAction DefinedName{}  = False
80 isAction _              = True
81
82 copyright :: String
83 copyright = "GHC package manager version " ++ version ++ "\n"
84
85 -- hackery to convice cpp to splice GHC_PKG_VERSION into a string
86 version :: String
87 version = tail "\ 
88    \ GHC_PKG_VERSION"
89
90 usageHeader :: String -> String
91 usageHeader prog = "Usage: " ++ prog ++ " [OPTION...]\n"
92
93 flags :: [OptDescr Flag]
94 flags = [
95   Option ['f'] ["config-file"] (ReqArg Config "FILE")
96         "use the specified package config file",
97   Option ['l'] ["list-packages"] (NoArg List)
98         "list packages in all config files",
99   Option ['L'] ["list-local-packages"] (NoArg ListLocal)
100         "list packages in the specified config file",
101   Option ['a'] ["add-package"] (NoArg (Add False))
102         "add a new package",
103   Option ['u'] ["update-package"] (NoArg (Add True))
104         "update package with new configuration",
105   Option ['i'] ["input-file"] (ReqArg Input "FILE")
106         "read new package info from specified file",
107   Option ['s'] ["show-package"] (ReqArg Show "NAME")
108         "show the configuration for package NAME",
109   Option [] ["field"] (ReqArg Field "FIELD")
110         "(with --show-package) Show field FIELD only",
111   Option [] ["force"] (NoArg Force)
112         "ignore missing directories/libraries",
113   Option ['r'] ["remove-package"] (ReqArg Remove "NAME")
114         "remove an installed package",
115   Option ['g'] ["auto-ghci-libs"] (NoArg AutoGHCiLibs)
116         "automatically build libs for GHCi (with -a)",
117   Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
118         "define NAME as VALUE",
119    Option ['?'] ["help"] (NoArg DumpHelp)
120         "display this help and exit",
121    Option ['V'] ["version"] (NoArg DumpVersion)
122         "output version information and exit"
123   ]
124  where
125   toDefined str = 
126     case break (=='=') str of
127       (nm,[]) -> DefinedName nm []
128       (nm,_:val) -> DefinedName nm val
129
130 runit :: [Flag] -> IO ()
131 runit clis = do
132   let err_msg = "missing -f option, location of package.conf unknown\n"
133   conf_filenames <- 
134      case [ f | Config f <- clis ] of
135         fs@(_:_) -> return (reverse fs) -- NOTE reverse
136         [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
137                  case mb_dir of
138                         Nothing  -> die err_msg
139                         Just dir -> return [dir ++ "/package.conf"]
140
141   let toField "import_dirs"     = return import_dirs
142       toField "source_dirs"     = return source_dirs
143       toField "library_dirs"    = return library_dirs
144       toField "hs_libraries"    = return hs_libraries
145       toField "extra_libraries" = return extra_libraries
146       toField "include_dirs"    = return include_dirs
147       toField "c_includes"      = return c_includes
148       toField "package_deps"    = return package_deps
149       toField "extra_ghc_opts"  = return extra_ghc_opts
150       toField "extra_cc_opts"   = return extra_cc_opts
151       toField "extra_ld_opts"   = return extra_ld_opts  
152       toField "framework_dirs"  = return framework_dirs  
153       toField "extra_frameworks"= return extra_frameworks  
154       toField s                 = die ("unknown field: `" ++ s ++ "'\n")
155
156   fields <- mapM toField [ f | Field f <- clis ]
157
158   let read_parse_conf filename = do
159           str <- readFile filename
160           let packages = parsePackageConfig str
161           eval_catch packages
162             (\_ -> die (filename ++ ": parse error in package config file\n"))
163
164   pkg_confs <- mapM read_parse_conf conf_filenames
165
166   let conf_filename = head conf_filenames
167         -- this is the file we're going to update: the last one specified
168         -- on the command-line.
169
170   let auto_ghci_libs = any isAuto clis 
171          where isAuto AutoGHCiLibs = True; isAuto _ = False
172       input_file = head ([ f | (Input f) <- clis] ++ ["-"])
173
174       force = Force `elem` clis
175       
176       defines = [ (nm,val) | DefinedName nm val <- clis ]
177
178   case [ c | c <- clis, isAction c ] of
179     [ List ]      -> listPackages pkg_confs conf_filenames
180     [ ListLocal ] -> listPackages [head pkg_confs] [""]
181     [ Add upd ]  -> addPackage pkg_confs defines 
182                                conf_filename input_file
183                                auto_ghci_libs upd force
184     [ Remove p ] -> removePackage pkg_confs conf_filename p
185     [ Show p ]   -> showPackage pkg_confs conf_filename p fields
186     _            -> do prog <- getProgramName
187                        die (usageInfo (usageHeader prog) flags)
188
189
190 listPackages :: [[PackageConfig]] -> [FilePath] -> IO ()
191 listPackages pkg_confs conf_filenames = do
192   zipWithM_ show_pkgconf pkg_confs conf_filenames
193   where show_pkgconf pkg_conf filename =
194           hPutStrLn stdout (render $
195                 if null filename 
196                         then packages   
197                         else text (filename ++ ":") $$ nest 4 packages
198                 )
199            where packages = fsep (punctuate comma (map (text . name) pkg_conf))
200
201 showPackage :: [[PackageConfig]]
202             -> FilePath
203             -> String
204             -> [PackageConfig -> [String]]
205             -> IO ()
206 showPackage pkg_confs _ pkg_name fields =
207   case [ p | pkgs <- pkg_confs, p <- pkgs, name p == pkg_name ] of
208     []    -> die ("can't find package `" ++ pkg_name ++ "'\n")
209     [pkg] | null fields -> hPutStrLn stdout (render (dumpPkgGuts pkg))
210           | otherwise   -> hPutStrLn stdout (render (vcat 
211                                 (map (vcat . map text) (map ($ pkg) fields))))
212     _     -> die "showPackage: internal error\n"
213
214 addPackage :: [[PackageConfig]] -> [(String, String)] 
215            -> FilePath -> FilePath
216            -> Bool -> Bool -> Bool -> IO ()
217 addPackage pkg_confs defines 
218            filename inputFile
219            auto_ghci_libs updatePkg force = do
220   checkConfigAccess filename
221   s <-
222     case inputFile of
223       "-" -> do
224         hPutStr stdout "Reading package info from stdin... "
225         getContents
226       f   -> do
227         hPutStr stdout ("Reading package info from " ++ show f)
228         readFile f
229   let new_pkg = parseOnePackageConfig s
230   eval_catch new_pkg (\_ -> die "parse error in package info\n")
231   hPutStrLn stdout "done."
232   hPutStr stdout "Expanding embedded variables... "
233   new_exp_pkg <- expandEnvVars new_pkg defines force
234   hPutStrLn stdout "done."
235   new_details <- validatePackageConfig new_exp_pkg pkg_confs 
236                         auto_ghci_libs updatePkg force
237   savePackageConfig filename
238   maybeRestoreOldConfig filename $
239     writeNewConfig filename new_details
240
241 removePackage :: [[PackageConfig]] -> FilePath -> String -> IO ()
242 removePackage (packages : _) filename pkgName = do  
243   checkConfigAccess filename
244   when (pkgName `notElem` map name packages)
245        (die (filename ++ ": package `" ++ pkgName ++ "' not found\n"))
246   savePackageConfig filename
247   maybeRestoreOldConfig filename $
248     writeNewConfig filename (filter ((/= pkgName) . name) packages)
249
250 checkConfigAccess :: FilePath -> IO ()
251 checkConfigAccess filename = do
252   access <- getPermissions filename
253   when (not (writable access))
254       (die (filename ++ ": you don't have permission to modify this file\n"))
255
256 maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
257 maybeRestoreOldConfig filename io
258   = my_catch io (\e -> do
259         hPutStr stdout "\nWARNING: an error was encountered while the new \n\ 
260                        \configuration was being written.  Attempting to \n\ 
261                        \restore the old configuration... "
262         renameFile (filename ++ ".old")  filename
263         hPutStrLn stdout "done."
264         my_throw e
265     )
266
267 writeNewConfig :: FilePath -> [PackageConfig] -> IO ()
268 writeNewConfig filename packages = do
269   hPutStr stdout "Writing new package config file... "
270   h <- openFile filename WriteMode
271   hPutStrLn h (dumpPackages packages)
272   hClose h
273   hPutStrLn stdout "done."
274
275 savePackageConfig :: FilePath -> IO ()
276 savePackageConfig filename = do
277   hPutStr stdout "Saving old package config file... "
278     -- mv rather than cp because we've already done an hGetContents
279     -- on this file so we won't be able to open it for writing
280     -- unless we move the old one out of the way...
281   let oldFile = filename ++ ".old"
282   doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
283   when doesExist (removeFile oldFile `catch` (const $ return ()))
284   catch (renameFile filename oldFile)
285         (\ err -> do
286                 hPutStrLn stderr (unwords [ "Unable to rename "
287                                           , show filename
288                                           , " to "
289                                           , show oldFile
290                                           ])
291                 ioError err)
292   hPutStrLn stdout "done."
293
294 -----------------------------------------------------------------------------
295 -- Sanity-check a new package config, and automatically build GHCi libs
296 -- if requested.
297
298 validatePackageConfig :: PackageConfig 
299                       -> [[PackageConfig]]
300                       -> Bool
301                       -> Bool
302                       -> Bool
303                       -> IO [PackageConfig]
304 validatePackageConfig pkg pkg_confs@(pkgs:_) auto_ghci_libs updatePkg force = do
305   when (not updatePkg && (name pkg `elem` map name pkgs))
306        (die ("package `" ++ name pkg ++ "' is already installed\n"))
307   mapM_ (checkDep pkg_confs force) (package_deps pkg)
308   mapM_ (checkDir force) (import_dirs pkg)
309   mapM_ (checkDir force) (source_dirs pkg)
310   mapM_ (checkDir force) (library_dirs pkg)
311   mapM_ (checkDir force) (include_dirs pkg)
312   mapM_ (checkHSLib (library_dirs pkg) auto_ghci_libs force) (hs_libraries pkg)
313   -- ToDo: check these somehow?
314   --    extra_libraries :: [String],
315   --    c_includes      :: [String],
316   let existing_pkgs
317        | updatePkg = filter ((/=(name pkg)).name) pkgs  
318        | otherwise = pkgs
319   return (existing_pkgs ++ [pkg])
320
321 checkDir :: Bool -> String -> IO ()
322 checkDir force d
323  | "$libdir" `isPrefixOf` d = return ()
324         -- can't check this, because we don't know what $libdir is
325  | otherwise = do
326    there <- doesDirectoryExist d
327    when (not there)
328        (dieOrForce force ("`" ++ d ++ "' doesn't exist or isn't a directory\n"))
329
330 checkDep :: [[PackageConfig]] -> Bool -> String -> IO ()
331 checkDep pkgs force n
332   | n `elem` pkg_names = return ()
333   | otherwise = dieOrForce force ("dependency `" ++ n ++ "' doesn't exist\n")
334   where
335     pkg_names = concat (map (map name) pkgs)
336
337 checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
338 checkHSLib dirs auto_ghci_libs force lib = do
339   let batch_lib_file = "lib" ++ lib ++ ".a"
340   bs <- mapM (doesLibExistIn batch_lib_file) dirs
341   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
342         [] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
343                                  "' on library path") 
344         (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
345
346 doesLibExistIn :: String -> String -> IO Bool
347 doesLibExistIn lib d
348  | "$libdir" `isPrefixOf` d = return True
349  | otherwise                = doesFileExist (d ++ '/':lib)
350
351 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
352 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build = do
353   let ghci_lib_file = lib ++ ".o"
354   bs <- mapM (\d -> doesFileExist (d ++ '/':ghci_lib_file)) dirs
355   case [ dir | (exists,dir) <- zip bs dirs, exists ] of
356         [] | auto_build -> 
357                 autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
358            | otherwise  -> 
359                 hPutStrLn stderr ("warning: can't find GHCi lib `"
360                                          ++ ghci_lib_file ++ "'")
361         (_:_) -> return ()
362
363 -- automatically build the GHCi version of a batch lib, 
364 -- using ld --whole-archive.
365
366 autoBuildGHCiLib :: String -> String -> String -> IO ()
367 autoBuildGHCiLib dir batch_file ghci_file = do
368   let ghci_lib_file  = dir ++ '/':ghci_file
369       batch_lib_file = dir ++ '/':batch_file
370   hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
371 #ifdef darwin_TARGET_OS
372   system("ld -r -x -o " ++ ghci_lib_file ++ 
373          " -all_load " ++ batch_lib_file)
374 #else
375   system("ld -r -x -o " ++ ghci_lib_file ++ 
376          " --whole-archive " ++ batch_lib_file)
377 #endif
378   hPutStrLn stderr (" done.")
379
380 -----------------------------------------------------------------------------
381 expandEnvVars :: PackageConfig -> [(String, String)] -> Bool -> IO PackageConfig
382 expandEnvVars pkg defines force = do
383    -- permit _all_ strings to contain ${..} environment variable references,
384    -- arguably too flexible.
385   nm       <- expandString (name pkg)
386   imp_dirs <- expandStrings (import_dirs pkg) 
387   src_dirs <- expandStrings (source_dirs pkg) 
388   lib_dirs <- expandStrings (library_dirs pkg) 
389   hs_libs  <- expandStrings (hs_libraries pkg)
390   ex_libs  <- expandStrings (extra_libraries pkg)
391   inc_dirs <- expandStrings (include_dirs pkg)
392   c_incs   <- expandStrings (c_includes pkg)
393   p_deps   <- expandStrings (package_deps pkg)
394   e_g_opts <- expandStrings (extra_ghc_opts pkg)
395   e_c_opts <- expandStrings (extra_cc_opts pkg)
396   e_l_opts <- expandStrings (extra_ld_opts pkg)
397   f_dirs   <- expandStrings (framework_dirs pkg)
398   e_frames <- expandStrings (extra_frameworks pkg)
399   return (pkg { name            = nm
400               , import_dirs     = imp_dirs
401               , source_dirs     = src_dirs
402               , library_dirs    = lib_dirs
403               , hs_libraries    = hs_libs
404               , extra_libraries = ex_libs
405               , include_dirs    = inc_dirs
406               , c_includes      = c_incs
407               , package_deps    = p_deps
408               , extra_ghc_opts  = e_g_opts
409               , extra_cc_opts   = e_c_opts
410               , extra_ld_opts   = e_l_opts
411               , framework_dirs  = f_dirs
412               , extra_frameworks= e_frames
413               })
414   where
415    expandStrings :: [String] -> IO [String]
416    expandStrings = liftM concat . mapM expandSpecial
417
418    -- Permit substitutions for list-valued variables (but only when
419    -- they occur alone), e.g., package_deps["${deps}"] where env var
420    -- (say) 'deps' is "base,haskell98,network"
421    expandSpecial :: String -> IO [String]
422    expandSpecial str =
423       let expand f = liftM f $ expandString str
424       in case splitString str of
425          [Var _] -> expand (wordsBy (== ','))
426          _ -> expand (\x -> [x])
427
428    expandString :: String -> IO String
429    expandString = liftM concat . mapM expandElem . splitString
430
431    expandElem :: Elem -> IO String
432    expandElem (String s) = return s
433    expandElem (Var v)    = lookupEnvVar v
434
435    lookupEnvVar :: String -> IO String
436    lookupEnvVar nm = 
437      case lookup nm defines of
438        Just x | not (null x) -> return x
439        _      -> 
440         catch (System.getEnv nm)
441            (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
442                                         show nm)
443                       return "")
444
445 data Elem = String String | Var String
446
447 splitString :: String -> [Elem]
448 splitString "" = []
449 splitString str =
450    case break (== '$') str of
451       (pre, _:'{':xs) ->
452          case span (/= '}') xs of
453             (var, _:suf) ->
454                (if null pre then id else (String pre :)) (Var var : splitString suf)
455             _ -> [String str]   -- no closing brace
456       _ -> [String str]   -- no dollar/opening brace combo
457
458 -- wordsBy isSpace == words
459 wordsBy :: (Char -> Bool) -> String -> [String]
460 wordsBy p s = case dropWhile p s of
461   "" -> []
462   s' -> w : wordsBy p s'' where (w,s'') = break p s'
463
464 -----------------------------------------------------------------------------
465
466 getProgramName :: IO String
467 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
468    where str `withoutSuffix` suff
469             | suff `isSuffixOf` str = take (length str - length suff) str
470             | otherwise             = str
471
472 bye :: String -> IO a
473 bye s = putStr s >> exitWith ExitSuccess
474
475 die :: String -> IO a
476 die s = do { hFlush stdout ; hPutStr stderr s; exitWith (ExitFailure 1) }
477
478 dieOrForce :: Bool -> String -> IO ()
479 dieOrForce force s 
480   | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
481   | otherwise = die (s ++ "\n")
482
483 -----------------------------------------------------------------------------
484 -- Exceptions
485
486 #ifndef __GLASGOW_HASKELL__
487
488 eval_catch a h = a `seq` return ()
489 my_catch = IO.catch
490 my_throw = IO.fail
491
492 #else /* GHC */
493
494 my_throw = Exception.throw
495 #if __GLASGOW_HASKELL__ > 408
496 eval_catch = Exception.catch . Exception.evaluate
497 my_catch = Exception.catch
498 #else
499 eval_catch = Exception.catchAll
500 my_catch = Exception.catchAllIO
501 #endif
502
503 #endif
504
505 -----------------------------------------
506 --      Cut and pasted from ghc/compiler/SysTools
507
508 #if defined(mingw32_HOST_OS)
509 subst a b ls = map (\ x -> if x == a then b else x) ls
510 unDosifyPath xs = subst '\\' '/' xs
511
512 getExecDir :: String -> IO (Maybe String)
513 -- (getExecDir cmd) returns the directory in which the current
514 --                  executable, which should be called 'cmd', is running
515 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
516 -- you'll get "/a/b/c" back as the result
517 getExecDir cmd
518   = allocaArray len $ \buf -> do
519         ret <- getModuleFileName nullPtr buf len
520         if ret == 0 then return Nothing
521                     else do s <- peekCString buf
522                             return (Just (reverse (drop (length cmd) 
523                                                         (reverse (unDosifyPath s)))))
524   where
525     len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
526
527 foreign import stdcall "GetModuleFileNameA" unsafe 
528   getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
529 #else
530 getExecDir :: String -> IO (Maybe String) 
531 getExecDir _ = return Nothing
532 #endif