diff --git a/buildSrc/src/main/kotlin/datadog/gradle/plugin/version/BranchFirstVersioning.kt b/buildSrc/src/main/kotlin/datadog/gradle/plugin/version/BranchFirstVersioning.kt new file mode 100644 index 00000000000..3747e9a11f8 --- /dev/null +++ b/buildSrc/src/main/kotlin/datadog/gradle/plugin/version/BranchFirstVersioning.kt @@ -0,0 +1,393 @@ +package datadog.gradle.plugin.version + +import com.github.zafarkhaja.semver.Version +import datadog.gradle.plugin.version.TracerVersionPlugin.TracerVersionExtension +import org.gradle.api.GradleException +import org.gradle.api.file.DirectoryProperty +import org.gradle.api.logging.Logging +import org.gradle.api.provider.ListProperty +import org.gradle.api.provider.Property +import org.gradle.api.provider.ProviderFactory +import org.gradle.api.provider.ValueSource +import org.gradle.api.provider.ValueSourceParameters +import org.gradle.process.ExecOperations +import java.io.ByteArrayOutputStream +import java.io.File +import java.nio.charset.Charset +import javax.inject.Inject + +/** + * The `X.Y` version line of a `release/vX.Y.x` branch. + * + * In the branch-first release process, `release/vX.Y.x` is cut from master before `vX.Y.0` is + * tagged, so the branch name, not the last tag, tells which line a build belongs to. + */ +internal data class ReleaseLine(val major: Long, val minor: Long) : Comparable { + override fun compareTo(other: ReleaseLine): Int = compareValuesBy(this, other, ReleaseLine::major, ReleaseLine::minor) + + /** The `git describe --match` pattern of the tags of this line, like `v1.69.[0-9]*`. */ + fun tagPattern(tagPrefix: String): String = "$tagPrefix$major.$minor.[0-9]*" + + override fun toString(): String = "$major.$minor" + + companion object { + private val BRANCH_REGEX = Regex("release/v(\\d+)\\.(\\d+)\\.x") + + /** Parses a `release/vX.Y.x` branch name, or returns `null` for any other branch name. */ + fun fromBranch(branch: String): ReleaseLine? = BRANCH_REGEX.matchEntire(branch)?.let { + val (major, minor) = it.destructured + ReleaseLine(major.toLong(), minor.toLong()) + } + } +} + +/** + * Computes the tracer version of a git clone in the branch-first release process. + * + * - `release/vX.Y.x` branches build `X.Y.0-rc.N` before the `vX.Y.0` tag, where `N` is the number + * of first-parent commits since the branch was cut from master, then `X.Y.(Z+1)-rc.N` after the + * `vX.Y.Z` tag, where `N` is the number of commits since that tag. + * - Other `release/v*` branches build the next patch `-rc.N` version of the last tag. + * - Master and feature branches build the next minor `-SNAPSHOT` version, one above the newer of + * the last tag line and the newest `release/vX.Y.x` branch line. + * - A build checked out on a release tag builds that exact version. + * + * @param warn reports the warnings, such as a release branch with master merged into it + */ +internal class BranchFirstVersioning( + private val providerFactory: ProviderFactory, + private val repoWorkingDirectory: File, + private val warn: (String) -> Unit = { LOGGER.warn(it) }, +) { + /** + * Computes the version of the clone. + * + * @param branch the current branch, already resolved from `CI_COMMIT_BRANCH` on detached HEADs + * @param extension the version settings: tag prefix, qualifier, dirtiness, snapshot, default version + * @param isReleaseTag checks whether a build checked out on that exact tag, with its prefix, may + * use it as the release version + */ + fun version( + branch: String, + extension: TracerVersionExtension, + isReleaseTag: (String) -> Boolean, + ): String { + val releaseLine = ReleaseLine.fromBranch(branch) + if (releaseLine != null) { + return releaseLineVersion(releaseLine, extension, isReleaseTag) + } + val isReleaseBranch = branch.startsWith(RELEASE_BRANCH_PREFIX) + // Use --first-parent only on release branches so they stay anchored to their own version + // line; feature branches pick up newer tags merged in from master. + val describeString = describe(extension, firstParent = isReleaseBranch) + return tagVersion(describeString, extension, isReleaseBranch, isReleaseTag) + } + + /** + * Computes the version of a `release/vX.Y.x` branch from the tags of its `X.Y` line only. + */ + private fun releaseLineVersion( + releaseLine: ReleaseLine, + extension: TracerVersionExtension, + isReleaseTag: (String) -> Boolean, + ): String { + val tagPrefix = extension.tagVersionPrefix.get() + val linePattern = releaseLine.tagPattern(tagPrefix) + // --always prints the commit hash, with the dirtiness, while the line has no tag + val describeString = describe(extension, firstParent = true, match = linePattern, always = true) + if (describeString.startsWith(tagPrefix)) { + return tagVersion(describeString, extension, isReleaseBranch = true, isReleaseTag) + } + + LOGGER.info("Git describe output: {} (no {} tag yet)", describeString, linePattern) + val commitsSinceCut = commitsSinceMasterCut(releaseLine) ?: run { + val lastTagDescribe = describe(extension, firstParent = true) + commitsSinceTag(tagRegex(tagPrefix).find(lastTagDescribe)?.groupValues?.get(2).orEmpty()) + } + return firstReleaseCandidateVersion( + releaseLine, + commitsSinceCut, + extension.versionQualifier.orNull, + dirty = describeString.endsWith("-dirty"), + useSnapshot = extension.useSnapshot.get(), + ) + } + + /** + * Builds the version from the `git describe` output of a version tag. + * + * Builds with commits after the last tag get the next minor `-SNAPSHOT` version, except on + * release branches, which get the next patch `-rc.N` version, where `N` is the number of commits + * since the last tag. + */ + private fun tagVersion( + describeString: String, + extension: TracerVersionExtension, + isReleaseBranch: Boolean, + isReleaseTag: (String) -> Boolean, + ): String { + LOGGER.info("Git describe output: {}", describeString) + + val tagPrefix = extension.tagVersionPrefix.get() + val matchResult = tagRegex(tagPrefix).find(describeString) + ?: return extension.defaultVersion.get() + + val (lastTagVersion, describeTrailer) = matchResult.destructured + val hasLaterCommits = describeTrailer.isNotBlank() || !isReleaseTag("$tagPrefix$lastTagVersion") + val version = Version.parse(lastTagVersion).let { + when { + !hasLaterCommits -> it + + isReleaseBranch -> { + LOGGER.info("Incrementing patch because release branch") + it.nextPatchVersion() + } + + else -> { + LOGGER.info("Incrementing minor") + nextMinorVersion(it, newestReleaseLine(releaseBranchRefs())) + } + } + } + + return buildString { + append(version.toString()) + + // Add optional version qualifier (e.g., "-ddprof") + val qualifier = extension.versionQualifier.orNull + if (!qualifier.isNullOrBlank()) { + append("-").append(qualifier) + } + + if (hasLaterCommits) { + append( + when { + isReleaseBranch -> "-rc.${commitsSinceTag(describeTrailer)}" + extension.useSnapshot.get() || describeTrailer.isBlank() -> "-SNAPSHOT" + else -> describeTrailer + } + ) + } + + if (describeTrailer.endsWith("-dirty")) { + append(if (extension.useSnapshot.get()) "-DIRTY" else "-dirty") + } + } + } + + /** + * Counts the first-parent commits of HEAD since it was cut from master, so later master commits + * are never counted. + * + * Warns when the cut commit, the merge base with master, is not on the first-parent history of + * HEAD: master was merged into the release branch, which moved the merge base to the merged + * master commit. + * + * @return the commit count, or `null` when there is no master ref or no merge base with it + */ + private fun commitsSinceMasterCut(releaseLine: ReleaseLine): Int? { + val existingRefs = git("for-each-ref", "--format=%(refname)", *MASTER_REFS).lines() + val masterRef = MASTER_REFS.firstOrNull { it in existingRefs } + if (masterRef == null) { + warn( + "Master is missing from the git clone (no ${MASTER_REFS.joinToString(" or ")}): " + + "cannot find where release/v$releaseLine.x was cut from master, " + + "so rc.N counts the commits since the last tag instead" + ) + return null + } + + // Fails, for instance, on shallow clones without the cut commit + val cut = git("merge-base", masterRef, "HEAD", ignoreFailure = true) + if (cut.isBlank()) { + warn( + "No merge base between $masterRef and HEAD in the git clone (shallow clone?): " + + "cannot find where release/v$releaseLine.x was cut from master, " + + "so rc.N counts the commits since the last tag instead" + ) + return null + } + + val count = git("rev-list", "--count", "--first-parent", "$cut..HEAD").toInt() + // HEAD~count is the cut commit when it is on the first-parent history + val countedFrom = git("rev-parse", "--verify", "--quiet", "HEAD~$count", ignoreFailure = true) + if (countedFrom != cut) { + warn( + "release/v$releaseLine.x looks corrupted, master was merged into it: its merge base with " + + "$masterRef, $cut, is the merged master commit, not on its first-parent history. " + + "rc.$count counts its first-parent commits since " + + countedFrom.ifBlank { "its root" } + " instead." + ) + } + return count + } + + /** + * Lists the release branches of origin, or the local remote-tracking ones when origin can't be + * reached or has none. + */ + private fun releaseBranchRefs(): List { + val refs = git("ls-remote", "--heads", ORIGIN, "refs/heads/release/v*", ignoreFailure = true) + .ifBlank { git("for-each-ref", "--format=%(refname)", "refs/remotes/$ORIGIN/release/") } + return refs.lines().filter { it.isNotBlank() } + } + + private fun describe( + extension: TracerVersionExtension, + firstParent: Boolean, + match: String = "${extension.tagVersionPrefix.get()}[0-9].[0-9]*.[0-9]*", + always: Boolean = false, + ): String { + val args = mutableListOf("describe", "--abbrev=8", "--tags", "--match=$match") + if (firstParent) { + args += "--first-parent" + } + if (always) { + args += "--always" + } + if (extension.detectDirty.getOrElse(false)) { + args += "--dirty" + } + return git(*args.toTypedArray()) + } + + private fun git(vararg args: String, ignoreFailure: Boolean = false): String = providerFactory.of(BranchFirstGitValueSource::class.java) { + parameters { + gitCommand.add("git") + gitCommand.addAll(*args) + this.ignoreFailure.set(ignoreFailure) + workingDirectory.set(repoWorkingDirectory) + } + }.get() + + /** Pure version computations of the branch-first release process. */ + companion object { + private val LOGGER = Logging.getLogger(BranchFirstVersioning::class.java) + + private const val ORIGIN = "origin" + + /** Branches starting with this prefix build the next patch `-rc.N` version. */ + private const val RELEASE_BRANCH_PREFIX = "release/v" + + /** Master refs, by preference: the remote one is fresher than a possibly stale local branch. */ + private val MASTER_REFS = arrayOf("refs/remotes/$ORIGIN/master", "refs/heads/master") + + /** Matches the `git describe` output of a version tag: the tag version, then the trailer. */ + private fun tagRegex(tagPrefix: String) = Regex("$tagPrefix(\\d+\\.\\d+\\.\\d+)(.*)") + + private val COMMITS_SINCE_TAG_REGEX = Regex("^-(\\d+)-g[0-9a-f]+") + + /** + * Finds the newest release line among release branch refs. + * + * @param refs lines of `git ls-remote` (`\trefs/heads/release/vX.Y.x`) or + * `git for-each-ref` (`refs/remotes/origin/release/vX.Y.x`) output; other names are ignored + */ + fun newestReleaseLine(refs: List): ReleaseLine? = refs.asSequence() + .map { it.substringAfterLast('\t').trim().removePrefix("refs/heads/").removePrefix("refs/remotes/origin/") } + .mapNotNull(ReleaseLine::fromBranch) + .maxOrNull() + + /** + * Returns the next minor version of master and feature branches: one above the newer of the + * last tag line and the newest release branch line, since a release branch may exist before + * its `vX.Y.0` tag. + */ + fun nextMinorVersion(lastTagVersion: Version, newestReleaseLine: ReleaseLine?): Version { + val lastTagLine = ReleaseLine(lastTagVersion.majorVersion(), lastTagVersion.minorVersion()) + return if (newestReleaseLine != null && newestReleaseLine > lastTagLine) { + Version.of(newestReleaseLine.major, newestReleaseLine.minor + 1, 0) + } else { + lastTagVersion.nextMinorVersion() + } + } + + /** + * Builds the `X.Y.0-rc.N` version of a release branch that has no tag of its line yet, in the + * same format as tagged release branches: `X.Y.0[-qualifier]-rc.N[-DIRTY|-dirty]`. + * + * @param commitsSinceCut the number of commits added to the release branch since it was cut + */ + fun firstReleaseCandidateVersion( + line: ReleaseLine, + commitsSinceCut: Int, + qualifier: String?, + dirty: Boolean, + useSnapshot: Boolean, + ): String = buildString { + append(Version.of(line.major, line.minor, 0).toString()) + if (!qualifier.isNullOrBlank()) { + append("-").append(qualifier) + } + append("-rc.").append(commitsSinceCut) + if (dirty) { + append(if (useSnapshot) "-DIRTY" else "-dirty") + } + } + + /** + * Reads the number of commits since the last tag from the `git describe` trailer, like + * `-3-g1234abcd` or `-3-g1234abcd-dirty`. The trailer is blank, or only `-dirty`, on the + * tagged commit itself. + */ + private fun commitsSinceTag(describeTrailer: String): Int = COMMITS_SINCE_TAG_REGEX.find(describeTrailer)?.groupValues?.get(1)?.toInt() ?: 0 + } +} + +/** + * Runs a git command of [BranchFirstVersioning] and returns its standard output. + * + * Returns a blank output outside a git repository, when `git describe` finds no tag, or, with + * [Parameters.ignoreFailure], when the command fails. + */ +internal abstract class BranchFirstGitValueSource @Inject constructor( + private val execOperations: ExecOperations, +) : ValueSource { + override fun obtain(): String { + val commands = parameters.gitCommand.get() + val standardOutput = ByteArrayOutputStream() + val errorOutput = ByteArrayOutputStream() + val result = try { + execOperations.exec { + commandLine(commands) + workingDir(parameters.workingDirectory.get()) + this.standardOutput = standardOutput + this.errorOutput = errorOutput + isIgnoreExitValue = true + } + } catch (e: Exception) { + throw GradleException("Failed to run: ${commands.joinToString(" ")}", e) + } + + val charset = Charset.defaultCharset().name() + val output = standardOutput.toString(charset).trim() + val error = errorOutput.toString(charset).trim() + return when { + result.exitValue == 0 -> output + + parameters.ignoreFailure.getOrElse(false) -> "" + + // Behaves as if not a git repository + result.exitValue == 128 && + (error.startsWith("fatal: not a git repository") || error.startsWith("fatal: No names found")) -> "" + + else -> throw GradleException( + """ + Failed to run: ${commands.joinToString(" ")} + (exit code: ${result.exitValue}) + Output: + $output + $error + """.trimIndent() + ) + } + } + + interface Parameters : ValueSourceParameters { + val workingDirectory: DirectoryProperty + val gitCommand: ListProperty + + /** Returns a blank output instead of failing when the command exits with a non-zero code. */ + val ignoreFailure: Property + } +} diff --git a/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningIntegrationTest.kt b/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningIntegrationTest.kt new file mode 100644 index 00000000000..7d5f6b1422f --- /dev/null +++ b/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningIntegrationTest.kt @@ -0,0 +1,333 @@ +package datadog.gradle.plugin.version + +import datadog.gradle.plugin.version.TracerVersionPlugin.TracerVersionExtension +import org.assertj.core.api.Assertions.assertThat +import org.gradle.testfixtures.ProjectBuilder +import org.junit.jupiter.api.Test +import org.junit.jupiter.api.io.TempDir +import java.io.File + +/** + * Tests [BranchFirstVersioning] against real git repositories, in the branch-first release + * process where `release/vX.Y.x` is cut from master before `vX.Y.0` is tagged on the release + * branch. + */ +class BranchFirstVersioningIntegrationTest : VersionPluginsFixture() { + @TempDir + lateinit var originDir: File + + @TempDir + lateinit var gradleProjectDir: File + + private val warnings = mutableListOf() + + @Test + fun `should build first release candidate at release branch cut`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + + assertVersion("1.69.0-rc.0") + } + + @Test + fun `should count release branch commits since cut before line tag`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + + assertVersion("1.69.0-rc.1") + } + + @Test + fun `should not count master commits after release branch cut`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "switch", "master") + repeat(3) { commit("master-after-cut-$it") } + exec("git", "push", "origin", "master") + exec("git", "fetch", "origin") + exec("git", "switch", "release/v1.69.x") + + assertVersion("1.69.0-rc.1") + } + + @Test + fun `should build release candidate in GitLab detached HEAD before line tag`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "switch", "--detach") + + // The plugin resolves the detached HEAD branch from CI_COMMIT_BRANCH + assertVersion("1.69.0-rc.1", branch = "release/v1.69.x", env = mapOf("GITLAB_CI" to "true")) + } + + @Test + fun `should prefer origin master over stale local master`() { + initMasterWithOrigin() + repeat(2) { commit("master-before-cut-$it") } + exec("git", "push", "origin", "master") + exec("git", "fetch", "origin") + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + // The local master branch was not updated before the release branch was cut + exec("git", "branch", "-f", "master", "v1.68.0") + + assertVersion("1.69.0-rc.1") + } + + @Test + fun `should use local master without origin`() { + initMasterRepo() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + + assertVersion("1.69.0-rc.1") + } + + @Test + fun `should count commits since last tag and warn without master ref`() { + // The repository default branch is main, and there is no origin + initRepo() + exec("git", "tag", "v1.68.0", "-m", "") + commit("main-commit") + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + + assertVersion("1.69.0-rc.2") + assertThat(warnings).singleElement().asString().startsWith("Master is missing from the git clone") + } + + @Test + fun `should warn about corrupted release branch with master merged into it`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "switch", "master") + repeat(2) { commit("master-after-cut-$it") } + exec("git", "push", "origin", "master") + exec("git", "fetch", "origin") + exec("git", "switch", "release/v1.69.x") + exec("git", "merge", "--no-edit", "origin/master") + commit("fix") + + // The first-parent count still starts from the original cut: pin, merge and fix commits + assertVersion("1.69.0-rc.3") + assertThat(warnings).singleElement().asString() + .startsWith("release/v1.69.x looks corrupted, master was merged into it") + .contains(gitOutput("rev-parse", "origin/master"), gitOutput("rev-parse", "HEAD~3")) + } + + @Test + fun `should not warn on release branch with another branch merged into it`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "switch", "-c", "fix") + commit("fix") + exec("git", "switch", "release/v1.69.x") + exec("git", "merge", "--no-ff", "--no-edit", "fix") + + // The pin and merge commits + assertVersion("1.69.0-rc.2") + assertThat(warnings).isEmpty() + } + + @Test + fun `should increment patch after line tag on release branch`() { + initReleaseBranchWithLineTag() + commit("backport") + + assertVersion("1.69.1-rc.1") + } + + @Test + fun `should increment patch on line tag checked out by a GitLab release branch pipeline`() { + initReleaseBranchWithLineTag() + exec("git", "switch", "--detach", "v1.69.0") + + assertVersion("1.69.1-rc.0", branch = "release/v1.69.x", env = mapOf("GITLAB_CI" to "true")) + } + + @Test + fun `should use exact version on line tag in GitLab tag pipeline`() { + initReleaseBranchWithLineTag() + exec("git", "switch", "--detach", "v1.69.0") + + // The plugin keeps the release branch name when CI_COMMIT_BRANCH is unset + assertVersion( + "1.69.0", + branch = "release/v1.69.x", + env = mapOf("GITLAB_CI" to "true", "CI_COMMIT_TAG" to "v1.69.0"), + ) + } + + @Test + fun `should ignore older line tag on release branch`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "tag", "v1.68.1", "-m", "") + commit("fix") + + assertVersion("1.69.0-rc.2") + } + + @Test + fun `should keep last tag version line on unparsable release branch`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x-hotfix") + commit("pin-system-tests") + + assertVersion("1.68.1-rc.2") + } + + @Test + fun `should mark qualifier and dirtiness on release branch before line tag`() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + writeFile("pin-system-tests.txt", "An uncommitted modification", append = true) + + assertVersion("1.69.0-ddprof-rc.1-DIRTY", detectDirty = true, qualifier = "ddprof") + } + + @Test + fun `should skip newer release branch line on master`() { + initMasterWithOrigin() + pushReleaseBranch("release/v1.69.x") + commit("master-after-cut") + + assertVersion("1.70.0-SNAPSHOT") + } + + @Test + fun `should skip newer release branch line on feature branch`() { + initMasterWithOrigin() + pushReleaseBranch("release/v1.69.x") + exec("git", "switch", "-c", "mo/feature") + commit("feature") + + assertVersion("1.70.0-SNAPSHOT") + } + + @Test + fun `should increment minor of last tag on master without newer release branch`() { + initMasterWithOrigin() + pushReleaseBranch("release/v1.68.x") + pushReleaseBranch("release/v1.70.x-test") + commit("another-master-commit") + + assertVersion("1.69.0-SNAPSHOT") + } + + @Test + fun `should use remote-tracking release branches when ls-remote fails`() { + initMasterWithOrigin() + pushReleaseBranch("release/v1.69.x") + exec("git", "fetch", "origin") + exec("git", "remote", "set-url", "origin", File(originDir, "missing").absolutePath) + commit("master-after-cut") + + assertVersion("1.70.0-SNAPSHOT") + } + + @Test + fun `should increment minor of last tag on master when ls-remote fails without remote-tracking release branch`() { + initMasterRepo() + commit("another-master-commit") + + assertVersion("1.69.0-SNAPSHOT") + } + + @Test + fun `should mark qualifier and dirtiness on master with newer release branch`() { + initMasterWithOrigin() + pushReleaseBranch("release/v1.69.x") + commit("master-after-cut") + writeFile("master-after-cut.txt", "An uncommitted modification", append = true) + + assertVersion("1.70.0-ddprof-SNAPSHOT-DIRTY", detectDirty = true, qualifier = "ddprof") + } + + /** Initializes a repository on main with a first commit. */ + private fun initRepo() { + writeFile("README.md", "test repository") + initGitRepo() + } + + /** Initializes a repository on master with a `v1.68.0` tag followed by a commit. */ + private fun initMasterRepo() { + initRepo() + exec("git", "branch", "-m", "master") + exec("git", "tag", "v1.68.0", "-m", "") + commit("master-commit") + } + + /** Same as [initMasterRepo], with master pushed to a local bare `origin` repository. */ + private fun initMasterWithOrigin() { + initMasterRepo() + exec(originDir, "git", "init", "--bare") + exec("git", "remote", "add", "origin", originDir.absolutePath) + exec("git", "push", "origin", "master") + exec("git", "fetch", "origin") + } + + /** Cuts `release/v1.69.x` from master, adds a commit, and tags it `v1.69.0`. */ + private fun initReleaseBranchWithLineTag() { + initMasterWithOrigin() + exec("git", "switch", "-c", "release/v1.69.x") + commit("pin-system-tests") + exec("git", "tag", "v1.69.0", "-m", "") + // Master moves on without the release tag + exec("git", "switch", "master") + commit("master-after-cut") + exec("git", "push", "origin", "master") + exec("git", "switch", "release/v1.69.x") + } + + /** Pushes a branch at HEAD to origin without fetching it, so only `git ls-remote` sees it. */ + private fun pushReleaseBranch(branch: String) { + exec("git", "push", "origin", "HEAD:refs/heads/$branch") + } + + private fun commit(name: String) { + writeFile("$name.txt", name) + commitAll(name) + } + + private fun gitOutput(vararg args: String): String = ProcessBuilder("git", *args) + .directory(projectDir) + .start() + .let { process -> process.inputStream.bufferedReader().readText().trim().also { process.waitFor() } } + + private fun currentBranch(): String = gitOutput("rev-parse", "--abbrev-ref", "HEAD") + + /** + * Computes the version of the [projectDir] repository like the tracer version plugin does. + * + * @param branch the branch the plugin resolves, defaults to the checked out branch + * @param env the GitLab variables deciding whether the checked out tag is the release version + */ + private fun assertVersion( + expectedVersion: String, + branch: String = currentBranch(), + env: Map = emptyMap(), + detectDirty: Boolean = false, + qualifier: String? = null, + ) { + // A project outside the repository, so its files never make the repository dirty + val project = ProjectBuilder.builder().withProjectDir(gradleProjectDir).build() + val extension = project.objects.newInstance(TracerVersionExtension::class.java).apply { + this.detectDirty.set(detectDirty) + versionQualifier.set(qualifier) + } + val isReleaseTag = { tag: String -> "GITLAB_CI" !in env || tag == env["CI_COMMIT_TAG"] } + + val version = BranchFirstVersioning(project.providers, projectDir) { warnings += it } + .version(branch, extension, isReleaseTag) + + assertThat(version).isEqualTo(expectedVersion) + } +} diff --git a/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningTest.kt b/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningTest.kt new file mode 100644 index 00000000000..794434a8509 --- /dev/null +++ b/buildSrc/src/test/kotlin/datadog/gradle/plugin/version/BranchFirstVersioningTest.kt @@ -0,0 +1,87 @@ +package datadog.gradle.plugin.version + +import com.github.zafarkhaja.semver.Version +import org.assertj.core.api.Assertions.assertThat +import org.tabletest.junit.TableTest + +class BranchFirstVersioningTest { + // A blank expectedLine means the branch name is not a release line (fromBranch returns null). + @TableTest( + """ + scenario | branch | expectedLine + release line | release/v1.69.x | 1.69 + major release line | release/v2.0.x | 2.0 + multi-digit line | release/v10.123.x | 10.123 + patch branch name | release/v1.69.1 | + missing patch placeholder | release/v1.69 | + other release-like branch | release/v1.69.x-ff | + nested release-like branch | release/v1.69.x/fix | + master | master | + feature branch | mo/release/v1.69.x | + """ + ) + fun parsesReleaseLineFromBranchName(branch: String, expectedLine: String?) { + assertThat(ReleaseLine.fromBranch(branch)?.toString()).isEqualTo(expectedLine) + } + + @TableTest( + """ + scenario | refs | expectedLine + no release branch | [] | + ls-remote output | ['abc123\trefs/heads/release/v1.68.x', 'def456\trefs/heads/release/v1.69.x'] | 1.69 + for-each-ref output | [refs/remotes/origin/release/v1.69.x, refs/remotes/origin/release/v1.68.x] | 1.69 + numeric not lexical order | [refs/remotes/origin/release/v1.9.x, refs/remotes/origin/release/v1.10.x] | 1.10 + major beats minor | [refs/remotes/origin/release/v1.99.x, refs/remotes/origin/release/v2.0.x] | 2.0 + unparsable names ignored | [refs/remotes/origin/release/v1.99.x-test, refs/remotes/origin/release/v1.68.x] | 1.68 + only unparsable names | [refs/remotes/origin/release/v1.99, refs/remotes/origin/release/vnext] | + """ + ) + fun findsNewestReleaseLine(refs: List, expectedLine: String?) { + val tabSeparatedRefs = refs.map { it.replace("\\t", "\t") } + assertThat(BranchFirstVersioning.newestReleaseLine(tabSeparatedRefs)?.toString()).isEqualTo(expectedLine) + } + + @TableTest( + """ + scenario | lastTag | newestReleaseLine | expectedVersion + no release branch | 1.68.0 | | 1.69.0 + release branch of last tag line | 1.68.0 | 1.68 | 1.69.0 + older release branch | 1.68.2 | 1.67 | 1.69.0 + release branch cut before its tag | 1.68.0 | 1.69 | 1.70.0 + release branch of new major | 1.99.0 | 2.0 | 2.1.0 + """ + ) + fun computesNextMinorVersion(lastTag: String, newestReleaseLine: String?, expectedVersion: String) { + val line = newestReleaseLine?.let { ReleaseLine.fromBranch("release/v$it.x") } + assertThat(BranchFirstVersioning.nextMinorVersion(Version.parse(lastTag), line).toString()).isEqualTo(expectedVersion) + } + + @TableTest( + """ + scenario | commitsSinceCut | qualifier | dirty | useSnapshot | expectedVersion + at branch cut | 0 | | false | true | 1.69.0-rc.0 + after pin commit | 1 | | false | true | 1.69.0-rc.1 + with qualifier | 2 | ddprof | false | true | 1.69.0-ddprof-rc.2 + blank qualifier | 2 | ' ' | false | true | 1.69.0-rc.2 + dirty with snapshot | 1 | | true | true | 1.69.0-rc.1-DIRTY + dirty without snapshot | 1 | | true | false | 1.69.0-rc.1-dirty + qualifier and dirty | 3 | ddprof | true | true | 1.69.0-ddprof-rc.3-DIRTY + """ + ) + fun buildsFirstReleaseCandidateVersion( + commitsSinceCut: Int, + qualifier: String?, + dirty: Boolean, + useSnapshot: Boolean, + expectedVersion: String, + ) { + val version = BranchFirstVersioning.firstReleaseCandidateVersion( + ReleaseLine(1, 69), + commitsSinceCut, + qualifier, + dirty, + useSnapshot, + ) + assertThat(version).isEqualTo(expectedVersion) + } +}