1 {-# OPTIONS -fglasgow-exts #-}
3 -----------------------------------------------------------------------------
4 -- $Id: Main.hs,v 1.31 2002/10/29 10:53:42 simonpj 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)
57 | List | Add Bool {- True => replace existing info -}
58 | Remove String | Show String
59 | Field String | AutoGHCiLibs | Force
62 isAction (Config _) = False
63 isAction (Field _) = False
64 isAction (Input _) = False
65 isAction (AutoGHCiLibs) = False
66 isAction (Force) = False
69 usageHeader = "ghc-pkg [OPTION...]"
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))
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)"
96 let err_msg = "missing -f option, location of package.conf unknown"
98 case [ f | Config f <- clis ] of
99 fs@(_:_) -> return (last fs)
100 [] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
102 Nothing -> die err_msg
103 Just dir -> return (dir ++ "/package.conf")
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 ++ "'")
120 fields <- mapM toField [ f | Field f <- clis ]
122 s <- readFile conf_file
123 let packages = parsePackageConfig s
124 eval_catch packages (\_ -> die "parse error in package config file")
126 let auto_ghci_libs = any isAuto clis
127 where isAuto AutoGHCiLibs = True; isAuto _ = False
128 input_file = head ([ f | (Input f) <- clis] ++ ["-"])
130 force = Force `elem` clis
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)
141 listPackages :: [PackageConfig] -> IO ()
142 listPackages packages = hPutStrLn stdout (listPkgs packages)
144 showPackage :: [PackageConfig]
147 -> [PackageConfig -> [String]]
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"
157 addPackage :: [PackageConfig] -> FilePath -> FilePath
158 -> Bool -> Bool -> Bool -> IO ()
159 addPackage packages pkgconf inputFile auto_ghci_libs updatePkg force = do
160 checkConfigAccess pkgconf
164 hPutStr stdout "Reading package info from stdin... "
167 hPutStr stdout ("Reading package info from " ++ show 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
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)
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")
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."
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)
213 hPutStrLn stdout "done."
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)
226 hPutStrLn stderr (unwords [ "Unable to rename "
232 hPutStrLn stdout "done."
234 -----------------------------------------------------------------------------
235 -- Sanity-check a new package config, and automatically build GHCi libs
238 validatePackageConfig :: PackageConfig
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],
257 | updatePkg = filter ((/=(name pkg)).name) pkgs
259 return (existing_pkgs ++ [pkg])
262 | "$libdir" `isPrefixOf` d = return ()
263 -- can't check this, because we don't know what $libdir is
265 there <- doesDirectoryExist d
267 (dieOrForce force ("`" ++ d ++ "' doesn't exist or isn't a directory"))
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")
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 ++
281 (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
284 | "$libdir" `isPrefixOf` d = return True
285 | otherwise = doesFileExist (d ++ '/':lib)
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
294 autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
296 hPutStrLn stderr ("warning: can't find GHCi lib `"
297 ++ ghci_lib_file ++ "'")
300 -- automatically build the GHCi version of a batch lib,
301 -- using ld --whole-archive.
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)
311 system("ld -r -x -o " ++ ghci_lib_file ++
312 " --whole-archive " ++ batch_lib_file)
314 hPutStrLn stderr (" done.")
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
351 expandStrings = mapM expandString
353 -- Just for fun, keep this in the IO monad.
354 expandString :: String -> IO String
356 case break (=='$') str of
358 case span (/='}') rs of
359 (nm,_:remainder) -> do
360 nm' <- lookupEnvVar nm
361 str' <- expandString remainder
363 _ -> return str -- no closing '}'
367 catch (System.getEnv nm)
368 (\ _ -> do dieOrForce force ("Unable to expand variable " ++
372 -----------------------------------------------------------------------------
374 die :: String -> IO a
375 die s = do { hFlush stdout ; hPutStrLn stderr s; exitWith (ExitFailure 1) }
377 dieOrForce :: Bool -> String -> IO ()
379 | force = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
382 -----------------------------------------------------------------------------
385 #ifndef __GLASGOW_HASKELL__
387 eval_catch a h = a `seq` return ()
393 my_throw = Exception.throw
394 #if __GLASGOW_HASKELL__ > 408
395 eval_catch = Exception.catch . Exception.evaluate
396 my_catch = Exception.catch
398 eval_catch = Exception.catchAll
399 my_catch = Exception.catchAllIO
404 -----------------------------------------
405 -- Cut and pasted from ghc/compiler/SysTools
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
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
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)))))
424 len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.
426 foreign import stdcall "GetModuleFileNameA" unsafe
427 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
429 getExecDir :: String -> IO (Maybe String)
430 getExecDir s = do return Nothing