1 -----------------------------------------------------------------------------
2 -- $Id: Main.hs,v 1.20 2002/02/03 17:06:12 sof Exp $
4 -- Package management tool
5 -----------------------------------------------------------------------------
11 #ifdef __GLASGOW_HASKELL__
12 import qualified Exception
18 import System ( getEnv, getArgs,
23 import List ( isPrefixOf )
25 #include "../../includes/config.h"
27 #ifdef mingw32_TARGET_OS
34 case getOpt Permute flags args of
35 (clis@(_:_),[],[]) -> runit clis
36 (_,_,errors) -> die (concat errors ++
37 usageInfo usageHeader flags)
42 | List | Add Bool {- True => replace existing info -}
43 | Remove String | Show String
44 | Field String | AutoGHCiLibs
46 isAction (Config _) = False
47 isAction (Field _) = False
48 isAction (Input _) = False
49 isAction (AutoGHCiLibs) = False
52 usageHeader = "ghc-pkg [OPTION...]"
55 Option ['f'] ["config-file"] (ReqArg Config "FILE")
56 "Use the specified package config file",
57 Option ['l'] ["list-packages"] (NoArg List)
58 "List the currently installed packages",
59 Option ['a'] ["add-package"] (NoArg (Add False))
61 Option ['u'] ["update-package"] (NoArg (Add True))
62 "Update package with new configuration",
63 Option ['i'] ["input-file"] (ReqArg Input "FILE")
64 "Read new package info from specified file",
65 Option ['s'] ["show-package"] (ReqArg Show "NAME")
66 "Show the configuration for package NAME",
67 Option [] ["field"] (ReqArg Field "FIELD")
68 "(with --show-package) Show field FIELD only",
69 Option ['r'] ["remove-package"] (ReqArg Remove "NAME")
70 "Remove an installed package",
71 Option ['g'] ["auto-ghci-libs"] (NoArg AutoGHCiLibs)
72 "Automatically build libs for GHCi (with -a)"
75 #ifdef mingw32_TARGET_OS
76 subst a b ls = map (\ x -> if x == a then b else x) ls
78 unDosifyPath xs = subst '\\' '/' xs
83 case [ f | Config f <- clis ] of
84 fs@(_:_) -> return (last fs)
85 #ifndef mingw32_TARGET_OS
86 [] -> die "missing -f option, location of package.conf unknown"
88 [] -> do h <- getModuleHandle Nothing
89 n <- getModuleFileName h
90 return (reverse (drop (length "/bin/ghc-pkg.exe") (reverse (unDosifyPath n))) ++ "/package.conf")
93 let toField "import_dirs" = return import_dirs
94 toField "source_dirs" = return source_dirs
95 toField "library_dirs" = return library_dirs
96 toField "hs_libraries" = return hs_libraries
97 toField "extra_libraries" = return extra_libraries
98 toField "include_dirs" = return include_dirs
99 toField "c_includes" = return c_includes
100 toField "package_deps" = return package_deps
101 toField "extra_ghc_opts" = return extra_ghc_opts
102 toField "extra_cc_opts" = return extra_cc_opts
103 toField "extra_ld_opts" = return extra_ld_opts
104 toField s = die ("unknown field: `" ++ s ++ "'")
106 fields <- mapM toField [ f | Field f <- clis ]
108 s <- readFile conf_file
109 let packages = read s :: [PackageConfig]
110 eval_catch packages (\_ -> die "parse error in package config file")
112 let auto_ghci_libs = any isAuto clis
113 where isAuto AutoGHCiLibs = True; isAuto _ = False
114 input_file = head ([ f | (Input f) <- clis] ++ ["-"])
116 case [ c | c <- clis, isAction c ] of
117 [ List ] -> listPackages packages
118 [ Add upd ] -> addPackage packages conf_file input_file auto_ghci_libs upd
119 [ Remove p ] -> removePackage packages conf_file p
120 [ Show p ] -> showPackage packages conf_file p fields
121 _ -> die (usageInfo usageHeader flags)
124 listPackages :: [PackageConfig] -> IO ()
125 listPackages packages = hPutStrLn stdout (listPkgs packages)
127 showPackage :: [PackageConfig]
130 -> [PackageConfig -> [String]]
132 showPackage packages pkgconf pkg_name fields =
133 case [ p | p <- packages, name p == pkg_name ] of
134 [] -> die ("can't find package `" ++ pkg_name ++ "'")
135 [pkg] | null fields -> hPutStrLn stdout (render (dumpPkgGuts pkg))
136 | otherwise -> hPutStrLn stdout (render (vcat
137 (map (vcat . map text) (map ($pkg) fields))))
138 _ -> die "showPackage: internal error"
140 addPackage :: [PackageConfig] -> FilePath -> FilePath -> Bool -> Bool -> IO ()
141 addPackage packages pkgconf inputFile auto_ghci_libs updatePkg = do
142 checkConfigAccess pkgconf
146 hPutStr stdout "Reading package info from stdin... "
149 hPutStr stdout ("Reading package info from " ++ show f)
151 let new_pkg = read s :: PackageConfig
152 eval_catch new_pkg (\_ -> die "parse error in package info")
153 hPutStrLn stdout "done."
154 hPutStr stdout "Expanding embedded variables..."
155 new_exp_pkg <- expandEnvVars new_pkg
156 hPutStrLn stdout "done."
157 new_details <- validatePackageConfig new_exp_pkg packages auto_ghci_libs updatePkg
158 savePackageConfig pkgconf
159 maybeRestoreOldConfig pkgconf $
160 writeNewConfig pkgconf new_details
162 removePackage :: [PackageConfig] -> FilePath -> String -> IO ()
163 removePackage packages pkgconf pkgName = do
164 checkConfigAccess pkgconf
165 when (pkgName `notElem` map name packages)
166 (die ("package `" ++ pkgName ++ "' not installed"))
167 savePackageConfig pkgconf
168 maybeRestoreOldConfig pkgconf $
169 writeNewConfig pkgconf (filter ((/= pkgName) . name) packages)
171 checkConfigAccess :: FilePath -> IO ()
172 checkConfigAccess pkgconf = do
173 access <- getPermissions pkgconf
174 when (not (writable access))
175 (die "you don't have permission to modify the package configuration file")
177 maybeRestoreOldConfig :: String -> IO () -> IO ()
178 maybeRestoreOldConfig conf_file io
179 = my_catch io (\e -> do
180 hPutStr stdout "\nWARNING: an error was encountered while the new \n\
181 \configuration was being written. Attempting to \n\
182 \restore the old configuration... "
183 renameFile (conf_file ++ ".old") conf_file
184 hPutStrLn stdout "done."
188 writeNewConfig :: String -> [PackageConfig] -> IO ()
189 writeNewConfig conf_file packages = do
190 hPutStr stdout "Writing new package config file... "
191 h <- openFile conf_file WriteMode
192 hPutStrLn h (dumpPackages packages)
194 hPutStrLn stdout "done."
196 savePackageConfig :: String -> IO ()
197 savePackageConfig conf_file = do
198 hPutStr stdout "Saving old package config file... "
199 -- mv rather than cp because we've already done an hGetContents
200 -- on this file so we won't be able to open it for writing
201 -- unless we move the old one out of the way...
202 let oldFile = conf_file ++ ".old"
203 doesExist <- doesFileExist oldFile `catch` (\ _ -> return False)
204 when doesExist (removeFile oldFile `catch` (const $ return ()))
205 catch (renameFile conf_file oldFile)
207 hPutStrLn stderr (unwords [ "Unable to rename "
213 hPutStrLn stdout "done."
215 -----------------------------------------------------------------------------
216 -- Sanity-check a new package config, and automatically build GHCi libs
219 validatePackageConfig :: PackageConfig
223 -> IO [PackageConfig]
224 validatePackageConfig pkg pkgs auto_ghci_libs updatePkg = do
225 when (not updatePkg && (name pkg `elem` map name pkgs))
226 (die ("package `" ++ name pkg ++ "' is already installed"))
227 mapM_ (checkDep pkgs) (package_deps pkg)
228 mapM_ checkDir (import_dirs pkg)
229 mapM_ checkDir (source_dirs pkg)
230 mapM_ checkDir (library_dirs pkg)
231 mapM_ checkDir (include_dirs pkg)
232 mapM_ (checkHSLib (library_dirs pkg) auto_ghci_libs) (hs_libraries pkg)
233 -- ToDo: check these somehow?
234 -- extra_libraries :: [String],
235 -- c_includes :: [String],
237 | updatePkg = filter ((/=(name pkg)).name) pkgs
239 return (existing_pkgs ++ [pkg])
242 there <- doesDirectoryExist d
244 (die ("`" ++ d ++ "' doesn't exist or isn't a directory"))
246 checkDep :: [PackageConfig] -> String -> IO ()
248 | n `elem` map name pkgs = return ()
249 | otherwise = die ("dependency `" ++ n ++ "' doesn't exist")
251 checkHSLib :: [String] -> Bool -> String -> IO ()
252 checkHSLib dirs auto_ghci_libs lib = do
253 let batch_lib_file = "lib" ++ lib ++ ".a"
254 bs <- mapM (\d -> doesFileExist (d ++ '/':batch_lib_file)) dirs
255 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
256 [] -> die ("cannot find `" ++ batch_lib_file ++ "' on library path")
257 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
259 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
260 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build = do
261 let ghci_lib_file = lib ++ ".o"
262 ghci_lib_path = batch_lib_dir ++ '/':ghci_lib_file
263 bs <- mapM (\d -> doesFileExist (d ++ '/':ghci_lib_file)) dirs
264 case [ dir | (exists,dir) <- zip bs dirs, exists ] of
266 autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
268 hPutStrLn stderr ("warning: can't find GHCi lib `"
269 ++ ghci_lib_file ++ "'")
272 -- automatically build the GHCi version of a batch lib,
273 -- using ld --whole-archive.
275 autoBuildGHCiLib dir batch_file ghci_file = do
276 let ghci_lib_file = dir ++ '/':ghci_file
277 batch_lib_file = dir ++ '/':batch_file
278 hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
279 system("ld -r -x -o " ++ ghci_lib_file ++
280 " --whole-archive " ++ batch_lib_file)
281 hPutStrLn stderr (" done.")
283 -----------------------------------------------------------------------------
284 expandEnvVars :: PackageConfig -> IO PackageConfig
285 expandEnvVars pkg = do
286 -- permit _all_ strings to contain ${..} environment variable references,
287 -- arguably too flexible.
288 nm <- expandString (name pkg)
289 imp_dirs <- expandStrings (import_dirs pkg)
290 src_dirs <- expandStrings (source_dirs pkg)
291 lib_dirs <- expandStrings (library_dirs pkg)
292 hs_libs <- expandStrings (hs_libraries pkg)
293 ex_libs <- expandStrings (extra_libraries pkg)
294 inc_dirs <- expandStrings (include_dirs pkg)
295 c_incs <- expandStrings (c_includes pkg)
296 p_deps <- expandStrings (package_deps pkg)
297 e_g_opts <- expandStrings (extra_ghc_opts pkg)
298 e_c_opts <- expandStrings (extra_cc_opts pkg)
299 e_l_opts <- expandStrings (extra_ld_opts pkg)
300 return (pkg { name = nm
301 , import_dirs = imp_dirs
302 , source_dirs = src_dirs
303 , library_dirs = lib_dirs
304 , hs_libraries = hs_libs
305 , extra_libraries = ex_libs
306 , include_dirs = inc_dirs
307 , c_includes = c_incs
308 , package_deps = p_deps
309 , extra_ghc_opts = e_g_opts
310 , extra_cc_opts = e_c_opts
311 , extra_ld_opts = e_l_opts
314 expandStrings = mapM expandString
316 -- Just for fun, keep this in the IO monad.
317 expandString :: String -> IO String
319 case break (=='$') str of
321 case span (/='}') rs of
322 (nm,_:remainder) -> do
323 nm' <- lookupEnvVar nm
324 str' <- expandString remainder
326 _ -> return str -- no closing '}'
330 catch (System.getEnv nm)
331 (\ _ -> die ("Unable to expand variable " ++ show nm))
333 -----------------------------------------------------------------------------
335 die :: String -> IO a
336 die s = do { hFlush stdout ; hPutStrLn stderr s; exitWith (ExitFailure 1) }
338 -----------------------------------------------------------------------------
341 #ifndef __GLASGOW_HASKELL__
343 eval_catch a h = a `seq` return ()
349 my_throw = Exception.throw
350 #if __GLASGOW_HASKELL__ > 408
351 eval_catch = Exception.catch . Exception.evaluate
352 my_catch = Exception.catch
354 eval_catch = Exception.catchAll
355 my_catch = Exception.catchAllIO