{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE TypeApplications #-}

-- | Handling project configuration.
module Distribution.Client.ProjectConfig
  ( -- * Types for project config
    ProjectConfig (..)
  , ProjectConfigToParse (..)
  , ProjectConfigBuildOnly (..)
  , ProjectConfigShared (..)
  , ProjectConfigProvenance (..)
  , PackageConfig (..)
  , MapLast (..)
  , MapMappend (..)

    -- * Project root
  , findProjectRoot
  , getProjectRootUsability
  , ProjectRoot (..)
  , BadProjectRoot (..)
  , ProjectRootUsability (..)

    -- * Project config files
  , readProjectConfig
  , readGlobalConfig
  , readProjectLocalExtraConfig
  , readProjectLocalFreezeConfig
  , reportParseResult
  , showProjectConfig
  , withGlobalConfig
  , withProjectOrGlobalConfig
  , writeProjectLocalExtraConfig
  , writeProjectLocalFreezeConfig
  , writeProjectConfigFile
  , commandLineFlagsToProjectConfig
  , onlyTopLevelProvenance
  , readSourcePackageCabalFile
  , readSourcePackageCabalFile'
  , CabalFileParseError (..)

    -- * Packages within projects
  , ProjectPackageLocation (..)
  , BadPackageLocations (..)
  , BadPackageLocation (..)
  , BadPackageLocationMatch (..)
  , findProjectPackages
  , fetchAndReadSourcePackages

    -- * Resolving configuration
  , lookupLocalPackageConfig
  , projectConfigWithBuilderRepoContext
  , projectConfigWithSolverRepoContext
  , SolverSettings (..)
  , resolveSolverSettings
  , BuildTimeSettings (..)
  , resolveBuildTimeSettings
  , resolveNumJobsSetting

    -- * Checking configuration
  , checkBadPerPackageCompilerPaths
  , BadPerPackageCompilerPaths (..)

    -- * Globals
  , maxNumFetchJobs
  ) where

import Distribution.Client.Compat.Prelude hiding (empty)
import Distribution.Simple.Utils
  ( createDirectoryIfMissingVerbose
  , dieWithException
  , maybeExit
  , notice
  , noticeDoc
  , ordNub
  , rawSystemIOWithEnv
  , warn
  )
import Text.PrettyPrint (cat, colon, comma, empty, hsep, nest, quotes, render, text, vcat)
import Prelude ()

import Distribution.Client.Glob
  ( isTrivialRootedGlob
  )
import Distribution.Client.JobControl
import Distribution.Client.ProjectConfig.Legacy
import Distribution.Client.ProjectConfig.Types
import Distribution.Client.RebuildMonad
import Distribution.Client.VCS
  ( SourceRepoProblem (..)
  , VCS (..)
  , configureVCS
  , knownVCSs
  , syncSourceRepos
  , validateSourceRepos
  )

import Distribution.Client.BuildReports.Types
  ( ReportLevel (..)
  )
import Distribution.Client.Config
  ( getConfigFilePath
  , loadConfig
  )
import Distribution.Client.DistDirLayout
  ( CabalDirLayout (..)
  , DistDirLayout (..)
  , ProjectRoot (..)
  , defaultProjectFile
  )
import Distribution.Client.GlobalFlags
  ( RepoContext (..)
  , withRepoContext'
  )
import Distribution.Client.HashValue
import Distribution.Client.HttpUtils
  ( HttpTransport
  , configureTransport
  , downloadURI
  , transportCheckHttps
  )
import Distribution.Client.Types
import Distribution.Client.Utils.Parsec (renderParseError)

import Distribution.Solver.Types.ConstraintSource
import Distribution.Solver.Types.PackageConstraint
import Distribution.Solver.Types.Settings
import Distribution.Solver.Types.SourcePackage

import Distribution.Client.Errors
import Distribution.Client.Setup
  ( defaultMaxBackjumps
  , defaultSolver
  )
import Distribution.Client.SrcDist
  ( packageDirToSdist
  )
import Distribution.Client.Targets
import Distribution.Client.Types.SourceRepo
  ( SourceRepoList
  , SourceRepositoryPackage (..)
  , srpFanOut
  )
import Distribution.Client.Utils
  ( determineNumJobs
  )
import qualified Distribution.Deprecated.ParseUtils as OldParser
  ( locatedErrorMsg
  , showPWarning
  )
import qualified Distribution.Deprecated.ProjectParseUtils as OldParser
  ( ProjectParseResult (..)
  )
import Distribution.Fields
  ( PError
  , PWarning
  , runParseResult
  , showPWarning
  )
import Distribution.Package
import Distribution.PackageDescription.Parsec
  ( parseGenericPackageDescription
  )
import Distribution.Simple.Compiler
  ( Compiler
  , compilerInfo
  )
import Distribution.Simple.InstallDirs
  ( PathTemplate
  , fromPathTemplate
  , initialPathTemplateEnv
  , substPathTemplate
  , toPathTemplate
  )
import Distribution.Simple.Program
  ( ConfiguredProgram (..)
  )
import Distribution.Simple.Setup
  ( Flag
  , flagToList
  , flagToMaybe
  , fromFlag
  , fromFlagOrDefault
  , toFlag
  , pattern Flag
  )
import Distribution.System
  ( Platform
  )
import Distribution.Types.GenericPackageDescription
  ( GenericPackageDescription
  )
import Distribution.Types.PackageVersionConstraint
  ( PackageVersionConstraint (..)
  )
import Distribution.Types.SourceRepo
  ( RepoType (..)
  )
import Distribution.Utils.Generic
  ( toUTF8BS
  , toUTF8LBS
  )
import Distribution.Utils.NubList
  ( fromNubList
  )
import Distribution.Verbosity
  ( modifyVerbosity
  , verbose
  )
import Distribution.Version

import qualified Codec.Archive.Tar as Tar
import qualified Codec.Archive.Tar.Entry as Tar
import qualified Distribution.Client.GZipUtils as GZipUtils
import qualified Distribution.Client.Tar as Tar

import Control.Exception (handle)
import Control.Monad.Trans (liftIO)
import qualified Data.ByteString as BS
import qualified Data.ByteString.Lazy as LBS
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as Map
import qualified Data.Set as Set

import Network.URI
  ( URI (..)
  , URIAuth (..)
  , parseAbsoluteURI
  , uriToString
  )
import System.Directory
  ( canonicalizePath
  , doesDirectoryExist
  , doesFileExist
  , doesPathExist
  , getCurrentDirectory
  , getDirectoryContents
  , getHomeDirectory
  , pathIsSymbolicLink
  )
import System.FilePath hiding (combine)
import System.IO
  ( IOMode (ReadMode)
  , withBinaryFile
  )

import Distribution.Deprecated.ProjectParseUtils (ProjectParseError (..), ProjectParseWarning)
import Distribution.Solver.Types.ProjectConfigPath

----------------------------------------
-- Resolving configuration to settings
--

-- | Look up a 'PackageConfig' field in the 'ProjectConfig' for a specific
-- 'PackageName'. This returns the configuration that applies to all local
-- packages plus any package-specific configuration for this package.
lookupLocalPackageConfig
  :: (Semigroup a, Monoid a)
  => (PackageConfig -> a)
  -> ProjectConfig
  -> PackageName
  -> a
lookupLocalPackageConfig :: forall a.
(Semigroup a, Monoid a) =>
(PackageConfig -> a) -> ProjectConfig -> PackageName -> a
lookupLocalPackageConfig
  PackageConfig -> a
field
  ProjectConfig
    { PackageConfig
projectConfigLocalPackages :: PackageConfig
projectConfigLocalPackages :: ProjectConfig -> PackageConfig
projectConfigLocalPackages
    , MapMappend PackageName PackageConfig
projectConfigSpecificPackage :: MapMappend PackageName PackageConfig
projectConfigSpecificPackage :: ProjectConfig -> MapMappend PackageName PackageConfig
projectConfigSpecificPackage
    }
  PackageName
pkgname =
    PackageConfig -> a
field PackageConfig
projectConfigLocalPackages
      a -> a -> a
forall a. Semigroup a => a -> a -> a
<> a -> (PackageConfig -> a) -> Maybe PackageConfig -> a
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
        a
forall a. Monoid a => a
mempty
        PackageConfig -> a
field
        (PackageName -> Map PackageName PackageConfig -> Maybe PackageConfig
forall k a. Ord k => k -> Map k a -> Maybe a
Map.lookup PackageName
pkgname (MapMappend PackageName PackageConfig
-> Map PackageName PackageConfig
forall k v. MapMappend k v -> Map k v
getMapMappend MapMappend PackageName PackageConfig
projectConfigSpecificPackage))

-- | Use a 'RepoContext' based on the 'BuildTimeSettings'.
projectConfigWithBuilderRepoContext
  :: Verbosity
  -> BuildTimeSettings
  -> (RepoContext -> IO a)
  -> IO a
projectConfigWithBuilderRepoContext :: forall a.
Verbosity -> BuildTimeSettings -> (RepoContext -> IO a) -> IO a
projectConfigWithBuilderRepoContext Verbosity
verbosity BuildTimeSettings{Bool
[Char]
[[Char]]
[PathTemplate]
[LocalRepo]
[RemoteRepo]
Maybe [Char]
Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
Verbosity
ReportLevel
ParStratInstall
buildSettingDryRun :: Bool
buildSettingOnlyDeps :: Bool
buildSettingOnlyDownload :: Bool
buildSettingSummaryFile :: [PathTemplate]
buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
buildSettingLogVerbosity :: Verbosity
buildSettingBuildReports :: ReportLevel
buildSettingReportPlanningFailure :: Bool
buildSettingSymlinkBinDir :: [[Char]]
buildSettingNumJobs :: ParStratInstall
buildSettingKeepGoing :: Bool
buildSettingOfflineMode :: Bool
buildSettingKeepTempFiles :: Bool
buildSettingRemoteRepos :: [RemoteRepo]
buildSettingLocalNoIndexRepos :: [LocalRepo]
buildSettingCacheDir :: [Char]
buildSettingHttpTransport :: Maybe [Char]
buildSettingIgnoreExpiry :: Bool
buildSettingProgPathExtra :: [[Char]]
buildSettingHaddockOpen :: Bool
buildSettingBuildReports :: BuildTimeSettings -> ReportLevel
buildSettingCacheDir :: BuildTimeSettings -> [Char]
buildSettingDryRun :: BuildTimeSettings -> Bool
buildSettingHaddockOpen :: BuildTimeSettings -> Bool
buildSettingHttpTransport :: BuildTimeSettings -> Maybe [Char]
buildSettingIgnoreExpiry :: BuildTimeSettings -> Bool
buildSettingKeepGoing :: BuildTimeSettings -> Bool
buildSettingKeepTempFiles :: BuildTimeSettings -> Bool
buildSettingLocalNoIndexRepos :: BuildTimeSettings -> [LocalRepo]
buildSettingLogFile :: BuildTimeSettings
-> Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
buildSettingLogVerbosity :: BuildTimeSettings -> Verbosity
buildSettingNumJobs :: BuildTimeSettings -> ParStratInstall
buildSettingOfflineMode :: BuildTimeSettings -> Bool
buildSettingOnlyDeps :: BuildTimeSettings -> Bool
buildSettingOnlyDownload :: BuildTimeSettings -> Bool
buildSettingProgPathExtra :: BuildTimeSettings -> [[Char]]
buildSettingRemoteRepos :: BuildTimeSettings -> [RemoteRepo]
buildSettingReportPlanningFailure :: BuildTimeSettings -> Bool
buildSettingSummaryFile :: BuildTimeSettings -> [PathTemplate]
buildSettingSymlinkBinDir :: BuildTimeSettings -> [[Char]]
..} =
  Verbosity
-> [RemoteRepo]
-> [LocalRepo]
-> [Char]
-> Maybe [Char]
-> Maybe Bool
-> [[Char]]
-> (RepoContext -> IO a)
-> IO a
forall a.
Verbosity
-> [RemoteRepo]
-> [LocalRepo]
-> [Char]
-> Maybe [Char]
-> Maybe Bool
-> [[Char]]
-> (RepoContext -> IO a)
-> IO a
withRepoContext'
    Verbosity
verbosity
    [RemoteRepo]
buildSettingRemoteRepos
    [LocalRepo]
buildSettingLocalNoIndexRepos
    [Char]
buildSettingCacheDir
    Maybe [Char]
buildSettingHttpTransport
    (Bool -> Maybe Bool
forall a. a -> Maybe a
Just Bool
buildSettingIgnoreExpiry)
    [[Char]]
buildSettingProgPathExtra

-- | Use a 'RepoContext', but only for the solver. The solver does not use the
-- full facilities of the 'RepoContext' so we can get away with making one
-- that doesn't have an http transport. And that avoids having to have access
-- to the 'BuildTimeSettings'
projectConfigWithSolverRepoContext
  :: Verbosity
  -> ProjectConfigShared
  -> ProjectConfigBuildOnly
  -> (RepoContext -> IO a)
  -> IO a
projectConfigWithSolverRepoContext :: forall a.
Verbosity
-> ProjectConfigShared
-> ProjectConfigBuildOnly
-> (RepoContext -> IO a)
-> IO a
projectConfigWithSolverRepoContext
  Verbosity
verbosity
  ProjectConfigShared{[Maybe PackageDBCWD]
[(UserConstraint, ConstraintSource)]
[PackageVersionConstraint]
Maybe AllowNewer
Maybe AllowOlder
Flag Bool
Flag Int
Flag [Char]
Flag CompilerFlavor
Flag Version
Flag PreSolver
Flag PathTemplate
Flag TotalIndexState
Flag ActiveRepos
Flag WriteGhcEnvironmentFilesPolicy
Flag IndependentGoals
Flag AllowBootLibInstalls
Flag CountConflicts
Flag FineGrainedConflicts
Flag MinimizeConflictSet
Flag OnlyConstrained
Flag PreferOldest
Flag ReorderGoals
Flag StrongFlags
InstallDirs (Flag PathTemplate)
NubList [Char]
NubList LocalRepo
NubList RemoteRepo
projectConfigDistDir :: Flag [Char]
projectConfigConfigFile :: Flag [Char]
projectConfigProjectDir :: Flag [Char]
projectConfigProjectFile :: Flag [Char]
projectConfigIgnoreProject :: Flag Bool
projectConfigHcFlavor :: Flag CompilerFlavor
projectConfigHcPath :: Flag [Char]
projectConfigHcPkg :: Flag [Char]
projectConfigHaddockIndex :: Flag PathTemplate
projectConfigInstallDirs :: InstallDirs (Flag PathTemplate)
projectConfigPackageDBs :: [Maybe PackageDBCWD]
projectConfigRemoteRepos :: NubList RemoteRepo
projectConfigLocalNoIndexRepos :: NubList LocalRepo
projectConfigActiveRepos :: Flag ActiveRepos
projectConfigIndexState :: Flag TotalIndexState
projectConfigStoreDir :: Flag [Char]
projectConfigConstraints :: [(UserConstraint, ConstraintSource)]
projectConfigPreferences :: [PackageVersionConstraint]
projectConfigCabalVersion :: Flag Version
projectConfigSolver :: Flag PreSolver
projectConfigAllowOlder :: Maybe AllowOlder
projectConfigAllowNewer :: Maybe AllowNewer
projectConfigWriteGhcEnvironmentFilesPolicy :: Flag WriteGhcEnvironmentFilesPolicy
projectConfigMaxBackjumps :: Flag Int
projectConfigReorderGoals :: Flag ReorderGoals
projectConfigCountConflicts :: Flag CountConflicts
projectConfigFineGrainedConflicts :: Flag FineGrainedConflicts
projectConfigMinimizeConflictSet :: Flag MinimizeConflictSet
projectConfigStrongFlags :: Flag StrongFlags
projectConfigAllowBootLibInstalls :: Flag AllowBootLibInstalls
projectConfigOnlyConstrained :: Flag OnlyConstrained
projectConfigPerComponent :: Flag Bool
projectConfigIndependentGoals :: Flag IndependentGoals
projectConfigPreferOldest :: Flag PreferOldest
projectConfigProgPathExtra :: NubList [Char]
projectConfigMultiRepl :: Flag Bool
projectConfigActiveRepos :: ProjectConfigShared -> Flag ActiveRepos
projectConfigAllowBootLibInstalls :: ProjectConfigShared -> Flag AllowBootLibInstalls
projectConfigAllowNewer :: ProjectConfigShared -> Maybe AllowNewer
projectConfigAllowOlder :: ProjectConfigShared -> Maybe AllowOlder
projectConfigCabalVersion :: ProjectConfigShared -> Flag Version
projectConfigConfigFile :: ProjectConfigShared -> Flag [Char]
projectConfigConstraints :: ProjectConfigShared -> [(UserConstraint, ConstraintSource)]
projectConfigCountConflicts :: ProjectConfigShared -> Flag CountConflicts
projectConfigDistDir :: ProjectConfigShared -> Flag [Char]
projectConfigFineGrainedConflicts :: ProjectConfigShared -> Flag FineGrainedConflicts
projectConfigHaddockIndex :: ProjectConfigShared -> Flag PathTemplate
projectConfigHcFlavor :: ProjectConfigShared -> Flag CompilerFlavor
projectConfigHcPath :: ProjectConfigShared -> Flag [Char]
projectConfigHcPkg :: ProjectConfigShared -> Flag [Char]
projectConfigIgnoreProject :: ProjectConfigShared -> Flag Bool
projectConfigIndependentGoals :: ProjectConfigShared -> Flag IndependentGoals
projectConfigIndexState :: ProjectConfigShared -> Flag TotalIndexState
projectConfigInstallDirs :: ProjectConfigShared -> InstallDirs (Flag PathTemplate)
projectConfigLocalNoIndexRepos :: ProjectConfigShared -> NubList LocalRepo
projectConfigMaxBackjumps :: ProjectConfigShared -> Flag Int
projectConfigMinimizeConflictSet :: ProjectConfigShared -> Flag MinimizeConflictSet
projectConfigMultiRepl :: ProjectConfigShared -> Flag Bool
projectConfigOnlyConstrained :: ProjectConfigShared -> Flag OnlyConstrained
projectConfigPackageDBs :: ProjectConfigShared -> [Maybe PackageDBCWD]
projectConfigPerComponent :: ProjectConfigShared -> Flag Bool
projectConfigPreferOldest :: ProjectConfigShared -> Flag PreferOldest
projectConfigPreferences :: ProjectConfigShared -> [PackageVersionConstraint]
projectConfigProgPathExtra :: ProjectConfigShared -> NubList [Char]
projectConfigProjectDir :: ProjectConfigShared -> Flag [Char]
projectConfigProjectFile :: ProjectConfigShared -> Flag [Char]
projectConfigRemoteRepos :: ProjectConfigShared -> NubList RemoteRepo
projectConfigReorderGoals :: ProjectConfigShared -> Flag ReorderGoals
projectConfigSolver :: ProjectConfigShared -> Flag PreSolver
projectConfigStoreDir :: ProjectConfigShared -> Flag [Char]
projectConfigStrongFlags :: ProjectConfigShared -> Flag StrongFlags
projectConfigWriteGhcEnvironmentFilesPolicy :: ProjectConfigShared -> Flag WriteGhcEnvironmentFilesPolicy
..}
  ProjectConfigBuildOnly{Flag Bool
Flag [Char]
Flag (Maybe Int)
Flag Verbosity
Flag ReportLevel
Flag PathTemplate
NubList PathTemplate
ClientInstallFlags
projectConfigVerbosity :: Flag Verbosity
projectConfigDryRun :: Flag Bool
projectConfigOnlyDeps :: Flag Bool
projectConfigOnlyDownload :: Flag Bool
projectConfigSummaryFile :: NubList PathTemplate
projectConfigLogFile :: Flag PathTemplate
projectConfigBuildReports :: Flag ReportLevel
projectConfigReportPlanningFailure :: Flag Bool
projectConfigSymlinkBinDir :: Flag [Char]
projectConfigNumJobs :: Flag (Maybe Int)
projectConfigUseSemaphore :: Flag Bool
projectConfigKeepGoing :: Flag Bool
projectConfigOfflineMode :: Flag Bool
projectConfigKeepTempFiles :: Flag Bool
projectConfigHttpTransport :: Flag [Char]
projectConfigIgnoreExpiry :: Flag Bool
projectConfigCacheDir :: Flag [Char]
projectConfigLogsDir :: Flag [Char]
projectConfigClientInstallFlags :: ClientInstallFlags
projectConfigBuildReports :: ProjectConfigBuildOnly -> Flag ReportLevel
projectConfigCacheDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigClientInstallFlags :: ProjectConfigBuildOnly -> ClientInstallFlags
projectConfigDryRun :: ProjectConfigBuildOnly -> Flag Bool
projectConfigHttpTransport :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigIgnoreExpiry :: ProjectConfigBuildOnly -> Flag Bool
projectConfigKeepGoing :: ProjectConfigBuildOnly -> Flag Bool
projectConfigKeepTempFiles :: ProjectConfigBuildOnly -> Flag Bool
projectConfigLogFile :: ProjectConfigBuildOnly -> Flag PathTemplate
projectConfigLogsDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigNumJobs :: ProjectConfigBuildOnly -> Flag (Maybe Int)
projectConfigOfflineMode :: ProjectConfigBuildOnly -> Flag Bool
projectConfigOnlyDeps :: ProjectConfigBuildOnly -> Flag Bool
projectConfigOnlyDownload :: ProjectConfigBuildOnly -> Flag Bool
projectConfigReportPlanningFailure :: ProjectConfigBuildOnly -> Flag Bool
projectConfigSummaryFile :: ProjectConfigBuildOnly -> NubList PathTemplate
projectConfigSymlinkBinDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigUseSemaphore :: ProjectConfigBuildOnly -> Flag Bool
projectConfigVerbosity :: ProjectConfigBuildOnly -> Flag Verbosity
..} =
    Verbosity
-> [RemoteRepo]
-> [LocalRepo]
-> [Char]
-> Maybe [Char]
-> Maybe Bool
-> [[Char]]
-> (RepoContext -> IO a)
-> IO a
forall a.
Verbosity
-> [RemoteRepo]
-> [LocalRepo]
-> [Char]
-> Maybe [Char]
-> Maybe Bool
-> [[Char]]
-> (RepoContext -> IO a)
-> IO a
withRepoContext'
      Verbosity
verbosity
      (NubList RemoteRepo -> [RemoteRepo]
forall a. NubList a -> [a]
fromNubList NubList RemoteRepo
projectConfigRemoteRepos)
      (NubList LocalRepo -> [LocalRepo]
forall a. NubList a -> [a]
fromNubList NubList LocalRepo
projectConfigLocalNoIndexRepos)
      ( [Char] -> Flag [Char] -> [Char]
forall a. a -> Flag a -> a
fromFlagOrDefault
          ( [Char] -> [Char]
forall a. HasCallStack => [Char] -> a
error
              [Char]
"projectConfigWithSolverRepoContext: projectConfigCacheDir"
          )
          Flag [Char]
projectConfigCacheDir
      )
      (Flag [Char] -> Maybe [Char]
forall a. Flag a -> Maybe a
flagToMaybe Flag [Char]
projectConfigHttpTransport)
      (Flag Bool -> Maybe Bool
forall a. Flag a -> Maybe a
flagToMaybe Flag Bool
projectConfigIgnoreExpiry)
      (NubList [Char] -> [[Char]]
forall a. NubList a -> [a]
fromNubList NubList [Char]
projectConfigProgPathExtra)

-- | Resolve the project configuration, with all its optional fields, into
-- 'SolverSettings' with no optional fields (by applying defaults).
resolveSolverSettings :: ProjectConfig -> SolverSettings
resolveSolverSettings :: ProjectConfig -> SolverSettings
resolveSolverSettings
  ProjectConfig
    { ProjectConfigShared
projectConfigShared :: ProjectConfigShared
projectConfigShared :: ProjectConfig -> ProjectConfigShared
projectConfigShared
    , PackageConfig
projectConfigLocalPackages :: ProjectConfig -> PackageConfig
projectConfigLocalPackages :: PackageConfig
projectConfigLocalPackages
    , MapMappend PackageName PackageConfig
projectConfigSpecificPackage :: ProjectConfig -> MapMappend PackageName PackageConfig
projectConfigSpecificPackage :: MapMappend PackageName PackageConfig
projectConfigSpecificPackage
    } =
    SolverSettings{[(UserConstraint, ConstraintSource)]
[PackageVersionConstraint]
[LocalRepo]
[RemoteRepo]
Maybe Int
Maybe Version
Maybe TotalIndexState
Maybe ActiveRepos
Map PackageName FlagAssignment
FlagAssignment
PreSolver
AllowNewer
AllowOlder
IndependentGoals
AllowBootLibInstalls
CountConflicts
FineGrainedConflicts
MinimizeConflictSet
OnlyConstrained
PreferOldest
ReorderGoals
StrongFlags
solverSettingRemoteRepos :: [RemoteRepo]
solverSettingLocalNoIndexRepos :: [LocalRepo]
solverSettingConstraints :: [(UserConstraint, ConstraintSource)]
solverSettingPreferences :: [PackageVersionConstraint]
solverSettingFlagAssignment :: FlagAssignment
solverSettingFlagAssignments :: Map PackageName FlagAssignment
solverSettingCabalVersion :: Maybe Version
solverSettingSolver :: PreSolver
solverSettingAllowOlder :: AllowOlder
solverSettingAllowNewer :: AllowNewer
solverSettingMaxBackjumps :: Maybe Int
solverSettingReorderGoals :: ReorderGoals
solverSettingCountConflicts :: CountConflicts
solverSettingFineGrainedConflicts :: FineGrainedConflicts
solverSettingMinimizeConflictSet :: MinimizeConflictSet
solverSettingStrongFlags :: StrongFlags
solverSettingAllowBootLibInstalls :: AllowBootLibInstalls
solverSettingOnlyConstrained :: OnlyConstrained
solverSettingIndexState :: Maybe TotalIndexState
solverSettingActiveRepos :: Maybe ActiveRepos
solverSettingIndependentGoals :: IndependentGoals
solverSettingPreferOldest :: PreferOldest
solverSettingActiveRepos :: Maybe ActiveRepos
solverSettingAllowBootLibInstalls :: AllowBootLibInstalls
solverSettingAllowNewer :: AllowNewer
solverSettingAllowOlder :: AllowOlder
solverSettingCabalVersion :: Maybe Version
solverSettingConstraints :: [(UserConstraint, ConstraintSource)]
solverSettingCountConflicts :: CountConflicts
solverSettingFineGrainedConflicts :: FineGrainedConflicts
solverSettingFlagAssignment :: FlagAssignment
solverSettingFlagAssignments :: Map PackageName FlagAssignment
solverSettingIndependentGoals :: IndependentGoals
solverSettingIndexState :: Maybe TotalIndexState
solverSettingLocalNoIndexRepos :: [LocalRepo]
solverSettingMaxBackjumps :: Maybe Int
solverSettingMinimizeConflictSet :: MinimizeConflictSet
solverSettingOnlyConstrained :: OnlyConstrained
solverSettingPreferOldest :: PreferOldest
solverSettingPreferences :: [PackageVersionConstraint]
solverSettingRemoteRepos :: [RemoteRepo]
solverSettingReorderGoals :: ReorderGoals
solverSettingSolver :: PreSolver
solverSettingStrongFlags :: StrongFlags
..}
    where
      -- TODO: [required eventually] some of these settings need validation, e.g.
      -- the flag assignments need checking.
      cabalPkgname :: PackageName
cabalPkgname = [Char] -> PackageName
mkPackageName [Char]
"Cabal"

      profilingDynamicConstraint :: (UserConstraint, ConstraintSource)
profilingDynamicConstraint =
        ( UserConstraintScope -> PackageProperty -> UserConstraint
UserConstraint
            (PackageName -> UserConstraintScope
UserAnySetupQualifier PackageName
cabalPkgname)
            (VersionRange -> PackageProperty
PackagePropertyVersion (VersionRange -> PackageProperty)
-> VersionRange -> PackageProperty
forall a b. (a -> b) -> a -> b
$ Version -> VersionRange
orLaterVersion ([Int] -> Version
mkVersion [Int
3, Int
13, Int
0]))
        , ConstraintSource
ConstraintSourceProfiledDynamic
        )

      profDynEnabledGlobally :: Bool
profDynEnabledGlobally = Bool -> Flag Bool -> Bool
forall a. a -> Flag a -> a
fromFlagOrDefault Bool
False (PackageConfig -> Flag Bool
packageConfigProfShared PackageConfig
projectConfigLocalPackages)

      profDynEnabledAnyLocally :: Bool
profDynEnabledAnyLocally =
        [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or
          [ Bool -> Flag Bool -> Bool
forall a. a -> Flag a -> a
fromFlagOrDefault Bool
False (PackageConfig -> Flag Bool
packageConfigProfShared PackageConfig
ppc)
          | (PackageName
_, PackageConfig
ppc) <- Map PackageName PackageConfig -> [(PackageName, PackageConfig)]
forall k a. Map k a -> [(k, a)]
Map.toList (MapMappend PackageName PackageConfig
-> Map PackageName PackageConfig
forall k v. MapMappend k v -> Map k v
getMapMappend MapMappend PackageName PackageConfig
projectConfigSpecificPackage)
          ]

      -- Add a setup.Cabal >= 3.13 constraint if prof+dyn is enabled globally
      -- or any package in the project enables it.
      -- Ideally we'd apply this constraint only on the closure of packages requiring prof+dyn,
      -- but that would require another solver run for marginal advantages that
      -- will further shrink as 3.13 is adopted.
      solverCabalLibConstraints :: [(UserConstraint, ConstraintSource)]
solverCabalLibConstraints =
        [(UserConstraint, ConstraintSource)
profilingDynamicConstraint | Bool
profDynEnabledGlobally Bool -> Bool -> Bool
|| Bool
profDynEnabledAnyLocally]

      solverSettingRemoteRepos :: [RemoteRepo]
solverSettingRemoteRepos = NubList RemoteRepo -> [RemoteRepo]
forall a. NubList a -> [a]
fromNubList NubList RemoteRepo
projectConfigRemoteRepos
      solverSettingLocalNoIndexRepos :: [LocalRepo]
solverSettingLocalNoIndexRepos = NubList LocalRepo -> [LocalRepo]
forall a. NubList a -> [a]
fromNubList NubList LocalRepo
projectConfigLocalNoIndexRepos
      solverSettingConstraints :: [(UserConstraint, ConstraintSource)]
solverSettingConstraints = [(UserConstraint, ConstraintSource)]
solverCabalLibConstraints [(UserConstraint, ConstraintSource)]
-> [(UserConstraint, ConstraintSource)]
-> [(UserConstraint, ConstraintSource)]
forall a. [a] -> [a] -> [a]
++ [(UserConstraint, ConstraintSource)]
projectConfigConstraints
      solverSettingPreferences :: [PackageVersionConstraint]
solverSettingPreferences = [PackageVersionConstraint]
projectConfigPreferences
      solverSettingFlagAssignment :: FlagAssignment
solverSettingFlagAssignment = PackageConfig -> FlagAssignment
packageConfigFlagAssignment PackageConfig
projectConfigLocalPackages
      solverSettingFlagAssignments :: Map PackageName FlagAssignment
solverSettingFlagAssignments =
        (PackageConfig -> FlagAssignment)
-> Map PackageName PackageConfig -> Map PackageName FlagAssignment
forall a b. (a -> b) -> Map PackageName a -> Map PackageName b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap
          PackageConfig -> FlagAssignment
packageConfigFlagAssignment
          (MapMappend PackageName PackageConfig
-> Map PackageName PackageConfig
forall k v. MapMappend k v -> Map k v
getMapMappend MapMappend PackageName PackageConfig
projectConfigSpecificPackage)
      solverSettingCabalVersion :: Maybe Version
solverSettingCabalVersion = Flag Version -> Maybe Version
forall a. Flag a -> Maybe a
flagToMaybe Flag Version
projectConfigCabalVersion
      solverSettingSolver :: PreSolver
solverSettingSolver = Flag PreSolver -> PreSolver
forall a. WithCallStack (Flag a -> a)
fromFlag Flag PreSolver
projectConfigSolver
      solverSettingAllowOlder :: AllowOlder
solverSettingAllowOlder = AllowOlder -> Maybe AllowOlder -> AllowOlder
forall a. a -> Maybe a -> a
fromMaybe AllowOlder
forall a. Monoid a => a
mempty Maybe AllowOlder
projectConfigAllowOlder
      solverSettingAllowNewer :: AllowNewer
solverSettingAllowNewer = AllowNewer -> Maybe AllowNewer -> AllowNewer
forall a. a -> Maybe a -> a
fromMaybe AllowNewer
forall a. Monoid a => a
mempty Maybe AllowNewer
projectConfigAllowNewer
      solverSettingMaxBackjumps :: Maybe Int
solverSettingMaxBackjumps = case Flag Int -> Int
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Int
projectConfigMaxBackjumps of
        Int
n
          | Int
n Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
< Int
0 -> Maybe Int
forall a. Maybe a
Nothing
          | Bool
otherwise -> Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n
      solverSettingReorderGoals :: ReorderGoals
solverSettingReorderGoals = Flag ReorderGoals -> ReorderGoals
forall a. WithCallStack (Flag a -> a)
fromFlag Flag ReorderGoals
projectConfigReorderGoals
      solverSettingCountConflicts :: CountConflicts
solverSettingCountConflicts = Flag CountConflicts -> CountConflicts
forall a. WithCallStack (Flag a -> a)
fromFlag Flag CountConflicts
projectConfigCountConflicts
      solverSettingFineGrainedConflicts :: FineGrainedConflicts
solverSettingFineGrainedConflicts = Flag FineGrainedConflicts -> FineGrainedConflicts
forall a. WithCallStack (Flag a -> a)
fromFlag Flag FineGrainedConflicts
projectConfigFineGrainedConflicts
      solverSettingMinimizeConflictSet :: MinimizeConflictSet
solverSettingMinimizeConflictSet = Flag MinimizeConflictSet -> MinimizeConflictSet
forall a. WithCallStack (Flag a -> a)
fromFlag Flag MinimizeConflictSet
projectConfigMinimizeConflictSet
      solverSettingStrongFlags :: StrongFlags
solverSettingStrongFlags = Flag StrongFlags -> StrongFlags
forall a. WithCallStack (Flag a -> a)
fromFlag Flag StrongFlags
projectConfigStrongFlags
      solverSettingAllowBootLibInstalls :: AllowBootLibInstalls
solverSettingAllowBootLibInstalls = Flag AllowBootLibInstalls -> AllowBootLibInstalls
forall a. WithCallStack (Flag a -> a)
fromFlag Flag AllowBootLibInstalls
projectConfigAllowBootLibInstalls
      solverSettingOnlyConstrained :: OnlyConstrained
solverSettingOnlyConstrained = Flag OnlyConstrained -> OnlyConstrained
forall a. WithCallStack (Flag a -> a)
fromFlag Flag OnlyConstrained
projectConfigOnlyConstrained
      solverSettingIndexState :: Maybe TotalIndexState
solverSettingIndexState = Flag TotalIndexState -> Maybe TotalIndexState
forall a. Flag a -> Maybe a
flagToMaybe Flag TotalIndexState
projectConfigIndexState
      solverSettingActiveRepos :: Maybe ActiveRepos
solverSettingActiveRepos = Flag ActiveRepos -> Maybe ActiveRepos
forall a. Flag a -> Maybe a
flagToMaybe Flag ActiveRepos
projectConfigActiveRepos
      solverSettingIndependentGoals :: IndependentGoals
solverSettingIndependentGoals = Flag IndependentGoals -> IndependentGoals
forall a. WithCallStack (Flag a -> a)
fromFlag Flag IndependentGoals
projectConfigIndependentGoals
      solverSettingPreferOldest :: PreferOldest
solverSettingPreferOldest = Flag PreferOldest -> PreferOldest
forall a. WithCallStack (Flag a -> a)
fromFlag Flag PreferOldest
projectConfigPreferOldest
      -- solverSettingShadowPkgs        = fromFlag projectConfigShadowPkgs
      -- solverSettingReinstall         = fromFlag projectConfigReinstall
      -- solverSettingAvoidReinstalls   = fromFlag projectConfigAvoidReinstalls
      -- solverSettingOverrideReinstall = fromFlag projectConfigOverrideReinstall
      -- solverSettingUpgradeDeps       = fromFlag projectConfigUpgradeDeps

      ProjectConfigShared{[Maybe PackageDBCWD]
[(UserConstraint, ConstraintSource)]
[PackageVersionConstraint]
Maybe AllowNewer
Maybe AllowOlder
Flag Bool
Flag Int
Flag [Char]
Flag CompilerFlavor
Flag Version
Flag PreSolver
Flag PathTemplate
Flag TotalIndexState
Flag ActiveRepos
Flag WriteGhcEnvironmentFilesPolicy
Flag IndependentGoals
Flag AllowBootLibInstalls
Flag CountConflicts
Flag FineGrainedConflicts
Flag MinimizeConflictSet
Flag OnlyConstrained
Flag PreferOldest
Flag ReorderGoals
Flag StrongFlags
InstallDirs (Flag PathTemplate)
NubList [Char]
NubList LocalRepo
NubList RemoteRepo
projectConfigActiveRepos :: ProjectConfigShared -> Flag ActiveRepos
projectConfigAllowBootLibInstalls :: ProjectConfigShared -> Flag AllowBootLibInstalls
projectConfigAllowNewer :: ProjectConfigShared -> Maybe AllowNewer
projectConfigAllowOlder :: ProjectConfigShared -> Maybe AllowOlder
projectConfigCabalVersion :: ProjectConfigShared -> Flag Version
projectConfigConfigFile :: ProjectConfigShared -> Flag [Char]
projectConfigConstraints :: ProjectConfigShared -> [(UserConstraint, ConstraintSource)]
projectConfigCountConflicts :: ProjectConfigShared -> Flag CountConflicts
projectConfigDistDir :: ProjectConfigShared -> Flag [Char]
projectConfigFineGrainedConflicts :: ProjectConfigShared -> Flag FineGrainedConflicts
projectConfigHaddockIndex :: ProjectConfigShared -> Flag PathTemplate
projectConfigHcFlavor :: ProjectConfigShared -> Flag CompilerFlavor
projectConfigHcPath :: ProjectConfigShared -> Flag [Char]
projectConfigHcPkg :: ProjectConfigShared -> Flag [Char]
projectConfigIgnoreProject :: ProjectConfigShared -> Flag Bool
projectConfigIndependentGoals :: ProjectConfigShared -> Flag IndependentGoals
projectConfigIndexState :: ProjectConfigShared -> Flag TotalIndexState
projectConfigInstallDirs :: ProjectConfigShared -> InstallDirs (Flag PathTemplate)
projectConfigLocalNoIndexRepos :: ProjectConfigShared -> NubList LocalRepo
projectConfigMaxBackjumps :: ProjectConfigShared -> Flag Int
projectConfigMinimizeConflictSet :: ProjectConfigShared -> Flag MinimizeConflictSet
projectConfigMultiRepl :: ProjectConfigShared -> Flag Bool
projectConfigOnlyConstrained :: ProjectConfigShared -> Flag OnlyConstrained
projectConfigPackageDBs :: ProjectConfigShared -> [Maybe PackageDBCWD]
projectConfigPerComponent :: ProjectConfigShared -> Flag Bool
projectConfigPreferOldest :: ProjectConfigShared -> Flag PreferOldest
projectConfigPreferences :: ProjectConfigShared -> [PackageVersionConstraint]
projectConfigProgPathExtra :: ProjectConfigShared -> NubList [Char]
projectConfigProjectDir :: ProjectConfigShared -> Flag [Char]
projectConfigProjectFile :: ProjectConfigShared -> Flag [Char]
projectConfigRemoteRepos :: ProjectConfigShared -> NubList RemoteRepo
projectConfigReorderGoals :: ProjectConfigShared -> Flag ReorderGoals
projectConfigSolver :: ProjectConfigShared -> Flag PreSolver
projectConfigStoreDir :: ProjectConfigShared -> Flag [Char]
projectConfigStrongFlags :: ProjectConfigShared -> Flag StrongFlags
projectConfigWriteGhcEnvironmentFilesPolicy :: ProjectConfigShared -> Flag WriteGhcEnvironmentFilesPolicy
projectConfigRemoteRepos :: NubList RemoteRepo
projectConfigLocalNoIndexRepos :: NubList LocalRepo
projectConfigConstraints :: [(UserConstraint, ConstraintSource)]
projectConfigPreferences :: [PackageVersionConstraint]
projectConfigCabalVersion :: Flag Version
projectConfigSolver :: Flag PreSolver
projectConfigAllowOlder :: Maybe AllowOlder
projectConfigAllowNewer :: Maybe AllowNewer
projectConfigMaxBackjumps :: Flag Int
projectConfigReorderGoals :: Flag ReorderGoals
projectConfigCountConflicts :: Flag CountConflicts
projectConfigFineGrainedConflicts :: Flag FineGrainedConflicts
projectConfigMinimizeConflictSet :: Flag MinimizeConflictSet
projectConfigStrongFlags :: Flag StrongFlags
projectConfigAllowBootLibInstalls :: Flag AllowBootLibInstalls
projectConfigOnlyConstrained :: Flag OnlyConstrained
projectConfigIndexState :: Flag TotalIndexState
projectConfigActiveRepos :: Flag ActiveRepos
projectConfigIndependentGoals :: Flag IndependentGoals
projectConfigPreferOldest :: Flag PreferOldest
projectConfigDistDir :: Flag [Char]
projectConfigConfigFile :: Flag [Char]
projectConfigProjectDir :: Flag [Char]
projectConfigProjectFile :: Flag [Char]
projectConfigIgnoreProject :: Flag Bool
projectConfigHcFlavor :: Flag CompilerFlavor
projectConfigHcPath :: Flag [Char]
projectConfigHcPkg :: Flag [Char]
projectConfigHaddockIndex :: Flag PathTemplate
projectConfigInstallDirs :: InstallDirs (Flag PathTemplate)
projectConfigPackageDBs :: [Maybe PackageDBCWD]
projectConfigStoreDir :: Flag [Char]
projectConfigWriteGhcEnvironmentFilesPolicy :: Flag WriteGhcEnvironmentFilesPolicy
projectConfigPerComponent :: Flag Bool
projectConfigProgPathExtra :: NubList [Char]
projectConfigMultiRepl :: Flag Bool
..} = ProjectConfigShared
defaults ProjectConfigShared -> ProjectConfigShared -> ProjectConfigShared
forall a. Semigroup a => a -> a -> a
<> ProjectConfigShared
projectConfigShared

      defaults :: ProjectConfigShared
defaults =
        ProjectConfigShared
forall a. Monoid a => a
mempty
          { projectConfigSolver = Flag defaultSolver
          , projectConfigAllowOlder = Just (AllowOlder mempty)
          , projectConfigAllowNewer = Just (AllowNewer mempty)
          , projectConfigMaxBackjumps = Flag defaultMaxBackjumps
          , projectConfigReorderGoals = Flag (ReorderGoals False)
          , projectConfigCountConflicts = Flag (CountConflicts True)
          , projectConfigFineGrainedConflicts = Flag (FineGrainedConflicts True)
          , projectConfigMinimizeConflictSet = Flag (MinimizeConflictSet False)
          , projectConfigStrongFlags = Flag (StrongFlags False)
          , projectConfigAllowBootLibInstalls = Flag (AllowBootLibInstalls False)
          , projectConfigOnlyConstrained = Flag OnlyConstrainedNone
          , projectConfigIndependentGoals = Flag (IndependentGoals False)
          , projectConfigPreferOldest = Flag (PreferOldest False)
          -- projectConfigShadowPkgs        = Flag False,
          -- projectConfigReinstall         = Flag False,
          -- projectConfigAvoidReinstalls   = Flag False,
          -- projectConfigOverrideReinstall = Flag False,
          -- projectConfigUpgradeDeps       = Flag False
          }

-- | Resolve the project configuration, with all its optional fields, into
-- 'BuildTimeSettings' with no optional fields (by applying defaults).
resolveBuildTimeSettings
  :: Verbosity
  -> CabalDirLayout
  -> ProjectConfig
  -> BuildTimeSettings
resolveBuildTimeSettings :: Verbosity -> CabalDirLayout -> ProjectConfig -> BuildTimeSettings
resolveBuildTimeSettings
  Verbosity
verbosity
  CabalDirLayout
    { [Char]
cabalLogsDirectory :: [Char]
cabalLogsDirectory :: CabalDirLayout -> [Char]
cabalLogsDirectory
    }
  ProjectConfig
    { projectConfigShared :: ProjectConfig -> ProjectConfigShared
projectConfigShared =
      ProjectConfigShared
        { NubList RemoteRepo
projectConfigRemoteRepos :: ProjectConfigShared -> NubList RemoteRepo
projectConfigRemoteRepos :: NubList RemoteRepo
projectConfigRemoteRepos
        , NubList LocalRepo
projectConfigLocalNoIndexRepos :: ProjectConfigShared -> NubList LocalRepo
projectConfigLocalNoIndexRepos :: NubList LocalRepo
projectConfigLocalNoIndexRepos
        , NubList [Char]
projectConfigProgPathExtra :: ProjectConfigShared -> NubList [Char]
projectConfigProgPathExtra :: NubList [Char]
projectConfigProgPathExtra
        }
    , ProjectConfigBuildOnly
projectConfigBuildOnly :: ProjectConfigBuildOnly
projectConfigBuildOnly :: ProjectConfig -> ProjectConfigBuildOnly
projectConfigBuildOnly
    } =
    BuildTimeSettings{Bool
[Char]
[[Char]]
[PathTemplate]
[LocalRepo]
[RemoteRepo]
Maybe [Char]
Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
Verbosity
ReportLevel
ParStratInstall
buildSettingBuildReports :: ReportLevel
buildSettingCacheDir :: [Char]
buildSettingDryRun :: Bool
buildSettingHaddockOpen :: Bool
buildSettingHttpTransport :: Maybe [Char]
buildSettingIgnoreExpiry :: Bool
buildSettingKeepGoing :: Bool
buildSettingKeepTempFiles :: Bool
buildSettingLocalNoIndexRepos :: [LocalRepo]
buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
buildSettingLogVerbosity :: Verbosity
buildSettingNumJobs :: ParStratInstall
buildSettingOfflineMode :: Bool
buildSettingOnlyDeps :: Bool
buildSettingOnlyDownload :: Bool
buildSettingProgPathExtra :: [[Char]]
buildSettingRemoteRepos :: [RemoteRepo]
buildSettingReportPlanningFailure :: Bool
buildSettingSummaryFile :: [PathTemplate]
buildSettingSymlinkBinDir :: [[Char]]
buildSettingDryRun :: Bool
buildSettingOnlyDeps :: Bool
buildSettingOnlyDownload :: Bool
buildSettingSummaryFile :: [PathTemplate]
buildSettingBuildReports :: ReportLevel
buildSettingSymlinkBinDir :: [[Char]]
buildSettingNumJobs :: ParStratInstall
buildSettingKeepGoing :: Bool
buildSettingOfflineMode :: Bool
buildSettingKeepTempFiles :: Bool
buildSettingRemoteRepos :: [RemoteRepo]
buildSettingLocalNoIndexRepos :: [LocalRepo]
buildSettingCacheDir :: [Char]
buildSettingHttpTransport :: Maybe [Char]
buildSettingIgnoreExpiry :: Bool
buildSettingReportPlanningFailure :: Bool
buildSettingProgPathExtra :: [[Char]]
buildSettingHaddockOpen :: Bool
buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
buildSettingLogVerbosity :: Verbosity
..}
    where
      buildSettingDryRun :: Bool
buildSettingDryRun = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigDryRun
      buildSettingOnlyDeps :: Bool
buildSettingOnlyDeps = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigOnlyDeps
      buildSettingOnlyDownload :: Bool
buildSettingOnlyDownload = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigOnlyDownload
      buildSettingSummaryFile :: [PathTemplate]
buildSettingSummaryFile = NubList PathTemplate -> [PathTemplate]
forall a. NubList a -> [a]
fromNubList NubList PathTemplate
projectConfigSummaryFile
      -- buildSettingLogFile       -- defined below, more complicated
      -- buildSettingLogVerbosity  -- defined below, more complicated
      buildSettingBuildReports :: ReportLevel
buildSettingBuildReports = Flag ReportLevel -> ReportLevel
forall a. WithCallStack (Flag a -> a)
fromFlag Flag ReportLevel
projectConfigBuildReports
      buildSettingSymlinkBinDir :: [[Char]]
buildSettingSymlinkBinDir = Flag [Char] -> [[Char]]
forall a. Flag a -> [a]
flagToList Flag [Char]
projectConfigSymlinkBinDir
      buildSettingNumJobs :: ParStratInstall
buildSettingNumJobs = Flag Bool -> Flag (Maybe Int) -> ParStratInstall
resolveNumJobsSetting Flag Bool
projectConfigUseSemaphore Flag (Maybe Int)
projectConfigNumJobs
      buildSettingKeepGoing :: Bool
buildSettingKeepGoing = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigKeepGoing
      buildSettingOfflineMode :: Bool
buildSettingOfflineMode = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigOfflineMode
      buildSettingKeepTempFiles :: Bool
buildSettingKeepTempFiles = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigKeepTempFiles
      buildSettingRemoteRepos :: [RemoteRepo]
buildSettingRemoteRepos = NubList RemoteRepo -> [RemoteRepo]
forall a. NubList a -> [a]
fromNubList NubList RemoteRepo
projectConfigRemoteRepos
      buildSettingLocalNoIndexRepos :: [LocalRepo]
buildSettingLocalNoIndexRepos = NubList LocalRepo -> [LocalRepo]
forall a. NubList a -> [a]
fromNubList NubList LocalRepo
projectConfigLocalNoIndexRepos
      buildSettingCacheDir :: [Char]
buildSettingCacheDir = Flag [Char] -> [Char]
forall a. WithCallStack (Flag a -> a)
fromFlag Flag [Char]
projectConfigCacheDir
      buildSettingHttpTransport :: Maybe [Char]
buildSettingHttpTransport = Flag [Char] -> Maybe [Char]
forall a. Flag a -> Maybe a
flagToMaybe Flag [Char]
projectConfigHttpTransport
      buildSettingIgnoreExpiry :: Bool
buildSettingIgnoreExpiry = Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigIgnoreExpiry
      buildSettingReportPlanningFailure :: Bool
buildSettingReportPlanningFailure =
        Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigReportPlanningFailure
      buildSettingProgPathExtra :: [[Char]]
buildSettingProgPathExtra = NubList [Char] -> [[Char]]
forall a. NubList a -> [a]
fromNubList NubList [Char]
projectConfigProgPathExtra
      buildSettingHaddockOpen :: Bool
buildSettingHaddockOpen = Bool
False

      ProjectConfigBuildOnly{Flag Bool
Flag [Char]
Flag (Maybe Int)
Flag Verbosity
Flag ReportLevel
Flag PathTemplate
NubList PathTemplate
ClientInstallFlags
projectConfigBuildReports :: ProjectConfigBuildOnly -> Flag ReportLevel
projectConfigCacheDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigClientInstallFlags :: ProjectConfigBuildOnly -> ClientInstallFlags
projectConfigDryRun :: ProjectConfigBuildOnly -> Flag Bool
projectConfigHttpTransport :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigIgnoreExpiry :: ProjectConfigBuildOnly -> Flag Bool
projectConfigKeepGoing :: ProjectConfigBuildOnly -> Flag Bool
projectConfigKeepTempFiles :: ProjectConfigBuildOnly -> Flag Bool
projectConfigLogFile :: ProjectConfigBuildOnly -> Flag PathTemplate
projectConfigLogsDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigNumJobs :: ProjectConfigBuildOnly -> Flag (Maybe Int)
projectConfigOfflineMode :: ProjectConfigBuildOnly -> Flag Bool
projectConfigOnlyDeps :: ProjectConfigBuildOnly -> Flag Bool
projectConfigOnlyDownload :: ProjectConfigBuildOnly -> Flag Bool
projectConfigReportPlanningFailure :: ProjectConfigBuildOnly -> Flag Bool
projectConfigSummaryFile :: ProjectConfigBuildOnly -> NubList PathTemplate
projectConfigSymlinkBinDir :: ProjectConfigBuildOnly -> Flag [Char]
projectConfigUseSemaphore :: ProjectConfigBuildOnly -> Flag Bool
projectConfigVerbosity :: ProjectConfigBuildOnly -> Flag Verbosity
projectConfigDryRun :: Flag Bool
projectConfigOnlyDeps :: Flag Bool
projectConfigOnlyDownload :: Flag Bool
projectConfigSummaryFile :: NubList PathTemplate
projectConfigBuildReports :: Flag ReportLevel
projectConfigSymlinkBinDir :: Flag [Char]
projectConfigUseSemaphore :: Flag Bool
projectConfigNumJobs :: Flag (Maybe Int)
projectConfigKeepGoing :: Flag Bool
projectConfigOfflineMode :: Flag Bool
projectConfigKeepTempFiles :: Flag Bool
projectConfigCacheDir :: Flag [Char]
projectConfigHttpTransport :: Flag [Char]
projectConfigIgnoreExpiry :: Flag Bool
projectConfigReportPlanningFailure :: Flag Bool
projectConfigVerbosity :: Flag Verbosity
projectConfigLogFile :: Flag PathTemplate
projectConfigLogsDir :: Flag [Char]
projectConfigClientInstallFlags :: ClientInstallFlags
..} =
        ProjectConfigBuildOnly
defaults
          ProjectConfigBuildOnly
-> ProjectConfigBuildOnly -> ProjectConfigBuildOnly
forall a. Semigroup a => a -> a -> a
<> ProjectConfigBuildOnly
projectConfigBuildOnly

      defaults :: ProjectConfigBuildOnly
defaults =
        ProjectConfigBuildOnly
forall a. Monoid a => a
mempty
          { projectConfigDryRun = toFlag False
          , projectConfigOnlyDeps = toFlag False
          , projectConfigOnlyDownload = toFlag False
          , projectConfigBuildReports = toFlag NoReports
          , projectConfigReportPlanningFailure = toFlag False
          , projectConfigKeepGoing = toFlag False
          , projectConfigOfflineMode = toFlag False
          , projectConfigKeepTempFiles = toFlag False
          , projectConfigIgnoreExpiry = toFlag False
          }

      -- The logging logic: what log file to use and what verbosity.
      --
      -- If the user has specified --remote-build-reporting=detailed, use the
      -- default log file location. If the --build-log option is set, use the
      -- provided location. Otherwise don't use logging, unless building in
      -- parallel (in which case the default location is used).
      --
      buildSettingLogFile
        :: Maybe
            ( Compiler
              -> Platform
              -> PackageId
              -> UnitId
              -> FilePath
            )
      buildSettingLogFile :: Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
buildSettingLogFile
        | Bool
useDefaultTemplate = (Compiler -> Platform -> PackageId -> UnitId -> [Char])
-> Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
forall a. a -> Maybe a
Just (PathTemplate
-> Compiler -> Platform -> PackageId -> UnitId -> [Char]
substLogFileName PathTemplate
defaultTemplate)
        | Bool
otherwise = (PathTemplate
 -> Compiler -> Platform -> PackageId -> UnitId -> [Char])
-> Maybe PathTemplate
-> Maybe (Compiler -> Platform -> PackageId -> UnitId -> [Char])
forall a b. (a -> b) -> Maybe a -> Maybe b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap PathTemplate
-> Compiler -> Platform -> PackageId -> UnitId -> [Char]
substLogFileName Maybe PathTemplate
givenTemplate

      defaultTemplate :: PathTemplate
defaultTemplate =
        [Char] -> PathTemplate
toPathTemplate ([Char] -> PathTemplate) -> [Char] -> PathTemplate
forall a b. (a -> b) -> a -> b
$
          [Char]
cabalLogsDirectory
            [Char] -> [Char] -> [Char]
</> [Char]
"$compiler"
            [Char] -> [Char] -> [Char]
</> [Char]
"$libname"
            [Char] -> [Char] -> [Char]
<.> [Char]
"log"
      givenTemplate :: Maybe PathTemplate
givenTemplate = Flag PathTemplate -> Maybe PathTemplate
forall a. Flag a -> Maybe a
flagToMaybe Flag PathTemplate
projectConfigLogFile

      useDefaultTemplate :: Bool
useDefaultTemplate
        | ReportLevel
buildSettingBuildReports ReportLevel -> ReportLevel -> Bool
forall a. Eq a => a -> a -> Bool
== ReportLevel
DetailedReports = Bool
True
        | Maybe PathTemplate -> Bool
forall a. Maybe a -> Bool
isJust Maybe PathTemplate
givenTemplate = Bool
False
        | ParStratInstall -> Bool
forall n. ParStratX n -> Bool
isParallelBuild ParStratInstall
buildSettingNumJobs = Bool
True
        | Bool
otherwise = Bool
False

      substLogFileName
        :: PathTemplate
        -> Compiler
        -> Platform
        -> PackageId
        -> UnitId
        -> FilePath
      substLogFileName :: PathTemplate
-> Compiler -> Platform -> PackageId -> UnitId -> [Char]
substLogFileName PathTemplate
template Compiler
compiler Platform
platform PackageId
pkgid UnitId
uid =
        PathTemplate -> [Char]
fromPathTemplate (PathTemplateEnv -> PathTemplate -> PathTemplate
substPathTemplate PathTemplateEnv
env PathTemplate
template)
        where
          env :: PathTemplateEnv
env =
            PackageId -> UnitId -> CompilerInfo -> Platform -> PathTemplateEnv
initialPathTemplateEnv
              PackageId
pkgid
              UnitId
uid
              (Compiler -> CompilerInfo
compilerInfo Compiler
compiler)
              Platform
platform

      -- If the user has specified --remote-build-reporting=detailed or
      -- --build-log, use more verbose logging.
      --
      buildSettingLogVerbosity :: Verbosity
      buildSettingLogVerbosity :: Verbosity
buildSettingLogVerbosity
        | Bool
overrideVerbosity = (Verbosity -> Verbosity) -> Verbosity -> Verbosity
modifyVerbosity (Verbosity -> Verbosity -> Verbosity
forall a. Ord a => a -> a -> a
max Verbosity
verbose) Verbosity
verbosity
        | Bool
otherwise = Verbosity
verbosity

      overrideVerbosity :: Bool
      overrideVerbosity :: Bool
overrideVerbosity
        | ReportLevel
buildSettingBuildReports ReportLevel -> ReportLevel -> Bool
forall a. Eq a => a -> a -> Bool
== ReportLevel
DetailedReports = Bool
True
        | Maybe PathTemplate -> Bool
forall a. Maybe a -> Bool
isJust Maybe PathTemplate
givenTemplate = Bool
True
        | ParStratInstall -> Bool
forall n. ParStratX n -> Bool
isParallelBuild ParStratInstall
buildSettingNumJobs = Bool
False
        | Bool
otherwise = Bool
False

-- | Determine the number of jobs (ParStrat) from the project config
resolveNumJobsSetting
  :: Flag Bool
  -- ^ Whether to use a semaphore (-jsem)
  -> Flag (Maybe Int)
  -- ^ The number of jobs to run concurrently
  -> ParStratX Int
resolveNumJobsSetting :: Flag Bool -> Flag (Maybe Int) -> ParStratInstall
resolveNumJobsSetting Flag Bool
projectConfigUseSemaphore Flag (Maybe Int)
projectConfigNumJobs =
  if Flag Bool -> Bool
forall a. WithCallStack (Flag a -> a)
fromFlag Flag Bool
projectConfigUseSemaphore
    then Int -> ParStratInstall
forall sem. sem -> ParStratX sem
UseSem (Flag (Maybe Int) -> Int
determineNumJobs Flag (Maybe Int)
projectConfigNumJobs)
    else case (Flag (Maybe Int) -> Int
determineNumJobs Flag (Maybe Int)
projectConfigNumJobs) of
      Int
1 -> ParStratInstall
forall sem. ParStratX sem
Serial
      Int
n -> Maybe Int -> ParStratInstall
forall sem. Maybe Int -> ParStratX sem
NumJobs (Int -> Maybe Int
forall a. a -> Maybe a
Just Int
n)

---------------------------------------------
-- Reading and writing project config files
--

-- | Get @ProjectRootUsability@ of a given file
getProjectRootUsability :: FilePath -> IO ProjectRootUsability
getProjectRootUsability :: [Char] -> IO ProjectRootUsability
getProjectRootUsability [Char]
filePath = do
  exists <- [Char] -> IO Bool
doesFileExist [Char]
filePath
  if exists
    then return ProjectRootUsabilityPresentAndUsable
    else do
      let isUsableAction =
            forall e a. Exception e => (e -> IO a) -> IO a -> IO a
handle @IOException
              -- NOTE: if any IOException is raised, we assume the file does not exist.
              -- That is what happen when we call @pathIsSymbolicLink@ on a @FilePath@ that does not exist.
              (IO Bool -> IOException -> IO Bool
forall a b. a -> b -> a
const (IO Bool -> IOException -> IO Bool)
-> IO Bool -> IOException -> IO Bool
forall a b. (a -> b) -> a -> b
$ Bool -> IO Bool
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure Bool
False)
              (Bool -> Bool -> Bool
(||) (Bool -> Bool -> Bool) -> IO Bool -> IO (Bool -> Bool)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO Bool
pathIsSymbolicLink [Char]
filePath IO (Bool -> Bool) -> IO Bool -> IO Bool
forall a b. IO (a -> b) -> IO a -> IO b
forall (f :: * -> *) a b. Applicative f => f (a -> b) -> f a -> f b
<*> [Char] -> IO Bool
doesPathExist [Char]
filePath)
      isUnusable <- isUsableAction
      if isUnusable
        then return ProjectRootUsabilityPresentAndUnusable
        else return ProjectRootUsabilityNotPresent

-- | Find the root of this project.
--
-- The project directory will be one of the following:
--   1. @mprojectDir@ when present
--   2. The first directory containing @mprojectFile@/@cabal.project@, starting from the current directory
--      and recursively checking parent directories
--   3. The current directory
findProjectRoot
  :: Verbosity
  -> Maybe FilePath
  -- ^ Explicit project directory
  -> Maybe FilePath
  -- ^ Explicit project file
  -> IO (Either BadProjectRoot ProjectRoot)
findProjectRoot :: Verbosity
-> Maybe [Char]
-> Maybe [Char]
-> IO (Either BadProjectRoot ProjectRoot)
findProjectRoot Verbosity
verbosity Maybe [Char]
mprojectDir Maybe [Char]
mprojectFile = do
  case Maybe [Char]
mprojectDir of
    Maybe [Char]
Nothing
      | Just [Char]
file <- Maybe [Char]
mprojectFile
      , [Char] -> Bool
isAbsolute [Char]
file -> do
          Verbosity -> [Char] -> IO ()
warn Verbosity
verbosity ([Char] -> IO ()) -> [Char] -> IO ()
forall a b. (a -> b) -> a -> b
$
            [Char]
"Specifying an absolute path to the project file is deprecated."
              [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
" Use --project-dir to set the project's directory."

          [Char] -> IO ProjectRootUsability
getProjectRootUsability [Char]
file IO ProjectRootUsability
-> (ProjectRootUsability -> IO (Either BadProjectRoot ProjectRoot))
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
            ProjectRootUsability
ProjectRootUsabilityPresentAndUsable ->
              ([Char] -> [Char] -> IO (Either BadProjectRoot ProjectRoot))
-> ([Char], [Char]) -> IO (Either BadProjectRoot ProjectRoot)
forall a b c. (a -> b -> c) -> (a, b) -> c
uncurry [Char] -> [Char] -> IO (Either BadProjectRoot ProjectRoot)
forall {f :: * -> *} {a}.
Applicative f =>
[Char] -> [Char] -> f (Either a ProjectRoot)
projectRoot
                (([Char], [Char]) -> IO (Either BadProjectRoot ProjectRoot))
-> IO ([Char], [Char]) -> IO (Either BadProjectRoot ProjectRoot)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< ([Char] -> [Char]) -> ([Char], [Char]) -> ([Char], [Char])
forall b c d. (b -> c) -> (b, d) -> (c, d)
forall (a :: * -> * -> *) b c d.
Arrow a =>
a b c -> a (b, d) (c, d)
first [Char] -> [Char]
dropTrailingPathSeparator (([Char], [Char]) -> ([Char], [Char]))
-> ([Char] -> ([Char], [Char])) -> [Char] -> ([Char], [Char])
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> ([Char], [Char])
splitFileName ([Char] -> ([Char], [Char])) -> IO [Char] -> IO ([Char], [Char])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO [Char]
canonicalizePath [Char]
file
            ProjectRootUsability
ProjectRootUsabilityNotPresent ->
              BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootExplicitFileNotFound [Char]
file)
            ProjectRootUsability
ProjectRootUsabilityPresentAndUnusable ->
              BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootFileBroken [Char]
file)
      | Bool
otherwise -> Maybe [Char] -> IO (Either BadProjectRoot ProjectRoot)
probeProjectRoot Maybe [Char]
mprojectFile
    Just [Char]
dir ->
      [Char] -> IO Bool
doesDirectoryExist [Char]
dir IO Bool
-> (Bool -> IO (Either BadProjectRoot ProjectRoot))
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
        Bool
False -> BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootDirNotFound [Char]
dir)
        Bool
