/*
 * sbt
 * Copyright 2023, Scala center
 * Copyright 2011 - 2022, Lightbend, Inc.
 * Copyright 2008 - 2010, Mark Harrah
 * Licensed under Apache License 2.0 (see LICENSE)
 */

package sbt

import java.nio.file.Path as NioPath
import java.io.File
import java.net.URI
import lmcoursier.definitions.{ CacheLogger, ModuleMatchers, Reconciliation }
import lmcoursier.{ CoursierConfiguration, FallbackDependency }
import org.apache.ivy.core.module.descriptor.ModuleDescriptor
import org.apache.ivy.core.module.id.ModuleRevisionId
import sbt.Def.*
import sbt.KeyRanks.*
import sbt.internal.InMemoryCacheStore.CacheStoreFactoryFactory
import sbt.internal.*
import sbt.internal.bsp.*
import sbt.internal.inc.ScalaInstance
import sbt.internal.librarymanagement.{ CompatibilityWarningOptions, IvySbt }
import sbt.internal.librarymanagement.ivy.{ IvyConfiguration, UpdateOptions }
import sbt.internal.server.BuildServerProtocol.BspFullWorkspace
import sbt.internal.server.{ BspCompileTask, BuildServerReporter, ServerHandler }
import sbt.internal.util.{ AttributeKey, ProgressState, SourcePosition }
import sbt.internal.util.StringAttributeKey
import sbt.internal.worker.{ ClientJobParams, ScalaInstanceConfig }
import sbt.io.*
import sbt.librarymanagement.Configurations.CompilerPlugin
import sbt.librarymanagement.LibraryManagementCodec.*
import sbt.librarymanagement.*
import sbt.nio.file.Glob
import sbt.protocol.testing.TestResult
import sbt.testing.Framework
import sbt.util.{ ActionCacheStore, Digest, Level, Logger, LoggerContext }
import xsbti.{ HashedVirtualFileRef, VirtualFile, VirtualFileRef }
import xsbti.compile.*
import xsbti.compile.analysis.ReadStamps

import scala.concurrent.duration.{ Duration, FiniteDuration }
import scala.xml.{ NodeSeq, Node as XNode }


// format: off

object Keys {
  // Normally we prefer concrete datatype like Vector, but due to ++= implicits and for backward compatibility,
  // for keys we should stick to using Seq.

  val TraceValues = "-1 to disable, 0 for up to the first sbt frame, or a positive number to set the maximum number of frames shown."

  // logging
  val logLevel = SettingKey(BasicKeys.logLevel).withRank(ASetting)
  val persistLogLevel = settingKey[Level.Value]("The amount of logging sent to a file for persistence.").withRank(CSetting)
  val traceLevel = settingKey[Int]("The amount of a stack trace displayed.  " + TraceValues).withRank(ASetting)
  val persistTraceLevel = settingKey[Int]("The amount of stack trace persisted.").withRank(CSetting)
  val showSuccess = settingKey[Boolean]("If true, displays a success message after running a command successfully.").withRank(CSetting)
  val showTiming = settingKey[Boolean]("If true, the command success message includes the completion time.").withRank(CSetting)
  val timingFormat = settingKey[java.text.DateFormat]("The format used for displaying the completion time.").withRank(CSetting)
  @transient
  val extraAppenders = settingKey[AppenderSupplier]("A function that provides additional loggers for a given setting.").withRank(DSetting)
  @deprecated("will be removed", "2.0.0")
  val useLog4J = settingKey[Boolean]("Toggles whether or not to use log4j for sbt internal loggers.").withRank(Invisible)
  val logManager = settingKey[LogManager]("The log manager, which creates Loggers for different contexts.").withRank(DSetting)
  private[sbt] val loggerContext = AttributeKey[LoggerContext]("sbt-logger-context", "The logger config which creates Loggers for different contexts.", Int.MaxValue)
  val logBuffered = settingKey[Boolean]("True if logging should be buffered until work completes.").withRank(CSetting)
  val sLog = settingKey[Logger]("Logger usable by settings during project loading.").withRank(CSetting)
  val serverLog = taskKey[Unit]("A dummy task to set server log level using Global / serverLog / logLevel.").withRank(CTask)
  val canonicalInput = settingKey[Boolean]("Toggles whether a task should use canonical input (line buffered with echo) or raw input").withRank(DSetting)
  val echoInput = settingKey[Boolean]("Toggles whether a task should echo user input").withRank(DSetting)
  val terminal = taskKey[Terminal]("The Terminal associated with a task").withRank(DTask)
  private[sbt] val terminalKey = AttributeKey[Terminal]("terminal-key", Invisible)

  // Project keys
  val autoGeneratedProject = settingKey[Boolean]("If it exists, represents that the project (and name) were automatically created, rather than user specified.").withRank(DSetting)
  val projectCommand = AttributeKey[Boolean]("projectCommand", "Marks Commands that were registered for the current Project.", Invisible)
  val sessionSettings = AttributeKey[SessionSettings]("sessionSettings", "Tracks current build, project, and setting modifications.", DSetting)
  val stateBuildStructure = AttributeKey[BuildStructure]("stateBuildStructure", "Data structure containing all information about the build definition.", BSetting)
  val buildStructure = taskKey[BuildStructure]("Provides access to the build structure, settings, and streams manager.").withRank(DTask)
  val loadedBuild = settingKey[LoadedBuild]("Provides access to the loaded project structure.  This is the information available before settings are evaluated.").withRank(DSetting)
  val buildDependencies = settingKey[BuildDependencies]("Definitive source of inter-project dependencies for compilation and dependency management.\n\tThis is populated by default by the dependencies declared on Project instances, but may be modified.\n\tThe main restriction is that new builds may not be introduced.").withRank(DSetting)
  val appConfiguration = settingKey[xsbti.AppConfiguration]("Provides access to the launched sbt configuration, including the ScalaProvider, Launcher, and GlobalLock.").withRank(DSetting)
  val thisProject = settingKey[ResolvedProject]("Provides the current project for the referencing scope.").withRank(CSetting)

  @transient
  val thisProjectRef = settingKey[ProjectRef]("Provides a fully-resolved reference to the current project for the referencing scope.").withRank(CSetting)
  val configurationStr = StringAttributeKey("configuration")

  @transient
  val configuration = settingKey[Configuration]("Provides the current configuration of the referencing scope.").withRank(CSetting)
  val commands = settingKey[Seq[Command]]("Defines commands to be registered when this project or build is the current selected one.").withRank(CSetting)
  val initialize = settingKey[Unit]("A convenience setting for performing side-effects during initialization.").withRank(BSetting)
  val onLoad = settingKey[State => State]("Transformation to apply to the build state when the build is loaded.").withRank(DSetting)
  val onUnload = settingKey[State => State]("Transformation to apply to the build state when the build is unloaded.").withRank(DSetting)
  val onLoadMessage = settingKey[String]("Message to display when the project is loaded.").withRank(DSetting)
  val transformState = AttributeKey[State => State]("transformState", "State transformation to apply after tasks run.", DSetting)

  val onComplete = Def.onComplete //  settingKey[() => Unit]("Hook to run when task evaluation completes.  The type of this setting is subject to change, pending the resolution of SI-2915.").withRank(DSetting)

  // Project Matrix
  val virtualAxes = settingKey[Seq[VirtualAxis]]("Virtual axes for the project")
  val projectMatrixBaseDirectory = settingKey[File]("Base directory of the current project matrix")

  // Command keys
  val historyPath = SettingKey(BasicKeys.historyPath)
  val shellPrompt = SettingKey(BasicKeys.shellPrompt)
  val colorShellPrompt = SettingKey(BasicKeys.colorShellPrompt)
  val autoStartServer = SettingKey(BasicKeys.autoStartServer)
  val serverPort = SettingKey(BasicKeys.serverPort)
  val serverHost = SettingKey(BasicKeys.serverHost)
  val serverAuthentication = SettingKey(BasicKeys.serverAuthentication)
  val serverConnectionType = SettingKey(BasicKeys.serverConnectionType)
  val serverIdleTimeout = SettingKey(BasicKeys.serverIdleTimeout)
  val windowsServerSecurityLevel = SettingKey(BasicKeys.windowsServerSecurityLevel)
  val serverUseJni = SettingKey(BasicKeys.serverUseJni)
  val fullServerHandlers = SettingKey(BasicKeys.fullServerHandlers)
  val serverHandlers = settingKey[Seq[ServerHandler]]("User-defined server handlers.")
  val cacheStores = settingKey[Seq[ActionCacheStore]]("Cache backends")
  @transient
  val remoteCache = settingKey[Option[URI]]("URI of the remote cache")
  @transient
  val remoteCacheTlsCertificate = settingKey[Option[File]]("Path to a TLS certificate (*.crt) that is trusted to sign server certificates")
  @transient
  val remoteCacheTlsClientCertificate = settingKey[Option[File]]("Path to a TLS client certificate *.crt used with remoteCacheTlsClientKey ")
  @transient
  val remoteCacheTlsClientKey = settingKey[Option[File]]("Path to a TLS client key *.pem used with remoteCacheTlsClientCertificate")
  @transient
  val remoteCacheHeaders = settingKey[Seq[String]]("List of key=value headers to be sent to the remote cache.")
  val rootOutputDirectory = SettingKey(BasicKeys.rootOutputDirectory)

