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 import GHC.Handle (fdToHandle)
67 import System.Process(runInteractiveCommand)
68 import qualified System.Info(os)
71 -- -----------------------------------------------------------------------------
78 case getOpt Permute (flags ++ deprecFlags) args of
79 (cli,_,[]) | FlagHelp `elem` cli -> do
80 prog <- getProgramName
81 bye (usageInfo (usageHeader prog) flags)
82 (cli,_,[]) | FlagVersion `elem` cli ->
85 case getVerbosity Normal cli of
86 Right v -> runit v cli nonopts
89 prog <- getProgramName
90 die (concat errors ++ usageInfo (usageHeader prog) flags)
92 -- -----------------------------------------------------------------------------
93 -- Command-line syntax
100 | FlagConfig FilePath
101 | FlagGlobalConfig FilePath
109 | FlagVerbosity (Maybe String)
112 flags :: [OptDescr Flag]
114 Option [] ["user"] (NoArg FlagUser)
115 "use the current user's package database",
116 Option [] ["global"] (NoArg FlagGlobal)
117 "use the global package database",
118 Option ['f'] ["package-conf"] (ReqArg FlagConfig "FILE")
119 "use the specified package config file",
120 Option [] ["global-conf"] (ReqArg FlagGlobalConfig "FILE")
121 "location of the global package config",
122 Option [] ["no-user-package-conf"] (NoArg FlagNoUserDb)
123 "never read the user package database",
124 Option [] ["force"] (NoArg FlagForce)
125 "ignore missing dependencies, directories, and libraries",
126 Option [] ["force-files"] (NoArg FlagForceFiles)
127 "ignore missing directories and libraries only",
128 Option ['g'] ["auto-ghci-libs"] (NoArg FlagAutoGHCiLibs)
129 "automatically build libs for GHCi (with register)",
130 Option ['?'] ["help"] (NoArg FlagHelp)
131 "display this help and exit",
132 Option ['V'] ["version"] (NoArg FlagVersion)
133 "output version information and exit",
134 Option [] ["simple-output"] (NoArg FlagSimpleOutput)
135 "print output in easy-to-parse format for some commands",
136 Option [] ["names-only"] (NoArg FlagNamesOnly)
137 "only print package names, not versions; can only be used with list --simple-output",
138 Option [] ["ignore-case"] (NoArg FlagIgnoreCase)
139 "ignore case for substring matching",
140 Option ['v'] ["verbose"] (OptArg FlagVerbosity "Verbosity")
141 "verbosity level (0-2, default 1)"
144 data Verbosity = Silent | Normal | Verbose
145 deriving (Show, Eq, Ord)
147 getVerbosity :: Verbosity -> [Flag] -> Either String Verbosity
148 getVerbosity v [] = Right v
149 getVerbosity _ (FlagVerbosity Nothing : fs) = getVerbosity Verbose fs
150 getVerbosity _ (FlagVerbosity (Just "0") : fs) = getVerbosity Silent fs
151 getVerbosity _ (FlagVerbosity (Just "1") : fs) = getVerbosity Normal fs
152 getVerbosity _ (FlagVerbosity (Just "2") : fs) = getVerbosity Verbose fs
153 getVerbosity _ (FlagVerbosity v : _) = Left ("Bad verbosity: " ++ show v)
154 getVerbosity v (_ : fs) = getVerbosity v fs
156 deprecFlags :: [OptDescr Flag]
158 -- put deprecated flags here
161 ourCopyright :: String
162 ourCopyright = "GHC package manager version " ++ Version.version ++ "\n"
164 usageHeader :: String -> String
165 usageHeader prog = substProg prog $
167 " $p register {filename | -}\n" ++
168 " Register the package using the specified installed package\n" ++
169 " description. The syntax for the latter is given in the $p\n" ++
170 " documentation.\n" ++
172 " $p update {filename | -}\n" ++
173 " Register the package, overwriting any other package with the\n" ++
176 " $p unregister {pkg-id}\n" ++
177 " Unregister the specified package.\n" ++
179 " $p expose {pkg-id}\n" ++
180 " Expose the specified package.\n" ++
182 " $p hide {pkg-id}\n" ++
183 " Hide the specified package.\n" ++
185 " $p list [pkg]\n" ++
186 " List registered packages in the global database, and also the\n" ++
187 " user database if --user is given. If a package name is given\n" ++
188 " all the registered versions will be listed in ascending order.\n" ++
189 " Accepts the --simple-output flag.\n" ++
191 " $p find-module {module}\n" ++
192 " List registered packages exposing module {module} in the global\n" ++
193 " database, and also the user database if --user is given.\n" ++
194 " All the registered versions will be listed in ascending order.\n" ++
195 " Accepts the --simple-output flag.\n" ++
197 " $p latest {pkg-id}\n" ++
198 " Prints the highest registered version of a package.\n" ++
201 " Check the consistency of package depenencies and list broken packages.\n" ++
202 " Accepts the --simple-output flag.\n" ++
204 " $p describe {pkg}\n" ++
205 " Give the registered description for the specified package. The\n" ++
206 " description is returned in precisely the syntax required by $p\n" ++
209 " $p field {pkg} {field}\n" ++
210 " Extract the specified field of the package description for the\n" ++
211 " specified package. Accepts comma-separated multiple fields.\n" ++
214 " Dump the registered description for every package. This is like\n" ++
215 " \"ghc-pkg describe '*'\", except that it is intended to be used\n" ++
216 " by tools that parse the results, rather than humans.\n" ++
218 " Substring matching is supported for {module} in find-module and\n" ++
219 " for {pkg} in list, describe, and field, where a '*' indicates\n" ++
220 " open substring ends (prefix*, *suffix, *infix*).\n" ++
222 " When asked to modify a database (register, unregister, update,\n"++
223 " hide, expose, and also check), ghc-pkg modifies the global database by\n"++
224 " default. Specifying --user causes it to act on the user database,\n"++
225 " or --package-conf can be used to act on another database\n"++
226 " entirely. When multiple of these options are given, the rightmost\n"++
227 " one is used as the database to act upon.\n"++
229 " Commands that query the package database (list, latest, describe,\n"++
230 " field) operate on the list of databases specified by the flags\n"++
231 " --user, --global, and --package-conf. If none of these flags are\n"++
232 " given, the default is --global --user.\n"++
234 " The following optional flags are also accepted:\n"
236 substProg :: String -> String -> String
238 substProg prog ('$':'p':xs) = prog ++ substProg prog xs
239 substProg prog (c:xs) = c : substProg prog xs
241 -- -----------------------------------------------------------------------------
244 data Force = NoForce | ForceFiles | ForceAll | CannotForce
247 data PackageArg = Id PackageIdentifier | Substring String (String->Bool)
249 runit :: Verbosity -> [Flag] -> [String] -> IO ()
250 runit verbosity cli nonopts = do
251 installSignalHandlers -- catch ^C and clean up
252 prog <- getProgramName
255 | FlagForce `elem` cli = ForceAll
256 | FlagForceFiles `elem` cli = ForceFiles
257 | otherwise = NoForce
258 auto_ghci_libs = FlagAutoGHCiLibs `elem` cli
259 splitFields fields = unfoldr splitComma (',':fields)
260 where splitComma "" = Nothing
261 splitComma fs = Just $ break (==',') (tail fs)
263 substringCheck :: String -> Maybe (String -> Bool)
264 substringCheck "" = Nothing
265 substringCheck "*" = Just (const True)
266 substringCheck [_] = Nothing
267 substringCheck (h:t) =
268 case (h, init t, last t) of
269 ('*',s,'*') -> Just (isInfixOf (f s) . f)
270 ('*',_, _ ) -> Just (isSuffixOf (f t) . f)
271 ( _ ,s,'*') -> Just (isPrefixOf (f (h:s)) . f)
273 where f | FlagIgnoreCase `elem` cli = map toLower
276 glob x | System.Info.os=="mingw32" = do
277 -- glob echoes its argument, after win32 filename globbing
278 (_,o,_,_) <- runInteractiveCommand ("glob "++x)
279 txt <- hGetContents o
281 glob x | otherwise = return [x]
284 -- first, parse the command
287 -- dummy command to demonstrate usage and permit testing
288 -- without messing things up; use glob to selectively enable
289 -- windows filename globbing for file parameters
290 -- register, update, FlagGlobalConfig, FlagConfig; others?
291 ["glob", filename] -> do
293 glob filename >>= print
295 ["register", filename] ->
296 registerPackage filename verbosity cli auto_ghci_libs False force
297 ["update", filename] ->
298 registerPackage filename verbosity cli auto_ghci_libs True force
299 ["unregister", pkgid_str] -> do
300 pkgid <- readGlobPkgId pkgid_str
301 unregisterPackage pkgid verbosity cli force
302 ["expose", pkgid_str] -> do
303 pkgid <- readGlobPkgId pkgid_str
304 exposePackage pkgid verbosity cli force
305 ["hide", pkgid_str] -> do
306 pkgid <- readGlobPkgId pkgid_str
307 hidePackage pkgid verbosity cli force
309 listPackages cli Nothing Nothing
310 ["list", pkgid_str] ->
311 case substringCheck pkgid_str of
312 Nothing -> do pkgid <- readGlobPkgId pkgid_str
313 listPackages cli (Just (Id pkgid)) Nothing
314 Just m -> listPackages cli (Just (Substring pkgid_str m)) Nothing
315 ["find-module", moduleName] -> do
316 let match = maybe (==moduleName) id (substringCheck moduleName)
317 listPackages cli Nothing (Just match)
318 ["latest", pkgid_str] -> do
319 pkgid <- readGlobPkgId pkgid_str
320 latestPackage cli pkgid
321 ["describe", pkgid_str] ->
322 case substringCheck pkgid_str of
323 Nothing -> do pkgid <- readGlobPkgId pkgid_str
324 describePackage cli (Id pkgid)
325 Just m -> describePackage cli (Substring pkgid_str m)
326 ["field", pkgid_str, fields] ->
327 case substringCheck pkgid_str of
328 Nothing -> do pkgid <- readGlobPkgId pkgid_str
329 describeField cli (Id pkgid) (splitFields fields)
330 Just m -> describeField cli (Substring pkgid_str m)
339 die ("missing command\n" ++
340 usageInfo (usageHeader prog) flags)
342 die ("command-line syntax error\n" ++
343 usageInfo (usageHeader prog) flags)
345 parseCheck :: ReadP a a -> String -> String -> IO a
346 parseCheck parser str what =
347 case [ x | (x,ys) <- readP_to_S parser str, all isSpace ys ] of
349 _ -> die ("cannot parse \'" ++ str ++ "\' as a " ++ what)
351 readGlobPkgId :: String -> IO PackageIdentifier
352 readGlobPkgId str = parseCheck parseGlobPackageId str "package identifier"
354 parseGlobPackageId :: ReadP r PackageIdentifier
360 return (PackageIdentifier{ pkgName = n, pkgVersion = globVersion }))
362 -- globVersion means "all versions"
363 globVersion :: Version
364 globVersion = Version{ versionBranch=[], versionTags=["*"] }
366 -- -----------------------------------------------------------------------------
369 -- Some commands operate on a single database:
370 -- register, unregister, expose, hide
371 -- however these commands also check the union of the available databases
372 -- in order to check consistency. For example, register will check that
373 -- dependencies exist before registering a package.
375 -- Some commands operate on multiple databases, with overlapping semantics:
376 -- list, describe, field
378 type PackageDBName = FilePath
379 type PackageDB = [InstalledPackageInfo]
381 type NamedPackageDB = (PackageDBName, PackageDB)
382 type PackageDBStack = [NamedPackageDB]
383 -- A stack of package databases. Convention: head is the topmost
384 -- in the stack. Earlier entries override later one.
386 allPackagesInStack :: PackageDBStack -> [InstalledPackageInfo]
387 allPackagesInStack = concatMap snd
389 getPkgDatabases :: Bool -> [Flag] -> IO (PackageDBStack, Maybe PackageDBName)
390 getPkgDatabases modify my_flags = do
391 -- first we determine the location of the global package config. On Windows,
392 -- this is found relative to the ghc-pkg.exe binary, whereas on Unix the
393 -- location is passed to the binary using the --global-config flag by the
395 let err_msg = "missing --global-conf option, location of global package.conf unknown\n"
397 case [ f | FlagGlobalConfig f <- my_flags ] of
398 [] -> do mb_dir <- getLibDir
400 Nothing -> die err_msg
402 do let path = dir </> "package.conf"
403 exists <- doesFileExist path
404 unless exists $ die "Can't find package.conf"
406 fs -> return (last fs)
408 let global_conf_dir = global_conf ++ ".d"
409 global_conf_dir_exists <- doesDirectoryExist global_conf_dir
411 if global_conf_dir_exists
412 then do files <- getDirectoryContents global_conf_dir
413 return [ global_conf_dir ++ '/' : file
415 , isSuffixOf ".conf" file]
418 let no_user_db = FlagNoUserDb `elem` my_flags
420 -- get the location of the user package database, and create it if necessary
421 -- getAppUserDataDirectory can fail (e.g. if $HOME isn't set)
422 appdir <- try $ getAppUserDataDirectory "ghc"
425 if no_user_db then return Nothing else
428 let subdir = targetARCH ++ '-':targetOS ++ '-':Version.version
429 user_conf = dir </> subdir </> "package.conf"
430 user_exists <- doesFileExist user_conf
431 return (Just (user_conf,user_exists))
435 -- If the user database doesn't exist, and this command isn't a
436 -- "modify" command, then we won't attempt to create or use it.
438 | Just (user_conf,user_exists) <- mb_user_conf,
439 modify || user_exists = user_conf : global_confs ++ [global_conf]
440 | otherwise = global_confs ++ [global_conf]
442 e_pkg_path <- try (System.Environment.getEnv "GHC_PACKAGE_PATH")
445 Left _ -> sys_databases
447 | last cs == "" -> init cs ++ sys_databases
449 where cs = parseSearchPath path
451 -- The "global" database is always the one at the bottom of the stack.
452 -- This is the database we modify by default.
453 virt_global_conf = last env_stack
455 let db_flags = [ f | Just f <- map is_db_flag my_flags ]
456 where is_db_flag FlagUser
457 | Just (user_conf, _user_exists) <- mb_user_conf
459 is_db_flag FlagGlobal = Just virt_global_conf
460 is_db_flag (FlagConfig f) = Just f
461 is_db_flag _ = Nothing
463 (final_stack, to_modify) <-
465 then -- For a "read" command, we use all the databases
466 -- specified on the command line. If there are no
467 -- command-line flags specifying databases, the default
468 -- is to use all the ones we know about.
469 if null db_flags then return (env_stack, Nothing)
470 else return (reverse (nub db_flags), Nothing)
472 -- For a "modify" command, treat all the databases as
473 -- a stack, where we are modifying the top one, but it
474 -- can refer to packages in databases further down the
477 -- -f flags on the command line add to the database
478 -- stack, unless any of them are present in the stack
480 flag_stack = filter (`notElem` env_stack)
481 [ f | FlagConfig f <- reverse my_flags ]
484 -- the database we actually modify is the one mentioned
485 -- rightmost on the command-line.
486 to_modify = if null db_flags
487 then Just virt_global_conf
488 else Just (last db_flags)
490 return (flag_stack, to_modify)
492 db_stack <- mapM (readParseDatabase mb_user_conf) final_stack
493 return (db_stack, to_modify)
495 readParseDatabase :: Maybe (PackageDBName,Bool)
497 -> IO (PackageDBName,PackageDB)
498 readParseDatabase mb_user_conf filename
499 -- the user database (only) is allowed to be non-existent
500 | Just (user_conf,False) <- mb_user_conf, filename == user_conf
501 = return (filename, [])
503 = do str <- readFile filename
504 let packages = map convertPackageInfoIn $ read str
505 Exception.evaluate packages
507 die ("error while parsing " ++ filename ++ ": " ++ show e)
508 return (filename,packages)
510 -- -----------------------------------------------------------------------------
513 registerPackage :: FilePath
516 -> Bool -- auto_ghci_libs
520 registerPackage input verbosity my_flags auto_ghci_libs update force = do
521 (db_stack, Just to_modify) <- getPkgDatabases True my_flags
523 db_to_operate_on = my_head "register" $
524 filter ((== to_modify).fst) db_stack
529 when (verbosity >= Normal) $
530 putStr "Reading package info from stdin ... "
533 when (verbosity >= Normal) $
534 putStr ("Reading package info from " ++ show f ++ " ... ")
537 expanded <- expandEnvVars s force
539 pkg <- parsePackageInfo expanded
540 when (verbosity >= Normal) $
543 let unversioned_deps = filter (not . realVersion) (depends pkg)
544 unless (null unversioned_deps) $
545 die ("Unversioned dependencies found: " ++
546 unwords (map display unversioned_deps))
548 let truncated_stack = dropWhile ((/= to_modify).fst) db_stack
549 -- truncate the stack for validation, because we don't allow
550 -- packages lower in the stack to refer to those higher up.
551 validatePackageConfig pkg truncated_stack auto_ghci_libs update force
552 let new_details = filter not_this (snd db_to_operate_on) ++ [pkg]
553 not_this p = package p /= package pkg
554 writeNewConfig verbosity to_modify new_details
558 -> IO InstalledPackageInfo
559 parsePackageInfo str =
560 case parseInstalledPackageInfo str of
561 ParseOk _warns ok -> return ok
562 ParseFailed err -> case locatedErrorMsg err of
563 (Nothing, s) -> die s
564 (Just l, s) -> die (show l ++ ": " ++ s)
566 -- -----------------------------------------------------------------------------
567 -- Exposing, Hiding, Unregistering are all similar
569 exposePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
570 exposePackage = modifyPackage (\p -> [p{exposed=True}])
572 hidePackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
573 hidePackage = modifyPackage (\p -> [p{exposed=False}])
575 unregisterPackage :: PackageIdentifier -> Verbosity -> [Flag] -> Force -> IO ()
576 unregisterPackage = modifyPackage (\_ -> [])
579 :: (InstalledPackageInfo -> [InstalledPackageInfo])
585 modifyPackage fn pkgid verbosity my_flags force = do
586 (db_stack, Just _to_modify) <- getPkgDatabases True{-modify-} my_flags
587 ((db_name, pkgs), ps) <- fmap head $ findPackagesByDB db_stack (Id pkgid)
588 -- let ((db_name, pkgs) : rest_of_stack) = db_stack
589 -- ps <- findPackages [(db_name,pkgs)] (Id pkgid)
591 pids = map package ps
593 | package pkg `elem` pids = fn pkg
595 new_config = concat (map modify pkgs)
598 old_broken = brokenPackages (allPackagesInStack db_stack)
599 rest_of_stack = [ (nm, mypkgs)
600 | (nm, mypkgs) <- db_stack, nm /= db_name ]
601 new_stack = (db_name,new_config) : rest_of_stack
602 new_broken = map package (brokenPackages (allPackagesInStack new_stack))
603 newly_broken = filter (`notElem` map package old_broken) new_broken
605 when (not (null newly_broken)) $
606 dieOrForceAll force ("unregistering " ++ display pkgid ++
607 " would break the following packages: "
608 ++ unwords (map display newly_broken))
610 writeNewConfig verbosity db_name new_config
612 -- -----------------------------------------------------------------------------
615 listPackages :: [Flag] -> Maybe PackageArg -> Maybe (String->Bool) -> IO ()
616 listPackages my_flags mPackageName mModuleName = do
617 let simple_output = FlagSimpleOutput `elem` my_flags
618 (db_stack, _) <- getPkgDatabases False my_flags
619 let db_stack_filtered -- if a package is given, filter out all other packages
620 | Just this <- mPackageName =
621 map (\(conf,pkgs) -> (conf, filter (this `matchesPkg`) pkgs))
623 | Just match <- mModuleName = -- packages which expose mModuleName
624 map (\(conf,pkgs) -> (conf, filter (match `exposedInPkg`) pkgs))
626 | otherwise = db_stack
629 = [ (db, sort_pkgs pkgs) | (db,pkgs) <- db_stack_filtered ]
630 where sort_pkgs = sortBy cmpPkgIds
631 cmpPkgIds pkg1 pkg2 =
632 case pkgName p1 `compare` pkgName p2 of
635 EQ -> pkgVersion p1 `compare` pkgVersion p2
636 where (p1,p2) = (package pkg1, package pkg2)
638 match `exposedInPkg` pkg = any match (map display $ exposedModules pkg)
640 pkg_map = allPackagesInStack db_stack
641 show_func = if simple_output then show_simple else mapM_ (show_normal pkg_map)
643 show_func (reverse db_stack_sorted)
645 where show_normal pkg_map (db_name,pkg_confs) =
646 hPutStrLn stdout (render $
647 text db_name <> colon $$ nest 4 packages
649 where packages = fsep (punctuate comma (map pp_pkg pkg_confs))
650 broken = map package (brokenPackages pkg_map)
652 | package p `elem` broken = braces doc
654 | otherwise = parens doc
655 where doc = text (display (package p))
657 show_simple = simplePackageList my_flags . allPackagesInStack
659 simplePackageList :: [Flag] -> [InstalledPackageInfo] -> IO ()
660 simplePackageList my_flags pkgs = do
661 let showPkg = if FlagNamesOnly `elem` my_flags then display . pkgName
663 strs = map showPkg $ sortBy compPkgIdVer $ map package pkgs
664 when (not (null pkgs)) $
665 hPutStrLn stdout $ concat $ intersperse " " strs
667 -- -----------------------------------------------------------------------------
668 -- Prints the highest (hidden or exposed) version of a package
670 latestPackage :: [Flag] -> PackageIdentifier -> IO ()
671 latestPackage my_flags pkgid = do
672 (db_stack, _) <- getPkgDatabases False my_flags
673 ps <- findPackages db_stack (Id pkgid)
674 show_pkg (sortBy compPkgIdVer (map package ps))
676 show_pkg [] = die "no matches"
677 show_pkg pids = hPutStrLn stdout (display (last pids))
679 -- -----------------------------------------------------------------------------
682 describePackage :: [Flag] -> PackageArg -> IO ()
683 describePackage my_flags pkgarg = do
684 (db_stack, _) <- getPkgDatabases False my_flags
685 ps <- findPackages db_stack pkgarg
688 dumpPackages :: [Flag] -> IO ()
689 dumpPackages my_flags = do
690 (db_stack, _) <- getPkgDatabases False my_flags
691 doDump (allPackagesInStack db_stack)
693 doDump :: [InstalledPackageInfo] -> IO ()
694 doDump = mapM_ putStrLn . intersperse "---" . map showInstalledPackageInfo
696 -- PackageId is can have globVersion for the version
697 findPackages :: PackageDBStack -> PackageArg -> IO [InstalledPackageInfo]
698 findPackages db_stack pkgarg
699 = fmap (concatMap snd) $ findPackagesByDB db_stack pkgarg
701 findPackagesByDB :: PackageDBStack -> PackageArg
702 -> IO [(NamedPackageDB, [InstalledPackageInfo])]
703 findPackagesByDB db_stack pkgarg
704 = case [ (db, matched)
705 | db@(_, pkgs) <- db_stack,
706 let matched = filter (pkgarg `matchesPkg`) pkgs,
707 not (null matched) ] of
708 [] -> die ("cannot find package " ++ pkg_msg pkgarg)
711 pkg_msg (Id pkgid) = display pkgid
712 pkg_msg (Substring pkgpat _) = "matching " ++ pkgpat
714 matches :: PackageIdentifier -> PackageIdentifier -> Bool
716 = (pkgName pid == pkgName pid')
717 && (pkgVersion pid == pkgVersion pid' || not (realVersion pid))
719 matchesPkg :: PackageArg -> InstalledPackageInfo -> Bool
720 (Id pid) `matchesPkg` pkg = pid `matches` package pkg
721 (Substring _ m) `matchesPkg` pkg = m (display (package pkg))
723 compPkgIdVer :: PackageIdentifier -> PackageIdentifier -> Ordering
724 compPkgIdVer p1 p2 = pkgVersion p1 `compare` pkgVersion p2
726 -- -----------------------------------------------------------------------------
729 describeField :: [Flag] -> PackageArg -> [String] -> IO ()
730 describeField my_flags pkgarg fields = do
731 (db_stack, _) <- getPkgDatabases False my_flags
732 fns <- toFields fields
733 ps <- findPackages db_stack pkgarg
734 let top_dir = takeDirectory (fst (last db_stack))
735 mapM_ (selectFields fns) (mungePackagePaths top_dir ps)
736 where toFields [] = return []
737 toFields (f:fs) = case toField f of
738 Nothing -> die ("unknown field: " ++ f)
739 Just fn -> do fns <- toFields fs
741 selectFields fns info = mapM_ (\fn->putStrLn (fn info)) fns
743 mungePackagePaths :: String -> [InstalledPackageInfo] -> [InstalledPackageInfo]
744 -- Replace the strings "$topdir" and "$httptopdir" at the beginning of a path
745 -- with the current topdir (obtained from the -B option).
746 mungePackagePaths top_dir ps = map munge_pkg ps
748 munge_pkg p = p{ importDirs = munge_paths (importDirs p),
749 includeDirs = munge_paths (includeDirs p),
750 libraryDirs = munge_paths (libraryDirs p),
751 frameworkDirs = munge_paths (frameworkDirs p),
752 haddockInterfaces = munge_paths (haddockInterfaces p),
753 haddockHTMLs = munge_paths (haddockHTMLs p)
756 munge_paths = map munge_path
759 | Just p' <- maybePrefixMatch "$topdir" p = top_dir ++ p'
760 | Just p' <- maybePrefixMatch "$httptopdir" p = toHttpPath top_dir ++ p'
763 toHttpPath p = "file:///" ++ p
765 maybePrefixMatch :: String -> String -> Maybe String
766 maybePrefixMatch [] rest = Just rest
767 maybePrefixMatch (_:_) [] = Nothing
768 maybePrefixMatch (p:pat) (r:rest)
769 | p == r = maybePrefixMatch pat rest
770 | otherwise = Nothing
772 toField :: String -> Maybe (InstalledPackageInfo -> String)
773 -- backwards compatibility:
774 toField "import_dirs" = Just $ strList . importDirs
775 toField "source_dirs" = Just $ strList . importDirs
776 toField "library_dirs" = Just $ strList . libraryDirs
777 toField "hs_libraries" = Just $ strList . hsLibraries
778 toField "extra_libraries" = Just $ strList . extraLibraries
779 toField "include_dirs" = Just $ strList . includeDirs
780 toField "c_includes" = Just $ strList . includes
781 toField "package_deps" = Just $ strList . map display. depends
782 toField "extra_cc_opts" = Just $ strList . ccOptions
783 toField "extra_ld_opts" = Just $ strList . ldOptions
784 toField "framework_dirs" = Just $ strList . frameworkDirs
785 toField "extra_frameworks"= Just $ strList . frameworks
786 toField s = showInstalledPackageInfoField s
788 strList :: [String] -> String
792 -- -----------------------------------------------------------------------------
793 -- Check: Check consistency of installed packages
795 checkConsistency :: [Flag] -> IO ()
796 checkConsistency my_flags = do
797 (db_stack, _) <- getPkgDatabases True my_flags
798 -- check behaves like modify for the purposes of deciding which
799 -- databases to use, because ordering is important.
801 let simple_output = FlagSimpleOutput `elem` my_flags
803 let pkgs = allPackagesInStack db_stack
806 (_,es) <- runValidate $ checkPackageConfig p db_stack False True
810 when (not simple_output) $ do
811 reportError ("There are problems in package " ++ display (package p) ++ ":")
812 reportValidateErrors es " " Nothing
816 broken_pkgs <- concat `fmap` mapM checkPackage pkgs
818 let filterOut pkgs1 pkgs2 = filter not_in pkgs2
819 where not_in p = package p `notElem` all_ps
820 all_ps = map package pkgs1
822 let not_broken_pkgs = filterOut broken_pkgs pkgs
823 (_, trans_broken_pkgs) = closure [] not_broken_pkgs
824 all_broken_pkgs = broken_pkgs ++ trans_broken_pkgs
826 when (not (null all_broken_pkgs)) $ do
828 then simplePackageList my_flags all_broken_pkgs
830 reportError ("\nThe following packages are broken, either because they have a problem\n"++
831 "listed above, or because they depend on a broken package.")
832 mapM_ (hPutStrLn stderr . display . package) all_broken_pkgs
834 when (not (null all_broken_pkgs)) $ exitWith (ExitFailure 1)
837 closure :: [InstalledPackageInfo] -> [InstalledPackageInfo]
838 -> ([InstalledPackageInfo], [InstalledPackageInfo])
839 closure pkgs db_stack = go pkgs db_stack
842 case partition (depsAvailable avail) not_avail of
843 ([], not_avail') -> (avail, not_avail')
844 (new_avail, not_avail') -> go (new_avail ++ avail) not_avail'
846 depsAvailable :: [InstalledPackageInfo] -> InstalledPackageInfo
848 depsAvailable pkgs_ok pkg = null dangling
849 where dangling = filter (`notElem` pids) (depends pkg)
850 pids = map package pkgs_ok
852 -- we want mutually recursive groups of package to show up
853 -- as broken. (#1750)
855 brokenPackages :: [InstalledPackageInfo] -> [InstalledPackageInfo]
856 brokenPackages pkgs = snd (closure [] pkgs)
858 -- -----------------------------------------------------------------------------
859 -- Manipulating package.conf files
861 type InstalledPackageInfoString = InstalledPackageInfo_ String
863 convertPackageInfoOut :: InstalledPackageInfo -> InstalledPackageInfoString
864 convertPackageInfoOut
865 (pkgconf@(InstalledPackageInfo { exposedModules = e,
866 hiddenModules = h })) =
867 pkgconf{ exposedModules = map display e,
868 hiddenModules = map display h }
870 convertPackageInfoIn :: InstalledPackageInfoString -> InstalledPackageInfo
872 (pkgconf@(InstalledPackageInfo { exposedModules = e,
873 hiddenModules = h })) =
874 pkgconf{ exposedModules = map convert e,
875 hiddenModules = map convert h }
876 where convert = fromJust . simpleParse
878 writeNewConfig :: Verbosity -> FilePath -> [InstalledPackageInfo] -> IO ()
879 writeNewConfig verbosity filename packages = do
880 when (verbosity >= Normal) $
881 hPutStr stdout "Writing new package config file... "
882 createDirectoryIfMissing True $ takeDirectory filename
883 let shown = concat $ intersperse ",\n "
884 $ map (show . convertPackageInfoOut) packages
885 fileContents = "[" ++ shown ++ "\n]"
886 writeFileAtomic filename fileContents
888 if isPermissionError e
889 then die (filename ++ ": you don't have permission to modify this file")
891 when (verbosity >= Normal) $
892 hPutStrLn stdout "done."
894 -----------------------------------------------------------------------------
895 -- Sanity-check a new package config, and automatically build GHCi libs
898 type ValidateError = (Force,String)
900 newtype Validate a = V { runValidate :: IO (a, [ValidateError]) }
902 instance Monad Validate where
903 return a = V $ return (a, [])
905 (a, es) <- runValidate m
906 (b, es') <- runValidate (k a)
909 verror :: Force -> String -> Validate ()
910 verror f s = V (return ((),[(f,s)]))
912 liftIO :: IO a -> Validate a
913 liftIO k = V (k >>= \a -> return (a,[]))
915 -- returns False if we should die
916 reportValidateErrors :: [ValidateError] -> String -> Maybe Force -> IO Bool
917 reportValidateErrors es prefix mb_force = do
918 oks <- mapM report es
922 | Just force <- mb_force
924 then do reportError (prefix ++ s ++ " (ignoring)")
926 else if f < CannotForce
927 then do reportError (prefix ++ s ++ " (use --force to override)")
929 else do reportError err
931 | otherwise = do reportError err
936 validatePackageConfig :: InstalledPackageInfo
938 -> Bool -- auto-ghc-libs
939 -> Bool -- update, or check
942 validatePackageConfig pkg db_stack auto_ghci_libs update force = do
943 (_,es) <- runValidate $ checkPackageConfig pkg db_stack auto_ghci_libs update
944 ok <- reportValidateErrors es (display (package pkg) ++ ": ") (Just force)
945 when (not ok) $ exitWith (ExitFailure 1)
947 checkPackageConfig :: InstalledPackageInfo
949 -> Bool -- auto-ghc-libs
950 -> Bool -- update, or check
952 checkPackageConfig pkg db_stack auto_ghci_libs update = do
954 checkDuplicates db_stack pkg update
955 mapM_ (checkDep db_stack) (depends pkg)
956 checkDuplicateDepends (depends pkg)
957 mapM_ (checkDir "import-dirs") (importDirs pkg)
958 mapM_ (checkDir "library-dirs") (libraryDirs pkg)
959 mapM_ (checkDir "include-dirs") (includeDirs pkg)
961 mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs) (hsLibraries pkg)
962 -- ToDo: check these somehow?
963 -- extra_libraries :: [String],
964 -- c_includes :: [String],
966 -- When the package name and version are put together, sometimes we can
967 -- end up with a package id that cannot be parsed. This will lead to
968 -- difficulties when the user wants to refer to the package later, so
969 -- we check that the package id can be parsed properly here.
970 checkPackageId :: InstalledPackageInfo -> Validate ()
972 let str = display (package ipi) in
973 case [ x :: PackageIdentifier | (x,ys) <- readP_to_S parse str, all isSpace ys ] of
975 [] -> verror CannotForce ("invalid package identifier: " ++ str)
976 _ -> verror CannotForce ("ambiguous package identifier: " ++ str)
978 checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Validate ()
979 checkDuplicates db_stack pkg update = do
982 (_top_db_name, pkgs) : _ = db_stack
984 -- Check whether this package id already exists in this DB
986 when (not update && (pkgid `elem` map package pkgs)) $
988 "package " ++ display pkgid ++ " is already installed"
991 uncasep = map toLower . display
992 dups = filter ((== uncasep pkgid) . uncasep) (map package pkgs)
994 when (not update && not (null dups)) $ verror ForceAll $
995 "Package names may be treated case-insensitively in the future.\n"++
996 "Package " ++ display pkgid ++
997 " overlaps with: " ++ unwords (map display dups)
1000 checkDir :: String -> String -> Validate ()
1001 checkDir thisfield d
1002 | "$topdir" `isPrefixOf` d = return ()
1003 | "$httptopdir" `isPrefixOf` d = return ()
1004 -- can't check these, because we don't know what $(http)topdir is
1006 there <- liftIO $ doesDirectoryExist d
1008 verror ForceFiles (thisfield ++ ": " ++ d ++ " doesn't exist or isn't a directory")
1010 checkDep :: PackageDBStack -> PackageIdentifier -> Validate ()
1011 checkDep db_stack pkgid
1012 | pkgid `elem` pkgids || (not real_version && name_exists) = return ()
1013 | otherwise = verror ForceAll ("dependency " ++ display pkgid
1014 ++ " doesn't exist")
1016 -- for backwards compat, we treat 0.0 as a special version,
1017 -- and don't check that it actually exists.
1018 real_version = realVersion pkgid
1020 name_exists = any (\p -> pkgName (package p) == name) all_pkgs
1021 name = pkgName pkgid
1023 all_pkgs = allPackagesInStack db_stack
1024 pkgids = map package all_pkgs
1026 checkDuplicateDepends :: [PackageIdentifier] -> Validate ()
1027 checkDuplicateDepends deps
1028 | null dups = return ()
1029 | otherwise = verror ForceAll ("package has duplicate dependencies: " ++
1030 unwords (map display dups))
1032 dups = [ p | (p:_:_) <- group (sort deps) ]
1034 realVersion :: PackageIdentifier -> Bool
1035 realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
1037 checkHSLib :: [String] -> Bool -> String -> Validate ()
1038 checkHSLib dirs auto_ghci_libs lib = do
1039 let batch_lib_file = "lib" ++ lib ++ ".a"
1040 m <- liftIO $ doesFileExistOnPath batch_lib_file dirs
1042 Nothing -> verror ForceFiles ("cannot find " ++ batch_lib_file ++
1044 Just dir -> liftIO $ checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
1046 doesFileExistOnPath :: String -> [FilePath] -> IO (Maybe FilePath)
1047 doesFileExistOnPath file path = go path
1048 where go [] = return Nothing
1049 go (p:ps) = do b <- doesFileExistIn file p
1050 if b then return (Just p) else go ps
1052 doesFileExistIn :: String -> String -> IO Bool
1053 doesFileExistIn lib d
1054 | "$topdir" `isPrefixOf` d = return True
1055 | "$httptopdir" `isPrefixOf` d = return True
1056 | otherwise = doesFileExist (d </> lib)
1058 checkModules :: InstalledPackageInfo -> Validate ()
1059 checkModules pkg = do
1060 mapM_ findModule (exposedModules pkg ++ hiddenModules pkg)
1062 findModule modl = do
1063 -- there's no .hi file for GHC.Prim
1064 if modl == fromString "GHC.Prim" then return () else do
1065 let file = toFilePath modl <.> "hi"
1066 m <- liftIO $ doesFileExistOnPath file (importDirs pkg)
1067 when (isNothing m) $
1068 verror ForceFiles ("file " ++ file ++ " is missing")
1070 checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
1071 checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
1072 | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
1074 m <- doesFileExistOnPath ghci_lib_file dirs
1075 when (isNothing m && ghci_lib_file /= "HSrts.o") $
1076 hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
1078 ghci_lib_file = lib <.> "o"
1080 -- automatically build the GHCi version of a batch lib,
1081 -- using ld --whole-archive.
1083 autoBuildGHCiLib :: String -> String -> String -> IO ()
1084 autoBuildGHCiLib dir batch_file ghci_file = do
1085 let ghci_lib_file = dir ++ '/':ghci_file
1086 batch_lib_file = dir ++ '/':batch_file
1087 hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
1088 #if defined(darwin_HOST_OS)
1089 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
1090 #elif defined(mingw32_HOST_OS)
1091 execDir <- getLibDir
1092 r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1094 r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
1096 when (r /= ExitSuccess) $ exitWith r
1097 hPutStrLn stderr (" done.")
1099 -- -----------------------------------------------------------------------------
1100 -- Searching for modules
1104 findModules :: [FilePath] -> IO [String]
1106 mms <- mapM searchDir paths
1109 searchDir path prefix = do
1110 fs <- getDirectoryEntries path `catch` \_ -> return []
1111 searchEntries path prefix fs
1113 searchEntries path prefix [] = return []
1114 searchEntries path prefix (f:fs)
1115 | looks_like_a_module = do
1116 ms <- searchEntries path prefix fs
1117 return (prefix `joinModule` f : ms)
1118 | looks_like_a_component = do
1119 ms <- searchDir (path </> f) (prefix `joinModule` f)
1120 ms' <- searchEntries path prefix fs
1123 searchEntries path prefix fs
1126 (base,suffix) = splitFileExt f
1127 looks_like_a_module =
1128 suffix `elem` haskell_suffixes &&
1129 all okInModuleName base
1130 looks_like_a_component =
1131 null suffix && all okInModuleName base
1137 -- ---------------------------------------------------------------------------
1138 -- expanding environment variables in the package configuration
1140 expandEnvVars :: String -> Force -> IO String
1141 expandEnvVars str0 force = go str0 ""
1143 go "" acc = return $! reverse acc
1144 go ('$':'{':str) acc | (var, '}':rest) <- break close str
1145 = do value <- lookupEnvVar var
1146 go rest (reverse value ++ acc)
1147 where close c = c == '}' || c == '\n' -- don't span newlines
1151 lookupEnvVar :: String -> IO String
1153 catch (System.Environment.getEnv nm)
1154 (\ _ -> do dieOrForceAll force ("Unable to expand variable " ++
1158 -----------------------------------------------------------------------------
1160 getProgramName :: IO String
1161 getProgramName = liftM (`withoutSuffix` ".bin") getProgName
1162 where str `withoutSuffix` suff
1163 | suff `isSuffixOf` str = take (length str - length suff) str
1166 bye :: String -> IO a
1167 bye s = putStr s >> exitWith ExitSuccess
1169 die :: String -> IO a
1172 dieWith :: Int -> String -> IO a
1175 prog <- getProgramName
1176 hPutStrLn stderr (prog ++ ": " ++ s)
1177 exitWith (ExitFailure ec)
1179 dieOrForceAll :: Force -> String -> IO ()
1180 dieOrForceAll ForceAll s = ignoreError s
1181 dieOrForceAll _other s = dieForcible s
1183 ignoreError :: String -> IO ()
1184 ignoreError s = reportError (s ++ " (ignoring)")
1186 reportError :: String -> IO ()
1187 reportError s = do hFlush stdout; hPutStrLn stderr s
1189 dieForcible :: String -> IO ()
1190 dieForcible s = die (s ++ " (use --force to override)")
1192 my_head :: String -> [a] -> a
1193 my_head s [] = error s
1194 my_head _ (x : _) = x
1196 -----------------------------------------
1197 -- Cut and pasted from ghc/compiler/main/SysTools
1199 #if defined(mingw32_HOST_OS)
1200 subst :: Char -> Char -> String -> String
1201 subst a b ls = map (\ x -> if x == a then b else x) ls
1203 unDosifyPath :: FilePath -> FilePath
1204 unDosifyPath xs = subst '\\' '/' xs
1206 getLibDir :: IO (Maybe String)
1207 getLibDir = fmap (fmap (</> "lib")) $ getExecDir "/bin/ghc-pkg.exe"
1209 -- (getExecDir cmd) returns the directory in which the current
1210 -- executable, which should be called 'cmd', is running
1211 -- So if the full path is /a/b/c/d/e, and you pass "d/e" as cmd,
1212 -- you'll get "/a/b/c" back as the result
1213 getExecDir :: String -> IO (Maybe String)
1215 getExecPath >>= maybe (return Nothing) removeCmdSuffix
1216 where initN n = reverse . drop n . reverse
1217 removeCmdSuffix = return . Just . initN (length cmd) . unDosifyPath
1219 getExecPath :: IO (Maybe String)
1221 allocaArray len $ \buf -> do
1222 ret <- getModuleFileName nullPtr buf len
1223 if ret == 0 then return Nothing
1224 else liftM Just $ peekCString buf
1225 where len = 2048 -- Plenty, PATH_MAX is 512 under Win32.
1227 foreign import stdcall unsafe "GetModuleFileNameA"
1228 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
1231 getLibDir :: IO (Maybe String)
1232 getLibDir = return Nothing
1235 -----------------------------------------
1236 -- Adapted from ghc/compiler/utils/Panic
1238 installSignalHandlers :: IO ()
1239 installSignalHandlers = do
1240 threadid <- myThreadId
1242 interrupt = Exception.throwTo threadid
1243 (Exception.ErrorCall "interrupted")
1245 #if !defined(mingw32_HOST_OS)
1246 installHandler sigQUIT (Catch interrupt) Nothing
1247 installHandler sigINT (Catch interrupt) Nothing
1249 #elif __GLASGOW_HASKELL__ >= 603
1250 -- GHC 6.3+ has support for console events on Windows
1251 -- NOTE: running GHCi under a bash shell for some reason requires
1252 -- you to press Ctrl-Break rather than Ctrl-C to provoke
1253 -- an interrupt. Ctrl-C is getting blocked somewhere, I don't know
1254 -- why --SDM 17/12/2004
1255 let sig_handler ControlC = interrupt
1256 sig_handler Break = interrupt
1257 sig_handler _ = return ()
1259 installHandler (Catch sig_handler)
1262 return () -- nothing
1265 #if __GLASGOW_HASKELL__ <= 604
1266 isInfixOf :: (Eq a) => [a] -> [a] -> Bool
1267 isInfixOf needle haystack = any (isPrefixOf needle) (tails haystack)
1270 #if mingw32_HOST_OS || mingw32_TARGET_OS
1271 throwIOIO :: Exception.IOException -> IO a
1272 throwIOIO = Exception.throwIO
1274 catchIO :: IO a -> (Exception.IOException -> IO a) -> IO a
1275 catchIO = Exception.catch
1278 catchError :: IO a -> (String -> IO a) -> IO a
1279 catchError io handler = io `Exception.catch` handler'
1280 where handler' (Exception.ErrorCall err) = handler err
1283 -- copied from Cabal's Distribution.Simple.Utils, except that we want
1284 -- to use text files here, rather than binary files.
1285 writeFileAtomic :: FilePath -> String -> IO ()
1286 writeFileAtomic targetFile content = do
1287 (newFile, newHandle) <- openNewFile targetDir template
1288 do hPutStr newHandle content
1290 #if mingw32_HOST_OS || mingw32_TARGET_OS
1291 renameFile newFile targetFile
1292 -- If the targetFile exists then renameFile will fail
1293 `catchIO` \err -> do
1294 exists <- doesFileExist targetFile
1296 then do removeFile targetFile
1297 -- Big fat hairy race condition
1298 renameFile newFile targetFile
1299 -- If the removeFile succeeds and the renameFile fails
1300 -- then we've lost the atomic property.
1303 renameFile newFile targetFile
1305 `Exception.onException` do hClose newHandle
1308 template = targetName <.> "tmp"
1309 targetDir | null targetDir_ = "."
1310 | otherwise = targetDir_
1311 --TODO: remove this when takeDirectory/splitFileName is fixed
1312 -- to always return a valid dir
1313 (targetDir_,targetName) = splitFileName targetFile
1315 -- Ugh, this is a copy/paste of code from the base library, but
1316 -- if uses 666 rather than 600 for the permissions.
1317 openNewFile :: FilePath -> String -> IO (FilePath, Handle)
1318 openNewFile dir template = do
1322 -- We split off the last extension, so we can use .foo.ext files
1323 -- for temporary files (hidden on Unix OSes). Unfortunately we're
1324 -- below filepath in the hierarchy here.
1326 case break (== '.') $ reverse template of
1327 -- First case: template contains no '.'s. Just re-reverse it.
1328 (rev_suffix, "") -> (reverse rev_suffix, "")
1329 -- Second case: template contains at least one '.'. Strip the
1330 -- dot from the prefix and prepend it to the suffix (if we don't
1331 -- do this, the unique number will get added after the '.' and
1332 -- thus be part of the extension, which is wrong.)
1333 (rev_suffix, '.':rest) -> (reverse rest, '.':reverse rev_suffix)
1334 -- Otherwise, something is wrong, because (break (== '.')) should
1335 -- always return a pair with either the empty string or a string
1336 -- beginning with '.' as the second component.
1337 _ -> error "bug in System.IO.openTempFile"
1339 oflags = rw_flags .|. o_EXCL
1342 fd <- withCString filepath $ \ f ->
1343 c_open f oflags 0o666
1348 then findTempName (x+1)
1349 else ioError (errnoToIOError "openNewBinaryFile" errno Nothing (Just dir))
1351 -- XXX We want to tell fdToHandle what the filepath is,
1352 -- as any exceptions etc will only be able to report the
1355 #if __GLASGOW_HASKELL__ >= 609
1358 fdToHandle (fromIntegral fd)
1360 `Exception.onException` c_close fd
1361 return (filepath, h)
1363 filename = prefix ++ show x ++ suffix
1364 filepath = dir `combine` filename
1366 -- XXX Copied from GHC.Handle
1367 std_flags, output_flags, rw_flags :: CInt
1368 std_flags = o_NONBLOCK .|. o_NOCTTY
1369 output_flags = std_flags .|. o_CREAT
1370 rw_flags = output_flags .|. o_RDWR
1372 -- | The function splits the given string to substrings
1373 -- using 'isSearchPathSeparator'.
1374 parseSearchPath :: String -> [FilePath]
1375 parseSearchPath path = split path
1377 split :: String -> [String]
1381 _:rest -> chunk : split rest
1385 #ifdef mingw32_HOST_OS
1386 ('\"':xs@(_:_)) | last xs == '\"' -> init xs
1390 (chunk', rest') = break isSearchPathSeparator s