True -> do
          projectDir <- [Char] -> IO [Char]
canonicalizePath [Char]
dir

          case mprojectFile of
            Maybe [Char]
Nothing -> Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either BadProjectRoot ProjectRoot
 -> IO (Either BadProjectRoot ProjectRoot))
-> Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. (a -> b) -> a -> b
$ ProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. b -> Either a b
Right ([Char] -> [Char] -> ProjectRoot
ProjectRootExplicit [Char]
projectDir [Char]
defaultProjectFile)
            Just [Char]
projectFile
              | [Char] -> Bool
isAbsolute [Char]
projectFile ->
                  [Char] -> IO ProjectRootUsability
getProjectRootUsability [Char]
projectFile IO ProjectRootUsability
-> (ProjectRootUsability -> IO (Either BadProjectRoot ProjectRoot))
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                    ProjectRootUsability
ProjectRootUsabilityNotPresent ->
                      BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootAbsoluteFileNotFound [Char]
projectFile)
                    ProjectRootUsability
ProjectRootUsabilityPresentAndUsable ->
                      ProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. b -> Either a b
Right (ProjectRoot -> Either BadProjectRoot ProjectRoot)
-> ([Char] -> ProjectRoot)
-> [Char]
-> Either BadProjectRoot ProjectRoot
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char] -> ProjectRoot
ProjectRootExplicitAbsolute [Char]
dir ([Char] -> Either BadProjectRoot ProjectRoot)
-> IO [Char] -> IO (Either BadProjectRoot ProjectRoot)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> IO [Char]
canonicalizePath [Char]
projectFile
                    ProjectRootUsability