  // val analysis = AttributeKey[CompileAnalysis]("analysis", "Analysis of compilation, including dependencies and generated outputs.", DSetting)
  val analysis = StringAttributeKey("analysis")


  val suppressSbtShellNotification = settingKey[Boolean]("""True to suppress the "Executing in batch mode.." message.""").withRank(CSetting)
  val pollInterval = settingKey[FiniteDuration]("Interval between checks for modified sources by the continuous execution command.").withRank(BMinusSetting)
  val watchAntiEntropy = settingKey[FiniteDuration]("Duration for which the watch EventMonitor will ignore events for a file after that file has triggered a build.").withRank(BMinusSetting)
  val watchService = settingKey[() => WatchService]("Service to use to monitor file system changes.").withRank(BMinusSetting).withRank(DSetting)

  // Deprecated watch apis
  val watchSources = taskKey[Seq[Watched.WatchSource]]("Defines the sources in this project for continuous execution to watch for changes.").withRank(BMinusSetting)

  // Path Keys
  val baseDirectory = settingKey[File]("The base directory.  Depending on the scope, this is the base directory for the build, project, configuration, or task.").withRank(AMinusSetting)

  @transient
  val target = settingKey[File]("Main directory for files generated by the build.").withRank(AMinusSetting)
  val crossTarget = settingKey[File]("Main directory for files generated by the build that are cross-built.").withRank(BSetting)

  // Source paths
  val sourceDirectory = settingKey[File]("Default directory containing sources.").withRank(AMinusSetting)
  val sourceManaged = settingKey[File]("Default directory for sources generated by the build.").withRank(BPlusSetting)
  val scalaSource = settingKey[File]("Default Scala source directory.").withRank(ASetting)
  val javaSource = settingKey[File]("Default Java source directory.").withRank(ASetting)
  val sourceDirectories = settingKey[Seq[File]]("List of all source directories, both managed and unmanaged.").withRank(AMinusSetting)
  val unmanagedSourceDirectories = settingKey[Seq[File]]("Unmanaged source directories, which contain manually created sources.").withRank(ASetting)
  @transient
  val unmanagedSources = taskKey[Seq[File]]("Unmanaged sources, which are manually created.").withRank(DTask)
  val unmanagedSourcesVF = taskKey[Vector[HashedVirtualFileRef]]("Unmanaged sources, which are manually created.").withRank(BPlusTask)
  val managedSourceDirectories = settingKey[Seq[File]]("Managed source directories, which contain sources generated by the build.").withRank(BSetting)
  @transient
  val managedSources = taskKey[Seq[File]]("Sources generated by the build.").withRank(DTask)
  val managedSourcesVF = taskKey[Vector[HashedVirtualFileRef]]("Sources generated by the build.").withRank(BTask)
  @transient
  val sources = taskKey[Seq[File]]("All sources, both managed and unmanaged.").withRank(DTask)
  val sourcesVF = taskKey[Vector[HashedVirtualFileRef]]("All sources, both managed and unmanaged.").withRank(BTask)
  val sourcesInBase = settingKey[Boolean]("If true, sources from the project's base directory are included as main sources.")

  // Filters
  val includeFilter = settingKey[FileFilter]("Filter for including sources and resources files from default directories.").withRank(CSetting)
  val excludeFilter = settingKey[FileFilter]("Filter for excluding sources and resources files from default directories.").withRank(CSetting)

  // Resource paths
  val resourceDirectory = settingKey[File]("Default unmanaged resource directory, used for user-defined resources.").withRank(ASetting)
  val resourceManaged = settingKey[File]("Default managed resource directory, used when generating resources.").withRank(BSetting)
  val unmanagedResourceDirectories = settingKey[Seq[File]]("Unmanaged resource directories, containing resources manually created by the user.").withRank(AMinusSetting)
  @transient
  val unmanagedResources = taskKey[Seq[File]]("Unmanaged resources, which are manually created.").withRank(DTask)
  val unmanagedResourcesVF = taskKey[Vector[HashedVirtualFileRef]]("Unmanaged resources, which are manually created.").withRank(BPlusTask)
  val managedResourceDirectories = settingKey[Seq[File]]("List of managed resource directories.").withRank(AMinusSetting)
  @transient
  val managedResources = taskKey[Seq[File]]("Resources generated by the build.").withRank(DTask)
  val managedResourcesVF = taskKey[Vector[HashedVirtualFileRef]]("Resources generated by the build.").withRank(BTask)
  val resourceDirectories = settingKey[Seq[File]]("List of all resource directories, both managed and unmanaged.").withRank(BPlusSetting)
  @transient
  val resources = taskKey[Seq[File]]("All resource files, both managed and unmanaged.").withRank(DTask)
  val resourcesVF = taskKey[Vector[HashedVirtualFileRef]]("All resource files, both managed and unmanaged.").withRank(BTask)
  private[sbt] val resourceDigests = taskKey[Seq[Digest]]("All resource files, both managed and unmanaged.").withRank(BTask)

  // Output paths
  @transient
  val classDirectory = settingKey[File]("Directory for compiled classes and copied resources.").withRank(AMinusSetting)

  @transient
  val earlyOutput = settingKey[VirtualFile]("JAR file for pickles used for build pipelining")
  val backendOutput = settingKey[VirtualFile]("Output directory of the compiler backend")

  @transient
  val cleanFiles = taskKey[Seq[File]]("The files to recursively delete during a clean.").withRank(BSetting)
  val cleanKeepFiles = settingKey[Seq[File]]("Files or directories to keep during a clean. Must be direct children of target.").withRank(CSetting)
  val cleanKeepGlobs = settingKey[Seq[Glob]]("Globs to keep during a clean. Must be direct children of target.").withRank(CSetting)
  val crossPaths = settingKey[Boolean]("If true, enables cross paths, which distinguish input and output directories for cross-building.").withRank(ASetting)
  val taskTemporaryDirectory = settingKey[File]("Directory used for temporary files for tasks that is deleted after each task execution.").withRank(DSetting)

  // Generators
  val sourceGenerators = settingKey[Seq[Task[Seq[File]]]]("List of tasks that generate sources.").withRank(CSetting)
  val resourceGenerators = settingKey[Seq[Task[Seq[File]]]]("List of tasks that generate resources.").withRank(CSetting)

  // compile/doc keys
  val autoCompilerPlugins = settingKey[Boolean]("If true, enables automatically generating -Xplugin arguments to the compiler based on the classpath for the " + CompilerPlugin.name + " configuration.").withRank(AMinusSetting)
  val maxErrors = settingKey[Int]("The maximum number of errors, such as compile errors, to list.").withRank(ASetting)
  val scalacOptions = taskKey[Seq[String]]("Options for the Scala compiler.").withRank(BPlusTask)
  val javacOptions = taskKey[Seq[String]]("Options for the Java compiler.").withRank(BPlusTask)
  val incOptions = taskKey[IncOptions]("Options for the incremental compiler.").withRank(BTask)
  val extraIncOptions = taskKey[Seq[(String, String)]]("Extra options for the incremental compiler").withRank(CTask)
  val compileOrder = settingKey[CompileOrder]("Configures the order in which Java and sources within a single compilation are compiled.  Valid values are: JavaThenScala, ScalaThenJava, or Mixed.").withRank(BPlusSetting)
  val initialCommands = settingKey[String]("Initial commands to execute when starting up the Scala interpreter.").withRank(AMinusSetting)
  val cleanupCommands = settingKey[String]("Commands to execute before the Scala interpreter exits.").withRank(BMinusSetting)
  val asciiGraphWidth = settingKey[Int]("Determines maximum width of the settings graph in ASCII mode").withRank(AMinusSetting)
  val compileOptions = taskKey[CompileOptions]("Collects basic options to configure compilers").withRank(DTask)

