+validatePackageConfig :: InstalledPackageInfo
+ -> PackageDBStack
+ -> Bool -- auto-ghc-libs
+ -> Bool -- update
+ -> Bool -- force
+ -> IO [PackageIdentifier]
+validatePackageConfig pkg db_stack auto_ghci_libs update force = do
+ checkPackageId pkg
+ overlaps <- checkDuplicates db_stack pkg update force
+ mapM_ (checkDep db_stack force) (depends pkg)
+ mapM_ (checkDir force) (importDirs pkg)
+ mapM_ (checkDir force) (libraryDirs pkg)
+ mapM_ (checkDir force) (includeDirs pkg)
+ mapM_ (checkHSLib (libraryDirs pkg) auto_ghci_libs force) (hsLibraries pkg)
+ return overlaps
+ -- ToDo: check these somehow?
+ -- extra_libraries :: [String],
+ -- c_includes :: [String],
+
+-- When the package name and version are put together, sometimes we can
+-- end up with a package id that cannot be parsed. This will lead to
+-- difficulties when the user wants to refer to the package later, so
+-- we check that the package id can be parsed properly here.
+checkPackageId :: InstalledPackageInfo -> IO ()
+checkPackageId ipi =
+ let str = showPackageId (package ipi) in
+ case [ x | (x,ys) <- readP_to_S parsePackageId str, all isSpace ys ] of
+ [_] -> return ()
+ [] -> die ("invalid package identifier: " ++ str)
+ _ -> die ("ambiguous package identifier: " ++ str)
+
+resolveDeps :: PackageDBStack -> InstalledPackageInfo -> InstalledPackageInfo
+resolveDeps db_stack p = updateDeps p
+ where
+ -- The input package spec is allowed to give a package dependency
+ -- without a version number; e.g.
+ -- depends: base
+ -- Here, we update these dependencies without version numbers to
+ -- match the actual versions of the relevant packages installed.
+ updateDeps p = p{depends = map resolveDep (depends p)}
+
+ resolveDep dep_pkgid
+ | realVersion dep_pkgid = dep_pkgid
+ | otherwise = lookupDep dep_pkgid
+
+ lookupDep dep_pkgid
+ = let
+ name = pkgName dep_pkgid
+ in
+ case [ pid | p <- concat (map snd db_stack),
+ let pid = package p,
+ pkgName pid == name ] of
+ (pid:_) -> pid -- Found installed package,
+ -- replete with its version
+ [] -> dep_pkgid -- No installed package; use
+ -- the version-less one
+
+checkDuplicates :: PackageDBStack -> InstalledPackageInfo -> Bool -> Bool
+ -> IO [PackageIdentifier]
+checkDuplicates db_stack pkg update force = do
+ let
+ pkgid = package pkg
+ (_top_db_name, pkgs) : _ = db_stack
+ --
+ -- Check whether this package id already exists in this DB
+ --
+ when (not update && (pkgid `elem` map package pkgs)) $
+ die ("package " ++ showPackageId pkgid ++ " is already installed")
+
+ --
+ -- Check whether any of the dependencies of the current package
+ -- conflict with each other.
+ --
+ let
+ all_pkgs = concat (map snd db_stack)
+
+ allModules p = exposedModules p ++ hiddenModules p
+
+ our_dependencies = closePackageDeps all_pkgs [pkg]
+ all_dep_modules = concat (map (\p -> zip (allModules p) (repeat p))
+ our_dependencies)
+
+ overlaps = [ (m, map snd group)
+ | group@((m,_):_) <- groupBy eqfst (sortBy cmpfst all_dep_modules),
+ length group > 1 ]
+ where eqfst (a,_) (b,_) = a == b
+ cmpfst (a,_) (b,_) = a `compare` b
+
+ when (not (null overlaps)) $
+ diePrettyOrForce force $ vcat [
+ text "package" <+> text (showPackageId (package pkg)) <+>
+ text "has conflicting dependencies:",
+ let complain_about (mod,ps) =
+ text mod <+> text "is in the following packages:" <+>
+ sep (map (text.showPackageId.package) ps)
+ in
+ nest 3 (vcat (map complain_about overlaps))
+ ]
+
+ --
+ -- Now check whether exposing this package will result in conflicts, and
+ -- Figure out which packages we need to hide to resolve the conflicts.
+ --
+ let
+ closure_exposed_pkgs = closePackageDeps pkgs (filter exposed pkgs)
+
+ new_dep_modules = concat $ map allModules $
+ filter (\p -> package p `notElem`
+ map package closure_exposed_pkgs) $
+ our_dependencies
+
+ pkgs_with_overlapping_modules =
+ [ (p, overlapping_mods)
+ | p <- closure_exposed_pkgs,
+ let overlapping_mods =
+ filter (`elem` new_dep_modules) (allModules p),
+ (_:_) <- [overlapping_mods] --trick to get the non-empty ones
+ ]
+
+ to_hide = map package
+ $ filter exposed
+ $ closePackageDepsUpward pkgs
+ $ map fst pkgs_with_overlapping_modules
+
+ when (not update && exposed pkg && not (null pkgs_with_overlapping_modules)) $ do
+ diePretty $ vcat [
+ text "package" <+> text (showPackageId (package pkg)) <+>
+ text "conflicts with the following packages, which are",
+ text "either exposed or a dependency (direct or indirect) of an exposed package:",
+ let complain_about (p, mods)
+ = text (showPackageId (package p)) <+> text "contains modules" <+>
+ sep (punctuate comma (map text mods)) in
+ nest 3 (vcat (map complain_about pkgs_with_overlapping_modules)),
+ text "Using 'update' instead of 'register' will cause the following packages",
+ text "to be hidden, which will eliminate the conflict:",
+ nest 3 (sep (map (text.showPackageId) to_hide))
+ ]
+
+ when (not (null to_hide)) $ do
+ hPutStrLn stderr $ render $
+ sep [text "Warning: hiding the following packages to avoid conflict: ",
+ nest 2 (sep (map (text.showPackageId) to_hide))]
+
+ return to_hide
+
+
+closure :: (a->[a]->Bool) -> (a -> [a]) -> [a] -> [a] -> [a]
+closure pred more [] res = res
+closure pred more (p:ps) res
+ | p `pred` res = closure pred more ps res
+ | otherwise = closure pred more (more p ++ ps) (p:res)
+
+closePackageDeps :: [InstalledPackageInfo] -> [InstalledPackageInfo]
+ -> [InstalledPackageInfo]
+closePackageDeps db start
+ = closure (\p ps -> package p `elem` map package ps) getDepends start []
+ where
+ getDepends p = [ pkg | dep <- depends p, pkg <- lookupPkg dep ]
+ lookupPkg p = [ q | q <- db, p == package q ]
+
+closePackageDepsUpward :: [InstalledPackageInfo] -> [InstalledPackageInfo]
+ -> [InstalledPackageInfo]
+closePackageDepsUpward db start
+ = closure (\p ps -> package p `elem` map package ps) getUpwardDepends start []
+ where
+ getUpwardDepends p = [ pkg | pkg <- db, package p `elem` depends pkg ]
+
+
+checkDir :: Bool -> String -> IO ()
+checkDir force d
+ | "$topdir" `isPrefixOf` d = return ()
+ -- can't check this, because we don't know what $topdir is
+ | otherwise = do
+ there <- doesDirectoryExist d
+ when (not there)
+ (dieOrForce force (d ++ " doesn't exist or isn't a directory"))
+
+checkDep :: PackageDBStack -> Bool -> PackageIdentifier -> IO ()
+checkDep db_stack force pkgid
+ | not real_version || pkgid `elem` pkgids = return ()
+ | otherwise = dieOrForce force ("dependency " ++ showPackageId pkgid
+ ++ " doesn't exist")
+ where
+ -- for backwards compat, we treat 0.0 as a special version,
+ -- and don't check that it actually exists.
+ real_version = realVersion pkgid
+
+ all_pkgs = concat (map snd db_stack)
+ pkgids = map package all_pkgs
+
+realVersion :: PackageIdentifier -> Bool
+realVersion pkgid = versionBranch (pkgVersion pkgid) /= []
+
+checkHSLib :: [String] -> Bool -> Bool -> String -> IO ()
+checkHSLib dirs auto_ghci_libs force lib = do
+ let batch_lib_file = "lib" ++ lib ++ ".a"
+ bs <- mapM (doesLibExistIn batch_lib_file) dirs
+ case [ dir | (exists,dir) <- zip bs dirs, exists ] of
+ [] -> dieOrForce force ("cannot find " ++ batch_lib_file ++
+ " on library path")
+ (dir:_) -> checkGHCiLib dirs dir batch_lib_file lib auto_ghci_libs
+
+doesLibExistIn :: String -> String -> IO Bool
+doesLibExistIn lib d
+ | "$topdir" `isPrefixOf` d = return True
+ | otherwise = doesFileExist (d ++ '/':lib)
+
+checkGHCiLib :: [String] -> String -> String -> String -> Bool -> IO ()
+checkGHCiLib dirs batch_lib_dir batch_lib_file lib auto_build
+ | auto_build = autoBuildGHCiLib batch_lib_dir batch_lib_file ghci_lib_file
+ | otherwise = do
+ bs <- mapM (doesLibExistIn ghci_lib_file) dirs
+ case [dir | (exists,dir) <- zip bs dirs, exists] of
+ [] -> hPutStrLn stderr ("warning: can't find GHCi lib " ++ ghci_lib_file)
+ (_:_) -> return ()
+ where
+ ghci_lib_file = lib ++ ".o"
+
+-- automatically build the GHCi version of a batch lib,
+-- using ld --whole-archive.
+
+autoBuildGHCiLib :: String -> String -> String -> IO ()
+autoBuildGHCiLib dir batch_file ghci_file = do
+ let ghci_lib_file = dir ++ '/':ghci_file
+ batch_lib_file = dir ++ '/':batch_file
+ hPutStr stderr ("building GHCi library " ++ ghci_lib_file ++ "...")
+#if defined(darwin_HOST_OS)
+ r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"-all_load",batch_lib_file]
+#elif defined(mingw32_HOST_OS)
+ execDir <- getExecDir "/bin/ghc-pkg.exe"
+ r <- rawSystem (maybe "" (++"/gcc-lib/") execDir++"ld") ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
+#else
+ r <- rawSystem "ld" ["-r","-x","-o",ghci_lib_file,"--whole-archive",batch_lib_file]
+#endif
+ when (r /= ExitSuccess) $ exitWith r
+ hPutStrLn stderr (" done.")
+
+-- -----------------------------------------------------------------------------
+-- Updating the DB with the new package.
+
+updatePackageDB
+ :: PackageDBStack -- the full stack
+ -> [PackageIdentifier] -- packages to hide
+ -> [InstalledPackageInfo] -- packages in *this* DB
+ -> InstalledPackageInfo -- the new package
+ -> IO [InstalledPackageInfo]
+updatePackageDB db_stack to_hide pkgs new_pkg = do
+ let
+ pkgid = package new_pkg
+
+ pkgs' = [ maybe_hide p | p <- pkgs, package p /= pkgid ]
+
+ -- When update is on, and we're exposing the new package,
+ -- we hide any packages which conflict (see checkDuplicates)
+ -- in the current DB.
+ maybe_hide p
+ | exposed new_pkg && package p `elem` to_hide = p{ exposed = False }
+ | otherwise = p
+ --
+ return (pkgs'++ [new_pkg])
+
+-- -----------------------------------------------------------------------------
+-- Searching for modules
+
+#if not_yet
+
+findModules :: [FilePath] -> IO [String]
+findModules paths =
+ mms <- mapM searchDir paths
+ return (concat mms)
+
+searchDir path prefix = do
+ fs <- getDirectoryEntries path `catch` \_ -> return []
+ searchEntries path prefix fs
+
+searchEntries path prefix [] = return []
+searchEntries path prefix (f:fs)
+ | looks_like_a_module = do
+ ms <- searchEntries path prefix fs
+ return (prefix `joinModule` f : ms)
+ | looks_like_a_component = do
+ ms <- searchDir (path `joinFilename` f) (prefix `joinModule` f)
+ ms' <- searchEntries path prefix fs
+ return (ms ++ ms')
+ | otherwise
+ searchEntries path prefix fs
+
+ where
+ (base,suffix) = splitFileExt f
+ looks_like_a_module =
+ suffix `elem` haskell_suffixes &&
+ all okInModuleName base
+ looks_like_a_component =
+ null suffix && all okInModuleName base
+
+okInModuleName c
+
+#endif
+
+-- -----------------------------------------------------------------------------
+-- The old command-line syntax, supported for backwards compatibility
+
+data OldFlag
+ = OF_Config FilePath
+ | OF_Input FilePath
+ | OF_List
+ | OF_ListLocal
+ | OF_Add Bool {- True => replace existing info -}
+ | OF_Remove String | OF_Show String
+ | OF_Field String | OF_AutoGHCiLibs | OF_Force
+ | OF_DefinedName String String
+ | OF_GlobalConfig FilePath
+ deriving (Eq)
+
+isAction :: OldFlag -> Bool
+isAction OF_Config{} = False
+isAction OF_Field{} = False
+isAction OF_Input{} = False
+isAction OF_AutoGHCiLibs{} = False
+isAction OF_Force{} = False
+isAction OF_DefinedName{} = False
+isAction OF_GlobalConfig{} = False
+isAction _ = True
+
+oldFlags :: [OptDescr OldFlag]
+oldFlags = [
+ Option ['f'] ["config-file"] (ReqArg OF_Config "FILE")
+ "use the specified package config file",
+ Option ['l'] ["list-packages"] (NoArg OF_List)
+ "list packages in all config files",
+ Option ['L'] ["list-local-packages"] (NoArg OF_ListLocal)
+ "list packages in the specified config file",
+ Option ['a'] ["add-package"] (NoArg (OF_Add False))
+ "add a new package",
+ Option ['u'] ["update-package"] (NoArg (OF_Add True))
+ "update package with new configuration",
+ Option ['i'] ["input-file"] (ReqArg OF_Input "FILE")
+ "read new package info from specified file",
+ Option ['s'] ["show-package"] (ReqArg OF_Show "NAME")
+ "show the configuration for package NAME",
+ Option [] ["field"] (ReqArg OF_Field "FIELD")
+ "(with --show-package) Show field FIELD only",
+ Option [] ["force"] (NoArg OF_Force)
+ "ignore missing directories/libraries",
+ Option ['r'] ["remove-package"] (ReqArg OF_Remove "NAME")
+ "remove an installed package",
+ Option ['g'] ["auto-ghci-libs"] (NoArg OF_AutoGHCiLibs)
+ "automatically build libs for GHCi (with -a)",
+ Option ['D'] ["define-name"] (ReqArg toDefined "NAME=VALUE")
+ "define NAME as VALUE",
+ Option [] ["global-conf"] (ReqArg OF_GlobalConfig "FILE")
+ "location of the global package config"
+ ]
+ where
+ toDefined str =
+ case break (=='=') str of
+ (nm,[]) -> OF_DefinedName nm []
+ (nm,_:val) -> OF_DefinedName nm val
+
+oldRunit :: [OldFlag] -> IO ()
+oldRunit clis = do
+ let new_flags = [ f | Just f <- map conv clis ]
+
+ conv (OF_GlobalConfig f) = Just (FlagGlobalConfig f)
+ conv (OF_Config f) = Just (FlagConfig f)
+ conv _ = Nothing
+
+
+
+ let fields = [ f | OF_Field f <- clis ]
+
+ let auto_ghci_libs = any isAuto clis
+ where isAuto OF_AutoGHCiLibs = True; isAuto _ = False
+ input_file = my_head "inp" ([ f | (OF_Input f) <- clis] ++ ["-"])
+
+ force = OF_Force `elem` clis
+
+ defines = [ (nm,val) | OF_DefinedName nm val <- clis ]
+
+ case [ c | c <- clis, isAction c ] of
+ [ OF_List ] -> listPackages new_flags Nothing
+ [ OF_ListLocal ] -> listPackages new_flags Nothing
+ [ OF_Add upd ] ->
+ registerPackage input_file defines new_flags auto_ghci_libs upd force
+ [ OF_Remove pkgid_str ] -> do
+ pkgid <- readPkgId pkgid_str
+ unregisterPackage pkgid new_flags
+ [ OF_Show pkgid_str ]
+ | null fields -> do
+ pkgid <- readPkgId pkgid_str
+ describePackage new_flags pkgid
+ | otherwise -> do
+ pkgid <- readPkgId pkgid_str
+ mapM_ (describeField new_flags pkgid) fields
+ _ -> do
+ prog <- getProgramName
+ die (usageInfo (usageHeader prog) flags)
+
+my_head :: String -> [a] -> a
+my_head s [] = error s
+my_head s (x:xs) = x
+
+-- ---------------------------------------------------------------------------
+-- expanding environment variables in the package configuration
+
+expandEnvVars :: String -> [(String, String)] -> Bool -> IO String
+expandEnvVars str defines force = go str ""
+ where
+ go "" acc = return $! reverse acc
+ go ('$':'{':str) acc | (var, '}':rest) <- break close str
+ = do value <- lookupEnvVar var
+ go rest (reverse value ++ acc)
+ where close c = c == '}' || c == '\n' -- don't span newlines
+ go (c:str) acc
+ = go str (c:acc)
+
+ lookupEnvVar :: String -> IO String
+ lookupEnvVar nm =
+ case lookup nm defines of
+ Just x | not (null x) -> return x
+ _ ->
+ catch (System.getEnv nm)
+ (\ _ -> do dieOrForce force ("Unable to expand variable " ++
+ show nm)
+ return "")