ProjectRootUsabilityPresentAndUnusable ->
                      BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootFileBroken [Char]
projectFile)
              | Bool
otherwise ->
                  [Char] -> IO ProjectRootUsability
getProjectRootUsability ([Char]
projectDir [Char] -> [Char] -> [Char]
</> [Char]
projectFile) IO ProjectRootUsability
-> (ProjectRootUsability -> IO (Either BadProjectRoot ProjectRoot))
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
                    ProjectRootUsability
ProjectRootUsabilityNotPresent ->
                      BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> [Char] -> BadProjectRoot
BadProjectRootDirFileNotFound [Char]
dir [Char]
projectFile)
                    ProjectRootUsability
ProjectRootUsabilityPresentAndUsable ->
                      [Char] -> [Char] -> IO (Either BadProjectRoot ProjectRoot)
forall {f :: * -> *} {a}.
Applicative f =>
[Char] -> [Char] -> f (Either a ProjectRoot)
projectRoot [Char]
projectDir [Char]
projectFile
                    ProjectRootUsability
ProjectRootUsabilityPresentAndUnusable ->
                      BadProjectRoot -> IO (Either BadProjectRoot ProjectRoot)
forall {a} {b}. a -> IO (Either a b)
left ([Char] -> BadProjectRoot
BadProjectRootFileBroken [Char]
projectFile)
  where
    left :: a -> IO (Either a b)
left = Either a b -> IO (Either a b)
forall a. a -> IO a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either a b -> IO (Either a b))
-> (a -> Either a b) -> a -> IO (Either a b)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. a -> Either a b
forall a b. a -> Either a b
Left

    projectRoot :: [Char] -> [Char] -> f (Either a ProjectRoot)
projectRoot [Char]
projectDir [Char]
projectFile =
      Either a ProjectRoot -> f (Either a ProjectRoot)
forall a. a -> f a
forall (f :: * -> *) a. Applicative f => a -> f a
pure (Either a ProjectRoot -> f (Either a ProjectRoot))
-> Either a ProjectRoot -> f (Either a ProjectRoot)
forall a b. (a -> b) -> a -> b
$ ProjectRoot -> Either a ProjectRoot
forall a b. b -> Either a b
Right ([Char] -> [Char] -> ProjectRoot
ProjectRootExplicit [Char]
projectDir [Char]
projectFile)

probeProjectRoot :: Maybe FilePath -> IO (Either BadProjectRoot ProjectRoot)
probeProjectRoot :: Maybe [Char] -> IO (Either BadProjectRoot ProjectRoot)
probeProjectRoot Maybe [Char]
mprojectFile = do
  startdir <- IO [Char]
System.Directory.getCurrentDirectory
  homedir <- getHomeDirectory
  probe startdir homedir
  where
    projectFileName :: String
    projectFileName :: [Char]
projectFileName = [Char] -> Maybe [Char] -> [Char]
forall a. a -> Maybe a -> a
fromMaybe [Char]
defaultProjectFile Maybe [Char]
mprojectFile

    -- Search upwards. If we get to the users home dir or the filesystem root,
    -- then use the current dir
    probe :: FilePath -> String -> IO (Either BadProjectRoot ProjectRoot)
    probe :: [Char] -> [Char] -> IO (Either BadProjectRoot ProjectRoot)
probe [Char]
startdir [Char]
homedir = [Char] -> IO (Either BadProjectRoot ProjectRoot)
go [Char]
startdir
      where
        go :: FilePath -> IO (Either BadProjectRoot ProjectRoot)
        go :: [Char] -> IO (Either BadProjectRoot ProjectRoot)
go [Char]
dir | [Char] -> Bool
isDrive [Char]
dir Bool -> Bool -> Bool
|| [Char]
dir [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
homedir =
          case Maybe [Char]
mprojectFile of
            Maybe [Char]
Nothing -> Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. b -> Either a b
Right ([Char] -> ProjectRoot
ProjectRootImplicit [Char]
startdir))
            Just [Char]
file -> Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. a -> Either a b
Left ([Char] -> BadProjectRoot
BadProjectRootExplicitFileNotFound [Char]
file))
        go [Char]
dir = do
          [Char] -> IO ProjectRootUsability
getProjectRootUsability ([Char]
dir [Char] -> [Char] -> [Char]
</> [Char]
projectFileName) IO ProjectRootUsability
-> (ProjectRootUsability -> IO (Either BadProjectRoot ProjectRoot))
-> IO (Either BadProjectRoot ProjectRoot)
forall a b. IO a -> (a -> IO b) -> IO b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= \case
            ProjectRootUsability
ProjectRootUsabilityNotPresent ->
              [Char] -> IO (Either BadProjectRoot ProjectRoot)
