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