  @transient
  val compileInputs = taskKey[Inputs]("Collects all inputs needed for compilation.").withRank(DTask)
  val compileInputs2 = taskKey[CompileInputs2]("")
  val scalaHome = settingKey[Option[File]]("If Some, defines the local Scala installation to use for compilation, running, and testing.").withRank(ASetting)
  @transient
  val scalaInstance = taskKey[ScalaInstance]("Defines the Scala instance to use for compilation, running, and testing.").withRank(DTask)
  @transient
  val scalaInstanceConfig = taskKey[ScalaInstanceConfig]("Defines the Scala instance configuration.").withRank(DTask)
  val scalaOrganization = settingKey[String]("Organization/group ID of the Scala used in the project. Default value is 'org.scala-lang'. This is an advanced setting used for clones of the Scala Language. It should be disregarded in standard use cases.").withRank(CSetting)
  val scalaVersion = settingKey[String]("The version of Scala used for building.").withRank(APlusSetting)
  val scalaDynVersion = taskKey[String]("Resolves dynamic Scala version strings like '3-latest.candidate' to concrete versions.").withRank(DSetting)
  val scalaBinaryVersion = settingKey[String]("The Scala version substring describing binary compatibility.").withRank(BPlusSetting)
  val scalaEarlyVersion = settingKey[String]("The Scala version substring describing the binary compatibility, except for prereleases it returns the binary version of the release.").withRank(DSetting)
  val crossScalaVersions = settingKey[Seq[String]]("The versions of Scala used when cross-building.").withRank(BPlusSetting)
  val crossVersion = settingKey[CrossVersion]("Configures handling of the Scala version when cross-building.").withRank(CSetting)
  val platform = settingKey[String]("Configures the default suffix to be used for %% operator.").withRank(CSetting)
  val classpathOptions = settingKey[ClasspathOptions]("Configures handling of Scala classpaths.").withRank(DSetting)
  val discoveredSbtPlugins = taskKey[PluginDiscovery.DiscoveredNames]("The names of sbt plugin-related modules (modules that extend Build, Plugin, AutoPlugin) defined by this project.").withRank(CTask)
  val sbtPlugin = settingKey[Boolean]("If true, enables adding sbt as a dependency and auto-generation of the plugin descriptor file.").withRank(BMinusSetting)
  val isMetaBuild = settingKey[Boolean]("If true, this is a metabuild, a project inside project/ directory, and sbt is added to the classpath.").withRank(DSetting)
  val reresolveSbtArtifacts = settingKey[Boolean]("If true, include sbt into the metabuild dependency graph. Otherwise reuse the artifacts resolved by the launcher on startup.").withRank(DSetting)
  val pluginCrossBuild = taskKey[Unit]("Dummy task to scope `pluginCrossBuild / sbtVersion`, which gets used for plugin compilation.")
  val crossSbtVersions = settingKey[Seq[String]]("The versions of Sbt used when cross-building an sbt plugin.")
  val printWarnings = taskKey[Unit]("Shows warnings from compilation, including ones that weren't printed initially.").withRank(BPlusTask)
  val fileInputOptions = settingKey[Seq[String]]("Options that take file input, which may invalidate the cache.").withRank(CSetting)
  val scalaCompilerBridgeBin = taskKey[Seq[HashedVirtualFileRef]]("Optionally, the jar of the compiler bridge. When not None, this takes precedence over scalaCompilerBridgeSource").withRank(DTask)
  val scalaCompilerBridgeSource = settingKey[ModuleID]("Configures the module ID of the sources of the compiler bridge when scalaCompilerBridgeBinaryJar is None").withRank(CSetting)
  val scalaCompilerBridgeScope = taskKey[Unit]("The compiler bridge scope.").withRank(DTask)
  @transient
  val scalaCompilerBridgeJars = taskKey[Seq[HashedVirtualFileRef]]("The compiler bridge JAR.").withRank(DTask)
  val scalaArtifacts = settingKey[Seq[String]]("Configures the list of artifacts which should match the Scala binary version").withRank(CSetting)
  val crossJavaVersions = settingKey[Seq[String]]("The java versions used during JDK cross testing").withRank(BPlusSetting)
  val semanticdbEnabled = settingKey[Boolean]("Enables SemanticDB Scalac plugin").withRank(CSetting)
  val semanticdbCompilerPlugin = settingKey[ModuleID]("SemanticDB Scalac plugin").withRank(CSetting)
  val semanticdbVersion = settingKey[String]("SemanticDB version").withRank(CSetting)
  val semanticdbIncludeInJar = settingKey[Boolean]("Include *.semanticdb files in published artifacts").withRank(CSetting)
  val semanticdbTargetRoot = settingKey[File]("The output directory to produce META-INF/semanticdb/**/*.semanticdb files").withRank(CSetting)
  val semanticdbOptions = settingKey[Seq[String]]("The Scalac options introduced for SemanticDB").withRank(CSetting)

  val clean = taskKey[Unit]("Deletes files produced by the build, such as generated sources, compiled classes, and task caches.").withRank(APlusTask)
  val console = taskKey[Unit]("Starts the Scala interpreter with the project classes on the classpath.").withRank(APlusTask)
  val consoleQuick = TaskKey[Unit]("consoleQuick", "Starts the Scala interpreter with the project dependencies on the classpath.", ATask, console)
  val consoleProject = taskKey[Unit]("Starts the Scala interpreter with the sbt and the build definition on the classpath and useful imports.").withRank(AMinusTask)
  val compile = taskKey[CompileAnalysis]("Compiles sources.").withRank(APlusTask)
  val manipulateBytecode = taskKey[CompileResult]("Manipulates generated bytecode").withRank(BTask)
  val compileIncremental = taskKey[(Boolean, VirtualFileRef, HashedVirtualFileRef)]("Actually runs the incremental compilation").withRank(DTask)
  val previousCompile = taskKey[PreviousResult]("Read the incremental compiler analysis from disk").withRank(DTask)
  @transient
  val tastyFiles = taskKey[Seq[File]]("Returns the TASTy files produced by compilation").withRank(DTask)
  val tastyFilesVF = taskKey[Seq[HashedVirtualFileRef]]("Returns the TASTy files produced by compilation").withRank(DTask)
  private[sbt] val compileScalaBackend = taskKey[CompileResult]("Compiles only Scala sources if pipelining is enabled. Compiles both Scala and Java sources otherwise").withRank(Invisible)
  private[sbt] val compileEarly = taskKey[CompileAnalysis]("Compiles only Scala sources if pipelining is enabled, and produce an early output (pickle JAR)").withRank(Invisible)

  @transient
  private[sbt] val earlyOutputPing = taskKey[PromiseWrap[Boolean]]("When pipelining is enabled, this returns true when early output (pickle JAR) is created; false otherwise").withRank(Invisible)
  private[sbt] val compileJava = taskKey[CompileResult]("Compiles only Java sources (called only for pipelining)").withRank(Invisible)
  private[sbt] val compileSplit = taskKey[CompileResult]("When pipelining is enabled, compile Scala then Java; otherwise compile both").withRank(Invisible)

  val compileProgress = taskKey[CompileProgress]("Callback used by the compiler to report phase progress")
  val compilers = taskKey[Compilers]("Defines the Scala and Java compilers to use for compilation.").withRank(DTask)
  val compileAnalysisFilename = taskKey[String]("Defines the filename used for compileAnalysisFile.").withRank(DTask)
  val compileAnalysisTargetRoot = settingKey[File]("The output directory to produce Zinc Analysis files").withRank(DSetting)
  val earlyCompileAnalysisTargetRoot = settingKey[File]("The output directory to produce Zinc Analysis files").withRank(DSetting)
  @transient
  val compileAnalysisFile = taskKey[File]("Zinc analysis storage.").withRank(DSetting)
  @transient
  val earlyCompileAnalysisFile = taskKey[File]("Zinc analysis storage for early compilation").withRank(DSetting)

  @transient
  val compileIncSetup = taskKey[Setup]("Configures aspects of incremental compilation.").withRank(DTask)
  val compilerCache = taskKey[GlobalsCache]("Cache of scala.tools.nsc.Global instances.  This should typically be cached so that it isn't recreated every task run.").withRank(DTask)
  val stateCompilerCache = AttributeKey[GlobalsCache]("stateCompilerCache", "Internal use: Global cache.")
  @transient
  val classpathEntryDefinesClass = taskKey[File => DefinesClass]("Internal use: provides a function that determines whether the provided file contains a given class.").withRank(Invisible)
  private[sbt] val classpathDefinesClassCache = settingKey[VirtualFileValueCache[DefinesClass]]("Internal use: a cache of jar classpath entries that persists across command evaluations.").withRank(Invisible)
  val persistJarClasspath = settingKey[Boolean]("Toggles whether or not to cache jar classpath entries between command evaluations")
  val classpathEntryDefinesClassVF = taskKey[VirtualFile => DefinesClass]("Internal use: provides a function that determines whether the provided file contains a given class.").withRank(Invisible)
  @transient
  val doc = taskKey[File]("Generates API documentation.").withRank(AMinusTask)
  val docVF = taskKey[HashedVirtualFileRef]("Generates API documentation.").withRank(AMinusTask)
  @transient
  val copyResources = taskKey[Seq[(File, File)]]("Copies resources to the output directory.").withRank(AMinusTask)
  val aggregate = settingKey[Boolean]("Configures task aggregation.").withRank(BMinusSetting)
  val sourcePositionMappers = taskKey[Seq[xsbti.Position => Option[xsbti.Position]]]("Maps positions in generated source files to the original source it was generated from").withRank(DTask)
  private[sbt] val externalHooks = taskKey[ExternalHooks]("The external hooks used by zinc.")
  val zincCompilationListeners = settingKey[Seq[RunProfiler]]("Listeners that receive information about incremental compiler decisions.").withRank(DSetting)
  val auxiliaryClassFiles = taskKey[Seq[AuxiliaryClassFiles]]("The auxiliary class files that must be managed by Zinc (for instance the TASTy files)")

  @transient
  val fileConverter = SettingKey(BasicKeys.fileConverter)
  val allowMachinePath = settingKey[Boolean]("Allow machine-specific paths during conversion.")
  val reportAbsolutePath = settingKey[Boolean]("Report absolute paths during compilation.")
  val rootPaths = settingKey[Map[String, NioPath]]("The root paths used to abstract machine-specific paths.")
  private[sbt] val timeWrappedStamper = settingKey[ReadStamps]("The stamper to create timestamp or hash.")
  private[sbt] val reusableStamper = taskKey[ReadStamps]("The stamper can be reused across subprojects and sessions.")