go ([Char] -> [Char]
takeDirectory [Char]
dir)
            ProjectRootUsability
ProjectRootUsabilityPresentAndUsable ->
              Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (ProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. b -> Either a b
Right (ProjectRoot -> Either BadProjectRoot ProjectRoot)
-> ProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> ProjectRoot
ProjectRootExplicit [Char]
dir [Char]
projectFileName)
            ProjectRootUsability
ProjectRootUsabilityPresentAndUnusable ->
              Either BadProjectRoot ProjectRoot
-> IO (Either BadProjectRoot ProjectRoot)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. a -> Either a b
Left (BadProjectRoot -> Either BadProjectRoot ProjectRoot)
-> BadProjectRoot -> Either BadProjectRoot ProjectRoot
forall a b. (a -> b) -> a -> b
$ [Char] -> BadProjectRoot
BadProjectRootFileBroken [Char]
projectFileName)

-- | Errors returned by 'findProjectRoot'.
data BadProjectRoot
  = BadProjectRootExplicitFileNotFound FilePath
  | BadProjectRootDirNotFound FilePath
  | BadProjectRootAbsoluteFileNotFound FilePath
  | BadProjectRootDirFileNotFound FilePath FilePath
  | BadProjectRootFileBroken FilePath
  deriving (Int -> BadProjectRoot -> [Char] -> [Char]
[BadProjectRoot] -> [Char] -> [Char]
BadProjectRoot -> [Char]
(Int -> BadProjectRoot -> [Char] -> [Char])
-> (BadProjectRoot -> [Char])
-> ([BadProjectRoot] -> [Char] -> [Char])
-> Show BadProjectRoot
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> BadProjectRoot -> [Char] -> [Char]
showsPrec :: Int -> BadProjectRoot -> [Char] -> [Char]
$cshow :: BadProjectRoot -> [Char]
show :: BadProjectRoot -> [Char]
$cshowList :: [BadProjectRoot] -> [Char] -> [Char]
showList :: [BadProjectRoot] -> [Char] -> [Char]
Show, BadProjectRoot -> BadProjectRoot -> Bool
(BadProjectRoot -> BadProjectRoot -> Bool)
-> (BadProjectRoot -> BadProjectRoot -> Bool) -> Eq BadProjectRoot
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: BadProjectRoot -> BadProjectRoot -> Bool
== :: BadProjectRoot -> BadProjectRoot -> Bool
$c/= :: BadProjectRoot -> BadProjectRoot -> Bool
/= :: BadProjectRoot -> BadProjectRoot -> Bool
Eq)

instance Exception BadProjectRoot where
  displayException :: BadProjectRoot -> [Char]
displayException = BadProjectRoot -> [Char]
renderBadProjectRoot

renderBadProjectRoot :: BadProjectRoot -> String
renderBadProjectRoot :: BadProjectRoot -> [Char]
renderBadProjectRoot = \case
  BadProjectRootExplicitFileNotFound [Char]
projectFile ->
    [Char]
