1 {-# OPTIONS -fglasgow-exts -cpp #-}
2 -----------------------------------------------------------------------------
4 -- (c) The University of Glasgow 2004.
6 -- Package management tool
8 -----------------------------------------------------------------------------
12 -- * expanding of variables in new-style package conf
13 -- * version manipulation (checking whether old version exists,
14 -- hiding old version?)
16 module Main (main) where
18 import Version ( version, targetOS, targetARCH )
19 import Distribution.ModuleName hiding (main)
20 import Distribution.InstalledPackageInfo hiding (depends)
21 import Distribution.Compat.ReadP
22 import Distribution.ParseUtils
23 import Distribution.Package
24 import Distribution.Text
25 import Distribution.Version
26 import System.FilePath
27 import System.Cmd ( rawSystem )
28 import System.Directory ( getAppUserDataDirectory, createDirectoryIfMissing )
32 #include "../../includes/ghcconfig.h"
34 import System.Console.GetOpt
35 import Text.PrettyPrint
36 #if __GLASGOW_HASKELL__ >= 609
37 import qualified Control.Exception as Exception
39 import qualified Control.Exception.Extensible as Exception
43 import Data.Char ( isSpace, toLower )
45 import System.Directory ( doesDirectoryExist, getDirectoryContents,
46 doesFileExist, renameFile, removeFile )
47 import System.Exit ( exitWith, ExitCode(..) )
48 import System.Environment ( getArgs, getProgName, getEnv )
50 import System.IO.Error (try)
52 import Control.Concurrent
56 #ifdef mingw32_HOST_OS
57 import GHC.ConsoleHandler
59 import System.Posix hiding (fdToHandle)
62 import IO ( isPermissionError )
63 import System.Posix.Internals
64 #if __GLASGOW_HASKELL__ >= 611
65 import GHC.IO.Handle.FD (fdToHandle)
67 import GHC.Handle (fdToHandle)
71 import System.Process(runInteractiveCommand)
72 import qualified System.Info(os)
75 -- -----------------------------------------------------------------------------
82 case getOpt Permute (flags ++ deprecFlags) args of
83 (cli,_,[]) | FlagHelp `elem` cli -> do
84 prog <- getProgramName
85 bye (usageInfo (usageHeader prog) flags)
86 (cli,_,[]) | FlagVersion `elem` cli ->
89 case getVerbosity Normal cli of
90 Right v -> runit v cli nonopts
93 prog <- getProgramName
94 die (concat errors ++ usageInfo (usageHeader prog) flags)
96 -- -----------------------------------------------------------------------------
97 -- Command-line syntax
104 | FlagConfig FilePath
105 | FlagGlobalConfig FilePath
113 | FlagVerbosity (Maybe String)
116 flags :: [OptDescr Flag]
118 Option [] ["user"] (NoArg FlagUser)
119 "use the current user's package database",
120 Option [] ["global"] (NoArg FlagGlobal)
121 "use the global package database",
122 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
123 "use the specified package config file",
124 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
125 "location of the global package config",
126 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
127 "never read the user package database",
128 Option [] ["force"] (NoArg FlagForce)
129 "ignore missing dependencies, directories, and libraries",
130 Option [] ["force-files"] (NoArg FlagForceFiles)
131 "ignore missing directories and libraries only",
132 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
133 "automatically build libs for GHCi (with register)",
134 Option ['?'] ["help"] (NoArg FlagHelp)
135 "display this help and exit",
136 Option ['V'] ["version"] (NoArg FlagVersion)
137 "output version information and exit",
138 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
139 "print output in easy-to-parse format for some commands",
140 Option [] ["names-only"] (NoArg FlagNamesOnly)
141 "only print package names, not versions; can only be used with list --simple-output",
142 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
143 "ignore case for substring matching",
144 Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
145 "verbosity level (0-2, default 1)"
148 data Verbosity = Silent | Normal | Verbose
149 deriving (Show, Eq, Ord)
151 getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
152 getVerbosity v [] = Right v
153 getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
154 getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
155 getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
156 getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
157 getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
158 getVerbosity v (_ : fs) = getVerbosity v fs
160 deprecFlags :: [OptDescr Flag]
162 -- put deprecated flags here
165 ourCopyright :: String
166 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
168 usageHeader :: String -> String
169 usageHeader prog = substProg prog $
171 " $p register {filename | -}\n" ++
172 " Register the package using the specified installed package\n" ++
173 " description. The syntax for the latter is given in the $p\n" ++
174 " documentation.\n" ++
176 " $p update {filename | -}\n" ++
177 " Register the package, overwriting any other package with the\n" ++
180 " $p unregister {pkg-id}\n" ++
181 " Unregister the specified package.\n" ++
183 " $p expose {pkg-id}\n" ++
184 " Expose the specified package.\n" ++
186 " $p hide {pkg-id}\n" ++
187 " Hide the specified package.\n" ++
189 " $p list [pkg]\n" ++
190 " List registered packages in the global database, and also the\n" ++
191 " user database if --user is given. If a package name is given\n" ++
192 " all the registered versions will be listed in ascending order.\n" ++
193 " Accepts the --simple-output flag.\n" ++
195 " $p find-module {module}\n" ++
196 " List registered packages exposing module {module} in the global\n" ++
197 " database, and also the user database if --user is given.\n" ++
198 " All the registered versions will be listed in ascending order.\n" ++
199 " Accepts the --simple-output flag.\n" ++
201 " $p latest {pkg-id}\n" ++
202 " Prints the highest registered version of a package.\n" ++
205 " Check the consistency of package depenencies and list broken packages.\n" ++
206 " Accepts the --simple-output flag.\n" ++
208 " $p describe {pkg}\n" ++
209 " Give the registered description for the specified package. The\n" ++
210 " description is returned in precisely the syntax required by $p\n" ++
213 " $p field {pkg} {field}\n" ++
214 " Extract the specified field of the package description for the\n" ++
215 " specified package. Accepts comma-separated multiple fields.\n" ++
218 " Dump the registered description for every package. This is like\n" ++
219 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
220 " by tools that parse the results, rather than humans.\n" ++
222 " Substring matching is supported for {module} in find-module and\n" ++
223 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
224 " open substring ends (prefix*, *suffix, *infix*).\n" ++
226 " When asked to modify a database (register, unregister, update,\n"++
227 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
228 " default. Specifying --user causes it to act on the user database,\n"++
229 " or --package-conf can be used to act on another database\n"++
230 " entirely. When multiple of these options are given, the rightmost\n"++
231 " one is used as the database to act upon.\n"++
233 " Commands that query the package database (list, latest, describe,\n"++
234 " field) operate on the list of databases specified by the flags\n"++
235 " --user, --global, and --package-conf. If none of these flags are\n"++
236 " given, the default is --global --user.\n"++
238 " The following optional flags are also accepted:\n"
240 substProg :: String -> String -> String
242 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
243 substProg prog (c:xs) = c : substProg prog xs
245 -- -----------------------------------------------------------------------------
248 data Force = NoForce | ForceFiles | ForceAll | CannotForce
251 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
253 runit :: Verbosity -> [Flag] -> [String] -> IO ()
254 runit verbosity cli nonopts = do
255 installSignalHandlers -- catch ^C and clean up
256 prog <- getProgramName
259 | FlagForce `elem` cli = ForceAll
260 | FlagForceFiles `elem` cli = ForceFiles
261 | otherwise = NoForce
262 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
263 splitFields fields = unfoldr splitComma (',':fields)
264 where splitComma "" = Nothing
265 splitComma fs = Just $ break (==',') (tail fs)
267 substringCheck :: String -> Maybe (String -> Bool)
268 substringCheck "" = Nothing
269 substringCheck "*" = Just (const True)
270 substringCheck [_] = Nothing
271 substringCheck (h:t) =
272 case (h, init t, last t) of
273 ('*',s,'*') -> Just (isInfixOf (f s) . f)
274 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
275 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
277 where f | FlagIgnoreCase `elem` cli = map toLower
280 glob x | System.Info.os=="mingw32" = do
281 -- glob echoes its argument, after win32 filename globbing
282 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
283 txt <- hGetContents o
285 glob x | otherwise = return [x]
288 -- first, parse the command
291 -- dummy command to demonstrate usage and permit testing
292 -- without messing things up; use glob to selectively enable
293 -- windows filename globbing for file parameters
294 -- register, update, FlagGlobalConfig, FlagConfig; others?
295 ["glob", filename] -> do
297 glob filename >>= print
299 ["register", filename] ->
300 registerPackage filename verbosity cli auto_ghci_libs False force
301 ["update", filename] ->
302 registerPackage filename verbosity cli auto_ghci_libs True force
303 ["unregister", pkgid_str] -> do
304 pkgid <- readGlobPkgId pkgid_str
305 unregisterPackage pkgid verbosity cli force
306 ["expose", pkgid_str] -> do
307 pkgid <- readGlobPkgId pkgid_str
308 exposePackage pkgid verbosity cli force
309 ["hide", pkgid_str] -> do
310 pkgid <- readGlobPkgId pkgid_str
311 hidePackage pkgid verbosity cli force
313 listPackages cli Nothing Nothing
314 ["list", pkgid_str] ->
315 case substringCheck pkgid_str of
316 Nothing -> do pkgid <- readGlobPkgId pkgid_str
317 listPackages cli (Just (Id pkgid)) Nothing
318 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
319 ["find-module", moduleName] -> do
320 let match = maybe (==moduleName) id (substringCheck moduleName)
321 listPackages cli Nothing (Just match)
322 ["latest", pkgid_str] -> do
323 pkgid <- readGlobPkgId pkgid_str
324 latestPackage cli pkgid
325 ["describe", pkgid_str] ->
326 case substringCheck pkgid_str of
327 Nothing -> do pkgid <- readGlobPkgId pkgid_str
328 describePackage cli (Id pkgid)
329 Just m -> describePackage cli (Substring pkgid_str m)
330 ["field", pkgid_str, fields] ->
331 case substringCheck pkgid_str of
332 Nothing -> do pkgid <- readGlobPkgId pkgid_str
333 describeField cli (Id pkgid) (splitFields fields)
334 Just m -> describeField cli (Substring pkgid_str m)
343 die ("missing command\n" ++
344 usageInfo (usageHeader prog) flags)
346 die ("command-line syntax error\n" ++
347 usageInfo (usageHeader prog) flags)
349 parseCheck :: ReadP a a -> String -> String -> IO a
350 parseCheck parser str what =
351 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
353 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
355 readGlobPkgId :: String -> IO PackageIdentifier
356 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
358 parseGlobPackageId :: ReadP r PackageIdentifier
364 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
366 -- globVersion means "all versions"
367 globVersion :: Version
368 globVersion = Version{ versionBranch=[], versionTags=["*"] }
370 -- -----------------------------------------------------------------------------
373 -- Some commands operate on a single database:
374 -- register, unregister, expose, hide
375 -- however these commands also check the union of the available databases
376 -- in order to check consistency. For example, register will check that
377 -- dependencies exist before registering a package.
379 -- Some commands operate on multiple databases, with overlapping semantics:
380 -- list, describe, field
382 type PackageDBName = FilePath
383 type PackageDB = [InstalledPackageInfo]
385 type NamedPackageDB = (PackageDBName, PackageDB)
386 type PackageDBStack = [NamedPackageDB]
387 -- A stack of package databases. Convention: head is the topmost
388 -- in the stack. Earlier entries override later one.
390 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
391 allPackagesInStack = concatMap snd
393 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
394 getPkgDatabases modify my_flags = do
395 -- first we determine the location of the global package config. On Windows,
396 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
397 -- location is passed to the binary using the --global-config flag by the
399 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
401 case [ f | FlagGlobalConfig f <- my_flags ] of
402 [] -> do mb_dir <- getLibDir
404 Nothing -> die err_msg
406 do let path = dir </> "package.conf"
407 exists <- doesFileExist path
408 unless exists $ die "Can't find package.conf"
410 fs -> return (last fs)
412 let global_conf_dir = global_conf ++ ".d"
413 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
415 if global_conf_dir_exists
416 then do files <- getDirectoryContents global_conf_dir
417 return [ global_conf_dir ++ '/' : file
419 , isSuffixOf ".conf" file]
422 let no_user_db = FlagNoUserDb `elem` my_flags
424 -- get the location of the user package database, and create it if necessary
425 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
426 appdir <- try $ getAppUserDataDirectory "ghc"
429 if no_user_db then return Nothing else
432 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
433 user_conf = dir </> subdir </> "package.conf"
434 user_exists <- doesFileExist user_conf
435 return (Just (user_conf,user_exists))
439 -- If the user database doesn't exist, and this command isn't a
440 -- "modify" command, then we won't attempt to create or use it.
442 | Just (user_conf,user_exists) <- mb_user_conf,
443 modify || user_exists = user_conf : global_confs ++ [global_conf]
444 | otherwise = global_confs ++ [global_conf]
446 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
449 Left _ -> sys_databases
451 | last cs == "" -> init cs ++ sys_databases
453 where cs = parseSearchPath path
455 -- The "global" database is always the one at the bottom of the stack.
456 -- This is the database we modify by default.
457 virt_global_conf = last env_stack
459 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
460 where is_db_flag FlagUser
461 | Just (user_conf, _user_exists) <- mb_user_conf
463 is_db_flag FlagGlobal = Just virt_global_conf
464 is_db_flag (FlagConfig f) = Just f
465 is_db_flag _ = Nothing
467 (final_stack, to_modify) <-
469 then -- For a "read" command, we use all the databases
470 -- specified on the command line. If there are no
471 -- command-line flags specifying databases, the default
472 -- is to use all the ones we know about.
473 if null db_flags then return (env_stack, Nothing)
474 else return (reverse (nub db_flags), Nothing)
476 -- For a "modify" command, treat all the databases as
477 -- a stack, where we are modifying the top one, but it
478 -- can refer to packages in databases further down the
481 -- -f flags on the command line add to the database
482 -- stack, unless any of them are present in the stack
484 flag_stack = filter (`notElem` env_stack)
485 [ f | FlagConfig f <- reverse my_flags ]
488 -- the database we actually modify is the one mentioned
489 -- rightmost on the command-line.
490 to_modify = if null db_flags
491 then Just virt_global_conf
492 else Just (last db_flags)
494 return (flag_stack, to_modify)
496 db_stack <- mapM (readParseDatabase mb_user_conf) final_stack
497 return (db_stack, to_modify)
499 readParseDatabase :: Maybe (PackageDBName,Bool)
501 -> IO (PackageDBName,PackageDB)
502 readParseDatabase mb_user_conf filename
503 -- the user database (only) is allowed to be non-existent
504 | Just (user_conf,False) <- mb_user_conf, filename == user_conf
505 = return (filename, [])
507 = do str <- readFile filename
508 let packages = map convertPackageInfoIn $ read str
509 _ <- Exception.evaluate packages
511 die ("error while parsing " ++ filename ++ ": " ++ show e)
512 return (filename,packages)
514 -- -----------------------------------------------------------------------------
517 registerPackage :: FilePath
520 -> Bool -- auto_ghci_libs
524 registerPackage input verbosity my_flags auto_ghci_libs update force = do
525 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
527 db_to_operate_on = my_head "register" $
528 filter ((== to_modify).fst) db_stack
533 when (verbosity >= Normal) $
534 putStr "Reading package info from stdin ... "
537 when (verbosity >= Normal) $
538 putStr ("Reading package info from " ++ show f ++ " ... ")
541 expanded <- expandEnvVars s force
543 pkg <- parsePackageInfo expanded
544 when (verbosity >= Normal) $
547 let unversioned_deps = filter (not . realVersion) (depends pkg)
548 unless (null unversioned_deps) $
549 die ("Unversioned dependencies found: " ++
550 unwords (map display unversioned_deps))
552 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
553 -- truncate the stack for validation, because we don't allow
554 -- packages lower in the stack to refer to those higher up.
555 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
556 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
557 not_this p = package p /= package pkg
558 writeNewConfig verbosity to_modify new_details
562 -> IO InstalledPackageInfo
563 parsePackageInfo str =
564 case parseInstalledPackageInfo str of
565 ParseOk _warns ok -> return ok
566 ParseFailed err -> case locatedErrorMsg err of
567 (Nothing, s) -> die s
568 (Just l, s) -> die (show l ++ ": " ++ s)
570 -- -----------------------------------------------------------------------------
571 -- Exposing, Hiding, Unregistering are all similar
573 exposePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
574 exposePackage = modifyPackage (\p -> [p{exposed=True}])
576 hidePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
577 hidePackage = modifyPackage (\p -> [p{exposed=False}])
579 unregisterPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
580 unregisterPackage = modifyPackage (\_ -> [])
583 :: (InstalledPackageInfo -> [InstalledPackageInfo])
589 modifyPackage fn pkgid verbosity my_flags force = do
590 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
591 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
592 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
593 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
595 pids = map package ps
597 | package pkg `elem` pids = fn pkg
599 new_config = concat (map modify pkgs)
602 old_broken = brokenPackages (allPackagesInStack db_stack)
603 rest_of_stack = [ (nm, mypkgs)
604 | (nm, mypkgs) <- db_stack, nm /= db_name ]
605 new_stack = (db_name,new_config) : rest_of_stack
606 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
607 newly_broken = filter (`notElem` map package old_broken) new_broken
609 when (not (null newly_broken)) $
610 dieOrForceAll force ("unregistering " ++ display pkgid ++
611 " would break the following packages: "
612 ++ unwords (map display newly_broken))
614 writeNewConfig verbosity db_name new_config
616 -- -----------------------------------------------------------------------------
619 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
620 listPackages my_flags mPackageName mModuleName = do
621 let simple_output = FlagSimpleOutput `elem` my_flags
622 (db_stack, _) <- getPkgDatabases False my_flags
623 let db_stack_filtered -- if a package is given, filter out all other packages
624 | Just this <- mPackageName =
625 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
627 | Just match <- mModuleName = -- packages which expose mModuleName
628 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
630 | otherwise = db_stack
633 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
634 where sort_pkgs = sortBy cmpPkgIds
635 cmpPkgIds pkg1 pkg2 =
636 case pkgName p1 `compare` pkgName p2 of
639 EQ -> pkgVersion p1 `compare` pkgVersion p2
640 where (p1,p2) = (package pkg1, package pkg2)
642 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
644 pkg_map = allPackagesInStack db_stack
645 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
647 show_func (reverse db_stack_sorted)
649 where show_normal pkg_map (db_name,pkg_confs) =
650 hPutStrLn stdout (render $
651 text db_name <> colon $$ nest 4 packages
653 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
654 broken = map package (brokenPackages pkg_map)
656 | package p `elem` broken = braces doc
658 | otherwise = parens doc
659 where doc = text (display (package p))
661 show_simple = simplePackageList my_flags . allPackagesInStack
663 simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
664 simplePackageList my_flags pkgs = do
665 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
667 strs = map showPkg $ sortBy compPkgIdVer $ map package pkgs
668 when (not (null pkgs)) $
669 hPutStrLn stdout $ concat $ intersperse " " strs
671 -- -----------------------------------------------------------------------------
672 -- Prints the highest (hidden or exposed) version of a package
674 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
675 latestPackage my_flags pkgid = do
676 (db_stack, _) <- getPkgDatabases False my_flags
677 ps <- findPackages db_stack (Id pkgid)
678 show_pkg (sortBy compPkgIdVer (map package ps))
680 show_pkg [] = die "no matches"
681 show_pkg pids = hPutStrLn stdout (display (last pids))
683 -- -----------------------------------------------------------------------------
686 describePackage :: [Flag] -> PackageArg -> IO ()
687 describePackage my_flags pkgarg = do
688 (db_stack, _) <- getPkgDatabases False my_flags
689 ps <- findPackages db_stack pkgarg
692 dumpPackages :: [Flag] -> IO ()
693 dumpPackages my_flags = do
694 (db_stack, _) <- getPkgDatabases False my_flags
695 doDump (allPackagesInStack db_stack)
697 doDump :: [InstalledPackageInfo] -> IO ()
698 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
700 -- PackageId is can have globVersion for the version
701 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
702 findPackages db_stack pkgarg
703 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
705 findPackagesByDB :: PackageDBStack -> PackageArg
706 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
707 findPackagesByDB db_stack pkgarg
708 = case [ (db, matched)
709 | db@(_, pkgs) <- db_stack,
710 let matched = filter (pkgarg `matchesPkg`) pkgs,
711 not (null matched) ] of
712 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
715 pkg_msg (Id pkgid) = display pkgid
716 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
718 matches :: PackageIdentifier -> PackageIdentifier -> Bool
720 = (pkgName pid == pkgName pid')
721 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
723 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
724 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
725 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
727 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
728 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
730 -- -----------------------------------------------------------------------------
733 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
734 describeField my_flags pkgarg fields = do
735 (db_stack, _) <- getPkgDatabases False my_flags
736 fns <- toFields fields
737 ps <- findPackages db_stack pkgarg
738 let top_dir = takeDirectory (fst (last db_stack))
739 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
740 where toFields [] = return []
741 toFields (f:fs) = case toField f of
742 Nothing -> die ("unknown field: " ++ f)
743 Just fn -> do fns <- toFields fs
745 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
747 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
748 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
749 -- with the current topdir (obtained from the -B option).
750 mungePackagePaths top_dir ps = map munge_pkg ps
752 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
753 includeDirs = munge_paths (includeDirs p),
754 libraryDirs = munge_paths (libraryDirs p),
755 frameworkDirs = munge_paths (frameworkDirs p),
756 haddockInterfaces = munge_paths (haddockInterfaces p),
757 haddockHTMLs = munge_paths (haddockHTMLs p)
760 munge_paths = map munge_path
763 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
764 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
767 toHttpPath p = "file:///" ++ p
769 maybePrefixMatch :: String -> String -> Maybe String
770 maybePrefixMatch [] rest = Just rest
771 maybePrefixMatch (_:_) [] = Nothing
772 maybePrefixMatch (p:pat) (r:rest)
773 | p == r = maybePrefixMatch pat rest
774 | otherwise = Nothing
776 toField :: String -> Maybe (InstalledPackageInfo -> String)
777 -- backwards compatibility:
778 toField "import_dirs" = Just $ strList . importDirs
779 toField "source_dirs" = Just $ strList . importDirs
780 toField "library_dirs" = Just $ strList . libraryDirs
781 toField "hs_libraries" = Just $ strList . hsLibraries
782 toField "extra_libraries" = Just $ strList . extraLibraries
783 toField "include_dirs" = Just $ strList . includeDirs
784 toField "c_includes" = Just $ strList . includes
785 toField "package_deps" = Just $ strList . map display. depends
786 toField "extra_cc_opts" = Just $ strList . ccOptions
787 toField "extra_ld_opts" = Just $ strList . ldOptions
788 toField "framework_dirs" = Just $ strList . frameworkDirs
789 toField "extra_frameworks"= Just $ strList . frameworks
790 toField s = showInstalledPackageInfoField s
792 strList :: [String] -> String
796 -- -----------------------------------------------------------------------------
797 -- Check: Check consistency of installed packages
799 checkConsistency :: [Flag] -> IO ()
800 checkConsistency my_flags = do
801 (db_stack, _) <- getPkgDatabases True my_flags
802 -- check behaves like modify for the purposes of deciding which
803 -- databases to use, because ordering is important.
805 let simple_output = FlagSimpleOutput `elem` my_flags
807 let pkgs = allPackagesInStack db_stack
810 (_,es) <- runValidate $ checkPackageConfig p db_stack False True
814 when (not simple_output) $ do
815 reportError ("There are problems in package " ++ display (package p) ++ ":")
816 _ <- reportValidateErrors es " " Nothing
820 broken_pkgs <- concat `fmap` mapM checkPackage pkgs
822 let filterOut pkgs1 pkgs2 = filter not_in pkgs2
823 where not_in p = package p `notElem` all_ps
824 all_ps = map package pkgs1
826 let not_broken_pkgs = filterOut broken_pkgs pkgs
827 (_, trans_broken_pkgs) = closure [] not_broken_pkgs
828 all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
830 when (not (null all_broken_pkgs)) $ do
832 then simplePackageList my_flags all_broken_pkgs
834 reportError ("\nThe following packages are broken, either because they have a problem\n"++
835 "listed above, or because they depend on a broken package.")
836 mapM_ (hPutStrLn stderr . display . package) all_broken_pkgs
838 when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
841 closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
842 -> ([InstalledPackageInfo], [InstalledPackageInfo])
843 closure pkgs db_stack = go pkgs db_stack
846 case partition (depsAvailable avail) not_avail of
847 ([], not_avail') -> (avail, not_avail')
848 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
850 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
852 depsAvailable pkgs_ok pkg = null dangling
853 where dangling = filter (`notElem` pids) (depends pkg)
854 pids = map package pkgs_ok
856 -- we want mutually recursive groups of package to show up
857 -- as broken. (#1750)
859 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
860 brokenPackages pkgs = snd (closure [] pkgs)
862 -- -----------------------------------------------------------------------------
863 -- Manipulating package.conf files
865 type InstalledPackageInfoString = InstalledPackageInfo_ String
867 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
868 convertPackageInfoOut
869 (pkgconf@(InstalledPackageInfo { exposedModules = e,
870 hiddenModules = h })) =
871 pkgconf{ exposedModules = map display e,
872 hiddenModules = map display h }
874 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
876 (pkgconf@(InstalledPackageInfo { exposedModules = e,
877 hiddenModules = h })) =
878 pkgconf{ exposedModules = map convert e,
879 hiddenModules = map convert h }
880 where convert = fromJust . simpleParse
882 writeNewConfig :: Verbosity -> FilePath -> [InstalledPackageInfo] -> IO ()
883 writeNewConfig verbosity filename packages = do
884 when (verbosity >= Normal) $
885 hPutStr stdout "Writing new package config file... "
886 createDirectoryIfMissing True $ takeDirectory filename
887 let shown = concat $ intersperse ",\n "
888 $ map (show . convertPackageInfoOut) packages
889 fileContents = "[" ++ shown ++ "\n]"
890 writeFileAtomic filename fileContents
892 if isPermissionError e
893 then die (filename ++ ": you don't have permission to modify this file")
895 when (verbosity >= Normal) $
896 hPutStrLn stdout "done."
898 -----------------------------------------------------------------------------
899 -- Sanity-check a new package config, and automatically build GHCi libs
902 type ValidateError = (Force,String)
904 newtype Validate a = V { runValidate :: IO (a, [ValidateError]) }
906 instance Monad Validate where
907 return a = V $ return (a, [])
909 (a, es) <- runValidate m
910 (b, es') <- runValidate (k a)
913 verror :: Force -> String -> Validate ()
914 verror f s = V (return ((),[(f,s)]))
916 liftIO :: IO a -> Validate a
917 liftIO k = V (k >>= \a -> return (a,[]))
919 -- returns False if we should die
920 reportValidateErrors :: [ValidateError] -> String -> Maybe Force -> IO Bool
921 reportValidateErrors es prefix mb_force = do
922 oks <- mapM report es
926 | Just force <- mb_force
928 then do reportError (prefix ++ s ++ " (ignoring)")
930 else if f < CannotForce
931 then do reportError (prefix ++ s ++ " (use --force to override)")
933 else do reportError err
935 | otherwise = do reportError err
940 validatePackageConfig :: InstalledPackageInfo
942 -> Bool -- auto-ghc-libs
943 -> Bool -- update, or check
946 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
947 (_,es) <- runValidate $ checkPackageConfig pkg db_stack auto_ghci_libs update
948 ok <- reportValidateErrors es (display (package pkg) ++ ": ") (Just force)
949 when (not ok) $ exitWith (ExitFailure 1)
951 checkPackageConfig :: InstalledPackageInfo
953 -> Bool -- auto-ghc-libs
954 -> Bool -- update, or check
956 checkPackageConfig pkg db_stack auto_ghci_libs update = do
958 checkDuplicates db_stack pkg update
959 mapM_ (checkDep db_stack) (depends pkg)
960 checkDuplicateDepends (depends pkg)
961 mapM_ (checkDir "import-dirs") (importDirs pkg)
962 mapM_ (checkDir "library-dirs") (libraryDirs pkg)
963 mapM_ (checkDir "include-dirs") (includeDirs pkg)
965 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg)
966 -- ToDo: check these somehow?
967 -- extra_libraries :: [String],
968 -- c_includes :: [String],
970 -- When the package name and version are put together, sometimes we can
971 -- end up with a package id that cannot be parsed. This will lead to
972 -- difficulties when the user wants to refer to the package later, so
973 -- we check that the package id can be parsed properly here.
974 checkPackageId :: InstalledPackageInfo -> Validate ()
976 let str = display (package ipi) in
977 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
979 [] -> verror CannotForce ("invalid package identifier: " ++ str)
980 _ -> verror CannotForce ("ambiguous package identifier: " ++ str)
982 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Validate ()
983 checkDuplicates db_stack pkg update = do
986 (_top_db_name, pkgs) : _ = db_stack
988 -- Check whether this package id already exists in this DB
990 when (not update && (pkgid `elem` map package pkgs)) $
992 "package " ++ display pkgid ++ " is already installed"
995 uncasep = map toLower . display
996 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
998 when (not update && not (null dups)) $ verror ForceAll $
999 "Package names may be treated case-insensitively in the future.\n"++
1000 "Package " ++ display pkgid ++
1001 " overlaps with: " ++ unwords (map display dups)
1004 checkDir :: String -> String -> Validate ()
1005 checkDir thisfield d
1006 | "$topdir" `isPrefixOf` d = return ()
1007 | "$httptopdir" `isPrefixOf` d = return ()
1008 -- can't check these, because we don't know what $(http)topdir is
1010 there <- liftIO $ doesDirectoryExist d
1012 verror ForceFiles (thisfield ++ ": " ++ d ++ " doesn't exist or isn't a directory")
1014 checkDep :: PackageDBStack -> PackageIdentifier -> Validate ()
1015 checkDep db_stack pkgid
1016 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
1017 | otherwise = verror ForceAll ("dependency " ++ display pkgid
1018 ++ " doesn't exist")
1020 -- for backwards compat, we treat 0.0 as a special version,
1021 -- and don't check that it actually exists.
1022 real_version = realVersion pkgid
1024 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
1025 name = pkgName pkgid
1027 all_pkgs = allPackagesInStack db_stack
1028 pkgids = map package all_pkgs
1030 checkDuplicateDepends :: [PackageIdentifier] -> Validate ()
1031 checkDuplicateDepends deps
1032 | null dups = return ()
1033 | otherwise = verror ForceAll ("package has duplicate dependencies: " ++
1034 unwords (map display dups))
1036 dups = [ p | (p:_:_) <- group (sort deps) ]
1038 realVersion :: PackageIdentifier -> Bool
1039 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
1041 checkHSLib :: [String] -> Bool -> String -> Validate ()
1042 checkHSLib dirs auto_ghci_libs lib = do
1043 let batch_lib_file = "lib" ++ lib ++ ".a"
1044 m <- liftIO $ doesFileExistOnPath batch_lib_file dirs
1046 Nothing -> verror ForceFiles ("cannot find " ++ batch_lib_file ++
1048 Just dir -> liftIO $ checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
1050 doesFileExistOnPath :: String -> [FilePath] -> IO (Maybe FilePath)
1051 doesFileExistOnPath file path = go path
1052 where go [] = return Nothing
1053 go (p:ps) = do b <- doesFileExistIn file p
1054 if b then return (Just p) else go ps
1056 doesFileExistIn :: String -> String -> IO Bool
1057 doesFileExistIn lib d
1058 | "$topdir" `isPrefixOf` d = return True
1059 | "$httptopdir" `isPrefixOf` d = return True
1060 | otherwise = doesFileExist (d </> lib)
1062 checkModules :: InstalledPackageInfo -> Validate ()
1063 checkModules pkg = do
1064 mapM_ findModule (exposedModules pkg ++ hiddenModules pkg)
1066 findModule modl = do
1067 -- there's no .hi file for GHC.Prim
1068 if modl == fromString "GHC.Prim" then return () else do
1069 let file = toFilePath modl <.> "hi"
1070 m <- liftIO $ doesFileExistOnPath file (importDirs pkg)
1071 when (isNothing m) $
1072 verror ForceFiles ("file " ++ file ++ " is missing")
1074 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
1075 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
1076 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
1078 m <- doesFileExistOnPath ghci_lib_file dirs
1079 when (isNothing m && ghci_lib_file /= "HSrts.o") $
1080 hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
1082 ghci_lib_file = lib <.> "o"
1084 -- automatically build the GHCi version of a batch lib,
1085 -- using ld --whole-archive.
1087 autoBuildGHCiLib :: String -> String -> String -> IO ()
1088 autoBuildGHCiLib dir batch_file ghci_file = do
1089 let ghci_lib_file = dir ++ '/':ghci_file
1090 batch_lib_file = dir ++ '/':batch_file
1091 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
1092 #if defined(darwin_HOST_OS)
1093 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
1094 #elif defined(mingw32_HOST_OS)
1095 execDir <- getLibDir
1096 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1098 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1100 when (r /= ExitSuccess) $ exitWith r
1101 hPutStrLn stderr (" done.")
1103 -- -----------------------------------------------------------------------------
1104 -- Searching for modules
1108 findModules :: [FilePath] -> IO [String]
1110 mms <- mapM searchDir paths
1113 searchDir path prefix = do
1114 fs <- getDirectoryEntries path `catch` \_ -> return []
1115 searchEntries path prefix fs
1117 searchEntries path prefix [] = return []
1118 searchEntries path prefix (f:fs)
1119 | looks_like_a_module = do
1120 ms <- searchEntries path prefix fs
1121 return (prefix `joinModule` f : ms)
1122 | looks_like_a_component = do
1123 ms <- searchDir (path </> f) (prefix `joinModule` f)
1124 ms' <- searchEntries path prefix fs
1127 searchEntries path prefix fs
1130 (base,suffix) = splitFileExt f
1131 looks_like_a_module =
1132 suffix `elem` haskell_suffixes &&
1133 all okInModuleName base
1134 looks_like_a_component =
1135 null suffix && all okInModuleName base
1141 -- ---------------------------------------------------------------------------
1142 -- expanding environment variables in the package configuration
1144 expandEnvVars :: String -> Force -> IO String
1145 expandEnvVars str0 force = go str0 ""
1147 go "" acc = return $! reverse acc
1148 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1149 = do value <- lookupEnvVar var
1150 go rest (reverse value ++ acc)
1151 where close c = c == '}' || c == '\n' -- don't span newlines
1155 lookupEnvVar :: String -> IO String
1157 catch (System.Environment.getEnv nm)
1158 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1162 -----------------------------------------------------------------------------
1164 getProgramName :: IO String
1165 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1166 where str `withoutSuffix` suff
1167 | suff `isSuffixOf` str = take (length str - length suff) str
1170 bye :: String -> IO a
1171 bye s = putStr s >> exitWith ExitSuccess
1173 die :: String -> IO a
1176 dieWith :: Int -> String -> IO a
1179 prog <- getProgramName
1180 hPutStrLn stderr (prog ++ ": " ++ s)
1181 exitWith (ExitFailure ec)
1183 dieOrForceAll :: Force -> String -> IO ()
1184 dieOrForceAll ForceAll s = ignoreError s
1185 dieOrForceAll _other s = dieForcible s
1187 ignoreError :: String -> IO ()
1188 ignoreError s = reportError (s ++ " (ignoring)")
1190 reportError :: String -> IO ()
1191 reportError s = do hFlush stdout; hPutStrLn stderr s
1193 dieForcible :: String -> IO ()
1194 dieForcible s = die (s ++ " (use --force to override)")
1196 my_head :: String -> [a] -> a
1197 my_head s [] = error s
1198 my_head _ (x : _) = x
1200 -----------------------------------------
1201 -- Cut and pasted from ghc/compiler/main/SysTools
1203 #if defined(mingw32_HOST_OS)
1204 subst :: Char -> Char -> String -> String
1205 subst a b ls = map (\ x -> if x == a then b else x) ls
1207 unDosifyPath :: FilePath -> FilePath
1208 unDosifyPath xs = subst '\\' '/' xs
1210 getLibDir :: IO (Maybe String)
1211 getLibDir = fmap (fmap (</> "lib")) $ getExecDir "/bin/ghc-pkg.exe"
1213 -- (getExecDir cmd) returns the directory in which the current
1214 -- executable, which should be called 'cmd', is running
1215 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1216 -- you'll get "/a/b/c" back as the result
1217 getExecDir :: String -> IO (Maybe String)
1219 getExecPath >>= maybe (return Nothing) removeCmdSuffix
1220 where initN n = reverse . drop n . reverse
1221 removeCmdSuffix = return . Just . initN (length cmd) . unDosifyPath
1223 getExecPath :: IO (Maybe String)
1225 allocaArray len $ \buf -> do
1226 ret <- getModuleFileName nullPtr buf len
1227 if ret == 0 then return Nothing
1228 else liftM Just $ peekCString buf
1229 where len = 2048 -- Plenty, PATH_MAX is 512 under Win32.
1231 foreign import stdcall unsafe "GetModuleFileNameA"
1232 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1235 getLibDir :: IO (Maybe String)
1236 getLibDir = return Nothing
1239 -----------------------------------------
1240 -- Adapted from ghc/compiler/utils/Panic
1242 installSignalHandlers :: IO ()
1243 installSignalHandlers = do
1244 threadid <- myThreadId
1246 interrupt = Exception.throwTo threadid
1247 (Exception.ErrorCall "interrupted")
1249 #if !defined(mingw32_HOST_OS)
1250 _ <- installHandler sigQUIT (Catch interrupt) Nothing
1251 _ <- installHandler sigINT (Catch interrupt) Nothing
1253 #elif __GLASGOW_HASKELL__ >= 603
1254 -- GHC 6.3+ has support for console events on Windows
1255 -- NOTE: running GHCi under a bash shell for some reason requires
1256 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1257 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1258 -- why --SDM 17/12/2004
1259 let sig_handler ControlC = interrupt
1260 sig_handler Break = interrupt
1261 sig_handler _ = return ()
1263 _ <- installHandler (Catch sig_handler)
1266 return () -- nothing
1269 #if __GLASGOW_HASKELL__ <= 604
1270 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1271 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1274 #if mingw32_HOST_OS || mingw32_TARGET_OS
1275 throwIOIO :: Exception.IOException -> IO a
1276 throwIOIO = Exception.throwIO
1278 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1279 catchIO = Exception.catch
1282 catchError :: IO a -> (String -> IO a) -> IO a
1283 catchError io handler = io `Exception.catch` handler'
1284 where handler' (Exception.ErrorCall err) = handler err
1287 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1288 -- to use text files here, rather than binary files.
1289 writeFileAtomic :: FilePath -> String -> IO ()
1290 writeFileAtomic targetFile content = do
1291 (newFile, newHandle) <- openNewFile targetDir template
1292 do hPutStr newHandle content
1294 #if mingw32_HOST_OS || mingw32_TARGET_OS
1295 renameFile newFile targetFile
1296 -- If the targetFile exists then renameFile will fail
1297 `catchIO` \err -> do
1298 exists <- doesFileExist targetFile
1300 then do removeFile targetFile
1301 -- Big fat hairy race condition
1302 renameFile newFile targetFile
1303 -- If the removeFile succeeds and the renameFile fails
1304 -- then we've lost the atomic property.
1307 renameFile newFile targetFile
1309 `Exception.onException` do hClose newHandle
1312 template = targetName <.> "tmp"
1313 targetDir | null targetDir_ = "."
1314 | otherwise = targetDir_
1315 --TODO: remove this when takeDirectory/splitFileName is fixed
1316 -- to always return a valid dir
1317 (targetDir_,targetName) = splitFileName targetFile
1319 -- Ugh, this is a copy/paste of code from the base library, but
1320 -- if uses 666 rather than 600 for the permissions.
1321 openNewFile :: FilePath -> String -> IO (FilePath, Handle)
1322 openNewFile dir template = do
1326 -- We split off the last extension, so we can use .foo.ext files
1327 -- for temporary files (hidden on Unix OSes). Unfortunately we're
1328 -- below filepath in the hierarchy here.
1330 case break (== '.') $ reverse template of
1331 -- First case: template contains no '.'s. Just re-reverse it.
1332 (rev_suffix, "") -> (reverse rev_suffix, "")
1333 -- Second case: template contains at least one '.'. Strip the
1334 -- dot from the prefix and prepend it to the suffix (if we don't
1335 -- do this, the unique number will get added after the '.' and
1336 -- thus be part of the extension, which is wrong.)
1337 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
1338 -- Otherwise, something is wrong, because (break (== '.')) should
1339 -- always return a pair with either the empty string or a string
1340 -- beginning with '.' as the second component.
1341 _ -> error "bug in System.IO.openTempFile"
1343 oflags = rw_flags .|. o_EXCL
1345 #if __GLASGOW_HASKELL__ < 611
1346 withFilePath = withCString
1350 fd <- withFilePath filepath $ \ f ->
1351 c_open f oflags 0o666
1356 then findTempName (x+1)
1357 else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
1359 -- XXX We want to tell fdToHandle what the filepath is,
1360 -- as any exceptions etc will only be able to report the
1363 #if __GLASGOW_HASKELL__ >= 609
1366 fdToHandle (fromIntegral fd)
1368 `Exception.onException` c_close fd
1369 return (filepath, h)
1371 filename = prefix ++ show x ++ suffix
1372 filepath = dir `combine` filename
1374 -- XXX Copied from GHC.Handle
1375 std_flags, output_flags, rw_flags :: CInt
1376 std_flags = o_NONBLOCK .|. o_NOCTTY
1377 output_flags = std_flags .|. o_CREAT
1378 rw_flags = output_flags .|. o_RDWR
1380 -- | The function splits the given string to substrings
1381 -- using 'isSearchPathSeparator'.
1382 parseSearchPath :: String -> [FilePath]
1383 parseSearchPath path = split path
1385 split :: String -> [String]
1389 _:rest -> chunk : split rest
1393 #ifdef mingw32_HOST_OS
1394 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1398 (chunk', rest') = break isSearchPathSeparator s