  // package keys
  val packageBin = taskKey[HashedVirtualFileRef]("Produces a main artifact, such as a binary jar.").withRank(ATask)
  val `package` = taskKey[HashedVirtualFileRef]("Produces the main artifact, such as a binary jar.  This is typically an alias for the task that actually does the packaging.").withRank(APlusTask)
  val packageDoc = taskKey[HashedVirtualFileRef]("Produces a documentation artifact, such as a jar containing API documentation.").withRank(AMinusTask)
  val packageSrc = taskKey[HashedVirtualFileRef]("Produces a source artifact, such as a jar containing sources and resources.").withRank(AMinusTask)

  val packageOptions = taskKey[Seq[PackageOption]]("Options for packaging.").withRank(BTask)
  val packageTimestamp = settingKey[Option[Long]]("Overwrites timestamps in JAR file to make the build reproducible; None keeps the existing timestamps (useful for web resources)").withRank(CSetting)
  val packageConfiguration = taskKey[Pkg.Configuration]("Collects all inputs needed for packaging.").withRank(DTask)
  val artifactPath = settingKey[VirtualFileRef]("The location of a generated artifact.").withRank(BPlusSetting)
  val artifactStr = StringAttributeKey("artifact")
  val artifact = settingKey[Artifact]("Describes an artifact.").withRank(BMinusSetting)
  val artifactClassifier = settingKey[Option[String]]("Sets the classifier used by the default artifact definition.").withRank(BSetting)
  val artifactName = settingKey[(ScalaVersion, ModuleID, Artifact) => String]("Function that produces the artifact name from its definition.").withRank(CSetting)

  @transient
  val mappings = taskKey[Seq[(HashedVirtualFileRef, String)]]("Defines the mappings from a file to a path, used by packaging, for example.").withRank(BTask)

  @transient
  val fileMappings = taskKey[Seq[(File, File)]]("Defines the mappings from a file to a file, used for copying files, for example.").withRank(BMinusTask)

  // Run Keys
  val selectMainClass = taskKey[Option[String]]("Selects the main class to run.").withRank(BMinusTask)
  val mainClass = taskKey[Option[String]]("Defines the main class for packaging or running.").withRank(BPlusTask)
  val run = inputKey[Unit | ClientJobParams]("Runs a main class, passing along arguments provided on the command line.").withRank(APlusTask)
  val runMain = inputKey[Unit | ClientJobParams]("Runs the main class selected by the first argument, passing the remaining arguments to the main method.").withRank(ATask)
  val discoveredMainClasses = taskKey[Seq[String]]("Auto-detects main classes.").withRank(BMinusTask)
  val runner = taskKey[ScalaRun]("Implementation used to run a main class.").withRank(DTask)
  val trapExit = settingKey[Boolean]("If true, enables exit trapping and thread management for 'run'-like tasks. This was removed in sbt 1.6.0 due to JDK 17 deprecating Security Manager.").withRank(CSetting)

  val fork = settingKey[Boolean]("If true, forks a new JVM when running.  If false, runs in the same JVM as the build.").withRank(ASetting)
  val forkOptions = taskKey[ForkOptions]("Configures JVM forking.").withRank(DSetting)
  val outputStrategy = settingKey[Option[sbt.OutputStrategy]]("Selects how to log output when running a main class.").withRank(DSetting)
  val connectInput = settingKey[Boolean]("If true, connects standard input when running a main class forked.").withRank(CSetting)
  val javaHome = settingKey[Option[File]]("Selects the Java installation used for compiling and forking.  If None, uses the Java installation running the build.").withRank(ASetting)
  val discoveredJavaHomes = settingKey[Map[String, File]]("Discovered Java home directories")
  val javaHomes = settingKey[Map[String, File]]("The user-defined additional Java home directories")
  val fullJavaHomes = settingKey[Map[String, File]]("Combines discoveredJavaHomes and custom javaHomes.").withRank(CTask)
  val clientSide = settingKey[Boolean]("If true, takes the action on the client-side")

  val javaOptions = taskKey[Seq[String]]("Options passed to a new JVM when forking.").withRank(BPlusTask)
  val envVars = taskKey[Map[String, String]]("Environment variables used when forking a new JVM").withRank(BTask)

  val bgJobServiceDirectory = settingKey[File]("The directory for temporary files used by background jobs.")
  val bgJobService = settingKey[BackgroundJobService]("Job manager used to run background jobs.")
  val bgList = taskKey[Seq[JobHandle]]("List running background jobs.")
  val ps = taskKey[Seq[JobHandle]]("bgList variant that displays on the log.")
  val bgStop = inputKey[Unit]("Stop a background job by providing its ID.")
  val bgWaitFor = inputKey[Unit]("Wait for a background job to finish by providing its ID.")
  val bgRun = inputKey[JobHandle]("Start an application's default main class as a background job")
  val fgRun = inputKey[Unit]("Start an application's default main class as a foreground job")
  val bgRunMain = inputKey[JobHandle]("Start a provided main class as a background job")
  val fgRunMain = inputKey[Unit]("Start a provided main class as a foreground job")
  val bgCopyClasspath = settingKey[Boolean]("Copies classpath on bgRun to prevent conflict.")
  val bgHashClasspath = settingKey[Boolean]("Toggles whether to use a hash or the last modified time to stamp the classpath jars")
  val classLoaderLayeringStrategy = settingKey[ClassLoaderLayeringStrategy]("Creates the classloader layering strategy for the particular configuration.")

  // Test Keys
  val testLoader = taskKey[ClassLoader]("Provides the class loader used for testing.").withRank(DTask)
  val loadedTestFrameworks = taskKey[Map[TestFramework, Framework]]("Loads Framework definitions from the test loader.").withRank(DTask)
  @transient
  val definedTests = taskKey[Seq[TestDefinition]]("Provides the list of defined tests.").withRank(BMinusTask)
  val definedTestNames = taskKey[Seq[String]]("Provides the set of defined test names.").withRank(BMinusTask)
  val definedTestDigests = taskKey[Map[String, Digest]]("Provides a unique digest of defined tests.").withRank(DTask)
  val executeTests = taskKey[Tests.Output]("Executes all tests, producing a report.").withRank(CTask)
  val test = inputKey[TestResult]("Executes the tests that either failed before, were not run or whose transitive dependencies changed, among those provided as arguments.").withRank(ATask)
  val testFull = taskKey[TestResult]("Executes all tests.").withRank(APlusTask)
  val testOnly = inputKey[TestResult]("Executes the tests provided as arguments or all tests if no arguments are provided.").withRank(ATask)
  val testSelected = inputKey[TestResult]("Executes the tests provided as arguments or all tests if no arguments are provided. Used internally by testOnly command.").withRank(BMinusTask)
  val testQuick = inputKey[TestResult]("Alias for test.").withRank(CTask)
  @transient
  val testOptions = taskKey[Seq[TestOption]]("Options for running tests.").withRank(BPlusTask)
  private[sbt] val testOptionDigests = taskKey[Seq[Digest]]("Digest for testOptions").withRank(DTask)
  val testFrameworks = settingKey[Seq[TestFramework]]("Registered, although not necessarily present, test frameworks.").withRank(CTask)

  @transient
  val testListeners = taskKey[Seq[TestReportListener]]("Defines test listeners.").withRank(DTask)
  val testForkedParallel = settingKey[Boolean]("Whether forked tests should be executed in parallel").withRank(CTask)
  val testForkedParallelism = settingKey[Option[Int]]("Maximum number of parallel test threads when using testForkedParallel. Defaults to the number of available processors.").withRank(CTask)
  val testExecution = taskKey[Tests.Execution]("Settings controlling test execution").withRank(DTask)
  val testFilter = taskKey[Seq[String] => Seq[String => Boolean]]("Filter controlling whether the test is executed").withRank(DTask)
  val testResultLogger = settingKey[TestResultLogger]("Logs results after a test task completes.").withRank(DTask)
  val testGrouping = taskKey[Seq[Tests.Group]]("Collects discovered tests into groups. Whether to fork and the options for forking are configurable on a per-group basis.").withRank(BMinusTask)
  val isModule = AttributeKey[Boolean]("isModule", "True if the target is a module.", DSetting)
  val extraTestDigests = taskKey[Seq[Digest]]("Extra digests that would invalidate test caching").withRank(DTask)

  // Classpath/Dependency Management Keys
  type Classpath = Def.Classpath