"The given project file '" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
projectFile [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not exist."
  BadProjectRootDirNotFound [Char]
dir ->
    [Char]
"The given project directory '" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
dir [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"' does not exist."
  BadProjectRootAbsoluteFileNotFound [Char]
file ->
    [Char]
"The given project file '" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
file [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"' does not exist."
  BadProjectRootDirFileNotFound [Char]
dir [Char]
file ->
    [Char]
"The given project directory/file combination '" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
dir [Char] -> [Char] -> [Char]
</> [Char]
file [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"' does not exist."
  BadProjectRootFileBroken [Char]
file ->
    [Char]
"The given project file '" [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
file [Char] -> [Char] -> [Char]
forall a. Semigroup a => a -> a -> a
<> [Char]
"' is broken. Is it a broken symbolic link?"

-- | State of the project file, encodes if the file can be used
data ProjectRootUsability
  = -- | The file is present and can be used
    ProjectRootUsabilityPresentAndUsable
  | -- | The file is present but can't be used (e.g. broken symlink)
    ProjectRootUsabilityPresentAndUnusable
  | -- | The file is not present
    ProjectRootUsabilityNotPresent
  deriving (ProjectRootUsability -> ProjectRootUsability -> Bool
(ProjectRootUsability -> ProjectRootUsability -> Bool)
-> (ProjectRootUsability -> ProjectRootUsability -> Bool)
-> Eq ProjectRootUsability
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: ProjectRootUsability -> ProjectRootUsability -> Bool
== :: ProjectRootUsability -> ProjectRootUsability -> Bool
$c/= :: ProjectRootUsability -> ProjectRootUsability -> Bool
/= :: ProjectRootUsability -> ProjectRootUsability -> Bool
Eq, Int -> ProjectRootUsability -> [Char] -> [Char]
[ProjectRootUsability] -> [Char] -> [Char]
ProjectRootUsability -> [Char]
(Int -> ProjectRootUsability -> [Char] -> [Char])
-> (ProjectRootUsability -> [Char])
-> ([ProjectRootUsability] -> [Char] -> [Char])
-> Show ProjectRootUsability
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> ProjectRootUsability -> [Char] -> [Char]
showsPrec :: Int -> ProjectRootUsability -> [Char] -> [Char]
$cshow :: ProjectRootUsability -> [Char]
show :: ProjectRootUsability -> [Char]
$cshowList :: [ProjectRootUsability] -> [Char] -> [Char]
showList :: [ProjectRootUsability] -> [Char] -> [Char]
Show)

withGlobalConfig
  :: Verbosity
  -- ^ verbosity
  -> Flag FilePath
  -- ^ @--cabal-config@
  -> (ProjectConfig -> IO a)
  -- ^ with global
  -> IO a
withGlobalConfig :: forall a.
Verbosity -> Flag [Char] -> (ProjectConfig -> IO a) -> IO a
withGlobalConfig Verbosity
verbosity Flag [Char]
gcf ProjectConfig -> IO a
with = do
  globalConfig <- [Char] -> Rebuild ProjectConfig -> IO ProjectConfig
forall a. [Char] -> Rebuild a -> IO a
runRebuild [Char]
"" (Rebuild ProjectConfig -> IO ProjectConfig)
-> Rebuild ProjectConfig -> IO ProjectConfig
forall a b. (a -> b) -> a -> b
$ Verbosity -> Flag [Char] -> Rebuild ProjectConfig
readGlobalConfig Verbosity
verbosity Flag [Char]
gcf
  with globalConfig

withProjectOrGlobalConfig
  :: Flag Bool
  -- ^ whether to ignore local project (--ignore-project flag)
  -> IO a
  -- ^ continuation with project
  -> IO a
  -- ^ continuation without project
  -> IO a
withProjectOrGlobalConfig :: forall a. Flag Bool -> IO a -> IO a -> IO a
withProjectOrGlobalConfig (Flag Bool
True) IO a
_with IO a
without = do
  without
withProjectOrGlobalConfig Flag Bool
_ignorePrj IO a
with IO a
without =
  IO a -> IO a -> IO a
forall a. IO a -> IO a -> IO a
withProjectOrGlobalConfig' IO a
with IO a
without

withProjectOrGlobalConfig'
  :: IO a
  -- ^ continuation with project
  -> IO a
  -- ^ continuation without project
  -> IO a
withProjectOrGlobalConfig' :: forall a. IO a -> IO a -> IO a
withProjectOrGlobalConfig' IO a
with IO a
without = do
  IO a -> (BadPackageLocations -> IO a) -> IO a
forall e a. Exception e => IO a -> (e -> IO a) -> IO a
catch IO a
with ((BadPackageLocations -> IO a) -> IO a)
-> (BadPackageLocations -> IO a) -> IO a
forall a b. (a -> b) -> a -> b
$
    \case
      (BadPackageLocations Set ProjectConfigProvenance
prov [BadPackageLocation]
locs)
        | Set ProjectConfigProvenance
prov Set ProjectConfigProvenance -> Set ProjectConfigProvenance -> Bool
forall a. Eq a => a -> a -> Bool
== ProjectConfigProvenance -> Set ProjectConfigProvenance
forall a. a -> Set a
Set.singleton ProjectConfigProvenance
Implicit
        , let
            isGlobErr :: BadPackageLocation -> Bool
isGlobErr (BadLocGlobEmptyMatch [Char]
_) = Bool
True
            isGlobErr BadPackageLocation
_ = Bool
False
        , (BadPackageLocation -> Bool) -> [BadPackageLocation] -> Bool
forall (t :: * -> *) a. Foldable t => (a -> Bool) -> t a -> Bool
any BadPackageLocation -> Bool
isGlobErr [BadPackageLocation]
locs -> do
            without
      BadPackageLocations
err -> BadPackageLocations -> IO a
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO BadPackageLocations
err

-- | Read all the config relevant for a project. This includes the project
-- file if any, plus other global config.
readProjectConfig
  :: Verbosity
  -> HttpTransport
  -> Flag Bool
  -- ^ @--ignore-project@
  -> Flag FilePath
  -> DistDirLayout
  -> Rebuild ProjectConfigSkeleton
readProjectConfig :: Verbosity
-> HttpTransport
-> Flag Bool
-> Flag [Char]
-> DistDirLayout
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectConfig Verbosity
verbosity HttpTransport
_ (Flag Bool
True) Flag [Char]
configFileFlag DistDirLayout
_ = do
  global <- ProjectConfig -> CondTree ConfVar [ProjectConfigPath] ProjectConfig
singletonProjectConfigSkeleton (ProjectConfig
 -> CondTree ConfVar [ProjectConfigPath] ProjectConfig)
-> Rebuild ProjectConfig
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Verbosity -> Flag [Char] -> Rebuild ProjectConfig
readGlobalConfig Verbosity
verbosity Flag [Char]
configFileFlag
  return (global <> singletonProjectConfigSkeleton defaultImplicitProjectConfig)
readProjectConfig Verbosity
verbosity HttpTransport
httpTransport Flag Bool
_ Flag [Char]
configFileFlag DistDirLayout
distDirLayout = do
  global <- ProjectConfig -> CondTree ConfVar [ProjectConfigPath] ProjectConfig
singletonProjectConfigSkeleton (ProjectConfig
 -> CondTree ConfVar [ProjectConfigPath] ProjectConfig)
-> Rebuild ProjectConfig
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> Verbosity -> Flag [Char] -> Rebuild ProjectConfig
readGlobalConfig Verbosity
verbosity Flag [Char]
configFileFlag
  local <- readProjectLocalConfigOrDefault verbosity httpTransport distDirLayout
  freeze <- readProjectLocalFreezeConfig verbosity httpTransport distDirLayout
  extra <- readProjectLocalExtraConfig verbosity httpTransport distDirLayout
  return (global <> local <> freeze <> extra)

-- | Reads an explicit @cabal.project@ file in the given project root dir,
-- or returns the default project config for an implicitly defined project.
readProjectLocalConfigOrDefault
  :: Verbosity
  -> HttpTransport
  -> DistDirLayout
  -> Rebuild ProjectConfigSkeleton
readProjectLocalConfigOrDefault :: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectLocalConfigOrDefault Verbosity
verbosity HttpTransport
httpTransport DistDirLayout
distDirLayout = do
  let projectFile :: [Char]
projectFile = DistDirLayout -> [Char] -> [Char]
distProjectFile DistDirLayout
distDirLayout [Char]
""
  usesExplicitProjectRoot <- IO Bool -> Rebuild Bool
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> Rebuild Bool) -> IO Bool -> Rebuild Bool
forall a b. (a -> b) -> a -> b
$ [Char] -> IO Bool
doesFileExist [Char]
projectFile
  if usesExplicitProjectRoot
    then do
      readProjectFileSkeleton verbosity httpTransport distDirLayout "" "project file"
    else do
      monitorFiles [monitorNonExistentFile projectFile]
      return (singletonProjectConfigSkeleton defaultImplicitProjectConfig)

defaultImplicitProjectConfig :: ProjectConfig
defaultImplicitProjectConfig :: ProjectConfig
defaultImplicitProjectConfig =
  ProjectConfig
forall a. Monoid a => a
mempty
    { -- We expect a package in the current directory.
      projectPackages = ["./*.cabal"]
    , projectConfigProvenance = Set.singleton Implicit
    }

-- | Reads a @cabal.project.local@ file in the given project root dir,
-- or returns empty. This file gets written by @cabal configure@, or in
-- principle can be edited manually or by other tools.
readProjectLocalExtraConfig
  :: Verbosity
  -> HttpTransport
  -> DistDirLayout
  -> Rebuild ProjectConfigSkeleton
readProjectLocalExtraConfig :: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectLocalExtraConfig Verbosity
verbosity HttpTransport
httpTransport DistDirLayout
distDirLayout =
  Verbosity
-> HttpTransport
-> DistDirLayout
-> [Char]
-> [Char]
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectFileSkeleton
    Verbosity
verbosity
    HttpTransport
httpTransport
    DistDirLayout
distDirLayout
    [Char]
"local"
    [Char]
"project local configuration file"

-- | Reads a @cabal.project.freeze@ file in the given project root dir,
-- or returns empty. This file gets written by @cabal freeze@, or in
-- principle can be edited manually or by other tools.
readProjectLocalFreezeConfig
  :: Verbosity
  -> HttpTransport
  -> DistDirLayout
  -> Rebuild ProjectConfigSkeleton
readProjectLocalFreezeConfig :: Verbosity
-> HttpTransport
-> DistDirLayout
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectLocalFreezeConfig Verbosity
verbosity HttpTransport
httpTransport DistDirLayout
distDirLayout =
  Verbosity
-> HttpTransport
-> DistDirLayout
-> [Char]
-> [Char]
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectFileSkeleton
    Verbosity
verbosity
    HttpTransport
httpTransport
    DistDirLayout
distDirLayout
    [Char]
"freeze"
    [Char]
"project freeze file"

-- | Reads a named extended (with imports and conditionals) config file in the given project root dir, or returns empty.
readProjectFileSkeleton :: Verbosity -> HttpTransport -> DistDirLayout -> String -> String -> Rebuild ProjectConfigSkeleton
readProjectFileSkeleton :: Verbosity
-> HttpTransport
-> DistDirLayout
-> [Char]
-> [Char]
-> Rebuild (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readProjectFileSkeleton
  Verbosity
verbosity
  HttpTransport
httpTransport
  DistDirLayout{[Char] -> [Char]
distProjectFile :: DistDirLayout -> [Char] -> [Char]
distProjectFile :: [Char] -> [Char]
distProjectFile, [Char]
distDownloadSrcDirectory :: [Char]
distDownloadSrcDirectory :: DistDirLayout -> [Char]
distDownloadSrcDirectory}
  [Char]
extensionName
  [Char]
extensionDescription = do
    exists <- IO Bool -> Rebuild Bool
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> Rebuild Bool) -> IO Bool -> Rebuild Bool
forall a b. (a -> b) -> a -> b
$ [Char] -> IO Bool
doesFileExist [Char]
extensionFile
    if exists
      then do
        monitorFiles [monitorFileHashed extensionFile]
        pcs <- liftIO readExtensionFile
        monitorFiles $ map monitorFileHashed (projectConfigPathRoot <$> projectSkeletonImports pcs)
        pure pcs
      else do
        monitorFiles [monitorNonExistentFile extensionFile]
        return mempty
    where
      extensionFile :: [Char]
extensionFile = [Char] -> [Char]
distProjectFile [Char]
extensionName

      readExtensionFile :: IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
readExtensionFile =
        Verbosity
-> [Char]
-> [Char]
-> ProjectParseResult
     (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
reportParseResult Verbosity
verbosity [Char]
extensionDescription [Char]
extensionFile
          (ProjectParseResult
   (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
 -> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
-> IO
     (ProjectParseResult
        (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Char]
-> [Char]
-> HttpTransport
-> Verbosity
-> ProjectConfigToParse
-> IO
     (ProjectParseResult
        (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
parseProject [Char]
extensionFile [Char]
distDownloadSrcDirectory HttpTransport
httpTransport Verbosity
verbosity (ProjectConfigToParse
 -> IO
      (ProjectParseResult
         (CondTree ConfVar [ProjectConfigPath] ProjectConfig)))
-> (ByteString -> ProjectConfigToParse)
-> ByteString
-> IO
     (ProjectParseResult
        (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ProjectConfigToParse
ProjectConfigToParse
          (ByteString
 -> IO
      (ProjectParseResult
         (CondTree ConfVar [ProjectConfigPath] ProjectConfig)))
-> IO ByteString
-> IO
     (ProjectParseResult
        (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Char] -> IO ByteString
BS.readFile [Char]
extensionFile

-- | Render the 'ProjectConfig' format.
--
-- For the moment this is implemented in terms of a pretty printer for the
-- legacy configuration types, plus a conversion.
showProjectConfig :: ProjectConfig -> String
showProjectConfig :: ProjectConfig -> [Char]
showProjectConfig =
  LegacyProjectConfig -> [Char]
showLegacyProjectConfig (LegacyProjectConfig -> [Char])
-> (ProjectConfig -> LegacyProjectConfig)
-> ProjectConfig
-> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ProjectConfig -> LegacyProjectConfig
convertToLegacyProjectConfig

-- | Write a @cabal.project.local@ file in the given project root dir.
writeProjectLocalExtraConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalExtraConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalExtraConfig DistDirLayout{[Char] -> [Char]
distProjectFile :: DistDirLayout -> [Char] -> [Char]
distProjectFile :: [Char] -> [Char]
distProjectFile} =
  [Char] -> ProjectConfig -> IO ()
writeProjectConfigFile ([Char] -> [Char]
distProjectFile [Char]
"local")

-- | Write a @cabal.project.freeze@ file in the given project root dir.
writeProjectLocalFreezeConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalFreezeConfig :: DistDirLayout -> ProjectConfig -> IO ()
writeProjectLocalFreezeConfig DistDirLayout{[Char] -> [Char]
distProjectFile :: DistDirLayout -> [Char] -> [Char]
distProjectFile :: [Char] -> [Char]
distProjectFile} =
  [Char] -> ProjectConfig -> IO ()
writeProjectConfigFile ([Char] -> [Char]
distProjectFile [Char]
"freeze")

-- | Write in the @cabal.project@ format to the given file.
writeProjectConfigFile :: FilePath -> ProjectConfig -> IO ()
writeProjectConfigFile :: [Char] -> ProjectConfig -> IO ()
writeProjectConfigFile [Char]
file =
  [Char] -> [Char] -> IO ()
writeFile [Char]
file ([Char] -> IO ())
-> (ProjectConfig -> [Char]) -> ProjectConfig -> IO ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ProjectConfig -> [Char]
showProjectConfig

-- | Read the user's cabal-install config file.
readGlobalConfig :: Verbosity -> Flag FilePath -> Rebuild ProjectConfig
readGlobalConfig :: Verbosity -> Flag [Char] -> Rebuild ProjectConfig
readGlobalConfig Verbosity
verbosity Flag [Char]
configFileFlag = do
  config <- IO SavedConfig -> Rebuild SavedConfig
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (Verbosity -> Flag [Char] -> IO SavedConfig
loadConfig Verbosity
verbosity Flag [Char]
configFileFlag)
  configFile <- liftIO (getConfigFilePath configFileFlag)
  monitorFiles [monitorFileHashed configFile]
  return (convertLegacyGlobalConfig config)

reportProjectParseWarnings :: Verbosity -> FilePath -> [ProjectParseWarning] -> IO ()
reportProjectParseWarnings :: Verbosity -> [Char] -> [ProjectParseWarning] -> IO ()
reportProjectParseWarnings Verbosity
verbosity [Char]
projectFile [ProjectParseWarning]
warnings =
  Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([ProjectParseWarning] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [ProjectParseWarning]
warnings) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
    let msgs :: [[Char]]
msgs =
          [ [Char] -> PWarning -> [Char]
OldParser.showPWarning [Char]
pFilename PWarning
w
          | (ProjectConfigPath
p, PWarning
w) <- [ProjectParseWarning]
warnings
          , let pFilename :: [Char]
pFilename = ([Char], Maybe ProjectConfigPath) -> [Char]
forall a b. (a, b) -> a
fst (([Char], Maybe ProjectConfigPath) -> [Char])
-> ([Char], Maybe ProjectConfigPath) -> [Char]
forall a b. (a -> b) -> a -> b
$ ProjectConfigPath -> ([Char], Maybe ProjectConfigPath)
unconsProjectConfigPath ProjectConfigPath
p
          ]
     in Verbosity -> Doc -> IO ()
noticeDoc Verbosity
verbosity (Doc -> IO ()) -> Doc -> IO ()
forall a b. (a -> b) -> a -> b
$
          [Doc] -> Doc
vcat
            [ ([Char] -> Doc
text [Char]
"Warnings found while parsing the project file" Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
comma) Doc -> Doc -> Doc
<+> ([Char] -> Doc
text ([Char] -> [Char]
takeFileName [Char]
projectFile) Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
colon)
            , [Doc] -> Doc
cat [Int -> Doc -> Doc
nest Int
1 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ [Char] -> Doc
text [Char]
"-" Doc -> Doc -> Doc
<+> [Char] -> Doc
text [Char]
m | [Char]
m <- [[Char]] -> [[Char]]
forall a. Ord a => [a] -> [a]
ordNub [[Char]]
msgs]
            ]

reportParseResult :: Verbosity -> String -> FilePath -> OldParser.ProjectParseResult ProjectConfigSkeleton -> IO ProjectConfigSkeleton
reportParseResult :: Verbosity
-> [Char]
-> [Char]
-> ProjectParseResult
     (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
reportParseResult Verbosity
verbosity [Char]
_filetype [Char]
projectFile (OldParser.ProjectParseOk [ProjectParseWarning]
warnings CondTree ConfVar [ProjectConfigPath] ProjectConfig
x) = do
  Verbosity -> [Char] -> [ProjectParseWarning] -> IO ()
reportProjectParseWarnings Verbosity
verbosity [Char]
projectFile [ProjectParseWarning]
warnings
  CondTree ConfVar [ProjectConfigPath] ProjectConfig
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return CondTree ConfVar [ProjectConfigPath] ProjectConfig
x
reportParseResult Verbosity
verbosity [Char]
filetype [Char]
projectFile (OldParser.ProjectParseFailed (ProjectParseError Maybe [Char]
snippet Maybe ProjectConfigPath
rootOrImportee PError
err)) = do
  let (Maybe Int
line, [Char]
msg) = PError -> (Maybe Int, [Char])
OldParser.locatedErrorMsg PError
err
  let errLineNo :: [Char]
errLineNo = [Char] -> (Int -> [Char]) -> Maybe Int -> [Char]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [Char]
"" (\Int
n -> Char
':' Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
: Int -> [Char]
forall a. Show a => a -> [Char]
show Int
n) Maybe Int
line
  let ([Char]
sourceFile, Doc
provenance) =
        ([Char], Doc)
-> (ProjectConfigPath -> ([Char], Doc))
-> Maybe ProjectConfigPath
-> ([Char], Doc)
forall b a. b -> (a -> b) -> Maybe a -> b
maybe
          ([Char]
projectFile, Doc
empty)
          ( \ProjectConfigPath
p ->
              ( ([Char], Maybe ProjectConfigPath) -> [Char]
forall a b. (a, b) -> a
fst (([Char], Maybe ProjectConfigPath) -> [Char])
-> ([Char], Maybe ProjectConfigPath) -> [Char]
forall a b. (a -> b) -> a -> b
$ ProjectConfigPath -> ([Char], Maybe ProjectConfigPath)
unconsProjectConfigPath ProjectConfigPath
p
              , if ProjectConfigPath -> Bool
isTopLevelConfigPath ProjectConfigPath
p then Doc
empty else ProjectConfigPath -> Doc
docProjectConfigPath ProjectConfigPath
p
              )
          )
          Maybe ProjectConfigPath
rootOrImportee
  let doc :: Doc
doc = case Maybe [Char]
snippet of
        Maybe [Char]
Nothing -> [Doc] -> Doc
vcat ([Char] -> Doc
text ([Char] -> Doc) -> [[Char]] -> [Doc]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> [[Char]]
lines [Char]
msg)
        Just [Char]
s ->
          [Doc] -> Doc
vcat
            [ Doc
provenance
            , [Char] -> Doc
text [Char]
"Failed to parse" Doc -> Doc -> Doc
<+> Doc -> Doc
quotes ([Char] -> Doc
text [Char]
s) Doc -> Doc -> Doc
<+> ([Char] -> Doc
text [Char]
"with error" Doc -> Doc -> Doc
forall a. Semigroup a => a -> a -> a
<> Doc
colon)
            , Int -> Doc -> Doc
nest Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ [Doc] -> Doc
hsep ([Doc] -> Doc) -> [Doc] -> Doc
forall a b. (a -> b) -> a -> b
$ [Char] -> Doc
text ([Char] -> Doc) -> [[Char]] -> [Doc]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> [Char] -> [[Char]]
lines [Char]
msg
            ]
  Verbosity
-> CabalInstallException
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall a1 a.
(HasCallStack, Show a1, Typeable a1,
 Exception (VerboseException a1)) =>
Verbosity -> a1 -> IO a
dieWithException Verbosity
verbosity (CabalInstallException
 -> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig))
-> CabalInstallException
-> IO (CondTree ConfVar [ProjectConfigPath] ProjectConfig)
forall a b. (a -> b) -> a -> b
$ [Char] -> [Char] -> [Char] -> Doc -> CabalInstallException
ReportParseResult [Char]
filetype [Char]
sourceFile [Char]
errLineNo Doc
doc

---------------------------------------------
-- Finding packages in the project
--

-- | The location of a package as part of a project. Local file paths are
-- either absolute (if the user specified it as such) or they are relative
-- to the project root.
data ProjectPackageLocation
  = ProjectPackageLocalCabalFile FilePath
  | ProjectPackageLocalDirectory FilePath FilePath -- dir and .cabal file
  | ProjectPackageLocalTarball FilePath
  | ProjectPackageRemoteTarball URI
  | ProjectPackageRemoteRepo SourceRepoList
  | ProjectPackageNamed PackageVersionConstraint
  deriving (Int -> ProjectPackageLocation -> [Char] -> [Char]
[ProjectPackageLocation] -> [Char] -> [Char]
ProjectPackageLocation -> [Char]
(Int -> ProjectPackageLocation -> [Char] -> [Char])
-> (ProjectPackageLocation -> [Char])
-> ([ProjectPackageLocation] -> [Char] -> [Char])
-> Show ProjectPackageLocation
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> ProjectPackageLocation -> [Char] -> [Char]
showsPrec :: Int -> ProjectPackageLocation -> [Char] -> [Char]
$cshow :: ProjectPackageLocation -> [Char]
show :: ProjectPackageLocation -> [Char]
$cshowList :: [ProjectPackageLocation] -> [Char] -> [Char]
showList :: [ProjectPackageLocation] -> [Char] -> [Char]
Show)

-- | Exception thrown by 'findProjectPackages'.
data BadPackageLocations
  = BadPackageLocations (Set ProjectConfigProvenance) [BadPackageLocation]
  deriving (Int -> BadPackageLocations -> [Char] -> [Char]
[BadPackageLocations] -> [Char] -> [Char]
BadPackageLocations -> [Char]
(Int -> BadPackageLocations -> [Char] -> [Char])
-> (BadPackageLocations -> [Char])
-> ([BadPackageLocations] -> [Char] -> [Char])
-> Show BadPackageLocations
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> BadPackageLocations -> [Char] -> [Char]
showsPrec :: Int -> BadPackageLocations -> [Char] -> [Char]
$cshow :: BadPackageLocations -> [Char]
show :: BadPackageLocations -> [Char]
$cshowList :: [BadPackageLocations] -> [Char] -> [Char]
showList :: [BadPackageLocations] -> [Char] -> [Char]
Show)

instance Exception BadPackageLocations where
  displayException :: BadPackageLocations -> [Char]
displayException = BadPackageLocations -> [Char]
renderBadPackageLocations

-- TODO: [nice to have] custom exception subclass for Doc rendering, colour etc

data BadPackageLocation
  = BadPackageLocationFile BadPackageLocationMatch
  | BadLocGlobEmptyMatch String
  | BadLocGlobBadMatches String [BadPackageLocationMatch]
  | BadLocUnexpectedUriScheme String
  | BadLocUnrecognisedUri String
  | BadLocUnrecognised String
  deriving (Int -> BadPackageLocation -> [Char] -> [Char]
[BadPackageLocation] -> [Char] -> [Char]
BadPackageLocation -> [Char]
(Int -> BadPackageLocation -> [Char] -> [Char])
-> (BadPackageLocation -> [Char])
-> ([BadPackageLocation] -> [Char] -> [Char])
-> Show BadPackageLocation
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> BadPackageLocation -> [Char] -> [Char]
showsPrec :: Int -> BadPackageLocation -> [Char] -> [Char]
$cshow :: BadPackageLocation -> [Char]
show :: BadPackageLocation -> [Char]
$cshowList :: [BadPackageLocation] -> [Char] -> [Char]
showList :: [BadPackageLocation] -> [Char] -> [Char]
Show)

data BadPackageLocationMatch
  = BadLocUnexpectedFile String
  | BadLocNonexistantFile String
  | BadLocDirNoCabalFile String
  | BadLocDirManyCabalFiles String
  deriving (Int -> BadPackageLocationMatch -> [Char] -> [Char]
[BadPackageLocationMatch] -> [Char] -> [Char]
BadPackageLocationMatch -> [Char]
(Int -> BadPackageLocationMatch -> [Char] -> [Char])
-> (BadPackageLocationMatch -> [Char])
-> ([BadPackageLocationMatch] -> [Char] -> [Char])
-> Show BadPackageLocationMatch
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> BadPackageLocationMatch -> [Char] -> [Char]
showsPrec :: Int -> BadPackageLocationMatch -> [Char] -> [Char]
$cshow :: BadPackageLocationMatch -> [Char]
show :: BadPackageLocationMatch -> [Char]
$cshowList :: [BadPackageLocationMatch] -> [Char] -> [Char]
showList :: [BadPackageLocationMatch] -> [Char] -> [Char]
Show)

renderBadPackageLocations :: BadPackageLocations -> String
renderBadPackageLocations :: BadPackageLocations -> [Char]
renderBadPackageLocations (BadPackageLocations Set ProjectConfigProvenance
provenance [BadPackageLocation]
bpls)
  -- There is no provenance information,
  -- render standard bad package error information.
  | Set ProjectConfigProvenance -> Bool
forall a. Set a -> Bool
Set.null Set ProjectConfigProvenance
provenance = (BadPackageLocation -> [Char]) -> [Char]
renderErrors BadPackageLocation -> [Char]
renderBadPackageLocation
  -- The configuration is implicit, render bad package locations
  -- using possibly specialized error messages.
  | ProjectConfigProvenance -> Set ProjectConfigProvenance
forall a. a -> Set a
Set.singleton ProjectConfigProvenance
Implicit Set ProjectConfigProvenance -> Set ProjectConfigProvenance -> Bool
forall a. Eq a => a -> a -> Bool
== Set ProjectConfigProvenance
provenance =
      (BadPackageLocation -> [Char]) -> [Char]
renderErrors BadPackageLocation -> [Char]
renderImplicitBadPackageLocation
  -- The configuration contains both implicit and explicit provenance.
  -- This should not occur, and a message is output to assist debugging.
  | ProjectConfigProvenance
Implicit ProjectConfigProvenance -> Set ProjectConfigProvenance -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set ProjectConfigProvenance
provenance =
      [Char]
"Warning: both implicit and explicit configuration is present."
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
renderExplicit
  -- The configuration was read from one or more explicit path(s),
  -- list the locations and render the bad package error information.
  -- The intent is to supersede this with the relevant location information
  -- per package error.
  | Bool
otherwise = [Char]
renderExplicit
  where
    renderErrors :: (BadPackageLocation -> [Char]) -> [Char]
renderErrors BadPackageLocation -> [Char]
f = [[Char]] -> [Char]
unlines ((BadPackageLocation -> [Char]) -> [BadPackageLocation] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map BadPackageLocation -> [Char]
f [BadPackageLocation]
bpls)

    renderExplicit :: [Char]
renderExplicit =
      [Char]
"When using configuration from:\n"
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Doc -> [Char]
render (Int -> Doc -> Doc
nest Int
2 (Doc -> Doc)
-> ([ProjectConfigPath] -> Doc) -> [ProjectConfigPath] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [ProjectConfigPath] -> Doc
docProjectConfigFiles ([ProjectConfigPath] -> Doc) -> [ProjectConfigPath] -> Doc
forall a b. (a -> b) -> a -> b
$ (ProjectConfigProvenance -> Maybe ProjectConfigPath)
-> [ProjectConfigProvenance] -> [ProjectConfigPath]
forall a b. (a -> Maybe b) -> [a] -> [b]
mapMaybe ProjectConfigProvenance -> Maybe ProjectConfigPath
getExplicit (Set ProjectConfigProvenance -> [ProjectConfigProvenance]
forall a. Set a -> [a]
Set.toList Set ProjectConfigProvenance
provenance))
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"\nThe following errors occurred:\n"
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Doc -> [Char]
render (Int -> Doc -> Doc
nest Int
2 (Doc -> Doc) -> Doc -> Doc
forall a b. (a -> b) -> a -> b
$ [Doc] -> Doc
vcat (([Char] -> Doc
text [Char]
"-" Doc -> Doc -> Doc
<+>) (Doc -> Doc) -> ([Char] -> Doc) -> [Char] -> Doc
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> Doc
text ([Char] -> Doc) -> [[Char]] -> [Doc]
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> (BadPackageLocation -> [Char]) -> [BadPackageLocation] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map BadPackageLocation -> [Char]
renderBadPackageLocation [BadPackageLocation]
bpls))

    getExplicit :: ProjectConfigProvenance -> Maybe ProjectConfigPath
getExplicit (Explicit ProjectConfigPath
path) = ProjectConfigPath -> Maybe ProjectConfigPath
forall a. a -> Maybe a
Just ProjectConfigPath
path
    getExplicit ProjectConfigProvenance
Implicit = Maybe ProjectConfigPath
forall a. Maybe a
Nothing

-- TODO: [nice to have] keep track of the config file (and src loc) packages
-- were listed, to use in error messages

-- | Render bad package location error information for the implicit
-- @cabal.project@ configuration.
--
-- TODO: This is currently not fully realized, with only one of the implicit
-- cases handled. More cases should be added with informative help text
-- about the issues related specifically when having no project configuration
-- is present.
renderImplicitBadPackageLocation :: BadPackageLocation -> String
renderImplicitBadPackageLocation :: BadPackageLocation -> [Char]
renderImplicitBadPackageLocation BadPackageLocation
bpl = case BadPackageLocation
bpl of
  BadLocGlobEmptyMatch [Char]
pkglocstr ->
    [Char]
"No cabal.project file or cabal file matching the default glob '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' was found.\n"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"Please create a package description file <pkgname>.cabal "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"or a cabal.project file referencing the packages you "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"want to build."
  BadPackageLocation
_ -> BadPackageLocation -> [Char]
renderBadPackageLocation BadPackageLocation
bpl

renderBadPackageLocation :: BadPackageLocation -> String
renderBadPackageLocation :: BadPackageLocation -> [Char]
renderBadPackageLocation BadPackageLocation
bpl = case BadPackageLocation
bpl of
  BadPackageLocationFile BadPackageLocationMatch
badmatch ->
    BadPackageLocationMatch -> [Char]
renderBadPackageLocationMatch BadPackageLocationMatch
badmatch
  BadLocGlobEmptyMatch [Char]
pkglocstr ->
    [Char]
"The package location glob '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not match any files or directories."
  BadLocGlobBadMatches [Char]
pkglocstr [BadPackageLocationMatch]
failures ->
    [Char]
"The package location glob '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not match any "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"recognised forms of package. "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ (BadPackageLocationMatch -> [Char])
-> [BadPackageLocationMatch] -> [Char]
forall (t :: * -> *) a b. Foldable t => (a -> [b]) -> t a -> [b]
concatMap ((Char
' ' Char -> [Char] -> [Char]
forall a. a -> [a] -> [a]
:) ([Char] -> [Char])
-> (BadPackageLocationMatch -> [Char])
-> BadPackageLocationMatch
-> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. BadPackageLocationMatch -> [Char]
renderBadPackageLocationMatch) [BadPackageLocationMatch]
failures
  BadLocUnexpectedUriScheme [Char]
pkglocstr ->
    [Char]
"The package location URI '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not use a "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"supported URI scheme. The supported URI schemes are http, https and "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"file."
  BadLocUnrecognisedUri [Char]
pkglocstr ->
    [Char]
"The package location URI '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not appear to "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"be a valid absolute URI."
  BadLocUnrecognised [Char]
pkglocstr ->
    [Char]
"The package location syntax '" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' is not recognised."

renderBadPackageLocationMatch :: BadPackageLocationMatch -> String
renderBadPackageLocationMatch :: BadPackageLocationMatch -> [Char]
renderBadPackageLocationMatch BadPackageLocationMatch
bplm = case BadPackageLocationMatch
bplm of
  BadLocUnexpectedFile [Char]
pkglocstr ->
    [Char]
"The package location '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' is not recognised. The "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"supported file targets are .cabal files, .tar.gz tarballs or package "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"directories (i.e. directories containing a .cabal file)."
  BadLocNonexistantFile [Char]
pkglocstr ->
    [Char]
"The package location '" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not exist."
  BadLocDirNoCabalFile [Char]
pkglocstr ->
    [Char]
"The package directory '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' does not contain any "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".cabal file."
  BadLocDirManyCabalFiles [Char]
pkglocstr ->
    [Char]
"The package directory '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkglocstr
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"' contains multiple "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".cabal files (which is not currently supported)."

-- | Determines the location of all packages mentioned in the project configuration.
--
-- Throws 'BadPackageLocations'.
findProjectPackages
  :: DistDirLayout
  -> ProjectConfig
  -> Rebuild [ProjectPackageLocation]
findProjectPackages :: DistDirLayout -> ProjectConfig -> Rebuild [ProjectPackageLocation]
findProjectPackages
  DistDirLayout{[Char]
distProjectRootDirectory :: [Char]
distProjectRootDirectory :: DistDirLayout -> [Char]
distProjectRootDirectory}
  ProjectConfig{[[Char]]
[PackageVersionConstraint]
[SourceRepoList]
Set ProjectConfigProvenance
MapMappend PackageName PackageConfig
PackageConfig
ProjectConfigBuildOnly
ProjectConfigShared
projectConfigLocalPackages :: ProjectConfig -> PackageConfig
projectConfigSpecificPackage :: ProjectConfig -> MapMappend PackageName PackageConfig
projectConfigShared :: ProjectConfig -> ProjectConfigShared
projectConfigBuildOnly :: ProjectConfig -> ProjectConfigBuildOnly
projectPackages :: ProjectConfig -> [[Char]]
projectConfigProvenance :: ProjectConfig -> Set ProjectConfigProvenance
projectPackages :: [[Char]]
projectPackagesOptional :: [[Char]]
projectPackagesRepo :: [SourceRepoList]
projectPackagesNamed :: [PackageVersionConstraint]
projectConfigBuildOnly :: ProjectConfigBuildOnly
projectConfigShared :: ProjectConfigShared
projectConfigProvenance :: Set ProjectConfigProvenance
projectConfigAllPackages :: PackageConfig
projectConfigLocalPackages :: PackageConfig
projectConfigSpecificPackage :: MapMappend PackageName PackageConfig
projectConfigAllPackages :: ProjectConfig -> PackageConfig
projectPackagesNamed :: ProjectConfig -> [PackageVersionConstraint]
projectPackagesOptional :: ProjectConfig -> [[Char]]
projectPackagesRepo :: ProjectConfig -> [SourceRepoList]
..} = do
    requiredPkgs <- Bool -> [[Char]] -> Rebuild [ProjectPackageLocation]
findPackageLocations Bool
True [[Char]]
projectPackages
    optionalPkgs <- findPackageLocations False projectPackagesOptional
    let repoPkgs = (SourceRepoList -> ProjectPackageLocation)
-> [SourceRepoList] -> [ProjectPackageLocation]
forall a b. (a -> b) -> [a] -> [b]
map SourceRepoList -> ProjectPackageLocation
ProjectPackageRemoteRepo [SourceRepoList]
projectPackagesRepo
        namedPkgs = (PackageVersionConstraint -> ProjectPackageLocation)
-> [PackageVersionConstraint] -> [ProjectPackageLocation]
forall a b. (a -> b) -> [a] -> [b]
map PackageVersionConstraint -> ProjectPackageLocation
ProjectPackageNamed [PackageVersionConstraint]
projectPackagesNamed

    return (concat [requiredPkgs, optionalPkgs, repoPkgs, namedPkgs])
    where
      findPackageLocations :: Bool -> [String] -> Rebuild [ProjectPackageLocation]
      findPackageLocations :: Bool -> [[Char]] -> Rebuild [ProjectPackageLocation]
findPackageLocations Bool
required [[Char]]
pkglocstr = do
        (problems, pkglocs) <-
          [Either BadPackageLocation [ProjectPackageLocation]]
-> ([BadPackageLocation], [[ProjectPackageLocation]])
forall a b. [Either a b] -> ([a], [b])
partitionEithers ([Either BadPackageLocation [ProjectPackageLocation]]
 -> ([BadPackageLocation], [[ProjectPackageLocation]]))
-> Rebuild [Either BadPackageLocation [ProjectPackageLocation]]
-> Rebuild ([BadPackageLocation], [[ProjectPackageLocation]])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([Char]
 -> Rebuild (Either BadPackageLocation [ProjectPackageLocation]))
-> [[Char]]
-> Rebuild [Either BadPackageLocation [ProjectPackageLocation]]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse (Bool
-> [Char]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
findPackageLocation Bool
required) [[Char]]
pkglocstr
        unless (null problems) $
          liftIO $
            throwIO $
              BadPackageLocations projectConfigProvenance problems
        return (concat pkglocs)

      findPackageLocation
        :: Bool
        -> String
        -> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
      findPackageLocation :: Bool
-> [Char]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
findPackageLocation _required :: Bool
_required@Bool
True [Char]
pkglocstr =
        -- strategy: try first as a file:// or http(s):// URL.
        -- then as a file glob (usually encompassing single file)
        -- finally as a single file, for files that fail to parse as globs
        [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsUriPackage [Char]
pkglocstr
          Rebuild
  (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall (m :: * -> *) a.
Monad m =>
m (Maybe a) -> m (Maybe a) -> m (Maybe a)
`mplusMaybeT` [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsFileGlobPackage [Char]
pkglocstr
          Rebuild
  (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall (m :: * -> *) a.
Monad m =>
m (Maybe a) -> m (Maybe a) -> m (Maybe a)
`mplusMaybeT` [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsSingleFilePackage [Char]
pkglocstr
          Rebuild
  (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> (Maybe (Either BadPackageLocation [ProjectPackageLocation])
    -> Rebuild (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a b. Rebuild a -> (a -> Rebuild b) -> Rebuild b
forall (m :: * -> *) a b. Monad m => m a -> (a -> m b) -> m b
>>= Rebuild (Either BadPackageLocation [ProjectPackageLocation])
-> (Either BadPackageLocation [ProjectPackageLocation]
    -> Rebuild (Either BadPackageLocation [ProjectPackageLocation]))
-> Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall b a. b -> (a -> b) -> Maybe a -> b
maybe (Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocation
BadLocUnrecognised [Char]
pkglocstr))) Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return
      findPackageLocation _required :: Bool
_required@Bool
False [Char]
pkglocstr = do
        -- just globs for optional case
        res <- [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsFileGlobPackage [Char]
pkglocstr
        case res of
          Maybe (Either BadPackageLocation [ProjectPackageLocation])
Nothing -> Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocation
BadLocUnrecognised [Char]
pkglocstr))
          Just (Left BadPackageLocation
_) -> Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return ([ProjectPackageLocation]
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. b -> Either a b
Right []) -- it's optional
          Just (Right [ProjectPackageLocation]
pkglocs) -> Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return ([ProjectPackageLocation]
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. b -> Either a b
Right [ProjectPackageLocation]
pkglocs)

      checkIsUriPackage
        , checkIsFileGlobPackage
        , checkIsSingleFilePackage
          :: String
          -> Rebuild (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
      checkIsUriPackage :: [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsUriPackage [Char]
pkglocstr =
        case [Char] -> Maybe URI
parseAbsoluteURI [Char]
pkglocstr of
          Just
            uri :: URI
uri@URI
              { uriScheme :: URI -> [Char]
uriScheme = [Char]
scheme
              , uriAuthority :: URI -> Maybe URIAuth
uriAuthority = Just URIAuth{uriRegName :: URIAuth -> [Char]
uriRegName = [Char]
host}
              , uriPath :: URI -> [Char]
uriPath = [Char]
path
              , uriQuery :: URI -> [Char]
uriQuery = [Char]
query
              , uriFragment :: URI -> [Char]
uriFragment = [Char]
frag
              }
              | Bool
recognisedScheme Bool -> Bool -> Bool
&& Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
host) ->
                  Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either BadPackageLocation [ProjectPackageLocation]
-> Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Maybe a
Just ([ProjectPackageLocation]
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. b -> Either a b
Right [URI -> ProjectPackageLocation
ProjectPackageRemoteTarball URI
uri]))
              | [Char]
scheme [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"file:" Bool -> Bool -> Bool
&& [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
host Bool -> Bool -> Bool
&& [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
query Bool -> Bool -> Bool
&& [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
frag ->
                  [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsSingleFilePackage [Char]
path
              | Bool -> Bool
not Bool
recognisedScheme Bool -> Bool -> Bool
&& Bool -> Bool
not ([Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
host) ->
                  Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either BadPackageLocation [ProjectPackageLocation]
-> Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Maybe a
Just (BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocation
BadLocUnexpectedUriScheme [Char]
pkglocstr)))
              | Bool
recognisedScheme Bool -> Bool -> Bool
&& [Char] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [Char]
host ->
                  Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either BadPackageLocation [ProjectPackageLocation]
-> Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Maybe a
Just (BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocation
BadLocUnrecognisedUri [Char]
pkglocstr)))
              where
                recognisedScheme :: Bool
recognisedScheme =
                  [Char]
scheme [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"http:"
                    Bool -> Bool -> Bool
|| [Char]
scheme [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"https:"
                    Bool -> Bool -> Bool
|| [Char]
scheme [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
"file:"
          Maybe URI
_ -> Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. Maybe a
Nothing

      checkIsFileGlobPackage :: [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsFileGlobPackage [Char]
pkglocstr =
        case [Char] -> Maybe RootedGlob
forall a. Parsec a => [Char] -> Maybe a
simpleParsec [Char]
pkglocstr of
          Maybe RootedGlob
Nothing -> Maybe (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. Maybe a
Nothing
          Just RootedGlob
glob -> (Either BadPackageLocation [ProjectPackageLocation]
 -> Maybe (Either BadPackageLocation [ProjectPackageLocation]))
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall (m :: * -> *) a1 r. Monad m => (a1 -> r) -> m a1 -> m r
liftM Either BadPackageLocation [ProjectPackageLocation]
-> Maybe (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Maybe a
Just (Rebuild (Either BadPackageLocation [ProjectPackageLocation])
 -> Rebuild
      (Maybe (Either BadPackageLocation [ProjectPackageLocation])))
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
forall a b. (a -> b) -> a -> b
$ do
            matches <- RootedGlob -> Rebuild [[Char]]
matchFileGlob RootedGlob
glob
            case matches of
              []
                | Maybe [Char] -> Bool
forall a. Maybe a -> Bool
isJust (RootedGlob -> Maybe [Char]
isTrivialRootedGlob RootedGlob
glob) ->
                    Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return
                      ( BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left
                          ( BadPackageLocationMatch -> BadPackageLocation
BadPackageLocationFile
                              ([Char] -> BadPackageLocationMatch
BadLocNonexistantFile [Char]
pkglocstr)
                          )
                      )
              [] -> Either BadPackageLocation [ProjectPackageLocation]
-> Rebuild (Either BadPackageLocation [ProjectPackageLocation])
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocation
BadLocGlobEmptyMatch [Char]
pkglocstr))
              [[Char]]
_ -> do
                (failures, pkglocs) <-
                  [Either BadPackageLocationMatch ProjectPackageLocation]
-> ([BadPackageLocationMatch], [ProjectPackageLocation])
forall a b. [Either a b] -> ([a], [b])
partitionEithers
                    ([Either BadPackageLocationMatch ProjectPackageLocation]
 -> ([BadPackageLocationMatch], [ProjectPackageLocation]))
-> Rebuild [Either BadPackageLocationMatch ProjectPackageLocation]
-> Rebuild ([BadPackageLocationMatch], [ProjectPackageLocation])
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ([Char]
 -> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation))
-> [[Char]]
-> Rebuild [Either BadPackageLocationMatch ProjectPackageLocation]
forall (t :: * -> *) (f :: * -> *) a b.
(Traversable t, Applicative f) =>
(a -> f b) -> t a -> f (t b)
forall (f :: * -> *) a b.
Applicative f =>
(a -> f b) -> [a] -> f [b]
traverse [Char]
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
checkFilePackageMatch [[Char]]
matches
                return $! case (failures, pkglocs) of
                  ([BadPackageLocationMatch
failure], [])
                    | Maybe [Char] -> Bool
forall a. Maybe a -> Bool
isJust (RootedGlob -> Maybe [Char]
isTrivialRootedGlob RootedGlob
glob) ->
                        BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left (BadPackageLocationMatch -> BadPackageLocation
BadPackageLocationFile BadPackageLocationMatch
failure)
                  ([BadPackageLocationMatch]
_, []) -> BadPackageLocation
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. a -> Either a b
Left ([Char] -> [BadPackageLocationMatch] -> BadPackageLocation
BadLocGlobBadMatches [Char]
pkglocstr [BadPackageLocationMatch]
failures)
                  ([BadPackageLocationMatch], [ProjectPackageLocation])
_ -> [ProjectPackageLocation]
-> Either BadPackageLocation [ProjectPackageLocation]
forall a b. b -> Either a b
Right [ProjectPackageLocation]
pkglocs

      checkIsSingleFilePackage :: [Char]
-> Rebuild
     (Maybe (Either BadPackageLocation [ProjectPackageLocation]))
checkIsSingleFilePackage [Char]
pkglocstr = do
        let filename :: [Char]
filename = [Char]
distProjectRootDirectory [Char] -> [Char] -> [Char]
</> [Char]
pkglocstr
        isFile <- IO Bool -> Rebuild Bool
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> Rebuild Bool) -> IO Bool -> Rebuild Bool
forall a b. (a -> b) -> a -> b
$ [Char] -> IO Bool
doesFileExist [Char]
filename
        isDir <- liftIO $ doesDirectoryExist filename
        if isFile || isDir
          then
            checkFilePackageMatch pkglocstr
              >>= either
                (return . Just . Left . BadPackageLocationFile)
                (return . Just . Right . (\ProjectPackageLocation
x -> [ProjectPackageLocation
x]))
          else return Nothing

      checkFilePackageMatch
        :: String
        -> Rebuild
            ( Either
                BadPackageLocationMatch
                ProjectPackageLocation
            )
      checkFilePackageMatch :: [Char]
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
checkFilePackageMatch [Char]
pkglocstr = do
        -- The pkglocstr may be absolute or may be relative to the project root.
        -- Either way, </> does the right thing here. We return relative paths if
        -- they were relative in the first place.
        let abspath :: [Char]
abspath = [Char]
distProjectRootDirectory [Char] -> [Char] -> [Char]
</> [Char]
pkglocstr
        isFile <- IO Bool -> Rebuild Bool
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> Rebuild Bool) -> IO Bool -> Rebuild Bool
forall a b. (a -> b) -> a -> b
$ [Char] -> IO Bool
doesFileExist [Char]
abspath
        isDir <- liftIO $ doesDirectoryExist abspath
        parentDirExists <- case takeDirectory abspath of
          [] -> Bool -> Rebuild Bool
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return Bool
False
          [Char]
dir -> IO Bool -> Rebuild Bool
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO Bool -> Rebuild Bool) -> IO Bool -> Rebuild Bool
forall a b. (a -> b) -> a -> b
$ [Char] -> IO Bool
doesDirectoryExist [Char]
dir
        case () of
          ()
_
            | Bool
isDir ->
                do
                  matches <- RootedGlob -> Rebuild [[Char]]
matchFileGlob ([Char] -> RootedGlob
globStarDotCabal [Char]
pkglocstr)
                  case matches of
                    [[Char]
cabalFile] ->
                      Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return
                        ( ProjectPackageLocation
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. b -> Either a b
Right
                            ( [Char] -> [Char] -> ProjectPackageLocation
ProjectPackageLocalDirectory
                                [Char]
pkglocstr
                                [Char]
cabalFile
                            )
                        )
                    [] -> Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocationMatch
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocationMatch
BadLocDirNoCabalFile [Char]
pkglocstr))
                    [[Char]]
_ -> Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocationMatch
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocationMatch
BadLocDirManyCabalFiles [Char]
pkglocstr))
            | [Char] -> Bool
extensionIsTarGz [Char]
pkglocstr ->
                Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (ProjectPackageLocation
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. b -> Either a b
Right ([Char] -> ProjectPackageLocation
ProjectPackageLocalTarball [Char]
pkglocstr))
            | [Char] -> [Char]
takeExtension [Char]
pkglocstr [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".cabal" ->
                Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (ProjectPackageLocation
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. b -> Either a b
Right ([Char] -> ProjectPackageLocation
ProjectPackageLocalCabalFile [Char]
pkglocstr))
            | Bool
isFile ->
                Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocationMatch
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocationMatch
BadLocUnexpectedFile [Char]
pkglocstr))
            | Bool
parentDirExists ->
                Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocationMatch
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocationMatch
BadLocNonexistantFile [Char]
pkglocstr))
            | Bool
otherwise ->
                Either BadPackageLocationMatch ProjectPackageLocation
-> Rebuild (Either BadPackageLocationMatch ProjectPackageLocation)
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (BadPackageLocationMatch
-> Either BadPackageLocationMatch ProjectPackageLocation
forall a b. a -> Either a b
Left ([Char] -> BadPackageLocationMatch
BadLocUnexpectedFile [Char]
pkglocstr))

      extensionIsTarGz :: [Char] -> Bool
extensionIsTarGz [Char]
f =
        [Char] -> [Char]
takeExtension [Char]
f [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".gz"
          Bool -> Bool -> Bool
&& [Char] -> [Char]
takeExtension ([Char] -> [Char]
dropExtension [Char]
f) [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".tar"

-- | A glob to find all the cabal files in a directory.
--
-- For a directory @some/dir/@, this is a glob of the form @some/dir/\*.cabal@.
-- The directory part can be either absolute or relative.
globStarDotCabal :: FilePath -> RootedGlob
globStarDotCabal :: [Char] -> RootedGlob
globStarDotCabal [Char]
dir =
  FilePathRoot -> Glob -> RootedGlob
RootedGlob
    (if [Char] -> Bool
isAbsolute [Char]
dir then [Char] -> FilePathRoot
FilePathRoot [Char]
root else FilePathRoot
FilePathRelative)
    ( ([Char] -> Glob -> Glob) -> Glob -> [[Char]] -> Glob
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr
        (\[Char]
d -> GlobPieces -> Glob -> Glob
GlobDir [[Char] -> GlobPiece
Literal [Char]
d])
        (GlobPieces -> Glob
GlobFile [GlobPiece
WildCard, [Char] -> GlobPiece
Literal [Char]
".cabal"])
        [[Char]]
dirComponents
    )
  where
    ([Char]
root, [[Char]]
dirComponents) = ([Char] -> [[Char]]) -> ([Char], [Char]) -> ([Char], [[Char]])
forall a b. (a -> b) -> ([Char], a) -> ([Char], b)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [Char] -> [[Char]]
splitDirectories ([Char] -> ([Char], [Char])
splitDrive [Char]
dir)

-- TODO: [code cleanup] use sufficiently recent transformers package
mplusMaybeT :: Monad m => m (Maybe a) -> m (Maybe a) -> m (Maybe a)
mplusMaybeT :: forall (m :: * -> *) a.
Monad m =>
m (Maybe a) -> m (Maybe a) -> m (Maybe a)
mplusMaybeT m (Maybe a)
ma m (Maybe a)
mb = do
  mx <- m (Maybe a)
ma
  case mx of
    Maybe a
Nothing -> m (Maybe a)
mb
    Just a
x -> Maybe a -> m (Maybe a)
forall a. a -> m a
forall (m :: * -> *) a. Monad m => a -> m a
return (a -> Maybe a
forall a. a -> Maybe a
Just a
x)

-------------------------------------------------
-- Fetching and reading packages in the project
--

-- | Read the @.cabal@ files for a set of packages. For remote tarballs and
-- VCS source repos this also fetches them if needed.
--
-- Note here is where we convert from project-root relative paths to absolute
-- paths.
fetchAndReadSourcePackages
  :: Verbosity
  -> DistDirLayout
  -> Maybe Compiler
  -> ProjectConfigShared
  -> ProjectConfigBuildOnly
  -> [ProjectPackageLocation]
  -> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
fetchAndReadSourcePackages :: Verbosity
-> DistDirLayout
-> Maybe Compiler
-> ProjectConfigShared
-> ProjectConfigBuildOnly
-> [ProjectPackageLocation]
-> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
fetchAndReadSourcePackages
  Verbosity
verbosity
  DistDirLayout
distDirLayout
  Maybe Compiler
compiler
  ProjectConfigShared
projectConfigShared
  ProjectConfigBuildOnly
projectConfigBuildOnly
  [ProjectPackageLocation]
pkgLocations = do
    pkgsLocalDirectory <-
      [Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))]
-> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a. Applicative f => [f a] -> f [a]
sequenceA
        [ Verbosity
-> [Char]
-> [Char]
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readSourcePackageLocalDirectory Verbosity
verbosity [Char]
dir [Char]
cabalFile
        | ProjectPackageLocation
location <- [ProjectPackageLocation]
pkgLocations
        , ([Char]
dir, [Char]
cabalFile) <- ProjectPackageLocation -> [([Char], [Char])]
projectPackageLocal ProjectPackageLocation
location
        ]

    pkgsLocalTarball <-
      sequenceA
        [ readSourcePackageLocalTarball verbosity path
        | ProjectPackageLocalTarball path <- pkgLocations
        ]

    pkgsRemoteTarball <- do
      getTransport <-
        delayInitSharedResource $
          configureTransport
            verbosity
            progPathExtra
            preferredHttpTransport
      sequenceA
        [ fetchAndReadSourcePackageRemoteTarball
          verbosity
          distDirLayout
          getTransport
          uri
        | ProjectPackageRemoteTarball uri <- pkgLocations
        ]

    pkgsRemoteRepo <-
      syncAndReadSourcePackagesRemoteRepos
        verbosity
        distDirLayout
        compiler
        projectConfigShared
        projectConfigBuildOnly
        (fromFlag (projectConfigOfflineMode projectConfigBuildOnly))
        [repo | ProjectPackageRemoteRepo repo <- pkgLocations]

    let pkgsNamed =
          [ PackageName -> [PackageProperty] -> PackageSpecifier pkg
forall pkg.
PackageName -> [PackageProperty] -> PackageSpecifier pkg
NamedPackage PackageName
pkgname [VersionRange -> PackageProperty
PackagePropertyVersion VersionRange
verrange]
          | ProjectPackageNamed (PackageVersionConstraint PackageName
pkgname VersionRange
verrange) <- [ProjectPackageLocation]
pkgLocations
          ]

    return $
      concat
        [ pkgsLocalDirectory
        , pkgsLocalTarball
        , pkgsRemoteTarball
        , pkgsRemoteRepo
        , pkgsNamed
        ]
    where
      projectPackageLocal :: ProjectPackageLocation -> [([Char], [Char])]
projectPackageLocal (ProjectPackageLocalDirectory [Char]
dir [Char]
file) = [([Char]
dir, [Char]
file)]
      projectPackageLocal (ProjectPackageLocalCabalFile [Char]
file) = [([Char]
dir, [Char]
file)]
        where
          dir :: [Char]
dir = [Char] -> [Char]
takeDirectory [Char]
file
      projectPackageLocal ProjectPackageLocation
_ = []

      progPathExtra :: [[Char]]
progPathExtra = NubList [Char] -> [[Char]]
forall a. NubList a -> [a]
fromNubList (ProjectConfigShared -> NubList [Char]
projectConfigProgPathExtra ProjectConfigShared
projectConfigShared)
      preferredHttpTransport :: Maybe [Char]
preferredHttpTransport =
        Flag [Char] -> Maybe [Char]
forall a. Flag a -> Maybe a
flagToMaybe (ProjectConfigBuildOnly -> Flag [Char]
projectConfigHttpTransport ProjectConfigBuildOnly
projectConfigBuildOnly)

-- | A helper for 'fetchAndReadSourcePackages' to handle the case of
-- 'ProjectPackageLocalDirectory' and 'ProjectPackageLocalCabalFile'.
-- We simply read the @.cabal@ file.
readSourcePackageLocalDirectory
  :: Verbosity
  -> FilePath
  -- ^ The package directory
  -> FilePath
  -- ^ The package @.cabal@ file
  -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readSourcePackageLocalDirectory :: Verbosity
-> [Char]
-> [Char]
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readSourcePackageLocalDirectory Verbosity
verbosity [Char]
dir [Char]
cabalFile = do
  [MonitorFilePath] -> Rebuild ()
monitorFiles [[Char] -> MonitorFilePath
monitorFileHashed [Char]
cabalFile]
  root <- Rebuild [Char]
askRoot
  let location = [Char] -> PackageLocation local
forall local. [Char] -> PackageLocation local
LocalUnpackedPackage ([Char]
root [Char] -> [Char] -> [Char]
</> [Char]
dir)
  liftIO $
    fmap (mkSpecificSourcePackage location)
      . readSourcePackageCabalFile verbosity cabalFile
      =<< BS.readFile (root </> cabalFile)

-- | A helper for 'fetchAndReadSourcePackages' to handle the case of
-- 'ProjectPackageLocalTarball'. We scan through the @.tar.gz@ file to find
-- the @.cabal@ file and read that.
readSourcePackageLocalTarball
  :: Verbosity
  -> FilePath
  -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readSourcePackageLocalTarball :: Verbosity
-> [Char]
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readSourcePackageLocalTarball Verbosity
verbosity [Char]
tarballFile = do
  [MonitorFilePath] -> Rebuild ()
monitorFiles [[Char] -> MonitorFilePath
monitorFile [Char]
tarballFile]
  root <- Rebuild [Char]
askRoot
  let location = [Char] -> PackageLocation local
forall local. [Char] -> PackageLocation local
LocalTarballPackage ([Char]
root [Char] -> [Char] -> [Char]
</> [Char]
tarballFile)
  liftIO $
    fmap (mkSpecificSourcePackage location)
      . uncurry (readSourcePackageCabalFile verbosity)
      =<< extractTarballPackageCabalFile (root </> tarballFile)

-- | A helper for 'fetchAndReadSourcePackages' to handle the case of
-- 'ProjectPackageRemoteTarball'. We download the tarball to the dist src dir
-- and after that handle it like the local tarball case.
fetchAndReadSourcePackageRemoteTarball
  :: Verbosity
  -> DistDirLayout
  -> Rebuild HttpTransport
  -> URI
  -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
fetchAndReadSourcePackageRemoteTarball :: Verbosity
-> DistDirLayout
-> Rebuild HttpTransport
-> URI
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
fetchAndReadSourcePackageRemoteTarball
  Verbosity
verbosity
  DistDirLayout
    { [Char]
distDownloadSrcDirectory :: DistDirLayout -> [Char]
distDownloadSrcDirectory :: [Char]
distDownloadSrcDirectory
    }
  Rebuild HttpTransport
getTransport
  URI
tarballUri =
    -- The tarball download is expensive so we use another layer of file
    -- monitor to avoid it whenever possible.
    Verbosity
-> FileMonitor
     URI (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> URI
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b.
(Binary a, Structured a, Binary b, Structured b) =>
Verbosity -> FileMonitor a b -> a -> Rebuild b -> Rebuild b
rerunIfChanged Verbosity
verbosity FileMonitor URI (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
monitor URI
tarballUri (Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
 -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc)))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. (a -> b) -> a -> b
$ do
      -- Download
      transport <- Rebuild HttpTransport
getTransport
      liftIO $ do
        transportCheckHttps verbosity transport tarballUri
        notice verbosity ("Downloading " ++ show tarballUri)
        createDirectoryIfMissingVerbose
          verbosity
          True
          distDownloadSrcDirectory
        _ <- downloadURI transport verbosity tarballUri tarballFile
        return ()

      -- Read
      monitorFiles [monitorFile tarballFile]
      let location = URI -> [Char] -> PackageLocation [Char]
forall local. URI -> local -> PackageLocation local
RemoteTarballPackage URI
tarballUri [Char]
tarballFile
      liftIO $
        fmap (mkSpecificSourcePackage location)
          . uncurry (readSourcePackageCabalFile verbosity)
          =<< extractTarballPackageCabalFile tarballFile
    where
      tarballStem :: FilePath
      tarballStem :: [Char]
tarballStem =
        [Char]
distDownloadSrcDirectory
          [Char] -> [Char] -> [Char]
</> URI -> [Char]
localFileNameForRemoteTarball URI
tarballUri
      tarballFile :: FilePath
      tarballFile :: [Char]
tarballFile = [Char]
tarballStem [Char] -> [Char] -> [Char]
<.> [Char]
"tar.gz"

      monitor :: FileMonitor URI (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
      monitor :: FileMonitor URI (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
monitor = [Char]
-> FileMonitor
     URI (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. Eq a => [Char] -> FileMonitor a b
newFileMonitor ([Char]
tarballStem [Char] -> [Char] -> [Char]
<.> [Char]
"cache")

-- | A helper for 'fetchAndReadSourcePackages' to handle all the cases of
-- 'ProjectPackageRemoteRepo'.
syncAndReadSourcePackagesRemoteRepos
  :: Verbosity
  -> DistDirLayout
  -> Maybe Compiler
  -> ProjectConfigShared
  -> ProjectConfigBuildOnly
  -> Bool
  -> [SourceRepoList]
  -> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
syncAndReadSourcePackagesRemoteRepos :: Verbosity
-> DistDirLayout
-> Maybe Compiler
-> ProjectConfigShared
-> ProjectConfigBuildOnly
-> Bool
-> [SourceRepoList]
-> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
syncAndReadSourcePackagesRemoteRepos
  Verbosity
verbosity
  DistDirLayout{[Char]
distDownloadSrcDirectory :: DistDirLayout -> [Char]
distDownloadSrcDirectory :: [Char]
distDownloadSrcDirectory}
  Maybe Compiler
compiler
  ProjectConfigShared
    { NubList [Char]
projectConfigProgPathExtra :: ProjectConfigShared -> NubList [Char]
projectConfigProgPathExtra :: NubList [Char]
projectConfigProgPathExtra
    }
  ProjectConfigBuildOnly
    { Flag Bool
projectConfigUseSemaphore :: ProjectConfigBuildOnly -> Flag Bool
projectConfigUseSemaphore :: Flag Bool
projectConfigUseSemaphore
    , Flag (Maybe Int)
projectConfigNumJobs :: ProjectConfigBuildOnly -> Flag (Maybe Int)
projectConfigNumJobs :: Flag (Maybe Int)
projectConfigNumJobs
    }
  Bool
offlineMode
  [SourceRepoList]
repos = do
    repos' <-
      ([(SourceRepoList, SourceRepoProblem)]
 -> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)])
-> ([(SourceRepoList, [Char], RepoType, VCS Program)]
    -> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)])
-> Either
     [(SourceRepoList, SourceRepoProblem)]
     [(SourceRepoList, [Char], RepoType, VCS Program)]
-> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)]
forall a c b. (a -> c) -> (b -> c) -> Either a b -> c
either [(SourceRepoList, SourceRepoProblem)]
-> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)]
forall a. [(SourceRepoList, SourceRepoProblem)] -> Rebuild a
reportSourceRepoProblems [(SourceRepoList, [Char], RepoType, VCS Program)]
-> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)]
forall a. a -> Rebuild a
forall (m :: * -> *) a. Monad m => a -> m a
return (Either
   [(SourceRepoList, SourceRepoProblem)]
   [(SourceRepoList, [Char], RepoType, VCS Program)]
 -> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)])
-> Either
     [(SourceRepoList, SourceRepoProblem)]
     [(SourceRepoList, [Char], RepoType, VCS Program)]
-> Rebuild [(SourceRepoList, [Char], RepoType, VCS Program)]
forall a b. (a -> b) -> a -> b
$
        [SourceRepoList]
-> Either
     [(SourceRepoList, SourceRepoProblem)]
     [(SourceRepoList, [Char], RepoType, VCS Program)]
forall (f :: * -> *).
[SourceRepositoryPackage f]
-> Either
     [(SourceRepositoryPackage f, SourceRepoProblem)]
     [(SourceRepositoryPackage f, [Char], RepoType, VCS Program)]
validateSourceRepos [SourceRepoList]
repos

    -- All 'SourceRepo's grouped by referring to the "same" remote repo
    -- instance. So same location but can differ in commit/tag/branch/subdir.
    let reposByLocation
          :: Map
              (RepoType, String)
              [(SourceRepoList, RepoType)]
        reposByLocation =
          ([(SourceRepoList, RepoType)]
 -> [(SourceRepoList, RepoType)] -> [(SourceRepoList, RepoType)])
-> [((RepoType, [Char]), [(SourceRepoList, RepoType)])]
-> Map (RepoType, [Char]) [(SourceRepoList, RepoType)]
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith
            [(SourceRepoList, RepoType)]
-> [(SourceRepoList, RepoType)] -> [(SourceRepoList, RepoType)]
forall a. [a] -> [a] -> [a]
(++)
            [ ((RepoType
rtype, [Char]
rloc), [(SourceRepoList
repo, VCS Program -> RepoType
forall program. VCS program -> RepoType
vcsRepoType VCS Program
vcs)])
            | (SourceRepoList
repo, [Char]
rloc, RepoType
rtype, VCS Program
vcs) <- [(SourceRepoList, [Char], RepoType, VCS Program)]
repos'
            ]

    let progPathExtra = NubList [Char] -> [[Char]]
forall a. NubList a -> [a]
fromNubList NubList [Char]
projectConfigProgPathExtra
    getConfiguredVCS <- delayInitSharedResources $ \RepoType
repoType ->
      let vcs :: VCS Program
vcs = VCS Program
-> RepoType -> Map RepoType (VCS Program) -> VCS Program
forall k a. Ord k => a -> k -> Map k a -> a
Map.findWithDefault ([Char] -> VCS Program
forall a. HasCallStack => [Char] -> a
error ([Char] -> VCS Program) -> [Char] -> VCS Program
forall a b. (a -> b) -> a -> b
$ [Char]
"Unknown VCS: " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ RepoType -> [Char]
forall a. Pretty a => a -> [Char]
prettyShow RepoType
repoType) RepoType
repoType Map RepoType (VCS Program)
knownVCSs
       in Verbosity -> [[Char]] -> VCS Program -> IO (VCS ConfiguredProgram)
configureVCS Verbosity
verbosity [[Char]]
progPathExtra VCS Program
vcs

    concat
      <$> rerunConcurrentlyIfChanged
        verbosity
        (newJobControlFromParStrat verbosity compiler parStrat (Just maxNumFetchJobs))
        [ ( monitor
          , repoGroup'
          , do
              vcs' <- getConfiguredVCS repoType
              syncRepoGroupAndReadSourcePackages vcs' pathStem repoGroup'
          )
        | repoGroup@((primaryRepo, repoType) : _) <- Map.elems reposByLocation
        , let repoGroup' = ((SourceRepoList, RepoType) -> SourceRepoList)
-> [(SourceRepoList, RepoType)] -> [SourceRepoList]
forall a b. (a -> b) -> [a] -> [b]
map (SourceRepoList, RepoType) -> SourceRepoList
forall a b. (a, b) -> a
fst [(SourceRepoList, RepoType)]
repoGroup
              pathStem =
                [Char]
distDownloadSrcDirectory
                  [Char] -> [Char] -> [Char]
</> SourceRepoList -> [Char]
localFileNameForRemoteRepo SourceRepoList
primaryRepo
              monitor
                :: FileMonitor
                    [SourceRepoList]
                    [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
              monitor = [Char]
-> FileMonitor
     [SourceRepoList]
     [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
forall a b. Eq a => [Char] -> FileMonitor a b
newFileMonitor ([Char]
pathStem [Char] -> [Char] -> [Char]
<.> [Char]
"cache")
        ]
    where
      parStrat :: ParStratInstall
parStrat = Flag Bool -> Flag (Maybe Int) -> ParStratInstall
resolveNumJobsSetting Flag Bool
projectConfigUseSemaphore Flag (Maybe Int)
projectConfigNumJobs
      syncRepoGroupAndReadSourcePackages
        :: VCS ConfiguredProgram
        -> FilePath
        -> [SourceRepoList]
        -> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
      syncRepoGroupAndReadSourcePackages :: VCS ConfiguredProgram
-> [Char]
-> [SourceRepoList]
-> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
syncRepoGroupAndReadSourcePackages VCS ConfiguredProgram
vcs [Char]
pathStem [SourceRepoList]
repoGroup = do
        IO () -> Rebuild ()
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Rebuild ()) -> IO () -> Rebuild ()
forall a b. (a -> b) -> a -> b
$
          Verbosity -> Bool -> [Char] -> IO ()
createDirectoryIfMissingVerbose
            Verbosity
verbosity
            Bool
False
            [Char]
distDownloadSrcDirectory

        -- For syncing we don't care about different 'SourceRepo' values that
        -- are just different subdirs in the same repo.
        -- Do not sync source repositories when `--offline` flag applied.
        if Bool -> Bool
not Bool
offlineMode
          then
            Verbosity
-> VCS ConfiguredProgram
-> [(SourceRepositoryPackage Proxy, [Char])]
-> Rebuild ()
forall (f :: * -> *).
Verbosity
-> VCS ConfiguredProgram
-> [(SourceRepositoryPackage f, [Char])]
-> Rebuild ()
syncSourceRepos
              Verbosity
verbosity
              VCS ConfiguredProgram
vcs
              [ (SourceRepositoryPackage Proxy
repo, [Char]
repoPath)
              | (SourceRepositoryPackage Proxy
repo, NonEmpty (SourceRepositoryPackage Maybe)
_, [Char]
repoPath) <- [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
repoGroupWithPaths
              ]
          else do
            IO () -> Rebuild ()
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Rebuild ()) -> ([Char] -> IO ()) -> [Char] -> Rebuild ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Verbosity -> [Char] -> IO ()
warn Verbosity
verbosity ([Char] -> Rebuild ()) -> [Char] -> Rebuild ()
forall a b. (a -> b) -> a -> b
$ [Char]
"--offline was specified, skipping sync of repositories:"
            IO () -> Rebuild ()
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Rebuild ())
-> (((SourceRepositoryPackage Proxy,
      NonEmpty (SourceRepositoryPackage Maybe), [Char])
     -> IO ())
    -> IO ())
-> ((SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])
    -> IO ())
-> Rebuild ()
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
-> ((SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])
    -> IO ())
-> IO ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
repoGroupWithPaths (((SourceRepositoryPackage Proxy,
   NonEmpty (SourceRepositoryPackage Maybe), [Char])
  -> IO ())
 -> Rebuild ())
-> ((SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])
    -> IO ())
-> Rebuild ()
forall a b. (a -> b) -> a -> b
$ \(SourceRepositoryPackage Proxy
repo, NonEmpty (SourceRepositoryPackage Maybe)
_, [Char]
_) -> Verbosity -> [Char] -> IO ()
warn Verbosity
verbosity ([Char] -> IO ()) -> [Char] -> IO ()
forall a b. (a -> b) -> a -> b
$ SourceRepositoryPackage Proxy -> [Char]
forall (f :: * -> *). SourceRepositoryPackage f -> [Char]
srpLocation SourceRepositoryPackage Proxy
repo

        -- Run post-checkout-command if it is specified
        [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
-> ((SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])
    -> Rebuild ())
-> Rebuild ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
repoGroupWithPaths (((SourceRepositoryPackage Proxy,
   NonEmpty (SourceRepositoryPackage Maybe), [Char])
  -> Rebuild ())
 -> Rebuild ())
-> ((SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])
    -> Rebuild ())
