1 {-# OPTIONS -fglasgow-exts #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.35 2003/08/17 01:36:54 sof Exp $
6 -- Package management tool
7 -----------------------------------------------------------------------------
13 #if __GLASGOW_HASKELL__ >= 504
14 import System.Console.GetOpt
15 import Text.PrettyPrint
16 import qualified Control.Exception as Exception
20 import qualified Exception
25 import System ( getEnv, getArgs,
30 import List ( isPrefixOf )
32 import ParsePkgConfLite
34 #include "../../includes/config.h"
36 #ifdef mingw32_HOST_OS
39 #if __GLASGOW_HASKELL__ >= 504
40 import Foreign.C.String
49 case getOpt Permute flags args of
50 (clis@(_:_),[],[]) -> runit clis
51 (_,_,errors) -> die (concat errors ++
52 usageInfo usageHeader flags)
59 | Add Bool {- True => replace existing info -}
60 | Remove String | Show String
61 | Field String | AutoGHCiLibs | Force
64 isAction (Config _) = False
65 isAction (Field _) = False
66 isAction (Input _) = False
67 isAction (AutoGHCiLibs) = False
68 isAction (Force) = False
71 usageHeader = "ghc-pkg [OPTION...]"
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))
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)"
100 let err_msg = "missing -f option, location of package.conf unknown"
102 case [ f | Config f <- clis ] of
103 fs@(_:_) -> return (reverse fs) -- NOTE reverse
104 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
106 Nothing -> die err_msg
107 Just dir -> return [dir ++ "/package.conf"]
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 ++ "'")
124 fields <- mapM toField [ f | Field f <- clis ]
126 let read_parse_conf filename = do
127 str <- readFile filename
128 let packages = parsePackageConfig str
130 (\_ -> die (filename ++ ": parse error in package config file"))
132 pkg_confs <- mapM read_parse_conf conf_filenames
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.
138 let auto_ghci_libs = any isAuto clis
139 where isAuto AutoGHCiLibs = True; isAuto _ = False
140 input_file = head ([ f | (Input f) <- clis] ++ ["-"])
142 force = Force `elem` clis
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)
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 $
161 else text (filename ++ ":") $$ nest 4 packages
163 where packages = fsep (punctuate comma (map (text . name) pkg_conf))
165 showPackage :: [[PackageConfig]]
168 -> [PackageConfig -> [String]]
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"
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
185 hPutStr stdout "Reading package info from stdin... "
188 hPutStr stdout ("Reading package info from " ++ show 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
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)
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"))
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."
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)
234 hPutStrLn stdout "done."
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)
247 hPutStrLn stderr (unwords [ "Unable to rename "
253 hPutStrLn stdout "done."
255 -----------------------------------------------------------------------------
256 -- Sanity-check a new package config, and automatically build GHCi libs
259 validatePackageConfig :: PackageConfig
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],
278 | updatePkg = filter ((/=(name pkg)).name) pkgs
280 return (existing_pkgs ++ [pkg])
283 | "$libdir" `isPrefixOf` d = return ()
284 -- can't check this, because we don't know what $libdir is
286 there <- doesDirectoryExist d
288 (dieOrForce force ("`" ++ d ++ "' doesn't exist or isn't a directory"))
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")
295 pkg_names = concat (map (map name) pkgs)
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 ++
304 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
307 | "$libdir" `isPrefixOf` d = return True
308 | otherwise = doesFileExist (d ++ '/':lib)
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
317 autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
319 hPutStrLn stderr ("warning: can't find GHCi lib `"
320 ++ ghci_lib_file ++ "'")
323 -- automatically build the GHCi version of a batch lib,
324 -- using ld --whole-archive.
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)
334 system("ld -r -x -o " ++ ghci_lib_file ++
335 " --whole-archive " ++ batch_lib_file)
337 hPutStrLn stderr (" done.")
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
374 expandStrings = mapM expandString
376 -- Just for fun, keep this in the IO monad.
377 expandString :: String -> IO String
379 case break (=='$') str of
381 case span (/='}') rs of
382 (nm,_:remainder) -> do
383 nm' <- lookupEnvVar nm
384 str' <- expandString remainder
385 return (xs ++ nm' ++ str')
386 _ -> return str -- no closing '}'
390 catch (System.getEnv nm)
391 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
395 -----------------------------------------------------------------------------
397 die :: String -> IO a
398 die s = do { hFlush stdout ; hPutStrLn stderr s; exitWith (ExitFailure 1) }
400 dieOrForce :: Bool -> String -> IO ()
402 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
405 -----------------------------------------------------------------------------
408 #ifndef __GLASGOW_HASKELL__
410 eval_catch a h = a `seq` return ()
416 my_throw = Exception.throw
417 #if __GLASGOW_HASKELL__ > 408
418 eval_catch = Exception.catch . Exception.evaluate
419 my_catch = Exception.catch
421 eval_catch = Exception.catchAll
422 my_catch = Exception.catchAllIO
427 -----------------------------------------
428 -- Cut and pasted from ghc/compiler/SysTools
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
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
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)))))
447 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
449 foreign import stdcall "GetModuleFileNameA" unsafe
450 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
452 getExecDir :: String -> IO (Maybe String)
453 getExecDir s = do return Nothing