  val name = settingKey[String]("Project name.").withRank(APlusSetting)
  val normalizedName = settingKey[String]("Project name transformed from mixed case and spaces to lowercase and dash-separated.").withRank(BSetting)
  val description = settingKey[String]("Project description.").withRank(BSetting)
  val homepage = settingKey[Option[URI]]("Project homepage.").withRank(BSetting)
  val startYear = settingKey[Option[Int]]("Year in which the project started.").withRank(BMinusSetting)
  val licenses = settingKey[Seq[License]]("Project licenses as (name, url) pairs.").withRank(BMinusSetting)
  val organization = settingKey[String]("Organization/group ID.").withRank(APlusSetting)
  val organizationName = settingKey[String]("Organization full/formal name.").withRank(BMinusSetting)
  val organizationHomepage = settingKey[Option[URI]]("Organization homepage.").withRank(BMinusSetting)
  val developers = settingKey[List[Developer]]("List of developers implicated in the project").withRank(BMinusSetting)
  val apiURL = settingKey[Option[URI]]("Base URI for API documentation.").withRank(BMinusSetting)
  val entryApiURL = StringAttributeKey("entryApiURL") // , "Base URL for the API documentation for a classpath entry.")
  val apiMappings = taskKey[Map[HashedVirtualFileRef, URI]]("Mappings from classpath entry to API documentation base URL.").withRank(BMinusSetting)
  val autoAPIMappings = settingKey[Boolean]("If true, automatically manages mappings to the API doc URL.").withRank(BMinusSetting)
  val releaseNotesURL = settingKey[Option[URI]]("URL for release notes.").withRank(BMinusSetting)
  val scmInfo = settingKey[Option[ScmInfo]]("Basic SCM information for the project.").withRank(BMinusSetting)
  val projectInfo = settingKey[ModuleInfo]("Addition project information like formal name, homepage, licenses etc.").withRank(CSetting)
  val defaultConfiguration = settingKey[Option[Configuration]]("Defines the configuration used when none is specified for a dependency in ivyXML.").withRank(CSetting)

  @transient
  val products = taskKey[Seq[File]]("Build products that get packaged.").withRank(DTask)
  @transient
  val productDirectories = taskKey[Seq[File]]("Base directories of build products.").withRank(CTask)
  val exportJars = settingKey[Boolean]("Determines whether the exported classpath for this project contains classes (false) or a packaged jar (true).").withRank(BSetting)
  val exportedProducts = taskKey[Classpath]("Build products that go on the exported classpath.").withRank(CTask)
  val exportedProductsIfMissing = taskKey[Classpath]("Build products that go on the exported classpath if missing.").withRank(CTask)
  val exportedProductsNoTracking = taskKey[Classpath]("Just the exported classpath without triggering the compilation.").withRank(CTask)
  val unmanagedClasspath = taskKey[Classpath]("Classpath entries (deep) that are manually managed.").withRank(BPlusTask)
  val unmanagedJars = taskKey[Classpath]("Classpath entries for the current project (shallow) that are manually managed.").withRank(BPlusTask)
  val managedClasspath = taskKey[Classpath]("The classpath consisting of external, managed library dependencies.").withRank(BMinusTask)
  val internalDependencyClasspath = taskKey[Classpath]("The internal (inter-project) classpath.").withRank(CTask)
  val externalDependencyClasspath = taskKey[Classpath]("The classpath consisting of library dependencies, both managed and unmanaged.").withRank(BMinusTask)
  val dependencyClasspath = taskKey[Classpath]("The classpath consisting of internal and external, managed and unmanaged dependencies.").withRank(BPlusTask)
  val filteredDependencyClasspath = taskKey[Classpath]("The dependency classpath filtered by dependencyMode. Only affects compilation, not runtime classpaths.").withRank(BMinusTask)
  val dependencyPicklePath = taskKey[Classpath]("The classpath consisting of internal pickles and external, managed and unmanaged dependencies. This task is promise-blocked.")
  val internalDependencyPicklePath = taskKey[Classpath]("The internal (inter-project) pickles. This task is promise-blocked.")
  val fullClasspath = taskKey[Classpath]("The exported classpath, consisting of build products and unmanaged and managed, internal and external dependencies.").withRank(BPlusTask)
  val dependencyMode = settingKey[DependencyMode]("Controls which managed dependencies appear on the classpath: Transitive (all), Direct (only direct + scala-library), or PlusOne (direct + their immediate deps + scala-library).").withRank(BSetting)
  val trackInternalDependencies = settingKey[TrackLevel]("The level of tracking for the internal (inter-project) dependency.").withRank(BSetting)
  val exportToInternal = settingKey[TrackLevel]("The level of tracking for this project by the internal callers.").withRank(BSetting)
  val exportedProductJars = taskKey[Classpath]("Build products that go on the exported classpath as JARs.")
  val exportedProductJarsIfMissing = taskKey[Classpath]("Build products that go on the exported classpath as JARs if missing.")
  val exportedProductJarsNoTracking = taskKey[Classpath]("Just the exported classpath as JARs without triggering the compilation.")
  val exportedPickles = taskKey[Classpath]("Build products that go on the exported compilation classpath as JARs. Note this is promise-blocked.").withRank(DTask)
  val pickleProducts = taskKey[Seq[VirtualFile]]("Pickle JARs").withRank(DTask)
  val internalDependencyAsJars = taskKey[Classpath]("The internal (inter-project) classpath as JARs.")
  val dependencyClasspathAsJars = taskKey[Classpath]("The classpath consisting of internal and external, managed and unmanaged dependencies, all as JARs.")
  val fullClasspathAsJars = taskKey[Classpath]("The exported classpath, consisting of build products and unmanaged and managed, internal and external dependencies, all as JARs.")
  val internalDependencyConfigurations = settingKey[Seq[(ProjectRef, Set[String])]]("The project configurations that this configuration depends on")
  val closeClassLoaders = settingKey[Boolean]("Close classloaders in run and test when the task completes.").withRank(DSetting)
  val allowZombieClassLoaders = settingKey[Boolean]("Allow a classloader that has previously been closed by `run` or `test` to continue loading classes.")
  val localCacheDirectory = settingKey[File]("Operating system specific cache directory.")
  val localDigestCacheByteSize = SettingKey[Long](BasicKeys.localDigestCacheByteSize).withRank(DSetting)
  val cacheVersion = SettingKey[Long](BasicKeys.cacheVersion).withRank(BSetting)
  val usePipelining = settingKey[Boolean]("Use subproject pipelining for compilation.").withRank(BSetting)
  val exportPipelining = settingKey[Boolean]("Produce early output so downstream subprojects can do pipelining.").withRank(BSetting)

  // BSP keys
  val bspConfig = taskKey[Unit]("Create or update the BSP connection files").withRank(DSetting)
  val bspEnabled = SettingKey[Boolean](BasicKeys.bspEnabled)
  val bspSbtEnabled = settingKey[Boolean]("Should BSP export meta-targets for the SBT build itself?")

  @transient
  val bspTargetIdentifier = settingKey[BuildTargetIdentifier]("Build target identifier of a project and configuration.").withRank(DSetting)
  val bspWorkspace = settingKey[Map[BuildTargetIdentifier, Scope]]("Mapping of BSP build targets to sbt scopes").withRank(DSetting)
  private[sbt] val bspFullWorkspace = settingKey[BspFullWorkspace]("Mapping of BSP build targets to sbt scopes and meta-targets for the SBT build itself").withRank(DSetting)
  val bspInternalDependencyConfigurations = settingKey[Seq[(ProjectRef, Set[ConfigKey])]]("The project configurations that this configuration depends on, possibly transitively").withRank(DSetting)
  val bspWorkspaceBuildTargets = taskKey[Seq[BuildTarget]]("List all the BSP build targets").withRank(DTask)
  val bspBuildTarget = taskKey[BuildTarget]("Description of the BSP build targets").withRank(DTask)
  val bspBuildTargetSources = inputKey[Unit]("").withRank(DTask)
  val bspBuildTargetSourcesItem = taskKey[SourcesItem]("").withRank(DTask)
  val bspBuildTargetResources = inputKey[Unit]("").withRank(DTask)
  val bspBuildTargetResourcesItem = taskKey[ResourcesItem]("").withRank(DTask)
  val bspBuildTargetDependencySources = inputKey[Unit]("").withRank(DTask)
  val bspBuildTargetDependencySourcesItem = taskKey[DependencySourcesItem]("").withRank(DTask)
  val bspBuildTargetOutputPaths = inputKey[Unit]("").withRank(DTask)
  @transient
  val bspBuildTargetOutputPathsItem = taskKey[OutputPathsItem]("").withRank(DTask)
  val bspBuildTargetCompile = inputKey[Unit]("").withRank(DTask)
  val bspBuildTargetCompileItem = taskKey[Int]("").withRank(DTask)
  @transient private[sbt] val bspCompileTask = taskKey[BspCompileTask]("").withRank(DTask)
  val bspBuildTargetTest = inputKey[Unit]("Corresponds to buildTarget/test request").withRank(DTask)
  val bspBuildTargetRun = inputKey[Unit]("Corresponds to buildTarget/run request").withRank(DTask)
  val bspBuildTargetCleanCache = inputKey[Unit]("Corresponds to buildTarget/cleanCache request").withRank(DTask)
  val bspBuildTargetScalacOptions = inputKey[Unit]("").withRank(DTask)
  val bspBuildTargetScalacOptionsItem = taskKey[ScalacOptionsItem]("").withRank(DTask)
  val bspBuildTargetJavacOptions = inputKey[Unit]("Implementation of buildTarget/javacOptions").withRank(DTask)
  val bspBuildTargetJavacOptionsItem = taskKey[JavacOptionsItem]("Item of buildTarget/javacOptions").withRank(DTask)

