Main.hs 17.6 KB
Newer Older
1
2
{-# OPTIONS -fglasgow-exts #-}

3
4
5
6
7
8
9
10
-----------------------------------------------------------------------------
-- Package management tool
-----------------------------------------------------------------------------

module Main where

import Package

11
12
13
14
15
#if __GLASGOW_HASKELL__ >= 504
import System.Console.GetOpt
import Text.PrettyPrint
import qualified Control.Exception as Exception
#else
16
17
import GetOpt
import Pretty
18
19
20
import qualified Exception
#endif

21
22
import Monad
import Directory
23
import System	( getEnv, getArgs, getProgName,
sof's avatar
sof committed
24
25
26
		  system, exitWith,
		  ExitCode(..)
		)
27
import IO
28
import List ( isPrefixOf, isSuffixOf )
29

30
31
import ParsePkgConfLite

32
#include "../../includes/config.h"
rrt's avatar
rrt committed
33

sof's avatar
sof committed
34
#ifdef mingw32_HOST_OS
35
import Foreign
36
37
38
39
40
41

#if __GLASGOW_HASKELL__ >= 504
import Foreign.C.String
#else
import CString
#endif
rrt's avatar
rrt committed
42
43
#endif

44
main :: IO ()
45
46
47
48
main = do
  args <- getArgs

  case getOpt Permute flags args of
49
50
51
52
53
54
55
56
57
58
	(cli,_,[]) | DumpHelp `elem` cli -> do
	   prog <- getProgramName
	   bye (usageInfo (usageHeader prog) flags)
	(cli,_,[]) | DumpVersion `elem` cli ->
	   bye copyright
	(cli@(_:_),[],[]) ->
	   runit cli
	(_,_,errors) -> do
	   prog <- getProgramName
	   die (concat errors ++ usageInfo (usageHeader prog) flags)
59

sof's avatar
sof committed
60
61
62
data Flag 
  = Config FilePath
  | Input FilePath
63
64
65
  | List
  | ListLocal
  | Add Bool {- True => replace existing info -}
sof's avatar
sof committed
66
  | Remove String | Show String 
67
  | Field String | AutoGHCiLibs | Force
sof's avatar
sof committed
68
  | DefinedName String String
69
70
  | DumpHelp
  | DumpVersion
71
  deriving (Eq)
72

73
isAction :: Flag -> Bool
74
75
isAction (Config _)     = False
isAction (Field _)      = False
sof's avatar
sof committed
76
isAction (Input _)      = False
77
isAction (AutoGHCiLibs) = False
78
isAction (Force)	= False
sof's avatar
sof committed
79
isAction DefinedName{}  = False
80
isAction _              = True
81

82
83
84
85
86
87
88
89
90
91
copyright :: String
copyright = "GHC package manager version " ++ version ++ "\n"

-- hackery to convice cpp to splice GHC_PKG_VERSION into a string
version :: String
version = tail "\ 
   \ GHC_PKG_VERSION"

usageHeader :: String -> String
usageHeader prog = "Usage: " ++ prog ++ " [OPTION...]\n"
92

93
flags :: [OptDescr Flag]
94
95
flags = [
  Option ['f'] ["config-file"] (ReqArg Config "FILE")
96
	"use the specified package config file",
97
  Option ['l'] ["list-packages"] (NoArg List)
98
 	"list packages in all config files",
99
  Option ['L'] ["list-local-packages"] (NoArg ListLocal)
100
 	"list packages in the specified config file",
sof's avatar
sof committed
101
  Option ['a'] ["add-package"] (NoArg (Add False))
102
 	"add a new package",
sof's avatar
sof committed
103
  Option ['u'] ["update-package"] (NoArg (Add True))
104
 	"update package with new configuration",
sof's avatar
sof committed
105
  Option ['i'] ["input-file"] (ReqArg Input "FILE")
106
	"read new package info from specified file",
107
  Option ['s'] ["show-package"] (ReqArg Show "NAME")
108
 	"show the configuration for package NAME",
109
110
  Option [] ["field"] (ReqArg Field "FIELD")
 	"(with --show-package) Show field FIELD only",
111
112
  Option [] ["force"] (NoArg Force)
 	"ignore missing directories/libraries",
113
  Option ['r'] ["remove-package"] (ReqArg Remove "NAME")
114
 	"remove an installed package",
115
  Option ['g'] ["auto-ghci-libs"] (NoArg AutoGHCiLibs)
116
	"automatically build libs for GHCi (with -a)",
sof's avatar
sof committed
117
  Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
118
119
120
121
122
  	"define NAME as VALUE",
   Option ['?'] ["help"] (NoArg DumpHelp)
	"display this help and exit",
   Option ['V'] ["version"] (NoArg DumpVersion)
	"output version information and exit"
123
  ]
sof's avatar
sof committed
124
125
126
127
128
 where
  toDefined str = 
    case break (=='=') str of
      (nm,[]) -> DefinedName nm []
      (nm,_:val) -> DefinedName nm val
rrt's avatar
rrt committed
129

130
runit :: [Flag] -> IO ()
131
runit clis = do
132
  let err_msg = "missing -f option, location of package.conf unknown\n"
133
  conf_filenames <- 
134
     case [ f | Config f <- clis ] of
135
        fs@(_:_) -> return (reverse fs) -- NOTE reverse
136
137
138
	[] -> do mb_dir <- getExecDir "/bin/ghc-pkg.exe"
		 case mb_dir of
			Nothing  -> die err_msg
139
			Just dir -> return [dir ++ "/package.conf"]
140

141
142
143
144
145
146
147
148
149
150
151
  let toField "import_dirs"     = return import_dirs
      toField "source_dirs"     = return source_dirs
      toField "library_dirs"    = return library_dirs
      toField "hs_libraries"    = return hs_libraries
      toField "extra_libraries" = return extra_libraries
      toField "include_dirs"    = return include_dirs
      toField "c_includes"      = return c_includes
      toField "package_deps"    = return package_deps
      toField "extra_ghc_opts"  = return extra_ghc_opts
      toField "extra_cc_opts"   = return extra_cc_opts
      toField "extra_ld_opts"   = return extra_ld_opts  
152
153
      toField "framework_dirs"  = return framework_dirs  
      toField "extra_frameworks"= return extra_frameworks  
154
      toField s			= die ("unknown field: `" ++ s ++ "'\n")
155
156
157

  fields <- mapM toField [ f | Field f <- clis ]

158
159
160
161
  let read_parse_conf filename = do
	  str <- readFile filename
	  let packages = parsePackageConfig str
	  eval_catch packages
162
	    (\_ -> die (filename ++ ": parse error in package config file\n"))
163
164
165
166
167
168

  pkg_confs <- mapM read_parse_conf conf_filenames

  let conf_filename = head conf_filenames
	-- this is the file we're going to update: the last one specified
	-- on the command-line.
169

170
171
  let auto_ghci_libs = any isAuto clis 
	 where isAuto AutoGHCiLibs = True; isAuto _ = False
sof's avatar
sof committed
172
      input_file = head ([ f | (Input f) <- clis] ++ ["-"])
173

174
      force = Force `elem` clis
sof's avatar
sof committed
175
176
      
      defines = [ (nm,val) | DefinedName nm val <- clis ]
177

178
  case [ c | c <- clis, isAction c ] of
179
180
    [ List ]      -> listPackages pkg_confs conf_filenames
    [ ListLocal ] -> listPackages [head pkg_confs] [""]
sof's avatar
sof committed
181
182
183
    [ Add upd ]  -> addPackage pkg_confs defines 
    			       conf_filename input_file
			       auto_ghci_libs upd force
184
185
    [ Remove p ] -> removePackage pkg_confs conf_filename p
    [ Show p ]   -> showPackage pkg_confs conf_filename p fields
186
187
    _            -> do prog <- getProgramName
		       die (usageInfo (usageHeader prog) flags)
188
189


190
191
192
193
listPackages :: [[PackageConfig]] -> [FilePath] -> IO ()
listPackages pkg_confs conf_filenames = do
  zipWithM_ show_pkgconf pkg_confs conf_filenames
  where show_pkgconf pkg_conf filename =
194
195
196
197
198
199
	  hPutStrLn stdout (render $
		if null filename 
			then packages	
			else text (filename ++ ":") $$ nest 4 packages
		)
	   where packages = fsep (punctuate comma (map (text . name) pkg_conf))
sof's avatar
sof committed
200

201
showPackage :: [[PackageConfig]]
sof's avatar
sof committed
202
203
204
205
	    -> FilePath
	    -> String
	    -> [PackageConfig -> [String]]
	    -> IO ()
206
showPackage pkg_confs _ pkg_name fields =
207
  case [ p | pkgs <- pkg_confs, p <- pkgs, name p == pkg_name ] of
208
    []    -> die ("can't find package `" ++ pkg_name ++ "'\n")
209
210
    [pkg] | null fields -> hPutStrLn stdout (render (dumpPkgGuts pkg))
	  | otherwise   -> hPutStrLn stdout (render (vcat 
211
				(map (vcat . map text) (map ($ pkg) fields))))
212
    _     -> die "showPackage: internal error\n"
213

sof's avatar
sof committed
214
215
216
217
218
219
addPackage :: [[PackageConfig]] -> [(String, String)] 
	   -> FilePath -> FilePath
 	   -> Bool -> Bool -> Bool -> IO ()
addPackage pkg_confs defines 
	   filename inputFile
	   auto_ghci_libs updatePkg force = do
220
  checkConfigAccess filename
sof's avatar
sof committed
221
222
223
224
225
226
227
228
  s <-
    case inputFile of
      "-" -> do
	hPutStr stdout "Reading package info from stdin... "
        getContents
      f   -> do
        hPutStr stdout ("Reading package info from " ++ show f)
	readFile f
229
  let new_pkg = parseOnePackageConfig s
230
  eval_catch new_pkg (\_ -> die "parse error in package info\n")
231
  hPutStrLn stdout "done."
232
  hPutStr stdout "Expanding embedded variables... "
sof's avatar
sof committed
233
  new_exp_pkg <- expandEnvVars new_pkg defines force
sof's avatar
sof committed
234
  hPutStrLn stdout "done."
235
  new_details <- validatePackageConfig new_exp_pkg pkg_confs 
236
			auto_ghci_libs updatePkg force
237
238
239
  savePackageConfig filename
  maybeRestoreOldConfig filename $
    writeNewConfig filename new_details
240

241
242
243
removePackage :: [[PackageConfig]] -> FilePath -> String -> IO ()
removePackage (packages : _) filename pkgName = do  
  checkConfigAccess filename
sof's avatar
sof committed
244
  when (pkgName `notElem` map name packages)
245
       (die (filename ++ ": package `" ++ pkgName ++ "' not found\n"))
246
247
248
  savePackageConfig filename
  maybeRestoreOldConfig filename $
    writeNewConfig filename (filter ((/= pkgName) . name) packages)
249
250

checkConfigAccess :: FilePath -> IO ()
251
252
checkConfigAccess filename = do
  access <- getPermissions filename
253
  when (not (writable access))
254
      (die (filename ++ ": you don't have permission to modify this file\n"))
255

256
257
maybeRestoreOldConfig :: FilePath -> IO () -> IO ()
maybeRestoreOldConfig filename io
258
259
260
261
  = my_catch io (\e -> do
        hPutStr stdout "\nWARNING: an error was encountered while the new \n\ 
        	       \configuration was being written.  Attempting to \n\ 
        	       \restore the old configuration... "
262
	renameFile (filename ++ ".old")  filename
263
264
265
266
        hPutStrLn stdout "done."
	my_throw e
    )

267
268
writeNewConfig :: FilePath -> [PackageConfig] -> IO ()
writeNewConfig filename packages = do
269
  hPutStr stdout "Writing new package config file... "
270
  h <- openFile filename WriteMode
sof's avatar
sof committed
271
  hPutStrLn h (dumpPackages packages)
272
273
274
  hClose h
  hPutStrLn stdout "done."

275
276
savePackageConfig :: FilePath -> IO ()
savePackageConfig filename = do
277
278
279
280
  hPutStr stdout "Saving old package config file... "
    -- mv rather than cp because we've already done an hGetContents
    -- on this file so we won't be able to open it for writing
    -- unless we move the old one out of the way...
281
  let oldFile = filename ++ ".old"
sof's avatar
sof committed
282
283
  doesExist <- doesFileExist oldFile  `catch` (\ _ -> return False)
  when doesExist (removeFile oldFile `catch` (const $ return ()))
284
  catch (renameFile filename oldFile)
sof's avatar
sof committed
285
  	(\ err -> do
sof's avatar
sof committed
286
		hPutStrLn stderr (unwords [ "Unable to rename "
287
					  , show filename
sof's avatar
sof committed
288
289
290
291
					  , " to "
					  , show oldFile
					  ])
		ioError err)
292
293
  hPutStrLn stdout "done."

294
295
296
297
-----------------------------------------------------------------------------
-- Sanity-check a new package config, and automatically build GHCi libs
-- if requested.

sof's avatar
sof committed
298
validatePackageConfig :: PackageConfig 
299
		      -> [[PackageConfig]]
sof's avatar
sof committed
300
301
		      -> Bool
		      -> Bool
302
		      -> Bool
sof's avatar
sof committed
303
		      -> IO [PackageConfig]
304
validatePackageConfig pkg pkg_confs@(pkgs:_) auto_ghci_libs updatePkg force = do
sof's avatar
sof committed
305
  when (not updatePkg && (name pkg `elem` map name pkgs))
306
       (die ("package `" ++ name pkg ++ "' is already installed\n"))
307
  mapM_	(checkDep pkg_confs force) (package_deps pkg)
308
309
310
311
312
  mapM_	(checkDir force) (import_dirs pkg)
  mapM_	(checkDir force) (source_dirs pkg)
  mapM_	(checkDir force) (library_dirs pkg)
  mapM_	(checkDir force) (include_dirs pkg)
  mapM_ (checkHSLib (library_dirs pkg) auto_ghci_libs force) (hs_libraries pkg)
313
314
315
  -- ToDo: check these somehow?
  --	extra_libraries :: [String],
  --	c_includes      :: [String],
sof's avatar
sof committed
316
317
318
319
  let existing_pkgs
       | updatePkg = filter ((/=(name pkg)).name) pkgs  
       | otherwise = pkgs
  return (existing_pkgs ++ [pkg])
320

321
checkDir :: Bool -> String -> IO ()
322
checkDir force d
323
324
325
326
327
 | "$libdir" `isPrefixOf` d = return ()
	-- can't check this, because we don't know what $libdir is
 | otherwise = do
   there <- doesDirectoryExist d
   when (not there)
328
       (dieOrForce force ("`" ++ d ++ "' doesn't exist or isn't a directory\n"))
329

330
checkDep :: [[PackageConfig]] -> Bool -> String -> IO ()
331
checkDep pkgs force n
332
  | n `elem` pkg_names = return ()
333
  | otherwise = dieOrForce force ("dependency `" ++ n ++ "' doesn't exist\n")
334
335
  where
    pkg_names = concat (map (map name) pkgs)
336

337
338
checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
checkHSLib dirs auto_ghci_libs force lib = do
339
  let batch_lib_file = "lib" ++ lib ++ ".a"
340
  bs <- mapM (doesLibExistIn batch_lib_file) dirs
341
  case [ dir | (exists,dir) <- zip bs dirs, exists ] of
342
343
	[] -> dieOrForce force ("cannot find `" ++ batch_lib_file ++
				 "' on library path") 
344
345
	(dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs

346
doesLibExistIn :: String -> String -> IO Bool
347
348
349
350
doesLibExistIn lib d
 | "$libdir" `isPrefixOf` d = return True
 | otherwise                = doesFileExist (d ++ '/':lib)

351
352
353
checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build = do
  let ghci_lib_file = lib ++ ".o"
354
  bs <- mapM (doesLibExistIn ghci_lib_file) dirs
355
356
357
358
359
360
  case [ dir | (exists,dir) <- zip bs dirs, exists ] of
        [] | auto_build -> 
		autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
	   | otherwise  -> 
		hPutStrLn stderr ("warning: can't find GHCi lib `"
					 ++ ghci_lib_file ++ "'")
361
   	(_:_) -> return ()
362
363
364
365

-- automatically build the GHCi version of a batch lib, 
-- using ld --whole-archive.

366
autoBuildGHCiLib :: String -> String -> String -> IO ()
367
368
369
370
autoBuildGHCiLib dir batch_file ghci_file = do
  let ghci_lib_file  = dir ++ '/':ghci_file
      batch_lib_file = dir ++ '/':batch_file
  hPutStr stderr ("building GHCi library `" ++ ghci_lib_file ++ "'...")
371
372
373
374
#ifdef darwin_TARGET_OS
  system("ld -r -x -o " ++ ghci_lib_file ++ 
	 " -all_load " ++ batch_lib_file)
#else
375
376
  system("ld -r -x -o " ++ ghci_lib_file ++ 
	 " --whole-archive " ++ batch_lib_file)
377
#endif
378
379
  hPutStrLn stderr (" done.")

sof's avatar
sof committed
380
-----------------------------------------------------------------------------
sof's avatar
sof committed
381
382
expandEnvVars :: PackageConfig -> [(String, String)] -> Bool -> IO PackageConfig
expandEnvVars pkg defines force = do
sof's avatar
sof committed
383
384
385
386
387
388
389
390
391
392
393
394
395
396
   -- permit _all_ strings to contain ${..} environment variable references,
   -- arguably too flexible.
  nm       <- expandString (name pkg)
  imp_dirs <- expandStrings (import_dirs pkg) 
  src_dirs <- expandStrings (source_dirs pkg) 
  lib_dirs <- expandStrings (library_dirs pkg) 
  hs_libs  <- expandStrings (hs_libraries pkg)
  ex_libs  <- expandStrings (extra_libraries pkg)
  inc_dirs <- expandStrings (include_dirs pkg)
  c_incs   <- expandStrings (c_includes pkg)
  p_deps   <- expandStrings (package_deps pkg)
  e_g_opts <- expandStrings (extra_ghc_opts pkg)
  e_c_opts <- expandStrings (extra_cc_opts pkg)
  e_l_opts <- expandStrings (extra_ld_opts pkg)
397
398
  f_dirs   <- expandStrings (framework_dirs pkg)
  e_frames <- expandStrings (extra_frameworks pkg)
sof's avatar
sof committed
399
400
401
402
403
404
405
406
407
408
409
410
  return (pkg { name            = nm
  	      , import_dirs     = imp_dirs
	      , source_dirs     = src_dirs
	      , library_dirs    = lib_dirs
	      , hs_libraries    = hs_libs
	      , extra_libraries = ex_libs
	      , include_dirs    = inc_dirs
	      , c_includes      = c_incs
	      , package_deps    = p_deps
	      , extra_ghc_opts  = e_g_opts
	      , extra_cc_opts   = e_c_opts
	      , extra_ld_opts   = e_l_opts
411
412
	      , framework_dirs  = f_dirs
	      , extra_frameworks= e_frames
sof's avatar
sof committed
413
414
	      })
  where
415
416
417
418
419
420
421
422
423
424
425
426
427
   expandStrings :: [String] -> IO [String]
   expandStrings = liftM concat . mapM expandSpecial

   -- Permit substitutions for list-valued variables (but only when
   -- they occur alone), e.g., package_deps["${deps}"] where env var
   -- (say) 'deps' is "base,haskell98,network"
   expandSpecial :: String -> IO [String]
   expandSpecial str =
      let expand f = liftM f $ expandString str
      in case splitString str of
         [Var _] -> expand (wordsBy (== ','))
         _ -> expand (\x -> [x])

sof's avatar
sof committed
428
   expandString :: String -> IO String
429
430
431
432
433
   expandString = liftM concat . mapM expandElem . splitString

   expandElem :: Elem -> IO String
   expandElem (String s) = return s
   expandElem (Var v)    = lookupEnvVar v
sof's avatar
sof committed
434

435
   lookupEnvVar :: String -> IO String
sof's avatar
sof committed
436
   lookupEnvVar nm = 
sof's avatar
sof committed
437
438
439
     case lookup nm defines of
       Just x | not (null x) -> return x
       _      -> 
sof's avatar
sof committed
440
	catch (System.getEnv nm)
441
442
443
	   (\ _ -> do dieOrForce force ("Unable to expand variable " ++ 
					show nm)
		      return "")
sof's avatar
sof committed
444

445
446
447
448
449
450
451
452
453
454
455
456
457
458
data Elem = String String | Var String

splitString :: String -> [Elem]
splitString "" = []
splitString str =
   case break (== '$') str of
      (pre, _:'{':xs) ->
         case span (/= '}') xs of
            (var, _:suf) ->
               (if null pre then id else (String pre :)) (Var var : splitString suf)
            _ -> [String str]   -- no closing brace
      _ -> [String str]   -- no dollar/opening brace combo

-- wordsBy isSpace == words
sof's avatar
sof committed
459
460
461
462
463
wordsBy :: (Char -> Bool) -> String -> [String]
wordsBy p s = case dropWhile p s of
  "" -> []
  s' -> w : wordsBy p s'' where (w,s'') = break p s'

464
465
-----------------------------------------------------------------------------

466
467
468
469
470
471
472
473
474
getProgramName :: IO String
getProgramName = liftM (`withoutSuffix` ".bin") getProgName
   where str `withoutSuffix` suff
            | suff `isSuffixOf` str = take (length str - length suff) str
            | otherwise             = str

bye :: String -> IO a
bye s = putStr s >> exitWith ExitSuccess

475
die :: String -> IO a
476
die s = do { hFlush stdout ; hPutStr stderr s; exitWith (ExitFailure 1) }
477

478
479
480
dieOrForce :: Bool -> String -> IO ()
dieOrForce force s 
  | force     = do hFlush stdout; hPutStrLn stderr (s ++ " (ignoring)")
481
  | otherwise = die (s ++ "\n")
482

483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
-----------------------------------------------------------------------------
-- Exceptions

#ifndef __GLASGOW_HASKELL__

eval_catch a h = a `seq` return ()
my_catch = IO.catch
my_throw = IO.fail

#else /* GHC */

my_throw = Exception.throw
#if __GLASGOW_HASKELL__ > 408
eval_catch = Exception.catch . Exception.evaluate
my_catch = Exception.catch
#else
eval_catch = Exception.catchAll
my_catch = Exception.catchAllIO
#endif

#endif
504
505
506
507
508

-----------------------------------------
--	Cut and pasted from ghc/compiler/SysTools

#if defined(mingw32_HOST_OS)
509
510
511
subst a b ls = map (\ x -> if x == a then b else x) ls
unDosifyPath xs = subst '\\' '/' xs

512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
getExecDir :: String -> IO (Maybe String)
-- (getExecDir cmd) returns the directory in which the current
--	  	    executable, which should be called 'cmd', is running
-- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
-- you'll get "/a/b/c" back as the result
getExecDir cmd
  = allocaArray len $ \buf -> do
	ret <- getModuleFileName nullPtr buf len
	if ret == 0 then return Nothing
	            else do s <- peekCString buf
			    return (Just (reverse (drop (length cmd) 
							(reverse (unDosifyPath s)))))
  where
    len = 2048::Int -- Plenty, PATH_MAX is 512 under Win32.

foreign import stdcall "GetModuleFileNameA" unsafe 
  getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
#else
getExecDir :: String -> IO (Maybe String) 
531
getExecDir _ = return Nothing
532
#endif