-> Rebuild ()
forall a b. (a -> b) -> a -> b
$ \(SourceRepositoryPackage Proxy
repo, NonEmpty (SourceRepositoryPackage Maybe)
_, [Char]
repoPath) ->
          Maybe (NonEmpty [Char])
-> (NonEmpty [Char] -> Rebuild ()) -> Rebuild ()
forall (t :: * -> *) (f :: * -> *) a b.
(Foldable t, Applicative f) =>
t a -> (a -> f b) -> f ()
for_ ([[Char]] -> Maybe (NonEmpty [Char])
forall a. [a] -> Maybe (NonEmpty a)
nonEmpty (SourceRepositoryPackage Proxy -> [[Char]]
forall (f :: * -> *). SourceRepositoryPackage f -> [[Char]]
srpCommand SourceRepositoryPackage Proxy
repo)) ((NonEmpty [Char] -> Rebuild ()) -> Rebuild ())
-> (NonEmpty [Char] -> Rebuild ()) -> Rebuild ()
forall a b. (a -> b) -> a -> b
$ \([Char]
cmd :| [[Char]]
args) -> IO () -> Rebuild ()
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO () -> Rebuild ()) -> IO () -> Rebuild ()
forall a b. (a -> b) -> a -> b
$ do
            IO ExitCode -> IO ()
