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