Skip to content

Commit

Permalink
Set published-version github output after 'publish' task
Browse files Browse the repository at this point in the history
  • Loading branch information
radoslaw-panuszewski committed Oct 20, 2024
1 parent 099f892 commit e2f1d1d
Show file tree
Hide file tree
Showing 5 changed files with 200 additions and 22 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,23 +16,34 @@ class BaseIntegrationTest extends RepositoryBasedTest {
}

void buildFile(String contents) {
new FileTreeBuilder(temporaryFolder).file("build.gradle", """
plugins {
id 'pl.allegro.tech.build.axion-release'
}
""" + contents +
new FileTreeBuilder(temporaryFolder).file("build.gradle",
"""
plugins {
id 'pl.allegro.tech.build.axion-release'
}
project.version = scmVersion.version
scmVersion.ignoreGlobalGitConfig = true
""")
$contents
project.version = scmVersion.version
scmVersion.ignoreGlobalGitConfig = true
"""
)
}

void vanillaBuildFile(String contents) {
new FileTreeBuilder(temporaryFolder).file("build.gradle", contents)
}

void vanillaSubprojectBuildFile(String subprojectName, String contents) {
new FileTreeBuilder(temporaryFolder).dir(subprojectName) {
file("build.gradle", contents)
}
}

void vanillaSettingsFile(String contents) {
new FileTreeBuilder(temporaryFolder).file("settings.gradle", contents)
}

GradleRunner gradle() {
return GradleRunner.create()
.withProjectDir(temporaryFolder)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package pl.allegro.tech.build.axion.release

import org.gradle.testkit.runner.BuildResult
import org.gradle.testkit.runner.TaskOutcome
import org.gradle.testkit.runner.UnexpectedBuildFailure
import org.junit.Rule
import org.junit.contrib.java.lang.system.EnvironmentVariables

Expand Down Expand Up @@ -40,7 +42,7 @@ class SimpleIntegrationTest extends BaseIntegrationTest {
result.task(":currentVersion").outcome == TaskOutcome.SUCCESS
}

def "should define a github output when running release task in github workflow context"() {
def "should set released-version github output after release task"() {
given:
def outputFile = File.createTempFile("github-outputs", ".tmp")
environmentVariablesRule.set("GITHUB_ACTIONS", "true")
Expand All @@ -59,6 +61,103 @@ class SimpleIntegrationTest extends BaseIntegrationTest {
environmentVariablesRule.clear("GITHUB_ACTIONS", "GITHUB_OUTPUT")
}

def "should set published-version github output after publish task"(String task, List<String> outputs) {
given:
def outputFile = File.createTempFile("github-outputs", ".tmp")
environmentVariablesRule.set("GITHUB_ACTIONS", "true")
environmentVariablesRule.set("GITHUB_OUTPUT", outputFile.getAbsolutePath())

vanillaSettingsFile("""
rootProject.name = 'root-project'
include 'sub-project'
"""
)

vanillaBuildFile("""
plugins {
id 'pl.allegro.tech.build.axion-release'
id 'maven-publish'
}
version = '1.0.0'
"""
)

vanillaSubprojectBuildFile("sub-project", """
plugins {
id 'pl.allegro.tech.build.axion-release'
id 'maven-publish'
}
version = '2.0.0'
"""
)

when:
runGradle(task)

then:
def definedEnvVariables = outputFile.getText().lines().collect(toList())
definedEnvVariables.size() == outputs.size()
definedEnvVariables.containsAll(outputs)

cleanup:
environmentVariablesRule.clear("GITHUB_ACTIONS", "GITHUB_OUTPUT")

where:
task || outputs
'publish' || ['published-version=1.0.0', 'root-project-published-version=1.0.0', 'sub-project-published-version=2.0.0']
':publish' || ['published-version=1.0.0', 'root-project-published-version=1.0.0']
':sub-project:publish' || ['published-version=2.0.0', 'sub-project-published-version=2.0.0']
}

def "should not set published-version github output if the publish task failed"() {
given:
def outputFile = File.createTempFile("github-outputs", ".tmp")
environmentVariablesRule.set("GITHUB_ACTIONS", "true")
environmentVariablesRule.set("GITHUB_OUTPUT", outputFile.getAbsolutePath())

vanillaBuildFile("""
plugins {
id 'pl.allegro.tech.build.axion-release'
id 'java-library'
id 'maven-publish'
}
group = 'com.example'
version = '1.0.0'
publishing {
repositories {
maven {
url = 'https://maven.example.com'
}
}
publications {
library(MavenPublication) {
from components.java
}
}
}
"""
)

when:
BuildResult buildResult;
try {
buildResult = runGradle('publish')
} catch(UnexpectedBuildFailure e) {
buildResult = e.buildResult
}

then:
outputFile.getText().lines().collect(toList()).isEmpty()

cleanup:
environmentVariablesRule.clear("GITHUB_ACTIONS", "GITHUB_OUTPUT")
}

def "should return released version on calling cV on repo with release commit"() {
given:
buildFile('')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ package pl.allegro.tech.build.axion.release

import org.gradle.api.Plugin
import org.gradle.api.Project
import org.gradle.api.provider.Provider
import org.gradle.api.publish.maven.tasks.AbstractPublishToMaven
import pl.allegro.tech.build.axion.release.domain.SnapshotDependenciesChecker
import pl.allegro.tech.build.axion.release.domain.VersionConfig
import pl.allegro.tech.build.axion.release.infrastructure.di.VersionResolutionContext
import pl.allegro.tech.build.axion.release.infrastructure.github.GithubFacade
import pl.allegro.tech.build.axion.release.util.FileLoader

abstract class ReleasePlugin implements Plugin<Project> {
Expand All @@ -21,7 +24,7 @@ abstract class ReleasePlugin implements Plugin<Project> {
void apply(Project project) {
FileLoader.setRoot(project.rootDir)

def versionConfig = project.extensions.create(VERSION_EXTENSION, VersionConfig, project.rootProject.layout.projectDirectory)
VersionConfig versionConfig = project.extensions.create(VERSION_EXTENSION, VersionConfig, project.rootProject.layout.projectDirectory)

project.tasks.withType(BaseAxionTask).configureEach({
it.versionConfig = versionConfig
Expand All @@ -42,6 +45,7 @@ abstract class ReleasePlugin implements Plugin<Project> {
group = 'Release'
description = 'Performs release - creates tag and pushes it to remote.'
dependsOn(VERIFY_RELEASE_TASK)
it.projectName = project.name
}

project.tasks.register(CREATE_RELEASE_TASK, CreateReleaseTask) {
Expand All @@ -65,9 +69,25 @@ abstract class ReleasePlugin implements Plugin<Project> {
description = 'Prints current project version extracted from SCM.'
}

setGithubOutputsAfterPublishTask(project)

maybeDisableReleaseTasks(project, versionConfig)
}

private setGithubOutputsAfterPublishTask(Project project) {
String projectName = project.name
Provider<String> projectVersion = project.provider { project.version.toString() }

project.plugins.withId("maven-publish") {
project.tasks.withType(AbstractPublishToMaven) { task ->
task.doLast {
GithubFacade.setOutputIfNotAlreadySet("published-version", projectVersion.get())
GithubFacade.setOutput("$projectName-published-version", projectVersion.get())
}
}
}
}

private static void maybeDisableReleaseTasks(Project project, VersionConfig versionConfig) {
project.afterEvaluate {
def context = VersionResolutionContext.create(versionConfig, project.layout.projectDirectory)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,19 @@
package pl.allegro.tech.build.axion.release

import org.gradle.api.provider.Property
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import pl.allegro.tech.build.axion.release.domain.Releaser
import pl.allegro.tech.build.axion.release.domain.scm.ScmPushResult
import pl.allegro.tech.build.axion.release.domain.scm.ScmPushResultOutcome
import pl.allegro.tech.build.axion.release.infrastructure.di.VersionResolutionContext

import java.nio.file.Files
import java.nio.file.Paths
import java.nio.file.StandardOpenOption
import pl.allegro.tech.build.axion.release.infrastructure.github.GithubFacade

abstract class ReleaseTask extends BaseAxionTask {

@Input
abstract Property<String> getProjectName()

@TaskAction
void release() {
VersionResolutionContext context = resolutionContext()
Expand All @@ -28,13 +30,9 @@ abstract class ReleaseTask extends BaseAxionTask {
}

if (result.outcome === ScmPushResultOutcome.SUCCESS) {
if (System.getenv().containsKey('GITHUB_ACTIONS')) {
Files.write(
Paths.get(System.getenv('GITHUB_OUTPUT')),
"released-version=${versionConfig.uncached.decoratedVersion}\n".getBytes(),
StandardOpenOption.APPEND
)
}
String version = versionConfig.uncached.decoratedVersion
GithubFacade.setOutputIfNotAlreadySet("released-version", version)
GithubFacade.setOutput("${projectName.get()}-released-version", version)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
package pl.allegro.tech.build.axion.release.infrastructure.github;

import org.gradle.api.logging.Logger;
import org.gradle.api.logging.Logging;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class GithubFacade {

private static final Logger logger = Logging.getLogger(GithubFacade.class);
private static final String GITHUB_ACTIONS = "GITHUB_ACTIONS";
private static final String GITHUB_OUTPUT = "GITHUB_OUTPUT";

public static void setOutputIfNotAlreadySet(String name, String value) {
if (System.getenv().containsKey(GITHUB_ACTIONS)) {
try {
boolean alreadySet = Files.readAllLines(githubOutputPath()).stream()
.anyMatch(line -> line.startsWith(name + "="));

if (!alreadySet) {
setOutput(name, value);
}
} catch (IOException e) {
logger.warn("Unable to the verify whether '{}' GitHub output is already set, cause: {}", name, e.getMessage());
}
}
}

public static void setOutput(String name, String value) {
if (System.getenv().containsKey(GITHUB_ACTIONS)) {
try {
Files.write(
githubOutputPath(),
String.format("%s=%s\n", name, value).getBytes(),
StandardOpenOption.APPEND
);
} catch (IOException e) {
logger.warn("Unable to the set '{}' GitHub output, cause: {}", name, e.getMessage());
}
}
}

private static Path githubOutputPath() {
return Paths.get(System.getenv(GITHUB_OUTPUT));
}
}

0 comments on commit e2f1d1d

Please sign in to comment.