  val bspBuildTargetJVMRunEnvironment = inputKey[Unit]("Implementation of buildTarget/jvmRunEnvironment").withRank(DTask)
  val bspBuildTargetJVMTestEnvironment = inputKey[Unit]("Implementation of buildTarget/jvmTestEnvironment").withRank(DTask)
  val bspBuildTargetJvmEnvironmentItem = taskKey[JvmEnvironmentItem]("Computes JVM environment item").withRank(DTask)

  val bspScalaTestClasses = inputKey[Unit]("Implementation of buildTarget/scalaTestClasses").withRank(DTask)
  val bspScalaTestClassesItem = taskKey[Seq[ScalaTestClassesItem]]("").withRank(DTask)
  val bspScalaMainClasses = inputKey[Unit]("Implementation of buildTarget/scalaMainClasses").withRank(DTask)
  val bspScalaMainClassesItem = taskKey[ScalaMainClassesItem]("").withRank(DTask)

  @transient
  val bspReporter = taskKey[BuildServerReporter]("").withRank(DTask)

  val csrCacheDirectory = settingKey[File]("Coursier cache directory. Uses -Dsbt.coursier.home or Coursier's default.").withRank(CSetting)
  val csrMavenProfiles = settingKey[Set[String]]("").withRank(CSetting)
  val csrConfiguration = taskKey[CoursierConfiguration]("General dependency management (Coursier) settings, such as the resolvers and options to use.").withRank(DTask)
  val csrProject = taskKey[lmcoursier.definitions.Project]("")
  val csrResolvers = taskKey[Seq[Resolver]]("")
  val csrRecursiveResolvers = taskKey[Seq[Resolver]]("Resolvers of the current project, plus those of all from its inter-dependency projects")
  val csrSbtResolvers = taskKey[Seq[Resolver]]("Resolvers used for sbt artifacts.")
  val csrInterProjectDependencies = taskKey[Seq[lmcoursier.definitions.Project]]("Projects the current project depends on, possibly transitively")
  val csrExtraProjects = taskKey[Seq[lmcoursier.definitions.Project]]("").withRank(CTask)
  val csrFallbackDependencies = taskKey[Seq[FallbackDependency]]("")
  val csrLogger = taskKey[Option[CacheLogger]]("")

  @transient
  val csrExtraCredentials = taskKey[Seq[lmcoursier.credentials.Credentials]]("")
  val csrPublications = taskKey[Seq[(lmcoursier.definitions.Configuration, lmcoursier.definitions.Publication)]]("")
  val csrReconciliations = settingKey[Seq[(ModuleMatchers, Reconciliation)]]("Strategy to reconcile version conflicts.")
  val csrSameVersions = settingKey[Seq[Set[InclExclRule]]]("Modules to keep at the same version.")
  val csrMavenDependencyOverride = settingKey[Boolean]("Enables Maven dependency override (bill of materials) support")
  val csrLocalArtifactsShouldBeCached =
    settingKey[Boolean]("When true, local file:// artifacts are copied to the cache directory.")

  val internalConfigurationMap = settingKey[Configuration => Configuration]("Maps configurations to the actual configuration used to define the classpath.").withRank(CSetting)
  val classpathConfiguration = taskKey[Configuration]("The configuration used to define the classpath.").withRank(CTask)
  val ivyConfiguration = taskKey[IvyConfiguration]("General dependency management (Ivy) settings, such as the resolvers and paths to use.").withRank(DTask)
  val ivyConfigurations = settingKey[Seq[Configuration]]("The defined configurations for dependency management.  This may be different from the configurations for Project settings.").withRank(BSetting)
  // This setting was created to work around the limitation of derived tasks not being able to use task-scoped task: ivyConfiguration in updateSbtClassifiers
  val bootIvyConfiguration = taskKey[IvyConfiguration]("General dependency management (Ivy) settings, configured to retrieve sbt's components.").withRank(DTask)
  val bootDependencyResolution = taskKey[DependencyResolution]("Dependency resolution to retrieve sbt's components.").withRank(CTask)
  val scalaCompilerBridgeDependencyResolution = taskKey[DependencyResolution]("Dependency resolution to retrieve the compiler bridge.").withRank(CTask)
  val moduleSettings = taskKey[ModuleSettings]("Module settings, which configure dependency management for a specific module, such as a project.").withRank(DTask)
  val unmanagedBase = settingKey[File]("The default directory for manually managed libraries.").withRank(ASetting)
  val updateConfiguration = settingKey[UpdateConfiguration]("Configuration for resolving and retrieving managed dependencies.").withRank(DSetting)
  val updateOptions = settingKey[UpdateOptions]("Options for resolving managed dependencies.").withRank(DSetting)

  @transient
  val unresolvedWarningConfiguration = taskKey[UnresolvedWarningConfiguration]("Configuration for unresolved dependency warning.").withRank(DTask)
  val dependencyPositions = taskKey[Map[ModuleID, SourcePosition]]("Source positions where the dependencies are defined.").withRank(DTask)