maybeExit (IO ExitCode -> IO ()) -> IO ExitCode -> IO ()
forall a b. (a -> b) -> a -> b
$ Verbosity
-> [Char]
-> [[Char]]
-> Maybe [Char]
-> Maybe [([Char], [Char])]
-> Maybe Handle
-> Maybe Handle
-> Maybe Handle
-> IO ExitCode
rawSystemIOWithEnv Verbosity
verbosity [Char]
cmd [[Char]]
args ([Char] -> Maybe [Char]
forall a. a -> Maybe a
Just [Char]
repoPath) Maybe [([Char], [Char])]
forall a. Maybe a
Nothing Maybe Handle
forall a. Maybe a
Nothing Maybe Handle
forall a. Maybe a
Nothing Maybe Handle
forall a. Maybe a
Nothing

        -- But for reading we go through each 'SourceRepo' including its subdir
        -- value and have to know which path each one ended up in.
        [Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))]
-> Rebuild [PackageSpecifier (SourcePackage UnresolvedPkgLoc)]
forall (t :: * -> *) (f :: * -> *) a.
(Traversable t, Applicative f) =>
t (f a) -> f (t a)
forall (f :: * -> *) a. Applicative f => [f a] -> f [a]
sequenceA
          [ SourceRepositoryPackage Maybe
-> [Char]
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readPackageFromSourceRepo SourceRepositoryPackage Maybe
repoWithSubdir [Char]
repoPath
          | (SourceRepositoryPackage Proxy
_, NonEmpty (SourceRepositoryPackage Maybe)
reposWithSubdir, [Char]
repoPath) <- [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
repoGroupWithPaths
          , SourceRepositoryPackage Maybe
repoWithSubdir <- NonEmpty (SourceRepositoryPackage Maybe)
-> [SourceRepositoryPackage Maybe]
forall a. NonEmpty a -> [a]
NE.toList NonEmpty (SourceRepositoryPackage Maybe)
reposWithSubdir
          ]
        where
          -- So to do both things above, we pair them up here.
          repoGroupWithPaths
            :: [(SourceRepositoryPackage Proxy, NonEmpty (SourceRepositoryPackage Maybe), FilePath)]
          repoGroupWithPaths :: [(SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe), [Char])]
repoGroupWithPaths =
            ((SourceRepositoryPackage Proxy,
  NonEmpty (SourceRepositoryPackage Maybe))
 -> [Char]
 -> (SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char]))
-> [(SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe))]
-> [[Char]]
-> [(SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe), [Char])]
forall a b c. (a -> b -> c) -> [a] -> [b] -> [c]
zipWith
              (\(SourceRepositoryPackage Proxy
x, NonEmpty (SourceRepositoryPackage Maybe)
y) [Char]
z -> (SourceRepositoryPackage Proxy
x, NonEmpty (SourceRepositoryPackage Maybe)
y, [Char]
z))
              ( [(SourceRepositoryPackage Proxy, SourceRepositoryPackage Maybe)]
-> [(SourceRepositoryPackage Proxy,
     NonEmpty (SourceRepositoryPackage Maybe))]
forall k v. Ord k => [(k, v)] -> [(k, NonEmpty v)]
mapGroup
                  [ (SourceRepositoryPackage Maybe
repo{srpSubdir = Proxy}, SourceRepositoryPackage Maybe
repo)
                  | SourceRepositoryPackage Maybe
repo <- (SourceRepoList -> [SourceRepositoryPackage Maybe])
-> [SourceRepoList] -> [SourceRepositoryPackage Maybe]
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (NonEmpty (SourceRepositoryPackage Maybe)
-> [SourceRepositoryPackage Maybe]
forall a. NonEmpty a -> [a]
NE.toList (NonEmpty (SourceRepositoryPackage Maybe)
 -> [SourceRepositoryPackage Maybe])
-> (SourceRepoList -> NonEmpty (SourceRepositoryPackage Maybe))
-> SourceRepoList
-> [SourceRepositoryPackage Maybe]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. SourceRepoList -> NonEmpty (SourceRepositoryPackage Maybe)
srpFanOut) [SourceRepoList]
repoGroup
                  ]
              )
              [[Char]]
repoPaths

          mapGroup :: Ord k => [(k, v)] -> [(k, NonEmpty v)]
          mapGroup :: forall k v. Ord k => [(k, v)] -> [(k, NonEmpty v)]
mapGroup = Map k (NonEmpty v) -> [(k, NonEmpty v)]
forall k a. Map k a -> [(k, a)]
Map.toList (Map k (NonEmpty v) -> [(k, NonEmpty v)])
-> ([(k, v)] -> Map k (NonEmpty v))
-> [(k, v)]
-> [(k, NonEmpty v)]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (NonEmpty v -> NonEmpty v -> NonEmpty v)
-> [(k, NonEmpty v)] -> Map k (NonEmpty v)
forall k a. Ord k => (a -> a -> a) -> [(k, a)] -> Map k a
Map.fromListWith NonEmpty v -> NonEmpty v -> NonEmpty v
forall a. Semigroup a => a -> a -> a
(<>) ([(k, NonEmpty v)] -> Map k (NonEmpty v))
-> ([(k, v)] -> [(k, NonEmpty v)])
-> [(k, v)]
-> Map k (NonEmpty v)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((k, v) -> (k, NonEmpty v)) -> [(k, v)] -> [(k, NonEmpty v)]
forall a b. (a -> b) -> [a] -> [b]
map (\(k
k, v
v) -> (k
k, v -> NonEmpty v
forall a. a -> NonEmpty a
forall (f :: * -> *) a. Applicative f => a -> f a
pure v
v))

          -- The repos in a group are given distinct names by simple enumeration
          -- foo, foo-2, foo-3 etc
          repoPaths :: [FilePath]
          repoPaths :: [[Char]]
repoPaths =
            [Char]
pathStem
              [Char] -> [[Char]] -> [[Char]]
forall a. a -> [a] -> [a]
: [[Char]
pathStem [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"-" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Int -> [Char]
forall a. Show a => a -> [Char]
show (Int
i :: Int) | Int
i <- [Int
2 ..]]

      readPackageFromSourceRepo
        :: SourceRepositoryPackage Maybe
        -> FilePath
        -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
      readPackageFromSourceRepo :: SourceRepositoryPackage Maybe
-> [Char]
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
readPackageFromSourceRepo SourceRepositoryPackage Maybe
repo [Char]
repoPath = do
        let packageDir :: FilePath
            packageDir :: [Char]
packageDir = [Char] -> ([Char] -> [Char]) -> Maybe [Char] -> [Char]
forall b a. b -> (a -> b) -> Maybe a -> b
maybe [Char]
repoPath ([Char]
repoPath [Char] -> [Char] -> [Char]
</>) (SourceRepositoryPackage Maybe -> Maybe [Char]
forall (f :: * -> *). SourceRepositoryPackage f -> f [Char]
srpSubdir SourceRepositoryPackage Maybe
repo)

        entries <- IO [[Char]] -> Rebuild [[Char]]
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO [[Char]] -> Rebuild [[Char]])
-> IO [[Char]] -> Rebuild [[Char]]
forall a b. (a -> b) -> a -> b
$ [Char] -> IO [[Char]]
getDirectoryContents [Char]
packageDir
        -- TODO: dcoutts 2018-06-23: wrap exceptions
        case filter (\[Char]
e -> [Char] -> [Char]
takeExtension [Char]
e [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".cabal") entries of
          [] -> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
 -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc)))
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. (a -> b) -> a -> b
$ CabalFileSearchFailure
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CabalFileSearchFailure
 -> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc)))
-> CabalFileSearchFailure
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. (a -> b) -> a -> b
$ [Char] -> CabalFileSearchFailure
NoCabalFileFound [Char]
packageDir
          ([Char]
_ : [Char]
_ : [[Char]]
_) -> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
 -> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc)))
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
-> Rebuild (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. (a -> b) -> a -> b
$ CabalFileSearchFailure
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CabalFileSearchFailure
 -> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc)))
-> CabalFileSearchFailure
-> IO (PackageSpecifier (SourcePackage UnresolvedPkgLoc))
forall a b. (a -> b) -> a -> b
$ [Char] -> CabalFileSearchFailure
MultipleCabalFilesFound [Char]
packageDir
          [[Char]
cabalFileName] -> do
            let cabalFilePath :: [Char]
cabalFilePath = [Char]
packageDir [Char] -> [Char] -> [Char]
</> [Char]
cabalFileName
            [MonitorFilePath] -> Rebuild ()
monitorFiles [[Char] -> MonitorFilePath
monitorFileHashed [Char]
cabalFilePath]
            gpd <- IO GenericPackageDescription -> Rebuild GenericPackageDescription
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO GenericPackageDescription -> Rebuild GenericPackageDescription)
-> IO GenericPackageDescription
-> Rebuild GenericPackageDescription
forall a b. (a -> b) -> a -> b
$ Verbosity -> [Char] -> ByteString -> IO GenericPackageDescription
readSourcePackageCabalFile Verbosity
verbosity [Char]
cabalFilePath (ByteString -> IO GenericPackageDescription)
-> IO ByteString -> IO GenericPackageDescription
forall (m :: * -> *) a b. Monad m => (a -> m b) -> m a -> m b
=<< [Char] -> IO ByteString
BS.readFile [Char]
cabalFilePath

            -- write sdist tarball, to repoPath-pgkid
            tarball <- liftIO $ packageDirToSdist verbosity gpd packageDir
            let tarballPath = [Char]
repoPath [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"-" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ PackageId -> [Char]
forall a. Pretty a => a -> [Char]
prettyShow (GenericPackageDescription -> PackageId
forall pkg. Package pkg => pkg -> PackageId
packageId GenericPackageDescription
gpd) [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
".tar.gz"
            liftIO $ LBS.writeFile tarballPath tarball

            let location = SourceRepositoryPackage Maybe -> [Char] -> PackageLocation [Char]
forall local.
SourceRepositoryPackage Maybe -> local -> PackageLocation local
RemoteSourceRepoPackage SourceRepositoryPackage Maybe
repo [Char]
tarballPath
            return $ mkSpecificSourcePackage location gpd

      reportSourceRepoProblems :: [(SourceRepoList, SourceRepoProblem)] -> Rebuild a
      reportSourceRepoProblems :: forall a. [(SourceRepoList, SourceRepoProblem)] -> Rebuild a
reportSourceRepoProblems = IO a -> Rebuild a
forall a. IO a -> Rebuild a
forall (m :: * -> *) a. MonadIO m => IO a -> m a
liftIO (IO a -> Rebuild a)
-> ([(SourceRepoList, SourceRepoProblem)] -> IO a)
-> [(SourceRepoList, SourceRepoProblem)]
-> Rebuild a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Verbosity -> CabalInstallException -> IO a
forall a1 a.
(HasCallStack, Show a1, Typeable a1,
 Exception (VerboseException a1)) =>
Verbosity -> a1 -> IO a
dieWithException Verbosity
verbosity (CabalInstallException -> IO a)
-> ([(SourceRepoList, SourceRepoProblem)] -> CabalInstallException)
-> [(SourceRepoList, SourceRepoProblem)]
-> IO a
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> CabalInstallException
ReportSourceRepoProblems ([Char] -> CabalInstallException)
-> ([(SourceRepoList, SourceRepoProblem)] -> [Char])
-> [(SourceRepoList, SourceRepoProblem)]
-> CabalInstallException
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [(SourceRepoList, SourceRepoProblem)] -> [Char]
renderSourceRepoProblems

      renderSourceRepoProblems :: [(SourceRepoList, SourceRepoProblem)] -> String
      renderSourceRepoProblems :: [(SourceRepoList, SourceRepoProblem)] -> [Char]
renderSourceRepoProblems = [[Char]] -> [Char]
unlines ([[Char]] -> [Char])
-> ([(SourceRepoList, SourceRepoProblem)] -> [[Char]])
-> [(SourceRepoList, SourceRepoProblem)]
-> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ((SourceRepoList, SourceRepoProblem) -> [Char])
-> [(SourceRepoList, SourceRepoProblem)] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map (SourceRepoList, SourceRepoProblem) -> [Char]
forall a. Show a => a -> [Char]
show -- "TODO: the repo problems"

-- | Utility used by all the helpers of 'fetchAndReadSourcePackages' to make an
-- appropriate @'PackageSpecifier' ('SourcePackage' (..))@ for a given package
-- from a given location.
mkSpecificSourcePackage
  :: PackageLocation FilePath
  -> GenericPackageDescription
  -> PackageSpecifier (SourcePackage UnresolvedPkgLoc)
mkSpecificSourcePackage :: PackageLocation [Char]
-> GenericPackageDescription
-> PackageSpecifier (SourcePackage UnresolvedPkgLoc)
mkSpecificSourcePackage PackageLocation [Char]
location GenericPackageDescription
pkg =
  SourcePackage UnresolvedPkgLoc
-> PackageSpecifier (SourcePackage UnresolvedPkgLoc)
forall pkg. pkg -> PackageSpecifier pkg
SpecificSourcePackage
    SourcePackage
      { srcpkgPackageId :: PackageId
srcpkgPackageId = GenericPackageDescription -> PackageId
forall pkg. Package pkg => pkg -> PackageId
packageId GenericPackageDescription
pkg
      , srcpkgDescription :: GenericPackageDescription
srcpkgDescription = GenericPackageDescription
pkg
      , srcpkgSource :: UnresolvedPkgLoc
srcpkgSource = ([Char] -> Maybe [Char])
-> PackageLocation [Char] -> UnresolvedPkgLoc
forall a b. (a -> b) -> PackageLocation a -> PackageLocation b
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
fmap [Char] -> Maybe [Char]
forall a. a -> Maybe a
Just PackageLocation [Char]
location
      , srcpkgDescrOverride :: PackageDescriptionOverride
srcpkgDescrOverride = PackageDescriptionOverride
forall a. Maybe a
Nothing
      }

-- | Errors reported upon failing to parse a @.cabal@ file.
data CabalFileParseError
  = CabalFileParseError
      FilePath
      -- ^ @.cabal@ file path
      BS.ByteString
      -- ^ @.cabal@ file contents
      (NonEmpty PError)
      -- ^ errors
      (Maybe Version)
      -- ^ We might discover the spec version the package needs
      [PWarning]
      -- ^ warnings

-- | Manual instance which skips file contents
instance Show CabalFileParseError where
  showsPrec :: Int -> CabalFileParseError -> [Char] -> [Char]
showsPrec Int
d (CabalFileParseError [Char]
fp ByteString
_ NonEmpty PError
es Maybe Version
mv [PWarning]
ws) =
    Bool -> ([Char] -> [Char]) -> [Char] -> [Char]
showParen (Int
d Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
> Int
10) (([Char] -> [Char]) -> [Char] -> [Char])
-> ([Char] -> [Char]) -> [Char] -> [Char]
forall a b. (a -> b) -> a -> b
$
      [Char] -> [Char] -> [Char]
showString [Char]
"CabalFileParseError"
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Char] -> [Char]
showChar Char
' '
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [Char] -> [Char] -> [Char]
forall a. Show a => Int -> a -> [Char] -> [Char]
showsPrec Int
11 [Char]
fp
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Char] -> [Char]
showChar Char
' '
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [Char] -> [Char] -> [Char]
forall a. Show a => Int -> a -> [Char] -> [Char]
showsPrec Int
11 ([Char]
"" :: String)
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Char] -> [Char]
showChar Char
' '
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> NonEmpty PError -> [Char] -> [Char]
forall a. Show a => Int -> a -> [Char] -> [Char]
showsPrec Int
11 NonEmpty PError
es
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Char] -> [Char]
showChar Char
' '
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> Maybe Version -> [Char] -> [Char]
forall a. Show a => Int -> a -> [Char] -> [Char]
showsPrec Int
11 Maybe Version
mv
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Char -> [Char] -> [Char]
showChar Char
' '
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. Int -> [PWarning] -> [Char] -> [Char]
forall a. Show a => Int -> a -> [Char] -> [Char]
showsPrec Int
11 [PWarning]
ws

instance Exception CabalFileParseError where
  displayException :: CabalFileParseError -> [Char]
displayException = CabalFileParseError -> [Char]
renderCabalFileParseError

renderCabalFileParseError :: CabalFileParseError -> String
renderCabalFileParseError :: CabalFileParseError -> [Char]
renderCabalFileParseError (CabalFileParseError [Char]
filePath ByteString
contents NonEmpty PError
errors Maybe Version
_ [PWarning]
warnings) =
  [Char] -> ByteString -> NonEmpty PError -> [PWarning] -> [Char]
renderParseError [Char]
filePath ByteString
contents NonEmpty PError
errors [PWarning]
warnings

-- | Wrapper for the @.cabal@ file parser. It reports warnings on higher
-- verbosity levels and throws 'CabalFileParseError' on failure.
readSourcePackageCabalFile
  :: Verbosity
  -> FilePath
  -> BS.ByteString
  -> IO GenericPackageDescription
readSourcePackageCabalFile :: Verbosity -> [Char] -> ByteString -> IO GenericPackageDescription
readSourcePackageCabalFile Verbosity
verbosity [Char]
pkgfilename ByteString
content =
  ([Char] -> IO ())
-> [Char] -> ByteString -> IO GenericPackageDescription
readSourcePackageCabalFile' (Verbosity -> [Char] -> IO ()
warn Verbosity
verbosity) [Char]
pkgfilename ByteString
content

-- | Like `readSourcePackageCabalFile`, but the `warn` function is an argument.
--
-- This is used when reading @.cabal@ files in indexes, where warnings should
-- generally be ignored.
readSourcePackageCabalFile'
  :: (String -> IO ())
  -> FilePath
  -> BS.ByteString
  -> IO GenericPackageDescription
