diff --git a/.hlint-test.yaml b/.hlint-test.yaml index b8fa9d2df8..45da3c7708 100644 --- a/.hlint-test.yaml +++ b/.hlint-test.yaml @@ -9,6 +9,7 @@ - name: - NoImplicitPrelude - CPP + - NoFieldSelectors - OverloadedLists # Provided from GHC 9.2.1 (base-4.16.0.0): - OverloadedRecordDot diff --git a/.hlint.yaml b/.hlint.yaml index d73992bff0..a6f26f3c2a 100644 --- a/.hlint.yaml +++ b/.hlint.yaml @@ -70,6 +70,7 @@ - GeneralizedNewtypeDeriving - LambdaCase - MultiWayIf + - NoFieldSelectors - OverloadedLists # Provided from GHC 9.2.1 (base-4.16.0.0): - OverloadedRecordDot diff --git a/.stan.toml b/.stan.toml index fc13a8d6ad..a180159435 100644 --- a/.stan.toml +++ b/.stan.toml @@ -25,7 +25,7 @@ # Infinite: base/isSuffixOf # Usage of the 'isSuffixOf' function that hangs on infinite lists [[ignore]] - id = "OBS-STAN-0102-luLR/n-522:30" + id = "OBS-STAN-0102-luLR/n-523:30" # ✦ Category: #Infinite #List # ✦ File: src\Stack\New.hs # @@ -36,7 +36,7 @@ # Infinite: base/isSuffixOf # Usage of the 'isSuffixOf' function that hangs on infinite lists [[ignore]] - id = "OBS-STAN-0102-luLR/n-522:65" + id = "OBS-STAN-0102-luLR/n-523:65" # ✦ Category: #Infinite #List # ✦ File: src\Stack\New.hs # @@ -54,47 +54,47 @@ # Anti-pattern: Data.ByteString.Char8.pack [[ignore]] - id = "OBS-STAN-0203-fki0nd-1134:21" + id = "OBS-STAN-0203-fki0nd-1132:21" # ✦ Description: Usage of 'pack' function that doesn't handle Unicode characters # ✦ Category: #AntiPattern # ✦ File: src\Stack\Build\Execute.hs # -# 1133 ┃ -# 1134 ┃ newProjectRoot <- S8.pack . toFilePath <$> view projectRootL -# 1135 ┃ ^^^^^^^ +# 1131 ┃ +# 1132 ┃ newProjectRoot <- S8.pack . toFilePath <$> view projectRootL +# 1133 ┃ ^^^^^^^ # Anti-pattern: Data.ByteString.Char8.pack [[ignore]] - id = "OBS-STAN-0203-fki0nd-2680:3" + id = "OBS-STAN-0203-fki0nd-2678:3" # ✦ Description: Usage of 'pack' function that doesn't handle Unicode characters # ✦ Category: #AntiPattern # ✦ File: src\Stack\Build\Execute.hs # -# 2679 ┃ -# 2680 ┃ S8.pack . formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%6Q" -# 2681 ┃ ^^^^^^^ +# 2677 ┃ +# 2678 ┃ S8.pack . formatTime defaultTimeLocale "%Y-%m-%dT%H:%M:%S%6Q" +# 2679 ┃ ^^^^^^^ # Anti-pattern: Data.ByteString.Char8.pack [[ignore]] - id = "OBS-STAN-0203-hTeu0Y-380:17" + id = "OBS-STAN-0203-hTeu0Y-381:17" # ✦ Description: Usage of 'pack' function that doesn't handle Unicode characters # ✦ Category: #AntiPattern # ✦ File: src\Stack\Init.hs # -# 379 ┃ -# 380 ┃ commentHelp = BC.pack . intercalate "\n" . map commentLine -# 381 ┃ ^^^^^^^ +# 380 ┃ +# 381 ┃ commentHelp = BC.pack . intercalate "\n" . map commentLine +# 382 ┃ ^^^^^^^ # Anti-pattern: Data.ByteString.Char8.pack [[ignore]] - id = "OBS-STAN-0203-hTeu0Y-397:26" + id = "OBS-STAN-0203-hTeu0Y-398:26" # ✦ Description: Usage of 'pack' function that doesn't handle Unicode characters # ✦ Category: #AntiPattern # ✦ File: src\Stack\Init.hs # -# 396 ┃ -# 397 ┃ <> B.byteString (BC.pack $ concat -# 398 ┃ ^^^^^^^ +# 397 ┃ +# 398 ┃ <> B.byteString (BC.pack $ concat +# 399 ┃ ^^^^^^^ # Anti-pattern: Data.ByteString.Char8.pack [[ignore]] @@ -170,6 +170,28 @@ # 484 ┃ embedFile path) # 485 ┃ +# Anti-pattern: unsafe functions +[[ignore]] + id = "OBS-STAN-0212-H4Wfj/-151:17" +# ✦ Description: Usage of unsafe functions breaks referential transparency +# ✦ Category: #Unsafe #AntiPattern +# ✦ File: src\Stack\Types\BuildOpts.hs +# +# 150 ┃ +# 151 ┃ buildMonoid = undefined :: BuildOptsMonoid +# 152 ┃ ^^^^^^^^^ + +# Anti-pattern: unsafe functions +[[ignore]] + id = "OBS-STAN-0212-H4Wfj/-480:14" +# ✦ Description: Usage of unsafe functions breaks referential transparency +# ✦ Category: #Unsafe #AntiPattern +# ✦ File: src\Stack\Types\BuildOpts.hs +# +# 479 ┃ +# 480 ┃ toMonoid = undefined :: TestOptsMonoid +# 481 ┃ ^^^^^^^^^ + # Anti-pattern: Pattern matching on '_' # Pattern matching on '_' for sum types can create maintainability issues # Stack uses pattern matching on '_' in many places. diff --git a/src/Control/Concurrent/Execute.hs b/src/Control/Concurrent/Execute.hs index 16ae883f85..face054cba 100644 --- a/src/Control/Concurrent/Execute.hs +++ b/src/Control/Concurrent/Execute.hs @@ -98,16 +98,16 @@ runActions threads keepGoing actions withProgress = do <*> newTVarIO Set.empty -- esInAction <*> newTVarIO 0 -- esCompleted <*> pure keepGoing -- esKeepGoing - _ <- async $ withProgress (esCompleted es) (esInAction es) + _ <- async $ withProgress es.esCompleted es.esInAction if threads <= 1 then runActions' es else replicateConcurrently_ threads $ runActions' es - readTVarIO $ esExceptions es + readTVarIO es.esExceptions -- | Sort actions such that those that can't be run concurrently are at -- the end. sortActions :: [Action] -> [Action] -sortActions = sortBy (compareConcurrency `on` actionConcurrency) +sortActions = sortBy (compareConcurrency `on` (.actionConcurrency)) where -- NOTE: Could derive Ord. However, I like to make this explicit so -- that changes to the datatype must consider how it's affecting @@ -139,7 +139,7 @@ runActions' es = loop processActions :: [Action] -> STM (IO ()) processActions actions = do inAction <- readTVar es.esInAction - case break (Set.null . actionDeps) actions of + case break (Set.null . (.actionDeps)) actions of (_, []) -> do check (Set.null inAction) unless es.esKeepGoing $ @@ -149,11 +149,11 @@ runActions' es = loop processAction :: Set ActionId -> [Action] -> Action -> STM (IO ()) processAction inAction otherActions action = do - let concurrency = actionConcurrency action + let concurrency = action.actionConcurrency unless (concurrency == ConcurrencyAllowed) $ check (Set.null inAction) - let action' = actionId action - otherActions' = Set.fromList $ map actionId otherActions + let action' = action.actionId + otherActions' = Set.fromList $ map (.actionId) otherActions remaining = Set.union otherActions' inAction actionContext = ActionContext { acRemaining = remaining @@ -164,7 +164,7 @@ runActions' es = loop modifyTVar es.esInAction (Set.insert action') pure $ do mask $ \restore -> do - eres <- try $ restore $ actionDo action actionContext + eres <- try $ restore $ action.actionDo actionContext atomically $ do modifyTVar es.esInAction (Set.delete action') modifyTVar es.esCompleted (+1) @@ -176,13 +176,13 @@ runActions' es = loop -- | Filter a list of actions to include only those that depend on the given -- action. downstreamActions :: ActionId -> [Action] -> [Action] - downstreamActions aid = filter (\a -> aid `Set.member` actionDeps a) + downstreamActions aid = filter (\a -> aid `Set.member` a.actionDeps) -- | Given two actions (the first specified by its id) yield an action -- equivalent to the second but excluding any dependency on the first action. dropDep :: ActionId -> Action -> Action dropDep action' action = - action { actionDeps = Set.delete action' $ actionDeps action } + action { actionDeps = Set.delete action' action.actionDeps } -- | @IO ()@ lifted into 'STM'. doNothing :: STM (IO ()) diff --git a/src/GHC/Utils/GhcPkg/Main/Compat.hs b/src/GHC/Utils/GhcPkg/Main/Compat.hs index 4ce406e484..13743a2b29 100644 --- a/src/GHC/Utils/GhcPkg/Main/Compat.hs +++ b/src/GHC/Utils/GhcPkg/Main/Compat.hs @@ -5,6 +5,7 @@ {-# LANGUAGE KindSignatures #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiParamTypeClasses #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} {-# LANGUAGE TupleSections #-} @@ -282,19 +283,19 @@ getPkgDatabases globalDb pkgarg pkgDb = do (db_stack, db_to_operate_on) <- getDatabases pkgDb final_stack - let flag_db_stack = [ db | db <- db_stack, location db == Abs pkgDb ] + let flag_db_stack = [ db | db <- db_stack, db.location == Abs pkgDb ] prettyDebugL $ flow "Db stack:" - : map (pretty . location) db_stack + : map (pretty . (.location)) db_stack F.forM_ db_to_operate_on $ \db -> prettyDebugL [ "Modifying:" - , pretty $ location db + , pretty db.location ] prettyDebugL $ flow "Flag db stack:" - : map (pretty . location) flag_db_stack + : map (pretty . (.location)) flag_db_stack pure (db_stack, db_to_operate_on, flag_db_stack) where @@ -310,7 +311,7 @@ getPkgDatabases globalDb pkgarg pkgDb = do then (, Nothing) <$> readDatabase db_path else do let hasPkg :: PackageDB mode -> Bool - hasPkg = not . null . findPackage pkgarg . packages + hasPkg = not . null . findPackage pkgarg . (.packages) openRo (e::IOException) = do db <- readDatabase db_path @@ -332,7 +333,7 @@ getPkgDatabases globalDb pkgarg pkgDb = do -- If the database is not for modification after all, -- drop the write lock as we are already finished with -- the database. - case packageDbLock db of + case db.packageDbLock of GhcPkg.DbOpenReadWrite lock -> liftIO $ GhcPkg.unlockPackageDb lock pure (ro_db, Nothing) @@ -468,14 +469,14 @@ adjustOldFileStylePackageDB :: PackageDB mode -> RIO env (PackageDB mode) adjustOldFileStylePackageDB db = do -- assumes we have not yet established if it's an old style or not mcontent <- liftIO $ - fmap Just (readFile (prjSomeBase toFilePath (location db))) `catchIO` \_ -> pure Nothing + fmap Just (readFile (prjSomeBase toFilePath db.location)) `catchIO` \_ -> pure Nothing case fmap (take 2) mcontent of -- it is an old style and empty db, so look for a dir kind in location.d/ Just "[]" -> do - adjustedDatabasePath <- adjustOldDatabasePath $ location db + adjustedDatabasePath <- adjustOldDatabasePath db.location pure db { location = adjustedDatabasePath } -- it is old style but not empty, we have to bail - Just _ -> prettyThrowIO $ SingleFileDBUnsupported (location db) + Just _ -> prettyThrowIO $ SingleFileDBUnsupported db.location -- probably not old style, carry on as normal Nothing -> pure db @@ -513,7 +514,7 @@ changeNewDB :: -> RIO env () changeNewDB cmds new_db = do new_db' <- adjustOldFileStylePackageDB new_db - prjSomeBase (createDirIfMissing True) (location new_db') + prjSomeBase (createDirIfMissing True) new_db'.location changeDBDir' cmds new_db' changeDBDir' :: @@ -523,7 +524,7 @@ changeDBDir' :: -> RIO env () changeDBDir' cmds db = do mapM_ do_cmd cmds - case packageDbLock db of + case db.packageDbLock of GhcPkg.DbOpenReadWrite lock -> liftIO $ GhcPkg.unlockPackageDb lock where do_cmd (RemovePackage p) = do @@ -532,7 +533,7 @@ changeDBDir' cmds db = do (prettyThrowIO $ CannotParseRelFileBug relFileConfName) pure (parseRelFile relFileConfName) - let file = mapSomeBase (P. relFileConf) (location db) + let file = mapSomeBase (P. relFileConf) db.location prettyDebugL [ "Removing" , pretty file @@ -566,7 +567,7 @@ unregisterPackages globalDb pkgargs pkgDb = do getPkgDatabases globalDb pkgarg pkgDb >>= \case (_, GhcPkg.DbOpenReadWrite (db :: PackageDB GhcPkg.DbReadWrite), _) -> do pks <- do - let pkgs = packages db + let pkgs = db.packages ps = findPackage pkgarg pkgs -- This shouldn't happen if getPkgsByPkgDBs picks the DB correctly. when (null ps) $ cannotFindPackage pkgarg $ Just db @@ -577,7 +578,7 @@ unregisterPackages globalDb pkgargs pkgDb = do -- consider. getPkgsByPkgDBs pkgsByPkgDBs ( pkgsByPkgDB : pkgsByPkgDBs') pkgarg = do let (db, pks') = pkgsByPkgDB - pkgs = packages db + pkgs = db.packages ps = findPackage pkgarg pkgs pks = map installedUnitId ps pkgByPkgDB' = (db, pks <> pks') @@ -595,7 +596,7 @@ unregisterPackages globalDb pkgargs pkgDb = do unregisterPackages' :: (PackageDB GhcPkg.DbReadWrite, [UnitId]) -> RIO env () unregisterPackages' (db, pks) = do - let pkgs = packages db + let pkgs = db.packages cmds = [ RemovePackage pkg | pkg <- pkgs, installedUnitId pkg `elem` pks ] @@ -618,7 +619,7 @@ findPackage pkgarg = filter (pkgarg `matchesPkg`) cannotFindPackage :: PackageArg -> Maybe (PackageDB mode) -> RIO env a cannotFindPackage pkgarg mdb = - prettyThrowIO $ CannotFindPackage pkgarg (location <$> mdb) + prettyThrowIO $ CannotFindPackage pkgarg ((.location) <$> mdb) matches :: GlobPackageIdentifier -> MungedPackageId -> Bool GlobPackageIdentifier pn `matches` pid' = pn == mungedName pid' diff --git a/src/Stack.hs b/src/Stack.hs index 464a7d57bb..e24cb90b1b 100644 --- a/src/Stack.hs +++ b/src/Stack.hs @@ -1,5 +1,6 @@ {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Main Stack tool entry point. @@ -77,9 +78,9 @@ main = do throwIO exitCode Right (globalMonoid, run) -> do global <- globalOptsFromMonoid isTerminal globalMonoid - when (globalLogLevel global == LevelDebug) $ + when (global.globalLogLevel == LevelDebug) $ hPutStrLn stderr versionString' - case globalReExecVersion global of + case global.globalReExecVersion of Just expectVersion -> do expectVersion' <- parseVersionThrowing expectVersion unless (checkVersion MatchMinor expectVersion' stackVersion) $ diff --git a/src/Stack/Build.hs b/src/Stack/Build.hs index a8bc72757b..787d22124c 100644 --- a/src/Stack/Build.hs +++ b/src/Stack/Build.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Build the project. @@ -95,10 +96,10 @@ instance Exception CabalVersionPrettyException -- | Helper for build and install commands buildCmd :: BuildOptsCLI -> RIO Runner () buildCmd opts = do - when (any (("-prof" `elem`) . fromRight [] . parseArgs Escaping) (boptsCLIGhcOptions opts)) $ + when (any (("-prof" `elem`) . fromRight [] . parseArgs Escaping) opts.boptsCLIGhcOptions) $ prettyThrowIO GHCProfOptionInvalid local (over globalOptsL modifyGO) $ - case boptsCLIFileWatch opts of + case opts.boptsCLIFileWatch of FileWatchPoll -> fileWatchPoll (inner . Just) FileWatch -> fileWatch (inner . Just) NoFileWatch -> inner Nothing @@ -110,14 +111,19 @@ buildCmd opts = do Stack.Build.build setLocalFiles -- Read the build command from the CLI and enable it to run modifyGO = - case boptsCLICommand opts of - Test -> set (globalOptsBuildOptsMonoidL.buildOptsMonoidTestsL) (Just True) - Haddock -> - set (globalOptsBuildOptsMonoidL.buildOptsMonoidHaddockL) (Just True) - Bench -> - set (globalOptsBuildOptsMonoidL.buildOptsMonoidBenchmarksL) (Just True) - Install -> - set (globalOptsBuildOptsMonoidL.buildOptsMonoidInstallExesL) (Just True) + case opts.boptsCLICommand of + Test -> set + (globalOptsBuildOptsMonoidL . buildOptsMonoidTestsL) + (Just True) + Haddock -> set + (globalOptsBuildOptsMonoidL . buildOptsMonoidHaddockL) + (Just True) + Bench -> set + (globalOptsBuildOptsMonoidL . buildOptsMonoidBenchmarksL) + (Just True) + Install -> set + (globalOptsBuildOptsMonoidL . buildOptsMonoidInstallExesL) + (Just True) Build -> id -- Default case is just Build -- | Build. @@ -129,25 +135,25 @@ build :: HasEnvConfig env => Maybe (Set (Path Abs File) -> IO ()) -- ^ callback after discovering all local files -> RIO env () build msetLocalFiles = do - mcp <- view $ configL.to configModifyCodePage - ghcVersion <- view $ actualCompilerVersionL.to getGhcVersion + mcp <- view $ configL . to (.configModifyCodePage) + ghcVersion <- view $ actualCompilerVersionL . to getGhcVersion fixCodePage mcp ghcVersion $ do bopts <- view buildOptsL - sourceMap <- view $ envConfigL.to envConfigSourceMap + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) locals <- projectLocalPackages depsLocals <- localDependencies let allLocals = locals <> depsLocals - boptsCli <- view $ envConfigL.to envConfigBuildOptsCLI + boptsCli <- view $ envConfigL . to (.envConfigBuildOptsCLI) -- Set local files, necessary for file watching stackYaml <- view stackYamlL for_ msetLocalFiles $ \setLocalFiles -> do files <- - if boptsCLIWatchAll boptsCli + if boptsCli.boptsCLIWatchAll then sequence [lpFiles lp | lp <- allLocals] else forM allLocals $ \lp -> do - let pn = packageName (lpPackage lp) - case Map.lookup pn (smtTargets $ smTargets sourceMap) of + let pn = lp.lpPackage.packageName + case Map.lookup pn sourceMap.smTargets.smtTargets of Nothing -> pure Set.empty Just (TargetAll _) -> @@ -169,9 +175,9 @@ build msetLocalFiles = do loadPackage sourceMap installedMap - (boptsCLIInitialBuildSteps boptsCli) + boptsCli.boptsCLIInitialBuildSteps - allowLocals <- view $ configL.to configAllowLocals + allowLocals <- view $ configL . to (.configAllowLocals) unless allowLocals $ case justLocals plan of [] -> pure () localsIdents -> throwM $ LocalPackagesPresent localsIdents @@ -180,10 +186,10 @@ build msetLocalFiles = do warnAboutSplitObjs bopts warnIfExecutablesWithSameNameCouldBeOverwritten locals plan - when (boptsPreFetch bopts) $ + when bopts.boptsPreFetch $ preFetch plan - if boptsCLIDryrun boptsCli + if boptsCli.boptsCLIDryrun then printPlan plan else executePlan boptsCli @@ -193,7 +199,7 @@ build msetLocalFiles = do snapshotDumpPkgs localDumpPkgs installedMap - (smtTargets $ smTargets sourceMap) + sourceMap.smTargets.smtTargets plan buildLocalTargets :: @@ -208,7 +214,7 @@ justLocals = map taskProvides . filter ((== Local) . taskLocation) . Map.elems . - planTasks + (.planTasks) checkCabalVersion :: HasEnvConfig env => RIO env () checkCabalVersion = do @@ -286,22 +292,22 @@ warnIfExecutablesWithSameNameCouldBeOverwritten locals plan = do exesToBuild = collect [ (exe, pkgName') - | (pkgName', task) <- Map.toList (planTasks plan) - , TTLocalMutable lp <- [taskType task] - , exe <- (Set.toList . exeComponents . lpComponents) lp + | (pkgName', task) <- Map.toList plan.planTasks + , TTLocalMutable lp <- [task.taskType] + , exe <- (Set.toList . exeComponents . (.lpComponents)) lp ] localExes :: Map Text (NonEmpty PackageName) localExes = collect - [ (exe, packageName pkg) - | pkg <- map lpPackage locals + [ (exe, pkg.packageName) + | pkg <- map (.lpPackage) locals , exe <- Set.toList (buildableExes pkg) ] collect :: Ord k => [(k, v)] -> Map k (NonEmpty v) collect = Map.mapMaybe nonEmpty . Map.fromDistinctAscList . groupSort warnAboutSplitObjs :: HasTerm env => BuildOpts -> RIO env () -warnAboutSplitObjs bopts | boptsSplitObjs bopts = +warnAboutSplitObjs bopts | bopts.boptsSplitObjs = prettyWarnL [ flow "Building with" , style Shell "--split-objs" @@ -365,7 +371,7 @@ checkComponentsBuildable lps = prettyThrowM $ SomeTargetsNotBuildable unbuildable where unbuildable = - [ (packageName (lpPackage lp), c) + [ (lp.lpPackage.packageName, c) | lp <- lps - , c <- Set.toList (lpUnbuildable lp) + , c <- Set.toList lp.lpUnbuildable ] diff --git a/src/Stack/Build/Cache.hs b/src/Stack/Build/Cache.hs index 1b1ded5495..de7ea744df 100644 --- a/src/Stack/Build/Cache.hs +++ b/src/Stack/Build/Cache.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Cache information about previous builds module Stack.Build.Cache @@ -131,7 +132,7 @@ buildCacheFile :: (HasEnvConfig env, MonadReader env m, MonadThrow m) -> m (Path Abs File) buildCacheFile dir component = do cachesDir <- buildCachesDir dir - smh <- view $ envConfigL.to envConfigSourceMapHash + smh <- view $ envConfigL . to (.envConfigSourceMapHash) smDirName <- smRelDir smh let nonLibComponent prefix name = prefix <> "-" <> T.unpack name cacheFileName <- parseRelFile $ case component of @@ -151,8 +152,9 @@ tryGetBuildCache :: HasEnvConfig env tryGetBuildCache dir component = do fp <- buildCacheFile dir component ensureDir $ parent fp - either (const Nothing) (Just . buildCacheTimes) <$> - liftIO (tryAny (Yaml.decodeFileThrow (toFilePath fp))) + let decode :: MonadIO m => m BuildCache + decode = Yaml.decodeFileThrow (toFilePath fp) + either (const Nothing) (Just . (.buildCacheTimes)) <$> liftIO (tryAny decode) -- | Try to read the dirtiness cache for the given package directory. tryGetConfigCache :: @@ -266,7 +268,7 @@ flagCacheKey installed = do installationRoot <- installationRootLocal case installed of Library _ installedInfo -> do - let gid = iliId installedInfo + let gid = installedInfo.iliId pure $ configCacheKey installationRoot (ConfigCacheTypeFlagLibrary gid) Executable ident -> pure $ configCacheKey installationRoot (ConfigCacheTypeFlagExecutable ident) @@ -361,7 +363,7 @@ getPrecompiledCacheKey loc copts buildHaddocks = do -- In Cabal versions 1.22 and later, the configure options contain the -- installed package IDs, which is what we need for a unique hash. See also -- issue: https://github.com/commercialhaskell/stack/issues/1103 - let input = coNoDirs copts + let input = copts.coNoDirs optionsHash = Mem.convert $ hashWith SHA256 $ encodeUtf8 $ tshow input pure $ precompiledCacheKey @@ -396,7 +398,7 @@ writePrecompiledCache exes' <- forM (Set.toList exes) $ \exe -> do name <- parseRelFile $ T.unpack exe stackRootRelative $ - bcoSnapInstallRoot baseConfigOpts bindirSuffix name + baseConfigOpts.bcoSnapInstallRoot bindirSuffix name let precompiled = PrecompiledCache { pcLibrary = mlibpath , pcSubLibs = subLibPaths @@ -411,7 +413,7 @@ writePrecompiledCache where pathFromPkgId stackRootRelative ipid = do ipid' <- parseRelFile $ ghcPkgIdString ipid ++ ".conf" - stackRootRelative $ bcoSnapDB baseConfigOpts ipid' + stackRootRelative $ baseConfigOpts.bcoSnapDB ipid' -- | Check the cache for a precompiled package matching the given configuration. readPrecompiledCache :: @@ -435,7 +437,7 @@ readPrecompiledCache loc copts buildHaddocks = do stackRoot <- view stackRootL let mkAbs' = (stackRoot ) pure PrecompiledCache - { pcLibrary = mkAbs' <$> pcLibrary pc0 - , pcSubLibs = mkAbs' <$> pcSubLibs pc0 - , pcExes = mkAbs' <$> pcExes pc0 + { pcLibrary = mkAbs' <$> pc0.pcLibrary + , pcSubLibs = mkAbs' <$> pc0.pcSubLibs + , pcExes = mkAbs' <$> pc0.pcExes } diff --git a/src/Stack/Build/ConstructPlan.hs b/src/Stack/Build/ConstructPlan.hs index af44f250fb..9e967bbaf5 100644 --- a/src/Stack/Build/ConstructPlan.hs +++ b/src/Stack/Build/ConstructPlan.hs @@ -1,7 +1,8 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ViewPatterns #-} -- | Construct a @Plan@ for how to build module Stack.Build.ConstructPlan @@ -150,12 +151,12 @@ constructPlan <> line econfig <- view envConfigL - globalCabalVersion <- view $ compilerPathsL.to cpCabalVersion + globalCabalVersion <- view $ compilerPathsL . to (.cpCabalVersion) sources <- getSources globalCabalVersion - mcur <- view $ buildConfigL.to bcCurator + mcur <- view $ buildConfigL . to (.bcCurator) pathEnvVar' <- liftIO $ maybe mempty T.pack <$> lookupEnv "PATH" let ctx = mkCtx econfig globalCabalVersion sources mcur pathEnvVar' - targetPackageNames = Map.keys $ smtTargets $ smTargets sourceMap + targetPackageNames = Map.keys sourceMap.smTargets.smtTargets -- Ignore the result of 'getCachedDepOrAddDep'. onTarget = void . getCachedDepOrAddDep inner = mapM_ onTarget targetPackageNames @@ -177,8 +178,8 @@ constructPlan , planUnregisterLocal = mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps , planInstallExes = - if boptsInstallExes (bcoBuildOpts baseConfigOpts0) - || boptsInstallCompilerTool (bcoBuildOpts baseConfigOpts0) + if baseConfigOpts0.bcoBuildOpts.boptsInstallExes + || baseConfigOpts0.bcoBuildOpts.boptsInstallCompilerTool then installExes else Map.empty } @@ -186,18 +187,18 @@ constructPlan stackYaml <- view stackYamlL stackRoot <- view stackRootL isImplicitGlobal <- - view $ configL.to (isPCGlobalProject . configProject) + view $ configL . to (isPCGlobalProject . (.configProject)) prettyThrowM $ ConstructPlanFailed errs stackYaml stackRoot isImplicitGlobal parents - (wanted ctx) + ctx.wanted prunedGlobalDeps where - sourceProject = smProject sourceMap - sourceDeps = smDeps sourceMap + sourceProject = sourceMap.smProject + sourceDeps = sourceMap.smDeps hasBaseInDeps = Map.member (mkPackageName "base") sourceDeps @@ -208,7 +209,7 @@ constructPlan , combinedMap = combineMap sources installedMap , ctxEnvConfig = econfig , callStack = [] - , wanted = Map.keysSet (smtTargets $ smTargets sourceMap) + , wanted = Map.keysSet sourceMap.smTargets.smtTargets , localNames = Map.keysSet sourceProject , mcurator = mcur , pathEnvVar = pathEnvVar' @@ -223,7 +224,7 @@ constructPlan toMaybe (k, Just v) = Just (k, v) takeSubset :: Plan -> RIO env Plan - takeSubset = case boptsCLIBuildSubset $ bcoBuildOptsCLI baseConfigOpts0 of + takeSubset = case baseConfigOpts0.bcoBuildOptsCLI.boptsCLIBuildSubset of BSAll -> pure BSOnlySnapshot -> stripLocals BSOnlyDependencies -> stripNonDeps @@ -232,17 +233,17 @@ constructPlan -- | Strip out anything from the 'Plan' intended for the local database. stripLocals :: Plan -> RIO env Plan stripLocals plan = pure plan - { planTasks = Map.filter checkTask $ planTasks plan + { planTasks = Map.filter checkTask plan.planTasks , planFinals = Map.empty , planUnregisterLocal = Map.empty - , planInstallExes = Map.filter (/= Local) $ planInstallExes plan + , planInstallExes = Map.filter (/= Local) plan.planInstallExes } where checkTask task = taskLocation task == Snap stripNonDeps :: Plan -> RIO env Plan stripNonDeps plan = pure plan - { planTasks = Map.filter checkTask $ planTasks plan + { planTasks = Map.filter checkTask plan.planTasks , planFinals = Map.empty , planInstallExes = Map.empty -- TODO maybe don't disable this? } @@ -250,9 +251,9 @@ constructPlan deps = Map.keysSet sourceDeps checkTask task = taskProvides task `Set.member` missingForDeps providesDep task = pkgName (taskProvides task) `Set.member` deps - tasks = Map.elems $ planTasks plan + tasks = Map.elems plan.planTasks missing = - Map.fromList $ map (taskProvides &&& tcoMissing . taskConfigOpts) tasks + Map.fromList $ map (taskProvides &&& (.taskConfigOpts.tcoMissing)) tasks missingForDeps = flip execState mempty $ for_ tasks $ \task -> when (providesDep task) $ @@ -275,7 +276,7 @@ constructPlan pure plan prunedGlobalDeps :: Map PackageName [PackageName] - prunedGlobalDeps = flip Map.mapMaybe (smGlobal sourceMap) $ + prunedGlobalDeps = flip Map.mapMaybe sourceMap.smGlobal $ \case ReplacedGlobalPackage deps -> let pruned = filter (not . inSourceMap) deps @@ -290,17 +291,17 @@ constructPlan let loadLocalPackage' pp = do lp <- loadLocalPackage pp let lpPackage' = - applyForceCustomBuild globalCabalVersion $ lpPackage lp + applyForceCustomBuild globalCabalVersion lp.lpPackage pure lp { lpPackage = lpPackage' } pPackages <- for sourceProject $ \pp -> do lp <- loadLocalPackage' pp pure $ PSFilePath lp - bopts <- view $ configL.to configBuild + bopts <- view $ configL . to (.configBuild) deps <- for sourceDeps $ \dp -> - case dpLocation dp of + case dp.dpLocation of PLImmutable loc -> pure $ - PSRemote loc (getPLIVersion loc) (dpFromSnapshot dp) (dpCommon dp) + PSRemote loc (getPLIVersion loc) dp.dpFromSnapshot dp.dpCommon PLMutable dir -> do pp <- mkProjectPackage YesPrintWarnings dir (shouldHaddockDeps bopts) lp <- loadLocalPackage' pp @@ -337,10 +338,10 @@ mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps = -- If any new packages were added to the unregister Map, we need to loop -- through the remaining packages again to detect if a transitive dependency -- is being unregistered. - | usAnyAdded us = loop (usToUnregister us) (usKeep us) + | us.usAnyAdded = loop us.usToUnregister us.usKeep -- Nothing added, so we've already caught them all. Return the Map we've -- already calculated. - | otherwise = usToUnregister us + | otherwise = us.usToUnregister where -- Run the unregister checking function on all packages we currently think -- we'll be keeping. @@ -354,20 +355,20 @@ mkUnregisterLocal tasks dirtyReason localDumpPkgs initialBuildSteps = go :: DumpPackage -> State UnregisterState () go dp = do us <- get - case maybeUnregisterReason (usToUnregister us) ident mParentLibId deps of + case maybeUnregisterReason us.usToUnregister ident mParentLibId deps of -- Not unregistering, add it to the keep list. - Nothing -> put us { usKeep = dp : usKeep us } + Nothing -> put us { usKeep = dp : us.usKeep } -- Unregistering, add it to the unregister Map; and indicate that a -- package was in fact added to the unregister Map, so we loop again. Just reason -> put us - { usToUnregister = Map.insert gid (ident, reason) (usToUnregister us) + { usToUnregister = Map.insert gid (ident, reason) us.usToUnregister , usAnyAdded = True } where - gid = dpGhcPkgId dp - ident = dpPackageIdent dp + gid = dp.dpGhcPkgId + ident = dp.dpPackageIdent mParentLibId = dpParentLibIdent dp - deps = dpDepends dp + deps = dp.dpDepends maybeUnregisterReason :: Map GhcPkgId (PackageIdentifier, Text) @@ -439,7 +440,7 @@ addFinal lp package isAllInOne buildHaddocks = do let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) - (baseConfigOpts ctx) + ctx.baseConfigOpts allDeps True -- local Mutable @@ -448,10 +449,10 @@ addFinal lp package isAllInOne buildHaddocks = do , taskPresent = present , taskType = TTLocalMutable lp , taskAllInOne = isAllInOne - , taskCachePkgSrc = CacheSrcLocal (toFilePath (parent (lpCabalFile lp))) + , taskCachePkgSrc = CacheSrcLocal (toFilePath (parent lp.lpCabalFile)) , taskBuildTypeConfig = packageBuildTypeConfig package } - tell mempty { wFinals = Map.singleton (packageName package) res } + tell mempty { wFinals = Map.singleton package.packageName res } -- | Given a 'PackageName', adds all of the build tasks to build the package, if -- needed. First checks if the package name is in the library map. @@ -486,15 +487,15 @@ checkCallStackAndAddDep :: -> M (Either ConstructPlanException AddDepRes) checkCallStackAndAddDep name = do ctx <- ask - res <- if name `elem` callStack ctx + res <- if name `elem` ctx.callStack then do logDebugPlanS "checkCallStackAndAddDep" $ "Detected cycle " <> fromPackageName name <> ": " - <> fromString (show $ map packageNameString (callStack ctx)) - pure $ Left $ DependencyCycleDetected $ name : callStack ctx - else case Map.lookup name $ combinedMap ctx of + <> fromString (show $ map packageNameString ctx.callStack) + pure $ Left $ DependencyCycleDetected $ name : ctx.callStack + else case Map.lookup name ctx.combinedMap of -- TODO look up in the package index and see if there's a -- recommendation available Nothing -> do @@ -505,7 +506,7 @@ checkCallStackAndAddDep name = do pure $ Left $ UnknownPackage name Just packageInfo -> -- Add the current package name to the head of the call stack. - local (\ctx' -> ctx' { callStack = name : callStack ctx' }) $ + local (\ctx' -> ctx' { callStack = name : ctx'.callStack }) $ addDep name packageInfo updateLibMap name res pure res @@ -534,7 +535,7 @@ addDep name packageInfo = do Nothing -> do -- This could happen for GHC boot libraries missing from -- Hackage. - cs <- asks (NE.nonEmpty . callStack) + cs <- asks (NE.nonEmpty . (.callStack)) cs' <- maybe (throwIO CallStackEmptyBug) (pure . NE.tail) @@ -562,11 +563,11 @@ addDep name packageInfo = do -- executables to the collected output. tellExecutables :: PackageName -> PackageSource -> M () tellExecutables _name (PSFilePath lp) - | lpWanted lp = tellExecutablesPackage Local $ lpPackage lp + | lp.lpWanted = tellExecutablesPackage Local lp.lpPackage | otherwise = pure () -- Ignores ghcOptions because they don't matter for enumerating executables. tellExecutables name (PSRemote pkgloc _version _fromSnapshot cp) = - tellExecutablesUpstream name (pure $ Just pkgloc) Snap (cpFlags cp) + tellExecutablesUpstream name (pure $ Just pkgloc) Snap cp.cpFlags -- | For a given 'PackageName' value, known to be immutable, adds relevant -- executables to the collected output. @@ -578,10 +579,10 @@ tellExecutablesUpstream :: -> M () tellExecutablesUpstream name retrievePkgLoc loc flags = do ctx <- ask - when (name `Set.member` wanted ctx) $ do + when (name `Set.member` ctx.wanted) $ do mPkgLoc <- retrievePkgLoc forM_ mPkgLoc $ \pkgLoc -> do - p <- loadPackage ctx pkgLoc flags [] [] + p <- ctx.loadPackage pkgLoc flags [] [] tellExecutablesPackage loc p -- | For given 'InstallLocation' and 'Package' values, adds relevant executables @@ -590,17 +591,17 @@ tellExecutablesUpstream name retrievePkgLoc loc flags = do -- executables are those executables that are wanted executables. tellExecutablesPackage :: InstallLocation -> Package -> M () tellExecutablesPackage loc p = do - cm <- asks combinedMap + cm <- asks (.combinedMap) -- Determine which components are enabled so we know which ones to copy let myComps = - case Map.lookup (packageName p) cm of + case Map.lookup p.packageName cm of Nothing -> assert False Set.empty Just (PIOnlyInstalled _ _) -> Set.empty Just (PIOnlySource ps) -> goSource ps Just (PIBoth ps _) -> goSource ps goSource (PSFilePath lp) - | lpWanted lp = exeComponents (lpComponents lp) + | lp.lpWanted = exeComponents lp.lpComponents | otherwise = Set.empty goSource PSRemote{} = Set.empty @@ -627,18 +628,18 @@ installPackage name ps minstalled = do "Doing all-in-one build for upstream package " <> fromPackageName name <> "." - package <- loadPackage - ctx pkgLoc (cpFlags cp) (cpGhcOptions cp) (cpCabalConfigOpts cp) - resolveDepsAndInstall True (cpHaddocks cp) ps package minstalled + package <- ctx.loadPackage + pkgLoc cp.cpFlags cp.cpGhcOptions cp.cpCabalConfigOpts + resolveDepsAndInstall True cp.cpHaddocks ps package minstalled PSFilePath lp -> do - case lpTestBench lp of + case lp.lpTestBench of Nothing -> do logDebugPlanS "installPackage" $ "No test or bench component for " <> fromPackageName name <> " so doing an all-in-one build." resolveDepsAndInstall - True (lpBuildHaddocks lp) ps (lpPackage lp) minstalled + True lp.lpBuildHaddocks ps lp.lpPackage minstalled Just tb -> do -- Attempt to find a plan which performs an all-in-one build. Ignore -- the writer action + reset the state if it fails. @@ -659,10 +660,10 @@ installPackage name ps minstalled = do -- test/benchmark failure could prevent library from being -- available to its dependencies but when it's already available -- it's OK to do that - splitRequired <- expectedTestOrBenchFailures <$> asks mcurator + splitRequired <- expectedTestOrBenchFailures <$> asks (.mcurator) let isAllInOne = not splitRequired adr <- installPackageGivenDeps - isAllInOne (lpBuildHaddocks lp) ps tb minstalled deps + isAllInOne lp.lpBuildHaddocks ps tb minstalled deps let finalAllInOne = case adr of ADRToInstall _ | splitRequired -> False _ -> True @@ -680,7 +681,7 @@ installPackage name ps minstalled = do -- Otherwise, fall back on building the tests / benchmarks in a -- separate step. res' <- resolveDepsAndInstall - False (lpBuildHaddocks lp) ps (lpPackage lp) minstalled + False lp.lpBuildHaddocks ps lp.lpPackage minstalled when (isRight res') $ do -- Insert it into the map so that it's available for addFinal. updateLibMap name res' @@ -689,8 +690,8 @@ installPackage name ps minstalled = do where expectedTestOrBenchFailures maybeCurator = fromMaybe False $ do curator <- maybeCurator - pure $ Set.member name (curatorExpectTestFailure curator) || - Set.member name (curatorExpectBenchmarkFailure curator) + pure $ Set.member name curator.curatorExpectTestFailure + || Set.member name curator.curatorExpectBenchmarkFailure resolveDepsAndInstall :: Bool @@ -727,7 +728,7 @@ installPackageGivenDeps :: -> M AddDepRes installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled (missing, present, minMutable) = do - let name = packageName package + let name = package.packageName ctx <- ask mRightVersionInstalled <- case (minstalled, Set.null missing) of (Just installed, True) -> do @@ -752,7 +753,7 @@ installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled let allDeps = Map.union present missing' in configureOpts (view envConfigL ctx) - (baseConfigOpts ctx) + ctx.baseConfigOpts allDeps (psLocal ps) mutable @@ -772,7 +773,7 @@ installPackageGivenDeps isAllInOne buildHaddocks ps package minstalled -- | Is the build type of the package Configure packageBuildTypeConfig :: Package -> Bool -packageBuildTypeConfig pkg = packageBuildType pkg == Configure +packageBuildTypeConfig pkg = pkg.packageBuildType == Configure -- Update response in the library map. If it is an error, and there's already an -- error about cyclic dependencies, prefer the cyclic error. @@ -846,7 +847,7 @@ processDep pkgId name value = do Couldn'tResolveItsDependencies version pure $ Left (name, (range, mLatestApplicable, bd)) Right adr - | isDepTypeLibrary (dvType value) && not (adrHasLibrary adr) -> + | isDepTypeLibrary value.dvType && not (adrHasLibrary adr) -> pure $ Left (name, (range, Nothing, HasNoLibrary)) Right adr -> do addParent @@ -861,7 +862,7 @@ processDep pkgId name value = do ) ) where - range = dvVersionRange value + range = value.dvVersionRange version = pkgVersion pkgId -- Update the parents map, for later use in plan construction errors -- - see 'getShortestDepsPath'. @@ -899,8 +900,8 @@ adrInRange :: adrInRange pkgId name range adr = if adrVersion adr `withinRange` range then pure True else do - allowNewer <- view $ configL.to configAllowNewer - allowNewerDeps <- view $ configL.to configAllowNewerDeps + allowNewer <- view $ configL . to (.configAllowNewer) + allowNewerDeps <- view $ configL . to (.configAllowNewerDeps) if allowNewer then case allowNewerDeps of Nothing -> do @@ -1008,7 +1009,7 @@ checkDirtiness ps installed package present buildHaddocks = do moldOpts <- runRIO ctx $ tryGetFlagCache installed let configOpts = configureOpts (view envConfigL ctx) - (baseConfigOpts ctx) + ctx.baseConfigOpts present (psLocal ps) (installLocationIsMutable $ psLocation ps) -- should be Local i.e. mutable always @@ -1019,11 +1020,11 @@ checkDirtiness ps installed package present buildHaddocks = do , configCacheComponents = case ps of PSFilePath lp -> - Set.map (encodeUtf8 . renderComponent) $ lpComponents lp + Set.map (encodeUtf8 . renderComponent) lp.lpComponents PSRemote{} -> Set.empty , configCacheHaddock = buildHaddocks , configCachePkgSrc = toCachePkgSrc ps - , configCachePathEnvVar = pathEnvVar ctx + , configCachePathEnvVar = ctx.pathEnvVar } config = view configL ctx mreason <- @@ -1044,21 +1045,21 @@ checkDirtiness ps installed package present buildHaddocks = do case mreason of Nothing -> pure False Just reason -> do - tell mempty { wDirty = Map.singleton (packageName package) reason } + tell mempty { wDirty = Map.singleton package.packageName reason } pure True describeConfigDiff :: Config -> ConfigCache -> ConfigCache -> Maybe Text describeConfigDiff config old new - | configCachePkgSrc old /= configCachePkgSrc new = Just $ + | old.configCachePkgSrc /= new.configCachePkgSrc = Just $ "switching from " <> - pkgSrcName (configCachePkgSrc old) <> " to " <> - pkgSrcName (configCachePkgSrc new) - | not (configCacheDeps new `Set.isSubsetOf` configCacheDeps old) = + pkgSrcName old.configCachePkgSrc <> " to " <> + pkgSrcName new.configCachePkgSrc + | not (new.configCacheDeps `Set.isSubsetOf` old.configCacheDeps) = Just "dependencies changed" | not $ Set.null newComponents = Just $ "components added: " `T.append` T.intercalate ", " (map (decodeUtf8With lenientDecode) (Set.toList newComponents)) - | not (configCacheHaddock old) && configCacheHaddock new = + | not old.configCacheHaddock && new.configCacheHaddock = Just "rebuilding with haddocks" | oldOpts /= newOpts = Just $ T.pack $ concat [ "flags changed from " @@ -1091,12 +1092,12 @@ describeConfigDiff config old new isKeeper = (== "-fhpc") -- more to be added later userOpts = filter (not . isStackOpt) - . (if configRebuildGhcOptions config + . (if config.configRebuildGhcOptions then id else stripGhcOptions) . map T.pack . (\(ConfigureOpts x y) -> x ++ y) - . configCacheOpts + . (.configCacheOpts) where -- options set by Stack isStackOpt :: Text -> Bool @@ -1130,20 +1131,20 @@ describeConfigDiff config old new removeMatching xs ys = (xs, ys) newComponents = - configCacheComponents new `Set.difference` configCacheComponents old + new.configCacheComponents `Set.difference` old.configCacheComponents pkgSrcName (CacheSrcLocal fp) = T.pack fp pkgSrcName CacheSrcUpstream = "upstream source" psForceDirty :: PackageSource -> Bool -psForceDirty (PSFilePath lp) = lpForceDirty lp +psForceDirty (PSFilePath lp) = lp.lpForceDirty psForceDirty PSRemote{} = False psDirty :: (MonadIO m, HasEnvConfig env, MonadReader env m) => PackageSource -> m (Maybe (Set FilePath)) -psDirty (PSFilePath lp) = runMemoizedWith $ lpDirtyFiles lp +psDirty (PSFilePath lp) = runMemoizedWith lp.lpDirtyFiles psDirty PSRemote {} = pure Nothing -- files never change in a remote package psLocal :: PackageSource -> Bool @@ -1172,14 +1173,14 @@ checkAndWarnForUnknownTools p = do notOnPath toolName = MaybeT $ do let settings = minimalEnvSettings { esIncludeLocals = True } config <- view configL - menv <- liftIO $ configProcessContextSettings config settings + menv <- liftIO $ config.configProcessContextSettings settings eFound <- runRIO menv $ findExecutable $ T.unpack toolName skipIf $ isRight eFound -- From Cabal 1.12, build-tools can specify another executable in the same -- package. notPackageExe toolName = - MaybeT $ skipIf $ collectionMember toolName (packageExecutables p) - warn name = MaybeT . pure . Just $ ToolWarning (ExeName name) (packageName p) + MaybeT $ skipIf $ collectionMember toolName p.packageExecutables + warn name = MaybeT . pure . Just $ ToolWarning (ExeName name) p.packageName skipIf p' = pure $ if p' then Nothing else Just () toolWarningText :: ToolWarning -> StyleDoc @@ -1196,7 +1197,7 @@ inSnapshot :: PackageName -> Version -> M Bool inSnapshot name version = do ctx <- ask pure $ fromMaybe False $ do - ps <- Map.lookup name (combinedMap ctx) + ps <- Map.lookup name ctx.combinedMap case ps of PIOnlySource (PSRemote _ srcVersion FromSnapshot _) -> pure $ srcVersion == version @@ -1218,7 +1219,7 @@ logDebugPlanS :: -> Utf8Builder -> m () logDebugPlanS s msg = do - debugPlan <- view $ globalOptsL.to globalPlanInLog + debugPlan <- view $ globalOptsL . to (.globalPlanInLog) when debugPlan $ logDebugS s msg -- | A function to yield a 'PackageInfo' value from: (1) a 'PackageSource' diff --git a/src/Stack/Build/Execute.hs b/src/Stack/Build/Execute.hs index 572fc7d55d..e4a8692ab8 100644 --- a/src/Stack/Build/Execute.hs +++ b/src/Stack/Build/Execute.hs @@ -64,7 +64,6 @@ import Distribution.Types.UnqualComponentName ( mkUnqualComponentName ) import Distribution.Verbosity ( showForCabal ) import Distribution.Version ( mkVersion ) -import GHC.Records ( getField ) import Path ( PathException, (), addExtension, filename , isProperPrefixOf, parent, parseRelDir, parseRelFile @@ -226,17 +225,17 @@ preFetch plan <> mconcat (L.intersperse ", " (display <$> Set.toList pkgLocs)) fetchPackages pkgLocs where - pkgLocs = Set.unions $ map toPkgLoc $ Map.elems $ planTasks plan + pkgLocs = Set.unions $ map toPkgLoc $ Map.elems plan.planTasks toPkgLoc task = - case taskType task of + case task.taskType of TTLocalMutable{} -> Set.empty TTRemotePackage _ _ pkgloc -> Set.singleton pkgloc -- | Print a description of build plan for human consumption. printPlan :: (HasRunner env, HasTerm env) => Plan -> RIO env () printPlan plan = do - case Map.elems $ planUnregisterLocal plan of + case Map.elems plan.planUnregisterLocal of [] -> prettyInfo $ flow "No packages would be unregistered." <> line @@ -250,7 +249,7 @@ printPlan plan = do <> bulletedList (map unregisterMsg xs) <> line - case Map.elems $ planTasks plan of + case Map.elems plan.planTasks of [] -> prettyInfo $ flow "Nothing to build." <> line @@ -263,8 +262,8 @@ printPlan plan = do let hasTests = not . Set.null . testComponents . taskComponents hasBenches = not . Set.null . benchComponents . taskComponents - tests = Map.elems $ Map.filter hasTests $ planFinals plan - benches = Map.elems $ Map.filter hasBenches $ planFinals plan + tests = Map.elems $ Map.filter hasTests plan.planFinals + benches = Map.elems $ Map.filter hasBenches plan.planFinals unless (null tests) $ do prettyInfo $ @@ -280,7 +279,7 @@ printPlan plan = do <> bulletedList (map displayTask benches) <> line - case Map.toList $ planInstallExes plan of + case Map.toList plan.planInstallExes of [] -> prettyInfo $ flow "No executables to be installed." <> line @@ -310,8 +309,8 @@ displayTask task = fillSep $ ) <> "," , "source=" - <> ( case taskType task of - TTLocalMutable lp -> pretty $ parent $ lpCabalFile lp + <> ( case task.taskType of + TTLocalMutable lp -> pretty $ parent lp.lpCabalFile TTRemotePackage _ _ pl -> fromString $ T.unpack $ textDisplay pl ) <> if Set.null missing @@ -325,7 +324,7 @@ displayTask task = fillSep $ | not $ Set.null missing ] where - missing = tcoMissing $ taskConfigOpts task + missing = task.taskConfigOpts.tcoMissing data ExecuteEnv = ExecuteEnv { eeInstallLock :: !(MVar ()) @@ -515,13 +514,13 @@ withExecuteEnv bopts boptsCli baseConfigOpts locals globalPackages snapshotPacka setupExe <- getSetupExe setupHs setupShimHs tmpdir cabalPkgVer <- view cabalVersionL - globalDB <- view $ compilerPathsL . to cpGlobalDB + globalDB <- view $ compilerPathsL . to (.cpGlobalDB) snapshotPackagesTVar <- liftIO $ newTVarIO (toDumpPackagesByGhcPkgId snapshotPackages) localPackagesTVar <- liftIO $ newTVarIO (toDumpPackagesByGhcPkgId localPackages) logFilesTChan <- liftIO $ atomically newTChan - let totalWanted = length $ filter lpWanted locals + let totalWanted = length $ filter (.lpWanted) locals pathEnvVar <- liftIO $ maybe mempty T.pack <$> lookupEnv "PATH" inner ExecuteEnv { eeBuildOpts = bopts @@ -550,10 +549,10 @@ withExecuteEnv bopts boptsCli baseConfigOpts locals globalPackages snapshotPacka , eePathEnvVar = pathEnvVar } `finally` dumpLogs logFilesTChan totalWanted where - toDumpPackagesByGhcPkgId = Map.fromList . map (\dp -> (dpGhcPkgId dp, dp)) + toDumpPackagesByGhcPkgId = Map.fromList . map (\dp -> (dp.dpGhcPkgId, dp)) createTempDirFunction - | boptsKeepTmpFiles bopts = withKeepSystemTempDir + | bopts.boptsKeepTmpFiles = withKeepSystemTempDir | otherwise = withSystemTempDir dumpLogs :: TChan (Path Abs Dir, Path Abs File) -> Int -> RIO env () @@ -563,7 +562,7 @@ withExecuteEnv bopts boptsCli baseConfigOpts locals globalPackages snapshotPacka -- No log files generated, nothing to dump [] -> pure () firstLog:_ -> do - toDump <- view $ configL . to configDumpLogs + toDump <- view $ configL . to (.configDumpLogs) case toDump of DumpAllLogs -> mapM_ (dumpLog "") allLogs DumpWarningLogs -> mapM_ dumpLogIfWarning allLogs @@ -696,10 +695,10 @@ executePlan mlargestPackageName (executePlan' installedMap targets plan) - copyExecutables (planInstallExes plan) + copyExecutables plan.planInstallExes config <- view configL - menv' <- liftIO $ configProcessContextSettings config EnvSettings + menv' <- liftIO $ config.configProcessContextSettings EnvSettings { esIncludeLocals = True , esIncludeGhcPackagePath = True , esStackExe = True @@ -707,13 +706,13 @@ executePlan , esKeepGhcRts = False } withProcessContext menv' $ - forM_ (boptsCLIExec boptsCli) $ \(cmd, args) -> + forM_ boptsCli.boptsCLIExec $ \(cmd, args) -> proc cmd args runProcess_ where mlargestPackageName = Set.lookupMax $ Set.map (length . packageNameString) $ - Map.keysSet (planTasks plan) <> Map.keysSet (planFinals plan) + Map.keysSet plan.planTasks <> Map.keysSet plan.planFinals copyExecutables :: HasEnvConfig env @@ -723,10 +722,10 @@ copyExecutables exes | Map.null exes = pure () copyExecutables exes = do snapBin <- ( bindirSuffix) <$> installationRootDeps localBin <- ( bindirSuffix) <$> installationRootLocal - compilerSpecific <- boptsInstallCompilerTool <$> view buildOptsL + compilerSpecific <- (.boptsInstallCompilerTool) <$> view buildOptsL destDir <- if compilerSpecific then bindirCompilerTools - else view $ configL . to configLocalBin + else view $ configL . to (.configLocalBin) ensureDir destDir destDir' <- liftIO . D.canonicalizePath . toFilePath $ destDir @@ -801,22 +800,22 @@ executePlan' :: HasEnvConfig env -> ExecuteEnv -> RIO env () executePlan' installedMap0 targets plan ee = do - when (toCoverage $ boptsTestOpts ee.eeBuildOpts) deleteHpcReports + when ee.eeBuildOpts.boptsTestOpts.toCoverage deleteHpcReports cv <- view actualCompilerVersionL - case nonEmpty . Map.toList $ planUnregisterLocal plan of + case nonEmpty $ Map.toList plan.planUnregisterLocal of Nothing -> pure () Just ids -> do localDB <- packageDatabaseLocal unregisterPackages cv localDB ids liftIO $ atomically $ modifyTVar' ee.eeLocalDumpPkgs $ \initMap -> - foldl' (flip Map.delete) initMap $ Map.keys (planUnregisterLocal plan) + foldl' (flip Map.delete) initMap $ Map.keys plan.planUnregisterLocal run <- askRunInIO -- If running tests concurrently with each other, then create an MVar -- which is empty while each test is being run. - concurrentTests <- view $ configL . to configConcurrentTests + concurrentTests <- view $ configL . to (.configConcurrentTests) mtestLock <- if concurrentTests then pure Nothing else Just <$> liftIO (newMVar ()) @@ -826,12 +825,12 @@ executePlan' installedMap0 targets plan ee = do (Map.mapMissing (\_ b -> (Just b, Nothing))) (Map.mapMissing (\_ f -> (Nothing, Just f))) (Map.zipWithMatched (\_ b f -> (Just b, Just f))) - (planTasks plan) - (planFinals plan) - threads <- view $ configL . to configJobs + plan.planTasks + plan.planFinals + threads <- view $ configL . to (.configJobs) let keepGoing = fromMaybe - (not (Map.null (planFinals plan))) - (boptsKeepGoing ee.eeBuildOpts) + (not (Map.null plan.planFinals)) + ee.eeBuildOpts.boptsKeepGoing terminal <- view terminalL terminalWidth <- view termWidthL errs <- liftIO $ runActions threads keepGoing actions $ @@ -851,7 +850,7 @@ executePlan' installedMap0 targets plan ee = do nowBuilding names = mconcat $ ": " : L.intersperse ", " (map fromPackageName names) - progressFormat = boptsProgressBar ee.eeBuildOpts + progressFormat = ee.eeBuildOpts.boptsProgressBar progressLine prev' total' = "Progress " <> display prev' <> "/" <> display total' @@ -871,13 +870,13 @@ executePlan' installedMap0 targets plan ee = do pure done loop done when (total > 1) $ loop 0 - when (toCoverage $ boptsTestOpts ee.eeBuildOpts) $ do + when ee.eeBuildOpts.boptsTestOpts.toCoverage $ do generateHpcUnifiedReport generateHpcMarkupIndex unless (null errs) $ prettyThrowM $ ExecutionFailure errs - when (boptsHaddock ee.eeBuildOpts) $ do - if boptsHaddockForHackage ee.eeBuildOpts + when ee.eeBuildOpts.boptsHaddock $ do + if ee.eeBuildOpts.boptsHaddockForHackage then generateLocalHaddockForHackageArchives ee.eeLocals else do @@ -894,15 +893,15 @@ executePlan' installedMap0 targets plan ee = do ee.eeBaseConfigOpts ee.eeGlobalDumpPkgs snapshotDumpPkgs - when (boptsOpenHaddocks ee.eeBuildOpts) $ do + when ee.eeBuildOpts.boptsOpenHaddocks $ do let planPkgs, localPkgs, installedPkgs, availablePkgs :: Map PackageName (PackageIdentifier, InstallLocation) planPkgs = - Map.map (taskProvides &&& taskLocation) (planTasks plan) + Map.map (taskProvides &&& taskLocation) plan.planTasks localPkgs = Map.fromList - [ (packageName p, (packageIdentifier p, Local)) - | p <- map lpPackage ee.eeLocals + [ (p.packageName, (packageIdentifier p, Local)) + | p <- map (.lpPackage) ee.eeLocals ] installedPkgs = Map.map (swap . second installedPackageIdentifier) installedMap' @@ -915,8 +914,7 @@ executePlan' installedMap0 targets plan ee = do installedMap' = Map.difference installedMap0 $ Map.fromList $ map (\(ident, _) -> (pkgName ident, ())) - $ Map.elems - $ planUnregisterLocal plan + $ Map.elems plan.planUnregisterLocal unregisterPackages :: (HasCompiler env, HasPlatform env, HasProcessContext env, HasTerm env) @@ -979,7 +977,7 @@ toActions installedMap mtestLock runInBase ee (mbuild, mfinal) = [ Action { actionId = ActionId (taskProvides task) ATBuild , actionDeps = - Set.map (`ActionId` ATBuild) (tcoMissing task.taskConfigOpts) + Set.map (`ActionId` ATBuild) task.taskConfigOpts.tcoMissing , actionDo = \ac -> runInBase $ singleBuild ac ee task installedMap False , actionConcurrency = ConcurrencyAllowed @@ -993,7 +991,7 @@ toActions installedMap mtestLock runInBase ee (mbuild, mfinal) = else (:) Action { actionId = ActionId pkgId ATBuildFinal , actionDeps = addBuild - (Set.map (`ActionId` ATBuild) (tcoMissing task.taskConfigOpts)) + (Set.map (`ActionId` ATBuild) task.taskConfigOpts.tcoMissing) , actionDo = \ac -> runInBase $ singleBuild ac ee task installedMap True , actionConcurrency = ConcurrencyAllowed @@ -1047,9 +1045,9 @@ toActions installedMap mtestLock runInBase ee (mbuild, mfinal) = Just _ -> Set.insert $ ActionId pkgId ATBuild withLock Nothing f = f withLock (Just lock) f = withMVar lock $ \() -> f - bopts = eeBuildOpts ee - topts = boptsTestOpts bopts - beopts = boptsBenchmarkOpts bopts + bopts = ee.eeBuildOpts + topts = bopts.boptsTestOpts + beopts = bopts.boptsBenchmarkOpts -- | Generate the ConfigCache getConfigCache :: @@ -1081,7 +1079,7 @@ getConfigCache ee task installedMap enableTest enableBench = do Nothing -- Expect to instead find it in installedMap if it's -- an initialBuildSteps target. - | boptsCLIInitialBuildSteps ee.eeBuildOptsCLI && taskIsTarget task + | ee.eeBuildOptsCLI.boptsCLIInitialBuildSteps && taskIsTarget task , Just (_, installed) <- Map.lookup (pkgName ident) installedMap -> pure $ installedToGhcPkgId ident installed Just installed -> pure $ installedToGhcPkgId ident installed @@ -1096,13 +1094,13 @@ getConfigCache ee task installedMap enableTest enableBench = do allDeps = Set.fromList $ Map.elems missing' ++ Map.elems task.taskPresent cache = ConfigCache { configCacheOpts = opts - { coNoDirs = coNoDirs opts ++ map T.unpack extra + { coNoDirs = opts.coNoDirs ++ map T.unpack extra } , configCacheDeps = allDeps , configCacheComponents = case task.taskType of TTLocalMutable lp -> - Set.map (encodeUtf8 . renderComponent) $ lpComponents lp + Set.map (encodeUtf8 . renderComponent) lp.lpComponents TTRemotePackage{} -> Set.empty , configCacheHaddock = task.taskBuildHaddock , configCachePkgSrc = task.taskCachePkgSrc @@ -1137,7 +1135,7 @@ ensureConfig newConfigCache pkgDir ee announce cabal cabalfp task = do taskAnyMissingHackEnabled <- view $ actualCompilerVersionL . to getGhcVersion . to (< mkVersion [8, 4]) needConfig <- - if boptsReconfigure ee.eeBuildOpts + if ee.eeBuildOpts.boptsReconfigure -- The reason 'taskAnyMissing' is necessary is a bug in Cabal. See: -- . -- The problem is that Cabal may end up generating the same package ID @@ -1171,9 +1169,9 @@ ensureConfig newConfigCache pkgDir ee announce cabal cabalfp task = do || mOldCabalMod /= Just newCabalMod || mOldSetupConfigMod /= newSetupConfigMod || mOldProjectRoot /= Just newProjectRoot - let ConfigureOpts dirs nodirs = configCacheOpts newConfigCache + let ConfigureOpts dirs nodirs = newConfigCache.configCacheOpts - when (taskBuildTypeConfig task) $ + when task.taskBuildTypeConfig $ -- When build-type is Configure, we need to have a configure script in the -- local directory. If it doesn't exist, build it with autoreconf -i. See: -- https://github.com/commercialhaskell/stack/issues/3534 @@ -1183,11 +1181,11 @@ ensureConfig newConfigCache pkgDir ee announce cabal cabalfp task = do deleteCaches pkgDir announce cp <- view compilerPathsL - let (GhcPkgExe pkgPath) = cpPkg cp + let (GhcPkgExe pkgPath) = cp.cpPkg let programNames = case cpWhich cp of Ghc -> - [ ("ghc", toFilePath (cpCompiler cp)) + [ ("ghc", toFilePath cp.cpCompiler) , ("ghc-pkg", toFilePath pkgPath) ] exes <- forM programNames $ \(name, file) -> do @@ -1204,7 +1202,7 @@ ensureConfig newConfigCache pkgDir ee announce cabal cabalfp task = do ] -- Only write the cache for local packages. Remote packages are built in a -- temporary directory so the cache would never be used anyway. - case taskType task of + case task.taskType of TTLocalMutable{} -> writeConfigCache pkgDir newConfigCache TTRemotePackage{} -> pure () writeCabalMod pkgDir newCabalMod @@ -1221,7 +1219,7 @@ packageNamePrefix :: ExecuteEnv -> PackageName -> String packageNamePrefix ee name' = let name = packageNameString name' paddedName = - case eeLargestPackageName ee of + case ee.eeLargestPackageName of Nothing -> name Just len -> assert (len >= length name) $ take len $ name ++ L.repeat ' ' @@ -1346,7 +1344,7 @@ withSingleContext wanted = case taskType of - TTLocalMutable lp -> lpWanted lp + TTLocalMutable lp -> lp.lpWanted TTRemotePackage{} -> False -- Output to the console if this is the last task, and the user asked to build @@ -1368,9 +1366,9 @@ withSingleContext withPackage inner = case taskType of TTLocalMutable lp -> do - let root = parent $ lpCabalFile lp + let root = parent lp.lpCabalFile withLockedDistDir prettyAnnounce root $ - inner (lpPackage lp) (lpCabalFile lp) root + inner lp.lpPackage lp.lpCabalFile root TTRemotePackage _ package pkgloc -> do suffix <- parseRelDir $ packageIdentifierString $ packageIdentifier package @@ -1403,8 +1401,8 @@ withSingleContext -- If the user requested interleaved output, dump to the console with a -- prefix. - | boptsInterleavedOutput ee.eeBuildOpts = inner $ - OTConsole $ Just $ fromString (packageNamePrefix ee $ packageName package) + | ee.eeBuildOpts.boptsInterleavedOutput = inner $ + OTConsole $ Just $ fromString (packageNamePrefix ee package.packageName) -- Neither condition applies, dump to a file. | otherwise = do @@ -1414,7 +1412,7 @@ withSingleContext -- We only want to dump logs for local non-dependency packages case taskType of - TTLocalMutable lp | lpWanted lp -> + TTLocalMutable lp | lp.lpWanted -> liftIO $ atomically $ writeTChan ee.eeLogFiles (pkgDir, logPath) _ -> pure () @@ -1430,8 +1428,8 @@ withSingleContext -> RIO env a withCabal package pkgDir outputType inner = do config <- view configL - unless (configAllowDifferentUser config) $ - checkOwnership (pkgDir configWorkDir config) + unless config.configAllowDifferentUser $ + checkOwnership (pkgDir config.configWorkDir) let envSettings = EnvSettings { esIncludeLocals = taskTypeLocation taskType == Local , esIncludeGhcPackagePath = False @@ -1439,13 +1437,13 @@ withSingleContext , esLocaleUtf8 = True , esKeepGhcRts = False } - menv <- liftIO $ configProcessContextSettings config envSettings + menv <- liftIO $ config.configProcessContextSettings envSettings distRelativeDir' <- distRelativeDir esetupexehs <- -- Avoid broken Setup.hs files causing problems for simple build -- types, see: -- https://github.com/commercialhaskell/stack/issues/370 - case (packageBuildType package, ee.eeSetupExe) of + case (package.packageBuildType, ee.eeSetupExe) of (C.Simple, Just setupExe) -> pure $ Left setupExe _ -> liftIO $ Right <$> getSetupHs pkgDir inner $ \keepOutputOpen stripTHLoading args -> do @@ -1453,7 +1451,7 @@ withSingleContext -- Omit cabal package dependency when building -- Cabal. See -- https://github.com/commercialhaskell/stack/issues/1356 - | packageName package == mkPackageName "Cabal" = [] + | package.packageName == mkPackageName "Cabal" = [] | otherwise = ["-package=" ++ packageIdentifierString (PackageIdentifier cabalPackageName @@ -1463,24 +1461,24 @@ withSingleContext : "-global-package-db" : map (("-package-db=" ++) . toFilePathNoTrailingSep) - (bcoExtraDBs ee.eeBaseConfigOpts) + ee.eeBaseConfigOpts.bcoExtraDBs ) ++ ( ( "-package-db=" - ++ toFilePathNoTrailingSep (bcoSnapDB ee.eeBaseConfigOpts) + ++ toFilePathNoTrailingSep ee.eeBaseConfigOpts.bcoSnapDB ) : ( "-package-db=" - ++ toFilePathNoTrailingSep (bcoLocalDB ee.eeBaseConfigOpts) + ++ toFilePathNoTrailingSep ee.eeBaseConfigOpts.bcoLocalDB ) : ["-hide-all-packages"] ) warnCustomNoDeps :: RIO env () warnCustomNoDeps = - case (taskType, packageBuildType package) of - (TTLocalMutable lp, C.Custom) | lpWanted lp -> + case (taskType, package.packageBuildType) of + (TTLocalMutable lp, C.Custom) | lp.lpWanted -> prettyWarnL [ flow "Package" - , fromPackageName $ packageName package + , fromPackageName package.packageName , flow "uses a custom Cabal build, but does not use a \ \custom-setup stanza" ] @@ -1488,7 +1486,7 @@ withSingleContext getPackageArgs :: Path Abs Dir -> RIO env [String] getPackageArgs setupDir = - case packageSetupDeps package of + case package.packageSetupDeps of -- The package is using the Cabal custom-setup -- configuration introduced in Cabal 1.24. In -- this case, the package is providing an @@ -1497,7 +1495,7 @@ withSingleContext Just customSetupDeps -> do unless (Map.member (mkPackageName "Cabal") customSetupDeps) $ prettyWarnL - [ fromPackageName $ packageName package + [ fromPackageName package.packageName , flow "has a setup-depends field, but it does not mention \ \a Cabal dependency. This is likely to cause build \ \errors." @@ -1506,7 +1504,7 @@ withSingleContext forM (Map.toList customSetupDeps) $ \(name, depValue) -> do let matches (PackageIdentifier name' version) = name == name' - && version `withinRange` dvVersionRange depValue + && version `withinRange` depValue.dvVersionRange case filter (matches . fst) (Map.toList allDeps) of x:xs -> do unless (null xs) $ @@ -1533,7 +1531,7 @@ withSingleContext ( encodeUtf8Builder ( T.pack ( C.generatePackageVersionMacros - (packageVersion package) + package.packageVersion macroDeps ) ) @@ -1565,9 +1563,9 @@ withSingleContext : "-global-package-db" : map (("-package-db=" ++) . toFilePathNoTrailingSep) - (bcoExtraDBs ee.eeBaseConfigOpts) + ee.eeBaseConfigOpts.bcoExtraDBs ++ [ "-package-db=" - ++ toFilePathNoTrailingSep (bcoSnapDB ee.eeBaseConfigOpts) + ++ toFilePathNoTrailingSep ee.eeBaseConfigOpts.bcoSnapDB ] ) @@ -1603,7 +1601,7 @@ withSingleContext withProcessContext menv $ case outputType of OTLogFile _ h -> do let prefixWithTimestamps = - if configPrefixTimestamps config + if config.configPrefixTimestamps then PrefixWithTimestamps else WithoutTimestamps void $ sinkProcessStderrStdout (toFilePath exeName) fullArgs @@ -1640,11 +1638,11 @@ withSingleContext let setupDir = distDir relDirSetup outputFile = setupDir relFileSetupLower customBuilt <- liftIO $ readIORef ee.eeCustomBuilt - if Set.member (packageName package) customBuilt + if Set.member package.packageName customBuilt then pure outputFile else do ensureDir setupDir - compilerPath <- view $ compilerPathsL . to cpCompiler + compilerPath <- view $ compilerPathsL . to (.cpCompiler) packageArgs <- getPackageArgs setupDir runExe compilerPath $ [ "--make" @@ -1667,19 +1665,19 @@ withSingleContext ( Map.findWithDefault [] AGOEverything - (configGhcOptionsByCat config) - ++ case configApplyGhcOptions config of - AGOEverything -> boptsCLIGhcOptions ee.eeBuildOptsCLI + config.configGhcOptionsByCat + ++ case config.configApplyGhcOptions of + AGOEverything -> ee.eeBuildOptsCLI.boptsCLIGhcOptions AGOTargets -> [] AGOLocals -> [] ) liftIO $ atomicModifyIORef' ee.eeCustomBuilt $ \oldCustomBuilt -> - (Set.insert (packageName package) oldCustomBuilt, ()) + (Set.insert package.packageName oldCustomBuilt, ()) pure outputFile let cabalVerboseArg = - let CabalVerbosity cv = boptsCabalVerbose ee.eeBuildOpts + let CabalVerbosity cv = ee.eeBuildOpts.boptsCabalVerbose in "--verbose=" <> showForCabal cv runExe exeName $ cabalVerboseArg:setupArgs @@ -1720,7 +1718,7 @@ singleBuild case mprecompiled of Just precompiled -> copyPreCompiled precompiled Nothing -> do - mcurator <- view $ buildConfigL . to bcCurator + mcurator <- view $ buildConfigL . to (.bcCurator) realConfigAndBuild cache mcurator allDepsMap case minstalled of Nothing -> pure () @@ -1739,10 +1737,10 @@ singleBuild && mainLibraryHasExposedModules package -- Special help for the curator tool to avoid haddocks that are known -- to fail - && maybe True (Set.notMember pname . curatorSkipHaddock) mcurator + && maybe True (Set.notMember pname . (.curatorSkipHaddock)) mcurator expectHaddockFailure = - maybe False (Set.member pname . curatorExpectHaddockFailure) - isHaddockForHackage = boptsHaddockForHackage ee.eeBuildOpts + maybe False (Set.member pname . (.curatorExpectHaddockFailure)) + isHaddockForHackage = ee.eeBuildOpts.boptsHaddockForHackage fulfillHaddockExpectations mcurator action | expectHaddockFailure mcurator = do eres <- tryAny $ action KeepOpen @@ -1770,9 +1768,9 @@ singleBuild ] (hasLib, hasSubLib, hasExe) = case task.taskType of TTLocalMutable lp -> - let package = lpPackage lp + let package = lp.lpPackage hasLibrary = hasBuildableMainLibrary package - hasSubLibraries = not . null $ packageSubLibraries package + hasSubLibraries = not $ null package.packageSubLibraries hasExecutables = not . Set.null $ exesToBuild executableBuildStatuses lp in (hasLibrary, hasSubLibraries, hasExecutables) @@ -1784,16 +1782,16 @@ singleBuild TTRemotePackage Immutable _ loc -> do mpc <- readPrecompiledCache loc - (configCacheOpts cache) - (configCacheHaddock cache) + cache.configCacheOpts + cache.configCacheHaddock case mpc of Nothing -> pure Nothing -- Only pay attention to precompiled caches that refer to packages -- within the snapshot. Just pc | maybe False - (bcoSnapInstallRoot ee.eeBaseConfigOpts `isProperPrefixOf`) - (pcLibrary pc) -> pure Nothing + (ee.eeBaseConfigOpts.bcoSnapInstallRoot `isProperPrefixOf`) + pc.pcLibrary -> pure Nothing -- If old precompiled cache files are left around but snapshots are -- deleted, it is possible for the precompiled file to refer to the -- very library we're building, and if flags are changed it may try to @@ -1805,7 +1803,7 @@ singleBuild b <- f x if b then allM f xs else pure False b <- liftIO $ - allM doesFileExist $ maybe id (:) (pcLibrary pc) $ pcExes pc + allM doesFileExist $ maybe id (:) pc.pcLibrary pc.pcExes pure $ if b then Just pc else Nothing _ -> pure Nothing @@ -1818,7 +1816,7 @@ singleBuild -- it was built with different flags. let subLibNames = Set.toList $ buildableSubLibs $ case task.taskType of - TTLocalMutable lp -> lpPackage lp + TTLocalMutable lp -> lp.lpPackage TTRemotePackage _ p _ -> p toMungedPackageId :: Text -> MungedPackageId toMungedPackageId subLib = @@ -1838,7 +1836,7 @@ singleBuild -- We want to ignore the global and user package databases. ghc-pkg -- allows us to specify --no-user-package-db and --package-db= on -- the command line. - let pkgDb = bcoSnapDB ee.eeBaseConfigOpts + let pkgDb = ee.eeBaseConfigOpts.bcoSnapDB ghcPkgExe <- getGhcPkgExe -- First unregister, silently, everything that needs to be unregistered. case nonEmpty allToUnregister of @@ -1859,7 +1857,7 @@ singleBuild _ -> pure () -- Find the package in the database - let pkgDbs = [bcoSnapDB ee.eeBaseConfigOpts] + let pkgDbs = [ee.eeBaseConfigOpts.bcoSnapDB] case mlib of Nothing -> pure $ Just $ Executable pkgId @@ -1871,7 +1869,7 @@ singleBuild Nothing -> assert False $ Executable pkgId Just pkgid -> simpleInstalledLib pkgId pkgid mempty where - bindir = bcoSnapInstallRoot ee.eeBaseConfigOpts bindirSuffix + bindir = ee.eeBaseConfigOpts.bcoSnapInstallRoot bindirSuffix realConfigAndBuild cache mcurator allDepsMap = withSingleContext ac ee task.taskType allDepsMap Nothing $ @@ -1883,7 +1881,7 @@ singleBuild ) $ prettyInfoL [ flow "Building all executables for" - , style Current (fromPackageName $ packageName package) + , style Current (fromPackageName package.packageName) , flow "once. After a successful build of all of them, only \ \specified executables will be rebuilt." ] @@ -1902,13 +1900,13 @@ singleBuild task let installedMapHasThisPkg :: Bool installedMapHasThisPkg = - case Map.lookup (packageName package) installedMap of + case Map.lookup package.packageName installedMap of Just (_, Library ident _) -> ident == pkgId Just (_, Executable _) -> True _ -> False - case ( boptsCLIOnlyConfigure ee.eeBuildOptsCLI - , boptsCLIInitialBuildSteps ee.eeBuildOptsCLI && taskIsTarget task + case ( ee.eeBuildOptsCLI.boptsCLIOnlyConfigure + , ee.eeBuildOptsCLI.boptsCLIInitialBuildSteps && taskIsTarget task ) of -- A full build is done if there are downstream actions, -- because their configure step will require that this @@ -1951,7 +1949,7 @@ singleBuild case task.taskType of TTLocalMutable lp -> do when enableTests $ setTestStatus pkgDir TSUnknown - caches <- runMemoizedWith $ lpNewBuildCaches lp + caches <- runMemoizedWith lp.lpNewBuildCaches mapM_ (uncurry (writeBuildCache pkgDir)) (Map.toList caches) @@ -1964,7 +1962,7 @@ singleBuild TTLocalMutable lp -> do warnings <- checkForUnlistedFiles task.taskType pkgDir -- TODO: Perhaps only emit these warnings for non extra-dep? - pure (Just (lpCabalFile lp, warnings)) + pure (Just (lp.lpCabalFile, warnings)) _ -> pure Nothing -- NOTE: once -- https://github.com/commercialhaskell/stack/issues/2649 @@ -2006,7 +2004,7 @@ singleBuild config <- view configL extraOpts <- extraBuildOptions wc ee.eeBuildOpts let stripTHLoading - | configHideTHLoading config = ExcludeTHLoading + | config.configHideTHLoading = ExcludeTHLoading | otherwise = KeepTHLoading cabal stripTHLoading (("build" :) $ (++ extraOpts) $ case (task.taskType, task.taskAllInOne, isFinalBuild) of @@ -2024,7 +2022,7 @@ singleBuild _ -> throwM ex postBuildCheck True - mcurator <- view $ buildConfigL . to bcCurator + mcurator <- view $ buildConfigL . to (.bcCurator) when (doHaddock mcurator package) $ do announce $ if isHaddockForHackage then "haddock for Hackage" @@ -2048,13 +2046,13 @@ singleBuild , "--html-location=../$pkg-$version/" ] , [ "--haddock-option=--hyperlinked-source" - | boptsHaddockHyperlinkSource ee.eeBuildOpts + | ee.eeBuildOpts.boptsHaddockHyperlinkSource ] - , [ "--internal" | boptsHaddockInternal ee.eeBuildOpts ] + , [ "--internal" | ee.eeBuildOpts.boptsHaddockInternal ] , quickjump ] <> [ [ "--haddock-option=" <> opt - | opt <- hoAdditionalArgs (boptsHaddockOpts ee.eeBuildOpts) + | opt <- ee.eeBuildOpts.boptsHaddockOpts.hoAdditionalArgs ] ] ) @@ -2062,8 +2060,8 @@ singleBuild cabal0 keep KeepTHLoading $ "haddock" : args let hasLibrary = hasBuildableMainLibrary package - hasSubLibraries = not $ null $ packageSubLibraries package - hasExecutables = not $ null $ packageExecutables package + hasSubLibraries = not $ null package.packageSubLibraries + hasExecutables = not $ null package.packageExecutables shouldCopy = not isFinalBuild && (hasLibrary || hasSubLibraries || hasExecutables) @@ -2073,13 +2071,13 @@ singleBuild case eres of Left err@CabalExitedUnsuccessfully{} -> throwM $ CabalCopyFailed - (packageBuildType package == C.Simple) + (package.packageBuildType == C.Simple) (displayException err) _ -> pure () when (hasLibrary || hasSubLibraries) $ cabal KeepTHLoading ["register"] -- copy ddump-* files - case T.unpack <$> boptsDdumpDir ee.eeBuildOpts of + case T.unpack <$> ee.eeBuildOpts.boptsDdumpDir of Just ddumpPath | buildingFinals && not (null ddumpPath) -> do distDir <- distRelativeDir ddumpDir <- parseRelDir ddumpPath @@ -2104,19 +2102,19 @@ singleBuild let (installedPkgDb, installedDumpPkgsTVar) = case taskLocation task of Snap -> - ( bcoSnapDB ee.eeBaseConfigOpts + ( ee.eeBaseConfigOpts.bcoSnapDB , ee.eeSnapshotDumpPkgs ) Local -> - ( bcoLocalDB ee.eeBaseConfigOpts + ( ee.eeBaseConfigOpts.bcoLocalDB , ee.eeLocalDumpPkgs ) - let ident = PackageIdentifier (packageName package) (packageVersion package) + let ident = PackageIdentifier package.packageName package.packageVersion -- only pure the sub-libraries to cache them if we also cache the main -- library (that is, if it exists) (mpkgid, subLibsPkgIds) <- if hasBuildableMainLibrary package then do subLibsPkgIds' <- fmap catMaybes $ - forM (getBuildableListAs id $ packageSubLibraries package) $ \subLib -> do - let subLibName = toCabalMungedPackageName (packageName package) subLib + forM (getBuildableListAs id package.packageSubLibraries) $ \subLib -> do + let subLibName = toCabalMungedPackageName package.packageName subLib maybeGhcpkgId <- loadInstalledPkg [installedPkgDb] installedDumpPkgsTVar @@ -2126,11 +2124,11 @@ singleBuild mpkgid <- loadInstalledPkg [installedPkgDb] installedDumpPkgsTVar - (packageName package) + package.packageName let makeInstalledLib pkgid = simpleInstalledLib ident pkgid (Map.fromList subLibsPkgIds') case mpkgid of - Nothing -> throwM $ Couldn'tFindPkgId $ packageName package + Nothing -> throwM $ Couldn'tFindPkgId package.packageName Just pkgid -> pure (makeInstalledLib pkgid, subLibsPkgIds) else do markExeInstalled (taskLocation task) pkgId -- TODO unify somehow @@ -2142,8 +2140,8 @@ singleBuild writePrecompiledCache ee.eeBaseConfigOpts loc - (configCacheOpts cache) - (configCacheHaddock cache) + cache.configCacheOpts + cache.configCacheHaddock mpkgid subLibsPkgIds (buildableExes package) @@ -2174,8 +2172,8 @@ singleBuild case dps of [] -> pure Nothing [dp] -> do - liftIO $ atomically $ modifyTVar' tvar (Map.insert (dpGhcPkgId dp) dp) - pure $ Just (dpGhcPkgId dp) + liftIO $ atomically $ modifyTVar' tvar (Map.insert dp.dpGhcPkgId dp) + pure $ Just dp.dpGhcPkgId _ -> throwM $ MultipleResultsBug name dps -- | Get the build status of all the package executables. Do so by @@ -2230,12 +2228,12 @@ checkForUnlistedFiles :: -> Path Abs Dir -> RIO env [PackageWarning] checkForUnlistedFiles (TTLocalMutable lp) pkgDir = do - caches <- runMemoizedWith $ lpNewBuildCaches lp + caches <- runMemoizedWith lp.lpNewBuildCaches (addBuildCache,warnings) <- addUnlistedToBuildCache - (lpPackage lp) - (lpCabalFile lp) - (lpComponents lp) + lp.lpPackage + lp.lpCabalFile + lp.lpComponents caches forM_ (Map.toList addBuildCache) $ \(component, newToCache) -> do let cache = Map.findWithDefault Map.empty component caches @@ -2258,20 +2256,20 @@ singleTest topts testsToRun ac ee task installedMap = do -- FIXME: Since this doesn't use cabal, we should be able to avoid using a -- full blown 'withSingleContext'. (allDepsMap, _cache) <- getConfigCache ee task installedMap True False - mcurator <- view $ buildConfigL . to bcCurator + mcurator <- view $ buildConfigL . to (.bcCurator) let pname = pkgName $ taskProvides task expectFailure = expectTestFailure pname mcurator - withSingleContext ac ee (taskType task) allDepsMap (Just "test") $ + withSingleContext ac ee task.taskType allDepsMap (Just "test") $ \package _cabalfp pkgDir _cabal announce outputType -> do config <- view configL - let needHpc = toCoverage topts + let needHpc = topts.toCoverage toRun <- - if toDisableRun topts + if topts.toDisableRun then do announce "Test running disabled by --no-run-tests flag." pure False - else if toRerunTests topts + else if topts.toRerunTests then pure True else do status <- getTestStatus pkgDir @@ -2297,8 +2295,8 @@ singleTest topts testsToRun ac ee task installedMap = do let suitesToRun = [ testSuitePair | testSuitePair <- - (fmap . fmap) (getField @"interface") <$> - collectionKeyValueList $ packageTestSuites package + ((fmap . fmap) (.interface) <$> collectionKeyValueList) + package.packageTestSuites , let testName = fst testSuitePair , testName `elem` testsToRun ] @@ -2312,7 +2310,7 @@ singleTest topts testsToRun ac ee task installedMap = do interface -> throwM (TestSuiteTypeUnsupported interface) let exeName = testName' ++ - case configPlatform config of + case config.configPlatform of Platform _ Windows -> ".exe" _ -> "" tixPath <- fmap (pkgDir ) $ parseRelFile $ exeName ++ ".tix" @@ -2327,15 +2325,15 @@ singleTest topts testsToRun ac ee task installedMap = do installed <- case Map.lookup pname installedMap of Just (_, installed) -> pure $ Just installed Nothing -> do - idMap <- liftIO $ readTVarIO (eeGhcPkgIds ee) + idMap <- liftIO $ readTVarIO ee.eeGhcPkgIds pure $ Map.lookup (taskProvides task) idMap let pkgGhcIdList = case installed of - Just (Library _ libInfo) -> [iliId libInfo] + Just (Library _ libInfo) -> [libInfo.iliId] _ -> [] -- doctest relies on template-haskell in QuickCheck-based tests thGhcId <- - case L.find ((== "template-haskell") . pkgName . dpPackageIdent. snd) - (Map.toList $ eeGlobalDumpPkgs ee) of + case L.find ((== "template-haskell") . pkgName . (.dpPackageIdent) . snd) + (Map.toList ee.eeGlobalDumpPkgs) of Just (ghcId, _) -> pure ghcId Nothing -> throwIO TemplateHaskellNotFoundBug -- env variable GHC_ENVIRONMENT is set for doctest so module names for @@ -2346,16 +2344,16 @@ singleTest topts testsToRun ac ee task installedMap = do let setEnv f pc = modifyEnvVars pc $ \envVars -> Map.insert "HASKELL_DIST_DIR" (T.pack $ toFilePath buildDir) $ Map.insert "GHC_ENVIRONMENT" (T.pack f) envVars - fp' = eeTempDir ee testGhcEnvRelFile + fp' = ee.eeTempDir testGhcEnvRelFile -- Add a random suffix to avoid conflicts between parallel jobs -- See https://github.com/commercialhaskell/stack/issues/5024 randomInt <- liftIO (randomIO :: IO Int) let randomSuffix = "." <> show (abs randomInt) fp <- toFilePath <$> addExtension randomSuffix fp' let snapDBPath = - toFilePathNoTrailingSep (bcoSnapDB $ eeBaseConfigOpts ee) + toFilePathNoTrailingSep ee.eeBaseConfigOpts.bcoSnapDB localDBPath = - toFilePathNoTrailingSep (bcoLocalDB $ eeBaseConfigOpts ee) + toFilePathNoTrailingSep ee.eeBaseConfigOpts.bcoLocalDB ghcEnv = "clear-package-db\n" <> "global-package-db\n" @@ -2374,7 +2372,7 @@ singleTest topts testsToRun ac ee task installedMap = do (pkgGhcIdList ++ thGhcId:Map.elems allDepsMap) writeFileUtf8Builder fp ghcEnv menv <- liftIO $ - setEnv fp =<< configProcessContextSettings config EnvSettings + setEnv fp =<< config.configProcessContextSettings EnvSettings { esIncludeLocals = taskLocation task == Local , esIncludeGhcPackagePath = True , esStackExe = True @@ -2394,7 +2392,7 @@ singleTest topts testsToRun ac ee task installedMap = do ] liftIO $ ignoringAbsence (removeFile tixPath) - let args = toAdditionalArgs topts + let args = topts.toAdditionalArgs argsDisplay = case args of [] -> "" _ -> ", args: " @@ -2427,7 +2425,7 @@ singleTest topts testsToRun ac ee task installedMap = do createSource OTLogFile _ h -> Nothing <$ useHandleOpen h optionalTimeout action - | Just maxSecs <- toMaximumTimeSeconds topts, maxSecs > 0 = + | Just maxSecs <- topts.toMaximumTimeSeconds, maxSecs > 0 = timeout (maxSecs * 1000000) action | otherwise = Just <$> action @@ -2447,8 +2445,8 @@ singleTest topts testsToRun ac ee task installedMap = do , mkUnqualComponentName (T.unpack testName) ) else do - isTerminal <- view $ globalOptsL . to globalTerminal - if toAllowStdin topts && isTerminal + isTerminal <- view $ globalOptsL . to (.globalTerminal) + if topts.toAllowStdin && isTerminal then pure id else pure $ setStdin $ byteStringInput mempty let pc = changeStdin @@ -2473,7 +2471,7 @@ singleTest topts testsToRun ac ee task installedMap = do -- directory into the hpc work dir, for -- tidiness. when needHpc $ - updateTixFile (packageName package) tixPath testName' + updateTixFile package.packageName tixPath testName' let announceResult result = announce $ "Test suite " @@ -2498,20 +2496,20 @@ singleTest topts testsToRun ac ee task installedMap = do unless expectFailure $ logError $ displayShow $ TestSuiteExeMissing - (packageBuildType package == C.Simple) + (package.packageBuildType == C.Simple) exeName - (packageNameString (packageName package)) + (packageNameString package.packageName) (T.unpack testName) pure emptyResult when needHpc $ do let testsToRun' = map f testsToRun f tName = - case getField @"interface" <$> mComponent of + case (.interface) <$> mComponent of Just C.TestSuiteLibV09{} -> tName <> "Stub" _ -> tName where - mComponent = collectionLookup tName (packageTestSuites package) + mComponent = collectionLookup tName package.packageTestSuites generateHpcReport pkgDir package testsToRun' bs <- liftIO $ @@ -2544,14 +2542,14 @@ singleBench :: HasEnvConfig env -> RIO env () singleBench beopts benchesToRun ac ee task installedMap = do (allDepsMap, _cache) <- getConfigCache ee task installedMap False True - withSingleContext ac ee (taskType task) allDepsMap (Just "bench") $ + withSingleContext ac ee task.taskType allDepsMap (Just "bench") $ \_package _cabalfp _pkgDir cabal announce _outputType -> do let args = map T.unpack benchesToRun <> maybe [] ((:[]) . ("--benchmark-options=" <>)) - (beoAdditionalArgs beopts) + beopts.beoAdditionalArgs toRun <- - if beoDisableRun beopts + if beopts.beoDisableRun then do announce "Benchmark running disabled by --no-run-benchmarks flag." pure False @@ -2705,7 +2703,7 @@ extraBuildOptions wc bopts = do colorOpt <- appropriateGhcColorFlag let optsFlag = compilerOptionsCabalFlag wc baseOpts = maybe "" (" " ++) colorOpt - if toCoverage (boptsTestOpts bopts) + if bopts.boptsTestOpts.toCoverage then do hpcIndexDir <- toFilePathNoTrailingSep <$> hpcRelativeDir pure [optsFlag, "-hpcdir " ++ hpcIndexDir ++ baseOpts] @@ -2722,20 +2720,20 @@ primaryComponentOptions executableBuildStatuses lp = -- users to turn off library building if desired ( if hasBuildableMainLibrary package then map T.unpack - $ T.append "lib:" (T.pack (packageNameString (packageName package))) + $ T.append "lib:" (T.pack (packageNameString package.packageName)) : map (T.append "flib:") - (getBuildableListText (packageForeignLibraries package)) + (getBuildableListText package.packageForeignLibraries) else [] ) ++ map (T.unpack . T.append "lib:") - (getBuildableListText $ packageSubLibraries package) + (getBuildableListText package.packageSubLibraries) ++ map (T.unpack . T.append "exe:") (Set.toList $ exesToBuild executableBuildStatuses lp) where - package = lpPackage lp + package = lp.lpPackage -- | History of this function: -- @@ -2751,9 +2749,9 @@ primaryComponentOptions executableBuildStatuses lp = -- exesToBuild :: Map Text ExecutableBuildStatus -> LocalPackage -> Set Text exesToBuild executableBuildStatuses lp = - if cabalIsSatisfied executableBuildStatuses && lpWanted lp - then exeComponents (lpComponents lp) - else buildableExes (lpPackage lp) + if cabalIsSatisfied executableBuildStatuses && lp.lpWanted + then exeComponents lp.lpComponents + else buildableExes lp.lpPackage -- | Do the current executables satisfy Cabal's bugged out requirements? cabalIsSatisfied :: Map k ExecutableBuildStatus -> Bool @@ -2764,21 +2762,21 @@ finalComponentOptions :: LocalPackage -> [String] finalComponentOptions lp = map (T.unpack . renderComponent) $ Set.toList $ - Set.filter (\c -> isCTest c || isCBench c) (lpComponents lp) + Set.filter (\c -> isCTest c || isCBench c) lp.lpComponents taskComponents :: Task -> Set NamedComponent taskComponents task = - case taskType task of - TTLocalMutable lp -> lpComponents lp -- FIXME probably just want lpWanted + case task.taskType of + TTLocalMutable lp -> lp.lpComponents -- FIXME probably just want lpWanted TTRemotePackage{} -> Set.empty expectTestFailure :: PackageName -> Maybe Curator -> Bool expectTestFailure pname = - maybe False (Set.member pname . curatorExpectTestFailure) + maybe False (Set.member pname . (.curatorExpectTestFailure)) expectBenchmarkFailure :: PackageName -> Maybe Curator -> Bool expectBenchmarkFailure pname = - maybe False (Set.member pname . curatorExpectBenchmarkFailure) + maybe False (Set.member pname . (.curatorExpectBenchmarkFailure)) fulfillCuratorBuildExpectations :: (HasCallStack, HasTerm env) diff --git a/src/Stack/Build/Haddock.hs b/src/Stack/Build/Haddock.hs index c8dbd7f035..61362a1130 100644 --- a/src/Stack/Build/Haddock.hs +++ b/src/Stack/Build/Haddock.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Generate haddocks module Stack.Build.Haddock @@ -63,7 +64,7 @@ openHaddocksInBrowser :: -- ^ Build targets as determined by 'Stack.Build.Source.loadSourceMap' -> RIO env () openHaddocksInBrowser bco pkgLocations buildTargets = do - let cliTargets = (boptsCLITargets . bcoBuildOptsCLI) bco + let cliTargets = bco.bcoBuildOptsCLI.boptsCLITargets getDocIndex = do let localDocs = haddockIndexFile (localDepsDocDir bco) localExists <- doesFileExist localDocs @@ -109,13 +110,12 @@ shouldHaddockPackage :: -> Bool shouldHaddockPackage bopts wanted name = if Set.member name wanted - then boptsHaddock bopts + then bopts.boptsHaddock else shouldHaddockDeps bopts -- | Determine whether to build haddocks for dependencies. shouldHaddockDeps :: BuildOpts -> Bool -shouldHaddockDeps bopts = - fromMaybe (boptsHaddock bopts) (boptsHaddockDeps bopts) +shouldHaddockDeps bopts = fromMaybe bopts.boptsHaddock bopts.boptsHaddockDeps -- | Generate Haddock index and contents for local packages. generateLocalHaddockIndex :: @@ -129,7 +129,7 @@ generateLocalHaddockIndex bco localDumpPkgs locals = do mapMaybe ( \LocalPackage{lpPackage = Package{packageName, packageVersion}} -> F.find - ( \dp -> dpPackageIdent dp == + ( \dp -> dp.dpPackageIdent == PackageIdentifier packageName packageVersion ) localDumpPkgs @@ -170,8 +170,8 @@ generateDepsHaddockIndex bco globalDumpPkgs snapshotDumpPkgs localDumpPkgs local getGhcPkgId :: LocalPackage -> Maybe GhcPkgId getGhcPkgId LocalPackage{lpPackage = Package{packageName, packageVersion}} = let pkgId = PackageIdentifier packageName packageVersion - mdpPkg = F.find (\dp -> dpPackageIdent dp == pkgId) localDumpPkgs - in fmap dpGhcPkgId mdpPkg + mdpPkg = F.find (\dp -> dp.dpPackageIdent == pkgId) localDumpPkgs + in fmap (.dpGhcPkgId) mdpPkg findTransitiveDepends :: [GhcPkgId] -> [GhcPkgId] findTransitiveDepends = (`go` HS.empty) . HS.fromList where @@ -181,7 +181,7 @@ generateDepsHaddockIndex bco globalDumpPkgs snapshotDumpPkgs localDumpPkgs local (ghcPkgId:_) -> let deps = case lookupDumpPackage ghcPkgId allDumpPkgs of Nothing -> HS.empty - Just pkgDP -> HS.fromList (dpDepends pkgDP) + Just pkgDP -> HS.fromList pkgDP.dpDepends deps' = deps `HS.difference` checked todo' = HS.delete ghcPkgId (deps' `HS.union` todo) checked' = HS.insert ghcPkgId checked @@ -236,13 +236,13 @@ generateHaddockIndex descr bco dumpPackages docRelFP destDir = do <> line <> pretty destIndexFile liftIO (mapM_ copyPkgDocs interfaceOpts) - haddockExeName <- view $ compilerPathsL.to (toFilePath . cpHaddock) + haddockExeName <- view $ compilerPathsL . to (toFilePath . (.cpHaddock)) withWorkingDir (toFilePath destDir) $ readProcessNull haddockExeName ( map (("--optghc=-package-db=" ++ ) . toFilePathNoTrailingSep) - [bcoSnapDB bco, bcoLocalDB bco] - ++ hoAdditionalArgs (boptsHaddockOpts (bcoBuildOpts bco)) + [bco.bcoSnapDB, bco.bcoLocalDB] + ++ bco.bcoBuildOpts.boptsHaddockOpts.hoAdditionalArgs ++ ["--gen-contents", "--gen-index"] ++ [x | (xs, _, _, _) <- interfaceOpts, x <- xs] ) @@ -322,7 +322,7 @@ haddockIndexFile destDir = destDir relFileIndexHtml -- | Path of local packages documentation directory. localDocDir :: BaseConfigOpts -> Path Abs Dir -localDocDir bco = bcoLocalInstallRoot bco docDirSuffix +localDocDir bco = bco.bcoLocalInstallRoot docDirSuffix -- | Path of documentation directory for the dependencies of local packages localDepsDocDir :: BaseConfigOpts -> Path Abs Dir @@ -330,7 +330,7 @@ localDepsDocDir bco = localDocDir bco relDirAll -- | Path of snapshot packages documentation directory. snapDocDir :: BaseConfigOpts -> Path Abs Dir -snapDocDir bco = bcoSnapInstallRoot bco docDirSuffix +snapDocDir bco = bco.bcoSnapInstallRoot docDirSuffix generateLocalHaddockForHackageArchives :: (HasEnvConfig env, HasTerm env) @@ -339,9 +339,9 @@ generateLocalHaddockForHackageArchives :: generateLocalHaddockForHackageArchives = mapM_ ( \lp -> - let pkg = lpPackage lp - pkgId = PackageIdentifier (packageName pkg) (packageVersion pkg) - pkgDir = parent (lpCabalFile lp) + let pkg = lp.lpPackage + pkgId = PackageIdentifier pkg.packageName pkg.packageVersion + pkgDir = parent lp.lpCabalFile in generateLocalHaddockForHackageArchive pkgDir pkgId ) diff --git a/src/Stack/Build/Installed.hs b/src/Stack/Build/Installed.hs index 050a2b35d0..e3566e1031 100644 --- a/src/Stack/Build/Installed.hs +++ b/src/Stack/Build/Installed.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ScopedTypeVariables #-} @@ -40,15 +41,15 @@ import Stack.Types.SourceMap toInstallMap :: MonadIO m => SourceMap -> m InstallMap toInstallMap sourceMap = do projectInstalls <- - for (smProject sourceMap) $ \pp -> do - version <- loadVersion (ppCommon pp) + for sourceMap.smProject $ \pp -> do + version <- loadVersion pp.ppCommon pure (Local, version) depInstalls <- - for (smDeps sourceMap) $ \dp -> - case dpLocation dp of + for sourceMap.smDeps $ \dp -> + case dp.dpLocation of PLImmutable pli -> pure (Snap, getPLIVersion pli) PLMutable _ -> do - version <- loadVersion (dpCommon dp) + version <- loadVersion dp.dpCommon pure (Local, version) pure $ projectInstalls <> depInstalls @@ -132,7 +133,7 @@ loadDatabase installMap db lhs0 = do pkgexe <- getGhcPkgExe (lhs1', dps) <- ghcPkgDump pkgexe pkgDb $ conduitDumpPackage .| sink lhs1 <- mapMaybeM processLoadResult lhs1' - let lhs = pruneDeps id lhId lhDeps const (lhs0 ++ lhs1) + let lhs = pruneDeps id (.lhId) (.lhDeps) const (lhs0 ++ lhs1) pure (map (\lh -> lh { lhDeps = [] }) $ Map.elems lhs, dps) where pkgDb = case db of @@ -152,7 +153,7 @@ loadDatabase installMap db lhs0 = do processLoadResult (reason, lh) = do logDebug $ "Ignoring package " - <> fromPackageName (fst (lhPair lh)) + <> fromPackageName (fst lh.lhPair) <> case db of GlobalPkgDb -> mempty UserPkgDb loc fp -> ", from " <> displayShow (loc, fp) <> "," @@ -209,7 +210,7 @@ isAllowed installMap pkgDb dp = case Map.lookup name installMap of Nothing -> checkNotFound Just pii -> checkFound pii where - PackageIdentifier name version = dpPackageIdent dp + PackageIdentifier name version = dp.dpPackageIdent -- Ensure that the installed location matches where the sourceMap says it -- should be installed. checkLocation Snap = @@ -265,17 +266,17 @@ toLoadHelper pkgDb dp = LoadHelper -- therefore not match the snapshot. if name `Set.member` wiredInPackages then [] - else dpDepends dp - , lhSublibrary = dpSublib dp + else dp.dpDepends + , lhSublibrary = dp.dpSublib , lhPair = ( name , (toInstallLocation pkgDb, Library ident installedLibInfo) ) } where - installedLibInfo = InstalledLibraryInfo gid (Right <$> dpLicense dp) mempty - gid = dpGhcPkgId dp - ident@(PackageIdentifier name _) = dpPackageIdent dp + installedLibInfo = InstalledLibraryInfo gid (Right <$> dp.dpLicense) mempty + gid = dp.dpGhcPkgId + ident@(PackageIdentifier name _) = dp.dpPackageIdent toInstallLocation :: PackageDbVariety -> InstallLocation toInstallLocation GlobalDb = Snap @@ -300,22 +301,22 @@ gatherAndTransformSubLoadHelper lh = = ( pLoc , Library pn existingLibInfo { iliSublib = Map.union - (iliSublib incomingLibInfo) - (iliSublib existingLibInfo) - , iliId = if isJust $ lhSublibrary lh - then iliId existingLibInfo - else iliId incomingLibInfo + incomingLibInfo.iliSublib + existingLibInfo.iliSublib + , iliId = if isJust lh.lhSublibrary + then existingLibInfo.iliId + else incomingLibInfo.iliId } ) onPreviousLoadHelper newVal _oldVal = newVal - (key, value) = case lhSublibrary lh of + (key, value) = case lh.lhSublibrary of Nothing -> (rawPackageName, rawValue) - Just sd -> (sdPackageName sd, updateAsSublib sd <$> rawValue) - (rawPackageName, rawValue) = lhPair lh + Just sd -> (sd.sdPackageName, updateAsSublib sd <$> rawValue) + (rawPackageName, rawValue) = lh.lhPair updateAsSublib sd (Library (PackageIdentifier _sublibMungedPackageName version) libInfo) = Library (PackageIdentifier key version) - libInfo {iliSublib = Map.singleton (sdLibraryName sd) (iliId libInfo)} + libInfo {iliSublib = Map.singleton sd.sdLibraryName libInfo.iliId} updateAsSublib _ v = v diff --git a/src/Stack/Build/Source.hs b/src/Stack/Build/Source.hs index 5846e67bfa..00b200bf87 100644 --- a/src/Stack/Build/Source.hs +++ b/src/Stack/Build/Source.hs @@ -74,16 +74,16 @@ import System.IO.Error ( isDoesNotExistError ) -- | loads and returns project packages projectLocalPackages :: HasEnvConfig env => RIO env [LocalPackage] projectLocalPackages = do - sm <- view $ envConfigL . to envConfigSourceMap - for (toList $ smProject sm) loadLocalPackage + sm <- view $ envConfigL . to (.envConfigSourceMap) + for (toList sm.smProject) loadLocalPackage -- | loads all local dependencies - project packages and local extra-deps localDependencies :: HasEnvConfig env => RIO env [LocalPackage] localDependencies = do - bopts <- view $ configL . to configBuild - sourceMap <- view $ envConfigL . to envConfigSourceMap - forMaybeM (Map.elems $ smDeps sourceMap) $ \dp -> - case dpLocation dp of + bopts <- view $ configL . to (.configBuild) + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) + forMaybeM (Map.elems sourceMap.smDeps) $ \dp -> + case dp.dpLocation of PLMutable dir -> do pp <- mkProjectPackage YesPrintWarnings dir (shouldHaddockDeps bopts) Just <$> loadLocalPackage pp @@ -98,42 +98,42 @@ loadSourceMap :: HasBuildConfig env -> RIO env SourceMap loadSourceMap smt boptsCli sma = do bconfig <- view buildConfigL - let compiler = smaCompiler sma - project = M.map applyOptsFlagsPP $ smaProject sma - bopts = configBuild (bcConfig bconfig) + let compiler = sma.smaCompiler + project = M.map applyOptsFlagsPP sma.smaProject + bopts = bconfig.bcConfig.configBuild applyOptsFlagsPP p@ProjectPackage{ppCommon = c} = - p{ppCommon = applyOptsFlags (M.member (cpName c) (smtTargets smt)) True c} - deps0 = smtDeps smt <> smaDeps sma + p{ppCommon = applyOptsFlags (M.member c.cpName smt.smtTargets) True c} + deps0 = smt.smtDeps <> sma.smaDeps deps = M.map applyOptsFlagsDep deps0 applyOptsFlagsDep d@DepPackage{dpCommon = c} = - d{dpCommon = applyOptsFlags (M.member (cpName c) (smtDeps smt)) False c} + d{dpCommon = applyOptsFlags (M.member c.cpName smt.smtDeps) False c} applyOptsFlags isTarget isProjectPackage common = - let name = cpName common + let name = common.cpName flags = getLocalFlags boptsCli name ghcOptions = generalGhcOptions bconfig boptsCli isTarget isProjectPackage cabalConfigOpts = - generalCabalConfigOpts bconfig boptsCli (cpName common) isTarget isProjectPackage + generalCabalConfigOpts bconfig boptsCli common.cpName isTarget isProjectPackage in common { cpFlags = if M.null flags - then cpFlags common + then common.cpFlags else flags , cpGhcOptions = - ghcOptions ++ cpGhcOptions common + ghcOptions ++ common.cpGhcOptions , cpCabalConfigOpts = - cabalConfigOpts ++ cpCabalConfigOpts common + cabalConfigOpts ++ common.cpCabalConfigOpts , cpHaddocks = if isTarget - then boptsHaddock bopts + then bopts.boptsHaddock else shouldHaddockDeps bopts } packageCliFlags = Map.fromList $ mapMaybe maybeProjectFlags $ - Map.toList (boptsCLIFlags boptsCli) + Map.toList boptsCli.boptsCLIFlags maybeProjectFlags (ACFByName name, fs) = Just (name, fs) maybeProjectFlags _ = Nothing - globals = pruneGlobals (smaGlobal sma) (Map.keysSet deps) + globals = pruneGlobals sma.smaGlobal (Map.keysSet deps) logDebug "Checking flags" checkFlagsUsedThrowing packageCliFlags FSCommandLine project deps logDebug "SourceMap constructed" @@ -173,7 +173,7 @@ hashSourceMapData :: hashSourceMapData boptsCli sm = do compilerPath <- getUtf8Builder . fromString . toFilePath <$> getCompilerPath compilerInfo <- getCompilerInfo - immDeps <- forM (Map.elems (smDeps sm)) depPackageHashableContent + immDeps <- forM (Map.elems sm.smDeps) depPackageHashableContent bc <- view buildConfigL let -- extra bytestring specifying GHC options supposed to be applied to GHC -- boot packages so we'll have different hashes when bare resolver @@ -196,10 +196,10 @@ depPackageHashableContent dp = if enabled then "" else "-" <> fromString (C.unFlagName f) - flags = map flagToBs $ Map.toList (cpFlags dp.dpCommon) - ghcOptions = map display (cpGhcOptions dp.dpCommon) - cabalConfigOpts = map display (cpCabalConfigOpts dp.dpCommon) - haddocks = if cpHaddocks dp.dpCommon then "haddocks" else "" + flags = map flagToBs $ Map.toList dp.dpCommon.cpFlags + ghcOptions = map display dp.dpCommon.cpGhcOptions + cabalConfigOpts = map display dp.dpCommon.cpCabalConfigOpts + haddocks = if dp.dpCommon.cpHaddocks then "haddocks" else "" hash = immutableLocSha pli pure $ hash @@ -218,7 +218,7 @@ getLocalFlags boptsCli name = Map.unions , Map.findWithDefault Map.empty ACFAllProjectPackages cliFlags ] where - cliFlags = boptsCLIFlags boptsCli + cliFlags = boptsCli.boptsCLIFlags -- | Get the options to pass to @./Setup.hs configure@ generalCabalConfigOpts :: @@ -229,14 +229,14 @@ generalCabalConfigOpts :: -> Bool -> [Text] generalCabalConfigOpts bconfig boptsCli name isTarget isLocal = concat - [ Map.findWithDefault [] CCKEverything (configCabalConfigOpts config) + [ Map.findWithDefault [] CCKEverything config.configCabalConfigOpts , if isLocal - then Map.findWithDefault [] CCKLocals (configCabalConfigOpts config) + then Map.findWithDefault [] CCKLocals config.configCabalConfigOpts else [] , if isTarget - then Map.findWithDefault [] CCKTargets (configCabalConfigOpts config) + then Map.findWithDefault [] CCKTargets config.configCabalConfigOpts else [] - , Map.findWithDefault [] (CCKPackage name) (configCabalConfigOpts config) + , Map.findWithDefault [] (CCKPackage name) config.configCabalConfigOpts , if includeExtraOptions then boptsCLIAllProgOptions boptsCli else [] @@ -244,7 +244,7 @@ generalCabalConfigOpts bconfig boptsCli name isTarget isLocal = concat where config = view configL bconfig includeExtraOptions = - case configApplyProgOptions config of + case config.configApplyProgOptions of APOTargets -> isTarget APOLocals -> isLocal APOEverything -> True @@ -253,27 +253,27 @@ generalCabalConfigOpts bconfig boptsCli name isTarget isLocal = concat -- configuration and commandline. generalGhcOptions :: BuildConfig -> BuildOptsCLI -> Bool -> Bool -> [Text] generalGhcOptions bconfig boptsCli isTarget isLocal = concat - [ Map.findWithDefault [] AGOEverything (configGhcOptionsByCat config) + [ Map.findWithDefault [] AGOEverything config.configGhcOptionsByCat , if isLocal - then Map.findWithDefault [] AGOLocals (configGhcOptionsByCat config) + then Map.findWithDefault [] AGOLocals config.configGhcOptionsByCat else [] , if isTarget - then Map.findWithDefault [] AGOTargets (configGhcOptionsByCat config) + then Map.findWithDefault [] AGOTargets config.configGhcOptionsByCat else [] - , concat [["-fhpc"] | isLocal && toCoverage (boptsTestOpts bopts)] - , if boptsLibProfile bopts || boptsExeProfile bopts + , concat [["-fhpc"] | isLocal && bopts.boptsTestOpts.toCoverage] + , if bopts.boptsLibProfile || bopts.boptsExeProfile then ["-fprof-auto", "-fprof-cafs"] else [] - , [ "-g" | not $ boptsLibStrip bopts || boptsExeStrip bopts ] + , [ "-g" | not $ bopts.boptsLibStrip || bopts.boptsExeStrip ] , if includeExtraOptions - then boptsCLIGhcOptions boptsCli + then boptsCli.boptsCLIGhcOptions else [] ] where - bopts = configBuild config + bopts = config.configBuild config = view configL bconfig includeExtraOptions = - case configApplyGhcOptions config of + case config.configApplyGhcOptions of AGOTargets -> isTarget AGOLocals -> isLocal AGOEverything -> True @@ -285,10 +285,10 @@ loadCommonPackage :: loadCommonPackage common = do config <- getPackageConfig - (cpFlags common) - (cpGhcOptions common) - (cpCabalConfigOpts common) - gpkg <- liftIO $ cpGPD common + common.cpFlags + common.cpGhcOptions + common.cpCabalConfigOpts + gpkg <- liftIO common.cpGPD pure $ resolvePackage config gpkg -- | Upgrade the initial project package info to a full-blown @LocalPackage@ @@ -299,16 +299,16 @@ loadLocalPackage :: -> RIO env LocalPackage loadLocalPackage pp = do sm <- view sourceMapL - let common = ppCommon pp + let common = pp.ppCommon bopts <- view buildOptsL - mcurator <- view $ buildConfigL . to bcCurator + mcurator <- view $ buildConfigL . to (.bcCurator) config <- getPackageConfig - (cpFlags common) - (cpGhcOptions common) - (cpCabalConfigOpts common) + common.cpFlags + common.cpGhcOptions + common.cpCabalConfigOpts gpkg <- ppGPD pp - let name = cpName common - mtarget = M.lookup name (smtTargets $ smTargets sm) + let name = common.cpName + mtarget = M.lookup name sm.smTargets.smtTargets (exeCandidates, testCandidates, benchCandidates) = case mtarget of Just (TargetComps comps) -> @@ -318,14 +318,14 @@ loadLocalPackage pp = do in (e, t, b) Just (TargetAll _packageType) -> ( buildableExes pkg - , if boptsTests bopts - && maybe True (Set.notMember name . curatorSkipTest) mcurator + , if bopts.boptsTests + && maybe True (Set.notMember name . (.curatorSkipTest)) mcurator then buildableTestSuites pkg else Set.empty - , if boptsBenchmarks bopts + , if bopts.boptsBenchmarks && maybe True - (Set.notMember name . curatorSkipBenchmark) + (Set.notMember name . (.curatorSkipBenchmark)) mcurator then buildableBenchmarks pkg else Set.empty @@ -341,10 +341,10 @@ loadLocalPackage pp = do Just _ -> hasBuildableMainLibrary pkg || not (Set.null nonLibComponents) - || not (null $ packageSubLibraries pkg) + || not (null pkg.packageSubLibraries) filterSkippedComponents = - Set.filter (not . (`elem` boptsSkipComponents bopts)) + Set.filter (not . (`elem` bopts.boptsSkipComponents)) (exes, tests, benches) = ( filterSkippedComponents exeCandidates , filterSkippedComponents testCandidates @@ -380,7 +380,7 @@ loadLocalPackage pp = do | otherwise = Just (resolvePackage btconfig gpkg) componentFiles <- memoizeRefWith $ - fst <$> getPackageFilesForTargets pkg (ppCabalFP pp) nonLibComponents + fst <$> getPackageFilesForTargets pkg pp.ppCabalFP nonLibComponents checkCacheResults <- memoizeRefWith $ do componentFiles' <- runMemoizedWith componentFiles @@ -408,11 +408,11 @@ loadLocalPackage pp = do { lpPackage = pkg , lpTestBench = btpkg , lpComponentFiles = componentFiles - , lpBuildHaddocks = cpHaddocks (ppCommon pp) - , lpForceDirty = boptsForceDirty bopts + , lpBuildHaddocks = pp.ppCommon.cpHaddocks + , lpForceDirty = bopts.boptsForceDirty , lpDirtyFiles = dirtyFiles , lpNewBuildCaches = newBuildCaches - , lpCabalFile = ppCabalFP pp + , lpCabalFile = pp.ppCabalFP , lpWanted = isWanted , lpComponents = nonLibComponents -- TODO: refactor this so that it's easier to be sure that these @@ -454,7 +454,7 @@ checkBuildCache oldCache files = do go fp _ _ | takeFileName fp == "cabal_macros.h" = pure (Set.empty, Map.empty) -- Common case where it's in the cache and on the filesystem. go fp (Just digest') (Just fci) - | fciHash fci == digest' = pure (Set.empty, Map.singleton fp fci) + | fci.fciHash == digest' = pure (Set.empty, Map.singleton fp fci) | otherwise = pure (Set.singleton fp, Map.singleton fp $ FileCacheInfo digest') -- Missing file. Add it to dirty files, but no FileCacheInfo. @@ -515,7 +515,7 @@ getPackageFilesForTargets pkg cabalFP nonLibComponents = do -- | Get file digest, if it exists getFileDigestMaybe :: HasEnvConfig env => FilePath -> RIO env (Maybe SHA256) getFileDigestMaybe fp = do - cache <- view $ envConfigL . to envConfigFileDigestCache + cache <- view $ envConfigL . to (.envConfigFileDigestCache) catch (Just <$> readFileDigest cache fp) (\e -> if isDoesNotExistError e then pure Nothing else throwM e) diff --git a/src/Stack/Build/Target.hs b/src/Stack/Build/Target.hs index c355f7bf27..73ef90aad4 100644 --- a/src/Stack/Build/Target.hs +++ b/src/Stack/Build/Target.hs @@ -2,6 +2,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE MultiWayIf #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE ViewPatterns #-} @@ -106,7 +107,7 @@ getRawInput :: -> Map PackageName ProjectPackage -> ([Text], [RawInput]) getRawInput boptscli locals = - let textTargets' = boptsCLITargets boptscli + let textTargets' = boptscli.boptsCLITargets textTargets = -- Handle the no targets case, which means we pass in the names of all -- project packages @@ -253,9 +254,9 @@ resolveRawTarget :: resolveRawTarget sma allLocs (ri, rt) = go rt where - locals = smaProject sma - deps = smaDeps sma - globals = smaGlobal sma + locals = sma.smaProject + deps = sma.smaDeps + globals = sma.smaGlobal -- Helper function: check if a 'NamedComponent' matches the given -- 'ComponentName' isCompNamed :: ComponentName -> NamedComponent -> Bool @@ -487,23 +488,23 @@ combineResolveResults :: ) combineResolveResults results = do addedDeps <- fmap Map.unions $ forM results $ \result -> - case rrAddedDep result of + case result.rrAddedDep of Nothing -> pure Map.empty - Just pl -> pure $ Map.singleton (rrName result) pl + Just pl -> pure $ Map.singleton result.rrName pl let m0 = Map.unionsWith (++) $ - map (\rr -> Map.singleton (rrName rr) [rr]) results + map (\rr -> Map.singleton rr.rrName [rr]) results (errs, ms) = partitionEithers $ flip map (Map.toList m0) $ \(name, rrs) -> - let mcomps = map rrComponent rrs in + let mcomps = map (.rrComponent) rrs in -- Confirm that there is either exactly 1 with no component, or that -- all rrs are components case rrs of [] -> assert False $ Left $ flow "Somehow got no rrComponent values, that can't happen." - [rr] | isNothing (rrComponent rr) -> - Right $ Map.singleton name $ TargetAll $ rrPackageType rr + [rr] | isNothing rr.rrComponent -> + Right $ Map.singleton name $ TargetAll rr.rrPackageType _ | all isJust mcomps -> Right $ Map.singleton name $ TargetComps $ Set.fromList $ @@ -519,7 +520,7 @@ combineResolveResults results = do pure (errs, Map.unions ms, addedDeps) where rrToStyleDoc :: ResolveResult -> StyleDoc - rrToStyleDoc = fromString . T.unpack . unRawInput . rrRaw + rrToStyleDoc = fromString . T.unpack . (.rrRaw.unRawInput) -------------------------------------------------------------------------------- -- OK, let's do it! @@ -536,13 +537,13 @@ parseTargets needTargets haddockDeps boptscli smActual = do logDebug "Parsing the targets" bconfig <- view buildConfigL workingDir <- getCurrentDir - locals <- view $ buildConfigL.to (smwProject . bcSMWanted) + locals <- view $ buildConfigL . to (.bcSMWanted.smwProject) let (textTargets', rawInput) = getRawInput boptscli locals (errs1, concat -> rawTargets) <- fmap partitionEithers $ forM rawInput $ parseRawTargetDirs workingDir locals - let depLocs = Map.map dpLocation $ smaDeps smActual + let depLocs = Map.map (.dpLocation) smActual.smaDeps (errs2, resolveResults) <- fmap partitionEithers $ forM rawTargets $ resolveRawTarget smActual depLocs @@ -581,7 +582,7 @@ parseTargets needTargets haddockDeps boptscli smActual = do } where bcImplicitGlobal bconfig = - case configProject $ bcConfig bconfig of + case bconfig.bcConfig.configProject of PCProject _ -> False PCGlobalProject -> True PCNoProject _ -> False diff --git a/src/Stack/BuildPlan.hs b/src/Stack/BuildPlan.hs index 436e7a3e3c..dda69d55d8 100644 --- a/src/Stack/BuildPlan.hs +++ b/src/Stack/BuildPlan.hs @@ -1,6 +1,7 @@ {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE DataKinds #-} {-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Resolving a build plan for a set of packages in a given Stackage snapshot. @@ -354,7 +355,7 @@ compareBuildPlanCheck -- Note: order of comparison flipped, since it's better to have fewer errors. compare (Map.size e2) (Map.size e1) compareBuildPlanCheck (BuildPlanCheckFail _ e1 _) (BuildPlanCheckFail _ e2 _) = - let numUserPkgs e = Map.size $ Map.unions (Map.elems (fmap deNeededBy e)) + let numUserPkgs e = Map.size $ Map.unions (Map.elems (fmap (.deNeededBy) e)) in compare (numUserPkgs e2) (numUserPkgs e1) compareBuildPlanCheck BuildPlanCheckOk{} BuildPlanCheckOk{} = EQ compareBuildPlanCheck BuildPlanCheckOk{} BuildPlanCheckPartial{} = GT @@ -379,16 +380,16 @@ checkSnapBuildPlan :: checkSnapBuildPlan pkgDirs flags snapCandidate = do platform <- view platformL sma <- snapCandidate pkgDirs - gpds <- liftIO $ forM (Map.elems $ smaProject sma) (cpGPD . ppCommon) + gpds <- liftIO $ forM (Map.elems sma.smaProject) (.ppCommon.cpGPD) - let compiler = smaCompiler sma + let compiler = sma.smaCompiler globalVersion (GlobalPackageVersion v) = v depVersion dep - | PLImmutable loc <- dpLocation dep = Just $ packageLocationVersion loc + | PLImmutable loc <- dep.dpLocation = Just $ packageLocationVersion loc | otherwise = Nothing snapPkgs = Map.union - (Map.mapMaybe depVersion $ smaDeps sma) - (Map.map globalVersion $ smaGlobal sma) + (Map.mapMaybe depVersion sma.smaDeps) + (Map.map globalVersion sma.smaGlobal) (f, errs) = checkBundleBuildPlan platform compiler snapPkgs flags gpds cerrs = compilerErrors compiler errs @@ -501,7 +502,7 @@ showCompilerErrors flags errs compiler = T.concat [ compilerVersionText compiler , " cannot be used for these packages:\n" - , showMapPackages $ Map.unions (Map.elems (fmap deNeededBy errs)) + , showMapPackages $ Map.unions (Map.elems (fmap (.deNeededBy) errs)) , showDepErrors flags errs -- TODO only in debug mode ] @@ -539,5 +540,5 @@ showDepErrors flags errs = ] flagVals = T.concat (map showFlags userPkgs) - userPkgs = Map.keys $ Map.unions (Map.elems (fmap deNeededBy errs)) + userPkgs = Map.keys $ Map.unions (Map.elems (fmap (.deNeededBy) errs)) showFlags pkg = maybe "" (showPackageFlags pkg) (Map.lookup pkg flags) diff --git a/src/Stack/CLI.hs b/src/Stack/CLI.hs index 5a9b61fab6..7c852c9309 100644 --- a/src/Stack/CLI.hs +++ b/src/Stack/CLI.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.CLI ( commandLineHandler @@ -456,7 +457,7 @@ commandLineHandler currentDir progName isInterpreter = ( \so gom -> gom { globalMonoidResolverRoot = - First $ Just $ takeDirectory $ soFile so + First $ Just $ takeDirectory so.soFile } ) (globalOpts OtherCmdGlobalOpts) diff --git a/src/Stack/Clean.hs b/src/Stack/Clean.hs index e57bc76384..f64c5efe82 100644 --- a/src/Stack/Clean.hs +++ b/src/Stack/Clean.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @clean@ and @purge@ commands. module Stack.Clean @@ -80,7 +81,7 @@ cleanDir dir = do dirsToDelete :: CleanOpts -> RIO BuildConfig [Path Abs Dir] dirsToDelete cleanOpts = do - packages <- view $ buildConfigL.to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) case cleanOpts of CleanShallow [] -> -- Filter out packages listed as extra-deps diff --git a/src/Stack/Component.hs b/src/Stack/Component.hs index 9eb8553149..d9fe3b99d6 100644 --- a/src/Stack/Component.hs +++ b/src/Stack/Component.hs @@ -171,16 +171,16 @@ gatherComponentToolsAndDepsFromCabal legacyBuildTools buildTools targetDeps = sbi (Cabal.ExeDependency pName (Cabal.mkUnqualComponentName exeName) range) Nothing -> sbi - {sbiUnknownTools = Set.insert (pack exeName) $ sbiUnknownTools sbi} + {sbiUnknownTools = Set.insert (pack exeName) sbi.sbiUnknownTools} processExeDependency sbi exeDep@(Cabal.ExeDependency pName _ _) | isPreInstalledPackages pName = sbi | otherwise = sbi { sbiDependency = - Map.insert pName (cabalExeToStackDep exeDep) $ sbiDependency sbi + Map.insert pName (cabalExeToStackDep exeDep) sbi.sbiDependency } processDependency sbi dep@(Cabal.Dependency pName _ _) = sbi { sbiDependency = - Map.insert pName (cabalToStackDep dep) $ sbiDependency sbi + Map.insert pName (cabalToStackDep dep) sbi.sbiDependency } componentDependencyMap :: diff --git a/src/Stack/ComponentFile.hs b/src/Stack/ComponentFile.hs index ca680f1475..8cbb97dd9c 100644 --- a/src/Stack/ComponentFile.hs +++ b/src/Stack/ComponentFile.hs @@ -79,7 +79,7 @@ stackBenchmarkFiles :: StackBenchmark -> RIO GetPackageFileContext (NamedComponent, ComponentFile) stackBenchmarkFiles bench = - resolveComponentFiles (CBench $ unqualCompToText bench.name) build names + resolveComponentFiles (CBench bench.name.unqualCompToText) build names where names = bnames <> exposed exposed = @@ -94,7 +94,7 @@ stackTestSuiteFiles :: StackTestSuite -> RIO GetPackageFileContext (NamedComponent, ComponentFile) stackTestSuiteFiles test = - resolveComponentFiles (CTest $ unqualCompToText test.name) build names + resolveComponentFiles (CTest test.name.unqualCompToText) build names where names = bnames <> exposed exposed = @@ -110,7 +110,7 @@ stackExecutableFiles :: StackExecutable -> RIO GetPackageFileContext (NamedComponent, ComponentFile) stackExecutableFiles exe = - resolveComponentFiles (CExe $ unqualCompToText exe.name) build names + resolveComponentFiles (CExe exe.name.unqualCompToText) build names where build = exe.buildInfo names = @@ -124,7 +124,7 @@ stackLibraryFiles :: stackLibraryFiles lib = resolveComponentFiles componentName build names where - componentRawName = unqualCompToText lib.name + componentRawName = lib.name.unqualCompToText componentName | componentRawName == mempty = CLib | otherwise = CSubLib componentRawName @@ -144,7 +144,7 @@ resolveComponentFiles :: -> RIO GetPackageFileContext (NamedComponent, ComponentFile) resolveComponentFiles component build names = do dirs <- mapMaybeM (resolveDirOrWarn . getSymbolicPath) build.hsSourceDirs - dir <- asks (parent . ctxFile) + dir <- asks (parent . (.ctxFile)) agdirs <- autogenDirs (modules,files,warnings) <- resolveFilesAndDeps @@ -155,8 +155,8 @@ resolveComponentFiles component build names = do pure (component, ComponentFile modules (files <> cfiles) warnings) where autogenDirs = do - cabalVer <- asks ctxCabalVer - distDir <- asks ctxDistDir + cabalVer <- asks (.ctxCabalVer) + distDir <- asks (.ctxDistDir) let compDir = componentAutogenDir cabalVer component distDir pkgDir = maybeToList $ packageAutogenDir cabalVer distDir filterM doesDirExist $ compDir : pkgDir @@ -272,8 +272,8 @@ getDependencies knownUsages component dirs dotCabalPath = DotCabalCFilePath{} -> pure (S.empty, M.empty) where readResolvedHi resolvedFile = do - dumpHIDir <- componentOutputDir component <$> asks ctxDistDir - dir <- asks (parent . ctxFile) + dumpHIDir <- componentOutputDir component <$> asks (.ctxDistDir) + dir <- asks (parent . (.ctxFile)) let sourceDir = fromMaybe dir $ find (`isProperPrefixOf` resolvedFile) dirs stripSourceDir d = stripProperPrefix d resolvedFile case stripSourceDir sourceDir of @@ -296,7 +296,7 @@ parseHI :: -- ^ The path to the *.hi file to be parsed -> RIO GetPackageFileContext (Set ModuleName, Map FilePath (Path Abs File)) parseHI knownUsages hiPath = do - dir <- asks (parent . ctxFile) + dir <- asks (parent . (.ctxFile)) result <- liftIO $ catchAnyDeep (Iface.fromFile hiPath) @@ -363,8 +363,8 @@ findCandidate :: -> DotCabalDescriptor -> RIO GetPackageFileContext (Maybe DotCabalPath) findCandidate dirs name = do - pkg <- asks ctxFile >>= parsePackageNameFromFilePath - customPreprocessorExts <- view $ configL . to configCustomPreprocessorExts + pkg <- asks (.ctxFile) >>= parsePackageNameFromFilePath + customPreprocessorExts <- view $ configL . to (.configCustomPreprocessorExts) let haskellPreprocessorExts = haskellDefaultPreprocessorExts ++ customPreprocessorExts candidates <- liftIO $ makeNameCandidates haskellPreprocessorExts @@ -460,8 +460,8 @@ buildOtherSources :: -> RIO GetPackageFileContext [DotCabalPath] buildOtherSources build = do cwd <- liftIO getCurrentDir - dir <- asks (parent . ctxFile) - file <- asks ctxFile + dir <- asks (parent . (.ctxFile)) + file <- asks (.ctxFile) let resolveDirFiles files toCabalPath = forMaybeM files $ \fp -> do result <- resolveDirFile dir fp @@ -576,8 +576,8 @@ resolveOrWarn :: -> RIO GetPackageFileContext (Maybe a) resolveOrWarn subject resolver path = do cwd <- liftIO getCurrentDir - file <- asks ctxFile - dir <- asks (parent . ctxFile) + file <- asks (.ctxFile) + dir <- asks (parent . (.ctxFile)) result <- resolver dir path when (isNothing result) $ warnMissingFile subject cwd path file pure result diff --git a/src/Stack/Config.hs b/src/Stack/Config.hs index 286ebfddec..b8980dc269 100644 --- a/src/Stack/Config.hs +++ b/src/Stack/Config.hs @@ -224,19 +224,19 @@ makeConcreteResolver ar = do let fp = implicitGlobalDir stackDotYaml iopc <- loadConfigYaml (parseProjectAndConfigMonoid (parent fp)) fp ProjectAndConfigMonoid project _ <- liftIO iopc - pure $ projectResolver project + pure project.projectResolver ARLatestNightly -> - RSLSynonym . Nightly . snapshotsNightly <$> getSnapshots + RSLSynonym . Nightly . (.snapshotsNightly) <$> getSnapshots ARLatestLTSMajor x -> do snapshots <- getSnapshots - case IntMap.lookup x $ snapshotsLts snapshots of + case IntMap.lookup x snapshots.snapshotsLts of Nothing -> throwIO $ NoLTSWithMajorVersion x Just y -> pure $ RSLSynonym $ LTS x y ARLatestLTS -> do snapshots <- getSnapshots - if IntMap.null $ snapshotsLts snapshots + if IntMap.null snapshots.snapshotsLts then throwIO NoLTSFound - else let (x, y) = IntMap.findMax $ snapshotsLts snapshots + else let (x, y) = IntMap.findMax snapshots.snapshotsLts in pure $ RSLSynonym $ LTS x y prettyInfoL [ flow "Selected resolver:" @@ -249,8 +249,8 @@ getLatestResolver :: HasConfig env => RIO env RawSnapshotLocation getLatestResolver = do snapshots <- getSnapshots let mlts = uncurry LTS <$> - listToMaybe (reverse (IntMap.toList (snapshotsLts snapshots))) - pure $ RSLSynonym $ fromMaybe (Nightly (snapshotsNightly snapshots)) mlts + listToMaybe (reverse (IntMap.toList snapshots.snapshotsLts)) + pure $ RSLSynonym $ fromMaybe (Nightly snapshots.snapshotsNightly) mlts -- Interprets ConfigMonoid options. configFromConfigMonoid :: @@ -320,7 +320,7 @@ configFromConfigMonoid os = defOS configPlatform = Platform arch os configRequireStackVersion = simplifyVersionRange - (getIntersectingVersionRange configMonoid.configMonoidRequireStackVersion) + configMonoid.configMonoidRequireStackVersion.getIntersectingVersionRange configCompilerCheck = fromFirst MatchMinor configMonoid.configMonoidCompilerCheck configPlatformVariant <- liftIO $ maybe PlatformVariantNone PlatformVariant <$> lookupEnv platformVariantEnvVar @@ -329,13 +329,13 @@ configFromConfigMonoid dockerOptsFromMonoid (fmap fst mproject) configResolver configMonoid.configMonoidDockerOpts configNix <- nixOptsFromMonoid configMonoid.configMonoidNixOpts os configSystemGHC <- - case (getFirst configMonoid.configMonoidSystemGHC, nixEnable configNix) of + case (getFirst configMonoid.configMonoidSystemGHC, configNix.nixEnable) of (Just False, True) -> throwM NixRequiresSystemGhc _ -> pure (fromFirst - (dockerEnable configDocker || nixEnable configNix) + (configDocker.dockerEnable || configNix.nixEnable) configMonoid.configMonoidSystemGHC) when (isJust configGHCVariant && configSystemGHC) $ throwM ManualGHCVariantSettingsAreIncompatibleWithSystemGHC @@ -429,7 +429,7 @@ configFromConfigMonoid useAnsi <- liftIO $ hSupportsANSI stderr let stylesUpdate' = (configRunner' ^. stylesUpdateL) <> configMonoid.configMonoidStyles - useColor' = runnerUseColor configRunner' + useColor' = configRunner'.runnerUseColor mUseColor = do colorWhen <- getFirst configMonoid.configMonoidColorWhen pure $ case colorWhen of @@ -441,7 +441,7 @@ configFromConfigMonoid & processContextL .~ origEnv & stylesUpdateL .~ stylesUpdate' & useColorL .~ useColor'' - go = runnerGlobalOpts configRunner' + go = configRunner'.runnerGlobalOpts pic <- case getFirst configMonoid.configMonoidPackageIndex of Nothing -> @@ -479,18 +479,20 @@ configFromConfigMonoid <> "/" <> display day <> ".yaml" mkRSLUrl builder = RSLUrl (utf8BuilderToText builder) Nothing addr' = display $ T.dropWhileEnd (=='/') addr - let configStackDeveloperMode = - fromFirst stackDeveloperModeDefault configMonoid.configMonoidStackDeveloperMode - configCasa = if fromFirstTrue $ casaMonoidEnable configMonoid.configMonoidCasaOpts - then - let casaRepoPrefix = fromFirst - (fromFirst defaultCasaRepoPrefix configMonoid.configMonoidCasaRepoPrefix) - (casaMonoidRepoPrefix configMonoid.configMonoidCasaOpts) - casaMaxKeysPerRequest = fromFirst - defaultCasaMaxPerRequest - (casaMonoidMaxKeysPerRequest configMonoid.configMonoidCasaOpts) - in Just (casaRepoPrefix, casaMaxKeysPerRequest) - else Nothing + let configStackDeveloperMode = fromFirst + stackDeveloperModeDefault + configMonoid.configMonoidStackDeveloperMode + configCasa = + if fromFirstTrue configMonoid.configMonoidCasaOpts.casaMonoidEnable + then + let casaRepoPrefix = fromFirst + (fromFirst defaultCasaRepoPrefix configMonoid.configMonoidCasaRepoPrefix) + configMonoid.configMonoidCasaOpts.casaMonoidRepoPrefix + casaMaxKeysPerRequest = fromFirst + defaultCasaMaxPerRequest + configMonoid.configMonoidCasaOpts.casaMonoidMaxKeysPerRequest + in Just (casaRepoPrefix, casaMaxKeysPerRequest) + else Nothing withNewLogFunc go useColor'' stylesUpdate' $ \logFunc -> do let configRunner = configRunner'' & logFuncL .~ logFunc withLocalLogFunc logFunc $ handleMigrationException $ do @@ -598,10 +600,10 @@ withNewLogFunc go useColor (StylesUpdate update) inner = do $ setLogLevelColors logLevelColors $ setLogSecondaryColor secondaryColor $ setLogAccentColors (const highlightColor) - $ setLogUseTime (globalTimeInLog go) - $ setLogMinLevel (globalLogLevel go) - $ setLogVerboseFormat (globalLogLevel go <= LevelDebug) - $ setLogTerminal (globalTerminal go) + $ setLogUseTime go.globalTimeInLog + $ setLogMinLevel go.globalLogLevel + $ setLogVerboseFormat (go.globalLogLevel <= LevelDebug) + $ setLogTerminal go.globalTerminal logOptions0 withLogFunc logOptions inner where @@ -644,10 +646,10 @@ loadConfig :: => (Config -> RIO env a) -> RIO env a loadConfig inner = do - mstackYaml <- view $ globalOptsL . to globalStackYaml + mstackYaml <- view $ globalOptsL . to (.globalStackYaml) mproject <- loadProjectConfig mstackYaml - mresolver <- view $ globalOptsL . to globalResolver - configArgs <- view $ globalOptsL . to globalConfigMonoid + mresolver <- view $ globalOptsL . to (.globalResolver) + configArgs <- view $ globalOptsL . to (.globalConfigMonoid) (configRoot, stackRoot, userOwnsStackRoot) <- determineStackRootAndOwnership configArgs @@ -665,7 +667,7 @@ loadConfig inner = do -- default docker to enabled, so make it look like they didn't exist map ( \c -> c {configMonoidDockerOpts = - (configMonoidDockerOpts c) {dockerMonoidDefaultEnable = Any False}} + c.configMonoidDockerOpts {dockerMonoidDefaultEnable = Any False}} ) extraConfigs0 @@ -678,10 +680,10 @@ loadConfig inner = do (mconcat $ configArgs : addConfigMonoid extraConfigs) withConfig $ \config -> do - let Platform arch _ = configPlatform config + let Platform arch _ = config.configPlatform case arch of OtherArch unknownArch - | configNotifyIfArchUnknown config -> + | config.configNotifyIfArchUnknown -> prettyWarnL [ flow "Unknown value for architecture setting:" , style Shell (fromString unknownArch) <> "." @@ -690,13 +692,13 @@ loadConfig inner = do , flow "in Stack's configuration." ] _ -> pure () - unless (stackVersion `withinRange` configRequireStackVersion config) - (throwM (BadStackVersionException (configRequireStackVersion config))) - unless (configAllowDifferentUser config) $ do + unless (stackVersion `withinRange` config.configRequireStackVersion) + (throwM (BadStackVersionException config.configRequireStackVersion)) + unless config.configAllowDifferentUser $ do unless userOwnsStackRoot $ throwM (UserDoesn'tOwnDirectory stackRoot) forM_ (configProjectRoot config) $ \dir -> - checkOwnership (dir configWorkDir config) + checkOwnership (dir config.configWorkDir) inner config -- | Load the build configuration, adds build-specific values to config loaded @@ -712,20 +714,20 @@ withBuildConfig inner = do -- to properly deal with an AbstractResolver, we need a base directory (to -- deal with custom snapshot relative paths). We consider the current working -- directory to be the correct base. Let's calculate the mresolver first. - mresolver <- forM (configResolver config) $ \aresolver -> do + mresolver <- forM config.configResolver $ \aresolver -> do logDebug ("Using resolver: " <> display aresolver <> " specified on command line") makeConcreteResolver aresolver - (project', stackYamlFP) <- case configProject config of + (project', stackYamlFP) <- case config.configProject of PCProject (project, fp) -> do - forM_ (projectUserMsg project) prettyWarnS + forM_ project.projectUserMsg prettyWarnS pure (project, fp) PCNoProject extraDeps -> do p <- case mresolver of Nothing -> throwIO NoResolverWhenUsingNoProject Just _ -> getEmptyProject mresolver extraDeps - pure (p, configUserConfigPath config) + pure (p, config.configUserConfigPath) PCGlobalProject -> do logDebug "Run from outside a project, using implicit global project config" destDir <- getImplicitGlobalProjectDir config @@ -740,13 +742,13 @@ withBuildConfig inner = do iopc <- loadConfigYaml (parseProjectAndConfigMonoid destDir) dest ProjectAndConfigMonoid project _ <- liftIO iopc when (view terminalL config) $ - case configResolver config of + case config.configResolver of Nothing -> logDebug $ - "Using resolver: " <> - display (projectResolver project) <> - " from implicit global project's config file: " <> - fromString dest' + "Using resolver: " + <> display project.projectResolver + <> " from implicit global project's config file: " + <> fromString dest' Just _ -> pure () pure (project, dest) else do @@ -764,7 +766,7 @@ withBuildConfig inner = do [ "# This is the implicit global project's config file, which is only used when\n" , "# 'stack' is run outside of a real project. Settings here do _not_ act as\n" , "# defaults for all projects. To change Stack's default settings, edit\n" - , "# '", encodeUtf8 (T.pack $ toFilePath $ configUserConfigPath config), "' instead.\n" + , "# '", encodeUtf8 (T.pack $ toFilePath config.configUserConfigPath), "' instead.\n" , "#\n" , "# For more information about Stack's configuration, see\n" , "# http://docs.haskellstack.org/en/stable/yaml_configuration/\n" @@ -775,14 +777,14 @@ withBuildConfig inner = do "used only when 'stack' is run\noutside of a " <> "real project.\n" pure (p, dest) - mcompiler <- view $ globalOptsL . to globalCompiler + mcompiler <- view $ globalOptsL . to (.globalCompiler) let project = project' - { projectCompiler = mcompiler <|> projectCompiler project' - , projectResolver = fromMaybe (projectResolver project') mresolver + { projectCompiler = mcompiler <|> project'.projectCompiler + , projectResolver = fromMaybe project'.projectResolver mresolver } - extraPackageDBs <- mapM resolveDir' (projectExtraPackageDBs project) + extraPackageDBs <- mapM resolveDir' project.projectExtraPackageDBs - wanted <- lockCachedWanted stackYamlFP (projectResolver project) $ + wanted <- lockCachedWanted stackYamlFP project.projectResolver $ fillProjectWanted stackYamlFP config project -- Unfortunately redoes getProjectWorkDir, since we don't have a BuildConfig @@ -796,7 +798,7 @@ withBuildConfig inner = do , bcSMWanted = wanted , bcExtraPackageDBs = extraPackageDBs , bcStackYaml = stackYamlFP - , bcCurator = projectCurator project + , bcCurator = project.projectCurator , bcProjectStorage = projectStorage } runRIO bc inner @@ -844,13 +846,13 @@ fillProjectWanted :: -> Map PackageName (Bool -> RIO env DepPackage) -> RIO env (SMWanted, [CompletedPLI]) fillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages = do - let bopts = configBuild config + let bopts = config.configBuild - packages0 <- for (projectPackages project) $ \fp@(RelFilePath t) -> do + packages0 <- for project.projectPackages $ \fp@(RelFilePath t) -> do abs' <- resolveDir (parent stackYamlFP) (T.unpack t) let resolved = ResolvedPath fp abs' - pp <- mkProjectPackage YesPrintWarnings resolved (boptsHaddock bopts) - pure (cpName $ ppCommon pp, pp) + pp <- mkProjectPackage YesPrintWarnings resolved bopts.boptsHaddock + pure (pp.ppCommon.cpName, pp) -- prefetch git repos to avoid cloning per subdirectory -- see https://github.com/commercialhaskell/stack/issues/5411 @@ -859,11 +861,11 @@ fillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages (RPLImmutable (RPLIRepo repo rpm)) -> Just (repo, rpm) _ -> Nothing ) - (projectDependencies project) + project.projectDependencies logDebug ("Prefetching git repos: " <> display (T.pack (show gitRepos))) fetchReposRaw gitRepos - (deps0, mcompleted) <- fmap unzip . forM (projectDependencies project) $ \rpl -> do + (deps0, mcompleted) <- fmap unzip . forM project.projectDependencies $ \rpl -> do (pl, mCompleted) <- case rpl of RPLImmutable rpli -> do (compl, mcompl) <- @@ -880,17 +882,17 @@ fillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages RPLMutable p -> pure (PLMutable p, Nothing) dp <- additionalDepPackage (shouldHaddockDeps bopts) pl - pure ((cpName $ dpCommon dp, dp), mCompleted) + pure ((dp.dpCommon.cpName, dp), mCompleted) checkDuplicateNames $ - map (second (PLMutable . ppResolvedDir)) packages0 ++ - map (second dpLocation) deps0 + map (second (PLMutable . (.ppResolvedDir))) packages0 ++ + map (second (.dpLocation)) deps0 let packages1 = Map.fromList packages0 snPackages = snapPackages `Map.difference` packages1 `Map.difference` Map.fromList deps0 - `Map.withoutKeys` projectDropPackages project + `Map.withoutKeys` project.projectDropPackages snDeps <- for snPackages $ \getDep -> getDep (shouldHaddockDeps bopts) @@ -898,19 +900,19 @@ fillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages let mergeApply m1 m2 f = MS.merge MS.preserveMissing MS.dropMissing (MS.zipWithMatched f) m1 m2 - pFlags = projectFlags project + pFlags = project.projectFlags packages2 = mergeApply packages1 pFlags $ - \_ p flags -> p{ppCommon=(ppCommon p){cpFlags=flags}} + \_ p flags -> p{ppCommon = p.ppCommon {cpFlags=flags}} deps2 = mergeApply deps1 pFlags $ - \_ d flags -> d{dpCommon=(dpCommon d){cpFlags=flags}} + \_ d flags -> d{dpCommon = d.dpCommon {cpFlags=flags}} checkFlagsUsedThrowing pFlags FSStackYaml packages1 deps1 - let pkgGhcOptions = configGhcOptionsByName config + let pkgGhcOptions = config.configGhcOptionsByName deps = mergeApply deps2 pkgGhcOptions $ - \_ d options -> d{dpCommon=(dpCommon d){cpGhcOptions=options}} + \_ d options -> d{dpCommon = d.dpCommon {cpGhcOptions=options}} packages = mergeApply packages2 pkgGhcOptions $ - \_ p options -> p{ppCommon=(ppCommon p){cpGhcOptions=options}} + \_ p options -> p{ppCommon = p.ppCommon {cpGhcOptions=options}} unusedPkgGhcOptions = pkgGhcOptions `Map.restrictKeys` Map.keysSet packages2 `Map.restrictKeys` Map.keysSet deps2 @@ -919,10 +921,10 @@ fillProjectWanted stackYamlFP config project locCache snapCompiler snapPackages throwM $ InvalidGhcOptionsSpecification (Map.keys unusedPkgGhcOptions) let wanted = SMWanted - { smwCompiler = fromMaybe snapCompiler (projectCompiler project) + { smwCompiler = fromMaybe snapCompiler project.projectCompiler , smwProject = packages , smwDeps = deps - , smwSnapshotLocation = projectResolver project + , smwSnapshotLocation = project.projectResolver } pure (wanted, catMaybes mcompleted) @@ -950,7 +952,7 @@ determineStackRootAndOwnership :: -> m (Path Abs Dir, Path Abs Dir, Bool) determineStackRootAndOwnership clArgs = liftIO $ do (configRoot, stackRoot) <- do - case getFirst (configMonoidStackRoot clArgs) of + case getFirst clArgs.configMonoidStackRoot of Just x -> pure (x, x) Nothing -> do mstackRoot <- lookupEnv stackRootEnvVar diff --git a/src/Stack/Config/Build.hs b/src/Stack/Config/Build.hs index d3e00f557f..07351e9fc0 100644 --- a/src/Stack/Config/Build.hs +++ b/src/Stack/Config/Build.hs @@ -109,7 +109,7 @@ testOptsFromMonoid toMonoid madditional = defaultTestOpts , toDisableRun = fromFirstFalse toMonoid.toMonoidDisableRun , toMaximumTimeSeconds = fromFirst - (toMaximumTimeSeconds defaultTestOpts) + defaultTestOpts.toMaximumTimeSeconds toMonoid.toMonoidMaximumTimeSeconds , toAllowStdin = fromFirstTrue toMonoid.toMonoidAllowStdin } @@ -124,6 +124,6 @@ benchmarkOptsFromMonoid beoMonoid madditional = fmap (\args -> unwords args <> " ") madditional <> getFirst beoMonoid.beoMonoidAdditionalArgs , beoDisableRun = fromFirst - (beoDisableRun defaultBenchmarkOpts) + defaultBenchmarkOpts.beoDisableRun beoMonoid.beoMonoidDisableRun } diff --git a/src/Stack/Config/Docker.hs b/src/Stack/Config/Docker.hs index 65d5cae9b9..4a00590bc6 100644 --- a/src/Stack/Config/Docker.hs +++ b/src/Stack/Config/Docker.hs @@ -38,7 +38,7 @@ instance Exception ConfigDockerException where (_, Just aresolver) -> T.unpack $ utf8BuilderToText $ display aresolver (Just project, Nothing) -> - T.unpack $ utf8BuilderToText $ display $ projectResolver project + T.unpack $ utf8BuilderToText $ display project.projectResolver , "\nUse an LTS resolver, or set the '" , T.unpack dockerImageArgName , "' explicitly, in your configuration file."] @@ -56,7 +56,7 @@ addDefaultTag base mproject maresolver = do Just (ARResolver (RSLSynonym lts@(LTS _ _))) -> pure lts Just _aresolver -> exc Nothing -> - case projectResolver <$> mproject of + case (.projectResolver) <$> mproject of Just (RSLSynonym lts@(LTS _ _)) -> pure lts _ -> exc pure $ base ++ ":" ++ show lts @@ -103,7 +103,8 @@ dockerOptsFromMonoid mproject maresolver dockerMonoid = do dockerEnv = dockerMonoid.dockerMonoidEnv dockerSetUser = getFirst dockerMonoid.dockerMonoidSetUser dockerRequireDockerVersion = - simplifyVersionRange (getIntersectingVersionRange dockerMonoid.dockerMonoidRequireDockerVersion) + simplifyVersionRange + dockerMonoid.dockerMonoidRequireDockerVersion.getIntersectingVersionRange dockerStackExe = getFirst dockerMonoid.dockerMonoidStackExe pure $ DockerOpts { dockerEnable diff --git a/src/Stack/ConfigCmd.hs b/src/Stack/ConfigCmd.hs index 52ccd78840..bfd7c988a3 100644 --- a/src/Stack/ConfigCmd.hs +++ b/src/Stack/ConfigCmd.hs @@ -1,6 +1,7 @@ {-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE GADTs #-} {-# LANGUAGE OverloadedLists #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Make changes to project or global configuration. @@ -89,7 +90,7 @@ cfgCmdSet cmd = do configFilePath <- case configCmdSetScope cmd of CommandScopeProject -> do - mstackYamlOption <- view $ globalOptsL.to globalStackYaml + mstackYamlOption <- view $ globalOptsL . to (.globalStackYaml) mstackYaml <- getProjectConfig mstackYamlOption case mstackYaml of PCProject stackYaml -> pure stackYaml @@ -97,7 +98,7 @@ cfgCmdSet cmd = do fmap ( stackDotYaml) (getImplicitGlobalProjectDir conf) PCNoProject _extraDeps -> throwIO NoProjectConfigAvailable -- maybe modify the ~/.stack/config.yaml file instead? - CommandScopeGlobal -> pure (configUserConfigPath conf) + CommandScopeGlobal -> pure conf.configUserConfigPath rawConfig <- liftIO (readFileUtf8 (toFilePath configFilePath)) config <- either throwM pure (Yaml.decodeEither' $ encodeUtf8 rawConfig) newValue <- cfgCmdSetValue (parent configFilePath) cmd @@ -347,7 +348,7 @@ data EnvVarAction = EVASet !Text | EVAUnset cfgCmdEnv :: EnvSettings -> RIO EnvConfig () cfgCmdEnv es = do origEnv <- liftIO $ Map.fromList . map (first fromString) <$> getEnvironment - mkPC <- view $ configL.to configProcessContextSettings + mkPC <- view $ configL . to (.configProcessContextSettings) pc <- liftIO $ mkPC es let newEnv = pc ^. envVarsL actions = Map.merge diff --git a/src/Stack/Coverage.hs b/src/Stack/Coverage.hs index 548e9a0ede..1d3eb7c86d 100644 --- a/src/Stack/Coverage.hs +++ b/src/Stack/Coverage.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Generate HPC (Haskell Program Coverage) reports module Stack.Coverage @@ -110,9 +111,9 @@ data HpcReportOpts = HpcReportOpts hpcReportCmd :: HpcReportOpts -> RIO Runner () hpcReportCmd hropts = do let (tixFiles, targetNames) = - L.partition (".tix" `T.isSuffixOf`) (hroptsInputs hropts) + L.partition (".tix" `T.isSuffixOf`) hropts.hroptsInputs boptsCLI = defaultBuildOptsCLI - { boptsCLITargets = if hroptsAll hropts then [] else targetNames } + { boptsCLITargets = if hropts.hroptsAll then [] else targetNames } withConfig YesReexec $ withEnvConfig AllowNoTargets boptsCLI $ generateHpcReportForTargets hropts tixFiles targetNames @@ -179,11 +180,11 @@ generateHpcReport pkgDir package tests = do compilerVersion <- view actualCompilerVersionL -- If we're using > GHC 7.10, the hpc 'include' parameter must specify a ghc package key. See -- https://github.com/commercialhaskell/stack/issues/785 - let pkgId = packageIdentifierString (packageIdentifier package) - pkgName' = packageNameString $ packageName package + let pkgId = packageIdentifierString $ packageIdentifier package + pkgName' = packageNameString package.packageName ghcVersion = getGhcVersion compilerVersion hasLibrary = hasBuildableMainLibrary package - subLibs = packageSubLibraries package + subLibs = package.packageSubLibraries eincludeName <- -- Pre-7.8 uses plain PKG-version in tix files. if ghcVersion < mkVersion [7, 10] then pure $ Right $ Just [pkgId] @@ -207,7 +208,7 @@ generateHpcReport pkgDir package tests = do pure $ Left err Right includeNames -> pure $ Right $ Just $ map T.unpack includeNames forM_ tests $ \testName -> do - tixSrc <- tixFilePath (packageName package) (T.unpack testName) + tixSrc <- tixFilePath package.packageName (T.unpack testName) let report = fillSep [ flow "coverage report for" , style Current (fromString pkgName') <> "'s" @@ -284,8 +285,8 @@ generateHpcReportInternal -- Directories for .mix files. hpcRelDir <- hpcRelativeDir -- Compute arguments used for both "hpc markup" and "hpc report". - pkgDirs <- view $ buildConfigL.to - (map ppRoot . Map.elems . smwProject . bcSMWanted) + pkgDirs <- view $ buildConfigL . to + (map ppRoot . Map.elems . (.bcSMWanted.smwProject)) let args = -- Use index files from all packages (allows cross-package -- coverage results). @@ -360,10 +361,10 @@ generateHpcReportForTargets opts tixFiles targetNames = do targetTixFiles <- -- When there aren't any package component arguments, and --all -- isn't passed, default to not considering any targets. - if not (hroptsAll opts) && null targetNames + if not opts.hroptsAll && null targetNames then pure [] else do - when (hroptsAll opts && not (null targetNames)) $ + when (opts.hroptsAll && not (null targetNames)) $ prettyWarnL $ "Since" : style Shell "--all" @@ -371,7 +372,7 @@ generateHpcReportForTargets opts tixFiles targetNames = do : mkNarrativeList (Just Target) False (map (fromString . T.unpack) targetNames :: [StyleDoc]) targets <- - view $ envConfigL.to envConfigSourceMap.to smTargets.to smtTargets + view $ envConfigL . to (.envConfigSourceMap.smTargets.smtTargets) fmap concat $ forM (Map.toList targets) $ \(name, target) -> case target of TargetAll PTDependency -> prettyThrowIO $ NotLocalPackage name @@ -401,7 +402,7 @@ generateHpcReportForTargets opts tixFiles targetNames = do mapM (resolveFile' . T.unpack) tixFiles when (null tixPaths) $ prettyThrowIO NoTargetsOrTixSpecified outputDir <- hpcReportDir - reportDir <- case hroptsDestDir opts of + reportDir <- case opts.hroptsDestDir of Nothing -> pure (outputDir relDirCombined relDirCustom) Just destDir -> do dest <- resolveDir' destDir @@ -411,7 +412,7 @@ generateHpcReportForTargets opts tixFiles targetNames = do reportHtml = "combined coverage report" mreportPath <- generateUnionReport report reportHtml reportDir tixPaths forM_ mreportPath $ \reportPath -> - if hroptsOpenBrowser opts + if opts.hroptsOpenBrowser then do prettyInfo $ "Opening" <+> pretty reportPath <+> "in the browser." void $ liftIO $ openBrowser (toFilePath reportPath) diff --git a/src/Stack/DependencyGraph.hs b/src/Stack/DependencyGraph.hs index d3b198882e..c466330438 100644 --- a/src/Stack/DependencyGraph.hs +++ b/src/Stack/DependencyGraph.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Module exporting a function to create a pruned dependency graph given a -- 'DotOpts' value. @@ -84,12 +85,13 @@ createPrunedDependencyGraph :: Runner (Set PackageName, Map PackageName (Set PackageName, DotPayload)) createPrunedDependencyGraph dotOpts = withDotConfig dotOpts $ do - localNames <- view $ buildConfigL.to (Map.keysSet . smwProject . bcSMWanted) + localNames <- + view $ buildConfigL . to (Map.keysSet . (.bcSMWanted.smwProject)) logDebug "Creating dependency graph" resultGraph <- createDependencyGraph dotOpts - let pkgsToPrune = if dotIncludeBase dotOpts - then dotPrune dotOpts - else Set.insert "base" (dotPrune dotOpts) + let pkgsToPrune = if dotOpts.dotIncludeBase + then dotOpts.dotPrune + else Set.insert "base" dotOpts.dotPrune prunedGraph = pruneGraph localNames pkgsToPrune resultGraph logDebug "Returning pruned dependency graph" pure (localNames, prunedGraph) @@ -101,21 +103,20 @@ withDotConfig :: -> RIO Runner a withDotConfig opts inner = local (over globalOptsL modifyGO) $ - if dotGlobalHints opts + if opts.dotGlobalHints then withConfig NoReexec $ withBuildConfig withGlobalHints else withConfig YesReexec withReal where withGlobalHints = do bconfig <- view buildConfigL - globals <- globalsFromHints $ smwCompiler $ bcSMWanted bconfig + globals <- globalsFromHints bconfig.bcSMWanted.smwCompiler fakeGhcPkgId <- parseGhcPkgId "ignored" actual <- either throwIO pure $ - wantedToActual $ smwCompiler $ - bcSMWanted bconfig + wantedToActual bconfig.bcSMWanted.smwCompiler let smActual = SMActual { smaCompiler = actual - , smaProject = smwProject $ bcSMWanted bconfig - , smaDeps = smwDeps $ bcSMWanted bconfig + , smaProject = bconfig.bcSMWanted.smwProject + , smaDeps = bconfig.bcSMWanted.smwDeps , smaGlobal = Map.mapWithKey toDump globals } toDump :: PackageName -> Version -> DumpPackage @@ -133,42 +134,43 @@ withDotConfig opts inner = , dpHaddockHtml = Nothing , dpIsExposed = True } - actualPkgs = Map.keysSet (smaDeps smActual) <> - Map.keysSet (smaProject smActual) - prunedActual = smActual { smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs } + actualPkgs = + Map.keysSet smActual.smaDeps <> Map.keysSet smActual.smaProject + prunedActual = + smActual { smaGlobal = pruneGlobals smActual.smaGlobal actualPkgs } targets <- parseTargets NeedTargets False boptsCLI prunedActual logDebug "Loading source map" sourceMap <- loadSourceMap targets boptsCLI smActual let dc = DotConfig { dcBuildConfig = bconfig , dcSourceMap = sourceMap - , dcGlobalDump = toList $ smaGlobal smActual + , dcGlobalDump = toList smActual.smaGlobal } logDebug "DotConfig fully loaded" runRIO dc inner withReal = withEnvConfig NeedTargets boptsCLI $ do envConfig <- ask - let sourceMap = envConfigSourceMap envConfig + let sourceMap = envConfig.envConfigSourceMap installMap <- toInstallMap sourceMap (_, globalDump, _, _) <- getInstalled installMap let dc = DotConfig - { dcBuildConfig = envConfigBuildConfig envConfig + { dcBuildConfig = envConfig.envConfigBuildConfig , dcSourceMap = sourceMap , dcGlobalDump = globalDump } runRIO dc inner boptsCLI = defaultBuildOptsCLI - { boptsCLITargets = dotTargets opts - , boptsCLIFlags = dotFlags opts + { boptsCLITargets = opts.dotTargets + , boptsCLIFlags = opts.dotFlags } modifyGO = - (if dotTestTargets opts - then set (globalOptsBuildOptsMonoidL.buildOptsMonoidTestsL) (Just True) + (if opts.dotTestTargets + then set (globalOptsBuildOptsMonoidL . buildOptsMonoidTestsL) (Just True) else id) . - (if dotBenchTargets opts - then set (globalOptsBuildOptsMonoidL.buildOptsMonoidBenchmarksL) (Just True) + (if opts.dotBenchTargets + then set (globalOptsBuildOptsMonoidL . buildOptsMonoidBenchmarksL) (Just True) else id) -- | Create the dependency graph, the result is a map from a package @@ -180,14 +182,18 @@ createDependencyGraph :: -> RIO DotConfig (Map PackageName (Set PackageName, DotPayload)) createDependencyGraph dotOpts = do sourceMap <- view sourceMapL - locals <- for (toList $ smProject sourceMap) loadLocalPackage - let graph = Map.fromList $ projectPackageDependencies dotOpts (filter lpWanted locals) - globalDump <- view $ to dcGlobalDump + locals <- for (toList sourceMap.smProject) loadLocalPackage + let graph = + Map.fromList $ projectPackageDependencies dotOpts (filter (.lpWanted) locals) + globalDump <- view $ to (.dcGlobalDump) -- TODO: Can there be multiple entries for wired-in-packages? If so, -- this will choose one arbitrarily.. - let globalDumpMap = Map.fromList $ map (\dp -> (Stack.Prelude.pkgName (dpPackageIdent dp), dp)) globalDump - globalIdMap = Map.fromList $ map (dpGhcPkgId &&& dpPackageIdent) globalDump - let depLoader = createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps + let globalDumpMap = Map.fromList $ + map (\dp -> (Stack.Prelude.pkgName dp.dpPackageIdent, dp)) globalDump + globalIdMap = + Map.fromList $ map ((.dpGhcPkgId) &&& (.dpPackageIdent)) globalDump + let depLoader = + createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps loadPackageDeps name version loc flags ghcOptions cabalConfigOpts -- Skip packages that can't be loaded - see -- https://github.com/commercialhaskell/stack/issues/2967 @@ -197,10 +203,10 @@ createDependencyGraph dotOpts = do | otherwise = fmap (setOfPackageDeps &&& makePayload loc) (loadPackage loc flags ghcOptions cabalConfigOpts) - resolveDependencies (dotDependencyDepth dotOpts) graph depLoader + resolveDependencies dotOpts.dotDependencyDepth graph depLoader where - makePayload loc pkg = DotPayload (Just $ packageVersion pkg) - (Just $ packageLicense pkg) + makePayload loc pkg = DotPayload (Just pkg.packageVersion) + (Just pkg.packageLicense) (Just $ PLImmutable loc) -- | Resolve the direct (depth 0) external dependencies of the given local @@ -211,19 +217,19 @@ projectPackageDependencies :: -> [(PackageName, (Set PackageName, DotPayload))] projectPackageDependencies dotOpts locals = map (\lp -> let pkg = localPackageToPackage lp - pkgDir = parent $ lpCabalFile lp + pkgDir = parent lp.lpCabalFile packageDepsSet = setOfPackageDeps pkg loc = PLMutable $ ResolvedPath (RelFilePath "N/A") pkgDir - in (packageName pkg, (deps pkg packageDepsSet, lpPayload pkg loc))) + in (pkg.packageName, (deps pkg packageDepsSet, lpPayload pkg loc))) locals where - deps pkg packageDepsSet = if dotIncludeExternal dotOpts - then Set.delete (packageName pkg) packageDepsSet + deps pkg packageDepsSet = if dotOpts.dotIncludeExternal + then Set.delete pkg.packageName packageDepsSet else Set.intersection localNames packageDepsSet - localNames = Set.fromList $ map (packageName . lpPackage) locals + localNames = Set.fromList $ map (.lpPackage.packageName) locals lpPayload pkg loc = - DotPayload (Just $ packageVersion pkg) - (Just $ packageLicense pkg) + DotPayload (Just pkg.packageVersion) + (Just pkg.packageLicense) (Just loc) -- | Given a SourceMap and a dependency loader, load the set of dependencies for @@ -246,27 +252,27 @@ createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps pkgName = fromMaybe (throwIO $ PackageNotFoundBug pkgName) (projectPackageDeps <|> dependencyDeps <|> globalDeps) where - projectPackageDeps = loadDeps <$> Map.lookup pkgName (smProject sourceMap) + projectPackageDeps = loadDeps <$> Map.lookup pkgName sourceMap.smProject where loadDeps pp = do - pkg <- loadCommonPackage (ppCommon pp) + pkg <- loadCommonPackage pp.ppCommon pure (setOfPackageDeps pkg, payloadFromLocal pkg Nothing) dependencyDeps = - loadDeps <$> Map.lookup pkgName (smDeps sourceMap) + loadDeps <$> Map.lookup pkgName sourceMap.smDeps where loadDeps DepPackage{dpLocation=PLMutable dir} = do pp <- mkProjectPackage YesPrintWarnings dir False - pkg <- loadCommonPackage (ppCommon pp) + pkg <- loadCommonPackage pp.ppCommon pure (setOfPackageDeps pkg, payloadFromLocal pkg (Just $ PLMutable dir)) loadDeps dp@DepPackage{dpLocation=PLImmutable loc} = do - let common = dpCommon dp - gpd <- liftIO $ cpGPD common + let common = dp.dpCommon + gpd <- liftIO common.cpGPD let PackageIdentifier name version = PD.package $ PD.packageDescription gpd - flags = cpFlags common - ghcOptions = cpGhcOptions common - cabalConfigOpts = cpCabalConfigOpts common + flags = common.cpFlags + ghcOptions = common.cpGhcOptions + cabalConfigOpts = common.cpCabalConfigOpts assert (pkgName == name) (loadPackageDeps pkgName version loc flags ghcOptions cabalConfigOpts) @@ -277,18 +283,18 @@ createDepLoader sourceMap globalDumpMap globalIdMap loadPackageDeps pkgName = where getDepsFromDump dump = (Set.fromList deps, payloadFromDump dump) where - deps = map ghcIdToPackageName (dpDepends dump) + deps = map ghcIdToPackageName dump.dpDepends ghcIdToPackageName depId = maybe (impureThrow $ DependencyNotFoundBug depId) Stack.Prelude.pkgName (Map.lookup depId globalIdMap) payloadFromLocal pkg = - DotPayload (Just $ packageVersion pkg) (Just $ packageLicense pkg) + DotPayload (Just pkg.packageVersion) (Just pkg.packageLicense) payloadFromDump dp = - DotPayload (Just $ pkgVersion $ dpPackageIdent dp) - (Right <$> dpLicense dp) + DotPayload (Just $ pkgVersion dp.dpPackageIdent) + (Right <$> dp.dpLicense) Nothing -- | Resolve the dependency graph up to (Just depth) or until fixpoint is reached @@ -347,8 +353,7 @@ pruneUnreachable dontPrune = fixpoint prune reachables = F.fold (fst <$> graph') localPackageToPackage :: LocalPackage -> Package -localPackageToPackage lp = - fromMaybe (lpPackage lp) (lpTestBench lp) +localPackageToPackage lp = fromMaybe lp.lpPackage lp.lpTestBench data DotConfig = DotConfig { dcBuildConfig :: !BuildConfig @@ -357,40 +362,40 @@ data DotConfig = DotConfig } instance HasLogFunc DotConfig where - logFuncL = runnerL.logFuncL + logFuncL = runnerL . logFuncL instance HasPantryConfig DotConfig where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasTerm DotConfig where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL instance HasStylesUpdate DotConfig where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasGHCVariant DotConfig where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasPlatform DotConfig where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasRunner DotConfig where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasProcessContext DotConfig where - processContextL = runnerL.processContextL + processContextL = runnerL . processContextL instance HasConfig DotConfig where - configL = buildConfigL.lens bcConfig (\x y -> x { bcConfig = y }) + configL = buildConfigL . lens (.bcConfig) (\x y -> x { bcConfig = y }) {-# INLINE configL #-} instance HasBuildConfig DotConfig where - buildConfigL = lens dcBuildConfig (\x y -> x { dcBuildConfig = y }) + buildConfigL = lens (.dcBuildConfig) (\x y -> x { dcBuildConfig = y }) instance HasSourceMap DotConfig where - sourceMapL = lens dcSourceMap (\x y -> x { dcSourceMap = y }) + sourceMapL = lens (.dcSourceMap) (\x y -> x { dcSourceMap = y }) diff --git a/src/Stack/Docker.hs b/src/Stack/Docker.hs index 537893c107..7a47f4ed89 100644 --- a/src/Stack/Docker.hs +++ b/src/Stack/Docker.hs @@ -98,7 +98,7 @@ getCmdArgs :: getCmdArgs docker imageInfo isRemoteDocker = do config <- view configL deUser <- - if fromMaybe (not isRemoteDocker) (dockerSetUser docker) + if fromMaybe (not isRemoteDocker) docker.dockerSetUser then liftIO $ do duUid <- User.getEffectiveUserID duGid <- User.getEffectiveGroupID @@ -121,9 +121,9 @@ getCmdArgs docker imageInfo isRemoteDocker = do ] ++ ) (liftIO getArgs) - case dockerStackExe (configDocker config) of + case config.configDocker.dockerStackExe of Just DockerStackExeHost - | configPlatform config == dockerContainerPlatform -> do + | config.configPlatform == dockerContainerPlatform -> do exePath <- resolveFile' =<< liftIO getExecutablePath cmdArgs args exePath | otherwise -> throwIO UnsupportedStackExeHostPlatformException @@ -133,13 +133,13 @@ getCmdArgs docker imageInfo isRemoteDocker = do Just (DockerStackExePath path) -> cmdArgs args path Just DockerStackExeDownload -> exeDownload args Nothing - | configPlatform config == dockerContainerPlatform -> do - (exePath,exeTimestamp,misCompatible) <- + | config.configPlatform == dockerContainerPlatform -> do + (exePath, exeTimestamp, misCompatible) <- do exePath <- resolveFile' =<< liftIO getExecutablePath exeTimestamp <- getModificationTime exePath isKnown <- loadDockerImageExeCache - (iiId imageInfo) + imageInfo.iiId exePath exeTimestamp pure (exePath, exeTimestamp, isKnown) @@ -154,7 +154,7 @@ getCmdArgs docker imageInfo isRemoteDocker = do [ "run" , "-v" , toFilePath exePath ++ ":" ++ "/tmp/stack" - , T.unpack (iiId imageInfo) + , T.unpack imageInfo.iiId , "/tmp/stack" , "--version"] sinkNull @@ -164,7 +164,7 @@ getCmdArgs docker imageInfo isRemoteDocker = do Left ExitCodeException{} -> False Right _ -> True saveDockerImageExeCache - (iiId imageInfo) + imageInfo.iiId exePath exeTimestamp compatible @@ -199,7 +199,7 @@ preventInContainer inner = runContainerAndExit :: HasConfig env => RIO env void runContainerAndExit = do config <- view configL - let docker = configDocker config + let docker = config.configDocker checkDockerVersion docker (env, isStdinTerminal, isStderrTerminal, homeDir) <- liftIO $ (,,,) @@ -216,7 +216,7 @@ runContainerAndExit = do muserEnv = lookup "USER" env isRemoteDocker = maybe False (isPrefixOf "tcp://") dockerHost mstackYaml <- for (lookup "STACK_YAML" env) RIO.Directory.makeAbsolute - image <- either throwIO pure (dockerImage docker) + image <- either throwIO pure docker.dockerImage when ( isRemoteDocker && maybe False (isInfixOf "boot2docker") dockerCertPath ) ( prettyWarnS @@ -226,7 +226,7 @@ runContainerAndExit = do imageInfo <- case maybeImageInfo of Just ii -> pure ii Nothing - | dockerAutoPull docker -> do + | docker.dockerAutoPull -> do pullImage docker image mii2 <- inspect image case mii2 of @@ -240,11 +240,11 @@ runContainerAndExit = do platformVariant = show $ hashRepoName image stackRoot = view stackRootL config sandboxHomeDir = sandboxDir homeDirName - isTerm = not (dockerDetach docker) && + isTerm = not docker.dockerDetach && isStdinTerminal && isStdoutTerminal && isStderrTerminal - keepStdinOpen = not (dockerDetach docker) && + keepStdinOpen = not docker.dockerDetach && -- Workaround for https://github.com/docker/docker/issues/12319 -- This is fixed in Docker 1.9.1, but will leave the workaround -- in place for now, for users who haven't upgraded yet. @@ -277,7 +277,7 @@ runContainerAndExit = do (Files.createSymbolicLink (toFilePathNoTrailingSep sshDir) (toFilePathNoTrailingSep (sandboxHomeDir sshRelDir)))) - let mountSuffix = maybe "" (":" ++) (dockerMountMode docker) + let mountSuffix = maybe "" (":" ++) docker.dockerMountMode containerID <- withWorkingDir (toFilePath projectRoot) $ trim . decodeUtf8 <$> readDockerProcess ( concat @@ -302,7 +302,7 @@ runContainerAndExit = do toFilePathNoTrailingSep sandboxHomeDir ++ mountSuffix , "-w", toFilePathNoTrailingSep pwd ] - , case dockerNetwork docker of + , case docker.dockerNetwork of Nothing -> ["--net=host"] Just name -> ["--net=" ++ name] , case muserEnv of @@ -328,14 +328,14 @@ runContainerAndExit = do ) ] , concatMap (\(k,v) -> ["-e", k ++ "=" ++ v]) envVars - , concatMap (mountArg mountSuffix) (extraMount ++ dockerMount docker) - , concatMap (\nv -> ["-e", nv]) (dockerEnv docker) - , case dockerContainerName docker of + , concatMap (mountArg mountSuffix) (extraMount ++ docker.dockerMount) + , concatMap (\nv -> ["-e", nv]) docker.dockerEnv + , case docker.dockerContainerName of Just name -> ["--name=" ++ name] Nothing -> [] , ["-t" | isTerm] , ["-i" | keepStdinOpen] - , dockerRunArgs docker + , docker.dockerRunArgs , [image] , [cmnd] , args @@ -386,7 +386,7 @@ inspects images = do -- containing invalid UTF-8 case eitherDecode (LBS.pack (filter isAscii (decodeUtf8 inspectOut))) of Left msg -> throwIO (InvalidInspectOutputException msg) - Right results -> pure (Map.fromList (map (\r -> (iiId r,r)) results)) + Right results -> pure (Map.fromList (map (\r -> (r.iiId, r)) results)) Left ece | any (`LBS.isPrefixOf` eceStderr ece) missingImagePrefixes -> pure Map.empty @@ -398,9 +398,9 @@ inspects images = do pull :: HasConfig env => RIO env () pull = do config <- view configL - let docker = configDocker config + let docker = config.configDocker checkDockerVersion docker - either throwIO (pullImage docker) (dockerImage docker) + either throwIO (pullImage docker) docker.dockerImage -- | Pull Docker image from registry. pullImage :: (HasProcessContext env, HasTerm env) @@ -412,14 +412,14 @@ pullImage docker image = do [ flow "Pulling image from registry:" , style Current (fromString image) <> "." ] - when (dockerRegistryLogin docker) $ do + when docker.dockerRegistryLogin $ do prettyInfoS "You may need to log in." proc "docker" ( concat [ ["login"] - , maybe [] (\n -> ["--username=" ++ n]) (dockerRegistryUsername docker) - , maybe [] (\p -> ["--password=" ++ p]) (dockerRegistryPassword docker) + , maybe [] (\n -> ["--username=" ++ n]) docker.dockerRegistryUsername + , maybe [] (\p -> ["--password=" ++ p]) docker.dockerRegistryPassword , [takeWhile (/= '/') image] ] ) @@ -454,8 +454,8 @@ checkDockerVersion docker = do throwIO (DockerTooOldException minimumDockerVersion v') | v' `elem` prohibitedDockerVersions -> throwIO (DockerVersionProhibitedException prohibitedDockerVersions v') - | not (v' `withinRange` dockerRequireDockerVersion docker) -> - throwIO (BadDockerVersionException (dockerRequireDockerVersion docker) v') + | not (v' `withinRange` docker.dockerRequireDockerVersion) -> + throwIO (BadDockerVersionException docker.dockerRequireDockerVersion v') | otherwise -> pure () _ -> throwIO InvalidVersionOutputException diff --git a/src/Stack/Dot.hs b/src/Stack/Dot.hs index 2486688079..8dd7a76afa 100644 --- a/src/Stack/Dot.hs +++ b/src/Stack/Dot.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Functions related to Stack's @dot@ command. module Stack.Dot @@ -41,7 +42,7 @@ printGraph dotOpts locals graph = do liftIO $ Text.putStrLn "}" where filteredLocals = - Set.filter (\local' -> local' `Set.notMember` dotPrune dotOpts) locals + Set.filter (\local' -> local' `Set.notMember` dotOpts.dotPrune) locals -- | Print the local nodes with a different style depending on options printLocalNodes :: @@ -53,7 +54,7 @@ printLocalNodes dotOpts locals = liftIO $ Text.putStrLn (Text.intercalate "\n" lpNodes) where applyStyle :: Text -> Text - applyStyle n = if dotIncludeExternal dotOpts + applyStyle n = if dotOpts.dotIncludeExternal then n <> " [style=dashed];" else n <> " [style=solid];" lpNodes :: [Text] diff --git a/src/Stack/Exec.hs b/src/Stack/Exec.hs index 7ed8ef7065..9dcbf8f3f9 100644 --- a/src/Stack/Exec.hs +++ b/src/Stack/Exec.hs @@ -107,7 +107,7 @@ execCmd opts = unless (null targets) $ build Nothing config <- view configL - menv <- liftIO $ configProcessContextSettings config eo.eoEnvSettings + menv <- liftIO $ config.configProcessContextSettings eo.eoEnvSettings withProcessContext menv $ do -- Add RTS options to arguments let argsWithRts args = if null eo.eoRtsOptions @@ -144,7 +144,7 @@ execCmd opts = map ("-package-id=" ++) <$> mapM getPkgId pkgs getRunCmd args = do - packages <- view $ buildConfigL . to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) pkgComponents <- for (Map.elems packages) ppComponents let executables = concatMap (filter isCExe . Set.toList) pkgComponents let (exe, args') = case args of @@ -162,12 +162,12 @@ execCmd opts = getGhcCmd pkgs args = do pkgopts <- getPkgOpts pkgs - compiler <- view $ compilerPathsL . to cpCompiler + compiler <- view $ compilerPathsL . to (.cpCompiler) pure (toFilePath compiler, pkgopts ++ args) getRunGhcCmd pkgs args = do pkgopts <- getPkgOpts pkgs - interpret <- view $ compilerPathsL . to cpInterpreter + interpret <- view $ compilerPathsL . to (.cpInterpreter) pure (toFilePath interpret, pkgopts ++ args) runWithPath :: Maybe FilePath -> RIO EnvConfig () -> RIO EnvConfig () diff --git a/src/Stack/GhcPkg.hs b/src/Stack/GhcPkg.hs index 647df0c82f..71d3a317b1 100644 --- a/src/Stack/GhcPkg.hs +++ b/src/Stack/GhcPkg.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Functions for the GHC package database. @@ -168,7 +169,7 @@ unregisterGhcPkgIds :: -> NonEmpty (Either PackageIdentifier GhcPkgId) -> RIO env () unregisterGhcPkgIds isWarn pkgexe pkgDb epgids = do - globalDb <- view $ compilerPathsL.to cpGlobalDB + globalDb <- view $ compilerPathsL . to (.cpGlobalDB) eres <- try $ do ghcPkgUnregisterForce globalDb pkgDb hasIpid pkgarg_strs -- ghcPkgUnregisterForce does not perform an effective diff --git a/src/Stack/Ghci.hs b/src/Stack/Ghci.hs index b3a802c5e8..fc4029c1cb 100644 --- a/src/Stack/Ghci.hs +++ b/src/Stack/Ghci.hs @@ -200,18 +200,18 @@ ghciCmd :: GhciOpts -> RIO Runner () ghciCmd ghciOpts = let boptsCLI = defaultBuildOptsCLI -- using only additional packages, targets then get overridden in `ghci` - { boptsCLITargets = map T.pack (ghciAdditionalPackages ghciOpts) + { boptsCLITargets = map T.pack ghciOpts.ghciAdditionalPackages , boptsCLIInitialBuildSteps = True - , boptsCLIFlags = ghciFlags ghciOpts - , boptsCLIGhcOptions = map T.pack (ghciGhcOptions ghciOpts) + , boptsCLIFlags = ghciOpts.ghciFlags + , boptsCLIGhcOptions = map T.pack ghciOpts.ghciGhcOptions } in withConfig YesReexec $ withEnvConfig AllowNoTargets boptsCLI $ do bopts <- view buildOptsL -- override env so running of tests and benchmarks is disabled let boptsLocal = bopts - { boptsTestOpts = (boptsTestOpts bopts) { toDisableRun = True } + { boptsTestOpts = bopts.boptsTestOpts { toDisableRun = True } , boptsBenchmarkOpts = - (boptsBenchmarkOpts bopts) { beoDisableRun = True } + bopts.boptsBenchmarkOpts { beoDisableRun = True } } local (set buildOptsL boptsLocal) (ghci ghciOpts) @@ -224,18 +224,18 @@ ghci opts = do { boptsCLITargets = [] , boptsCLIFlags = opts.ghciFlags } - sourceMap <- view $ envConfigL . to envConfigSourceMap + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) installMap <- toInstallMap sourceMap locals <- projectLocalPackages depLocals <- localDependencies let localMap = - M.fromList [(packageName $ lpPackage lp, lp) | lp <- locals ++ depLocals] + M.fromList [(lp.lpPackage.packageName, lp) | lp <- locals ++ depLocals] -- FIXME:qrilka this looks wrong to go back to SMActual sma = SMActual - { smaCompiler = smCompiler sourceMap - , smaProject = smProject sourceMap - , smaDeps = smDeps sourceMap - , smaGlobal = smGlobal sourceMap + { smaCompiler = sourceMap.smCompiler + , smaProject = sourceMap.smProject + , smaDeps = sourceMap.smDeps + , smaGlobal = sourceMap.smGlobal } -- Parse --main-is argument. mainIsTargets <- parseMainIsTargets buildOptsCLI sma opts.ghciMainIs @@ -255,7 +255,7 @@ ghci opts = do -- Get a list of all the non-local target packages. nonLocalTargets <- getAllNonLocalTargets inputTargets let getInternalDependencies target localPackage = - topSortPackageComponent (lpPackage localPackage) target False + topSortPackageComponent localPackage.lpPackage target False internalDependencies = M.intersectionWith getInternalDependencies inputTargets localMap relevantDependencies = M.filter (any isCSubLib) internalDependencies @@ -328,7 +328,7 @@ preprocessTargets buildOptsCLI sma rawTargets = do prettyThrowM $ GhciTargetParseException xs _ -> throwM pex unless (null fileTargetsRaw) $ throwM Can'tSpecifyFilesAndTargets - pure (Right $ smtTargets normalTargets) + pure (Right normalTargets.smtTargets) parseMainIsTargets :: HasEnvConfig env @@ -339,7 +339,7 @@ parseMainIsTargets :: parseMainIsTargets buildOptsCLI sma mtarget = forM mtarget $ \target -> do let boptsCLI = buildOptsCLI { boptsCLITargets = [target] } targets <- parseTargets AllowNoTargets False boptsCLI sma - pure $ smtTargets targets + pure targets.smtTargets -- | Display PackageName + NamedComponent displayPkgComponent :: (PackageName, NamedComponent) -> StyleDoc @@ -353,12 +353,12 @@ findFileTargets :: -> RIO env (Map PackageName Target, Map PackageName [Path Abs File], [Path Abs File]) findFileTargets locals fileTargets = do filePackages <- forM locals $ \lp -> do - PackageComponentFile _ compFiles _ _ <- getPackageFile (lpPackage lp) (lpCabalFile lp) + PackageComponentFile _ compFiles _ _ <- getPackageFile lp.lpPackage lp.lpCabalFile pure (lp, M.map (map dotCabalGetPath) compFiles) let foundFileTargetComponents :: [(Path Abs File, [(PackageName, NamedComponent)])] foundFileTargetComponents = map (\fp -> (fp, ) $ L.sort $ - concatMap (\(lp, files) -> map ((packageName (lpPackage lp), ) . fst) + concatMap (\(lp, files) -> map ((lp.lpPackage.packageName,) . fst) (filter (elem fp . snd) (M.toList files)) ) filePackages ) fileTargets @@ -417,13 +417,13 @@ getAllLocalTargets ghciOpts targets0 mainIsTargets localMap = do -- independently in order to handle the case where no targets are -- specified. let targets = maybe targets0 (unionTargets targets0) mainIsTargets - packages <- view $ envConfigL . to envConfigSourceMap . to smProject + packages <- view $ envConfigL . to (.envConfigSourceMap.smProject) -- Find all of the packages that are directly demanded by the -- targets. let directlyWanted = flip mapMaybe (M.toList packages) $ \(name, pp) -> case M.lookup name targets of - Just simpleTargets -> Just (name, (ppCabalFP pp, simpleTargets)) + Just simpleTargets -> Just (name, (pp.ppCabalFP, simpleTargets)) Nothing -> Nothing -- Figure out let extraLoadDeps = @@ -533,20 +533,20 @@ runGhci ++ M.foldMapWithKey subDepsPackageUnhide exposeInternalDep else [] oneWordOpts bio - | shouldHidePackages = bioOneWordOpts bio ++ bioPackageFlags bio - | otherwise = bioOneWordOpts bio + | shouldHidePackages = bio.bioOneWordOpts ++ bio.bioPackageFlags + | otherwise = bio.bioOneWordOpts genOpts = nubOrd - (concatMap (concatMap (oneWordOpts . snd) . ghciPkgOpts) pkgs) + (concatMap (concatMap (oneWordOpts . snd) . (.ghciPkgOpts)) pkgs) (omittedOpts, ghcOpts) = L.partition badForGhci $ - concatMap (concatMap (bioOpts . snd) . ghciPkgOpts) pkgs + concatMap (concatMap ((.bioOpts) . snd) . (.ghciPkgOpts)) pkgs ++ map T.unpack - ( fold (configGhcOptionsByCat config) + ( fold config.configGhcOptionsByCat -- ^ include everything, locals, and targets - ++ concatMap (getUserOptions . ghciPkgName) pkgs + ++ concatMap (getUserOptions . (.ghciPkgName)) pkgs ) getUserOptions pkg = - M.findWithDefault [] pkg (configGhcOptionsByName config) + M.findWithDefault [] pkg config.configGhcOptionsByName badForGhci x = L.isPrefixOf "-O" x || elem x (words "-debug -threaded -ticky -static -Werror") @@ -567,12 +567,13 @@ runGhci prettyInfoL ( flow "Configuring GHCi with the following packages:" : mkNarrativeList (Just Current) False - (map (fromPackageName . ghciPkgName) pkgs :: [StyleDoc]) + (map (fromPackageName . (.ghciPkgName)) pkgs :: [StyleDoc]) ) - compilerExeName <- view $ compilerPathsL . to cpCompiler . to toFilePath + compilerExeName <- + view $ compilerPathsL . to (.cpCompiler) . to toFilePath let execGhci extras = do menv <- - liftIO $ configProcessContextSettings config defaultEnvSettings + liftIO $ config.configProcessContextSettings defaultEnvSettings withPackageWorkingDir $ withProcessContext menv $ exec (fromMaybe compilerExeName ghciOpts.ghciGhcCommand) ( ("--interactive" : ) $ @@ -587,7 +588,7 @@ runGhci ) withPackageWorkingDir = case pkgs of - [pkg] -> withWorkingDir (toFilePath $ ghciPkgDir pkg) + [pkg] -> withWorkingDir (toFilePath pkg.ghciPkgDir) _ -> id -- Since usage of 'exec' does not pure, we cannot do any cleanup on ghci -- exit. So, instead leave the generated files. To make this more @@ -618,8 +619,8 @@ writeMacrosFile :: -> RIO env [String] writeMacrosFile outputDirectory pkgs = do fps <- fmap (nubOrd . catMaybes . concat) $ - forM pkgs $ \pkg -> forM (ghciPkgOpts pkg) $ \(_, bio) -> do - let cabalMacros = bioCabalMacros bio + forM pkgs $ \pkg -> forM pkg.ghciPkgOpts $ \(_, bio) -> do + let cabalMacros = bio.bioCabalMacros exists <- liftIO $ doesFileExist cabalMacros if exists then pure $ Just cabalMacros @@ -667,7 +668,7 @@ renderScript pkgs mainFile onlyMain extraFiles = do let addPhase = cmdAdd $ S.fromList (map Left allModules ++ addMain) addMain = maybe [] (L.singleton . Right) mainFile modulePhase = cmdModule $ S.fromList allModules - allModules = nubOrd $ concatMap (M.keys . ghciPkgModules) pkgs + allModules = nubOrd $ concatMap (M.keys . (.ghciPkgModules)) pkgs case getFileTargets pkgs <> extraFiles of [] -> if onlyMain @@ -681,7 +682,7 @@ renderScript pkgs mainFile onlyMain extraFiles = do -- Hacky check if module / main phase should be omitted. This should be -- improved if / when we have a better per-component load. getFileTargets :: [GhciPkgInfo] -> [Path Abs File] -getFileTargets = concatMap (concat . maybeToList . ghciPkgTargetFiles) +getFileTargets = concatMap (concat . maybeToList . (.ghciPkgTargetFiles)) -- | Figure out the main-is file to load based on the targets. Asks the user for -- input if there is more than one candidate main-is file. @@ -752,18 +753,18 @@ figureOutMainFile bopts mainIsTargets targets0 packages = mainIsTargets candidates = do pkg <- packages - case M.lookup (ghciPkgName pkg) targets of + case M.lookup pkg.ghciPkgName targets of Nothing -> [] Just target -> do (component,mains) <- M.toList $ M.filterWithKey (\k _ -> k `S.member` wantedComponents) - (ghciPkgMainIs pkg) + pkg.ghciPkgMainIs main <- mains - pure (ghciPkgName pkg, component, main) + pure (pkg.ghciPkgName, component, main) where wantedComponents = - wantedPackageComponents bopts target (ghciPkgPackage pkg) + wantedPackageComponents bopts target pkg.ghciPkgPackage renderCandidate c@(pkgName, namedComponent, mainIs) = let candidateIndex = fromString . show . (+1) . fromMaybe 0 . L.elemIndex c @@ -841,19 +842,19 @@ loadGhciPkgDesc :: loadGhciPkgDesc buildOptsCLI name cabalfp target = do econfig <- view envConfigL compilerVersion <- view actualCompilerVersionL - let sm = envConfigSourceMap econfig + let sm = econfig.envConfigSourceMap -- Currently this source map is being build with -- the default targets sourceMapGhcOptions = fromMaybe [] $ - (cpGhcOptions . ppCommon <$> M.lookup name sm.smProject) + ((.ppCommon.cpGhcOptions) <$> M.lookup name sm.smProject) <|> - (cpGhcOptions . dpCommon <$> M.lookup name sm.smDeps) + ((.dpCommon.cpGhcOptions) <$> M.lookup name sm.smDeps) sourceMapCabalConfigOpts = fromMaybe [] $ - (cpCabalConfigOpts . ppCommon <$> M.lookup name sm.smProject) + ( (.ppCommon.cpCabalConfigOpts) <$> M.lookup name sm.smProject) <|> - (cpCabalConfigOpts . dpCommon <$> M.lookup name sm.smDeps) + ((.dpCommon.cpCabalConfigOpts) <$> M.lookup name sm.smDeps) sourceMapFlags = - maybe mempty (cpFlags . ppCommon) $ M.lookup name sm.smProject + maybe mempty (.ppCommon.cpFlags) $ M.lookup name sm.smProject config = PackageConfig { packageConfigEnableTests = True , packageConfigEnableBenchmarks = True @@ -899,9 +900,9 @@ getGhciPkgInfos :: getGhciPkgInfos installMap addPkgs mfileTargets localTargets = do (installedMap, _, _, _) <- getInstalled installMap let localLibs = - [ packageName (ghciDescPkg desc) + [ desc.ghciDescPkg.packageName | desc <- localTargets - , hasLocalComp isCLib (ghciDescTarget desc) + , hasLocalComp isCLib desc.ghciDescTarget ] forM localTargets $ \pkgDesc -> makeGhciPkgInfo installMap installedMap localLibs addPkgs mfileTargets pkgDesc @@ -918,10 +919,10 @@ makeGhciPkgInfo :: -> RIO env GhciPkgInfo makeGhciPkgInfo installMap installedMap locals addPkgs mfileTargets pkgDesc = do bopts <- view buildOptsL - let pkg = ghciDescPkg pkgDesc - cabalfp = ghciDescCabalFp pkgDesc - target = ghciDescTarget pkgDesc - name = packageName pkg + let pkg = pkgDesc.ghciDescPkg + cabalfp = pkgDesc.ghciDescCabalFp + target = pkgDesc.ghciDescTarget + name = pkg.packageName (mods, files, opts) <- getPackageOpts pkg installMap installedMap locals addPkgs cabalfp let filteredOpts = filterWanted opts @@ -934,7 +935,7 @@ makeGhciPkgInfo installMap installedMap locals addPkgs mfileTargets pkgDesc = do , ghciPkgModules = unionModuleMaps $ map ( \(comp, mp) -> M.map - (\fp -> M.singleton fp (S.singleton (packageName pkg, comp))) + (\fp -> M.singleton fp (S.singleton (pkg.packageName, comp))) mp ) (M.toList (filterWanted mods)) @@ -957,14 +958,14 @@ wantedPackageComponents bopts (TargetAll PTProject) pkg = S.fromList $ ) <> map CExe buildableExes' <> map CSubLib buildableSubLibs - <> (if boptsTests bopts then map CTest buildableTestSuites else []) - <> (if boptsBenchmarks bopts then map CBench buildableBenchmarks else []) + <> (if bopts.boptsTests then map CTest buildableTestSuites else []) + <> (if bopts.boptsBenchmarks then map CBench buildableBenchmarks else []) where buildableForeignLibs' = S.toList $ buildableForeignLibs pkg - buildableSubLibs = getBuildableListText $ packageSubLibraries pkg + buildableSubLibs = getBuildableListText pkg.packageSubLibraries buildableExes' = S.toList $ buildableExes pkg - buildableTestSuites = getBuildableListText $ packageTestSuites pkg - buildableBenchmarks = getBuildableListText $ packageBenchmarks pkg + buildableTestSuites = getBuildableListText pkg.packageTestSuites + buildableBenchmarks = getBuildableListText pkg.packageBenchmarks wantedPackageComponents _ _ _ = S.empty checkForIssues :: HasTerm env => [GhciPkgInfo] -> RIO env () @@ -1072,11 +1073,11 @@ checkForIssues pkgs = where (xs, ys) = L.partition (any f . snd) compsWithOpts compsWithOpts = map (\(k, bio) -> - (k, bioOneWordOpts bio ++ bioOpts bio)) compsWithBios + (k, bio.bioOneWordOpts ++ bio.bioOpts)) compsWithBios compsWithBios = - [ ((ghciPkgName pkg, c), bio) + [ ((pkg.ghciPkgName, c), bio) | pkg <- pkgs - , (c, bio) <- ghciPkgOpts pkg + , (c, bio) <- pkg.ghciPkgOpts ] -- TODO: Should this also tell the user the filepaths, not just the @@ -1098,7 +1099,7 @@ checkForDuplicateModules pkgs = duplicates = filter (\(_, mp) -> M.size mp > 1) $ M.toList $ - unionModuleMaps (map ghciPkgModules pkgs) + unionModuleMaps (map (.ghciPkgModules) pkgs) prettyDuplicate :: (ModuleName, Map (Path Abs File) (Set (PackageName, NamedComponent))) -> StyleDoc @@ -1139,7 +1140,7 @@ targetWarnings localTargets nonLocalTargets mfileTargets = do \to ghci via -package flags." ] when (null localTargets && isNothing mfileTargets) $ do - smWanted <- view $ buildConfigL . to bcSMWanted + smWanted <- view $ buildConfigL . to (.bcSMWanted) stackYaml <- view stackYamlL prettyNote $ vsep [ flow "No local targets specified, so a plain ghci will be started with \ @@ -1147,7 +1148,7 @@ targetWarnings localTargets nonLocalTargets mfileTargets = do , "" , flow $ T.unpack $ utf8BuilderToText $ "You are using snapshot: " <> - display (smwSnapshotLocation smWanted) + display smWanted.smwSnapshotLocation , "" , flow "If you want to use package hiding and options, then you can try \ \one of the following:" @@ -1191,7 +1192,7 @@ getExtraLoadDeps loadAllDeps localMap targets = getDeps :: PackageName -> [PackageName] getDeps name = case M.lookup name localMap of - Just lp -> listOfPackageDeps (lpPackage lp) -- FIXME just Local? + Just lp -> listOfPackageDeps lp.lpPackage -- FIXME just Local? _ -> [] go :: PackageName @@ -1202,11 +1203,11 @@ getExtraLoadDeps loadAllDeps localMap targets = (Just (Just _), _) -> pure True (Just Nothing, _) | not loadAllDeps -> pure False (_, Just lp) -> do - let deps = listOfPackageDeps (lpPackage lp) + let deps = listOfPackageDeps lp.lpPackage shouldLoad <- or <$> mapM go deps if shouldLoad then do - modify (M.insert name (Just (lpCabalFile lp, TargetComps (S.singleton CLib)))) + modify (M.insert name (Just (lp.lpCabalFile, TargetComps (S.singleton CLib)))) pure True else do modify (M.insert name Nothing) diff --git a/src/Stack/Ghci/Script.hs b/src/Stack/Ghci/Script.hs index d30f42fc2a..87e8153cac 100644 --- a/src/Stack/Ghci/Script.hs +++ b/src/Stack/Ghci/Script.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Ghci.Script ( GhciScript @@ -44,7 +45,7 @@ scriptToLazyByteString = toLazyByteString . scriptToBuilder scriptToBuilder :: GhciScript -> Builder scriptToBuilder backwardScript = mconcat $ fmap commandToBuilder script where - script = reverse $ unGhciScript backwardScript + script = reverse backwardScript.unGhciScript scriptToFile :: Path Abs File -> GhciScript -> IO () scriptToFile path script = diff --git a/src/Stack/Hoogle.hs b/src/Stack/Hoogle.hs index f6855f87f6..1474ffdece 100644 --- a/src/Stack/Hoogle.hs +++ b/src/Stack/Hoogle.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | A wrapper around hoogle. @@ -153,10 +154,10 @@ hoogleCmd (args, setup, rebuild, startServer) = requiringHoogle :: Muted -> RIO EnvConfig x -> RIO EnvConfig x requiringHoogle muted f = do hoogleTarget <- do - sourceMap <- view $ sourceMapL . to smDeps + sourceMap <- view $ sourceMapL . to (.smDeps) case Map.lookup hooglePackageName sourceMap of Just hoogleDep -> - case dpLocation hoogleDep of + case hoogleDep.dpLocation of PLImmutable pli -> T.pack . packageIdentifierString <$> restrictMinHoogleVersion muted (packageLocationIdent pli) @@ -215,7 +216,7 @@ hoogleCmd (args, setup, rebuild, startServer) = runHoogle :: Path Abs File -> [String] -> RIO EnvConfig () runHoogle hooglePath hoogleArgs = do config <- view configL - menv <- liftIO $ configProcessContextSettings config envSettings + menv <- liftIO $ config.configProcessContextSettings envSettings dbpath <- hoogleDatabasePath let databaseArg = ["--database=" ++ toFilePath dbpath] withProcessContext menv $ proc @@ -230,7 +231,7 @@ hoogleCmd (args, setup, rebuild, startServer) = ensureHoogleInPath :: RIO EnvConfig (Path Abs File) ensureHoogleInPath = do config <- view configL - menv <- liftIO $ configProcessContextSettings config envSettings + menv <- liftIO $ config.configProcessContextSettings envSettings mHooglePath' <- eitherToMaybe <$> runRIO menv (findExecutable "hoogle") let mHooglePath'' = eitherToMaybe <$> requiringHoogle NotMuted (findExecutable "hoogle") diff --git a/src/Stack/IDE.hs b/src/Stack/IDE.hs index 72ce78f2a0..3adb4105ec 100644 --- a/src/Stack/IDE.hs +++ b/src/Stack/IDE.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @ide@ command. @@ -72,12 +73,12 @@ listPackages :: -> ListPackagesCmd -> RIO env () listPackages stream flag = do - packages <- view $ buildConfigL.to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) let strs = case flag of ListPackageNames -> map packageNameString (Map.keys packages) ListPackageCabalFiles -> - map (toFilePath . ppCabalFP) (Map.elems packages) + map (toFilePath . (.ppCabalFP)) (Map.elems packages) mapM_ (outputFunc stream) strs -- | List the targets in the current project. @@ -87,7 +88,7 @@ listTargets :: -> (NamedComponent -> Bool) -> RIO env () listTargets stream isCompType = do - packages <- view $ buildConfigL.to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) pairs <- concat <$> Map.traverseWithKey toNameAndComponent packages outputFunc stream $ T.unpack $ T.intercalate "\n" $ map renderPkgComponent pairs diff --git a/src/Stack/Init.hs b/src/Stack/Init.hs index ce0b64bb19..6c3ce9d38f 100644 --- a/src/Stack/Init.hs +++ b/src/Stack/Init.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE TypeFamilies #-} -- | Types and functions related to Stack's @init@ command. module Stack.Init @@ -204,7 +205,7 @@ initCmd initOpts = do pwd <- getCurrentDir go <- view globalOptsL withGlobalProject $ - withConfig YesReexec (initProject pwd initOpts (globalResolver go)) + withConfig YesReexec (initProject pwd initOpts go.globalResolver) -- | Generate a @stack.yaml@ file. initProject :: @@ -217,10 +218,10 @@ initProject currDir initOpts mresolver = do let dest = currDir stackDotYaml reldest <- toFilePath <$> makeRelativeToCurrentDir dest exists <- doesFileExist dest - when (not (forceOverwrite initOpts) && exists) $ + when (not initOpts.forceOverwrite && exists) $ prettyThrowIO $ ConfigFileAlreadyExists reldest - dirs <- mapM (resolveDir' . T.unpack) (searchDirs initOpts) - let find = findCabalDirs (includeSubDirs initOpts) + dirs <- mapM (resolveDir' . T.unpack) initOpts.searchDirs + let find = findCabalDirs initOpts.includeSubDirs dirs' = if null dirs then [currDir] else dirs prettyInfo $ fillSep @@ -512,7 +513,7 @@ getDefaultResolver initOpts mresolver pkgDirs = do snaps <- fmap getRecommendedSnapshots getSnapshots' (c, l, r) <- selectBestSnapshot (Map.elems pkgDirs) snaps case r of - BuildPlanCheckFail {} | not (omitPackages initOpts) + BuildPlanCheckFail {} | not initOpts.omitPackages -> prettyThrowM $ NoMatchingSnapshot snaps _ -> pure (c, l) @@ -589,7 +590,7 @@ checkBundleResolver initOpts snapshotLoc snapCandidate pkgDirs = do case result of BuildPlanCheckOk f -> pure $ Right (f, Map.empty) BuildPlanCheckPartial _f e -> do -- FIXME:qrilka unused f - if omitPackages initOpts + if initOpts.omitPackages then do warnPartial result prettyWarnS "Omitting packages with unsatisfied dependencies" @@ -597,7 +598,7 @@ checkBundleResolver initOpts snapshotLoc snapCandidate pkgDirs = do else prettyThrowM $ ResolverPartial snapshotLoc (show result) BuildPlanCheckFail _ e _ - | omitPackages initOpts -> do + | initOpts.omitPackages -> do prettyWarn $ fillSep [ "Resolver compiler mismatch:" @@ -618,7 +619,7 @@ checkBundleResolver initOpts snapshotLoc snapCandidate pkgDirs = do <> line <> indent 4 (string $ show res) - failedUserPkgs e = Map.keys $ Map.unions (Map.elems (fmap deNeededBy e)) + failedUserPkgs e = Map.keys $ Map.unions (Map.elems (fmap (.deNeededBy) e)) getRecommendedSnapshots :: Snapshots -> NonEmpty SnapName getRecommendedSnapshots snapshots = @@ -627,9 +628,9 @@ getRecommendedSnapshots snapshots = Just (mostRecent :| older) -> mostRecent :| (nightly : older) Nothing -> nightly :| [] where - ltss = map (uncurry LTS) (IntMap.toDescList $ snapshotsLts snapshots) + ltss = map (uncurry LTS) (IntMap.toDescList snapshots.snapshotsLts ) supportedLtss = filter (>= minSupportedLts) ltss - nightly = Nightly (snapshotsNightly snapshots) + nightly = Nightly snapshots.snapshotsNightly -- |Yields the minimum LTS supported by Stack. minSupportedLts :: SnapName diff --git a/src/Stack/List.hs b/src/Stack/List.hs index 94f0fef083..51e0a6d96f 100644 --- a/src/Stack/List.hs +++ b/src/Stack/List.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @list@ command. @@ -34,7 +35,7 @@ instance Exception ListPrettyException -- | Function underlying the @stack list@ command. List packages. listCmd :: [String] -> RIO Runner () listCmd names = withConfig NoReexec $ do - mresolver <- view $ globalOptsL.to globalResolver + mresolver <- view $ globalOptsL . to (.globalResolver) mSnapshot <- forM mresolver $ \resolver -> do concrete <- makeConcreteResolver resolver loc <- completeSnapshotLocation concrete diff --git a/src/Stack/Lock.hs b/src/Stack/Lock.hs index 7cdf9f959c..0822f2b49d 100644 --- a/src/Stack/Lock.hs +++ b/src/Stack/Lock.hs @@ -59,7 +59,7 @@ data LockedLocation a b = LockedLocation instance (ToJSON a, ToJSON b) => ToJSON (LockedLocation a b) where toJSON ll = - object [ "original" .= llOriginal ll, "completed" .= llCompleted ll ] + object [ "original" .= ll.llOriginal, "completed" .= ll.llCompleted ] instance ( FromJSON (WithJSONWarnings (Unresolved a)) , FromJSON (WithJSONWarnings (Unresolved b)) @@ -101,7 +101,8 @@ instance FromJSON (WithJSONWarnings (Unresolved Locked)) where parseJSON = withObjectWarnings "Locked" $ \o -> do snapshots <- jsonSubWarningsT $ o ..: "snapshots" packages <- jsonSubWarningsT $ o ..: "packages" - let unwrap ll = ll { llOriginal = unSingleRPLI (llOriginal ll) } + let unwrap :: LockedLocation SingleRPLI b -> LockedLocation RawPackageLocationImmutable b + unwrap ll = ll { llOriginal = ll.llOriginal.unSingleRPLI } pure $ Locked <$> sequenceA snapshots <*> (map unwrap <$> sequenceA packages) loadYamlThrow :: @@ -150,9 +151,9 @@ lockCachedWanted stackFile resolver fillWanted = do logDebug "Not reading lock file" pure $ Locked [] [] let toMap :: Ord a => [LockedLocation a b] -> Map a b - toMap = Map.fromList . map (llOriginal &&& llCompleted) - slocCache = toMap $ lckSnapshotLocations locked - pkgLocCache = toMap $ lckPkgImmutableLocations locked + toMap = Map.fromList . map ((.llOriginal) &&& (.llCompleted)) + slocCache = toMap locked.lckSnapshotLocations + pkgLocCache = toMap locked.lckPkgImmutableLocations debugRSL <- view rslInLogL (snap, slocCompleted, pliCompleted) <- loadAndCompleteSnapshotRaw' debugRSL resolver slocCache pkgLocCache diff --git a/src/Stack/Ls.hs b/src/Stack/Ls.hs index 61ad55a4d4..8934e4c777 100644 --- a/src/Stack/Ls.hs +++ b/src/Stack/Ls.hs @@ -193,7 +193,7 @@ renderData False content = T.putStr content displaySnapshotData :: Bool -> SnapshotData -> IO () displaySnapshotData term sdata = - case L.reverse $ snaps sdata of + case L.reverse sdata.snaps of [] -> pure () xs -> let snaps = T.concat $ L.map displaySingleSnap xs @@ -203,12 +203,12 @@ filterSnapshotData :: SnapshotData -> SnapshotType -> SnapshotData filterSnapshotData sdata stype = sdata { snaps = filterSnapData } where - snapdata = snaps sdata + snapdata = sdata.snaps filterSnapData = case stype of - Lts -> L.map (L.filter (\x -> "lts" `isPrefixOf` snapId x)) snapdata + Lts -> L.map (L.filter (\x -> "lts" `isPrefixOf` x.snapId)) snapdata Nightly -> - L.map (L.filter (\x -> "nightly" `isPrefixOf` snapId x)) snapdata + L.map (L.filter (\x -> "nightly" `isPrefixOf` x.snapId)) snapdata displayLocalSnapshot :: Bool -> [String] -> IO () displayLocalSnapshot term xs = renderData term (localSnaptoText xs) @@ -227,7 +227,7 @@ handleLocal lsOpts = do | otherwise = parent parentInstRoot snapData' <- liftIO $ listDirectory $ toFilePath snapRootDir let snapData = L.sort snapData' - case lsView lsOpts of + case lsOpts.lsView of LsSnapshot sopt -> case (sopt.soptLtsSnapView, sopt.soptNightlySnapView) of (True, False) -> @@ -250,7 +250,7 @@ handleRemote lsOpts = do let req' = addRequestHeader hAccept "application/json" req result <- httpJSON req' let snapData = getResponseBody result - case lsView lsOpts of + case lsOpts.lsView of LsSnapshot sopt -> case (sopt.soptLtsSnapView, sopt.soptNightlySnapView) of (True, False) -> @@ -270,7 +270,7 @@ handleRemote lsOpts = do lsCmd :: LsCmdOpts -> RIO Runner () lsCmd lsOpts = - case lsView lsOpts of + case lsOpts.lsView of LsSnapshot sopt -> case sopt.soptViewType of Local -> handleLocal lsOpts @@ -286,9 +286,9 @@ listStylesCmd opts = do -- This is the same test as is used in Stack.Types.Runner.withRunner let useColor = view useColorL lc styles = elems $ defaultStyles // stylesUpdate (view stylesUpdateL lc) - isComplex = not (coptBasic opts) - showSGR = isComplex && coptSGR opts - showExample = isComplex && coptExample opts && useColor + isComplex = not opts.coptBasic + showSGR = isComplex && opts.coptSGR + showExample = isComplex && opts.coptExample && useColor styleReports = L.map (styleReport showSGR showExample) styles liftIO $ T.putStrLn $ T.intercalate (if isComplex then "\n" else ":") styleReports @@ -309,9 +309,9 @@ listStylesCmd opts = do -- | List Stack's installed tools, sorted (see instance of 'Ord' for 'Tool'). listToolsCmd :: ListToolsOpts -> RIO Config () listToolsCmd opts = do - localPrograms <- view $ configL . to configLocalPrograms + localPrograms <- view $ configL . to (.configLocalPrograms) installed <- sort <$> listInstalled localPrograms - let wanted = case toptFilter opts of + let wanted = case opts.toptFilter of [] -> installed "ghc-git" -> [t | t@(ToolGhcGit _ _) <- installed] pkgName -> filtered pkgName installed @@ -322,9 +322,9 @@ listToolsCmd opts = do listDependencies :: ListDepsOpts -> RIO Runner () listDependencies opts = do - let dotOpts = listDepsDotOpts opts + let dotOpts = opts.listDepsDotOpts (pkgs, resultGraph) <- createPrunedDependencyGraph dotOpts - liftIO $ case listDepsFormat opts of + liftIO $ case opts.listDepsFormat of ListDepsTree treeOpts -> T.putStrLn "Packages" >> printTree treeOpts dotOpts 0 [] (treeRoots opts pkgs) resultGraph @@ -342,7 +342,7 @@ listDependencies opts = do treeRoots :: ListDepsOpts -> Set PackageName -> Set PackageName treeRoots opts projectPackages' = - let targets = dotTargets $ listDepsDotOpts opts + let targets = opts.listDepsDotOpts.dotTargets in if null targets then projectPackages' else Set.fromList $ map (mkPackageName . T.unpack) targets @@ -364,7 +364,7 @@ printTree opts dotOpts depth remainingDepsCounts packages dependencyMap = in case Map.lookup name dependencyMap of Just (deps, payload) -> do printTreeNode opts dotOpts depth newDepsCounts deps payload name - if Just depth == dotDependencyDepth dotOpts + if Just depth == dotOpts.dotDependencyDepth then pure () else printTree opts dotOpts (depth + 1) newDepsCounts deps dependencyMap @@ -381,7 +381,7 @@ printTreeNode :: -> PackageName -> IO () printTreeNode opts dotOpts depth remainingDepsCounts deps payload name = - let remainingDepth = fromMaybe 999 (dotDependencyDepth dotOpts) - depth + let remainingDepth = fromMaybe 999 dotOpts.dotDependencyDepth - depth hasDeps = not $ null deps in T.putStrLn $ treeNodePrefix "" remainingDepsCounts hasDeps remainingDepth <> " " <> @@ -400,12 +400,12 @@ treeNodePrefix t (_:ns) d remainingDepth = treeNodePrefix (t <> "│ ") ns d rem listDepsLine :: ListDepsFormatOpts -> PackageName -> DotPayload -> Text listDepsLine opts name payload = - T.pack (packageNameString name) <> listDepsSep opts <> + T.pack (packageNameString name) <> opts.listDepsSep <> payloadText opts payload payloadText :: ListDepsFormatOpts -> DotPayload -> Text payloadText opts payload = - if listDepsLicense opts + if opts.listDepsLicense then licenseText payload else versionText payload diff --git a/src/Stack/New.hs b/src/Stack/New.hs index 796ffa4359..730f93a1e6 100644 --- a/src/Stack/New.hs +++ b/src/Stack/New.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @new@ command. module Stack.New @@ -230,11 +231,11 @@ data NewOpts = NewOpts newCmd :: (NewOpts, InitOpts) -> RIO Runner () newCmd (newOpts, initOpts) = withGlobalProject $ withConfig YesReexec $ do - dir <- new newOpts (forceOverwrite initOpts) + dir <- new newOpts initOpts.forceOverwrite exists <- doesFileExist $ dir stackDotYaml - when (newOptsInit newOpts && (forceOverwrite initOpts || not exists)) $ do + when (newOpts.newOptsInit && (initOpts.forceOverwrite || not exists)) $ do go <- view globalOptsL - initProject dir initOpts (globalResolver go) + initProject dir initOpts go.globalResolver -- | Create a new project with the given options. new :: HasConfig env => NewOpts -> Bool -> RIO env (Path Abs Dir) @@ -247,7 +248,7 @@ new opts forceOverwrite = do else do relDir <- parseRelDir (packageNameString project) pure (pwd relDir) exists <- doesDirExist absDir - configTemplate <- view $ configL.to configDefaultTemplate + configTemplate <- view $ configL . to (.configDefaultTemplate) let template = fromMaybe defaultTemplateName $ asum [ cliOptionTemplate , configTemplate ] @@ -259,7 +260,7 @@ new opts forceOverwrite = do applyTemplate project template - (newOptsNonceParams opts) + opts.newOptsNonceParams absDir templateText when (not forceOverwrite && bare) $ @@ -268,10 +269,10 @@ new opts forceOverwrite = do runTemplateInits absDir pure absDir where - cliOptionTemplate = newOptsTemplate opts - project = newOptsProjectName opts + cliOptionTemplate = opts.newOptsTemplate + project = opts.newOptsProjectName projectName = packageNameString project - bare = newOptsCreateBare opts + bare = opts.newOptsCreateBare logUsing absDir template templateFrom = let loading = case templateFrom of LocalTemp -> flow "Loading local" @@ -306,7 +307,7 @@ loadTemplate :: -> (TemplateFrom -> RIO env ()) -> RIO env Text loadTemplate name logIt = do - templateDir <- view $ configL.to templatesDir + templateDir <- view $ configL . to templatesDir case templatePath name of AbsPath absFile -> logIt LocalTemp >> loadLocalFile absFile eitherByteStringToText @@ -320,9 +321,9 @@ loadTemplate name logIt = do pure f) ( \(e :: PrettyException) -> do settings <- fromMaybe (throwM e) (relSettings rawParam) - let url = tplDownloadUrl settings - mBasicAuth = tplBasicAuth settings - extract = tplExtract settings + let url = settings.tplDownloadUrl + mBasicAuth = settings.tplBasicAuth + extract = settings.tplExtract downloadTemplate url mBasicAuth extract (templateDir relFile) ) RepoPath rtp -> do @@ -355,10 +356,10 @@ loadTemplate name logIt = do downloadFromUrl :: TemplateDownloadSettings -> Path Abs Dir -> RIO env Text downloadFromUrl settings templateDir = do - let url = tplDownloadUrl settings - mBasicAuth = tplBasicAuth settings + let url = settings.tplDownloadUrl + mBasicAuth = settings.tplBasicAuth rel = fromMaybe backupUrlRelPath (parseRelFile url) - downloadTemplate url mBasicAuth (tplExtract settings) (templateDir rel) + downloadTemplate url mBasicAuth settings.tplExtract (templateDir rel) downloadTemplate :: String @@ -503,7 +504,7 @@ applyTemplate project template nonceParams dir templateText = do nameParams = M.fromList [ ("name", T.pack $ packageNameString project) , ("name-as-varid", nameAsVarId) , ("name-as-module", nameAsModule) ] - configParams = configTemplateParams config + configParams = config.configTemplateParams yearParam = M.singleton "year" currentYear files :: Map FilePath LB.ByteString <- catch @@ -568,7 +569,7 @@ applyTemplate project template nonceParams dir templateText = do prettyNote $ missingParameters missingKeys - (configUserConfigPath config) + config.configUserConfigPath pure $ M.fromList results where onlyMissingKeys (Mustache.VariableNotFound ks) = map T.unpack ks @@ -658,7 +659,7 @@ writeTemplateFiles files = runTemplateInits :: HasConfig env => Path Abs Dir -> RIO env () runTemplateInits dir = do config <- view configL - case configScmInit config of + case config.configScmInit of Nothing -> pure () Just Git -> withWorkingDir (toFilePath dir) $ catchAny diff --git a/src/Stack/Nix.hs b/src/Stack/Nix.hs index a750274125..ea76ecd2c0 100644 --- a/src/Stack/Nix.hs +++ b/src/Stack/Nix.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Run commands in a nix-shell module Stack.Nix @@ -57,7 +58,7 @@ runShellAndExit = do mshellFile <- case configProjectRoot config of Just projectRoot -> - traverse (resolveFile projectRoot) $ nixInitFile (configNix config) + traverse (resolveFile projectRoot) config.configNix.nixInitFile Nothing -> pure Nothing -- This will never result in double loading the build config, since: @@ -70,11 +71,11 @@ runShellAndExit = do ghc <- either throwIO pure $ nixCompiler compilerVersion ghcVersion <- either throwIO pure $ nixCompilerVersion compilerVersion - let pkgsInConfig = nixPackages (configNix config) + let pkgsInConfig = config.configNix.nixPackages pkgs = pkgsInConfig ++ [ghc, "git", "gcc", "gmp"] pkgsStr = "[" <> T.intercalate " " pkgs <> "]" - pureShell = nixPureShell (configNix config) - addGCRoots = nixAddGCRoots (configNix config) + pureShell = config.configNix.nixPureShell + addGCRoots = config.configNix.nixAddGCRoots nixopts = case mshellFile of Just fp -> [ toFilePath fp @@ -121,12 +122,12 @@ runShellAndExit = do then [ "--indirect" , "--add-root" , toFilePath - (configWorkDir config) + config.configWorkDir F. "nix-gc-symlinks" F. "gc-root" ] else [] - , map T.unpack (nixShellOptions (configNix config)) + , map T.unpack config.configNix.nixShellOptions , nixopts , ["--run", unwords (cmnd:"$STACK_IN_NIX_EXTRA_ARGS":args')] -- Using --run instead of --command so we cannot end up in the diff --git a/src/Stack/Options/Completion.hs b/src/Stack/Options/Completion.hs index e0aac97cb0..e6ac0b9b1f 100644 --- a/src/Stack/Options/Completion.hs +++ b/src/Stack/Options/Completion.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Options.Completion ( ghcOptsCompleter @@ -62,7 +63,7 @@ buildConfigCompleter inner = mkCompleter $ \inputRaw -> do targetCompleter :: Completer targetCompleter = buildConfigCompleter $ \input -> do - packages <- view $ buildConfigL.to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) comps <- for packages ppComponents pure $ concatMap @@ -75,7 +76,7 @@ targetCompleter = buildConfigCompleter $ \input -> do flagCompleter :: Completer flagCompleter = buildConfigCompleter $ \input -> do bconfig <- view buildConfigL - gpds <- for (smwProject $ bcSMWanted bconfig) ppGPD + gpds <- for bconfig.bcSMWanted.smwProject ppGPD let wildcardFlags = nubOrd $ concatMap (\(name, gpd) -> @@ -90,8 +91,8 @@ flagCompleter = buildConfigCompleter $ \input -> do let flname = C.unFlagName $ C.flagName fl in (if flagEnabled name fl then "-" else "") ++ flname prjFlags = - case configProject (bcConfig bconfig) of - PCProject (p, _) -> projectFlags p + case bconfig.bcConfig.configProject of + PCProject (p, _) -> p.projectFlags PCGlobalProject -> mempty PCNoProject _ -> mempty flagEnabled name fl = @@ -106,7 +107,7 @@ flagCompleter = buildConfigCompleter $ \input -> do projectExeCompleter :: Completer projectExeCompleter = buildConfigCompleter $ \input -> do - packages <- view $ buildConfigL.to (smwProject . bcSMWanted) + packages <- view $ buildConfigL . to (.bcSMWanted.smwProject) gpds <- Map.traverseWithKey (const ppGPD) packages pure $ filter (input `isPrefixOf`) diff --git a/src/Stack/Options/NixParser.hs b/src/Stack/Options/NixParser.hs index 7244c0581f..ccd2209328 100644 --- a/src/Stack/Options/NixParser.hs +++ b/src/Stack/Options/NixParser.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Options.NixParser ( nixOptsParser @@ -65,7 +66,7 @@ nixOptsParser hide0 = overrideActivation <$> where hide = hideMods hide0 overrideActivation m = - if fromFirst False (nixMonoidPureShell m) - then m { nixMonoidEnable = (First . Just . fromFirst True) (nixMonoidEnable m) } + if fromFirst False m.nixMonoidPureShell + then m { nixMonoidEnable = (First . Just . fromFirst True) m.nixMonoidEnable } else m textArgsOption = fmap (map T.pack) . argsOption diff --git a/src/Stack/Package.hs b/src/Stack/Package.hs index 4c33ed7171..13f83a0cb9 100644 --- a/src/Stack/Package.hs +++ b/src/Stack/Package.hs @@ -58,7 +58,6 @@ import Distribution.Utils.Path ( getSymbolicPath ) import Distribution.Verbosity ( silent ) import Distribution.Version ( anyVersion, mkVersion, orLaterVersion ) -import GHC.Records ( getField ) import Path ( (), parent, parseAbsDir, parseRelDir, parseRelFile , stripProperPrefix @@ -145,9 +144,9 @@ packageFromPackageDescription { packageName = name , packageVersion = pkgVersion pkgId , packageLicense = licenseRaw pkg - , packageGhcOptions = packageConfigGhcOptions packageConfig - , packageCabalConfigOpts = packageConfigCabalConfigOpts packageConfig - , packageFlags = packageConfigFlags packageConfig + , packageGhcOptions = packageConfig.packageConfigGhcOptions + , packageCabalConfigOpts = packageConfig.packageConfigCabalConfigOpts + , packageFlags = packageConfig.packageConfigFlags , packageDefaultFlags = M.fromList [(flagName flag, flagDefault flag) | flag <- pkgFlags] , packageLibrary = stackLibraryFromCabal <$> library pkg @@ -165,8 +164,8 @@ packageFromPackageDescription , packageSetupDeps = fmap cabalSetupDepsToStackDep (setupBuildInfo pkg) , packageCabalSpec = specVersion pkg , packageFile = stackPackageFileFromCabal pkg - , packageTestEnabled = packageConfigEnableTests packageConfig - , packageBenchmarkEnabled = packageConfigEnableBenchmarks packageConfig + , packageTestEnabled = packageConfig.packageConfigEnableTests + , packageBenchmarkEnabled = packageConfig.packageConfigEnableBenchmarks } where -- Gets all of the modules, files, build files, and data files that constitute @@ -248,8 +247,8 @@ generatePkgDescOpts , biBuildInfo = binfo , biDotCabalPaths = fromMaybe [] (M.lookup namedComponent componentPaths) - , biConfigLibDirs = configExtraLibDirs config - , biConfigIncludeDirs = configExtraIncludeDirs config + , biConfigLibDirs = config.configExtraLibDirs + , biConfigIncludeDirs = config.configExtraIncludeDirs , biComponentName = namedComponent , biCabalVersion = cabalVer } @@ -261,11 +260,11 @@ generatePkgDescOpts (selector pkg) (translatedInsertInMap constructor) let aggregateAllBuildInfoOpts = - makeBuildInfoOpts packageLibrary (const CLib) - . makeBuildInfoOpts packageSubLibraries CSubLib - . makeBuildInfoOpts packageExecutables CExe - . makeBuildInfoOpts packageBenchmarks CBench - . makeBuildInfoOpts packageTestSuites CTest + makeBuildInfoOpts (.packageLibrary) (const CLib) + . makeBuildInfoOpts (.packageSubLibraries) CSubLib + . makeBuildInfoOpts (.packageExecutables) CExe + . makeBuildInfoOpts (.packageBenchmarks) CBench + . makeBuildInfoOpts (.packageTestSuites) CTest pure $ aggregateAllBuildInfoOpts mempty where cabalDir = parent cabalfp @@ -277,7 +276,7 @@ generateBuildInfoOpts bi = BuildInfoOpts { bioOpts = ghcOpts - ++ fmap ("-optP" <>) (Component.cppOptions bi.biBuildInfo) + ++ fmap ("-optP" <>) bi.biBuildInfo.cppOptions -- NOTE for future changes: Due to this use of nubOrd (and other uses -- downstream), these generated options must not rely on multiple -- argument sequences. For example, ["--main-is", "Foo.hs", "--main- @@ -313,25 +312,25 @@ generateBuildInfoOpts bi = pkgs = bi.biAddPackages ++ [ name - | Dependency name _ _ <- Component.targetBuildDepends bi.biBuildInfo + | Dependency name _ _ <- bi.biBuildInfo.targetBuildDepends -- TODO: Cabal 3.0 introduced multiple public libraries in a single -- dependency , name `notElem` bi.biOmitPackages ] - PerCompilerFlavor ghcOpts _ = Component.options bi.biBuildInfo + PerCompilerFlavor ghcOpts _ = bi.biBuildInfo.options extOpts = - map (("-X" ++) . display) (Component.allLanguages bi.biBuildInfo) - <> map (("-X" ++) . display) (Component.usedExtensions bi.biBuildInfo) + map (("-X" ++) . display) bi.biBuildInfo.allLanguages + <> map (("-X" ++) . display) bi.biBuildInfo.usedExtensions srcOpts = map (("-i" <>) . toFilePathNoTrailingSep) (concat [ [ componentBuildDir bi.biCabalVersion bi.biComponentName bi.biDistDir ] , [ bi.biCabalDir - | null (Component.hsSourceDirs bi.biBuildInfo) + | null bi.biBuildInfo.hsSourceDirs ] , mapMaybe (toIncludeDir . getSymbolicPath) - (Component.hsSourceDirs bi.biBuildInfo) + bi.biBuildInfo.hsSourceDirs , [ componentAutogen ] , maybeToList (packageAutogenDir bi.biCabalVersion bi.biDistDir) , [ componentOutputDir bi.biComponentName bi.biDistDir ] @@ -345,22 +344,22 @@ generateBuildInfoOpts bi = map ("-I" <>) (bi.biConfigIncludeDirs <> pkgIncludeOpts) pkgIncludeOpts = [ toFilePathNoTrailingSep absDir - | dir <- Component.includeDirs bi.biBuildInfo + | dir <- bi.biBuildInfo.includeDirs , absDir <- handleDir dir ] libOpts = - map ("-l" <>) (Component.extraLibs bi.biBuildInfo) <> + map ("-l" <>) bi.biBuildInfo.extraLibs <> map ("-L" <>) (bi.biConfigLibDirs <> pkgLibDirs) pkgLibDirs = [ toFilePathNoTrailingSep absDir - | dir <- Component.extraLibDirs bi.biBuildInfo + | dir <- bi.biBuildInfo.extraLibDirs , absDir <- handleDir dir ] handleDir dir = case (parseAbsDir dir, parseRelDir dir) of (Just ab, _ ) -> [ab] (_ , Just rel) -> [bi.biCabalDir rel] (Nothing, Nothing ) -> [] - fworks = map ("-framework=" <>) (Component.frameworks bi.biBuildInfo) + fworks = map ("-framework=" <>) bi.biBuildInfo.frameworks -- | Make the .o path from the .c file path for a component. Example: -- @@ -468,10 +467,10 @@ resolvePackageDescription benches } where - flags = M.union (packageConfigFlags packageConfig) (flagMap defaultFlags) + flags = M.union packageConfig.packageConfigFlags (flagMap defaultFlags) rc = mkResolveConditions - (packageConfigCompilerVersion packageConfig) - (packageConfigPlatform packageConfig) + packageConfig.packageConfigCompilerVersion + packageConfig.packageConfigPlatform flags updateLibDeps lib deps = lib { libBuildInfo = (libBuildInfo lib) {targetBuildDepends = deps} } @@ -542,13 +541,13 @@ resolveConditions rc addDeps (CondNode lib deps cs) = basic <> children CAnd cx cy -> condSatisfied cx && condSatisfied cy varSatisfied v = case v of - OS os -> os == rcOS rc - Arch arch -> arch == rcArch rc - PackageFlag flag -> fromMaybe False $ M.lookup flag (rcFlags rc) + OS os -> os == rc.rcOS + Arch arch -> arch == rc.rcArch + PackageFlag flag -> fromMaybe False $ M.lookup flag rc.rcFlags -- NOTE: ^^^^^ This should never happen, as all flags which are used -- must be declared. Defaulting to False. Impl flavor range -> - case (flavor, rcCompilerVersion rc) of + case (flavor, rc.rcCompilerVersion) of (GHC, ACGhc vghc) -> vghc `withinRange` range _ -> False @@ -623,16 +622,15 @@ applyForceCustomBuild cabalVersion package | otherwise = package where cabalVersionRange = - orLaterVersion $ mkVersion $ cabalSpecToVersionDigits $ - packageCabalSpec package - forceCustomBuild = - packageBuildType package == Simple + orLaterVersion $ mkVersion $ cabalSpecToVersionDigits + package.packageCabalSpec + forceCustomBuild = package.packageBuildType == Simple && not (cabalVersion `withinRange` cabalVersionRange) -- | Check if the package has a main library that is buildable. hasBuildableMainLibrary :: Package -> Bool hasBuildableMainLibrary package = - maybe False isComponentBuildable $ packageLibrary package + maybe False isComponentBuildable package.packageLibrary -- | Check if the main library has any exposed modules. -- @@ -641,7 +639,7 @@ hasBuildableMainLibrary package = -- (for instance). mainLibraryHasExposedModules :: Package -> Bool mainLibraryHasExposedModules package = - maybe False (not . null . Component.exposedModules) $ packageLibrary package + maybe False (not . null . (.exposedModules)) package.packageLibrary -- | Aggregate all unknown tools from all components. Mostly meant for -- build tools specified in the legacy manner (build-tools:) that failed the @@ -650,33 +648,33 @@ mainLibraryHasExposedModules package = packageUnknownTools :: Package -> Set Text packageUnknownTools pkg = lib (bench <> tests <> flib <> sublib <> exe) where - lib setT = case packageLibrary pkg of + lib setT = case pkg.packageLibrary of Just libV -> addUnknownTools libV setT Nothing -> setT - bench = gatherUnknownTools $ packageBenchmarks pkg - tests = gatherUnknownTools $ packageTestSuites pkg - flib = gatherUnknownTools $ packageForeignLibraries pkg - sublib = gatherUnknownTools $ packageSubLibraries pkg - exe = gatherUnknownTools $ packageExecutables pkg + bench = gatherUnknownTools pkg.packageBenchmarks + tests = gatherUnknownTools pkg.packageTestSuites + flib = gatherUnknownTools pkg.packageForeignLibraries + sublib = gatherUnknownTools pkg.packageSubLibraries + exe = gatherUnknownTools pkg.packageExecutables addUnknownTools :: HasBuildInfo x => x -> Set Text -> Set Text - addUnknownTools = (<>) . Component.sbiUnknownTools . getField @"buildInfo" + addUnknownTools = (<>) . (.buildInfo.sbiUnknownTools) gatherUnknownTools :: HasBuildInfo x => CompCollection x -> Set Text gatherUnknownTools = foldr' addUnknownTools mempty buildableForeignLibs :: Package -> Set Text -buildableForeignLibs pkg = getBuildableSetText (packageForeignLibraries pkg) +buildableForeignLibs pkg = getBuildableSetText pkg.packageForeignLibraries buildableSubLibs :: Package -> Set Text -buildableSubLibs pkg = getBuildableSetText (packageSubLibraries pkg) +buildableSubLibs pkg = getBuildableSetText pkg.packageSubLibraries buildableExes :: Package -> Set Text -buildableExes pkg = getBuildableSetText (packageExecutables pkg) +buildableExes pkg = getBuildableSetText pkg.packageExecutables buildableTestSuites :: Package -> Set Text -buildableTestSuites pkg = getBuildableSetText (packageTestSuites pkg) +buildableTestSuites pkg = getBuildableSetText pkg.packageTestSuites buildableBenchmarks :: Package -> Set Text -buildableBenchmarks pkg = getBuildableSetText (packageBenchmarks pkg) +buildableBenchmarks pkg = getBuildableSetText pkg.packageBenchmarks -- | Apply a generic processing function in a Monad over all of the Package's -- components. @@ -698,19 +696,19 @@ processPackageComponent pkg componentFn = do foldComponentToAnotherCollection (target pkg) componentFn - processMainLib = maybe id componentFn (packageLibrary pkg) + processMainLib = maybe id componentFn pkg.packageLibrary processAllComp = - ( if packageBenchmarkEnabled pkg - then componentKindProcessor packageBenchmarks + ( if pkg.packageBenchmarkEnabled + then componentKindProcessor (.packageBenchmarks) else id ) - . ( if packageTestEnabled pkg - then componentKindProcessor packageTestSuites + . ( if pkg.packageTestEnabled + then componentKindProcessor (.packageTestSuites) else id ) - . componentKindProcessor packageForeignLibraries - . componentKindProcessor packageExecutables - . componentKindProcessor packageSubLibraries + . componentKindProcessor (.packageForeignLibraries) + . componentKindProcessor (.packageExecutables) + . componentKindProcessor (.packageSubLibraries) . processMainLib processAllComp @@ -723,7 +721,7 @@ processPackageMapDeps :: -> m a -> m a processPackageMapDeps pkg fn = do - let packageSetupDepsProcessor resAction = case packageSetupDeps pkg of + let packageSetupDepsProcessor resAction = case pkg.packageSetupDeps of Nothing -> resAction Just v -> fn v resAction processAllComp = processPackageComponent pkg (fn . componentDependencyMap) @@ -743,11 +741,11 @@ processPackageDeps pkg combineResults fn = do let asPackageNameSet accessor = S.map (mkPackageName . T.unpack) $ getBuildableSetText $ accessor pkg (!subLibNames, !foreignLibNames) = - ( asPackageNameSet packageSubLibraries - , asPackageNameSet packageForeignLibraries + ( asPackageNameSet (.packageSubLibraries) + , asPackageNameSet (.packageForeignLibraries) ) shouldIgnoreDep (packageNameV :: PackageName) - | packageNameV == packageName pkg = True + | packageNameV == pkg.packageName = True | packageNameV `S.member` subLibNames = True | packageNameV `S.member` foreignLibNames = True | otherwise = False @@ -813,7 +811,7 @@ topSortPackageComponent package target includeDirectTarget = runST $ do -> ST s (Seq NamedComponent) processComponent finallyAddComponent alreadyProcessedRef component res = do let depMap = componentDependencyMap component - internalDep = M.lookup (packageName package) depMap + internalDep = M.lookup package.packageName depMap processSubDep = processOneDep alreadyProcessedRef internalDep res qualName = component.qualifiedName processSubDepSaveName @@ -831,10 +829,10 @@ topSortPackageComponent package target includeDirectTarget = runST $ do >> processSubDepSaveName else processSubDepSaveName lookupLibName isMain name = if isMain - then packageLibrary package - else collectionLookup name $ packageSubLibraries package + then package.packageLibrary + else collectionLookup name package.packageSubLibraries processOneDep alreadyProcessed mDependency res = - case dvType <$> mDependency of + case (.dvType) <$> mDependency of Just (AsLibrary (DepLibrary mainLibDep subLibDeps)) -> do let processMainLibDep = case (mainLibDep, lookupLibName True mempty) of @@ -842,7 +840,7 @@ topSortPackageComponent package target includeDirectTarget = runST $ do processComponent True alreadyProcessed mainLib _ -> id processSingleSubLib name = - case lookupLibName False (unqualCompToText name) of + case lookupLibName False name.unqualCompToText of Just lib -> processComponent True alreadyProcessed lib Nothing -> id processSubLibDep r = foldr' processSingleSubLib r subLibDeps diff --git a/src/Stack/PackageDump.hs b/src/Stack/PackageDump.hs index d8bab5e00c..138eefaf72 100644 --- a/src/Stack/PackageDump.hs +++ b/src/Stack/PackageDump.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.PackageDump ( Line @@ -169,14 +170,14 @@ sinkMatching :: Monad m -> ConduitM DumpPackage o m (Map PackageName DumpPackage) sinkMatching allowed = Map.fromList - . map (pkgName . dpPackageIdent &&& id) + . map (pkgName . (.dpPackageIdent) &&& id) . Map.elems . pruneDeps id - dpGhcPkgId - dpDepends + (.dpGhcPkgId) + (.dpDepends) const -- Could consider a better comparison in the future - <$> (CL.filter (isAllowed . dpPackageIdent) .| CL.consume) + <$> (CL.filter (isAllowed . (.dpPackageIdent)) .| CL.consume) where isAllowed (PackageIdentifier name version) = case Map.lookup name allowed of diff --git a/src/Stack/PackageFile.hs b/src/Stack/PackageFile.hs index 5ff28090bb..e4a12fd09b 100644 --- a/src/Stack/PackageFile.hs +++ b/src/Stack/PackageFile.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | A module which exports all package-level file-gathering logic. @@ -53,16 +54,16 @@ packageDescModulesAndFiles :: PackageComponentFile packageDescModulesAndFiles pkg = do packageExtraFile <- resolveGlobFilesFromStackPackageFile - (packageCabalSpec pkg) (packageFile pkg) + pkg.packageCabalSpec pkg.packageFile let initialValue = mempty{packageExtraFile=packageExtraFile} let accumulator f comp st = (insertComponentFile <$> st) <*> f comp let gatherCompFileCollection createCompFileFn getCompFn res = foldr' (accumulator createCompFileFn) res (getCompFn pkg) - gatherCompFileCollection stackLibraryFiles packageLibrary - . gatherCompFileCollection stackLibraryFiles packageSubLibraries - . gatherCompFileCollection stackExecutableFiles packageExecutables - . gatherCompFileCollection stackTestSuiteFiles packageTestSuites - . gatherCompFileCollection stackBenchmarkFiles packageBenchmarks + gatherCompFileCollection stackLibraryFiles (.packageLibrary) + . gatherCompFileCollection stackLibraryFiles (.packageSubLibraries) + . gatherCompFileCollection stackExecutableFiles (.packageExecutables) + . gatherCompFileCollection stackTestSuiteFiles (.packageTestSuites) + . gatherCompFileCollection stackBenchmarkFiles (.packageBenchmarks) $ pure initialValue resolveGlobFilesFromStackPackageFile :: @@ -89,7 +90,7 @@ resolveGlobFiles cabalFileVersion = then explode name else fmap pure (resolveFileOrWarn name) explode name = do - dir <- asks (parent . ctxFile) + dir <- asks (parent . (.ctxFile)) names <- matchDirFileGlob' (toFilePath dir) name mapM resolveFileOrWarn names matchDirFileGlob' dir glob = @@ -127,7 +128,7 @@ getPackageFile pkg cabalfp = (GetPackageFileContext cabalfp distDir bc cabalVer) (packageDescModulesAndFiles pkg) setupFiles <- - if packageBuildType pkg == Cabal.Custom + if pkg.packageBuildType == Cabal.Custom then do let setupHsPath = pkgDir relFileSetupHs setupLhsPath = pkgDir relFileSetupLhs @@ -146,7 +147,7 @@ getPackageFile pkg cabalfp = pure $ if hpackExists then S.singleton hpackPath else S.empty pure packageComponentFile { packageExtraFile = - moreBuildFiles <> packageExtraFile packageComponentFile + moreBuildFiles <> packageComponentFile.packageExtraFile } stackPackageFileFromCabal :: Cabal.PackageDescription -> StackPackageFile diff --git a/src/Stack/Path.hs b/src/Stack/Path.hs index 34be5d9547..bcceff8e9a 100644 --- a/src/Stack/Path.hs +++ b/src/Stack/Path.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @path@ command. module Stack.Path @@ -53,7 +54,7 @@ path :: [Text] -> RIO Runner () -- Distinguish a request for only the Stack root, as such a request does not -- require 'withDefaultEnvConfig'. path [key] | key == stackRootOptionName' = do - clArgs <- view $ globalOptsL.to globalConfigMonoid + clArgs <- view $ globalOptsL . to (.globalConfigMonoid) liftIO $ do (_, stackRoot, _) <- determineStackRootAndOwnership clArgs T.putStrLn $ T.pack $ toFilePathNoTrailingSep stackRoot @@ -87,13 +88,14 @@ runHaddock x action = local modifyConfig $ withDefaultEnvConfig action where modifyConfig = set - (globalOptsL.globalOptsBuildOptsMonoidL.buildOptsMonoidHaddockL) (Just x) + (globalOptsL . globalOptsBuildOptsMonoidL . buildOptsMonoidHaddockL) + (Just x) fillPathInfo :: HasEnvConfig env => RIO env PathInfo fillPathInfo = do -- We must use a BuildConfig from an EnvConfig to ensure that it contains the -- full environment info including GHC paths etc. - piBuildConfig <- view $ envConfigL.buildConfigL + piBuildConfig <- view $ envConfigL . buildConfigL -- This is the modified 'bin-path', -- including the local GHC or MSYS if not configured to operate on -- global GHC. @@ -102,7 +104,7 @@ fillPathInfo = do piSnapDb <- packageDatabaseDeps piLocalDb <- packageDatabaseLocal piExtraDbs <- packageDatabaseExtra - piGlobalDb <- view $ compilerPathsL.to cpGlobalDB + piGlobalDb <- view $ compilerPathsL . to (.cpGlobalDB) piSnapRoot <- installationRootDeps piLocalRoot <- installationRootLocal piToolsDir <- bindirCompilerTools @@ -142,40 +144,40 @@ data PathInfo = PathInfo } instance HasPlatform PathInfo where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasLogFunc PathInfo where - logFuncL = configL.logFuncL + logFuncL = configL . logFuncL instance HasRunner PathInfo where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasStylesUpdate PathInfo where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm PathInfo where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL instance HasGHCVariant PathInfo where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasConfig PathInfo where - configL = buildConfigL.lens bcConfig (\x y -> x { bcConfig = y }) + configL = buildConfigL . lens (.bcConfig) (\x y -> x { bcConfig = y }) {-# INLINE configL #-} instance HasPantryConfig PathInfo where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasProcessContext PathInfo where - processContextL = configL.processContextL + processContextL = configL . processContextL instance HasBuildConfig PathInfo where - buildConfigL = lens piBuildConfig (\x y -> x { piBuildConfig = y }) + buildConfigL = lens (.piBuildConfig) (\x y -> x { piBuildConfig = y }) . buildConfigL data UseHaddocks a @@ -194,16 +196,18 @@ paths :: [(String, Text, UseHaddocks (PathInfo -> Text))] paths = [ ( "Global Stack root directory" , stackRootOptionName' - , WithoutHaddocks $ view (stackRootL.to toFilePathNoTrailingSep.to T.pack)) + , WithoutHaddocks $ + view (stackRootL . to toFilePathNoTrailingSep . to T.pack)) , ( "Global Stack configuration file" , T.pack stackGlobalConfigOptionName - , WithoutHaddocks $ view (stackGlobalConfigL.to toFilePath.to T.pack)) + , WithoutHaddocks $ view (stackGlobalConfigL . to toFilePath . to T.pack)) , ( "Project root (derived from stack.yaml file)" , "project-root" - , WithoutHaddocks $ view (projectRootL.to toFilePathNoTrailingSep.to T.pack)) + , WithoutHaddocks $ + view (projectRootL . to toFilePathNoTrailingSep . to T.pack)) , ( "Configuration location (where the stack.yaml file is)" , "config-location" - , WithoutHaddocks $ view (stackYamlL.to toFilePath.to T.pack)) + , WithoutHaddocks $ view (stackYamlL . to toFilePath . to T.pack)) , ( "PATH environment variable" , "bin-path" , WithoutHaddocks $ @@ -211,73 +215,73 @@ paths = , ( "Install location for GHC and other core tools (see 'stack ls tools' command)" , "programs" , WithoutHaddocks $ - view (configL.to configLocalPrograms.to toFilePathNoTrailingSep.to T.pack)) + view (configL . to (.configLocalPrograms) . to toFilePathNoTrailingSep . to T.pack)) , ( "Compiler binary (e.g. ghc)" , "compiler-exe" - , WithoutHaddocks $ T.pack . toFilePath . piCompiler ) + , WithoutHaddocks $ T.pack . toFilePath . (.piCompiler) ) , ( "Directory containing the compiler binary (e.g. ghc)" , "compiler-bin" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . parent . piCompiler ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . parent . (.piCompiler) ) , ( "Directory containing binaries specific to a particular compiler" , "compiler-tools-bin" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piToolsDir ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piToolsDir) ) , ( "Directory where Stack installs executables (e.g. ~/.local/bin (Unix-like OSs) or %APPDATA%\\local\\bin (Windows))" , "local-bin" , WithoutHaddocks $ - view $ configL.to configLocalBin.to toFilePathNoTrailingSep.to T.pack) + view $ configL . to (.configLocalBin) . to toFilePathNoTrailingSep . to T.pack) , ( "Extra include directories" , "extra-include-dirs" , WithoutHaddocks $ - T.intercalate ", " . map T.pack . configExtraIncludeDirs . view configL ) + T.intercalate ", " . map T.pack . (.configExtraIncludeDirs) . view configL ) , ( "Extra library directories" , "extra-library-dirs" , WithoutHaddocks $ - T.intercalate ", " . map T.pack . configExtraLibDirs . view configL ) + T.intercalate ", " . map T.pack . (.configExtraLibDirs) . view configL ) , ( "Snapshot package database" , "snapshot-pkg-db" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piSnapDb ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piSnapDb) ) , ( "Local project package database" , "local-pkg-db" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piLocalDb ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piLocalDb) ) , ( "Global package database" , "global-pkg-db" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piGlobalDb ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piGlobalDb) ) , ( "GHC_PACKAGE_PATH environment variable" , "ghc-package-path" , WithoutHaddocks $ \pi' -> mkGhcPackagePath True - (piLocalDb pi') - (piSnapDb pi') - (piExtraDbs pi') - (piGlobalDb pi') + pi'.piLocalDb + pi'.piSnapDb + pi'.piExtraDbs + pi'.piGlobalDb ) , ( "Snapshot installation root" , "snapshot-install-root" , WithoutHaddocks $ - T.pack . toFilePathNoTrailingSep . piSnapRoot ) + T.pack . toFilePathNoTrailingSep . (.piSnapRoot) ) , ( "Local project installation root" , "local-install-root" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piLocalRoot ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piLocalRoot) ) , ( "Snapshot documentation root" , "snapshot-doc-root" , UseHaddocks $ - \pi' -> T.pack (toFilePathNoTrailingSep (piSnapRoot pi' docDirSuffix)) + \pi' -> T.pack (toFilePathNoTrailingSep (pi'.piSnapRoot docDirSuffix)) ) , ( "Local project documentation root" , "local-doc-root" , UseHaddocks $ - \pi' -> T.pack (toFilePathNoTrailingSep (piLocalRoot pi' docDirSuffix)) + \pi' -> T.pack (toFilePathNoTrailingSep (pi'.piLocalRoot docDirSuffix)) ) , ( "Local project documentation root" , "local-hoogle-root" - , UseHaddocks $ T.pack . toFilePathNoTrailingSep . piHoogleRoot) + , UseHaddocks $ T.pack . toFilePathNoTrailingSep . (.piHoogleRoot)) , ( "Dist work directory, relative to package directory" , "dist-dir" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piDistDir ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piDistDir) ) , ( "Where HPC reports and tix files are stored" , "local-hpc-root" - , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . piHpcDir ) + , WithoutHaddocks $ T.pack . toFilePathNoTrailingSep . (.piHpcDir) ) ] -- | 'Text' equivalent of 'stackRootOptionName'. diff --git a/src/Stack/Prelude.hs b/src/Stack/Prelude.hs index dfa6ab0dd4..956c89e3d2 100644 --- a/src/Stack/Prelude.hs +++ b/src/Stack/Prelude.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Prelude ( withSystemTempDir @@ -284,10 +285,10 @@ instance Monoid FirstTrue where -- | Get the 'Bool', defaulting to 'True' fromFirstTrue :: FirstTrue -> Bool -fromFirstTrue = fromMaybe True . getFirstTrue +fromFirstTrue = fromMaybe True . (.getFirstTrue) -- | Helper for filling in default values -defaultFirstTrue :: (a -> FirstTrue) -> Bool +defaultFirstTrue :: FirstTrue -> Bool defaultFirstTrue _ = True -- | Like @First Bool@, but the default is @False@. @@ -305,10 +306,10 @@ instance Monoid FirstFalse where -- | Get the 'Bool', defaulting to 'False' fromFirstFalse :: FirstFalse -> Bool -fromFirstFalse = fromMaybe False . getFirstFalse +fromFirstFalse = fromMaybe False . (.getFirstFalse) -- | Helper for filling in default values -defaultFirstFalse :: (a -> FirstFalse) -> Bool +defaultFirstFalse :: FirstFalse -> Bool defaultFirstFalse _ = False -- | Write a @Builder@ to a file and atomically rename. diff --git a/src/Stack/Query.hs b/src/Stack/Query.hs index 0999f00217..a089a76a88 100644 --- a/src/Stack/Query.hs +++ b/src/Stack/Query.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @query@ command. module Stack.Query @@ -107,8 +108,8 @@ queryBuildInfo selectors0 = rawBuildInfo :: HasEnvConfig env => RIO env Value rawBuildInfo = do locals <- projectLocalPackages - wantedCompiler <- view $ wantedCompilerVersionL.to (utf8BuilderToText . display) - actualCompiler <- view $ actualCompilerVersionL.to compilerVersionText + wantedCompiler <- view $ wantedCompilerVersionL . to (utf8BuilderToText . display) + actualCompiler <- view $ actualCompilerVersionL . to compilerVersionText pure $ object [ "locals" .= Object (KeyMap.fromList $ map localToPair locals) , "compiler" .= object @@ -118,10 +119,10 @@ rawBuildInfo = do ] where localToPair lp = - (Key.fromText $ T.pack $ packageNameString $ packageName p, value) + (Key.fromText $ T.pack $ packageNameString p.packageName, value) where - p = lpPackage lp + p = lp.lpPackage value = object - [ "version" .= CabalString (packageVersion p) - , "path" .= toFilePath (parent $ lpCabalFile lp) + [ "version" .= CabalString p.packageVersion + , "path" .= toFilePath (parent lp.lpCabalFile) ] diff --git a/src/Stack/Runners.hs b/src/Stack/Runners.hs index 06b5da789c..270f708c71 100644 --- a/src/Stack/Runners.hs +++ b/src/Stack/Runners.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Utilities for running stack commands. -- @@ -127,7 +128,7 @@ withConfig shouldReexec inner = -- If we have been relaunched in a Docker container, perform in-container -- initialization (switch UID, etc.). We do this after first loading the -- configuration since it must happen ASAP but needs a configuration. - view (globalOptsL.to globalDockerEntrypoint) >>= + view (globalOptsL . to (.globalDockerEntrypoint)) >>= traverse_ (Docker.entrypoint config) runRIO config $ do -- Catching all exceptions here, since we don't want this @@ -145,8 +146,8 @@ withConfig shouldReexec inner = -- action. reexec :: RIO Config a -> RIO Config a reexec inner = do - nixEnable' <- asks $ nixEnable . configNix - notifyIfNixOnPath <- asks configNotifyIfNixOnPath + nixEnable' <- asks $ (.configNix.nixEnable) + notifyIfNixOnPath <- asks (.configNotifyIfNixOnPath) when (not nixEnable' && notifyIfNixOnPath) $ do eNix <- findExecutable nixProgName case eNix of @@ -189,7 +190,7 @@ reexec inner = do , muteMsg ] <> line - dockerEnable' <- asks $ dockerEnable . configDocker + dockerEnable' <- asks (.configDocker.dockerEnable) case (nixEnable', dockerEnable') of (True, True) -> throwIO DockerAndNixInvalid (False, False) -> inner @@ -220,18 +221,18 @@ withRunnerGlobal :: GlobalOpts -> RIO Runner a -> IO a withRunnerGlobal go inner = do colorWhen <- maybe defaultColorWhen pure $ - getFirst $ configMonoidColorWhen $ globalConfigMonoid go + getFirst go.globalConfigMonoid.configMonoidColorWhen useColor <- case colorWhen of ColorNever -> pure False ColorAlways -> pure True ColorAuto -> hSupportsANSI stderr termWidth <- clipWidth <$> maybe (fromMaybe defaultTerminalWidth <$> getTerminalWidth) - pure (globalTermWidth go) + pure go.globalTermWidth menv <- mkDefaultProcessContext -- MVar used to ensure the Docker entrypoint is performed exactly once. dockerEntrypointMVar <- newMVar False - let update = globalStylesUpdate go + let update = go.globalStylesUpdate withNewLogFunc go useColor update $ \logFunc -> do runRIO Runner { runnerGlobalOpts = go @@ -251,7 +252,7 @@ withRunnerGlobal go inner = do shouldUpgradeCheck :: RIO Config () shouldUpgradeCheck = do config <- ask - when (configRecommendUpgrade config) $ do + when config.configRecommendUpgrade $ do now <- getCurrentTime let yesterday = addUTCTime (-24 * 60 * 60) now checks <- upgradeChecksSince yesterday @@ -279,7 +280,7 @@ shouldUpgradeCheck = do [ flow "Tired of seeing this? Add" , style Shell (flow "recommend-stack-upgrade: false") , "to" - , pretty (configUserConfigPath config) <> "." + , pretty config.configUserConfigPath <> "." ] <> blankLine _ -> pure () diff --git a/src/Stack/SDist.hs b/src/Stack/SDist.hs index e71aeb9e0d..36e99cbae2 100644 --- a/src/Stack/SDist.hs +++ b/src/Stack/SDist.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE TypeFamilies #-} -- Types and functions related to Stack's @sdist@ command. module Stack.SDist @@ -143,10 +144,10 @@ sdistCmd :: SDistOpts -> RIO Runner () sdistCmd sdistOpts = withConfig YesReexec $ withDefaultEnvConfig $ do -- If no directories are specified, build all sdist tarballs. - dirs' <- if null (sdoptsDirsToWorkWith sdistOpts) + dirs' <- if null sdistOpts.sdoptsDirsToWorkWith then do dirs <- view $ - buildConfigL.to (map ppRoot . Map.elems . smwProject . bcSMWanted) + buildConfigL . to (map ppRoot . Map.elems . (.bcSMWanted.smwProject)) when (null dirs) $ do stackYaml <- view stackYamlL prettyErrorL @@ -159,10 +160,10 @@ sdistCmd sdistOpts = ] exitFailure pure dirs - else mapM resolveDir' (sdoptsDirsToWorkWith sdistOpts) + else mapM resolveDir' sdistOpts.sdoptsDirsToWorkWith forM_ dirs' $ \dir -> do (tarName, tarBytes, _mcabalRevision) <- - getSDistTarball (sdoptsPvpBounds sdistOpts) dir + getSDistTarball sdistOpts.sdoptsPvpBounds dir distDir <- distDirFromDir dir tarPath <- (distDir ) <$> parseRelFile tarName ensureDir (parent tarPath) @@ -174,7 +175,7 @@ sdistCmd sdistOpts = , pretty tarPath <> "." ] checkSDistTarball sdistOpts tarPath - forM_ (sdoptsTarPath sdistOpts) $ copyTarToTarPath tarPath tarName + forM_ sdistOpts.sdoptsTarPath $ copyTarToTarPath tarPath tarName where copyTarToTarPath tarPath tarName targetDir = liftIO $ do let targetTarPath = targetDir FP. tarName @@ -201,11 +202,11 @@ getSDistTarball :: getSDistTarball mpvpBounds pkgDir = do config <- view configL let PvpBounds pvpBounds asRevision = - fromMaybe (configPvpBounds config) mpvpBounds + fromMaybe config.configPvpBounds mpvpBounds tweakCabal = pvpBounds /= PvpBoundsNone pkgFp = toFilePath pkgDir lp <- readLocalPackage pkgDir - forM_ (packageSetupDeps (lpPackage lp)) $ \customSetupDeps -> + forM_ lp.lpPackage.packageSetupDeps $ \customSetupDeps -> case nonEmpty (map (T.pack . packageNameString) (Map.keys customSetupDeps)) of Just nonEmptyDepTargets -> do eres <- buildLocalTargets nonEmptyDepTargets @@ -219,12 +220,12 @@ getSDistTarball mpvpBounds pkgDir = do pure () Nothing -> prettyWarnS "unexpected empty custom-setup dependencies." - sourceMap <- view $ envConfigL.to envConfigSourceMap + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) installMap <- toInstallMap sourceMap (installedMap, _globalDumpPkgs, _snapshotDumpPkgs, _localDumpPkgs) <- getInstalled installMap let deps = Map.fromList - [ (pid, iliId libInfo) + [ (pid, libInfo.iliId) | (_, Library pid libInfo) <- Map.elems installedMap] prettyInfoL [ flow "Getting the file list for" @@ -273,7 +274,7 @@ getSDistTarball mpvpBounds pkgDir = do isCabalFp fp = toFilePath pkgDir FP. fp == toFilePath cabalfp tarName = pkgIdName FP.<.> "tar.gz" pkgIdName = packageIdentifierString pkgId - pkgId = packageIdentifier (lpPackage lp) + pkgId = packageIdentifier lp.lpPackage dirEntries <- mapM packDir (dirsFromFiles files) fileEntries <- mapM packFile files mcabalFileRevision <- liftIO (readIORef cabalFileRevisionRef) @@ -549,13 +550,13 @@ checkSDistTarball opts tarball = withTempTarGzContents tarball $ \pkgDir' -> do pkgDir <- (pkgDir' ) <$> (parseRelDir . FP.takeBaseName . FP.takeBaseName . toFilePath $ tarball) -- ^ drop ".tar" ^ drop ".gz" - when (sdoptsBuildTarball opts) + when opts.sdoptsBuildTarball ( buildExtractedTarball ResolvedPath { resolvedRelative = RelFilePath "this-is-not-used" -- ugly hack , resolvedAbsolute = pkgDir } ) - unless (sdoptsIgnoreCheck opts) (checkPackageInExtractedTarball pkgDir) + unless opts.sdoptsIgnoreCheck (checkPackageInExtractedTarball pkgDir) checkPackageInExtractedTarball :: HasEnvConfig env @@ -608,26 +609,26 @@ buildExtractedTarball pkgDir = do let isPathToRemove path = do localPackage <- readLocalPackage path pure - $ packageName (lpPackage localPackage) - == packageName (lpPackage localPackageToBuild) + $ localPackage.lpPackage.packageName + == localPackageToBuild.lpPackage.packageName pathsToKeep <- Map.fromList <$> filterM - (fmap not . isPathToRemove . resolvedAbsolute . ppResolvedDir . snd) - (Map.toList (smwProject (bcSMWanted (envConfigBuildConfig envConfig)))) + (fmap not . isPathToRemove . resolvedAbsolute . (.ppResolvedDir) . snd) + (Map.toList envConfig.envConfigBuildConfig.bcSMWanted.smwProject) pp <- mkProjectPackage YesPrintWarnings pkgDir False let adjustEnvForBuild env = let updatedEnvConfig = envConfig { envConfigSourceMap = - updatePackagesInSourceMap (envConfigSourceMap envConfig) + updatePackagesInSourceMap envConfig.envConfigSourceMap , envConfigBuildConfig = - updateBuildConfig (envConfigBuildConfig envConfig) + updateBuildConfig envConfig.envConfigBuildConfig } updateBuildConfig bc = bc - { bcConfig = (bcConfig bc) + { bcConfig = bc.bcConfig { configBuild = defaultBuildOpts { boptsTests = True } } } in set envConfigL updatedEnvConfig env updatePackagesInSourceMap sm = - sm {smProject = Map.insert (cpName $ ppCommon pp) pp pathsToKeep} + sm {smProject = Map.insert pp.ppCommon.cpName pp pathsToKeep} local adjustEnvForBuild $ build Nothing -- | Version of 'checkSDistTarball' that first saves lazy bytestring to diff --git a/src/Stack/Script.hs b/src/Stack/Script.hs index 254b4cba37..f7b60920bd 100644 --- a/src/Stack/Script.hs +++ b/src/Stack/Script.hs @@ -136,7 +136,7 @@ scriptCmd opts = do -- Note that in this functions we use logError instead of logWarn because, -- when using the interpreter mode, only error messages are shown. See: -- https://github.com/commercialhaskell/stack/issues/3007 - view (globalOptsL . to globalStackYaml) >>= \case + view (globalOptsL . to (.globalStackYaml)) >>= \case SYLOverride fp -> logError $ "Ignoring override stack.yaml file for script command: " <> fromString (toFilePath fp) @@ -144,25 +144,25 @@ scriptCmd opts = do SYLDefault -> pure () SYLNoProject _ -> assert False (pure ()) - file <- resolveFile' $ soFile opts + file <- resolveFile' opts.soFile let scriptFile = filename file - isNoRunCompile <- fromFirstFalse . configMonoidNoRunCompile <$> - view (globalOptsL . to globalConfigMonoid) + isNoRunCompile <- fromFirstFalse . (.configMonoidNoRunCompile) <$> + view (globalOptsL . to (.globalConfigMonoid)) let scriptDir = parent file modifyGO go = go - { globalConfigMonoid = (globalConfigMonoid go) + { globalConfigMonoid = go.globalConfigMonoid { configMonoidInstallGHC = FirstTrue $ Just True } - , globalStackYaml = SYLNoProject $ soScriptExtraDeps opts + , globalStackYaml = SYLNoProject opts.soScriptExtraDeps } (shouldRun, shouldCompile) = if isNoRunCompile then (NoRun, SECompile) - else (soShouldRun opts, soCompile opts) + else (opts.soShouldRun, opts.soCompile) root <- withConfig NoReexec $ view stackRootL - outputDir <- if soUseRoot opts + outputDir <- if opts.soUseRoot then do scriptFileAsDir <- maybe (throwIO $ FailedToParseScriptFileAsDirBug scriptFile) @@ -191,7 +191,7 @@ scriptCmd opts = do case shouldRun of YesRun -> pure () NoRun -> do - unless (null $ soArgs opts) $ throwIO ArgumentsWithNoRunInvalid + unless (null opts.soArgs) $ throwIO ArgumentsWithNoRunInvalid case shouldCompile of SEInterpret -> throwIO NoRunWithoutCompilationInvalid SECompile -> pure () @@ -208,7 +208,7 @@ scriptCmd opts = do where runCompiled shouldRun exe = do case shouldRun of - YesRun -> exec (fromAbsFile exe) (soArgs opts) + YesRun -> exec (fromAbsFile exe) opts.soArgs NoRun -> prettyInfoL [ flow "Compilation finished, executable available at" , style File (fromString (fromAbsFile exe)) <> "." @@ -226,13 +226,13 @@ scriptCmd opts = do withConfig YesReexec $ withDefaultEnvConfig $ do config <- view configL - menv <- liftIO $ configProcessContextSettings config defaultEnvSettings + menv <- liftIO $ config.configProcessContextSettings defaultEnvSettings withProcessContext menv $ do colorFlag <- appropriateGhcColorFlag targetsSet <- - case soPackages opts of - [] -> getPackagesFromImports (soFile opts) -- Using the import parser + case opts.soPackages of + [] -> getPackagesFromImports opts.soFile -- Using the import parser packages -> do let targets = concatMap wordsComma packages targets' <- mapM parsePackageNameThrowing targets @@ -243,7 +243,7 @@ scriptCmd opts = do -- to check which packages are installed already. If all needed -- packages are available, we can skip the (rather expensive) build -- call below. - GhcPkgExe pkg <- view $ compilerPathsL . to cpPkg + GhcPkgExe pkg <- view $ compilerPathsL . to (.cpPkg) -- https://github.com/haskell/process/issues/251 bss <- snd <$> sinkProcessStderrStdout (toFilePath pkg) ["list", "--simple-output"] CL.sinkNull CL.consume -- FIXME use the package info from envConfigPackages, or is that crazy? @@ -272,8 +272,8 @@ scriptCmd opts = do SEInterpret -> [] SECompile -> [] SEOptimize -> ["-O2"] - , soGhcOptions opts - , if soUseRoot opts + , opts.soGhcOptions + , if opts.soUseRoot then [ "-outputdir=" ++ fromAbsDir (parent exe) , "-o", fromAbsFile exe @@ -282,9 +282,9 @@ scriptCmd opts = do ] case shouldCompile of SEInterpret -> do - interpret <- view $ compilerPathsL . to cpInterpreter + interpret <- view $ compilerPathsL . to (.cpInterpreter) exec (toFilePath interpret) - (ghcArgs ++ toFilePath file : soArgs opts) + (ghcArgs ++ toFilePath file : opts.soArgs) _ -> do -- Use readProcessStdout_ so that (1) if GHC does send any output -- to stdout, we capture it and stop it from being sent to our @@ -293,7 +293,7 @@ scriptCmd opts = do -- to the user. liftIO $ Dir.createDirectoryIfMissing True (fromAbsDir (parent exe)) compilerExeName <- - view $ compilerPathsL . to cpCompiler . to toFilePath + view $ compilerPathsL . to (.cpCompiler) . to toFilePath withWorkingDir (fromAbsDir (parent file)) $ proc compilerExeName (ghcArgs ++ [toFilePath file]) @@ -330,12 +330,12 @@ getPackagesFromModuleNames mns = do hashSnapshot :: RIO EnvConfig SnapshotCacheHash hashSnapshot = do - sourceMap <- view $ envConfigL . to envConfigSourceMap + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) compilerInfo <- getCompilerInfo let eitherPliHash (pn, dep) - | PLImmutable pli <- dpLocation dep = Right $ immutableLocSha pli + | PLImmutable pli <- dep.dpLocation = Right $ immutableLocSha pli | otherwise = Left pn - deps = Map.toList (smDeps sourceMap) + deps = Map.toList sourceMap.smDeps case partitionEithers (map eitherPliHash deps) of ([], pliHashes) -> do let hashedContent = mconcat $ compilerInfo : pliHashes @@ -346,18 +346,19 @@ hashSnapshot = do mapSnapshotPackageModules :: RIO EnvConfig (Map PackageName (Set ModuleName)) mapSnapshotPackageModules = do - sourceMap <- view $ envConfigL . to envConfigSourceMap + sourceMap <- view $ envConfigL . to (.envConfigSourceMap) installMap <- toInstallMap sourceMap (_installedMap, globalDumpPkgs, snapshotDumpPkgs, _localDumpPkgs) <- getInstalled installMap - let globals = dumpedPackageModules (smGlobal sourceMap) globalDumpPkgs - notHidden = Map.filter (not . dpHidden) - notHiddenDeps = notHidden $ smDeps sourceMap + let globals = dumpedPackageModules sourceMap.smGlobal globalDumpPkgs + notHidden = Map.filter (not . (.dpHidden)) + notHiddenDeps = notHidden sourceMap.smDeps installedDeps = dumpedPackageModules notHiddenDeps snapshotDumpPkgs - dumpPkgs = Set.fromList $ map (pkgName . dpPackageIdent) snapshotDumpPkgs + dumpPkgs = + Set.fromList $ map (pkgName . (.dpPackageIdent)) snapshotDumpPkgs notInstalledDeps = Map.withoutKeys notHiddenDeps dumpPkgs otherDeps <- for notInstalledDeps $ \dep -> do - gpd <- liftIO $ cpGPD (dpCommon dep) + gpd <- liftIO dep.dpCommon.cpGPD Set.fromList <$> allExposedModules gpd -- source map construction process should guarantee unique package names in -- these maps diff --git a/src/Stack/Setup.hs b/src/Stack/Setup.hs index 10b2b8bae7..8608513f55 100644 --- a/src/Stack/Setup.hs +++ b/src/Stack/Setup.hs @@ -2,6 +2,7 @@ {-# LANGUAGE DataKinds #-} {-# LANGUAGE LambdaCase #-} {-# LANGUAGE MultiWayIf #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} {-# LANGUAGE TypeFamilies #-} {-# LANGUAGE ViewPatterns #-} @@ -641,47 +642,47 @@ setupEnv :: setupEnv needTargets boptsCLI mResolveMissingGHC = do config <- view configL bc <- view buildConfigL - let stackYaml = bcStackYaml bc + let stackYaml = bc.bcStackYaml platform <- view platformL wcVersion <- view wantedCompilerVersionL wanted <- view wantedCompilerVersionL actual <- either throwIO pure $ wantedToActual wanted let wc = actual^.whichCompilerL let sopts = SetupOpts - { soptsInstallIfMissing = configInstallGHC config - , soptsUseSystem = configSystemGHC config + { soptsInstallIfMissing = config.configInstallGHC + , soptsUseSystem = config.configSystemGHC , soptsWantedCompiler = wcVersion - , soptsCompilerCheck = configCompilerCheck config + , soptsCompilerCheck = config.configCompilerCheck , soptsStackYaml = Just stackYaml , soptsForceReinstall = False , soptsSanityCheck = False - , soptsSkipGhcCheck = configSkipGHCCheck config - , soptsSkipMsys = configSkipMsys config + , soptsSkipGhcCheck = config.configSkipGHCCheck + , soptsSkipMsys = config.configSkipMsys , soptsResolveMissingGHC = mResolveMissingGHC , soptsGHCBindistURL = Nothing } (compilerPaths, ghcBin) <- ensureCompilerAndMsys sopts - let compilerVer = cpCompilerVersion compilerPaths + let compilerVer = compilerPaths.cpCompilerVersion -- Modify the initial environment to include the GHC path, if a local GHC -- is being used menv0 <- view processContextL env <- either throwM (pure . removeHaskellEnvVars) $ augmentPathMap - (map toFilePath $ edBins ghcBin) + (map toFilePath ghcBin.edBins) (view envVarsL menv0) menv <- mkProcessContext env logDebug "Resolving package entries" (sourceMap, sourceMapHash) <- runWithGHC menv compilerPaths $ do - smActual <- actualFromGhc (bcSMWanted bc) compilerVer - let actualPkgs = Map.keysSet (smaDeps smActual) <> - Map.keysSet (smaProject smActual) + smActual <- actualFromGhc bc.bcSMWanted compilerVer + let actualPkgs = Map.keysSet smActual.smaDeps <> + Map.keysSet smActual.smaProject prunedActual = smActual - { smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs } - haddockDeps = shouldHaddockDeps (configBuild config) + { smaGlobal = pruneGlobals smActual.smaGlobal actualPkgs } + haddockDeps = shouldHaddockDeps config.configBuild targets <- parseTargets needTargets haddockDeps boptsCLI prunedActual sourceMap <- loadSourceMap targets boptsCLI smActual sourceMapHash <- hashSourceMapData boptsCLI sourceMap @@ -707,12 +708,12 @@ setupEnv needTargets boptsCLI mResolveMissingGHC = do either throwM pure $ augmentPath (toFilePath <$> mkDirs True) mpath deps <- runRIO envConfig0 packageDatabaseDeps - runWithGHC menv compilerPaths $ createDatabase (cpPkg compilerPaths) deps + runWithGHC menv compilerPaths $ createDatabase compilerPaths.cpPkg deps localdb <- runRIO envConfig0 packageDatabaseLocal - runWithGHC menv compilerPaths $ createDatabase (cpPkg compilerPaths) localdb + runWithGHC menv compilerPaths $ createDatabase compilerPaths.cpPkg localdb extras <- runReaderT packageDatabaseExtra envConfig0 let mkGPP locals = - mkGhcPackagePath locals localdb deps extras $ cpGlobalDB compilerPaths + mkGhcPackagePath locals localdb deps extras compilerPaths.cpGlobalDB distDir <- runReaderT distRelativeDir envConfig0 >>= canonicalizePath @@ -731,23 +732,23 @@ setupEnv needTargets boptsCLI mResolveMissingGHC = do eo <- mkProcessContext $ Map.insert "PATH" - (if esIncludeLocals es then localsPath else depsPath) - $ (if esIncludeGhcPackagePath es + (if es.esIncludeLocals then localsPath else depsPath) + $ (if es.esIncludeGhcPackagePath then Map.insert (ghcPkgPathEnvVar wc) - (mkGPP (esIncludeLocals es)) + (mkGPP es.esIncludeLocals) else id) - $ (if esStackExe es + $ (if es.esStackExe then Map.insert "STACK_EXE" (T.pack executablePath) else id) - $ (if esLocaleUtf8 es + $ (if es.esLocaleUtf8 then Map.union utf8EnvVars else id) - $ case (soptsSkipMsys sopts, platform) of + $ case (sopts.soptsSkipMsys, platform) of (False, Platform Cabal.I386 Cabal.Windows) -> Map.insert "MSYSTEM" "MINGW32" (False, Platform Cabal.X86_64 Cabal.Windows) -> @@ -755,7 +756,7 @@ setupEnv needTargets boptsCLI mResolveMissingGHC = do _ -> id -- See https://github.com/commercialhaskell/stack/issues/3444 - $ case (esKeepGhcRts es, mGhcRtsEnvVar) of + $ case (es.esKeepGhcRts, mGhcRtsEnvVar) of (True, Just ghcRts) -> Map.insert "GHCRTS" (T.pack ghcRts) _ -> id @@ -765,7 +766,7 @@ setupEnv needTargets boptsCLI mResolveMissingGHC = do "HASKELL_PACKAGE_SANDBOX" (T.pack $ toFilePathNoTrailingSep deps) $ Map.insert "HASKELL_PACKAGE_SANDBOXES" - (T.pack $ if esIncludeLocals es + (T.pack $ if es.esIncludeLocals then intercalate [searchPathSeparator] [ toFilePathNoTrailingSep localdb , toFilePathNoTrailingSep deps @@ -783,7 +784,7 @@ setupEnv needTargets boptsCLI mResolveMissingGHC = do -- are ignored, since we're setting up our -- own package databases. See -- https://github.com/commercialhaskell/stack/issues/4706 - $ (case cpCompilerVersion compilerPaths of + $ (case compilerPaths.cpCompilerVersion of ACGhc version | version >= mkVersion [8, 4, 4] -> Map.insert "GHC_ENVIRONMENT" "-" _ -> id) @@ -817,39 +818,39 @@ insideL :: Lens' (WithGHC env) env insideL = lens (\(WithGHC _ x) -> x) (\(WithGHC cp _) -> WithGHC cp) instance HasLogFunc env => HasLogFunc (WithGHC env) where - logFuncL = insideL.logFuncL + logFuncL = insideL . logFuncL instance HasRunner env => HasRunner (WithGHC env) where - runnerL = insideL.runnerL + runnerL = insideL . runnerL instance HasProcessContext env => HasProcessContext (WithGHC env) where - processContextL = insideL.processContextL + processContextL = insideL . processContextL instance HasStylesUpdate env => HasStylesUpdate (WithGHC env) where - stylesUpdateL = insideL.stylesUpdateL + stylesUpdateL = insideL . stylesUpdateL instance HasTerm env => HasTerm (WithGHC env) where - useColorL = insideL.useColorL - termWidthL = insideL.termWidthL + useColorL = insideL . useColorL + termWidthL = insideL . termWidthL instance HasPantryConfig env => HasPantryConfig (WithGHC env) where - pantryConfigL = insideL.pantryConfigL + pantryConfigL = insideL . pantryConfigL instance HasConfig env => HasPlatform (WithGHC env) where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasConfig env => HasGHCVariant (WithGHC env) where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasConfig env => HasConfig (WithGHC env) where - configL = insideL.configL + configL = insideL . configL instance HasBuildConfig env => HasBuildConfig (WithGHC env) where - buildConfigL = insideL.buildConfigL + buildConfigL = insideL . buildConfigL instance HasCompiler (WithGHC env) where compilerPathsL = to (\(WithGHC cp _) -> cp) @@ -878,39 +879,39 @@ insideMSYSL :: Lens' (WithMSYS env) env insideMSYSL = lens (\(WithMSYS x) -> x) (\(WithMSYS _) -> WithMSYS) instance HasLogFunc env => HasLogFunc (WithMSYS env) where - logFuncL = insideMSYSL.logFuncL + logFuncL = insideMSYSL . logFuncL instance HasRunner env => HasRunner (WithMSYS env) where - runnerL = insideMSYSL.runnerL + runnerL = insideMSYSL . runnerL instance HasProcessContext env => HasProcessContext (WithMSYS env) where - processContextL = insideMSYSL.processContextL + processContextL = insideMSYSL . processContextL instance HasStylesUpdate env => HasStylesUpdate (WithMSYS env) where - stylesUpdateL = insideMSYSL.stylesUpdateL + stylesUpdateL = insideMSYSL . stylesUpdateL instance HasTerm env => HasTerm (WithMSYS env) where - useColorL = insideMSYSL.useColorL - termWidthL = insideMSYSL.termWidthL + useColorL = insideMSYSL . useColorL + termWidthL = insideMSYSL . termWidthL instance HasPantryConfig env => HasPantryConfig (WithMSYS env) where - pantryConfigL = insideMSYSL.pantryConfigL + pantryConfigL = insideMSYSL . pantryConfigL instance HasConfig env => HasPlatform (WithMSYS env) where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasConfig env => HasGHCVariant (WithMSYS env) where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasConfig env => HasConfig (WithMSYS env) where - configL = insideMSYSL.configL + configL = insideMSYSL . configL instance HasBuildConfig env => HasBuildConfig (WithMSYS env) where - buildConfigL = insideMSYSL.buildConfigL + buildConfigL = insideMSYSL . buildConfigL -- | Set up a modified environment which includes the modified PATH that MSYS2 -- can be found on. @@ -927,7 +928,7 @@ runWithMSYS mmsysPaths inner = do Just msysPaths -> do envars <- either throwM pure $ augmentPathMap - (map toFilePath $ edBins msysPaths) + (map toFilePath msysPaths.edBins) (view envVarsL pc0) mkProcessContext envars let envMsys @@ -946,15 +947,15 @@ rebuildEnv :: -> BuildOptsCLI -> RIO env EnvConfig rebuildEnv envConfig needTargets haddockDeps boptsCLI = do - let bc = envConfigBuildConfig envConfig - cp = envConfigCompilerPaths envConfig - compilerVer = smCompiler $ envConfigSourceMap envConfig + let bc = envConfig.envConfigBuildConfig + cp = envConfig.envConfigCompilerPaths + compilerVer = envConfig.envConfigSourceMap.smCompiler runRIO (WithGHC cp bc) $ do - smActual <- actualFromGhc (bcSMWanted bc) compilerVer + smActual <- actualFromGhc bc.bcSMWanted compilerVer let actualPkgs = - Map.keysSet (smaDeps smActual) <> Map.keysSet (smaProject smActual) + Map.keysSet smActual.smaDeps <> Map.keysSet smActual.smaProject prunedActual = smActual - { smaGlobal = pruneGlobals (smaGlobal smActual) actualPkgs } + { smaGlobal = pruneGlobals smActual.smaGlobal actualPkgs } targets <- parseTargets needTargets haddockDeps boptsCLI prunedActual sourceMap <- loadSourceMap targets boptsCLI smActual pure $ envConfig @@ -971,8 +972,8 @@ withNewLocalBuildTargets :: -> RIO env a withNewLocalBuildTargets targets f = do envConfig <- view envConfigL - haddockDeps <- view $ configL.to configBuild.to shouldHaddockDeps - let boptsCLI = envConfigBuildOptsCLI envConfig + haddockDeps <- view $ configL . to (.configBuild) . to shouldHaddockDeps + let boptsCLI = envConfig.envConfigBuildOptsCLI envConfig' <- rebuildEnv envConfig NeedTargets haddockDeps $ boptsCLI {boptsCLITargets = targets} local (set envConfigL envConfig') f @@ -981,10 +982,10 @@ withNewLocalBuildTargets targets f = do addIncludeLib :: ExtraDirs -> Config -> Config addIncludeLib (ExtraDirs _bins includes libs) config = config { configExtraIncludeDirs = - configExtraIncludeDirs config ++ + config.configExtraIncludeDirs ++ map toFilePathNoTrailingSep includes , configExtraLibDirs = - configExtraLibDirs config ++ + config.configExtraLibDirs ++ map toFilePathNoTrailingSep libs } @@ -998,7 +999,7 @@ ensureCompilerAndMsys sopts = do getSetupInfo' <- memoizeRef getSetupInfo mmsys2Tool <- ensureMsys sopts getSetupInfo' mmsysPaths <- maybe (pure Nothing) (fmap Just . extraDirs) mmsys2Tool - actual <- either throwIO pure $ wantedToActual $ soptsWantedCompiler sopts + actual <- either throwIO pure $ wantedToActual sopts.soptsWantedCompiler didWarn <- warnUnsupportedCompiler $ getGhcVersion actual -- Modify the initial environment to include the MSYS2 path, if MSYS2 is being -- used @@ -1015,7 +1016,7 @@ warnUnsupportedCompiler :: => Version -> RIO env Bool warnUnsupportedCompiler ghcVersion = do - notifyIfGhcUntested <- view $ configL.to configNotifyIfGhcUntested + notifyIfGhcUntested <- view $ configL . to (.configNotifyIfGhcUntested) if | ghcVersion < mkVersion [7, 8] -> do prettyWarnL @@ -1048,9 +1049,9 @@ warnUnsupportedCompilerCabal :: -> RIO env () warnUnsupportedCompilerCabal cp didWarn = do unless didWarn $ - void $ warnUnsupportedCompiler $ getGhcVersion $ cpCompilerVersion cp - let cabalVersion = cpCabalVersion cp - notifyIfCabalUntested <- view $ configL.to configNotifyIfCabalUntested + void $ warnUnsupportedCompiler $ getGhcVersion cp.cpCompilerVersion + let cabalVersion = cp.cpCabalVersion + notifyIfCabalUntested <- view $ configL . to (.configNotifyIfCabalUntested) if | cabalVersion < mkVersion [1, 24, 0] -> do prettyWarnL @@ -1089,15 +1090,15 @@ ensureMsys :: -> RIO env (Maybe Tool) ensureMsys sopts getSetupInfo' = do platform <- view platformL - localPrograms <- view $ configL.to configLocalPrograms + localPrograms <- view $ configL . to (.configLocalPrograms) installed <- listInstalled localPrograms case platform of - Platform _ Cabal.Windows | not (soptsSkipMsys sopts) -> + Platform _ Cabal.Windows | not sopts.soptsSkipMsys -> case getInstalledTool installed (mkPackageName "msys2") (const True) of Just tool -> pure (Just tool) Nothing - | soptsInstallIfMissing sopts -> do + | sopts.soptsInstallIfMissing -> do si <- runMemoized getSetupInfo' let msysDir = fillSep [ style Dir "msys2-yyyymmdd" @@ -1106,12 +1107,12 @@ ensureMsys sopts getSetupInfo' = do osKey <- getOSKey "MSYS2" msysDir config <- view configL VersionedDownloadInfo version info <- - case Map.lookup osKey $ siMsys2 si of + case Map.lookup osKey si.siMsys2 of Just x -> pure x Nothing -> prettyThrowIO $ MSYS2NotFound osKey let tool = Tool (PackageIdentifier (mkPackageName "msys2") version) Just <$> downloadAndInstallTool - (configLocalPrograms config) + config.configLocalPrograms info tool (installMsys2Windows si) @@ -1128,9 +1129,9 @@ installGhcBindist :: -> RIO env (Tool, CompilerBuild) installGhcBindist sopts getSetupInfo' installed = do Platform expectedArch _ <- view platformL - let wanted = soptsWantedCompiler sopts + let wanted = sopts.soptsWantedCompiler isWanted = - isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts) + isWantedCompiler sopts.soptsCompilerCheck sopts.soptsWantedCompiler config <- view configL ghcVariant <- view ghcVariantL wc <- either throwIO (pure . whichCompiler) $ wantedToActual wanted @@ -1147,7 +1148,7 @@ installGhcBindist sopts getSetupInfo' installed = do pure (getInstalledTool installed ghcPkgName (isWanted . ACGhc), ghcBuild) let existingCompilers = concatMap (\(installedCompiler, compilerBuild) -> - case (installedCompiler, soptsForceReinstall sopts) of + case (installedCompiler, sopts.soptsForceReinstall) of (Just tool, False) -> [(tool, compilerBuild)] _ -> []) possibleCompilers @@ -1157,22 +1158,22 @@ installGhcBindist sopts getSetupInfo' installed = do case existingCompilers of (tool, build_):_ -> pure (tool, build_) [] - | soptsInstallIfMissing sopts -> do + | sopts.soptsInstallIfMissing -> do si <- runMemoized getSetupInfo' downloadAndInstallPossibleCompilers (map snd possibleCompilers) si - (soptsWantedCompiler sopts) - (soptsCompilerCheck sopts) - (soptsGHCBindistURL sopts) + sopts.soptsWantedCompiler + sopts.soptsCompilerCheck + sopts.soptsGHCBindistURL | otherwise -> do let suggestion = - fromMaybe defaultSuggestion (soptsResolveMissingGHC sopts) + fromMaybe defaultSuggestion sopts.soptsResolveMissingGHC defaultSuggestion = fillSep [ flow "To install the correct version of GHC into the \ \subdirectory for the specified platform in Stack's \ \directory for local tools" - , parens (pretty $ configLocalPrograms config) <> "," + , parens (pretty config.configLocalPrograms) <> "," , flow "try running" , style Shell (flow "stack setup") , flow "or use the" @@ -1189,13 +1190,13 @@ installGhcBindist sopts getSetupInfo' installed = do prettyThrowM $ CompilerVersionMismatch Nothing -- FIXME ((\(x, y, _) -> (x, y)) <$> msystem) - (soptsWantedCompiler sopts, expectedArch) + (sopts.soptsWantedCompiler, expectedArch) ghcVariant (case possibleCompilers of [] -> CompilerBuildStandard (_, compilerBuild):_ -> compilerBuild) - (soptsCompilerCheck sopts) - (soptsStackYaml sopts) + sopts.soptsCompilerCheck + sopts.soptsStackYaml suggestion -- | Ensure compiler is installed. @@ -1205,7 +1206,7 @@ ensureCompiler :: -> Memoized SetupInfo -> RIO (WithMSYS env) (CompilerPaths, ExtraDirs) ensureCompiler sopts getSetupInfo' = do - let wanted = soptsWantedCompiler sopts + let wanted = sopts.soptsWantedCompiler wc <- either throwIO (pure . whichCompiler) $ wantedToActual wanted hook <- ghcInstallHook @@ -1217,13 +1218,13 @@ ensureCompiler sopts getSetupInfo' = do Platform expectedArch _ <- view platformL let canUseCompiler cp - | soptsSkipGhcCheck sopts = pure cp - | not $ isWanted $ cpCompilerVersion cp = + | sopts.soptsSkipGhcCheck = pure cp + | not $ isWanted cp.cpCompilerVersion = prettyThrowIO UnwantedCompilerVersion - | cpArch cp /= expectedArch = prettyThrowIO UnwantedArchitecture + | cp.cpArch /= expectedArch = prettyThrowIO UnwantedArchitecture | otherwise = pure cp isWanted = - isWantedCompiler (soptsCompilerCheck sopts) (soptsWantedCompiler sopts) + isWantedCompiler sopts.soptsCompilerCheck sopts.soptsWantedCompiler let checkCompiler :: Path Abs File -> RIO (WithMSYS env) (Maybe CompilerPaths) checkCompiler compiler = do @@ -1240,7 +1241,7 @@ ensureCompiler sopts getSetupInfo' = do Right cp -> pure $ Just cp mcp <- - if | soptsUseSystem sopts -> do + if | sopts.soptsUseSystem -> do logDebug "Getting system compiler version" runConduit $ sourceSystemCompilers wanted .| @@ -1255,7 +1256,7 @@ ensureCompiler sopts getSetupInfo' = do Nothing -> ensureSandboxedCompiler sopts getSetupInfo' Just cp -> do let paths = ExtraDirs - { edBins = [parent $ cpCompiler cp] + { edBins = [parent cp.cpCompiler] , edInclude = [], edLib = [] } pure (cp, paths) @@ -1272,7 +1273,7 @@ runGHCInstallHook :: -> RIO env (Maybe (Path Abs File)) runGHCInstallHook sopts hook = do logDebug "Getting hook installed compiler version" - let wanted = soptsWantedCompiler sopts + let wanted = sopts.soptsWantedCompiler menv0 <- view processContextL menv <- mkProcessContext (Map.union (wantedCompilerToEnv wanted) $ removeHaskellEnvVars (view envVarsL menv0)) @@ -1282,7 +1283,7 @@ runGHCInstallHook sopts hook = do let ghcPath = stripNewline . TL.unpack . TL.decodeUtf8With T.lenientDecode $ out case parseAbsFile ghcPath of Just compiler -> do - when (soptsSanityCheck sopts) $ sanityCheck compiler + when sopts.soptsSanityCheck $ sanityCheck compiler logDebug ("Using GHC compiler at: " <> fromString (toFilePath compiler)) pure (Just compiler) Nothing -> do @@ -1326,22 +1327,22 @@ ensureSandboxedCompiler :: -> Memoized SetupInfo -> RIO (WithMSYS env) (CompilerPaths, ExtraDirs) ensureSandboxedCompiler sopts getSetupInfo' = do - let wanted = soptsWantedCompiler sopts + let wanted = sopts.soptsWantedCompiler -- List installed tools config <- view configL - let localPrograms = configLocalPrograms config + let localPrograms = config.configLocalPrograms installed <- listInstalled localPrograms logDebug $ "Installed tools: \n - " <> mconcat (intersperse "\n - " (map (fromString . toolString) installed)) (compilerTool, compilerBuild) <- - case soptsWantedCompiler sopts of + case sopts.soptsWantedCompiler of -- shall we build GHC from source? WCGhcGit commitId flavour -> buildGhcFromSource getSetupInfo' installed - (configCompilerRepository config) + config.configCompilerRepository commitId flavour _ -> installGhcBindist sopts getSetupInfo' installed @@ -1350,7 +1351,7 @@ ensureSandboxedCompiler sopts getSetupInfo' = do wc <- either throwIO (pure . whichCompiler) $ wantedToActual wanted menv0 <- view processContextL m <- either throwM pure - $ augmentPathMap (toFilePath <$> edBins paths) (view envVarsL menv0) + $ augmentPathMap (toFilePath <$> paths.edBins) (view envVarsL menv0) menv <- mkProcessContext (removeHaskellEnvVars m) names <- @@ -1364,10 +1365,10 @@ ensureSandboxedCompiler sopts getSetupInfo' = do -- sandbox. This led to a specific issue on Windows with GHC 9.0.1. See -- https://gitlab.haskell.org/ghc/ghc/-/issues/20074. Instead, now, we look -- on the paths specified only. - let loop [] = prettyThrowIO $ SandboxedCompilerNotFound names (edBins paths) + let loop [] = prettyThrowIO $ SandboxedCompilerNotFound names paths.edBins loop (x:xs) = do res <- liftIO $ - D.findExecutablesInDirectories (map toFilePath (edBins paths)) x + D.findExecutablesInDirectories (map toFilePath paths.edBins) x case res of [] -> loop xs compiler:rest -> do @@ -1389,7 +1390,7 @@ ensureSandboxedCompiler sopts getSetupInfo' = do -- Run this here to ensure that the sanity check uses the modified -- environment, otherwise we may infect GHC_PACKAGE_PATH and break sanity -- checks. - when (soptsSanityCheck sopts) $ sanityCheck compiler + when sopts.soptsSanityCheck $ sanityCheck compiler pure compiler @@ -1497,7 +1498,7 @@ pathsFromCompiler wc compilerBuild isSandboxed compiler = cabalPkgVer <- case Map.lookup cabalPackageName globalDump of Nothing -> prettyThrowIO $ CabalNotFound compiler - Just dp -> pure $ pkgVersion $ dpPackageIdent dp + Just dp -> pure $ pkgVersion dp.dpPackageIdent pure CompilerPaths { cpBuild = compilerBuild @@ -1560,7 +1561,7 @@ buildGhcFromSource getSetupInfo' installed (CompilerRepository url) commitId fla -- withRepo is guaranteed to set workingDirL, so let's get it mcwd <- traverse parseAbsDir =<< view workingDirL cwd <- maybe (throwIO WorkingDirectoryInvalidBug) pure mcwd - let threads = configJobs config + let threads = config.configJobs relFileHadrianStackDotYaml' = toFilePath relFileHadrianStackDotYaml ghcBootScriptPath = cwd ghcBootScript boot = if osIsWindows @@ -1573,7 +1574,7 @@ buildGhcFromSource getSetupInfo' installed (CompilerRepository url) commitId fla -- If a resolver is specified on the command line, Stack will -- apply it. This allows the resolver specified in Hadrian's -- stack.yaml file to be overridden. - args' = maybe args addResolver (configResolver config) + args' = maybe args addResolver config.configResolver addResolver resolver = "--resolver=" <> show resolver : args happy = stack ["install", "happy"] alex = stack ["install", "alex"] @@ -1648,7 +1649,7 @@ buildGhcFromSource getSetupInfo' installed (CompilerRepository url) commitId fla | otherwise = installGHCPosix ghcdlinfo si <- runMemoized getSetupInfo' _ <- downloadAndInstallTool - (configLocalPrograms config) + config.configLocalPrograms dlinfo compilerTool (installer si) @@ -1662,7 +1663,7 @@ buildGhcFromSource getSetupInfo' installed (CompilerRepository url) commitId fla getGhcBuilds :: HasConfig env => RIO env [CompilerBuild] getGhcBuilds = do config <- view configL - case configGHCBuild config of + case config.configGHCBuild of Just ghcBuild -> pure [ghcBuild] Nothing -> determineGhcBuild where @@ -1725,7 +1726,7 @@ getGhcBuilds = do libD = fromString (toFilePath lib) libT = T.pack (toFilePath lib) hasMatches lib dirs = do - matches <- filterM (doesFileExist .( lib)) dirs + matches <- filterM (doesFileExist . ( lib)) dirs case matches of [] -> logDebug @@ -1855,7 +1856,7 @@ ensureDockerStackExe containerPlatform = do config <- view configL containerPlatformDir <- runReaderT platformOnlyRelDir (containerPlatform,PlatformVariantNone) - let programsPath = configLocalProgramsBase config containerPlatformDir + let programsPath = config.configLocalProgramsBase containerPlatformDir tool = Tool (PackageIdentifier (mkPackageName "stack") stackVersion) stackExeDir <- installDir programsPath tool let stackExePath = stackExeDir relFileStack @@ -1904,8 +1905,8 @@ sourceSystemCompilers wanted = do getSetupInfo :: HasConfig env => RIO env SetupInfo getSetupInfo = do config <- view configL - let inlineSetupInfo = configSetupInfoInline config - locations' = configSetupInfoLocations config + let inlineSetupInfo = config.configSetupInfoInline + locations' = config.configSetupInfoLocations locations = if null locations' then [defaultSetupInfoYaml] else locations' resolvedSetupInfos <- mapM loadSetupInfo locations @@ -1981,13 +1982,13 @@ downloadAndInstallCompiler ghcBuild si wanted@(WCGhc version) versionCheck mbind ) _ -> do ghcKey <- getGhcKey ghcBuild - case Map.lookup ghcKey $ siGHCs si of + case Map.lookup ghcKey si.siGHCs of Nothing -> throwM $ UnknownOSKey ghcKey Just pairs_ -> getWantedCompilerInfo ghcKey versionCheck wanted ACGhc pairs_ config <- view configL let installer = - case configPlatform config of + case config.configPlatform of Platform _ Cabal.Windows -> installGHCWindows _ -> installGHCPosix downloadInfo prettyInfo $ @@ -2006,8 +2007,8 @@ downloadAndInstallCompiler ghcBuild si wanted@(WCGhc version) versionCheck mbind ("ghc" ++ ghcVariantSuffix ghcVariant ++ compilerBuildSuffix ghcBuild) let tool = Tool $ PackageIdentifier ghcPkgName selectedVersion downloadAndInstallTool - (configLocalPrograms config) - (gdiDownloadInfo downloadInfo) + config.configLocalPrograms + downloadInfo.gdiDownloadInfo tool (installer si) @@ -2092,7 +2093,7 @@ getGhcKey :: -> RIO env Text getGhcKey ghcBuild = do ghcVariant <- view ghcVariantL - wantedComiler <- view $ buildConfigL.to (smwCompiler . bcSMWanted) + wantedComiler <- view $ buildConfigL . to (.bcSMWanted.smwCompiler) ghcVersion <- case wantedComiler of WCGhc version -> pure version WCGhcjs _ _ -> throwIO GhcjsNotSupported @@ -2117,7 +2118,7 @@ getOSKey :: -- ^ Description of the root directory of the tool. -> RIO env Text getOSKey tool toolDir = do - programsDir <- view $ configL.to configLocalPrograms + programsDir <- view $ configL . to (.configLocalPrograms) platform <- view platformL case platform of Platform I386 Cabal.Linux -> pure "linux32" @@ -2159,7 +2160,7 @@ downloadOrUseLocal downloadLabel downloadInfo destination = pure (root path) _ -> prettyThrowIO $ URLInvalid url where - url = T.unpack $ downloadInfoUrl downloadInfo + url = T.unpack downloadInfo.downloadInfoUrl warnOnIgnoredChecks = do let DownloadInfo { downloadInfoContentLength = contentLength @@ -2201,7 +2202,7 @@ downloadFromInfo programsDir downloadInfo tool = do pure (localPath, archiveType) where - url = T.unpack $ downloadInfoUrl downloadInfo + url = T.unpack downloadInfo.downloadInfoUrl extension = loop url where loop fp @@ -2275,7 +2276,7 @@ installGHCPosix downloadInfo _ archiveFile archiveType tempDir destDir = do dir <- expectSingleUnpackedDir archiveFile tempDir - mOverrideGccPath <- view $ configL.to configOverrideGccPath + mOverrideGccPath <- view $ configL . to (.configOverrideGccPath) -- The make application uses the CC environment variable to configure the -- program for compiling C programs @@ -2285,14 +2286,14 @@ installGHCPosix downloadInfo _ archiveFile archiveType tempDir destDir = do -- Data.Map.union provides a left-biased union, so mGccEnv will prevail let ghcConfigureEnv = - fromMaybe Map.empty mGccEnv `Map.union` gdiConfigureEnv downloadInfo + fromMaybe Map.empty mGccEnv `Map.union` downloadInfo.gdiConfigureEnv logSticky "Configuring GHC ..." runStep "configuring" dir ghcConfigureEnv (toFilePath $ dir relFileConfigure) ( ("--prefix=" ++ toFilePath destDir) - : map T.unpack (gdiConfigureOpts downloadInfo) + : map T.unpack downloadInfo.gdiConfigureOpts ) logSticky "Installing GHC ..." @@ -2449,11 +2450,11 @@ setup7z :: => SetupInfo -> RIO env (Path Abs Dir -> Path Abs File -> m ()) setup7z si = do - dir <- view $ configL.to configLocalPrograms + dir <- view $ configL . to (.configLocalPrograms) ensureDir dir let exeDestination = dir relFile7zexe dllDestination = dir relFile7zdll - case (siSevenzDll si, siSevenzExe si) of + case (si.siSevenzDll, si.siSevenzExe) of (Just sevenzDll, Just sevenzExe) -> do _ <- downloadOrUseLocal "7z.dll" sevenzDll dllDestination exePath <- downloadOrUseLocal "7z.exe" sevenzExe exeDestination @@ -2505,7 +2506,7 @@ chattyDownload :: -> Path Abs File -- ^ destination -> RIO env () chattyDownload label downloadInfo path = do - let url = downloadInfoUrl downloadInfo + let url = downloadInfo.downloadInfoUrl req <- parseUrlThrow $ T.unpack url logSticky $ "Preparing to download " @@ -2518,8 +2519,8 @@ chattyDownload label downloadInfo path = do <> fromString (toFilePath path) <> " ..." hashChecks <- fmap catMaybes $ forM - [ ("sha1", HashCheck SHA1, downloadInfoSha1) - , ("sha256", HashCheck SHA256, downloadInfoSha256) + [ ("sha1", HashCheck SHA1, (.downloadInfoSha1)) + , ("sha256", HashCheck SHA256, (.downloadInfoSha256)) ] $ \(name, constr, getter) -> case getter downloadInfo of @@ -2542,7 +2543,7 @@ chattyDownload label downloadInfo path = do then logStickyDone ("Downloaded " <> display label <> ".") else logStickyDone ("Already downloaded " <> display label <> ".") where - mtotalSize = downloadInfoContentLength downloadInfo + mtotalSize = downloadInfo.downloadInfoContentLength -- | Perform a basic sanity check of GHC sanityCheck :: @@ -2957,7 +2958,7 @@ downloadStackExe platforms0 archiveInfo destDir checkPath testExe = do String url <- KeyMap.lookup "browser_download_url" o Just url findMatch _ _ = Nothing - findArchive (SRIHaskellStackOrg hso) _ = pure $ hsoUrl hso + findArchive (SRIHaskellStackOrg hso) _ = pure hso.hsoUrl handleTarball :: Path Abs File -> Bool -> T.Text -> IO () handleTarball tmpFile isWindows url = do @@ -3089,4 +3090,4 @@ getDownloadVersion (SRIGitHub val) = do String rawName <- KeyMap.lookup "name" o -- drop the "v" at the beginning of the name parseVersion $ T.unpack (T.drop 1 rawName) -getDownloadVersion (SRIHaskellStackOrg hso) = Just $ hsoVersion hso +getDownloadVersion (SRIHaskellStackOrg hso) = Just hso.hsoVersion diff --git a/src/Stack/Setup/Installed.hs b/src/Stack/Setup/Installed.hs index f0374b8ebd..ed67bf115f 100644 --- a/src/Stack/Setup/Installed.hs +++ b/src/Stack/Setup/Installed.hs @@ -1,8 +1,9 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE LambdaCase #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE LambdaCase #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ViewPatterns #-} module Stack.Setup.Installed ( getCompilerVersion @@ -135,8 +136,8 @@ getCompilerVersion wc exe = extraDirs :: HasConfig env => Tool -> RIO env ExtraDirs extraDirs tool = do config <- view configL - dir <- installDir (configLocalPrograms config) tool - case (configPlatform config, toolNameString tool) of + dir <- installDir config.configLocalPrograms tool + case (config.configPlatform, toolNameString tool) of (Platform _ Cabal.Windows, isGHC -> True) -> pure mempty { edBins = [ dir relDirBin diff --git a/src/Stack/SetupCmd.hs b/src/Stack/SetupCmd.hs index 221da0636d..e4c6c26020 100644 --- a/src/Stack/SetupCmd.hs +++ b/src/Stack/SetupCmd.hs @@ -34,7 +34,7 @@ data SetupCmdOpts = SetupCmdOpts -- | Function underlying the @stack setup@ command. setupCmd :: SetupCmdOpts -> RIO Runner () setupCmd sco = withConfig YesReexec $ do - installGHC <- view $ configL . to configInstallGHC + installGHC <- view $ configL . to (.configInstallGHC) if installGHC then withBuildConfig $ do @@ -43,7 +43,7 @@ setupCmd sco = withConfig YesReexec $ do Just v -> pure (v, MatchMinor, Nothing) Nothing -> (,,) <$> view wantedCompilerVersionL - <*> view (configL . to configCompilerCheck) + <*> view (configL . to (.configCompilerCheck)) <*> (Just <$> view stackYamlL) setup sco wantedCompiler compilerCheck mstack else @@ -64,7 +64,7 @@ setup :: -> RIO env () setup sco wantedCompiler compilerCheck mstack = do config <- view configL - sandboxedGhc <- cpSandboxed . fst <$> ensureCompilerAndMsys SetupOpts + sandboxedGhc <- (.cpSandboxed) . fst <$> ensureCompilerAndMsys SetupOpts { soptsInstallIfMissing = True , soptsUseSystem = config.configSystemGHC && not sco.scoForceReinstall , soptsWantedCompiler = wantedCompiler diff --git a/src/Stack/SourceMap.hs b/src/Stack/SourceMap.hs index 030b1ecaf5..6100e6909c 100644 --- a/src/Stack/SourceMap.hs +++ b/src/Stack/SourceMap.hs @@ -1,3 +1,4 @@ +{-# LANGUAGE NoImplicitPrelude #-} {-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} @@ -135,7 +136,7 @@ snapToDepPackage buildHaddocks name sp = do loadVersion :: MonadIO m => CommonPackage -> m Version loadVersion common = do - gpd <- liftIO $ cpGPD common + gpd <- liftIO common.cpGPD pure (pkgVersion $ PD.package $ PD.packageDescription gpd) getPLIVersion :: PackageLocationImmutable -> Version @@ -149,9 +150,9 @@ globalsFromDump :: -> RIO env (Map PackageName DumpedGlobalPackage) globalsFromDump pkgexe = do let pkgConduit = conduitDumpPackage - .| CL.foldMap (\dp -> Map.singleton (dpGhcPkgId dp) dp) + .| CL.foldMap (\dp -> Map.singleton dp.dpGhcPkgId dp) toGlobals ds = - Map.fromList $ map (pkgName . dpPackageIdent &&& id) $ Map.elems ds + Map.fromList $ map (pkgName . (.dpPackageIdent) &&& id) $ Map.elems ds toGlobals <$> ghcPkgDump pkgexe [] pkgConduit globalsFromHints :: @@ -177,12 +178,12 @@ actualFromGhc :: -> ActualCompiler -> RIO env (SMActual DumpedGlobalPackage) actualFromGhc smw ac = do - globals <- view $ compilerPathsL . to cpGlobalDump + globals <- view $ compilerPathsL . to (.cpGlobalDump) pure SMActual { smaCompiler = ac - , smaProject = smwProject smw - , smaDeps = smwDeps smw + , smaProject = smw.smwProject + , smaDeps = smw.smwDeps , smaGlobal = globals } @@ -196,8 +197,8 @@ actualFromHints smw ac = do pure SMActual { smaCompiler = ac - , smaProject = smwProject smw - , smaDeps = smwDeps smw + , smaProject = smw.smwProject + , smaDeps = smw.smwDeps , smaGlobal = Map.map GlobalPackageVersion globals } @@ -235,15 +236,15 @@ getUnusedPackageFlags :: -> Map PackageName DepPackage -> m (Maybe UnusedFlags) getUnusedPackageFlags (name, userFlags) source prj deps = - let maybeCommon = fmap ppCommon (Map.lookup name prj) - <|> fmap dpCommon (Map.lookup name deps) + let maybeCommon = fmap (.ppCommon) (Map.lookup name prj) + <|> fmap (.dpCommon) (Map.lookup name deps) in case maybeCommon of -- Package is not available as project or dependency Nothing -> pure $ Just $ UFNoPackage source name -- Package exists, let's check if the flags are defined Just common -> do - gpd <- liftIO $ cpGPD common + gpd <- liftIO common.cpGPD let pname = pkgName $ PD.package $ PD.packageDescription gpd pkgFlags = Set.fromList $ map PD.flagName $ PD.genPackageFlags gpd unused = Map.keysSet $ Map.withoutKeys userFlags pkgFlags @@ -259,13 +260,13 @@ pruneGlobals :: -> Map PackageName GlobalPackage pruneGlobals globals deps = let (prunedGlobals, keptGlobals) = - partitionReplacedDependencies globals (pkgName . dpPackageIdent) - dpGhcPkgId dpDepends deps - in Map.map (GlobalPackage . pkgVersion . dpPackageIdent) keptGlobals <> + partitionReplacedDependencies globals (pkgName . (.dpPackageIdent)) + (.dpGhcPkgId) (.dpDepends) deps + in Map.map (GlobalPackage . pkgVersion . (.dpPackageIdent)) keptGlobals <> Map.map ReplacedGlobalPackage prunedGlobals getCompilerInfo :: (HasConfig env, HasCompiler env) => RIO env Builder -getCompilerInfo = view $ compilerPathsL . to (byteString . cpGhcInfo) +getCompilerInfo = view $ compilerPathsL . to (byteString . (.cpGhcInfo)) immutableLocSha :: PackageLocationImmutable -> Builder immutableLocSha = byteString . treeKeyToBs . locationTreeKey @@ -296,7 +297,7 @@ loadProjectSnapshotCandidate loc printWarnings buildHaddocks = do pure $ \projectPackages -> do prjPkgs <- fmap Map.fromList . for projectPackages $ \resolved -> do pp <- mkProjectPackage printWarnings resolved buildHaddocks - pure (cpName $ ppCommon pp, pp) + pure (pp.ppCommon.cpName, pp) compiler <- either throwIO pure $ wantedToActual $ snapshotCompiler snapshot pure SMActual diff --git a/src/Stack/Storage/Project.hs b/src/Stack/Storage/Project.hs index d40a1b7c92..411746fd9a 100644 --- a/src/Stack/Storage/Project.hs +++ b/src/Stack/Storage/Project.hs @@ -98,7 +98,7 @@ withProjectStorage :: => ReaderT SqlBackend (RIO env) a -> RIO env a withProjectStorage inner = do - storage <- view (buildConfigL . to bcProjectStorage . to unProjectStorage) + storage <- view (buildConfigL . to (.bcProjectStorage.unProjectStorage)) withStorage_ storage inner -- | Key used to retrieve configuration or flag cache @@ -116,12 +116,12 @@ readConfigCache :: readConfigCache (Entity parentId configCacheParent) = do let configCachePkgSrc = configCacheParent.configCacheParentPkgSrc coDirs <- - map (configCacheDirOptionValue . entityVal) <$> + map ((.configCacheDirOptionValue) . entityVal) <$> selectList [ConfigCacheDirOptionParent ==. parentId] [Asc ConfigCacheDirOptionIndex] coNoDirs <- - map (configCacheNoDirOptionValue . entityVal) <$> + map ((.configCacheNoDirOptionValue) . entityVal) <$> selectList [ConfigCacheNoDirOptionParent ==. parentId] [Asc ConfigCacheNoDirOptionIndex] @@ -130,10 +130,10 @@ readConfigCache (Entity parentId configCacheParent) = do , coNoDirs } configCacheDeps <- - Set.fromList . map (configCacheDepValue . entityVal) <$> + Set.fromList . map ((.configCacheDepValue) . entityVal) <$> selectList [ConfigCacheDepParent ==. parentId] [] configCacheComponents <- - Set.fromList . map (configCacheComponentValue . entityVal) <$> + Set.fromList . map ((.configCacheComponentValue) . entityVal) <$> selectList [ConfigCacheComponentParent ==. parentId] [] let configCachePathEnvVar = configCacheParent.configCacheParentPathEnvVar let configCacheHaddock = configCacheParent.configCacheParentHaddock @@ -178,18 +178,18 @@ saveConfigCache key@(UniqueConfigCacheParent dir type_) new = ConfigCacheParent { configCacheParentDirectory = dir , configCacheParentType = type_ - , configCacheParentPkgSrc = configCachePkgSrc new + , configCacheParentPkgSrc = new.configCachePkgSrc , configCacheParentActive = True - , configCacheParentPathEnvVar = configCachePathEnvVar new - , configCacheParentHaddock = configCacheHaddock new + , configCacheParentPathEnvVar = new.configCachePathEnvVar + , configCacheParentHaddock = new.configCacheHaddock } Just parentEntity@(Entity parentId _) -> do old <- readConfigCache parentEntity update parentId - [ ConfigCacheParentPkgSrc =. configCachePkgSrc new + [ ConfigCacheParentPkgSrc =. new.configCachePkgSrc , ConfigCacheParentActive =. True - , ConfigCacheParentPathEnvVar =. configCachePathEnvVar new + , ConfigCacheParentPathEnvVar =. new.configCachePathEnvVar ] pure (parentId, Just old) updateList @@ -197,29 +197,29 @@ saveConfigCache key@(UniqueConfigCacheParent dir type_) new = ConfigCacheDirOptionParent parentId ConfigCacheDirOptionIndex - (maybe [] (coDirs . configCacheOpts) mold) - (coDirs $ configCacheOpts new) + (maybe [] (.configCacheOpts.coDirs) mold) + new.configCacheOpts.coDirs updateList ConfigCacheNoDirOption ConfigCacheNoDirOptionParent parentId ConfigCacheNoDirOptionIndex - (maybe [] (coNoDirs . configCacheOpts) mold) - (coNoDirs $ configCacheOpts new) + (maybe [] (.configCacheOpts.coNoDirs) mold) + new.configCacheOpts.coNoDirs updateSet ConfigCacheDep ConfigCacheDepParent parentId ConfigCacheDepValue - (maybe Set.empty configCacheDeps mold) - (configCacheDeps new) + (maybe Set.empty (.configCacheDeps) mold) + new.configCacheDeps updateSet ConfigCacheComponent ConfigCacheComponentParent parentId ConfigCacheComponentValue - (maybe Set.empty configCacheComponents mold) - (configCacheComponents new) + (maybe Set.empty (.configCacheComponents) mold) + new.configCacheComponents -- | Mark 'ConfigCache' as inactive in the database. -- We use a flag instead of deleting the records since, in most cases, the same diff --git a/src/Stack/Storage/User.hs b/src/Stack/Storage/User.hs index 95080fe966..e2306115e5 100644 --- a/src/Stack/Storage/User.hs +++ b/src/Stack/Storage/User.hs @@ -167,7 +167,7 @@ withUserStorage :: => ReaderT SqlBackend (RIO env) a -> RIO env a withUserStorage inner = do - storage <- view (configL . to configUserStorage . to unUserStorage) + storage <- view (configL . to (.configUserStorage.unUserStorage)) withStorage_ storage inner -- | Key used to retrieve the precompiled cache @@ -200,10 +200,10 @@ readPrecompiledCache key = do pcLibrary <- mapM parseRelFile precompiledCacheParent.precompiledCacheParentLibrary pcSubLibs <- - mapM (parseRelFile . precompiledCacheSubLibValue . entityVal) =<< + mapM (parseRelFile . (.precompiledCacheSubLibValue) . entityVal) =<< selectList [PrecompiledCacheSubLibParent ==. parentId] [] pcExes <- - mapM (parseRelFile . precompiledCacheExeValue . entityVal) =<< + mapM (parseRelFile . (.precompiledCacheExeValue) . entityVal) =<< selectList [PrecompiledCacheExeParent ==. parentId] [] pure ( parentId @@ -239,7 +239,7 @@ savePrecompiledCache ) new = withUserStorage $ do - let precompiledCacheParentLibrary = fmap toFilePath (pcLibrary new) + let precompiledCacheParentLibrary = fmap toFilePath new.pcLibrary mIdOld <- readPrecompiledCache key (parentId, mold) <- case mIdOld of @@ -264,15 +264,15 @@ savePrecompiledCache PrecompiledCacheSubLibParent parentId PrecompiledCacheSubLibValue - (maybe Set.empty (toFilePathSet . pcSubLibs) mold) - (toFilePathSet $ pcSubLibs new) + (maybe Set.empty (toFilePathSet . (.pcSubLibs)) mold) + (toFilePathSet new.pcSubLibs) updateSet PrecompiledCacheExe PrecompiledCacheExeParent parentId PrecompiledCacheExeValue - (maybe Set.empty (toFilePathSet . pcExes) mold) - (toFilePathSet $ pcExes new) + (maybe Set.empty (toFilePathSet . (.pcExes)) mold) + (toFilePathSet new.pcExes) where toFilePathSet = Set.fromList . map toFilePath @@ -284,7 +284,7 @@ loadDockerImageExeCache :: -> UTCTime -> RIO env (Maybe Bool) loadDockerImageExeCache imageId exePath exeTimestamp = withUserStorage $ - fmap (dockerImageExeCacheCompatible . entityVal) <$> + fmap ((.dockerImageExeCacheCompatible) . entityVal) <$> getBy (DockerImageExeCacheUnique imageId (toFilePath exePath) exeTimestamp) -- | Sets the record of whether an executable is compatible with a Docker image diff --git a/src/Stack/Types/Build.hs b/src/Stack/Types/Build.hs index 165310e819..f743d90d76 100644 --- a/src/Stack/Types/Build.hs +++ b/src/Stack/Types/Build.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Build-specific types. @@ -122,7 +123,7 @@ instance PersistFieldSql CachePkgSrc where toCachePkgSrc :: PackageSource -> CachePkgSrc toCachePkgSrc (PSFilePath lp) = - CacheSrcLocal (toFilePath (parent (lpCabalFile lp))) + CacheSrcLocal (toFilePath (parent lp.lpCabalFile)) toCachePkgSrc PSRemote{} = CacheSrcUpstream -- | A type representing tasks to perform when building. @@ -174,18 +175,18 @@ data TaskType -- | Were any of the dependencies missing? taskAnyMissing :: Task -> Bool -taskAnyMissing task = not $ Set.null $ tcoMissing $ taskConfigOpts task +taskAnyMissing task = not $ Set.null task.taskConfigOpts.tcoMissing -- | A function to yield the package name and version of a given 'TaskType' -- value. taskTypePackageIdentifier :: TaskType -> PackageIdentifier -taskTypePackageIdentifier (TTLocalMutable lp) = packageIdentifier $ lpPackage lp +taskTypePackageIdentifier (TTLocalMutable lp) = packageIdentifier lp.lpPackage taskTypePackageIdentifier (TTRemotePackage _ p _) = packageIdentifier p taskIsTarget :: Task -> Bool taskIsTarget t = - case taskType t of - TTLocalMutable lp -> lpWanted lp + case t.taskType of + TTLocalMutable lp -> lp.lpWanted _ -> False -- | A function to yield the relevant database (write-only or mutable) of a @@ -198,16 +199,16 @@ taskTypeLocation (TTRemotePackage Immutable _ _) = Snap -- | A function to yield the relevant database (write-only or mutable) of the -- given task. taskLocation :: Task -> InstallLocation -taskLocation = taskTypeLocation . taskType +taskLocation = taskTypeLocation . (.taskType) -- | A function to yield the package name and version to be built by the given -- task. taskProvides :: Task -> PackageIdentifier -taskProvides = taskTypePackageIdentifier . taskType +taskProvides = taskTypePackageIdentifier . (.taskType) taskTargetIsMutable :: Task -> IsMutable taskTargetIsMutable task = - case taskType task of + case task.taskType of TTLocalMutable _ -> Mutable TTRemotePackage mutable _ _ -> mutable diff --git a/src/Stack/Types/Build/ConstructPlan.hs b/src/Stack/Types/Build/ConstructPlan.hs index 824e716b97..c80545223d 100644 --- a/src/Stack/Types/Build/ConstructPlan.hs +++ b/src/Stack/Types/Build/ConstructPlan.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} -- | A module providing types and related helper functions used in module -- "Stack.Build.ConstructPlan". @@ -126,14 +127,14 @@ adrVersion (ADRToInstall task) = pkgVersion $ taskProvides task adrVersion (ADRFound _ installed) = installedVersion installed adrHasLibrary :: AddDepRes -> Bool -adrHasLibrary (ADRToInstall task) = case taskType task of - TTLocalMutable lp -> packageHasLibrary $ lpPackage lp +adrHasLibrary (ADRToInstall task) = case task.taskType of + TTLocalMutable lp -> packageHasLibrary lp.lpPackage TTRemotePackage _ p _ -> packageHasLibrary p where -- make sure we consider sub-libraries as libraries too packageHasLibrary :: Package -> Bool packageHasLibrary p = - hasBuildableMainLibrary p || not (null (packageSubLibraries p)) + hasBuildableMainLibrary p || not (null p.packageSubLibraries) adrHasLibrary (ADRFound _ Library{}) = True adrHasLibrary (ADRFound _ Executable{}) = False @@ -165,51 +166,51 @@ data Ctx = Ctx } instance HasPlatform Ctx where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasGHCVariant Ctx where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasLogFunc Ctx where - logFuncL = configL.logFuncL + logFuncL = configL . logFuncL instance HasRunner Ctx where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasStylesUpdate Ctx where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm Ctx where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL instance HasConfig Ctx where - configL = buildConfigL.lens bcConfig (\x y -> x { bcConfig = y }) + configL = buildConfigL . lens (.bcConfig) (\x y -> x { bcConfig = y }) {-# INLINE configL #-} instance HasPantryConfig Ctx where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasProcessContext Ctx where - processContextL = configL.processContextL + processContextL = configL . processContextL instance HasBuildConfig Ctx where - buildConfigL = envConfigL.lens - envConfigBuildConfig + buildConfigL = envConfigL . lens + (.envConfigBuildConfig) (\x y -> x { envConfigBuildConfig = y }) instance HasSourceMap Ctx where - sourceMapL = envConfigL.sourceMapL + sourceMapL = envConfigL . sourceMapL instance HasCompiler Ctx where - compilerPathsL = envConfigL.compilerPathsL + compilerPathsL = envConfigL . compilerPathsL instance HasEnvConfig Ctx where - envConfigL = lens ctxEnvConfig (\x y -> x { ctxEnvConfig = y }) + envConfigL = lens (.ctxEnvConfig) (\x y -> x { ctxEnvConfig = y }) -- | State to be maintained during the calculation of local packages -- to unregister. diff --git a/src/Stack/Types/Build/Exception.hs b/src/Stack/Types/Build/Exception.hs index 946d2f33d3..b370659d3f 100644 --- a/src/Stack/Types/Build/Exception.hs +++ b/src/Stack/Types/Build/Exception.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Types.Build.Exception ( BuildException (..) @@ -598,7 +599,7 @@ pprintExceptions exceptions stackYaml stackRoot isImplicitGlobal parentMap wante acc0 = (True, False, Map.empty, Set.empty) go acc (DependencyPlanFailures pkg m) = Map.foldrWithKey go' acc m where - pkgName = packageName pkg + pkgName = pkg.packageName go' name (_, Just extra, NotInBuildPlan) (_, _, m', s) = (False, True, Map.insert name extra m', s) go' _ (_, _, NotInBuildPlan) (_, _, m', s) = (False, True, m', s) @@ -621,14 +622,14 @@ pprintExceptions exceptions stackYaml stackRoot isImplicitGlobal parentMap wante depErrors -> Just $ fillSep [ flow "In the dependencies for" - , pkgIdent <> pprintFlags (packageFlags pkg) <> ":" + , pkgIdent <> pprintFlags pkg.packageFlags <> ":" ] <> line <> indent 2 (bulletedList depErrors) <> line <> fillSep ( flow "The above is/are needed" - : case getShortestDepsPath parentMap wanted' (packageName pkg) of + : case getShortestDepsPath parentMap wanted' pkg.packageName of Nothing -> [flow "for unknown reason - Stack invariant violated."] Just [] -> @@ -647,7 +648,7 @@ pprintExceptions exceptions stackYaml stackRoot isImplicitGlobal parentMap wante <> [pkgIdent] ) where - pkgName' = style Current . fromPackageName $ packageName pkg + pkgName' = style Current (fromPackageName pkg.packageName) pkgIdent = style Current (fromPackageId $ packageIdentifier pkg) -- Skip these when they are redundant with 'NotInBuildPlan' info. pprintException (UnknownPackage name) @@ -910,8 +911,8 @@ startDepsPath ident = DepsPath extendDepsPath :: PackageIdentifier -> DepsPath -> DepsPath extendDepsPath ident dp = DepsPath - { dpLength = dpLength dp + 1 - , dpNameLength = dpNameLength dp + length (packageNameString (pkgName ident)) + { dpLength = dp.dpLength + 1 + , dpNameLength = dp.dpNameLength + length (packageNameString (pkgName ident)) , dpPath = [ident] } diff --git a/src/Stack/Types/BuildConfig.hs b/src/Stack/Types/BuildConfig.hs index ccc8504dac..99d95802fc 100644 --- a/src/Stack/Types/BuildConfig.hs +++ b/src/Stack/Types/BuildConfig.hs @@ -1,7 +1,8 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE TypeFamilies #-} module Stack.Types.BuildConfig ( BuildConfig (..) @@ -45,36 +46,36 @@ data BuildConfig = BuildConfig } instance HasPlatform BuildConfig where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasGHCVariant BuildConfig where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasProcessContext BuildConfig where - processContextL = configL.processContextL + processContextL = configL . processContextL instance HasPantryConfig BuildConfig where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasConfig BuildConfig where - configL = lens bcConfig (\x y -> x { bcConfig = y }) + configL = lens (.bcConfig) (\x y -> x { bcConfig = y }) instance HasRunner BuildConfig where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasLogFunc BuildConfig where - logFuncL = runnerL.logFuncL + logFuncL = runnerL . logFuncL instance HasStylesUpdate BuildConfig where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm BuildConfig where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL class HasConfig env => HasBuildConfig env where buildConfigL :: Lens' env BuildConfig @@ -84,11 +85,11 @@ instance HasBuildConfig BuildConfig where {-# INLINE buildConfigL #-} stackYamlL :: HasBuildConfig env => Lens' env (Path Abs File) -stackYamlL = buildConfigL.lens bcStackYaml (\x y -> x { bcStackYaml = y }) +stackYamlL = buildConfigL . lens (.bcStackYaml) (\x y -> x { bcStackYaml = y }) -- | Directory containing the project's stack.yaml file projectRootL :: HasBuildConfig env => Getting r env (Path Abs Dir) -projectRootL = stackYamlL.to parent +projectRootL = stackYamlL . to parent -- | Per-project work dir getProjectWorkDir :: (HasBuildConfig env, MonadReader env m) => m (Path Abs Dir) @@ -100,4 +101,4 @@ getProjectWorkDir = do -- | The compiler specified by the @SnapshotDef@. This may be different from the -- actual compiler used! wantedCompilerVersionL :: HasBuildConfig s => Getting r s WantedCompiler -wantedCompilerVersionL = buildConfigL.to (smwCompiler . bcSMWanted) +wantedCompilerVersionL = buildConfigL . to (.bcSMWanted.smwCompiler) diff --git a/src/Stack/Types/BuildOpts.hs b/src/Stack/Types/BuildOpts.hs index 2f02fe1332..2ce3cd08a5 100644 --- a/src/Stack/Types/BuildOpts.hs +++ b/src/Stack/Types/BuildOpts.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Configuration options for building. module Stack.Types.BuildOpts @@ -112,36 +113,42 @@ data BuildOpts = BuildOpts defaultBuildOpts :: BuildOpts defaultBuildOpts = BuildOpts - { boptsLibProfile = defaultFirstFalse buildMonoidLibProfile - , boptsExeProfile = defaultFirstFalse buildMonoidExeProfile - , boptsLibStrip = defaultFirstTrue buildMonoidLibStrip - , boptsExeStrip = defaultFirstTrue buildMonoidExeStrip + { boptsLibProfile = defaultFirstFalse buildMonoid.buildMonoidLibProfile + , boptsExeProfile = defaultFirstFalse buildMonoid.buildMonoidExeProfile + , boptsLibStrip = defaultFirstTrue buildMonoid.buildMonoidLibStrip + , boptsExeStrip = defaultFirstTrue buildMonoid.buildMonoidExeStrip , boptsHaddock = False , boptsHaddockOpts = defaultHaddockOpts - , boptsOpenHaddocks = defaultFirstFalse buildMonoidOpenHaddocks + , boptsOpenHaddocks = defaultFirstFalse buildMonoid.buildMonoidOpenHaddocks , boptsHaddockDeps = Nothing - , boptsHaddockInternal = defaultFirstFalse buildMonoidHaddockInternal + , boptsHaddockInternal = + defaultFirstFalse buildMonoid.buildMonoidHaddockInternal , boptsHaddockHyperlinkSource = - defaultFirstTrue buildMonoidHaddockHyperlinkSource - , boptsHaddockForHackage = defaultFirstFalse buildMonoidHaddockForHackage - , boptsInstallExes = defaultFirstFalse buildMonoidInstallExes - , boptsInstallCompilerTool = defaultFirstFalse buildMonoidInstallCompilerTool - , boptsPreFetch = defaultFirstFalse buildMonoidPreFetch + defaultFirstTrue buildMonoid.buildMonoidHaddockHyperlinkSource + , boptsHaddockForHackage = + defaultFirstFalse buildMonoid.buildMonoidHaddockForHackage + , boptsInstallExes = defaultFirstFalse buildMonoid.buildMonoidInstallExes + , boptsInstallCompilerTool = + defaultFirstFalse buildMonoid.buildMonoidInstallCompilerTool + , boptsPreFetch = defaultFirstFalse buildMonoid.buildMonoidPreFetch , boptsKeepGoing = Nothing - , boptsKeepTmpFiles = defaultFirstFalse buildMonoidKeepTmpFiles - , boptsForceDirty = defaultFirstFalse buildMonoidForceDirty - , boptsTests = defaultFirstFalse buildMonoidTests + , boptsKeepTmpFiles = defaultFirstFalse buildMonoid.buildMonoidKeepTmpFiles + , boptsForceDirty = defaultFirstFalse buildMonoid.buildMonoidForceDirty + , boptsTests = defaultFirstFalse buildMonoid.buildMonoidTests , boptsTestOpts = defaultTestOpts - , boptsBenchmarks = defaultFirstFalse buildMonoidBenchmarks + , boptsBenchmarks = defaultFirstFalse buildMonoid.buildMonoidBenchmarks , boptsBenchmarkOpts = defaultBenchmarkOpts - , boptsReconfigure = defaultFirstFalse buildMonoidReconfigure + , boptsReconfigure = defaultFirstFalse buildMonoid.buildMonoidReconfigure , boptsCabalVerbose = CabalVerbosity normal - , boptsSplitObjs = defaultFirstFalse buildMonoidSplitObjs + , boptsSplitObjs = defaultFirstFalse buildMonoid.buildMonoidSplitObjs , boptsSkipComponents = [] - , boptsInterleavedOutput = defaultFirstTrue buildMonoidInterleavedOutput + , boptsInterleavedOutput = + defaultFirstTrue buildMonoid.buildMonoidInterleavedOutput , boptsProgressBar = CappedBar , boptsDdumpDir = Nothing } + where + buildMonoid = undefined :: BuildOptsMonoid defaultBuildOptsCLI ::BuildOptsCLI defaultBuildOptsCLI = BuildOptsCLI @@ -173,7 +180,7 @@ boptsCLIFlagsByName = Map.fromList . mapMaybe go . Map.toList . - boptsCLIFlags + (.boptsCLIFlags) where go (ACFAllProjectPackages, _) = Nothing go (ACFByName name, flags) = Just (name, flags) @@ -198,7 +205,7 @@ data BuildOptsCLI = BuildOptsCLI -- | Generate a list of --PROG-option="" arguments for all PROGs. boptsCLIAllProgOptions :: BuildOptsCLI -> [Text] boptsCLIAllProgOptions boptsCLI = - concatMap progOptionArgs (boptsCLIProgsOptions boptsCLI) + concatMap progOptionArgs boptsCLI.boptsCLIProgsOptions where -- Generate a list of --PROG-option="" arguments for a PROG. progOptionArgs :: (Text, [Text]) -> [Text] @@ -462,13 +469,15 @@ data TestOpts = TestOpts defaultTestOpts :: TestOpts defaultTestOpts = TestOpts - { toRerunTests = defaultFirstTrue toMonoidRerunTests + { toRerunTests = defaultFirstTrue toMonoid.toMonoidRerunTests , toAdditionalArgs = [] - , toCoverage = defaultFirstFalse toMonoidCoverage - , toDisableRun = defaultFirstFalse toMonoidDisableRun + , toCoverage = defaultFirstFalse toMonoid.toMonoidCoverage + , toDisableRun = defaultFirstFalse toMonoid.toMonoidDisableRun , toMaximumTimeSeconds = Nothing - , toAllowStdin = defaultFirstTrue toMonoidAllowStdin + , toAllowStdin = defaultFirstTrue toMonoid.toMonoidAllowStdin } + where + toMonoid = undefined :: TestOptsMonoid data TestOptsMonoid = TestOptsMonoid { toMonoidRerunTests :: !FirstTrue @@ -606,7 +615,7 @@ newtype CabalVerbosity deriving (Eq, Show) toFirstCabalVerbosity :: FirstFalse -> First CabalVerbosity -toFirstCabalVerbosity vf = First $ getFirstFalse vf <&> \p -> +toFirstCabalVerbosity vf = First $ vf.getFirstFalse <&> \p -> if p then verboseLevel else normalLevel where verboseLevel = CabalVerbosity verbose @@ -624,32 +633,32 @@ instance Parsec CabalVerbosity where buildOptsMonoidHaddockL :: Lens' BuildOptsMonoid (Maybe Bool) buildOptsMonoidHaddockL = - lens (getFirstFalse . buildMonoidHaddock) + lens (.buildMonoidHaddock.getFirstFalse) (\buildMonoid t -> buildMonoid {buildMonoidHaddock = FirstFalse t}) buildOptsMonoidTestsL :: Lens' BuildOptsMonoid (Maybe Bool) buildOptsMonoidTestsL = - lens (getFirstFalse . buildMonoidTests) + lens (.buildMonoidTests.getFirstFalse) (\buildMonoid t -> buildMonoid {buildMonoidTests = FirstFalse t}) buildOptsMonoidBenchmarksL :: Lens' BuildOptsMonoid (Maybe Bool) buildOptsMonoidBenchmarksL = - lens (getFirstFalse . buildMonoidBenchmarks) + lens (.buildMonoidBenchmarks.getFirstFalse) (\buildMonoid t -> buildMonoid {buildMonoidBenchmarks = FirstFalse t}) buildOptsMonoidInstallExesL :: Lens' BuildOptsMonoid (Maybe Bool) buildOptsMonoidInstallExesL = - lens (getFirstFalse . buildMonoidInstallExes) + lens (.buildMonoidInstallExes.getFirstFalse) (\buildMonoid t -> buildMonoid {buildMonoidInstallExes = FirstFalse t}) buildOptsInstallExesL :: Lens' BuildOpts Bool buildOptsInstallExesL = - lens boptsInstallExes + lens (.boptsInstallExes) (\bopts t -> bopts {boptsInstallExes = t}) buildOptsHaddockL :: Lens' BuildOpts Bool buildOptsHaddockL = - lens boptsHaddock + lens (.boptsHaddock) (\bopts t -> bopts {boptsHaddock = t}) -- Type representing formats of Stack's progress bar when building. diff --git a/src/Stack/Types/CompCollection.hs b/src/Stack/Types/CompCollection.hs index 32e1eb1136..c9f7a0a19c 100644 --- a/src/Stack/Types/CompCollection.hs +++ b/src/Stack/Types/CompCollection.hs @@ -51,8 +51,8 @@ data CompCollection component = CompCollection instance Semigroup (CompCollection component) where a <> b = CompCollection - { buildableOnes = buildableOnes a <> buildableOnes b - , unbuildableOnes = unbuildableOnes a <> unbuildableOnes b + { buildableOnes = a.buildableOnes <> b.buildableOnes + , unbuildableOnes = a.unbuildableOnes <> b.unbuildableOnes } instance Monoid (CompCollection component) where @@ -62,9 +62,9 @@ instance Monoid (CompCollection component) where } instance Foldable CompCollection where - foldMap fn collection = foldMap fn (asNameMap $ buildableOnes collection) - foldr' fn c collection = HM.foldr' fn c (asNameMap $ buildableOnes collection) - null = HM.null . asNameMap . buildableOnes + foldMap fn collection = foldMap fn collection.buildableOnes.asNameMap + foldr' fn c collection = HM.foldr' fn c collection.buildableOnes.asNameMap + null = HM.null . (.buildableOnes.asNameMap) -- | A type representing a collection of components, including a cache of -- the components' names. @@ -80,8 +80,8 @@ data InnerCollection component = InnerCollection instance Semigroup (InnerCollection component) where a <> b = InnerCollection - { asNameMap = asNameMap a <> asNameMap b - , asNameSet = asNameSet a <> asNameSet b + { asNameMap = a.asNameMap <> b.asNameMap + , asNameSet = a.asNameSet <> b.asNameSet } instance Monoid (InnerCollection component) where @@ -102,8 +102,8 @@ addComponent :: addComponent componentV collection = let nameV = componentV.name in collection - { asNameMap=HM.insert nameV componentV (asNameMap collection) - , asNameSet=Set.insert nameV (asNameSet collection) + { asNameMap=HM.insert nameV componentV collection.asNameMap + , asNameSet=Set.insert nameV collection.asNameSet } -- | For the given function and foldable data structure of components of type @@ -123,27 +123,27 @@ foldAndMakeCollection mapFn = foldl' compIterator mempty compCreator existingCollection component | component.buildInfo.sbiBuildable = existingCollection { buildableOnes = - addComponent component (buildableOnes existingCollection) + addComponent component existingCollection.buildableOnes } | otherwise = existingCollection { unbuildableOnes = - Set.insert component.name (unbuildableOnes existingCollection) + Set.insert component.name existingCollection.unbuildableOnes } -- | Get the names of the buildable components in the given collection, as a -- 'Set' of 'StackUnqualCompName'. getBuildableSet :: CompCollection component -> Set StackUnqualCompName -getBuildableSet = asNameSet . buildableOnes +getBuildableSet = (.buildableOnes.asNameSet) -- | Get the names of the buildable components in the given collection, as a -- 'Set' of 'Text'. getBuildableSetText :: CompCollection component -> Set Text -getBuildableSetText = Set.mapMonotonic unqualCompToText . getBuildableSet +getBuildableSetText = Set.mapMonotonic (.unqualCompToText) . getBuildableSet -- | Get the names of the buildable components in the given collection, as a -- list of 'Text. getBuildableListText :: CompCollection component -> [Text] -getBuildableListText = getBuildableListAs unqualCompToText +getBuildableListText = getBuildableListAs (.unqualCompToText) -- | Apply the given function to the names of the buildable components in the -- given collection, yielding a list. @@ -170,14 +170,14 @@ collectionLookup :: -- ^ Collection of components. -> Maybe component collectionLookup needle haystack = - HM.lookup (StackUnqualCompName needle) (asNameMap $ buildableOnes haystack) + HM.lookup (StackUnqualCompName needle) haystack.buildableOnes.asNameMap -- | For a given collection of components, yields a list of pairs for buildable -- components of the name of the component and the component. collectionKeyValueList :: CompCollection component -> [(Text, component)] collectionKeyValueList haystack = (\(StackUnqualCompName k, !v) -> (k, v)) - <$> HM.toList (asNameMap $ buildableOnes haystack) + <$> HM.toList haystack.buildableOnes.asNameMap -- | Yields 'True' if, and only if, the given collection of components includes -- a buildable component with the given name. @@ -202,4 +202,4 @@ foldComponentToAnotherCollection :: -- ^ Starting value. -> m a foldComponentToAnotherCollection collection fn initialValue = - HM.foldr' fn initialValue (asNameMap $ buildableOnes collection) + HM.foldr' fn initialValue collection.buildableOnes.asNameMap diff --git a/src/Stack/Types/CompilerPaths.hs b/src/Stack/Types/CompilerPaths.hs index 2ed615790f..5cc45c2e34 100644 --- a/src/Stack/Types/CompilerPaths.hs +++ b/src/Stack/Types/CompilerPaths.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.CompilerPaths ( CompilerPaths (..) @@ -61,20 +62,20 @@ newtype GhcPkgExe deriving Show cabalVersionL :: HasCompiler env => SimpleGetter env Version -cabalVersionL = compilerPathsL.to cpCabalVersion +cabalVersionL = compilerPathsL . to (.cpCabalVersion) compilerVersionL :: HasCompiler env => SimpleGetter env ActualCompiler -compilerVersionL = compilerPathsL.to cpCompilerVersion +compilerVersionL = compilerPathsL . to (.cpCompilerVersion) cpWhich :: (MonadReader env m, HasCompiler env) => m WhichCompiler -cpWhich = view $ compilerPathsL.to (whichCompiler.cpCompilerVersion) +cpWhich = view $ compilerPathsL . to (whichCompiler . (.cpCompilerVersion)) -- | Get the path for the given compiler ignoring any local binaries. -- -- https://github.com/commercialhaskell/stack/issues/1052 getCompilerPath :: HasCompiler env => RIO env (Path Abs File) -getCompilerPath = view $ compilerPathsL.to cpCompiler +getCompilerPath = view $ compilerPathsL . to (.cpCompiler) -- | Get the 'GhcPkgExe' from a 'HasCompiler' environment getGhcPkgExe :: HasCompiler env => RIO env GhcPkgExe -getGhcPkgExe = view $ compilerPathsL.to cpPkg +getGhcPkgExe = view $ compilerPathsL . to (.cpPkg) diff --git a/src/Stack/Types/Component.hs b/src/Stack/Types/Component.hs index 8503059464..cca9c94e60 100644 --- a/src/Stack/Types/Component.hs +++ b/src/Stack/Types/Component.hs @@ -168,19 +168,19 @@ instance HasField "qualifiedName" StackLibrary NamedComponent where | rawName == mempty = CLib | otherwise = CSubLib rawName where - rawName = unqualCompToText v.name + rawName = v.name.unqualCompToText instance HasField "qualifiedName" StackForeignLibrary NamedComponent where - getField = CFlib . unqualCompToText . (.name) + getField = CFlib . (.name.unqualCompToText) instance HasField "qualifiedName" StackExecutable NamedComponent where - getField = CExe . unqualCompToText . (.name) + getField = CExe . (.name.unqualCompToText) instance HasField "qualifiedName" StackTestSuite NamedComponent where - getField = CTest . unqualCompToText . (.name) + getField = CTest . (.name.unqualCompToText) instance HasField "qualifiedName" StackBenchmark NamedComponent where - getField = CTest . unqualCompToText . (.name) + getField = CTest . (.name.unqualCompToText) -- | Type synonym for a 'HasField' constraint which represent a virtual field, -- computed from the type, the NamedComponent constructor and the name. diff --git a/src/Stack/Types/Config.hs b/src/Stack/Types/Config.hs index 8c24e80bec..b6649436bc 100644 --- a/src/Stack/Types/Config.hs +++ b/src/Stack/Types/Config.hs @@ -1,12 +1,13 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE DefaultSignatures #-} -{-# LANGUAGE GADTs #-} -{-# LANGUAGE MultiWayIf #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE QuasiQuotes #-} -{-# LANGUAGE TypeFamilies #-} -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE DefaultSignatures #-} +{-# LANGUAGE GADTs #-} +{-# LANGUAGE MultiWayIf #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE QuasiQuotes #-} +{-# LANGUAGE TypeFamilies #-} +{-# LANGUAGE ViewPatterns #-} module Stack.Types.Config ( @@ -199,19 +200,19 @@ data Config = Config -- | The project root directory, if in a project. configProjectRoot :: Config -> Maybe (Path Abs Dir) configProjectRoot c = - case configProject c of + case c.configProject of PCProject (_, fp) -> Just $ parent fp PCGlobalProject -> Nothing PCNoProject _deps -> Nothing -- | Get the URL to request the information on the latest snapshots askLatestSnapshotUrl :: (MonadReader env m, HasConfig env) => m Text -askLatestSnapshotUrl = view $ configL.to configLatestSnapshot +askLatestSnapshotUrl = view $ configL . to (.configLatestSnapshot) -- | @STACK_ROOT\/hooks\/@ hooksDir :: HasConfig env => RIO env (Path Abs Dir) hooksDir = do - sr <- view $ configL.to configStackRoot + sr <- view $ configL . to (.configStackRoot) pure (sr [reldir|hooks|]) -- | @STACK_ROOT\/hooks\/ghc-install.sh@ @@ -239,67 +240,69 @@ class ( HasPlatform env ----------------------------------- instance HasPlatform Config where - platformL = lens configPlatform (\x y -> x { configPlatform = y }) + platformL = lens (.configPlatform) (\x y -> x { configPlatform = y }) platformVariantL = - lens configPlatformVariant (\x y -> x { configPlatformVariant = y }) + lens (.configPlatformVariant) (\x y -> x { configPlatformVariant = y }) instance HasGHCVariant Config where - ghcVariantL = to $ fromMaybe GHCStandard . configGHCVariant + ghcVariantL = to $ fromMaybe GHCStandard . (.configGHCVariant) instance HasProcessContext Config where - processContextL = runnerL.processContextL + processContextL = runnerL . processContextL instance HasPantryConfig Config where - pantryConfigL = lens configPantryConfig (\x y -> x { configPantryConfig = y }) + pantryConfigL = lens + (.configPantryConfig) + (\x y -> x { configPantryConfig = y }) instance HasConfig Config where configL = id {-# INLINE configL #-} instance HasRunner Config where - runnerL = lens configRunner (\x y -> x { configRunner = y }) + runnerL = lens (.configRunner) (\x y -> x { configRunner = y }) instance HasLogFunc Config where - logFuncL = runnerL.logFuncL + logFuncL = runnerL . logFuncL instance HasStylesUpdate Config where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm Config where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL ----------------------------------- -- Helper lenses ----------------------------------- stackRootL :: HasConfig s => Lens' s (Path Abs Dir) -stackRootL = configL.lens configStackRoot (\x y -> x { configStackRoot = y }) +stackRootL = + configL . lens (.configStackRoot) (\x y -> x { configStackRoot = y }) stackGlobalConfigL :: HasConfig s => Lens' s (Path Abs File) -stackGlobalConfigL = - configL.lens configUserConfigPath (\x y -> x { configUserConfigPath = y }) +stackGlobalConfigL = configL . lens + (.configUserConfigPath) + (\x y -> x { configUserConfigPath = y }) buildOptsL :: HasConfig s => Lens' s BuildOpts -buildOptsL = configL.lens - configBuild - (\x y -> x { configBuild = y }) +buildOptsL = configL . lens (.configBuild) (\x y -> x { configBuild = y }) envOverrideSettingsL :: HasConfig env => Lens' env (EnvSettings -> IO ProcessContext) -envOverrideSettingsL = configL.lens - configProcessContextSettings +envOverrideSettingsL = configL . lens + (.configProcessContextSettings) (\x y -> x { configProcessContextSettings = y }) -- | @".stack-work"@ workDirL :: HasConfig env => Lens' env (Path Rel Dir) -workDirL = configL.lens configWorkDir (\x y -> x { configWorkDir = y }) +workDirL = configL . lens (.configWorkDir) (\x y -> x { configWorkDir = y }) -- | In dev mode, print as a warning, otherwise as debug prettyStackDevL :: HasConfig env => [StyleDoc] -> RIO env () prettyStackDevL docs = do config <- view configL - if configStackDeveloperMode config + if config.configStackDeveloperMode then prettyWarnL docs else prettyDebugL docs diff --git a/src/Stack/Types/ConfigMonoid.hs b/src/Stack/Types/ConfigMonoid.hs index 74d9cbcf37..dbab255f28 100644 --- a/src/Stack/Types/ConfigMonoid.hs +++ b/src/Stack/Types/ConfigMonoid.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Types.ConfigMonoid ( ConfigMonoid (..) @@ -241,7 +242,7 @@ parseConfigMonoidObject rootDir obj = do FirstFalse <$> obj ..:? configMonoidSkipGHCCheckName configMonoidSkipMsys <- FirstFalse <$> obj ..:? configMonoidSkipMsysName configMonoidRequireStackVersion <- - IntersectingVersionRange . unVersionRangeJSON <$> + IntersectingVersionRange . (.unVersionRangeJSON) <$> ( obj ..:? configMonoidRequireStackVersionName ..!= VersionRangeJSON anyVersion ) @@ -275,8 +276,8 @@ parseConfigMonoidObject rootDir obj = do configMonoidCompilerRepository <- First <$> (obj ..:? configMonoidCompilerRepositoryName) - options <- - Map.map unGhcOptions <$> obj ..:? configMonoidGhcOptionsName ..!= mempty + options <- Map.map (.unGhcOptions) <$> + obj ..:? configMonoidGhcOptionsName ..!= (mempty :: Map GhcOptionKey GhcOptions) optionsEverything <- case (Map.lookup GOKOldEverything options, Map.lookup GOKEverything options) of diff --git a/src/Stack/Types/ConfigureOpts.hs b/src/Stack/Types/ConfigureOpts.hs index e4f2b2209a..698c445c91 100644 --- a/src/Stack/Types/ConfigureOpts.hs +++ b/src/Stack/Types/ConfigureOpts.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Types.ConfigureOpts ( ConfigureOpts (..) @@ -67,8 +68,8 @@ configureOptsDirs :: BaseConfigOpts configureOptsDirs bco isMutable package = concat [ ["--user", "--package-db=clear", "--package-db=global"] , map (("--package-db=" ++) . toFilePathNoTrailingSep) $ case isMutable of - Immutable -> bcoExtraDBs bco ++ [bcoSnapDB bco] - Mutable -> bcoExtraDBs bco ++ [bcoSnapDB bco] ++ [bcoLocalDB bco] + Immutable -> bco.bcoExtraDBs ++ [bco.bcoSnapDB] + Mutable -> bco.bcoExtraDBs ++ [bco.bcoSnapDB] ++ [bco.bcoLocalDB] , [ "--libdir=" ++ toFilePathNoTrailingSep (installRoot relDirLib) , "--bindir=" ++ toFilePathNoTrailingSep (installRoot bindirSuffix) , "--datadir=" ++ toFilePathNoTrailingSep (installRoot relDirShare) @@ -81,15 +82,15 @@ configureOptsDirs bco isMutable package = concat where installRoot = case isMutable of - Immutable -> bcoSnapInstallRoot bco - Mutable -> bcoLocalInstallRoot bco + Immutable -> bco.bcoSnapInstallRoot + Mutable -> bco.bcoLocalInstallRoot docDir = case pkgVerDir of Nothing -> installRoot docDirSuffix Just dir -> installRoot docDirSuffix dir pkgVerDir = parseRelDir ( packageIdentifierString - (PackageIdentifier (packageName package) (packageVersion package)) + (PackageIdentifier package.packageName package.packageVersion) ++ [pathSeparator] ) @@ -104,14 +105,14 @@ configureOptsNoDir :: configureOptsNoDir econfig bco deps isLocal package = concat [ depOptions , [ "--enable-library-profiling" - | boptsLibProfile bopts || boptsExeProfile bopts + | bopts.boptsLibProfile || bopts.boptsExeProfile ] - , ["--enable-profiling" | boptsExeProfile bopts && isLocal] - , ["--enable-split-objs" | boptsSplitObjs bopts] + , ["--enable-profiling" | bopts.boptsExeProfile && isLocal] + , ["--enable-split-objs" | bopts.boptsSplitObjs] , [ "--disable-library-stripping" - | not $ boptsLibStrip bopts || boptsExeStrip bopts + | not $ bopts.boptsLibStrip || bopts.boptsExeStrip ] - , ["--disable-executable-stripping" | not (boptsExeStrip bopts) && isLocal] + , ["--disable-executable-stripping" | not bopts.boptsExeStrip && isLocal] , map (\(name,enabled) -> "-f" <> (if enabled @@ -119,14 +120,14 @@ configureOptsNoDir econfig bco deps isLocal package = concat else "-") <> flagNameString name) (Map.toList flags) - , map T.unpack $ packageCabalConfigOpts package - , processGhcOptions (packageGhcOptions package) - , map ("--extra-include-dirs=" ++) (configExtraIncludeDirs config) - , map ("--extra-lib-dirs=" ++) (configExtraLibDirs config) + , map T.unpack package.packageCabalConfigOpts + , processGhcOptions package.packageGhcOptions + , map ("--extra-include-dirs=" ++) config.configExtraIncludeDirs + , map ("--extra-lib-dirs=" ++) config.configExtraLibDirs , maybe [] (\customGcc -> ["--with-gcc=" ++ toFilePath customGcc]) - (configOverrideGccPath config) + config.configOverrideGccPath , ["--exact-configuration"] , ["--ghc-option=-fhide-source-paths" | hideSourcePaths cv] ] @@ -161,18 +162,18 @@ configureOptsNoDir econfig bco deps isLocal package = concat newArgs = concat [preRtsArgs, fullRtsArgs, postRtsArgs] in concatMap (\x -> [compilerOptionsCabalFlag wc, T.unpack x]) newArgs - wc = view (actualCompilerVersionL.to whichCompiler) econfig - cv = view (actualCompilerVersionL.to getGhcVersion) econfig + wc = view (actualCompilerVersionL . to whichCompiler) econfig + cv = view (actualCompilerVersionL . to getGhcVersion) econfig hideSourcePaths ghcVersion = - ghcVersion >= C.mkVersion [8, 2] && configHideSourcePaths config + ghcVersion >= C.mkVersion [8, 2] && config.configHideSourcePaths config = view configL econfig - bopts = bcoBuildOpts bco + bopts = bco.bcoBuildOpts -- Unioning atop defaults is needed so that all flags are specified with -- --exact-configuration. - flags = packageFlags package `Map.union` packageDefaultFlags package + flags = package.packageFlags `Map.union` package.packageDefaultFlags depOptions = map toDepOption $ Map.toList deps diff --git a/src/Stack/Types/Curator.hs b/src/Stack/Types/Curator.hs index 483db8a23e..79875275d7 100644 --- a/src/Stack/Types/Curator.hs +++ b/src/Stack/Types/Curator.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Module exporting the 'Curator' type, used to represent Stack's -- project-specific @curator@ option, which supports the needs of the @@ -35,14 +36,14 @@ data Curator = Curator instance ToJSON Curator where toJSON c = object - [ "skip-test" .= Set.map CabalString (curatorSkipTest c) - , "expect-test-failure" .= Set.map CabalString (curatorExpectTestFailure c) - , "skip-bench" .= Set.map CabalString (curatorSkipBenchmark c) + [ "skip-test" .= Set.map CabalString c.curatorSkipTest + , "expect-test-failure" .= Set.map CabalString c.curatorExpectTestFailure + , "skip-bench" .= Set.map CabalString c.curatorSkipBenchmark , "expect-benchmark-failure" .= - Set.map CabalString (curatorExpectTestFailure c) - , "skip-haddock" .= Set.map CabalString (curatorSkipHaddock c) + Set.map CabalString c.curatorExpectTestFailure + , "skip-haddock" .= Set.map CabalString c.curatorSkipHaddock , "expect-haddock-failure" .= - Set.map CabalString (curatorExpectHaddockFailure c) + Set.map CabalString c.curatorExpectHaddockFailure ] instance FromJSON (WithJSONWarnings Curator) where diff --git a/src/Stack/Types/Dependency.hs b/src/Stack/Types/Dependency.hs index c78285791a..8e5ac8fff0 100644 --- a/src/Stack/Types/Dependency.hs +++ b/src/Stack/Types/Dependency.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.Dependency ( DepValue (..) @@ -43,8 +44,8 @@ data DepLibrary = DepLibrary deriving (Eq, Show) getDepSublib :: DepValue -> Maybe (Set StackUnqualCompName) -getDepSublib val = case dvType val of - AsLibrary libVal -> Just $ dlSublib libVal +getDepSublib val = case val.dvType of + AsLibrary libVal -> Just libVal.dlSublib _ -> Nothing defaultDepLibrary :: DepLibrary diff --git a/src/Stack/Types/DependencyTree.hs b/src/Stack/Types/DependencyTree.hs index 07cf2b9908..73b6107b9f 100644 --- a/src/Stack/Types/DependencyTree.hs +++ b/src/Stack/Types/DependencyTree.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Types.DependencyTree ( DependencyTree (..) @@ -47,7 +48,7 @@ dependencyToJSON pkg (deps, payload) = , "dependencies" .= Set.map packageNameString deps ] loc = catMaybes - [("location" .=) . pkgLocToJSON <$> payloadLocation payload] + [("location" .=) . pkgLocToJSON <$> payload.payloadLocation] in object $ fieldsAlwaysPresent ++ loc pkgLocToJSON :: PackageLocation -> Value @@ -82,8 +83,8 @@ pkgLocToJSON (PLImmutable (PLIRepo repo _)) = object licenseText :: DotPayload -> Text licenseText payload = maybe "" (Text.pack . display . either licenseFromSPDX id) - (payloadLicense payload) + payload.payloadLicense versionText :: DotPayload -> Text versionText payload = - maybe "" (Text.pack . display) (payloadVersion payload) + maybe "" (Text.pack . display) payload.payloadVersion diff --git a/src/Stack/Types/Docker.hs b/src/Stack/Types/Docker.hs index 09df05491c..e32e4cd27f 100644 --- a/src/Stack/Types/Docker.hs +++ b/src/Stack/Types/Docker.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Docker types. @@ -351,7 +352,7 @@ instance FromJSON (WithJSONWarnings DockerOptsMonoid) where dockerMonoidStackExe <- First <$> o ..:? dockerStackExeArgName dockerMonoidSetUser <- First <$> o ..:? dockerSetUserArgName dockerMonoidRequireDockerVersion <- - IntersectingVersionRange . unVersionRangeJSON <$> + IntersectingVersionRange . (.unVersionRangeJSON) <$> ( o ..:? dockerRequireDockerVersionArgName ..!= VersionRangeJSON anyVersion ) diff --git a/src/Stack/Types/DumpPackage.hs b/src/Stack/Types/DumpPackage.hs index 001b091203..cbc8166c2e 100644 --- a/src/Stack/Types/DumpPackage.hs +++ b/src/Stack/Types/DumpPackage.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.DumpPackage ( DumpPackage (..) @@ -49,7 +50,7 @@ data SublibDump = SublibDump deriving (Eq, Read, Show) dpParentLibIdent :: DumpPackage -> Maybe PackageIdentifier -dpParentLibIdent dp = case (dpSublib dp, dpPackageIdent dp) of +dpParentLibIdent dp = case (dp.dpSublib, dp.dpPackageIdent) of (Nothing, _) -> Nothing (Just sublibDump, PackageIdentifier _ v) -> Just $ PackageIdentifier libParentPackageName v diff --git a/src/Stack/Types/EnvConfig.hs b/src/Stack/Types/EnvConfig.hs index dd6d3ba9b3..22197c7aa0 100644 --- a/src/Stack/Types/EnvConfig.hs +++ b/src/Stack/Types/EnvConfig.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.EnvConfig ( EnvConfig (..) @@ -71,45 +72,45 @@ data EnvConfig = EnvConfig } instance HasConfig EnvConfig where - configL = buildConfigL.lens bcConfig (\x y -> x { bcConfig = y }) + configL = buildConfigL . lens (.bcConfig) (\x y -> x { bcConfig = y }) {-# INLINE configL #-} instance HasBuildConfig EnvConfig where - buildConfigL = envConfigL.lens - envConfigBuildConfig + buildConfigL = envConfigL . lens + (.envConfigBuildConfig) (\x y -> x { envConfigBuildConfig = y }) instance HasPlatform EnvConfig where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasGHCVariant EnvConfig where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasProcessContext EnvConfig where - processContextL = configL.processContextL + processContextL = configL . processContextL instance HasPantryConfig EnvConfig where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasCompiler EnvConfig where - compilerPathsL = to envConfigCompilerPaths + compilerPathsL = to (.envConfigCompilerPaths) instance HasRunner EnvConfig where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasLogFunc EnvConfig where - logFuncL = runnerL.logFuncL + logFuncL = runnerL . logFuncL instance HasStylesUpdate EnvConfig where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm EnvConfig where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL class (HasBuildConfig env, HasSourceMap env, HasCompiler env) => HasEnvConfig env where envConfigL :: Lens' env EnvConfig @@ -122,7 +123,7 @@ class HasSourceMap env where sourceMapL :: Lens' env SourceMap instance HasSourceMap EnvConfig where - sourceMapL = lens envConfigSourceMap (\x y -> x { envConfigSourceMap = y }) + sourceMapL = lens (.envConfigSourceMap) (\x y -> x { envConfigSourceMap = y }) shouldForceGhcColorFlag :: (HasEnvConfig env, HasRunner env) @@ -176,7 +177,7 @@ hoogleDatabasePath = do platformSnapAndCompilerRel :: HasEnvConfig env => RIO env (Path Rel Dir) platformSnapAndCompilerRel = do platform <- platformGhcRelDir - smh <- view $ envConfigL.to envConfigSourceMapHash + smh <- view $ envConfigL . to (.envConfigSourceMapHash) name <- smRelDir smh ghc <- compilerVersionDir useShaPathOnWindows (platform name ghc) @@ -187,7 +188,7 @@ platformGhcRelDir :: => m (Path Rel Dir) platformGhcRelDir = do cp <- view compilerPathsL - let cbSuffix = compilerBuildSuffix $ cpBuild cp + let cbSuffix = compilerBuildSuffix cp.cpBuild verOnly <- platformGhcVerOnlyRelDirStr parseRelDir (mconcat [ verOnly, cbSuffix ]) @@ -239,7 +240,7 @@ packageDatabaseLocal = do packageDatabaseExtra :: (HasEnvConfig env, MonadReader env m) => m [Path Abs Dir] -packageDatabaseExtra = view $ buildConfigL.to bcExtraPackageDBs +packageDatabaseExtra = view $ buildConfigL . to (.bcExtraPackageDBs) -- | Where HPC reports and tix files get stored. hpcReportDir :: HasEnvConfig env => RIO env (Path Abs Dir) @@ -263,7 +264,7 @@ extraBinDirs = do -- than that specified in the 'SnapshotDef' and returned by -- 'wantedCompilerVersionL'. actualCompilerVersionL :: HasSourceMap env => SimpleGetter env ActualCompiler -actualCompilerVersionL = sourceMapL.to smCompiler +actualCompilerVersionL = sourceMapL . to (.smCompiler) -- | Relative directory for the platform and GHC identifier without GHC bindist -- build diff --git a/src/Stack/Types/GlobalOpts.hs b/src/Stack/Types/GlobalOpts.hs index 60bc6db78e..e3cf638d97 100644 --- a/src/Stack/Types/GlobalOpts.hs +++ b/src/Stack/Types/GlobalOpts.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.GlobalOpts ( GlobalOpts (..) @@ -42,9 +43,9 @@ data GlobalOpts = GlobalOpts globalOptsBuildOptsMonoidL :: Lens' GlobalOpts BuildOptsMonoid globalOptsBuildOptsMonoidL = lens - globalConfigMonoid + (.globalConfigMonoid) (\x y -> x { globalConfigMonoid = y }) . lens - configMonoidBuildOpts + (.configMonoidBuildOpts) (\x y -> x { configMonoidBuildOpts = y }) diff --git a/src/Stack/Types/Installed.hs b/src/Stack/Types/Installed.hs index 469197f96f..1336a702cd 100644 --- a/src/Stack/Types/Installed.hs +++ b/src/Stack/Types/Installed.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} -- | This module contains all the types related to the idea of installing a -- package in the pkg-db or an executable on the file system. @@ -124,7 +125,7 @@ simpleInstalledLib pkgIdentifier ghcPkgId = installedToPackageIdOpt :: InstalledLibraryInfo -> [String] installedToPackageIdOpt libInfo = - M.foldr' (iterator (++)) (pure $ toStr (iliId libInfo)) (iliSublib libInfo) + M.foldr' (iterator (++)) (pure $ toStr libInfo.iliId) libInfo.iliSublib where toStr ghcPkgId = "-package-id=" <> ghcPkgIdString ghcPkgId iterator op ghcPkgId acc = pure (toStr ghcPkgId) `op` acc @@ -134,7 +135,7 @@ installedPackageIdentifier (Library pid _) = pid installedPackageIdentifier (Executable pid) = pid installedGhcPkgId :: Installed -> Maybe GhcPkgId -installedGhcPkgId (Library _ libInfo) = Just $ iliId libInfo +installedGhcPkgId (Library _ libInfo) = Just libInfo.iliId installedGhcPkgId (Executable _) = Nothing -- | Get the installed Version. diff --git a/src/Stack/Types/Package.hs b/src/Stack/Types/Package.hs index 9984dda74d..a4d5ab06b5 100644 --- a/src/Stack/Types/Package.hs +++ b/src/Stack/Types/Package.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.Types.Package ( BioInput (..) @@ -206,10 +207,10 @@ data Package = Package deriving (Show, Typeable) packageIdentifier :: Package -> PackageIdentifier -packageIdentifier p = PackageIdentifier (packageName p) (packageVersion p) +packageIdentifier p = PackageIdentifier p.packageName p.packageVersion packageDefinedFlags :: Package -> Set FlagName -packageDefinedFlags = M.keysSet . packageDefaultFlags +packageDefinedFlags = M.keysSet . (.packageDefaultFlags) -- | GHC options based on cabal information and ghc-options. data BuildInfoOpts = BuildInfoOpts @@ -244,11 +245,11 @@ data PackageConfig = PackageConfig -- | Compares the package name. instance Ord Package where - compare = on compare packageName + compare = on compare (.packageName) -- | Compares the package name. instance Eq Package where - (==) = on (==) packageName + (==) = on (==) (.packageName) -- | Where the package's source is located: local directory or package index data PackageSource @@ -269,7 +270,7 @@ instance Show PackageSource where ] psVersion :: PackageSource -> Version -psVersion (PSFilePath lp) = packageVersion $ lpPackage lp +psVersion (PSFilePath lp) = lp.lpPackage.packageVersion psVersion (PSRemote _ v _ _) = v -- | Information on a locally available package of source code. @@ -340,14 +341,14 @@ instance Show (MemoizedWith env a) where show _ = "<>" lpFiles :: HasEnvConfig env => LocalPackage -> RIO env (Set.Set (Path Abs File)) -lpFiles = runMemoizedWith . fmap (Set.unions . M.elems) . lpComponentFiles +lpFiles = runMemoizedWith . fmap (Set.unions . M.elems) . (.lpComponentFiles) lpFilesForComponents :: HasEnvConfig env => Set NamedComponent -> LocalPackage -> RIO env (Set.Set (Path Abs File)) lpFilesForComponents components lp = runMemoizedWith $ do - componentFiles <- lpComponentFiles lp + componentFiles <- lp.lpComponentFiles pure $ mconcat (M.elems (M.restrictKeys componentFiles components)) newtype FileCacheInfo = FileCacheInfo @@ -409,10 +410,11 @@ installedMapGhcPkgId :: installedMapGhcPkgId pkgId@(PackageIdentifier pkgName version) installedLib = finalMap where - finalMap = M.insert pkgId (iliId installedLib) baseMap + finalMap = M.insert pkgId installedLib.iliId baseMap baseMap = - M.mapKeysMonotonic (toCabalMungedPackageIdentifier pkgName version) $ - iliSublib installedLib + M.mapKeysMonotonic + (toCabalMungedPackageIdentifier pkgName version) + installedLib.iliSublib -- | Creates a 'MungedPackageName' identifier. toCabalMungedPackageIdentifier :: diff --git a/src/Stack/Types/PackageFile.hs b/src/Stack/Types/PackageFile.hs index 64b6a1c3ea..9efc000fce 100644 --- a/src/Stack/Types/PackageFile.hs +++ b/src/Stack/Types/PackageFile.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE DataKinds #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE DataKinds #-} +{-# LANGUAGE OverloadedRecordDot #-} -- | The facility for retrieving all files from the main Stack -- 'Stack.Types.Package' type. This was moved into its own module to allow @@ -33,40 +34,40 @@ data GetPackageFileContext = GetPackageFileContext } instance HasPlatform GetPackageFileContext where - platformL = configL.platformL + platformL = configL . platformL {-# INLINE platformL #-} - platformVariantL = configL.platformVariantL + platformVariantL = configL . platformVariantL {-# INLINE platformVariantL #-} instance HasGHCVariant GetPackageFileContext where - ghcVariantL = configL.ghcVariantL + ghcVariantL = configL . ghcVariantL {-# INLINE ghcVariantL #-} instance HasLogFunc GetPackageFileContext where - logFuncL = configL.logFuncL + logFuncL = configL . logFuncL instance HasRunner GetPackageFileContext where - runnerL = configL.runnerL + runnerL = configL . runnerL instance HasStylesUpdate GetPackageFileContext where - stylesUpdateL = runnerL.stylesUpdateL + stylesUpdateL = runnerL . stylesUpdateL instance HasTerm GetPackageFileContext where - useColorL = runnerL.useColorL - termWidthL = runnerL.termWidthL + useColorL = runnerL . useColorL + termWidthL = runnerL . termWidthL instance HasConfig GetPackageFileContext where - configL = buildConfigL.lens bcConfig (\x y -> x { bcConfig = y }) + configL = buildConfigL . lens (.bcConfig) (\x y -> x { bcConfig = y }) {-# INLINE configL #-} instance HasBuildConfig GetPackageFileContext where - buildConfigL = lens ctxBuildConfig (\x y -> x { ctxBuildConfig = y }) + buildConfigL = lens (.ctxBuildConfig) (\x y -> x { ctxBuildConfig = y }) instance HasPantryConfig GetPackageFileContext where - pantryConfigL = configL.pantryConfigL + pantryConfigL = configL . pantryConfigL instance HasProcessContext GetPackageFileContext where - processContextL = configL.processContextL + processContextL = configL . processContextL -- | A path resolved from the Cabal file, which is either main-is or -- an exposed/internal/referenced module. diff --git a/src/Stack/Types/Runner.hs b/src/Stack/Types/Runner.hs index e536e779b4..3a3f83ee75 100644 --- a/src/Stack/Types/Runner.hs +++ b/src/Stack/Types/Runner.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} module Stack.Types.Runner ( Runner (..) @@ -32,25 +33,27 @@ data Runner = Runner } instance HasLogFunc Runner where - logFuncL = lens runnerLogFunc (\x y -> x { runnerLogFunc = y }) + logFuncL = lens (.runnerLogFunc) (\x y -> x { runnerLogFunc = y }) instance HasProcessContext Runner where processContextL = - lens runnerProcessContext (\x y -> x { runnerProcessContext = y }) + lens (.runnerProcessContext) (\x y -> x { runnerProcessContext = y }) instance HasRunner Runner where runnerL = id instance HasStylesUpdate Runner where - stylesUpdateL = globalOptsL. - lens globalStylesUpdate (\x y -> x { globalStylesUpdate = y }) + stylesUpdateL = globalOptsL . lens + (.globalStylesUpdate) + (\x y -> x { globalStylesUpdate = y }) instance HasTerm Runner where - useColorL = lens runnerUseColor (\x y -> x { runnerUseColor = y }) - termWidthL = lens runnerTermWidth (\x y -> x { runnerTermWidth = y }) + useColorL = lens (.runnerUseColor) (\x y -> x { runnerUseColor = y }) + termWidthL = lens (.runnerTermWidth) (\x y -> x { runnerTermWidth = y }) instance HasDockerEntrypointMVar Runner where - dockerEntrypointMVarL = - lens runnerDockerEntrypointMVar (\x y -> x { runnerDockerEntrypointMVar = y }) + dockerEntrypointMVarL = lens + (.runnerDockerEntrypointMVar) + (\x y -> x { runnerDockerEntrypointMVar = y }) -- | Class for environment values which have a 'Runner'. class (HasProcessContext env, HasLogFunc env) => HasRunner env where @@ -62,21 +65,25 @@ class HasRunner env => HasDockerEntrypointMVar env where stackYamlLocL :: HasRunner env => Lens' env StackYamlLoc stackYamlLocL = - globalOptsL.lens globalStackYaml (\x y -> x { globalStackYaml = y }) + globalOptsL . lens (.globalStackYaml) (\x y -> x { globalStackYaml = y }) lockFileBehaviorL :: HasRunner env => SimpleGetter env LockFileBehavior -lockFileBehaviorL = globalOptsL.to globalLockFileBehavior +lockFileBehaviorL = globalOptsL . to (.globalLockFileBehavior) globalOptsL :: HasRunner env => Lens' env GlobalOpts -globalOptsL = runnerL.lens runnerGlobalOpts (\x y -> x { runnerGlobalOpts = y }) +globalOptsL = runnerL . lens + (.runnerGlobalOpts) + (\x y -> x { runnerGlobalOpts = y }) -- | See 'globalTerminal' terminalL :: HasRunner env => Lens' env Bool -terminalL = globalOptsL.lens globalTerminal (\x y -> x { globalTerminal = y }) +terminalL = globalOptsL . lens + (.globalTerminal) + (\x y -> x { globalTerminal = y }) -- | See 'globalReExecVersion' reExecL :: HasRunner env => SimpleGetter env Bool -reExecL = globalOptsL.to (isJust . globalReExecVersion) +reExecL = globalOptsL . to (isJust . (.globalReExecVersion)) rslInLogL :: HasRunner env => SimpleGetter env Bool -rslInLogL = globalOptsL.to globalRSLInLog +rslInLogL = globalOptsL . to (.globalRSLInLog) diff --git a/src/Stack/Types/SetupInfo.hs b/src/Stack/Types/SetupInfo.hs index b857d1dbcd..034098783d 100644 --- a/src/Stack/Types/SetupInfo.hs +++ b/src/Stack/Types/SetupInfo.hs @@ -1,6 +1,7 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} -{-# LANGUAGE ViewPatterns #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE ViewPatterns #-} module Stack.Types.SetupInfo @@ -49,19 +50,20 @@ instance FromJSON (WithJSONWarnings SetupInfo) where instance Semigroup SetupInfo where l <> r = SetupInfo - { siSevenzExe = siSevenzExe l <|> siSevenzExe r - , siSevenzDll = siSevenzDll l <|> siSevenzDll r - , siMsys2 = siMsys2 l <> siMsys2 r - , siGHCs = Map.unionWith (<>) (siGHCs l) (siGHCs r) - , siStack = Map.unionWith (<>) (siStack l) (siStack r) } + { siSevenzExe = l.siSevenzExe <|> r.siSevenzExe + , siSevenzDll = l.siSevenzDll <|> r.siSevenzDll + , siMsys2 = l.siMsys2 <> r.siMsys2 + , siGHCs = Map.unionWith (<>) l.siGHCs r.siGHCs + , siStack = Map.unionWith (<>) l.siStack r.siStack + } instance Monoid SetupInfo where mempty = SetupInfo - { siSevenzExe = Nothing - , siSevenzDll = Nothing - , siMsys2 = Map.empty - , siGHCs = Map.empty - , siStack = Map.empty - } + { siSevenzExe = Nothing + , siSevenzDll = Nothing + , siMsys2 = Map.empty + , siGHCs = Map.empty + , siStack = Map.empty + } mappend = (<>) diff --git a/src/Stack/Types/SourceMap.hs b/src/Stack/Types/SourceMap.hs index 020b939a01..de08b2d339 100644 --- a/src/Stack/Types/SourceMap.hs +++ b/src/Stack/Types/SourceMap.hs @@ -1,4 +1,5 @@ -{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} -- | A sourcemap maps a package name to how it should be built, including source -- code, flags, options, etc. This module contains various stages of source map @@ -169,11 +170,11 @@ smRelDir :: (MonadThrow m) => SourceMapHash -> m (Path Rel Dir) smRelDir (SourceMapHash smh) = parseRelDir $ T.unpack $ SHA256.toHexText smh ppGPD :: MonadIO m => ProjectPackage -> m GenericPackageDescription -ppGPD = liftIO . cpGPD . ppCommon +ppGPD = liftIO . (.ppCommon.cpGPD) -- | Root directory for the given 'ProjectPackage' ppRoot :: ProjectPackage -> Path Abs Dir -ppRoot = parent . ppCabalFP +ppRoot = parent . (.ppCabalFP) -- | All components available in the given 'ProjectPackage' ppComponents :: MonadIO m => ProjectPackage -> m (Set NamedComponent) diff --git a/src/Stack/Uninstall.hs b/src/Stack/Uninstall.hs index c4dbdfd1b4..c37ef6ba1f 100644 --- a/src/Stack/Uninstall.hs +++ b/src/Stack/Uninstall.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Function related to Stack's @uninstall@ command. module Stack.Uninstall @@ -21,8 +22,8 @@ uninstallCmd :: () -> RIO Runner () uninstallCmd () = withConfig NoReexec $ do stackRoot <- view stackRootL globalConfig <- view stackGlobalConfigL - programsDir <- view $ configL.to configLocalProgramsBase - localBinDir <- view $ configL.to configLocalBin + programsDir <- view $ configL . to (.configLocalProgramsBase) + localBinDir <- view $ configL . to (.configLocalBin) let toStyleDoc = style Dir . fromString . toFilePath stackRoot' = toStyleDoc stackRoot globalConfig' = toStyleDoc globalConfig diff --git a/src/Stack/Unpack.hs b/src/Stack/Unpack.hs index b2e9dc60cd..a42dfa7f69 100644 --- a/src/Stack/Unpack.hs +++ b/src/Stack/Unpack.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} -- | Functions related to Stack's @unpack@ command. @@ -92,7 +93,7 @@ unpackCmd (UnpackOpts targets areCandidates Nothing) = unpackCmd (UnpackOpts targets areCandidates (Just $ Rel relDirRoot)) unpackCmd (UnpackOpts targets areCandidates (Just dstPath)) = withConfig NoReexec $ do - mresolver <- view $ globalOptsL.to globalResolver + mresolver <- view $ globalOptsL . to (.globalResolver) mSnapshot <- forM mresolver $ \resolver -> do concrete <- makeConcreteResolver resolver loc <- completeSnapshotLocation concrete @@ -127,7 +128,7 @@ unpackPackages mSnapshot dest targets areCandidates = do \will be ignored." <> line locs1 <- forM pirs $ \pir -> do - hackageBaseUrl <- view $ configL.to configHackageBaseUrl + hackageBaseUrl <- view $ configL . to (.configHackageBaseUrl) let rpli = if areCandidates then let -- Ignoring revisions for package candidates. diff --git a/src/Stack/Upgrade.hs b/src/Stack/Upgrade.hs index f67b04c4f8..cd1c062a4c 100644 --- a/src/Stack/Upgrade.hs +++ b/src/Stack/Upgrade.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @upgrade@ command. module Stack.Upgrade @@ -117,7 +118,7 @@ data UpgradeOpts = UpgradeOpts upgradeCmd :: UpgradeOpts -> RIO Runner () upgradeCmd upgradeOpts = do go <- view globalOptsL - case globalResolver go of + case go.globalResolver of Just _ -> prettyThrowIO ResolverOptionInvalid Nothing -> withGlobalProject $ upgrade maybeGitHash upgradeOpts @@ -197,7 +198,7 @@ binaryUpgrade (BinaryOpts mplatform force' onlyLocalBin mver morg mrepo) = when toUpgrade $ do config <- view configL downloadStackExe - platforms0 archiveInfo (configLocalBin config) (not onlyLocalBin) $ + platforms0 archiveInfo config.configLocalBin (not onlyLocalBin) $ \tmpFile -> do -- Sanity check! ec <- rawSystem (toFilePath tmpFile) ["--version"] @@ -293,5 +294,5 @@ sourceUpgrade builtHash (SourceOpts gitRepo) = local (over globalOptsL (modifyGO dir)) $ withConfig NoReexec $ withEnvConfig AllowNoTargets boptsCLI - $ local (set (buildOptsL.buildOptsInstallExesL) True) + $ local (set (buildOptsL . buildOptsInstallExesL) True) $ build Nothing diff --git a/src/Stack/Upload.hs b/src/Stack/Upload.hs index 80f9bbb573..9416eb5576 100644 --- a/src/Stack/Upload.hs +++ b/src/Stack/Upload.hs @@ -1,6 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedRecordDot #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} -- | Types and functions related to Stack's @upload@ command. module Stack.Upload @@ -186,7 +186,7 @@ uploadCmd (UploadOpts [] uoDocumentation _ _ _ _ _) = do prettyThrowIO $ NoItemSpecified subject uploadCmd uo = withConfig YesReexec $ withDefaultEnvConfig $ do config <- view configL - let hackageUrl = T.unpack $ configHackageBaseUrl config + let hackageUrl = T.unpack config.configHackageBaseUrl if uo.uoDocumentation then do (dirs, invalid) <- @@ -254,7 +254,7 @@ uploadCmd uo = withConfig YesReexec $ withDefaultEnvConfig $ do pkgDir <- resolveDir' dir distDir <- distDirFromDir pkgDir lp <- readLocalPackage pkgDir - let pkgId = packageIdentifier (lpPackage lp) + let pkgId = packageIdentifier lp.lpPackage pkgIdName = packageIdentifierString pkgId name = pkgIdName <> "-docs" tarGzFileName <- maybe @@ -334,7 +334,7 @@ loadUserAndPassword config = do -- didn't do this writeFilePrivate fp $ lazyByteString lbs - unless (configSaveHackageCreds config) $ do + unless config.configSaveHackageCreds $ do prettyWarnL [ flow "You've set" , style Shell "save-hackage-creds" @@ -355,7 +355,7 @@ loadUserAndPassword config = do , hcCredsFile = fp } - when (configSaveHackageCreds config) $ do + when config.configSaveHackageCreds $ do shouldSave <- promptBool $ T.pack $ "Save Hackage credentials to file at " ++ fp ++ " [y/n]? " prettyNoteL @@ -428,8 +428,8 @@ applyCreds creds req0 = do pure (Left $ toException ExitSuccess ) else liftIO $ applyDigestAuth - (encodeUtf8 $ hcUsername creds) - (encodeUtf8 $ hcPassword creds) + (encodeUtf8 creds.hcUsername) + (encodeUtf8 creds.hcPassword) req0 manager case ereq of @@ -517,7 +517,7 @@ uploadBytes baseUrl auth contentForm mPkgIdName tarName uploadVariant bytes = do HACreds creds -> handleIO (const $ pure ()) - (liftIO $ removeFile (hcCredsFile creds)) + (liftIO $ removeFile creds.hcCredsFile) _ -> pure () prettyThrowIO AuthenticationFailure 403 -> do diff --git a/src/windows/Stack/Docker/Handlers.hs b/src/windows/Stack/Docker/Handlers.hs index e6820462d3..e4ac88b51f 100644 --- a/src/windows/Stack/Docker/Handlers.hs +++ b/src/windows/Stack/Docker/Handlers.hs @@ -1,4 +1,5 @@ {-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} -- | The module of this name differs as between Windows and non-Windows builds. -- This is the Windows version. @@ -26,13 +27,13 @@ handleSignals :: handleSignals docker keepStdinOpen containerID = do let args' = concat [ ["start"] - , ["-a" | not (dockerDetach docker)] + , ["-a" | not docker.dockerDetach] , ["-i" | keepStdinOpen] , [containerID] ] finally (try $ proc "docker" args' $ runProcess_ . setDelegateCtlc False) - ( unless (dockerPersist docker || dockerDetach docker) $ + ( unless (docker.dockerPersist || docker.dockerDetach) $ readProcessNull "docker" ["rm", "-f", containerID] `catch` (\(_ :: ExitCodeException) -> pure ()) ) diff --git a/src/windows/System/Posix/User.hs b/src/windows/System/Posix/User.hs index 7f1794bbbd..8ab0f716eb 100644 --- a/src/windows/System/Posix/User.hs +++ b/src/windows/System/Posix/User.hs @@ -1,3 +1,6 @@ +{-# LANGUAGE NoFieldSelectors #-} +{-# LANGUAGE OverloadedRecordDot #-} + -- | The module of this name differs as between Windows and non-Windows builds. -- This is the Windows version. Non-Windows builds rely on the unix package, -- which exposes a module of the same name. @@ -47,3 +50,6 @@ data UserEntry = UserEntry , homeDirectory :: String , userShell :: String } deriving (Eq, Read, Show) + +homeDirectory :: UserEntry -> String +homeDirectory ue = ue.homeDirectory diff --git a/tests/unit/Stack/ConfigSpec.hs b/tests/unit/Stack/ConfigSpec.hs index ba95144085..393bd5e413 100644 --- a/tests/unit/Stack/ConfigSpec.hs +++ b/tests/unit/Stack/ConfigSpec.hs @@ -190,7 +190,7 @@ spec = beforeAll setup $ do it "parses build config options" $ inTempDir $ do writeFile (toFilePath stackDotYaml) buildOptsConfig loadConfig' $ \config -> liftIO $ do - let bopts = configBuild config + let bopts = config.configBuild bopts.boptsLibProfile `shouldBe` True bopts.boptsExeProfile `shouldBe` True bopts.boptsHaddock `shouldBe` True diff --git a/tests/unit/Stack/LockSpec.hs b/tests/unit/Stack/LockSpec.hs index d62ab7d449..4e42f2a3c9 100644 --- a/tests/unit/Stack/LockSpec.hs +++ b/tests/unit/Stack/LockSpec.hs @@ -1,4 +1,5 @@ {-# LANGUAGE QuasiQuotes #-} +{-# LANGUAGE OverloadedRecordDot #-} {-# LANGUAGE OverloadedStrings #-} module Stack.LockSpec @@ -58,7 +59,7 @@ snapshots: compiler: ghc-8.6.5 packages: [] |] - pkgImm <- lckPkgImmutableLocations <$> decodeLocked lockFile + pkgImm <- (.lckPkgImmutableLocations) <$> decodeLocked lockFile pkgImm `shouldBe` [] it "parses lock file (empty with LTS resolver)" $ do let lockFile :: ByteString @@ -76,7 +77,7 @@ snapshots: compiler: ghc-8.6.5 packages: [] |] - pkgImm <- lckPkgImmutableLocations <$> decodeLocked lockFile + pkgImm <- (.lckPkgImmutableLocations) <$> decodeLocked lockFile pkgImm `shouldBe` [] it "parses lock file (LTS, wai + warp)" $ do let lockFile :: ByteString @@ -120,7 +121,7 @@ packages: sha256: f808e075811b002563d24c393ce115be826bb66a317d38da22c513ee42b7443a commit: d11d63f1a6a92db8c637a8d33e7953ce6194a3e0 |] - pkgImm <- lckPkgImmutableLocations <$> decodeLocked lockFile + pkgImm <- (.lckPkgImmutableLocations) <$> decodeLocked lockFile let waiSubdirRepo subdir = Repo { repoType = RepoGit , repoUrl = "https://github.com/yesodweb/wai.git" diff --git a/tests/unit/Stack/NixSpec.hs b/tests/unit/Stack/NixSpec.hs index f4152a59f6..3efba8b45b 100644 --- a/tests/unit/Stack/NixSpec.hs +++ b/tests/unit/Stack/NixSpec.hs @@ -1,5 +1,6 @@ -{-# LANGUAGE NoImplicitPrelude #-} -{-# LANGUAGE OverloadedStrings #-} +{-# LANGUAGE NoImplicitPrelude #-} +{-# LANGUAGE OverloadedRecordDot #-} +{-# LANGUAGE OverloadedStrings #-} module Stack.NixSpec ( sampleConfigNixEnabled @@ -72,42 +73,42 @@ spec = beforeAll setup $ do describe "nix disabled in config file" $ around_ (withStackDotYaml sampleConfigNixDisabled) $ do it "sees that the nix shell is not enabled" $ loadConfig' mempty $ \config -> - nixEnable (configNix config) `shouldBe` False + config.configNix.nixEnable `shouldBe` False describe "--nix given on command line" $ it "sees that the nix shell is enabled" $ loadConfig' (parseOpts ["--nix"]) $ \config -> - nixEnable (configNix config) `shouldBe` trueOnNonWindows + config.configNix.nixEnable `shouldBe` trueOnNonWindows describe "--nix-pure given on command line" $ it "sees that the nix shell is enabled" $ loadConfig' (parseOpts ["--nix-pure"]) $ \config -> - nixEnable (configNix config) `shouldBe` trueOnNonWindows + config.configNix.nixEnable `shouldBe` trueOnNonWindows describe "--no-nix given on command line" $ it "sees that the nix shell is not enabled" $ loadConfig' (parseOpts ["--no-nix"]) $ \config -> - nixEnable (configNix config) `shouldBe` False + config.configNix.nixEnable `shouldBe` False describe "--no-nix-pure given on command line" $ it "sees that the nix shell is not enabled" $ loadConfig' (parseOpts ["--no-nix-pure"]) $ \config -> - nixEnable (configNix config) `shouldBe` False + config.configNix.nixEnable `shouldBe` False describe "nix enabled in config file" $ around_ (withStackDotYaml sampleConfigNixEnabled) $ do it "sees that the nix shell is enabled" $ loadConfig' mempty $ \config -> - nixEnable (configNix config) `shouldBe` trueOnNonWindows + config.configNix.nixEnable `shouldBe` trueOnNonWindows describe "--no-nix given on command line" $ it "sees that the nix shell is not enabled" $ loadConfig' (parseOpts ["--no-nix"]) $ \config -> - nixEnable (configNix config) `shouldBe` False + config.configNix.nixEnable `shouldBe` False describe "--nix-pure given on command line" $ it "sees that the nix shell is enabled" $ loadConfig' (parseOpts ["--nix-pure"]) $ \config -> - nixEnable (configNix config) `shouldBe` trueOnNonWindows + config.configNix.nixEnable `shouldBe` trueOnNonWindows describe "--no-nix-pure given on command line" $ it "sees that the nix shell is enabled" $ loadConfig' (parseOpts ["--no-nix-pure"]) $ \config -> - nixEnable (configNix config) `shouldBe` trueOnNonWindows + config.configNix.nixEnable `shouldBe` trueOnNonWindows it "sees that the only package asked for is glpk and asks for the correct GHC derivation" $ loadConfig' mempty $ \config -> do - nixPackages (configNix config) `shouldBe` ["glpk"] + config.configNix.nixPackages `shouldBe` ["glpk"] v <- parseVersionThrowing "9.0.2" ghc <- either throwIO pure $ nixCompiler (WCGhc v) ghc `shouldBe` "haskell.compiler.ghc902"