  @transient
  val dependencyResolution = taskKey[DependencyResolution]("Provides the sbt interface to dependency resolution.").withRank(CTask)
  val publisher = taskKey[Publisher]("Provides the sbt interface to publisher")
  val ivySbt = taskKey[IvySbt]("Provides the sbt interface to Ivy.").withRank(CTask)
  val ivyModule = taskKey[IvySbt#Module]("Provides the sbt interface to a configured Ivy module.").withRank(CTask)
  val updateCacheName = taskKey[String]("Defines the directory name used to store the update cache files (inside the streams cacheDirectory).").withRank(DTask)
  val update = taskKey[UpdateReport]("Resolves and optionally retrieves dependencies, producing a report.").withRank(ATask)
  val updateFull = taskKey[UpdateReport]("Resolves and optionally retrieves dependencies, producing a full report with callers.").withRank(CTask)
  val evicted = taskKey[EvictionWarning]("Display detailed eviction warnings.").withRank(CTask)
  val evictionWarningOptions = settingKey[EvictionWarningOptions]("Options on eviction warnings after resolving managed dependencies.").withRank(DSetting)
  val evictionErrorLevel = settingKey[Level.Value]("The log level for the detected eviction errors. Level.Error will throw an error.").withRank(DSetting)
  val assumedEvictionErrorLevel = settingKey[Level.Value]("The log level for the assumed eviction errors. Level.Error will throw an error.").withRank(DSetting)
  val assumedVersionScheme = settingKey[String]("The assumed version scheme of a Scala library when POM doesn't have versionScheme.").withRank(DSetting)
  val assumedVersionSchemeJava = settingKey[String]("The assumed version scheme of a Java library when POM doesn't have versionScheme.").withRank(DSetting)
  val transitiveUpdate = taskKey[Seq[UpdateReport]]("UpdateReports for the internal dependencies of this project.").withRank(DTask)
  val updateClassifiers = TaskKey[UpdateReport]("updateClassifiers", "Resolves and optionally retrieves classified artifacts, such as javadocs and sources, for dependency definitions, transitively.", BPlusTask, update)
  val transitiveClassifiers = settingKey[Seq[String]]("List of classifiers used for transitively obtaining extra artifacts for sbt or declared dependencies.").withRank(BSetting)
  val updateSbtClassifiers = TaskKey[UpdateReport]("updateSbtClassifiers", "Resolves and optionally retrieves classifiers, such as javadocs and sources, for sbt, transitively.", BPlusTask, updateClassifiers)
  @transient
  val dependencyLock = taskKey[File]("Generates a dependency lock file from the current resolution.").withRank(BTask)
  val dependencyLockCheck = taskKey[Unit]("Checks if the dependency lock file is up-to-date.").withRank(BTask)
  val dependencyLockFile = settingKey[File]("The location of the dependency lock file.").withRank(CSetting)
  val sourceArtifactTypes = settingKey[Seq[String]]("Ivy artifact types that correspond to source artifacts. Used by IDEs to resolve these resources.").withRank(BSetting)
  val docArtifactTypes = settingKey[Seq[String]]("Ivy artifact types that correspond to javadoc artifacts. Used by IDEs to resolve these resources.").withRank(BSetting)

  val publishConfiguration = taskKey[PublishConfiguration]("Configuration for publishing to a repository.").withRank(DTask)
  val publishLocalConfiguration = taskKey[PublishConfiguration]("Configuration for publishing to the local Ivy repository.").withRank(DTask)
  val publishM2Configuration = taskKey[PublishConfiguration]("Configuration for publishing to the local Maven repository.").withRank(DTask)
  val makePomConfiguration = settingKey[MakePomConfiguration]("Configuration for generating a pom.").withRank(DSetting)
  val makeIvyXmlConfiguration = taskKey[PublishConfiguration]("Configuration for generating ivy.xml.").withRank(DSetting)
  val makeIvyXmlLocalConfiguration = taskKey[PublishConfiguration]("Configuration for generating ivy.xml.").withRank(DSetting)
  val packagedArtifacts = taskKey[Map[Artifact, HashedVirtualFileRef]]("Packages all artifacts for publishing and maps the Artifact definition to the generated file.").withRank(CTask)
  val publishMavenStyle = settingKey[Boolean]("Configures whether to generate and publish a pom (true) or Ivy file (false).").withRank(BSetting)
  val sbtPluginPublishLegacyMavenStyle = settingKey[Boolean]("Configuration for generating the legacy pom of sbt plugins, to publish to Maven").withRank(CSetting)
  val useIvy = settingKey[Boolean]("Use Ivy for publishing. When false, use the ivyless publisher.").withRank(BSetting)

  @transient
  val credentials = taskKey[Seq[Credentials]]("The credentials to use for updating and publishing.").withRank(BMinusTask)
  @transient
  val allCredentials = taskKey[Seq[Credentials]]("Aggregated credentials across current and root subprojects. Do not rewire this task.").withRank(DTask)

  val makePom = taskKey[HashedVirtualFileRef]("Generates a pom for publishing when publishing Maven-style.").withRank(BPlusTask)
  @transient
  val deliver = taskKey[File]("Generates the Ivy file for publishing to a repository.").withRank(BTask)
  @transient
  val deliverLocal = taskKey[File]("Generates the Ivy file for publishing to the local repository.").withRank(BTask)
  // makeIvyXml is currently identical to the confusingly-named "deliver", which may be deprecated in the future
  @transient
  val makeIvyXml = taskKey[File]("Generates the Ivy file for publishing to a repository.").withRank(BTask)
  /** BOM-resolved ModuleIDs for deps that had \"*\" (version from BOM); emitted as forced deps in published ivy.xml (sbt#4531). */
  val resolvedDependencies = taskKey[Seq[ModuleID]]("")
  val publish = taskKey[Unit]("Publishes artifacts to a repository.").withRank(APlusTask)
  val publishLocal = taskKey[Unit]("Publishes artifacts to the local Ivy repository.").withRank(APlusTask)
  val publishM2 = taskKey[Unit]("Publishes artifacts to the local Maven repository.").withRank(ATask)

  val pomExtra = settingKey[NodeSeq]("Extra XML to insert into the generated POM.").withRank(BSetting)
  val pomPostProcess = settingKey[XNode => XNode]("Transforms the generated POM.").withRank(CSetting)
  val pomIncludeRepository = settingKey[MavenRepository => Boolean]("Selects repositories to include in the generated POM.").withRank(CSetting)
  val pomAllRepositories = settingKey[Boolean]("If true, includes repositories used in module configurations in the pom repositories section.  If false, only the common repositories are included.").withRank(BMinusSetting)

  val moduleName = settingKey[String]("The name of the current module, used for dependency management.").withRank(BSetting)
  val outputPath = settingKey[String]("Path of the output directory relative from the rootOutputDirectory.").withRank(DSetting)
  val version = settingKey[String]("The version/revision of the current module.").withRank(APlusSetting)
  val isSnapshot = settingKey[Boolean]("True if the version of the project is a snapshot version.").withRank(BPlusSetting)
  val moduleIDStr = StringAttributeKey("moduleID")
  val moduleID = settingKey[ModuleID]("A dependency management descriptor.  This is currently used for associating a ModuleID with a classpath entry.").withRank(BPlusSetting)
  val projectID = settingKey[ModuleID]("The dependency management descriptor for the current module.").withRank(BMinusSetting)
  val overrideBuildResolvers = settingKey[Boolean]("Whether or not all the build resolvers should be overridden with what's defined from the launcher.").withRank(BMinusSetting)
  val bootResolvers = taskKey[Option[Seq[Resolver]]]("The resolvers used by the sbt launcher.").withRank(BMinusSetting)
  val appResolvers = settingKey[Option[Seq[Resolver]]]("The resolvers configured for this application by the sbt launcher.").withRank(BMinusSetting)
  val externalResolvers = taskKey[Seq[Resolver]]("The external resolvers for automatically managed dependencies.").withRank(BMinusSetting)
  val resolvers = settingKey[Seq[Resolver]]("The user-defined additional resolvers for automatically managed dependencies.").withRank(BMinusTask)

  @transient
  val projectResolver = taskKey[Resolver]("Resolver that handles inter-project dependencies.").withRank(DTask)
  val fullResolvers = taskKey[Seq[Resolver]]("Combines the project resolver, default resolvers, and user-defined resolvers.").withRank(CTask)

  @transient
  val otherResolvers = taskKey[Seq[Resolver]]("Resolvers not included in the main resolver chain, such as those in module configurations.").withRank(CSetting)

  @transient
  val scalaCompilerBridgeResolvers = taskKey[Seq[Resolver]]("Resolvers used to resolve compiler bridges.").withRank(CSetting)
  val includePluginResolvers = settingKey[Boolean]("Include the resolvers from the metabuild.").withRank(CSetting)
  val moduleConfigurations = settingKey[Seq[ModuleConfiguration]]("Defines module configurations, which override resolvers on a per-module basis.").withRank(BMinusSetting)
  val retrievePattern = settingKey[String]("Pattern used to retrieve managed dependencies to the current build.").withRank(DSetting)
  val retrieveConfiguration = settingKey[Option[RetrieveConfiguration]]("Configures retrieving dependencies to the current build.").withRank(DSetting)
  val offline = settingKey[Boolean]("Configures sbt to work without a network connection where possible.").withRank(ASetting)
  val ivyPaths = settingKey[IvyPaths]("Configures paths used by Ivy for dependency management.").withRank(DSetting)
  @transient
  val dependencyCacheDirectory = taskKey[File]("The base directory for cached dependencies.").withRank(DTask)
  val libraryDependencies = settingKey[Seq[ModuleID]]("Declares managed dependencies.").withRank(APlusSetting)
  val dependencyOverrides = settingKey[Seq[ModuleID]]("Declares managed dependency overrides.").withRank(BSetting)
  val excludeDependencies = settingKey[Seq[InclExclRule]]("Declares managed dependency exclusions.").withRank(BSetting)
  val allExcludeDependencies = settingKey[Seq[InclExclRule]]("User-defined dependency exclusions and sbt itself in the case of metabuild.").withRank(CTask)
  val allDependencies = taskKey[Seq[ModuleID]]("Inter-project and library dependencies.").withRank(CTask)
  val projectDependencies = taskKey[Seq[ModuleID]]("Inter-project dependencies.").withRank(DTask)
  val ivyXML = settingKey[NodeSeq]("Defines inline Ivy XML for configuring dependency management.").withRank(BSetting)
  val scalaModuleInfo = settingKey[Option[ScalaModuleInfo]]("Configures how Scala dependencies are checked, filtered, and injected.").withRank(CSetting)
  val ivyValidate = settingKey[Boolean]("Enables/disables Ivy validation of module metadata.").withRank(BSetting)
  val ivyLoggingLevel = settingKey[UpdateLogging]("The logging level for updating.").withRank(BSetting)

  @transient
  val publishTo = taskKey[Option[Resolver]]("The resolver to publish to.").withRank(ASetting)
  val artifacts = settingKey[Seq[Artifact]]("The artifact definitions for the current module.  Must be consistent with " + packagedArtifacts.key.label + ".").withRank(BSetting)
  private[sbt] val projectDescriptors = taskKey[Map[ModuleRevisionId, ModuleDescriptor]]("Project dependency map for the inter-project resolver.").withRank(DTask)
  val autoUpdate = settingKey[Boolean]("<unimplemented>").withRank(Invisible)
  val retrieveManaged = settingKey[Boolean]("If true, enables retrieving dependencies to the current build.  Otherwise, dependencies are used directly from the cache.").withRank(BSetting)
  val retrieveManagedSync = settingKey[Boolean]("If true, enables synchronizing the dependencies retrieved to the current build by removed unneeded files.").withRank(BSetting)
  val configurationsToRetrieve = settingKey[Option[Seq[ConfigRef]]]("An optional set of configurations from which to retrieve dependencies if retrieveManaged is set to true").withRank(BSetting)
  val managedDirectory = settingKey[File]("Directory to which managed dependencies are retrieved.").withRank(BSetting)
  val classpathTypes = settingKey[Set[String]]("Artifact types that are included on the classpath.").withRank(BSetting)
  val publishArtifact = settingKey[Boolean]("Enables (true) or disables (false) publishing an artifact.").withRank(AMinusSetting)
  val packagedArtifact = taskKey[(Artifact, HashedVirtualFileRef)]("Generates a packaged artifact, returning the Artifact and the produced File.").withRank(CTask)
  val checksums = settingKey[Seq[String]]("The list of checksums to generate and to verify for dependencies.").withRank(BSetting)
  val forceUpdatePeriod = settingKey[Option[FiniteDuration]]("Duration after which to force a full update to occur").withRank(CSetting)
  val versionScheme = settingKey[Option[String]]("""Version scheme used for the subproject: Supported values are Some("early-semver"), Some("pvp"), and Some("semver-spec")""").withRank(BSetting)
  val libraryDependencySchemes = settingKey[Seq[ModuleID]]("""Version scheme to use for specific modules set as "org" %% "name" % "<scheme>": Supported values are "early-semver", "pvp", "semver-spec", "always", and "strict".""").withRank(BSetting)
  @transient
  val stagingDirectory = settingKey[File]("Local staging directory for Sonatype publishing").withRank(CSetting)
  @transient
  val sonaBundle = taskKey[File]("Local bundle for Sonatype publishing").withRank(DTask)
  val localStaging = settingKey[Option[Resolver]]("Local staging resolver for Sonatype publishing").withRank(CSetting)
  val sonaDeploymentName = settingKey[String]("The name used for deployment").withRank(DSetting)
  val sonaUploadRequestTimeout = settingKey[FiniteDuration]("Request timeout for Sonatype publishing").withRank(DSetting)

  val classifiersModule = taskKey[GetClassifiersModule]("classifiers-module").withRank(CTask)
  val compatibilityWarningOptions = settingKey[CompatibilityWarningOptions]("Configures warnings around Maven incompatibility.").withRank(CSetting)
  val conflictWarning = settingKey[ConflictWarning]("Configures warnings for conflicts in dependency management.").withRank(CSetting)
  val conflictManager = settingKey[ConflictManager]("Selects the conflict manager to use for dependency management.").withRank(CSetting)
  val autoScalaLibrary = settingKey[Boolean]("Adds a dependency on scala-library if true.").withRank(ASetting)
  val managedScalaInstance = settingKey[Boolean]("Automatically obtains Scala tools as managed dependencies if true.").withRank(BSetting)
  val allowUnsafeScalaLibUpgrade = settingKey[Boolean]("Allow the Scala library on the compilation classpath to be newer than the scalaVersion (see Scala SIP-51).").withRank(CSetting)
  val allowMismatchScala = settingKey[Boolean]("When set to true, allow dependsOn to an arbitrary Scala version subproject without error.").withRank(CSetting)
  val sbtResolver = settingKey[Resolver]("Provides a resolver for obtaining sbt as a dependency.").withRank(BMinusSetting)
  val sbtResolvers = settingKey[Seq[Resolver]]("The external resolvers for sbt and plugin dependencies.").withRank(BMinusSetting)
  val sbtDependency = settingKey[ModuleID]("Provides a definition for declaring the current version of sbt.").withRank(BMinusSetting)
  val sbtVersion = settingKey[String]("Provides the version of sbt.  This setting should not be modified.").withRank(AMinusSetting)
  val sbtBinaryVersion = settingKey[String]("Defines the binary compatibility version substring.").withRank(BPlusSetting)
  val skip = taskKey[Boolean]("For tasks that support it (currently only 'compile', 'update', 'publish' and 'publishLocal'), setting skip to true will force the task to not to do its work.  The exact semantics may vary depending on the task.").withRank(BSetting)
  val templateResolverInfos = settingKey[Seq[TemplateResolverInfo]]("Template resolvers used for 'new'.").withRank(BSetting)
  val templateDescriptions = settingKey[Seq[(String, String)]]("List of templates with description used for 'new' / 'init'.")
  val templateRunLocal = inputKey[Unit]("Runs a local template.").withRank(DTask)
  val interactionService = taskKey[InteractionService]("Service used to ask for user input through the current user interface(s).").withRank(CTask)
  val insideCI = SettingKey[Boolean]("insideCI", "Determines if the sbt is running in a Continuous Integration environment", AMinusSetting)

  // sbt server internal
  val collectAnalyses = taskKey[Unit]("Collect analysis file locations for later use.")

  // special
  val sessionVars = AttributeKey[SessionVar.Map]("sessionVars", "Bindings that exist for the duration of the session.", Invisible)
  val parallelExecution = settingKey[Boolean]("Enables (true) or disables (false) parallel execution of tasks.").withRank(BMinusSetting)
  val tags = settingKey[Seq[(Tags.Tag, Int)]](ConcurrentRestrictions.tagsKey.description.getOrElse("tags")).withRank(BSetting)
  val concurrentRestrictions = settingKey[Seq[Tags.Rule]]("Rules describing restrictions on concurrent task execution.").withRank(BSetting)
  val cancelable = settingKey[Boolean]("Enables (true) or disables (false) the ability to interrupt task execution with CTRL+C.").withRank(BMinusSetting)
  val forcegc = settingKey[Boolean]("Enables (true) or disables (false) forcing garbage collection after task run when needed.").withRank(BMinusSetting)
  val minForcegcInterval = settingKey[Duration]("Minimal interval to check for forcing garbage collection.")
  val settingsData = std.FullInstance.settingsData
  private[sbt] val allScopes = settingKey[ScopeFilter.AllScopes]("Internal use: a view of all scopes for filtering")

  @transient
  val streams = taskKey[TaskStreams]("Provides streams for logging and persisting data.").withRank(DTask)
  val taskDefinitionKey = Def.taskDefinitionKey
  val (executionRoots, dummyRoots) = Def.dummy[Seq[ScopedKey[?]]]("executionRoots", "The list of root tasks for this task execution.  Roots are the top-level tasks that were directly requested to be run.")

  @transient
  val state = Def.stateKey
  val streamsManager = Def.streamsManagerKey
  // wrapper to work around SI-2915
  final class TaskProgress(val progress: ExecuteProgress)
  object TaskProgress {
    def apply(progress: ExecuteProgress): TaskProgress = new TaskProgress(progress)
  }
  private[sbt] val currentCommandProgress = AttributeKey[ExecuteProgress2]("current-command-progress")
  private[sbt] val taskProgress = AttributeKey[sbt.internal.TaskProgress]("active-task-progress")
  val useSuperShell = settingKey[Boolean]("Enables (true) or disables the super shell.")
  val superShellMaxTasks = settingKey[Int]("The max number of tasks to display in the supershell progress report")
  val superShellSleep = settingKey[FiniteDuration]("The minimum duration to sleep between progress reports")
  val superShellThreshold = settingKey[FiniteDuration]("The minimum amount of time a task must be running to appear in the supershell progress report")
  val turbo = settingKey[Boolean]("Enables (true) or disables optional performance features.")
  // This key can be used to add custom ExecuteProgress instances
  val progressReports = settingKey[Seq[TaskProgress]]("A function that returns a list of progress reporters.").withRank(DTask)
  @deprecated("unused", "1.4.0")
  private[sbt] val progressState = settingKey[Option[ProgressState]]("The optional progress state if supershell is enabled.").withRank(Invisible)
  private[sbt] val postProgressReports = settingKey[Unit]("Internally used to modify logger.").withRank(DTask)
  @deprecated("No longer used", "1.3.0")
  private[sbt] val executeProgress = settingKey[State => TaskProgress]("Experimental task execution listener.").withRank(DTask)
  val commandProgress = settingKey[Seq[ExecuteProgress2]]("Command progress listeners receive events when commands start and end, in addition to task progress events.")
  val lintUnused = inputKey[Unit]("Check for keys unused by other settings and tasks. Keys that are only used via key.all(ScopeFilter).value may still be reported as unused.")
  val lintIncludeFilter = settingKey[String => Boolean]("Filters key names that should be included in the lint check.")
  val lintExcludeFilter = settingKey[String => Boolean]("Filters key names that should be excluded in the lint check.")
  val excludeLintKeys = settingKey[Set[Def.KeyedInitialize[?]]]("Keys excluded from lintUnused task")
  val includeLintKeys = settingKey[Set[Def.KeyedInitialize[?]]]("Task keys that are included into lintUnused task")
  val lintUnusedKeysOnLoad = settingKey[Boolean]("Toggles whether or not to check for unused keys during startup")

  val useScalaReplJLine = settingKey[Boolean]("Toggles whether or not to use sbt's forked jline in the scala repl. Enabling this flag may break the thin client in the scala console.").withRank(KeyRanks.Invisible)
  val scalaInstanceTopLoader = settingKey[ClassLoader]("The top classloader for the scala instance").withRank(KeyRanks.Invisible)

  val stateStreams = AttributeKey[Streams]("stateStreams", "Streams manager, which provides streams for different contexts.  Setting this on State will override the default Streams implementation.")
  val resolvedScoped = Def.resolvedScoped
  val pluginData = taskKey[PluginData]("Information from the plugin build needed in the main build definition.").withRank(DTask)
  val globalPluginUpdate = taskKey[UpdateReport]("A hook to get the UpdateReport of the global plugin.").withRank(DTask)
  private[sbt] val taskCancelStrategy = settingKey[State => TaskCancellationStrategy]("Experimental task cancellation handler.").withRank(DTask)
  private[sbt] val cacheStoreFactoryFactory = AttributeKey[CacheStoreFactoryFactory]("cache-store-factory-factory")
  private[sbt] val bootServerSocket = AttributeKey[BootServerSocket]("boot-server-socket")
  private[sbt] val channelProjectCursors = AttributeKey[Map[String, ProjectRef]]("channel-project-cursors", "Per-channel project cursors for multi-client server mode.")
  val fileCacheSize = settingKey[String]("The approximate maximum size in bytes of the cache used to store previous task results. For example, it could be set to \"256M\" to make the maximum size 256 megabytes.")

  // Experimental in sbt 0.13.2 to enable grabbing semantic compile failures.
  private[sbt] val compilerReporter = taskKey[xsbti.Reporter]("Experimental hook to listen (or send) compilation failure messages.").withRank(DTask)

  val triggeredBy = Def.triggeredBy
  val runBefore = Def.runBefore

  type Streams = std.Streams[ScopedKey[?]]
  type TaskStreams = std.TaskStreams[ScopedKey[?]]
}

// format: on