readSourcePackageCabalFile' :: ([Char] -> IO ())
-> [Char] -> ByteString -> IO GenericPackageDescription
readSourcePackageCabalFile' [Char] -> IO ()
logWarnings [Char]
pkgfilename ByteString
content =
  case ParseResult GenericPackageDescription
-> ([PWarning],
    Either (Maybe Version, NonEmpty PError) GenericPackageDescription)
forall a.
ParseResult a
-> ([PWarning], Either (Maybe Version, NonEmpty PError) a)
runParseResult (ByteString -> ParseResult GenericPackageDescription
parseGenericPackageDescription ByteString
content) of
    ([PWarning]
warnings, Right GenericPackageDescription
pkg) -> do
      Bool -> IO () -> IO ()
forall (f :: * -> *). Applicative f => Bool -> f () -> f ()
unless ([PWarning] -> Bool
forall a. [a] -> Bool
forall (t :: * -> *) a. Foldable t => t a -> Bool
null [PWarning]
warnings) (IO () -> IO ()) -> IO () -> IO ()
forall a b. (a -> b) -> a -> b
$
        [Char] -> IO ()
logWarnings ([PWarning] -> [Char]
formatWarnings [PWarning]
warnings)
      GenericPackageDescription -> IO GenericPackageDescription
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return GenericPackageDescription
pkg
    ([PWarning]
warnings, Left (Maybe Version
mspecVersion, NonEmpty PError
errors)) ->
      CabalFileParseError -> IO GenericPackageDescription
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO (CabalFileParseError -> IO GenericPackageDescription)
-> CabalFileParseError -> IO GenericPackageDescription
forall a b. (a -> b) -> a -> b
$ [Char]
-> ByteString
-> NonEmpty PError
-> Maybe Version
-> [PWarning]
-> CabalFileParseError
CabalFileParseError [Char]
pkgfilename ByteString
content NonEmpty PError
errors Maybe Version
mspecVersion [PWarning]
warnings
  where
    formatWarnings :: [PWarning] -> [Char]
formatWarnings [PWarning]
warnings =
      [Char]
"The package description file "
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
pkgfilename
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
" has warnings: "
        [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [[Char]] -> [Char]
unlines ((PWarning -> [Char]) -> [PWarning] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map ([Char] -> PWarning -> [Char]
showPWarning [Char]
pkgfilename) [PWarning]
warnings)

-- | When looking for a package's @.cabal@ file we can find none, or several,
-- both of which are failures.
data CabalFileSearchFailure
  = NoCabalFileFound FilePath
  | MultipleCabalFilesFound FilePath
  deriving (Int -> CabalFileSearchFailure -> [Char] -> [Char]
[CabalFileSearchFailure] -> [Char] -> [Char]
CabalFileSearchFailure -> [Char]
(Int -> CabalFileSearchFailure -> [Char] -> [Char])
-> (CabalFileSearchFailure -> [Char])
-> ([CabalFileSearchFailure] -> [Char] -> [Char])
-> Show CabalFileSearchFailure
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> CabalFileSearchFailure -> [Char] -> [Char]
showsPrec :: Int -> CabalFileSearchFailure -> [Char] -> [Char]
$cshow :: CabalFileSearchFailure -> [Char]
show :: CabalFileSearchFailure -> [Char]
$cshowList :: [CabalFileSearchFailure] -> [Char] -> [Char]
showList :: [CabalFileSearchFailure] -> [Char] -> [Char]
Show)

instance Exception CabalFileSearchFailure

-- | Find the @.cabal@ file within a tarball file and return it by value.
--
-- Can fail with a 'Tar.FormatError' or 'CabalFileSearchFailure' exception.
extractTarballPackageCabalFile :: FilePath -> IO (FilePath, BS.ByteString)
extractTarballPackageCabalFile :: [Char] -> IO ([Char], ByteString)
extractTarballPackageCabalFile [Char]
tarballFile =
  [Char]
-> IOMode
-> (Handle -> IO ([Char], ByteString))
-> IO ([Char], ByteString)
forall r. [Char] -> IOMode -> (Handle -> IO r) -> IO r
withBinaryFile [Char]
tarballFile IOMode
ReadMode ((Handle -> IO ([Char], ByteString)) -> IO ([Char], ByteString))
-> (Handle -> IO ([Char], ByteString)) -> IO ([Char], ByteString)
forall a b. (a -> b) -> a -> b
$ \Handle
hnd -> do
    content <- Handle -> IO ByteString
LBS.hGetContents Handle
hnd
    case extractTarballPackageCabalFilePure tarballFile content of
      Left (Left FormatError
e) -> FormatError -> IO ([Char], ByteString)
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO FormatError
e
      Left (Right CabalFileSearchFailure
e) -> CabalFileSearchFailure -> IO ([Char], ByteString)
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO CabalFileSearchFailure
e
      Right ([Char]
fileName, ByteString
fileContent) ->
        (,) [Char]
fileName (ByteString -> ([Char], ByteString))
-> IO ByteString -> IO ([Char], ByteString)
forall (f :: * -> *) a b. Functor f => (a -> b) -> f a -> f b
<$> ByteString -> IO ByteString
forall a. a -> IO a
evaluate (ByteString -> ByteString
LBS.toStrict ByteString
fileContent)

-- | Scan through a tar file stream and collect the @.cabal@ file, or fail.
extractTarballPackageCabalFilePure
  :: FilePath
  -> LBS.ByteString
  -> Either
      ( Either
          Tar.FormatError
          CabalFileSearchFailure
      )
      (FilePath, LBS.ByteString)
extractTarballPackageCabalFilePure :: [Char]
-> ByteString
-> Either
     (Either FormatError CabalFileSearchFailure) ([Char], ByteString)
extractTarballPackageCabalFilePure [Char]
tarballFile =
  Either
  (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
  (Map TarPath (GenEntry ByteString TarPath LinkTarget))
-> Either
     (Either FormatError CabalFileSearchFailure) ([Char], ByteString)
forall {a} {b} {k} {b} {linkTarget}.
Either (a, b) (Map k (GenEntry b TarPath linkTarget))
-> Either (Either a CabalFileSearchFailure) ([Char], b)
check
    (Either
   (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
   (Map TarPath (GenEntry ByteString TarPath LinkTarget))
 -> Either
      (Either FormatError CabalFileSearchFailure) ([Char], ByteString))
-> (ByteString
    -> Either
         (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
         (Map TarPath (GenEntry ByteString TarPath LinkTarget)))
-> ByteString
-> Either
     (Either FormatError CabalFileSearchFailure) ([Char], ByteString)
forall b c a. (b -> c) -> (a -> b) -> a -> c
. GenEntries ByteString TarPath LinkTarget FormatError
-> Either
     (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
     (Map TarPath (GenEntry ByteString TarPath LinkTarget))
forall {content} {linkTarget} {e}.
GenEntries content TarPath linkTarget e
-> Either
     (e, Map TarPath (GenEntry content TarPath linkTarget))
     (Map TarPath (GenEntry content TarPath linkTarget))
accumEntryMap
    (GenEntries ByteString TarPath LinkTarget FormatError
 -> Either
      (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
      (Map TarPath (GenEntry ByteString TarPath LinkTarget)))
-> (ByteString
    -> GenEntries ByteString TarPath LinkTarget FormatError)
-> ByteString
-> Either
     (FormatError, Map TarPath (GenEntry ByteString TarPath LinkTarget))
     (Map TarPath (GenEntry ByteString TarPath LinkTarget))
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (GenEntry ByteString TarPath LinkTarget -> Bool)
-> GenEntries ByteString TarPath LinkTarget FormatError
-> GenEntries ByteString TarPath LinkTarget FormatError
forall e.
(GenEntry ByteString TarPath LinkTarget -> Bool)
-> Entries e -> Entries e
Tar.filterEntries GenEntry ByteString TarPath LinkTarget -> Bool
forall {content} {linkTarget}.
GenEntry content TarPath linkTarget -> Bool
isCabalFile
    (GenEntries ByteString TarPath LinkTarget FormatError
 -> GenEntries ByteString TarPath LinkTarget FormatError)
-> (ByteString
    -> GenEntries ByteString TarPath LinkTarget FormatError)
-> ByteString
-> GenEntries ByteString TarPath LinkTarget FormatError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> GenEntries ByteString TarPath LinkTarget FormatError
Tar.read
    (ByteString
 -> GenEntries ByteString TarPath LinkTarget FormatError)
-> (ByteString -> ByteString)
-> ByteString
-> GenEntries ByteString TarPath LinkTarget FormatError
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> ByteString
GZipUtils.maybeDecompress
  where
    accumEntryMap :: GenEntries content TarPath linkTarget e
-> Either
     (e, Map TarPath (GenEntry content TarPath linkTarget))
     (Map TarPath (GenEntry content TarPath linkTarget))
accumEntryMap =
      (Map TarPath (GenEntry content TarPath linkTarget)
 -> GenEntry content TarPath linkTarget
 -> Map TarPath (GenEntry content TarPath linkTarget))
-> Map TarPath (GenEntry content TarPath linkTarget)
-> GenEntries content TarPath linkTarget e
-> Either
     (e, Map TarPath (GenEntry content TarPath linkTarget))
     (Map TarPath (GenEntry content TarPath linkTarget))
forall a content tarPath linkTarget e.
(a -> GenEntry content tarPath linkTarget -> a)
-> a -> GenEntries content tarPath linkTarget e -> Either (e, a) a
Tar.foldlEntries
        (\Map TarPath (GenEntry content TarPath linkTarget)
m GenEntry content TarPath linkTarget
e -> TarPath
-> GenEntry content TarPath linkTarget
-> Map TarPath (GenEntry content TarPath linkTarget)
-> Map TarPath (GenEntry content TarPath linkTarget)
forall k a. Ord k => k -> a -> Map k a -> Map k a
Map.insert (GenEntry content TarPath linkTarget -> TarPath
forall content tarPath linkTarget.
GenEntry content tarPath linkTarget -> tarPath
Tar.entryTarPath GenEntry content TarPath linkTarget
e) GenEntry content TarPath linkTarget
e Map TarPath (GenEntry content TarPath linkTarget)
m)
        Map TarPath (GenEntry content TarPath linkTarget)
forall k a. Map k a
Map.empty

    check :: Either (a, b) (Map k (GenEntry b TarPath linkTarget))
-> Either (Either a CabalFileSearchFailure) ([Char], b)
check (Left (a
e, b
_m)) = Either a CabalFileSearchFailure
-> Either (Either a CabalFileSearchFailure) ([Char], b)
forall a b. a -> Either a b
Left (a -> Either a CabalFileSearchFailure
forall a b. a -> Either a b
Left a
e)
    check (Right Map k (GenEntry b TarPath linkTarget)
m) = case Map k (GenEntry b TarPath linkTarget)
-> [GenEntry b TarPath linkTarget]
forall k a. Map k a -> [a]
Map.elems Map k (GenEntry b TarPath linkTarget)
m of
      [] -> Either a CabalFileSearchFailure
-> Either (Either a CabalFileSearchFailure) ([Char], b)
forall a b. a -> Either a b
Left (CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. b -> Either a b
Right (CabalFileSearchFailure -> Either a CabalFileSearchFailure)
-> CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. (a -> b) -> a -> b
$ [Char] -> CabalFileSearchFailure
NoCabalFileFound [Char]
tarballFile)
      [GenEntry b TarPath linkTarget
file] -> case GenEntry b TarPath linkTarget -> GenEntryContent b linkTarget
forall content tarPath linkTarget.
GenEntry content tarPath linkTarget
-> GenEntryContent content linkTarget
Tar.entryContent GenEntry b TarPath linkTarget
file of
        Tar.NormalFile b
content FileSize
_ -> ([Char], b) -> Either (Either a CabalFileSearchFailure) ([Char], b)
forall a b. b -> Either a b
Right (GenEntry b TarPath linkTarget -> [Char]
forall content linkTarget.
GenEntry content TarPath linkTarget -> [Char]
Tar.entryPath GenEntry b TarPath linkTarget
file, b
content)
        GenEntryContent b linkTarget
_ -> Either a CabalFileSearchFailure
-> Either (Either a CabalFileSearchFailure) ([Char], b)
forall a b. a -> Either a b
Left (CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. b -> Either a b
Right (CabalFileSearchFailure -> Either a CabalFileSearchFailure)
-> CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. (a -> b) -> a -> b
$ [Char] -> CabalFileSearchFailure
NoCabalFileFound [Char]
tarballFile)
      [GenEntry b TarPath linkTarget]
_files -> Either a CabalFileSearchFailure
-> Either (Either a CabalFileSearchFailure) ([Char], b)
forall a b. a -> Either a b
Left (CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. b -> Either a b
Right (CabalFileSearchFailure -> Either a CabalFileSearchFailure)
-> CabalFileSearchFailure -> Either a CabalFileSearchFailure
forall a b. (a -> b) -> a -> b
$ [Char] -> CabalFileSearchFailure
MultipleCabalFilesFound [Char]
tarballFile)

    isCabalFile :: GenEntry content TarPath linkTarget -> Bool
isCabalFile GenEntry content TarPath linkTarget
e = case [Char] -> [[Char]]
splitPath (GenEntry content TarPath linkTarget -> [Char]
forall content linkTarget.
GenEntry content TarPath linkTarget -> [Char]
Tar.entryPath GenEntry content TarPath linkTarget
e) of
      [[Char]
_dir, [Char]
file] -> [Char] -> [Char]
takeExtension [Char]
file [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".cabal"
      [[Char]
".", [Char]
_dir, [Char]
file] -> [Char] -> [Char]
takeExtension [Char]
file [Char] -> [Char] -> Bool
forall a. Eq a => a -> a -> Bool
== [Char]
".cabal"
      [[Char]]
_ -> Bool
False

-- | The name to use for a local file for a remote tarball 'SourceRepo'.
-- This is deterministic based on the remote tarball URI, and is intended
-- to produce non-clashing file names for different tarballs.
localFileNameForRemoteTarball :: URI -> FilePath
localFileNameForRemoteTarball :: URI -> [Char]
localFileNameForRemoteTarball URI
uri =
  URI -> [Char]
mangleName URI
uri
    [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"-"
    [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ HashValue -> [Char]
showHashValue HashValue
locationHash
  where
    mangleName :: URI -> [Char]
mangleName =
      Int -> [Char] -> [Char]
truncateString Int
10
        ([Char] -> [Char]) -> (URI -> [Char]) -> URI -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
dropExtension
        ([Char] -> [Char]) -> (URI -> [Char]) -> URI -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
dropExtension
        ([Char] -> [Char]) -> (URI -> [Char]) -> URI -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
takeFileName
        ([Char] -> [Char]) -> (URI -> [Char]) -> URI -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
dropTrailingPathSeparator
        ([Char] -> [Char]) -> (URI -> [Char]) -> URI -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. URI -> [Char]
uriPath

    locationHash :: HashValue
    locationHash :: HashValue
locationHash = ByteString -> HashValue
hashValue ([Char] -> ByteString
toUTF8LBS (([Char] -> [Char]) -> URI -> [Char] -> [Char]
uriToString [Char] -> [Char]
forall a. a -> a
id URI
uri [Char]
""))

-- | The name to use for a local file or dir for a remote 'SourceRepo'.
-- This is deterministic based on the source repo identity details, and
-- intended to produce non-clashing file names for different repos.
localFileNameForRemoteRepo :: SourceRepoList -> FilePath
localFileNameForRemoteRepo :: SourceRepoList -> [Char]
localFileNameForRemoteRepo SourceRepositoryPackage{RepoType
srpType :: RepoType
srpType :: forall (f :: * -> *). SourceRepositoryPackage f -> RepoType
srpType, [Char]
srpLocation :: forall (f :: * -> *). SourceRepositoryPackage f -> [Char]
srpLocation :: [Char]
srpLocation} =
  [Char] -> [Char]
mangleName [Char]
srpLocation [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"-" [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ HashValue -> [Char]
showHashValue HashValue
locationHash
  where
    mangleName :: [Char] -> [Char]
mangleName =
      Int -> [Char] -> [Char]
truncateString Int
10
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
dropExtension
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
takeFileName
        ([Char] -> [Char]) -> ([Char] -> [Char]) -> [Char] -> [Char]
forall b c a. (b -> c) -> (a -> b) -> a -> c
. [Char] -> [Char]
dropTrailingPathSeparator

    -- just the parts that make up the "identity" of the repo
    locationHash :: HashValue
    locationHash :: HashValue
locationHash =
      ByteString -> HashValue
hashValue (ByteString -> HashValue) -> ByteString -> HashValue
forall a b. (a -> b) -> a -> b
$
        [ByteString] -> ByteString
LBS.fromChunks [[Char] -> ByteString
toUTF8BS [Char]
srpLocation, [Char] -> ByteString
toUTF8BS (RepoType -> [Char]
forall a. Show a => a -> [Char]
show RepoType
srpType)]

-- | Truncate a string, with a visual indication that it is truncated.
truncateString :: Int -> String -> String
truncateString :: Int -> [Char] -> [Char]
truncateString Int
n [Char]
s
  | [Char] -> Int
forall a. [a] -> Int
forall (t :: * -> *) a. Foldable t => t a -> Int
length [Char]
s Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
n = [Char]
s
  | Bool
otherwise = Int -> [Char] -> [Char]
forall a. Int -> [a] -> [a]
take (Int
n Int -> Int -> Int
forall a. Num a => a -> a -> a
- Int
1) [Char]
s [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"_"

-- TODO: add something like this, here or in the project planning
-- Based on the package location, which packages will be built inplace in the
-- build tree vs placed in the store. This has various implications on what we
-- can do with the package, e.g. can we run tests, ghci etc.
--
-- packageIsLocalToProject :: ProjectPackageLocation -> Bool

---------------------------------------------
-- Checking configuration sanity
--

data BadPerPackageCompilerPaths
  = BadPerPackageCompilerPaths [(PackageName, String)]
  deriving (Int -> BadPerPackageCompilerPaths -> [Char] -> [Char]
[BadPerPackageCompilerPaths] -> [Char] -> [Char]
BadPerPackageCompilerPaths -> [Char]
(Int -> BadPerPackageCompilerPaths -> [Char] -> [Char])
-> (BadPerPackageCompilerPaths -> [Char])
-> ([BadPerPackageCompilerPaths] -> [Char] -> [Char])
-> Show BadPerPackageCompilerPaths
forall a.
(Int -> a -> [Char] -> [Char])
-> (a -> [Char]) -> ([a] -> [Char] -> [Char]) -> Show a
$cshowsPrec :: Int -> BadPerPackageCompilerPaths -> [Char] -> [Char]
showsPrec :: Int -> BadPerPackageCompilerPaths -> [Char] -> [Char]
$cshow :: BadPerPackageCompilerPaths -> [Char]
show :: BadPerPackageCompilerPaths -> [Char]
$cshowList :: [BadPerPackageCompilerPaths] -> [Char] -> [Char]
showList :: [BadPerPackageCompilerPaths] -> [Char] -> [Char]
Show)

instance Exception BadPerPackageCompilerPaths where
  displayException :: BadPerPackageCompilerPaths -> [Char]
displayException = BadPerPackageCompilerPaths -> [Char]
renderBadPerPackageCompilerPaths

-- TODO: [nice to have] custom exception subclass for Doc rendering, colour etc

renderBadPerPackageCompilerPaths :: BadPerPackageCompilerPaths -> String
renderBadPerPackageCompilerPaths :: BadPerPackageCompilerPaths -> [Char]
renderBadPerPackageCompilerPaths
  (BadPerPackageCompilerPaths ((PackageName
pkgname, [Char]
progname) : [(PackageName, [Char])]
_)) =
    [Char]
"The path to the compiler program (or programs used by the compiler) "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"cannot be specified on a per-package basis in the cabal.project file "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"(i.e. setting the '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
progname
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"-location' for package '"
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ PackageName -> [Char]
forall a. Pretty a => a -> [Char]
prettyShow PackageName
pkgname
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"'). All packages have to use the same compiler, so "
      [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ [Char]
"specify the path in a global 'program-locations' section."
-- TODO: [nice to have] better format control so we can pretty-print the
-- offending part of the project file. Currently the line wrapping breaks any
-- formatting.
renderBadPerPackageCompilerPaths BadPerPackageCompilerPaths
_ = [Char] -> [Char]
forall a. HasCallStack => [Char] -> a
error [Char]
"renderBadPerPackageCompilerPaths"

-- | The project configuration is not allowed to specify program locations for
-- programs used by the compiler as these have to be the same for each set of
-- packages.
--
-- We cannot check this until we know which programs the compiler uses, which
-- in principle is not until we've configured the compiler.
--
-- Throws 'BadPerPackageCompilerPaths'
checkBadPerPackageCompilerPaths
  :: [ConfiguredProgram]
  -> Map PackageName PackageConfig
  -> IO ()
checkBadPerPackageCompilerPaths :: [ConfiguredProgram] -> Map PackageName PackageConfig -> IO ()
checkBadPerPackageCompilerPaths [ConfiguredProgram]
compilerPrograms Map PackageName PackageConfig
packagesConfig =
  case [ (PackageName
pkgname, [Char]
progname)
       | let compProgNames :: Set [Char]
compProgNames = [[Char]] -> Set [Char]
forall a. Ord a => [a] -> Set a
Set.fromList ((ConfiguredProgram -> [Char]) -> [ConfiguredProgram] -> [[Char]]
forall a b. (a -> b) -> [a] -> [b]
map ConfiguredProgram -> [Char]
programId [ConfiguredProgram]
compilerPrograms)
       , (PackageName
pkgname, PackageConfig
pkgconf) <- Map PackageName PackageConfig -> [(PackageName, PackageConfig)]
forall k a. Map k a -> [(k, a)]
Map.toList Map PackageName PackageConfig
packagesConfig
       , [Char]
progname <- Map [Char] [Char] -> [[Char]]
forall k a. Map k a -> [k]
Map.keys (MapLast [Char] [Char] -> Map [Char] [Char]
forall k v. MapLast k v -> Map k v
getMapLast (PackageConfig -> MapLast [Char] [Char]
packageConfigProgramPaths PackageConfig
pkgconf))
       , [Char]
progname [Char] -> Set [Char] -> Bool
forall a. Ord a => a -> Set a -> Bool
`Set.member` Set [Char]
compProgNames
       ] of
    [] -> () -> IO ()
forall a. a -> IO a
forall (m :: * -> *) a. Monad m => a -> m a
return ()
    [(PackageName, [Char])]
ps -> BadPerPackageCompilerPaths -> IO ()
forall e a. (HasCallStack, Exception e) => e -> IO a
throwIO ([(PackageName, [Char])] -> BadPerPackageCompilerPaths
BadPerPackageCompilerPaths [(PackageName, [Char])]
ps)

-- | Filter out non-top-level project configs.
onlyTopLevelProvenance :: Set ProjectConfigProvenance -> Set ProjectConfigProvenance
onlyTopLevelProvenance :: Set ProjectConfigProvenance -> Set ProjectConfigProvenance
onlyTopLevelProvenance = (ProjectConfigProvenance -> Bool)
-> Set ProjectConfigProvenance -> Set ProjectConfigProvenance
forall a. (a -> Bool) -> Set a -> Set a
Set.filter ((ProjectConfigProvenance -> Bool)
 -> Set ProjectConfigProvenance -> Set ProjectConfigProvenance)
-> (ProjectConfigProvenance -> Bool)
-> Set ProjectConfigProvenance
-> Set ProjectConfigProvenance
forall a b. (a -> b) -> a -> b
$ \case
  ProjectConfigProvenance
Implicit -> Bool
False
  Explicit ProjectConfigPath
ps -> ProjectConfigPath -> Bool
isTopLevelConfigPath ProjectConfigPath
ps

-- | The maximum amount of fetch jobs that can run concurrently.
-- For instance, this is used to limit the amount of concurrent downloads from
-- hackage, or the amount of concurrent git clones for
-- source-repository-package stanzas.
maxNumFetchJobs :: Int
maxNumFetchJobs :: Int
maxNumFetchJobs = Int
2