Updates for new sagain api, s-c-build 3.1 and boot 2.6 (#243)

Updates releaser to use spring cloud build 3.1.0

Transitively uses boot 2.6

Updates releaser to use new Sagan API

Fixes gh-196
Fixes gh-194
This commit is contained in:
Spencer Gibb
2022-02-18 14:29:17 -05:00
committed by GitHub
parent 2e7d318f13
commit e83cda4fed
195 changed files with 2914 additions and 4881 deletions

View File

@@ -12,7 +12,7 @@
<parent>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-build</artifactId>
<version>2.2.3.RELEASE</version>
<version>3.1.0</version>
<relativePath/>
<!-- lookup parent from repository -->
</parent>
@@ -21,7 +21,7 @@
<module>releaser-core</module>
<module>releaser-spring</module>
<module>releaser-test</module>
<module>spring-cloud-info</module>
<!--<module>spring-cloud-info</module>-->
<module>projects</module>
<module>docs</module>
</modules>
@@ -41,7 +41,7 @@
<handlebars.version>4.2.0</handlebars.version>
<initializr-metadata.version>0.10.0-SNAPSHOT</initializr-metadata.version>
<awaitility.version>4.0.3</awaitility.version>
<sagan-site.version>1.0.0.BUILD-SNAPSHOT</sagan-site.version>
<sagan-site.version>1.0.0-SNAPSHOT</sagan-site.version>
<javax.json.version>1.1.4</javax.json.version>
<jopt-simple.version>5.0.4</jopt-simple.version>
<fliptables.version>1.1.0</fliptables.version>

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReleaserApplication extends ReleaserCommandLineRunner {
public ReleaserApplication(SpringReleaser releaser,
ExecutionResultHandler executionResultHandler, Parser parser) {
public ReleaserApplication(SpringReleaser releaser, ExecutionResultHandler executionResultHandler, Parser parser) {
super(releaser, executionResultHandler, parser);
}

View File

@@ -48,39 +48,31 @@ class CfConfiguration {
@Bean
PasswordGrantTokenProvider tokenProvider(@Value("${cf.username}") String username,
@Value("${cf.password}") String password) {
return PasswordGrantTokenProvider.builder().password(password).username(username)
return PasswordGrantTokenProvider.builder().password(password).username(username).build();
}
@Bean
ReactorCloudFoundryClient cloudFoundryClient(ConnectionContext connectionContext, TokenProvider tokenProvider) {
return ReactorCloudFoundryClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider)
.build();
}
@Bean
ReactorCloudFoundryClient cloudFoundryClient(ConnectionContext connectionContext,
TokenProvider tokenProvider) {
return ReactorCloudFoundryClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider).build();
ReactorDopplerClient dopplerClient(ConnectionContext connectionContext, TokenProvider tokenProvider) {
return ReactorDopplerClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build();
}
@Bean
ReactorDopplerClient dopplerClient(ConnectionContext connectionContext,
TokenProvider tokenProvider) {
return ReactorDopplerClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider).build();
ReactorUaaClient uaaClient(ConnectionContext connectionContext, TokenProvider tokenProvider) {
return ReactorUaaClient.builder().connectionContext(connectionContext).tokenProvider(tokenProvider).build();
}
@Bean
ReactorUaaClient uaaClient(ConnectionContext connectionContext,
TokenProvider tokenProvider) {
return ReactorUaaClient.builder().connectionContext(connectionContext)
.tokenProvider(tokenProvider).build();
}
@Bean
DefaultCloudFoundryOperations defaultCloudFoundryOperations(
CloudFoundryClient cloudFoundryClient, DopplerClient dopplerClient,
UaaClient uaaClient, @Value("${cf.organization}") String organizationId,
DefaultCloudFoundryOperations defaultCloudFoundryOperations(CloudFoundryClient cloudFoundryClient,
DopplerClient dopplerClient, UaaClient uaaClient, @Value("${cf.organization}") String organizationId,
@Value("${cf.space}") String spaceId) {
return DefaultCloudFoundryOperations.builder()
.cloudFoundryClient(cloudFoundryClient).dopplerClient(dopplerClient)
.uaaClient(uaaClient).organization(organizationId).space(spaceId).build();
return DefaultCloudFoundryOperations.builder().cloudFoundryClient(cloudFoundryClient)
.dopplerClient(dopplerClient).uaaClient(uaaClient).organization(organizationId).space(spaceId).build();
}
}

View File

@@ -61,11 +61,9 @@ import releaser.internal.tech.ExecutionResult;
/**
* @author Simon Baslé
*/
public class GenerateReleaseNotesTask
implements ProjectPostReleaseReleaserTask, DryRunReleaseReleaserTask {
public class GenerateReleaseNotesTask implements ProjectPostReleaseReleaserTask, DryRunReleaseReleaserTask {
private static final Logger log = LoggerFactory
.getLogger(GenerateReleaseNotesTask.class);
private static final Logger log = LoggerFactory.getLogger(GenerateReleaseNotesTask.class);
private static final String NAME = "releaseNotes";
@@ -106,20 +104,18 @@ public class GenerateReleaseNotesTask
}
@Override
public ExecutionResult runTask(Arguments args)
throws BuildUnstableException, RuntimeException {
public ExecutionResult runTask(Arguments args) throws BuildUnstableException, RuntimeException {
if (args.versionFromBom.isSnapshot()) {
log.info("\nWon't generate notes for a snapshot version");
return ExecutionResult.success();
}
Repo repo = github.repos().get(new Coordinates.Simple(
args.properties.getGit().getOrgName(), args.projectToRun.name()));
Repo repo = github.repos()
.get(new Coordinates.Simple(args.properties.getGit().getOrgName(), args.projectToRun.name()));
String releaseTag = "v" + args.versionFromBom.version;
if (args.options.dryRun != Boolean.TRUE) {
Optional<String> maybeTagSha1 = gitHandler.findTagSha1(args.project,
releaseTag);
Optional<String> maybeTagSha1 = gitHandler.findTagSha1(args.project, releaseTag);
if (maybeTagSha1.isPresent()) {
String tagSha1 = maybeTagSha1.get();
try {
@@ -127,16 +123,13 @@ public class GenerateReleaseNotesTask
repo.git().references().get("tags/" + tagSha1).json();
}
catch (IOException e) {
return ExecutionResult.failure(new IllegalStateException(
"Shouldn't create a release if tag " + releaseTag + " (sha1="
+ tagSha1 + ") not visible in Github",
e));
return ExecutionResult.failure(new IllegalStateException("Shouldn't create a release if tag "
+ releaseTag + " (sha1=" + tagSha1 + ") not visible in Github", e));
}
}
else {
return ExecutionResult.failure(new IllegalStateException(
"Attempting to draft release note but tag not found in repository: "
+ releaseTag));
"Attempting to draft release note but tag not found in repository: " + releaseTag));
}
}
@@ -144,34 +137,26 @@ public class GenerateReleaseNotesTask
EnumMap<Type, List<ChangelogEntry>> entries = new EnumMap<>(Type.class);
String toVersionTag = "v" + args.versionFromBom.version;
if (args.options.dryRun == Boolean.TRUE
&& !gitHandler.findTagSha1(args.project, toVersionTag).isPresent()) {
if (args.options.dryRun == Boolean.TRUE && !gitHandler.findTagSha1(args.project, toVersionTag).isPresent()) {
toVersionTag = "HEAD";
}
// eg. 3.2.1 for current 3.2.2
String fromVersionTag = args.versionFromBom
.computePreviousPatchTag("v", "RELEASE").orElseGet(() -> {
Pattern pattern = args.versionFromBom
.computePreviousMinorTagPattern("v", "RELEASE")
.orElseGet(() -> args.versionFromBom
.computePreviousMajorTagPattern("v", "RELEASE"));
// eg. v3.2.*.RELEASE or v3.*.*.RELEASE
log.info(
"Couldn't simply compute previous version of {}, looking through tag list with pattern {}",
args.versionFromBom.version, pattern.pattern());
String fromVersionTag = args.versionFromBom.computePreviousPatchTag("v", "RELEASE").orElseGet(() -> {
Pattern pattern = args.versionFromBom.computePreviousMinorTagPattern("v", "RELEASE")
.orElseGet(() -> args.versionFromBom.computePreviousMajorTagPattern("v", "RELEASE"));
// eg. v3.2.*.RELEASE or v3.*.*.RELEASE
log.info("Couldn't simply compute previous version of {}, looking through tag list with pattern {}",
args.versionFromBom.version, pattern.pattern());
List<String> sortedTags = gitHandler
.findTagNamesMatching(args.project, pattern)
.collect(Collectors.toList());
if (sortedTags.isEmpty()) {
throw new IllegalStateException(
"Couldn't find a tag that matches pattern "
+ pattern.pattern());
}
sortedTags.forEach(System.out::println);
return sortedTags.get(0);
});
List<String> sortedTags = gitHandler.findTagNamesMatching(args.project, pattern)
.collect(Collectors.toList());
if (sortedTags.isEmpty()) {
throw new IllegalStateException("Couldn't find a tag that matches pattern " + pattern.pattern());
}
sortedTags.forEach(System.out::println);
return sortedTags.get(0);
});
if (Boolean.TRUE == args.options.interactive) {
log.info("\nComputed log range is {}..{}", fromVersionTag, toVersionTag);
@@ -189,8 +174,7 @@ public class GenerateReleaseNotesTask
log.info("Will fetch the log for range {}..{}", fromVersionTag, toVersionTag);
// gather commits. we use tags in the format `vVERSION`
final List<SimpleCommit> revCommits = gitHandler.commitsBetween(args.project,
fromVersionTag, toVersionTag);
final List<SimpleCommit> revCommits = gitHandler.commitsBetween(args.project, fromVersionTag, toVersionTag);
// parse and link to issues if possible, determining type
for (SimpleCommit revCommit : revCommits) {
@@ -202,8 +186,7 @@ public class GenerateReleaseNotesTask
}
// generate the notes
String notes = generateNotes(args, entries,
extractContributorMentions(repo, revCommits));
String notes = generateNotes(args, entries, extractContributorMentions(repo, revCommits));
if (args.options.dryRun != null && args.options.dryRun) {
// print out
@@ -220,8 +203,7 @@ public class GenerateReleaseNotesTask
JsonObject draftReleaseJson = null;
try {
// attempt to find gh release with this tag. stop at 2 month old releases
Instant oldestReleaseToConsider = ZonedDateTime.now().minusMonths(2)
.toInstant();
Instant oldestReleaseToConsider = ZonedDateTime.now().minusMonths(2).toInstant();
for (Release release : repo.releases().iterate()) {
JsonObject releaseJson = release.json();
// seems the created release has a wrong tag "untagged-xxxxx", we also
@@ -229,8 +211,8 @@ public class GenerateReleaseNotesTask
if (releaseJson.getString("tag_name").equals(releaseTag)
|| releaseJson.getString("name").equals(releaseTag)) {
if (!releaseJson.getBoolean("draft")) {
return ExecutionResult.failure(new IllegalStateException(
"Release already exists for tag " + releaseTag));
return ExecutionResult
.failure(new IllegalStateException("Release already exists for tag " + releaseTag));
}
else {
draftRelease = new Release.Smart(release);
@@ -252,16 +234,14 @@ public class GenerateReleaseNotesTask
}
}
catch (Throwable e) {
return ExecutionResult.failure(new IllegalStateException(
"Unable to try to match github releases with tag " + releaseTag,
e));
return ExecutionResult.failure(
new IllegalStateException("Unable to try to match github releases with tag " + releaseTag, e));
}
if (draftReleaseJson == null) {
// create a draft release for the tag
try {
Release.Smart release = new Release.Smart(
repo.releases().create(releaseTag));
Release.Smart release = new Release.Smart(repo.releases().create(releaseTag));
release.draft(true);
release.tag(releaseTag);
release.name(releaseTag);
@@ -279,8 +259,7 @@ public class GenerateReleaseNotesTask
// update the existing draft
try {
// edit the release
String oldAndNewNotes = draftReleaseJson.getString("body")
+ "\n\n----\nNew draft added "
String oldAndNewNotes = draftReleaseJson.getString("body") + "\n\n----\nNew draft added "
+ LocalDateTime.now().toString() + "\n----\n" + notes;
draftRelease.body(oldAndNewNotes);
return ExecutionResult.success();
@@ -295,18 +274,15 @@ public class GenerateReleaseNotesTask
/**
* Generate the release notes.
*/
protected String generateNotes(Arguments args,
EnumMap<Type, List<ChangelogEntry>> entries,
protected String generateNotes(Arguments args, EnumMap<Type, List<ChangelogEntry>> entries,
List<String> contributorGithubMentions) {
// TODO use a template? handlebars !
StringBuilder notes = new StringBuilder().append(args.projectToRun.name())
.append(" `").append(args.versionFromBom.version)
.append("` is part of **`").append(args.releaseTrain().version)
StringBuilder notes = new StringBuilder().append(args.projectToRun.name()).append(" `")
.append(args.versionFromBom.version).append("` is part of **`").append(args.releaseTrain().version)
.append("` Release Train**.");
notes.append("\n\n## :warning: Update considerations and deprecations");
for (ChangelogEntry noteworthy : entries.getOrDefault(Type.NOTEWORTHY,
Collections.emptyList())) {
for (ChangelogEntry noteworthy : entries.getOrDefault(Type.NOTEWORTHY, Collections.emptyList())) {
notes.append("\n - ").append(noteworthy.description);
for (String issueTitle : noteworthy.associatedIssueLinksAndTitles.values()) {
notes.append("\n\t - ").append(cleanupShortMessage(issueTitle));
@@ -314,8 +290,7 @@ public class GenerateReleaseNotesTask
}
notes.append("\n\n## :sparkles: New features and improvements");
for (ChangelogEntry feature : entries.getOrDefault(Type.FEATURE,
Collections.emptyList())) {
for (ChangelogEntry feature : entries.getOrDefault(Type.FEATURE, Collections.emptyList())) {
notes.append("\n - ").append(feature.description);
for (String issueTitle : feature.associatedIssueLinksAndTitles.values()) {
notes.append("\n\t - ").append(cleanupShortMessage(issueTitle));
@@ -323,8 +298,7 @@ public class GenerateReleaseNotesTask
}
notes.append("\n\n## :beetle: Bug fixes");
for (ChangelogEntry bug : entries.getOrDefault(Type.BUG,
Collections.emptyList())) {
for (ChangelogEntry bug : entries.getOrDefault(Type.BUG, Collections.emptyList())) {
notes.append("\n - ").append(bug.description);
for (String issueTitle : bug.associatedIssueLinksAndTitles.values()) {
notes.append("\n\t - ").append(cleanupShortMessage(issueTitle));
@@ -332,8 +306,7 @@ public class GenerateReleaseNotesTask
}
notes.append("\n\n## :book: Documentation, Tests and Build");
for (ChangelogEntry misc : entries.getOrDefault(Type.DOC_MISC,
Collections.emptyList())) {
for (ChangelogEntry misc : entries.getOrDefault(Type.DOC_MISC, Collections.emptyList())) {
notes.append("\n - ").append(misc.description);
for (String issueTitle : misc.associatedIssueLinksAndTitles.values()) {
notes.append("\n\t - ").append(cleanupShortMessage(issueTitle));
@@ -341,18 +314,15 @@ public class GenerateReleaseNotesTask
}
notes.append("\n\n## **TODO DISPATCH THESE**");
for (ChangelogEntry unclassified : entries.getOrDefault(Type.UNCLASSIFIED,
Collections.emptyList())) {
for (ChangelogEntry unclassified : entries.getOrDefault(Type.UNCLASSIFIED, Collections.emptyList())) {
notes.append("\n - ").append(unclassified.description);
for (String issueTitle : unclassified.associatedIssueLinksAndTitles
.values()) {
for (String issueTitle : unclassified.associatedIssueLinksAndTitles.values()) {
notes.append("\n\t - ").append(cleanupShortMessage(issueTitle));
}
}
// contributors
notes.append(
"\n\n## :+1: Thanks to the following contributors that also participated to this release\n");
notes.append("\n\n## :+1: Thanks to the following contributors that also participated to this release\n");
notes.append(String.join(", ", contributorGithubMentions));
return notes.toString();
@@ -400,8 +370,7 @@ public class GenerateReleaseNotesTask
return EnumSet.copyOf(types);
}
protected String commitToGithubMention(RepoCommits commitsClient,
SimpleCommit revCommit) {
protected String commitToGithubMention(RepoCommits commitsClient, SimpleCommit revCommit) {
RepoCommit dumbCommit = commitsClient.get(revCommit.fullSha1);
RepoCommit.Smart smartCommit = new RepoCommit.Smart(dumbCommit);
try {
@@ -412,17 +381,14 @@ public class GenerateReleaseNotesTask
}
else if (authorType == JsonValue.ValueType.NULL) {
// assume author+committer, look under commit.author.name
if (commitJson.containsKey("commit")
&& commitJson.getJsonObject("commit").containsKey("author")) {
return "@" + commitJson.getJsonObject("commit")
.getJsonObject("author").getString("name");
if (commitJson.containsKey("commit") && commitJson.getJsonObject("commit").containsKey("author")) {
return "@" + commitJson.getJsonObject("commit").getJsonObject("author").getString("name");
}
}
// in case unexpected json, output the "sha", "commit", "author" and
// "committer"
return "@RAW{\"sha\", " + commitJson.get("sha") + ", \"author\", \""
+ commitJson.get("author") + ", \"committer\", \""
+ commitJson.get("committer") + ", \"commit\", \""
return "@RAW{\"sha\", " + commitJson.get("sha") + ", \"author\", \"" + commitJson.get("author")
+ ", \"committer\", \"" + commitJson.get("committer") + ", \"commit\", \""
+ commitJson.get("commit") + "}";
}
catch (IOException e) {
@@ -437,9 +403,8 @@ public class GenerateReleaseNotesTask
*/
List<String> extractContributorMentions(Repo repo, List<SimpleCommit> revCommits) {
RepoCommits commitsClient = repo.commits();
return revCommits.stream().map(c -> commitToGithubMention(commitsClient, c))
.filter(Objects::nonNull).distinct().sorted(String.CASE_INSENSITIVE_ORDER)
.collect(Collectors.toList());
return revCommits.stream().map(c -> commitToGithubMention(commitsClient, c)).filter(Objects::nonNull).distinct()
.sorted(String.CASE_INSENSITIVE_ORDER).collect(Collectors.toList());
}
/**
@@ -487,8 +452,7 @@ public class GenerateReleaseNotesTask
* The labels and titles are injected in a {@link Set} of labels and {@link Map} of
* hashtag issue links to issue titles.
*/
protected void fetchIssueLabelsAndTitles(Issues issueClient,
Set<Integer> issueNumbers, Set<String> labelsTarget,
protected void fetchIssueLabelsAndTitles(Issues issueClient, Set<Integer> issueNumbers, Set<String> labelsTarget,
Map<String, String> referencedIssuesTarget) {
issueNumbers.forEach(i -> {
try {
@@ -496,10 +460,9 @@ public class GenerateReleaseNotesTask
// we have everything handy in the JSON
Issue issue = issueClient.get(i);
JsonObject issueJson = issue.json();
issueJson.getJsonArray("labels").forEach(label -> labelsTarget
.add(((JsonObject) label).getString("name")));
referencedIssuesTarget.put("#" + issueJson.getInt("number"),
issueJson.getString("title"));
issueJson.getJsonArray("labels")
.forEach(label -> labelsTarget.add(((JsonObject) label).getString("name")));
referencedIssuesTarget.put("#" + issueJson.getInt("number"), issueJson.getString("title"));
}
catch (Exception e) {
log.warn("Could not fetch issue information for #" + i, e);
@@ -510,20 +473,17 @@ public class GenerateReleaseNotesTask
/**
* Extract issue information from the commit and generate the {@link ChangelogEntry}.
*/
protected ChangelogEntry parseChangeLogEntry(Issues issueClient,
SimpleCommit commit) {
protected ChangelogEntry parseChangeLogEntry(Issues issueClient, SimpleCommit commit) {
String cleanShortMessage = cleanupShortMessage(commit);
Set<Integer> issueNumbers = extractIssueNumbers(commit);
Set<String> labelsTarget = new HashSet<>();
Map<String, String> referencedIssuesTarget = new LinkedHashMap<>();
fetchIssueLabelsAndTitles(issueClient, issueNumbers, labelsTarget,
referencedIssuesTarget);
fetchIssueLabelsAndTitles(issueClient, issueNumbers, labelsTarget, referencedIssuesTarget);
EnumSet<Type> types = extractTypes(labelsTarget, commit.title);
return new ChangelogEntry(types, commit.abbreviatedSha1, cleanShortMessage,
referencedIssuesTarget);
return new ChangelogEntry(types, commit.abbreviatedSha1, cleanShortMessage, referencedIssuesTarget);
}
/*
@@ -534,8 +494,7 @@ public class GenerateReleaseNotesTask
* reflecting the PR number in case there has been extensive review/discussion in that
* PR. Both references would be caught by ISSUE_REF pattern below.
*/
static Pattern SHORT_MESSAGE = Pattern
.compile("(?:[a-zA-Z]+ #[0-9]+)?([^\\(]+)(?:\\(#[0-9]+\\))?");
static Pattern SHORT_MESSAGE = Pattern.compile("(?:[a-zA-Z]+ #[0-9]+)?([^\\(]+)(?:\\(#[0-9]+\\))?");
/**
* A {@link Pattern} to find issue/pr numbers in a commit message, by detecting
@@ -607,8 +566,7 @@ public class GenerateReleaseNotesTask
}
else {
this.description = cleanShortMessage + " ("
+ String.join(", ", this.associatedIssueLinksAndTitles.keySet())
+ ")";
+ String.join(", ", this.associatedIssueLinksAndTitles.keySet()) + ")";
}
}

View File

@@ -41,27 +41,24 @@ class ReactorConfiguration {
}
@Bean
RestartSiteProjectPostReleaseTask restartSiteProjectPostReleaseTask(Releaser releaser,
CfClient cfClient, @Value("${cf.reactorAppName}") String reactorAppName) {
RestartSiteProjectPostReleaseTask restartSiteProjectPostReleaseTask(Releaser releaser, CfClient cfClient,
@Value("${cf.reactorAppName}") String reactorAppName) {
return new RestartSiteProjectPostReleaseTask(releaser, cfClient, reactorAppName);
}
@Bean
Github githubClient(ReleaserProperties properties) {
if (!StringUtils.hasText(properties.getGit().getOauthToken())) {
throw new BeanInitializationException(
"You must set the value of the OAuth token. You can do it "
+ "either via the command line [--releaser.git.oauth-token=...] "
+ "or put it as an env variable in [~/.bashrc] or "
+ "[~/.zshrc] e.g. [export RELEASER_GIT_OAUTH_TOKEN=...]");
throw new BeanInitializationException("You must set the value of the OAuth token. You can do it "
+ "either via the command line [--releaser.git.oauth-token=...] "
+ "or put it as an env variable in [~/.bashrc] or "
+ "[~/.zshrc] e.g. [export RELEASER_GIT_OAUTH_TOKEN=...]");
}
return new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry()
.through(RetryWire.class));
return new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry().through(RetryWire.class));
}
@Bean
GenerateReleaseNotesTask releaseNotesTask(Github github,
ProjectGitHandler gitHandler) {
GenerateReleaseNotesTask releaseNotesTask(Github github, ProjectGitHandler gitHandler) {
return new GenerateReleaseNotesTask(github, gitHandler);
}

View File

@@ -31,8 +31,7 @@ public class RestartSiteProjectPostReleaseTask extends PublishDocsReleaseTask {
private final String reactorAppName;
public RestartSiteProjectPostReleaseTask(Releaser releaser, CfClient cfClient,
String reactorAppName) {
public RestartSiteProjectPostReleaseTask(Releaser releaser, CfClient cfClient, String reactorAppName) {
super(releaser);
this.cfClient = cfClient;
this.reactorAppName = reactorAppName;
@@ -58,8 +57,7 @@ class CfClient {
}
void restartApp(String name) {
this.cloudFoundryOperations.applications()
.restart(RestartApplicationRequest.builder().name(name).build());
this.cloudFoundryOperations.applications().restart(RestartApplicationRequest.builder().name(name).build());
}
}

View File

@@ -49,13 +49,11 @@ class ReleaserApplicationTests {
@Test
void should_load_generate_release_notes_in_dry_run() {
Map<String, DryRunReleaseReleaserTask> beans = context
.getBeansOfType(DryRunReleaseReleaserTask.class);
Map<String, DryRunReleaseReleaserTask> beans = context.getBeansOfType(DryRunReleaseReleaserTask.class);
List<ReleaserTask> inOrder = new LinkedList<>(beans.values());
inOrder.sort(AnnotationAwareOrderComparator.INSTANCE);
assertThat(inOrder).anySatisfy(
task -> assertThat(task).isInstanceOf(GenerateReleaseNotesTask.class));
assertThat(inOrder).anySatisfy(task -> assertThat(task).isInstanceOf(GenerateReleaseNotesTask.class));
}
@Test
@@ -64,11 +62,9 @@ class ReleaserApplicationTests {
List<ReleaserTask> inOrder = new LinkedList<>(beans.values());
inOrder.sort(AnnotationAwareOrderComparator.INSTANCE);
assertThat(inOrder).anySatisfy(task -> assertThat(task)
.isInstanceOf(RestartSiteProjectPostReleaseTask.class));
assertThat(inOrder).noneSatisfy(
task -> assertThat(task).isInstanceOf(PublishDocsReleaseTask.class)
.isNotInstanceOf(RestartSiteProjectPostReleaseTask.class));
assertThat(inOrder).anySatisfy(task -> assertThat(task).isInstanceOf(RestartSiteProjectPostReleaseTask.class));
assertThat(inOrder).noneSatisfy(task -> assertThat(task).isInstanceOf(PublishDocsReleaseTask.class)
.isNotInstanceOf(RestartSiteProjectPostReleaseTask.class));
}

View File

@@ -60,23 +60,22 @@ class GenerateReleaseNotesTaskTest {
@Test
void extractTypeFromLabel() {
assertThat(task.extractTypes(Collections.singleton("type/bug"), ""))
.as("type/bug").containsOnly(Type.BUG);
assertThat(task.extractTypes(Collections.singleton("type/bug"), "")).as("type/bug").containsOnly(Type.BUG);
assertThat(task.extractTypes(Collections.singleton("type/enhancement"), ""))
.as("type/enhancement").containsOnly(Type.FEATURE);
assertThat(task.extractTypes(Collections.singleton("type/enhancement"), "")).as("type/enhancement")
.containsOnly(Type.FEATURE);
assertThat(task.extractTypes(Collections.singleton("type/documentation"), ""))
.as("type/documentation").containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.singleton("type/documentation"), "")).as("type/documentation")
.containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.singleton("type/chores"), ""))
.as("type/chores").containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.singleton("type/chores"), "")).as("type/chores")
.containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.singleton("warn/something"), ""))
.as("warn/*").containsOnly(Type.NOTEWORTHY);
assertThat(task.extractTypes(Collections.singleton("warn/something"), "")).as("warn/*")
.containsOnly(Type.NOTEWORTHY);
assertThat(task.extractTypes(Collections.singleton("type/whatever"), ""))
.as("type/whatever").containsOnly(Type.UNCLASSIFIED);
assertThat(task.extractTypes(Collections.singleton("type/whatever"), "")).as("type/whatever")
.containsOnly(Type.UNCLASSIFIED);
}
@Test
@@ -87,179 +86,158 @@ class GenerateReleaseNotesTaskTest {
labels.add("type/documentation");
labels.add("whatever");
assertThat(task.extractTypes(labels, "")).as("multiple labels")
.containsOnly(Type.BUG, Type.FEATURE, Type.DOC_MISC);
assertThat(task.extractTypes(labels, "")).as("multiple labels").containsOnly(Type.BUG, Type.FEATURE,
Type.DOC_MISC);
}
@Test
void extractMiscTypeFromBuildMessagePrefix() {
String message = "[build] Foo";
assertThat(task.extractTypes(Collections.emptySet(), message))
.containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.emptySet(), message)).containsOnly(Type.DOC_MISC);
}
@Test
void extractMiscTypeFromPolishMessagePrefix() {
String message = "[polish] Foo";
assertThat(task.extractTypes(Collections.emptySet(), message))
.containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.emptySet(), message)).containsOnly(Type.DOC_MISC);
}
@Test
void extractMiscTypeFromDocMessagePrefix() {
String message = "[doc] Foo";
assertThat(task.extractTypes(Collections.emptySet(), message))
.containsOnly(Type.DOC_MISC);
assertThat(task.extractTypes(Collections.emptySet(), message)).containsOnly(Type.DOC_MISC);
}
@Test
void extractUnclassifiedTypeFromRandomMessagePrefix() {
String message = "fix #123 There was a [bug], needed to [polish] the [doc]";
assertThat(task.extractTypes(Collections.emptySet(), message))
.containsOnly(Type.UNCLASSIFIED);
assertThat(task.extractTypes(Collections.emptySet(), message)).containsOnly(Type.UNCLASSIFIED);
}
@Test
void noTitleCleanupFromMergeCommit() {
SimpleCommit mergeCommit = new SimpleCommit("sha1", "fullsha1",
"merge #123 into 3.3 (#123)", "merge #123 into 3.3", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", true);
SimpleCommit mergeCommit = new SimpleCommit("sha1", "fullsha1", "merge #123 into 3.3 (#123)",
"merge #123 into 3.3", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", true);
assertThat(task.cleanupShortMessage(mergeCommit))
.isEqualTo("merge #123 into 3.3 (#123)");
assertThat(task.cleanupShortMessage(mergeCommit)).isEqualTo("merge #123 into 3.3 (#123)");
}
@Test
void titleCleanupFixPrefix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"fix #123 Text from title", "fix #123 Some more text", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "fix #123 Text from title",
"fix #123 Some more text", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io",
false);
assertThat(task.cleanupShortMessage(commit)).isEqualTo("Text from title");
}
@Test
void titleCleanupSeePrefix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"see #123 Text from title", "see #123 Some more text", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "see #123 Text from title",
"see #123 Some more text", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io",
false);
assertThat(task.cleanupShortMessage(commit)).isEqualTo("Text from title");
}
@Test
void titleCleanupPrStyleSuffix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"Commit without issue (#123)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "Commit without issue (#123)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.cleanupShortMessage(commit)).isEqualTo("Commit without issue");
}
@Test
void titleCleanupPrStyleSuffixNoSpace() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"Commit without issue(#123)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "Commit without issue(#123)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.cleanupShortMessage(commit)).isEqualTo("Commit without issue");
}
@Test
void titleCleanupBothPrefixAndSuffix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title (#123)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title (#123)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.cleanupShortMessage(commit)).isEqualTo("Commit title");
}
@Test
void issueNumberTitlePrefix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.extractIssueNumbers(commit)).containsOnly(123);
}
@Test
void issueNumberTitlePrStyleSuffix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "Commit title (#123)",
"fullMessage", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé",
"sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "Commit title (#123)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.extractIssueNumbers(commit)).containsOnly(123);
}
@Test
void issueNumberTitlePrefixAndSuffix() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title (#456)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title (#456)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.extractIssueNumbers(commit)).containsOnly(123, 456);
}
@Test
void issueNumberTitleNotSeparatedBySpace() {
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix#123Commit title(#456)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix#123Commit title(#456)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(task.extractIssueNumbers(commit)).containsOnly(123, 456);
}
static final VoidAnswer4<Issues, Set<Integer>, Set<String>, Map<String, String>> MOCK_FETCH_ISSUES = (
ignore1, issues, ignore2, resolved) -> issues
.forEach(i -> resolved.put("#" + i, "alternative title for " + i));
static final VoidAnswer4<Issues, Set<Integer>, Set<String>, Map<String, String>> MOCK_FETCH_ISSUES = (ignore1,
issues, ignore2, resolved) -> issues.forEach(i -> resolved.put("#" + i, "alternative title for " + i));
static final Issues MOCK_ISSUES = Mockito.mock(Issues.class);
@Test
void generateChangelogDescriptionSingleIssueTwice() throws IOException {
final GenerateReleaseNotesTask spy = Mockito.spy(task);
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(),
any(), any(), any());
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(), any(), any(), any());
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title (#123)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title (#123)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(),
commit).description).isEqualTo("Commit title (#123)");
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(), commit).description)
.isEqualTo("Commit title (#123)");
}
@Test
void generateChangelogDescriptionTwoIssues() throws IOException {
final GenerateReleaseNotesTask spy = Mockito.spy(task);
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(),
any(), any(), any());
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(), any(), any(), any());
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title (#456)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title (#456)", "fullMessage",
"Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(spy.parseChangeLogEntry(MOCK_ISSUES, commit).description)
.isEqualTo("Commit title (#123, #456)");
assertThat(spy.parseChangeLogEntry(MOCK_ISSUES, commit).description).isEqualTo("Commit title (#123, #456)");
}
@Test
void generateChangelogDescriptionTwoIssuesNoSpace() throws IOException {
final GenerateReleaseNotesTask spy = Mockito.spy(task);
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(),
any(), any(), any());
doAnswer(answerVoid(MOCK_FETCH_ISSUES)).when(spy).fetchIssueLabelsAndTitles(any(), any(), any(), any());
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123Commit title no space(#456)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123Commit title no space(#456)",
"fullMessage", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(),
commit).description).isEqualTo("Commit title no space (#123, #456)");
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(), commit).description)
.isEqualTo("Commit title no space (#123, #456)");
}
@Test
@@ -267,12 +245,11 @@ class GenerateReleaseNotesTaskTest {
final GenerateReleaseNotesTask spy = Mockito.spy(task);
doNothing().when(spy).fetchIssueLabelsAndTitles(any(), any(), any(), any());
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1",
"prefix #123 Commit title no space(#456)", "fullMessage", "Simon Baslé",
"sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
SimpleCommit commit = new SimpleCommit("sha1", "fullsha1", "prefix #123 Commit title no space(#456)",
"fullMessage", "Simon Baslé", "sbasle@pivotal.io", "Simon Baslé", "sbasle@pivotal.io", false);
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(),
commit).description).isEqualTo("Commit title no space (sha1)");
assertThat(spy.parseChangeLogEntry(githubClient.randomRepo().issues(), commit).description)
.isEqualTo("Commit title no space (sha1)");
}
@Test
@@ -284,9 +261,8 @@ class GenerateReleaseNotesTaskTest {
assertThatExceptionOfType(Exception.class).as("github client fails")
.isThrownBy(() -> new Issue.Smart(issuesClient.get(123)).title());
assertThatCode(() -> task.fetchIssueLabelsAndTitles(issuesClient,
Collections.singleton(123), labels, associatedIssues))
.as("fetching just does nothing").doesNotThrowAnyException();
assertThatCode(() -> task.fetchIssueLabelsAndTitles(issuesClient, Collections.singleton(123), labels,
associatedIssues)).as("fetching just does nothing").doesNotThrowAnyException();
assertThat(labels).as("labels").isEmpty();
assertThat(associatedIssues).as("associated issues").isEmpty();

View File

@@ -46,14 +46,13 @@ import org.springframework.context.annotation.Profile;
public class ReactorTestConfiguration {
@Bean
RestartSiteProjectPostReleaseTask restartSiteProjectPostReleaseTask(Releaser releaser,
CfClient cfClient, @Value("${cf.reactorAppName}") String reactorAppName) {
RestartSiteProjectPostReleaseTask restartSiteProjectPostReleaseTask(Releaser releaser, CfClient cfClient,
@Value("${cf.reactorAppName}") String reactorAppName) {
return new RestartSiteProjectPostReleaseTask(releaser, cfClient, reactorAppName);
}
@Bean
GenerateReleaseNotesTask releaseNotesTask(Github github,
ProjectGitHandler gitHandler) {
GenerateReleaseNotesTask releaseNotesTask(Github github, ProjectGitHandler gitHandler) {
return new GenerateReleaseNotesTask(github, gitHandler);
}

View File

@@ -16,8 +16,6 @@
package releaser.reactor;
import static org.junit.jupiter.api.Assertions.fail;
import org.assertj.core.api.BDDAssertions;
import org.junit.jupiter.api.Test;
import org.mockito.BDDMockito;
@@ -34,6 +32,8 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.ActiveProfiles;
import static org.junit.jupiter.api.Assertions.fail;
@SpringBootTest
@ActiveProfiles("test")
class RestartSiteProjectPostReleaseTaskTests {
@@ -51,16 +51,13 @@ class RestartSiteProjectPostReleaseTaskTests {
ExecutionResult result = task.runTask(arguments);
BDDAssertions.then(result.isSuccess()).isTrue();
BDDMockito.then(this.cfClient).should()
.restartApp(BDDMockito.eq("projectreactor"));
BDDMockito.then(this.cfClient).should().restartApp(BDDMockito.eq("projectreactor"));
}
@Test
void should_fail_if_original_version_is_null() {
ProjectToRun p = new ProjectToRun(null,
new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
null, new ReleaserProperties(),
BDDMockito.mock(Options.class)) {
ProjectToRun p = new ProjectToRun(null, new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
null, new ReleaserProperties(), BDDMockito.mock(Options.class)) {
@Override
public String name() {
return "reactor-core";
@@ -86,10 +83,8 @@ class RestartSiteProjectPostReleaseTaskTests {
}
private ProjectToRun reactorCoreProject() {
return new ProjectToRun(null,
new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
new ProjectVersion("foo", "1.0.0"), new ReleaserProperties(),
BDDMockito.mock(Options.class)) {
return new ProjectToRun(null, new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
new ProjectVersion("foo", "1.0.0"), new ReleaserProperties(), BDDMockito.mock(Options.class)) {
@Override
public String name() {
return "reactor-core";
@@ -98,10 +93,8 @@ class RestartSiteProjectPostReleaseTaskTests {
}
private ProjectToRun nonReactorCoreProject() {
return new ProjectToRun(null,
new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
new ProjectVersion("foo", "1.0.0"), new ReleaserProperties(),
BDDMockito.mock(Options.class)) {
return new ProjectToRun(null, new ProjectsFromBom(new Projects(), new ProjectVersion("foo", "1.0.0")),
new ProjectVersion("foo", "1.0.0"), new ReleaserProperties(), BDDMockito.mock(Options.class)) {
@Override
public String name() {
return "whatever";

View File

@@ -1,6 +1,3 @@
cf:
username: foo
password: bar
spring:
profiles:
active: test
password: bar

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReleaserApplication extends ReleaserCommandLineRunner {
public ReleaserApplication(SpringReleaser releaser,
ExecutionResultHandler executionResultHandler, Parser parser) {
public ReleaserApplication(SpringReleaser releaser, ExecutionResultHandler executionResultHandler, Parser parser) {
super(releaser, executionResultHandler, parser);
}

View File

@@ -24,8 +24,7 @@ final class SpringCloudBomConstants {
// boot
static final String SPRING_BOOT = "spring-boot";
static final String BOOT_STARTER_ARTIFACT_ID = "spring-boot-starter";
static final String BOOT_STARTER_PARENT_ARTIFACT_ID = BOOT_STARTER_ARTIFACT_ID
+ "-parent";
static final String BOOT_STARTER_PARENT_ARTIFACT_ID = BOOT_STARTER_ARTIFACT_ID + "-parent";
static final String BOOT_DEPENDENCIES_ARTIFACT_ID = "spring-boot-dependencies";
// sc-build

View File

@@ -51,17 +51,15 @@ import static releaser.cloud.buildsystem.SpringCloudBomConstants.STREAM_STARTER_
class SpringCloudStreamMavenBomParser implements CustomBomParser {
private static final Logger log = LoggerFactory
.getLogger(SpringCloudStreamMavenBomParser.class);
private static final Logger log = LoggerFactory.getLogger(SpringCloudStreamMavenBomParser.class);
@Override
public VersionsFromBom parseBom(File root, ReleaserProperties properties) {
VersionsFromBom springCloudBuild = springCloudBuild(root, properties);
VersionsFromBom boot = bootVersion(root, properties);
log.debug("Added Spring Cloud Build [{}] and boot versions [{}]",
springCloudBuild, boot);
return new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).projects(springCloudBuild, boot).merged();
log.debug("Added Spring Cloud Build [{}] and boot versions [{}]", springCloudBuild, boot);
return new VersionsFromBomBuilder().thisProjectRoot(root).releaserProperties(properties)
.projects(springCloudBuild, boot).merged();
}
private VersionsFromBom springCloudBuild(File root, ReleaserProperties properties) {
@@ -69,8 +67,8 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
if (StringUtils.isEmpty(buildVersion)) {
return VersionsFromBom.EMPTY_VERSION;
}
VersionsFromBom scBuild = new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).merged();
VersionsFromBom scBuild = new VersionsFromBomBuilder().thisProjectRoot(root).releaserProperties(properties)
.merged();
scBuild.add(BUILD_ARTIFACT_ID, buildVersion);
scBuild.add(CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildVersion);
return scBuild;
@@ -87,11 +85,9 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
}
Model model = PomReader.pom(root, properties.getPom().getThisTrainBom());
String buildArtifact = model.getParent().getArtifactId();
log.debug("[{}] artifact id is equal to [{}]",
CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildArtifact);
log.debug("[{}] artifact id is equal to [{}]", CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildArtifact);
if (!CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID.equals(buildArtifact)) {
throw new IllegalStateException(
"The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
throw new IllegalStateException("The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
}
buildVersion = model.getParent().getVersion();
log.debug("Spring Cloud Build version is equal to [{}]", buildVersion);
@@ -103,8 +99,7 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
if (StringUtils.hasText(bootVersion)) {
return bootVersion;
}
String pomWithBootStarterParent = properties.getPom()
.getPomWithBootStarterParent();
String pomWithBootStarterParent = properties.getPom().getPomWithBootStarterParent();
File pom = new File(root, pomWithBootStarterParent);
if (!pom.exists()) {
return "";
@@ -117,8 +112,8 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
log.debug("Boot artifact id is equal to [{}]", bootArtifactId);
if (!BOOT_STARTER_PARENT_ARTIFACT_ID.equals(bootArtifactId)) {
if (log.isDebugEnabled()) {
throw new IllegalStateException("The pom doesn't have a ["
+ BOOT_STARTER_PARENT_ARTIFACT_ID + "] artifact id");
throw new IllegalStateException(
"The pom doesn't have a [" + BOOT_STARTER_PARENT_ARTIFACT_ID + "] artifact id");
}
return "";
}
@@ -131,8 +126,8 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
return VersionsFromBom.EMPTY_VERSION;
}
log.debug("Boot version is equal to [{}]", bootVersion);
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder()
.thisProjectRoot(root).releaserProperties(properties).merged();
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).merged();
versionsFromBom.add(SPRING_BOOT, bootVersion);
versionsFromBom.add(BOOT_STARTER_PARENT_ARTIFACT_ID, bootVersion);
versionsFromBom.add(BOOT_DEPENDENCIES_ARTIFACT_ID, bootVersion);
@@ -140,8 +135,7 @@ class SpringCloudStreamMavenBomParser implements CustomBomParser {
}
@Override
public Set<Project> setVersion(Set<Project> projects, String projectName,
String version) {
public Set<Project> setVersion(Set<Project> projects, String projectName, String version) {
Set<Project> newProjects = new LinkedHashSet<>(projects);
switch (projectName) {
case SPRING_BOOT:

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@SpringBootTest(
classes = { ReleaserApplicationTests.Config.class, ReleaserApplication.class },
@SpringBootTest(classes = { ReleaserApplicationTests.Config.class, ReleaserApplication.class },
properties = { "releaser.sagan.update-sagan=false" })
class ReleaserApplicationTests {

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class ReleaserApplication extends ReleaserCommandLineRunner {
public ReleaserApplication(SpringReleaser releaser,
ExecutionResultHandler executionResultHandler, Parser parser) {
public ReleaserApplication(SpringReleaser releaser, ExecutionResultHandler executionResultHandler, Parser parser) {
super(releaser, executionResultHandler, parser);
}

View File

@@ -24,8 +24,7 @@ final class SpringCloudBomConstants {
// boot
static final String SPRING_BOOT = "spring-boot";
static final String BOOT_STARTER_ARTIFACT_ID = "spring-boot-starter";
static final String BOOT_STARTER_PARENT_ARTIFACT_ID = BOOT_STARTER_ARTIFACT_ID
+ "-parent";
static final String BOOT_STARTER_PARENT_ARTIFACT_ID = BOOT_STARTER_ARTIFACT_ID + "-parent";
static final String BOOT_DEPENDENCIES_ARTIFACT_ID = "spring-boot-dependencies";
// sc-build

View File

@@ -52,17 +52,15 @@ import static releaser.cloud.buildsystem.SpringCloudBomConstants.STREAM_STARTER_
class SpringCloudMavenBomParser implements CustomBomParser {
private static final Logger log = LoggerFactory
.getLogger(SpringCloudMavenBomParser.class);
private static final Logger log = LoggerFactory.getLogger(SpringCloudMavenBomParser.class);
@Override
public VersionsFromBom parseBom(File root, ReleaserProperties properties) {
VersionsFromBom springCloudBuild = springCloudBuild(root, properties);
VersionsFromBom boot = bootVersion(root, properties);
log.debug("Added Spring Cloud Build [{}] and boot versions [{}]",
springCloudBuild, boot);
return new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).projects(springCloudBuild, boot).merged();
log.debug("Added Spring Cloud Build [{}] and boot versions [{}]", springCloudBuild, boot);
return new VersionsFromBomBuilder().thisProjectRoot(root).releaserProperties(properties)
.projects(springCloudBuild, boot).merged();
}
private VersionsFromBom springCloudBuild(File root, ReleaserProperties properties) {
@@ -70,8 +68,8 @@ class SpringCloudMavenBomParser implements CustomBomParser {
if (StringUtils.isEmpty(buildVersion)) {
return VersionsFromBom.EMPTY_VERSION;
}
VersionsFromBom scBuild = new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).merged();
VersionsFromBom scBuild = new VersionsFromBomBuilder().thisProjectRoot(root).releaserProperties(properties)
.merged();
scBuild.add(BUILD_ARTIFACT_ID, buildVersion);
scBuild.add(CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildVersion);
return scBuild;
@@ -88,11 +86,9 @@ class SpringCloudMavenBomParser implements CustomBomParser {
}
Model model = PomReader.pom(root, properties.getPom().getThisTrainBom());
String buildArtifact = model.getParent().getArtifactId();
log.debug("[{}] artifact id is equal to [{}]",
CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildArtifact);
log.debug("[{}] artifact id is equal to [{}]", CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID, buildArtifact);
if (!CLOUD_DEPENDENCIES_PARENT_ARTIFACT_ID.equals(buildArtifact)) {
throw new IllegalStateException(
"The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
throw new IllegalStateException("The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
}
buildVersion = model.getParent().getVersion();
log.debug("Spring Cloud Build version is equal to [{}]", buildVersion);
@@ -104,8 +100,7 @@ class SpringCloudMavenBomParser implements CustomBomParser {
if (StringUtils.hasText(bootVersion)) {
return bootVersion;
}
String pomWithBootStarterParent = properties.getPom()
.getPomWithBootStarterParent();
String pomWithBootStarterParent = properties.getPom().getPomWithBootStarterParent();
File pom = new File(root, pomWithBootStarterParent);
if (!pom.exists()) {
return "";
@@ -118,8 +113,8 @@ class SpringCloudMavenBomParser implements CustomBomParser {
log.debug("Boot artifact id is equal to [{}]", bootArtifactId);
if (!BOOT_STARTER_PARENT_ARTIFACT_ID.equals(bootArtifactId)) {
if (log.isDebugEnabled()) {
throw new IllegalStateException("The pom doesn't have a ["
+ BOOT_STARTER_PARENT_ARTIFACT_ID + "] artifact id");
throw new IllegalStateException(
"The pom doesn't have a [" + BOOT_STARTER_PARENT_ARTIFACT_ID + "] artifact id");
}
return "";
}
@@ -132,8 +127,8 @@ class SpringCloudMavenBomParser implements CustomBomParser {
return VersionsFromBom.EMPTY_VERSION;
}
log.debug("Boot version is equal to [{}]", bootVersion);
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder()
.thisProjectRoot(root).releaserProperties(properties).merged();
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder().thisProjectRoot(root)
.releaserProperties(properties).merged();
versionsFromBom.add(SPRING_BOOT, bootVersion);
versionsFromBom.add(BOOT_STARTER_PARENT_ARTIFACT_ID, bootVersion);
versionsFromBom.add(BOOT_DEPENDENCIES_ARTIFACT_ID, bootVersion);
@@ -141,8 +136,7 @@ class SpringCloudMavenBomParser implements CustomBomParser {
}
@Override
public Set<Project> setVersion(Set<Project> projects, String projectName,
String version) {
public Set<Project> setVersion(Set<Project> projects, String projectName, String version) {
Set<Project> newProjects = new LinkedHashSet<>(projects);
switch (projectName) {
case SPRING_BOOT:

View File

@@ -35,18 +35,15 @@ import org.springframework.util.StringUtils;
/**
* @author Marcin Grzejszczak
*/
class SpringCloudCustomProjectDocumentationUpdater
implements CustomProjectDocumentationUpdater {
class SpringCloudCustomProjectDocumentationUpdater implements CustomProjectDocumentationUpdater {
private static final Logger log = LoggerFactory
.getLogger(SpringCloudCustomProjectDocumentationUpdater.class);
private static final Logger log = LoggerFactory.getLogger(SpringCloudCustomProjectDocumentationUpdater.class);
private final ProjectGitHandler gitHandler;
private final ReleaserProperties releaserProperties;
SpringCloudCustomProjectDocumentationUpdater(ProjectGitHandler gitHandler,
ReleaserProperties releaserProperties) {
SpringCloudCustomProjectDocumentationUpdater(ProjectGitHandler gitHandler, ReleaserProperties releaserProperties) {
this.gitHandler = gitHandler;
this.releaserProperties = releaserProperties;
}
@@ -60,11 +57,10 @@ class SpringCloudCustomProjectDocumentationUpdater
* used
*/
@Override
public File updateDocsRepoForReleaseTrain(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects, String bomBranch) {
public File updateDocsRepoForReleaseTrain(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects, String bomBranch) {
if (!currentProject.projectName.startsWith("spring-cloud")) {
log.info(
"Skipping updating docs for project [{}] that does not start with spring-cloud prefix",
log.info("Skipping updating docs for project [{}] that does not start with spring-cloud prefix",
currentProject.projectName);
return clonedDocumentationProject;
}
@@ -72,12 +68,10 @@ class SpringCloudCustomProjectDocumentationUpdater
ProjectVersion releaseTrainProject = new ProjectVersion(
this.releaserProperties.getMetaRelease().getReleaseTrainProjectName(),
branchToReleaseVersion(bomBranch));
File currentReleaseFolder = new File(clonedDocumentationProject,
currentFolder(releaseTrainProject));
File currentReleaseFolder = new File(clonedDocumentationProject, currentFolder(releaseTrainProject));
// remove the old way
removeAFolderWithRedirection(currentReleaseFolder);
File docsRepo = updateTheDocsRepo(releaseTrainProject, clonedDocumentationProject,
currentReleaseFolder);
File docsRepo = updateTheDocsRepo(releaseTrainProject, clonedDocumentationProject, currentReleaseFolder);
return pushChanges(docsRepo);
}
@@ -89,8 +83,8 @@ class SpringCloudCustomProjectDocumentationUpdater
* used
*/
@Override
public File updateDocsRepoForSingleProject(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects) {
public File updateDocsRepoForSingleProject(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects) {
if (!projects.containsProject(currentProject.projectName)) {
log.warn(
"Can't update the documentation repo for project [{}] cause it's not present on the projects list {}",
@@ -98,23 +92,18 @@ class SpringCloudCustomProjectDocumentationUpdater
return clonedDocumentationProject;
}
if (!currentProject.projectName.startsWith("spring-cloud")) {
log.info(
"Skipping updating docs for project [{}] that does not start with spring-cloud prefix",
log.info("Skipping updating docs for project [{}] that does not start with spring-cloud prefix",
currentProject.projectName);
return clonedDocumentationProject;
}
log.info("Updating link to documentation for project [{}]",
currentProject.projectName);
ProjectVersion currentProjectVersion = projects
.forName(currentProject.projectName);
File currentProjectReleaseFolder = new File(clonedDocumentationProject,
currentFolder(currentProjectVersion));
log.info("Updating link to documentation for project [{}]", currentProject.projectName);
ProjectVersion currentProjectVersion = projects.forName(currentProject.projectName);
File currentProjectReleaseFolder = new File(clonedDocumentationProject, currentFolder(currentProjectVersion));
removeAFolderWithRedirection(currentProjectReleaseFolder);
try {
updateTheDocsRepo(currentProjectVersion, clonedDocumentationProject,
currentProjectReleaseFolder);
log.info("Processed [{}] for project with name [{}]",
currentProjectReleaseFolder, currentProjectVersion.projectName);
updateTheDocsRepo(currentProjectVersion, clonedDocumentationProject, currentProjectReleaseFolder);
log.info("Processed [{}] for project with name [{}]", currentProjectReleaseFolder,
currentProjectVersion.projectName);
}
catch (Exception ex) {
log.warn("Exception occurred while trying o update the symlink of a project ["
@@ -140,14 +129,13 @@ class SpringCloudCustomProjectDocumentationUpdater
releaseTrain = currentProjectVersion.isReleaseTrain();
}
catch (IllegalStateException ex) {
log.warn("Exception occurred while trying to resolve if version ["
+ currentProjectVersion + "] is a release train", ex);
log.warn("Exception occurred while trying to resolve if version [" + currentProjectVersion
+ "] is a release train", ex);
releaseTrain = false;
}
// release train -> static/current
// project -> static/spring-cloud-sleuth/current
return releaseTrain ? "current"
: (StringUtils.hasText(projectName) ? projectName : "") + "/current";
return releaseTrain ? "current" : (StringUtils.hasText(projectName) ? projectName : "") + "/current";
}
String linkToVersion(File file) {
@@ -176,33 +164,28 @@ class SpringCloudCustomProjectDocumentationUpdater
return docsRepo;
}
private File updateTheDocsRepo(ProjectVersion projectVersion,
File documentationProject, File currentVersionFolder) {
private File updateTheDocsRepo(ProjectVersion projectVersion, File documentationProject,
File currentVersionFolder) {
try {
String storedVersion = linkToVersion(currentVersionFolder);
String currentVersion = projectVersion.version;
boolean newerVersion = StringUtils.isEmpty(storedVersion)
|| isMoreMature(storedVersion, currentVersion);
boolean newerVersion = StringUtils.isEmpty(storedVersion) || isMoreMature(storedVersion, currentVersion);
if (!newerVersion) {
log.info("Current version [{}] is not newer than the stored one [{}]",
currentVersion, storedVersion);
log.info("Current version [{}] is not newer than the stored one [{}]", currentVersion, storedVersion);
return documentationProject;
}
boolean deleted = Files.deleteIfExists(currentVersionFolder.toPath())
|| FileSystemUtils.deleteRecursively(currentVersionFolder.toPath());
if (deleted) {
log.info("Deleted current version folder link at [{}]",
currentVersionFolder);
log.info("Deleted current version folder link at [{}]", currentVersionFolder);
}
boolean creatingParentDirs = currentVersionFolder.getParentFile().mkdirs();
if (!creatingParentDirs) {
log.warn("Failed to create parent directory of [{}]",
currentVersionFolder);
log.warn("Failed to create parent directory of [{}]", currentVersionFolder);
}
File newTarget = new File(projectVersion.version);
Files.createSymbolicLink(currentVersionFolder.toPath(), newTarget.toPath());
log.info("Updated the link [{}] to point to [{}]",
currentVersionFolder.toPath(),
log.info("Updated the link [{}] to point to [{}]", currentVersionFolder.toPath(),
Files.readSymbolicLink(currentVersionFolder.toPath()));
return commitChanges(currentVersion, documentationProject);
}
@@ -212,8 +195,7 @@ class SpringCloudCustomProjectDocumentationUpdater
}
private boolean isMoreMature(String storedVersion, String currentVersion) {
return new ProjectVersion("project", currentVersion)
.isMoreMature(new ProjectVersion("project", storedVersion));
return new ProjectVersion("project", currentVersion).isMoreMature(new ProjectVersion("project", storedVersion));
}
private String branchToReleaseVersion(String branch) {
@@ -223,8 +205,7 @@ class SpringCloudCustomProjectDocumentationUpdater
return branch;
}
private File commitChanges(String currentVersion, File documentationProject)
throws IOException {
private File commitChanges(String currentVersion, File documentationProject) throws IOException {
log.info("Updated the symbolic links");
this.gitHandler.commit(documentationProject,
"Updating the link to the current version to [" + currentVersion + "]");

View File

@@ -26,10 +26,9 @@ import org.springframework.context.annotation.Configuration;
class SpringCloudDocsConfiguration {
@Bean
SpringCloudCustomProjectDocumentationUpdater springCloudCustomProjectDocumentationUpdater(
ProjectGitHandler handler, ReleaserProperties releaserProperties) {
return new SpringCloudCustomProjectDocumentationUpdater(handler,
releaserProperties);
SpringCloudCustomProjectDocumentationUpdater springCloudCustomProjectDocumentationUpdater(ProjectGitHandler handler,
ReleaserProperties releaserProperties) {
return new SpringCloudCustomProjectDocumentationUpdater(handler, releaserProperties);
}
}

View File

@@ -25,8 +25,7 @@ import org.springframework.context.annotation.Configuration;
class SpringCloudGithubConfiguration {
@Bean
SpringCloudGithubIssues springCloudGithubIssues(
ReleaserProperties releaserProperties) {
SpringCloudGithubIssues springCloudGithubIssues(ReleaserProperties releaserProperties) {
return new SpringCloudGithubIssues(releaserProperties);
}

View File

@@ -47,16 +47,14 @@ class SpringCloudGithubIssues implements CustomGithubIssues {
public void fileIssueInSpringGuides(Projects projects, ProjectVersion version) {
String user = "spring-guides";
String repo = "getting-started-guides";
this.githubIssueFiler.fileAGitHubIssue(user, repo, version, issueTitle(),
guidesIssueText(projects));
this.githubIssueFiler.fileAGitHubIssue(user, repo, version, issueTitle(), guidesIssueText(projects));
}
@Override
public void fileIssueInStartSpringIo(Projects projects, ProjectVersion version) {
String user = "spring-io";
String repo = "start.spring.io";
this.githubIssueFiler.fileAGitHubIssue(user, repo, version, issueTitle(),
startSpringIoIssueText(projects));
this.githubIssueFiler.fileAGitHubIssue(user, repo, version, issueTitle(), startSpringIoIssueText(projects));
}
private String issueTitle() {
@@ -72,21 +70,18 @@ class SpringCloudGithubIssues implements CustomGithubIssues {
}
private String startSpringIoIssueText(Projects projects) {
String springBootVersion = projects.containsProject("spring-boot")
? projects.forName("spring-boot").version : "";
return "Release train ["
+ this.properties.getMetaRelease().getReleaseTrainProjectName()
+ "] in version [" + parsedVersion()
+ "] released with the Spring Boot version [`" + springBootVersion + "`]";
String springBootVersion = projects.containsProject("spring-boot") ? projects.forName("spring-boot").version
: "";
return "Release train [" + this.properties.getMetaRelease().getReleaseTrainProjectName() + "] in version ["
+ parsedVersion() + "] released with the Spring Boot version [`" + springBootVersion + "`]";
}
private String guidesIssueText(Projects projects) {
StringBuilder builder = new StringBuilder().append("Release train [")
.append(this.properties.getMetaRelease().getReleaseTrainProjectName())
.append("] in version [").append(parsedVersion())
.append("] released with the following projects:").append("\n\n");
projects.forEach(project -> builder.append(project.projectName).append(" : ")
.append("`").append(project.version).append("`").append("\n"));
.append(this.properties.getMetaRelease().getReleaseTrainProjectName()).append("] in version [")
.append(parsedVersion()).append("] released with the following projects:").append("\n\n");
projects.forEach(project -> builder.append(project.projectName).append(" : ").append("`")
.append(project.version).append("`").append("\n"));
return builder.toString();
}

View File

@@ -27,8 +27,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@SpringBootTest(
classes = { ReleaserApplicationTests.Config.class, ReleaserApplication.class },
@SpringBootTest(classes = { ReleaserApplicationTests.Config.class, ReleaserApplication.class },
properties = { "releaser.sagan.update-sagan=false" })
class ReleaserApplicationTests {

View File

@@ -32,17 +32,13 @@ public class SpringCloudReleaserProperties {
public static ReleaserProperties get() {
try {
File releaserConfig = new File(SpringCloudReleaserProperties.class
.getResource("/application.yml").toURI());
File releaserConfig = new File(SpringCloudReleaserProperties.class.getResource("/application.yml").toURI());
YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
yamlProcessor.setResources(new FileSystemResource(releaserConfig));
Properties properties = yamlProcessor.getObject();
ReleaserProperties releaserProperties = new Binder(
new MapConfigurationPropertySource(properties.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString()))))
.bind("releaser", ReleaserProperties.class)
.get();
ReleaserProperties releaserProperties = new Binder(new MapConfigurationPropertySource(properties.entrySet()
.stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))))
.bind("releaser", ReleaserProperties.class).get();
return releaserProperties;
}
catch (URISyntaxException e) {

View File

@@ -37,80 +37,59 @@ public class SpringCloudCustomMavenBomTests {
@Test
public void should_add_boot_to_versions_when_version_is_created() {
List<CustomBomParser> bomParsers = Collections
.singletonList(new SpringCloudMavenBomParser());
List<CustomBomParser> bomParsers = Collections.singletonList(new SpringCloudMavenBomParser());
VersionsFromBom customVersionsFromBom = new VersionsFromBomBuilder()
.releaserProperties(SpringCloudReleaserProperties.get())
.parsers(bomParsers).projects(springCloudBuildProjects())
.retrieveFromBom();
.releaserProperties(SpringCloudReleaserProperties.get()).parsers(bomParsers)
.projects(springCloudBuildProjects()).retrieveFromBom();
customVersionsFromBom.setVersion("spring-boot", "1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot"))
.isEqualTo("1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot-starter-parent"))
.isEqualTo("1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot-dependencies"))
.isEqualTo("1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot")).isEqualTo("1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot-starter-parent")).isEqualTo("1.2.3.RELEASE");
then(customVersionsFromBom.versionForProject("spring-boot-dependencies")).isEqualTo("1.2.3.RELEASE");
}
@Test
public void should_update_projects_for_boot() {
VersionsFromBom versionsFromBom = mixedVersions().setVersion("spring-boot",
"3.0.0");
VersionsFromBom versionsFromBom = mixedVersions().setVersion("spring-boot", "3.0.0");
then(versionsFromBom.versionForProject("spring-boot")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies")).isEqualTo("3.0.0");
versionsFromBom = mixedVersions().setVersion("spring-boot-starter-parent",
"3.0.0");
versionsFromBom = mixedVersions().setVersion("spring-boot-starter-parent", "3.0.0");
then(versionsFromBom.versionForProject("spring-boot")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies")).isEqualTo("3.0.0");
versionsFromBom = mixedVersions().setVersion("spring-boot-dependencies", "3.0.0");
then(versionsFromBom.versionForProject("spring-boot")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-starter-parent")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-boot-dependencies")).isEqualTo("3.0.0");
}
@Test
public void should_update_projects_for_build() {
VersionsFromBom versionsFromBom = mixedVersions().setVersion("spring-cloud-build",
"3.0.0");
VersionsFromBom versionsFromBom = mixedVersions().setVersion("spring-cloud-build", "3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-build")).isEqualTo("3.0.0");
versionsFromBom = mixedVersions().setVersion("spring-cloud-build", "3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies-parent"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies"))
.isEqualTo("Greenwich.RELEASE");
then(versionsFromBom.versionForProject("spring-cloud-dependencies-parent")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies")).isEqualTo("Greenwich.RELEASE");
versionsFromBom = mixedVersions().setVersion("spring-cloud-dependencies-parent",
"3.0.0");
versionsFromBom = mixedVersions().setVersion("spring-cloud-dependencies-parent", "3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-build")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies-parent"))
.isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies"))
.isEqualTo("Greenwich.RELEASE");
then(versionsFromBom.versionForProject("spring-cloud-dependencies-parent")).isEqualTo("3.0.0");
then(versionsFromBom.versionForProject("spring-cloud-dependencies")).isEqualTo("Greenwich.RELEASE");
}
private VersionsFromBom mixedVersions() {
return new VersionsFromBomBuilder()
.releaserProperties(SpringCloudReleaserProperties.get())
.parsers(Collections.singletonList(new SpringCloudMavenBomParser()))
.projects(mixedProjects()).merged();
return new VersionsFromBomBuilder().releaserProperties(SpringCloudReleaserProperties.get())
.parsers(Collections.singletonList(new SpringCloudMavenBomParser())).projects(mixedProjects()).merged();
}
Set<Project> springCloudBuildProjects() {

View File

@@ -57,31 +57,26 @@ public class SpringCloudMavenBomParserTests {
this.tmpFolder = this.tmp.newFolder();
TestUtils.prepareLocalRepo();
FileSystemUtils.copyRecursively(file("/projects"), this.tmpFolder);
this.springCloudReleaseProject = new File(this.tmpFolder,
"/spring-cloud-release");
this.springCloudReleaseProject = new File(this.tmpFolder, "/spring-cloud-release");
}
private File file(String relativePath) throws URISyntaxException {
return new File(
SpringCloudMavenBomParserTests.class.getResource(relativePath).toURI());
return new File(SpringCloudMavenBomParserTests.class.getResource(relativePath).toURI());
}
@Test
public void should_throw_exception_when_null_is_passed_to_boot() {
this.properties.getPom().setPomWithBootStarterParent(null);
this.properties.getPom().setThisTrainBom(null);
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
thenThrownBy(() -> parser.versionsFromBom(this.springCloudReleaseProject))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Pom is not present");
}
@Test
public void should_populate_sc_release_version() {
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
String scReleaseVersion = parser.versionsFromBom(this.springCloudReleaseProject)
.versionForProject("spring-cloud-release");
@@ -91,22 +86,18 @@ public class SpringCloudMavenBomParserTests {
@Test
public void should_populate_boot_version() {
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
String bootVersion = parser.versionsFromBom(this.springCloudReleaseProject)
.versionForProject("spring-boot");
String bootVersion = parser.versionsFromBom(this.springCloudReleaseProject).versionForProject("spring-boot");
then(bootVersion).isNotBlank();
}
@Test
public void should_throw_exception_when_cloud_pom_is_missing() {
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
thenThrownBy(() -> parser.versionsFromBom(new File(".")))
.isInstanceOf(IllegalStateException.class)
thenThrownBy(() -> parser.versionsFromBom(new File("."))).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
}
@@ -114,54 +105,44 @@ public class SpringCloudMavenBomParserTests {
public void should_throw_exception_when_null_is_passed_to_cloud() {
this.properties.getPom().setPomWithBootStarterParent(null);
this.properties.getPom().setThisTrainBom(null);
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
thenThrownBy(() -> parser.versionsFromBom(this.springCloudReleaseProject))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Pom is not present");
}
@Test
public void should_throw_exception_when_cloud_version_is_missing_in_pom() {
this.properties.getPom().setPomWithBootStarterParent("pom.xml");
this.properties.getPom().setThisTrainBom("pom.xml");
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
thenThrownBy(() -> parser.versionsFromBom(this.springCloudReleaseProject))
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
"The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("The pom doesn't have a [spring-cloud-dependencies-parent] artifact id");
}
@Test
public void should_populate_cloud_version() {
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
VersionsFromBom cloudVersionsFromBom = parser
.versionsFromBom(this.springCloudReleaseProject);
VersionsFromBom cloudVersionsFromBom = parser.versionsFromBom(this.springCloudReleaseProject);
thenAllCloudVersionsSet(cloudVersionsFromBom);
}
private void thenAllCloudVersionsSet(VersionsFromBom cloudVersionsFromBom) {
Arrays.asList("spring-cloud-bus", "spring-cloud-contract",
"spring-cloud-cloudfoundry", "spring-cloud-commons",
"spring-cloud-config", "spring-cloud-netflix", "spring-cloud-security",
"spring-cloud-consul", "spring-cloud-sleuth", "spring-cloud-stream",
"spring-cloud-task", "spring-cloud-vault", "spring-cloud-zookeeper")
.forEach(s -> then(cloudVersionsFromBom.versionForProject(s))
.isNotBlank());
Arrays.asList("spring-cloud-bus", "spring-cloud-contract", "spring-cloud-cloudfoundry", "spring-cloud-commons",
"spring-cloud-config", "spring-cloud-netflix", "spring-cloud-security", "spring-cloud-consul",
"spring-cloud-sleuth", "spring-cloud-stream", "spring-cloud-task", "spring-cloud-vault",
"spring-cloud-zookeeper").forEach(s -> then(cloudVersionsFromBom.versionForProject(s)).isNotBlank());
}
@Test
public void should_populate_boot_and_cloud_version() {
BomParser parser = MavenBomParserAccessor.bomParser(this.properties,
new SpringCloudMavenBomParser());
BomParser parser = MavenBomParserAccessor.bomParser(this.properties, new SpringCloudMavenBomParser());
VersionsFromBom cloudVersionsFromBom = parser
.versionsFromBom(this.springCloudReleaseProject);
VersionsFromBom cloudVersionsFromBom = parser.versionsFromBom(this.springCloudReleaseProject);
then(cloudVersionsFromBom.versionForProject("spring-boot")).isNotBlank();
then(cloudVersionsFromBom.versionForProject("spring-cloud-build")).isNotBlank();

View File

@@ -36,41 +36,31 @@ public class SpringCloudProjectPomUpdaterTests {
public void should_convert_fixed_versions_to_updated_fixed_versions() {
ReleaserProperties properties = SpringCloudReleaserProperties.get();
properties.getFixedVersions().put("spring-cloud-task", "2.0.0.RELEASE");
properties.getFixedVersions().put("spring-cloud-openfeign",
"2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-openfeign", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-consul", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-zookeeper",
"2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-zookeeper", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-stream", "Elmhurst.RELEASE");
properties.getFixedVersions().put("spring-cloud-config", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-cloudfoundry",
"2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-cloudfoundry", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-netflix", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-vault", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-security",
"2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-security", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-commons", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-sleuth", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-aws", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-contract",
"2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-release",
"Finchley.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-contract", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-release", "Finchley.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-build", "2.0.3.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-bus", "2.0.1.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-function",
"1.0.0.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-starter-build",
"Finchley.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-function", "1.0.0.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-cloud-starter-build", "Finchley.BUILD-SNAPSHOT");
properties.getFixedVersions().put("spring-boot", "2.0.3.RELEASE");
properties.getFixedVersions().put("spring-cloud-gateway", "2.0.1.BUILD-SNAPSHOT");
ProjectPomUpdater updater = new ProjectPomUpdater(properties,
Collections.singletonList(MavenBomParserAccessor.bomParser(properties,
new SpringCloudMavenBomParser())));
ProjectPomUpdater updater = new ProjectPomUpdater(properties, Collections
.singletonList(MavenBomParserAccessor.bomParser(properties, new SpringCloudMavenBomParser())));
Map<String, String> fixedVersions = updater.fixedVersions().stream()
.collect(Collectors.toMap(projectVersion -> projectVersion.projectName,
projectVersion -> projectVersion.version));
Map<String, String> fixedVersions = updater.fixedVersions().stream().collect(Collectors
.toMap(projectVersion -> projectVersion.projectName, projectVersion -> projectVersion.version));
BDDAssertions.then(fixedVersions).containsEntry("spring-boot", "2.0.3.RELEASE")
.containsEntry("spring-boot-dependencies", "2.0.3.RELEASE")

View File

@@ -70,23 +70,17 @@ public class SpringCloudCustomProjectDocumentationUpdaterTests {
.getResource("/projects/spring-cloud-static").toURI());
TestUtils.prepareLocalRepo();
FileSystemUtils.copyRecursively(file("/projects"), this.tmpFolder);
this.properties.getGit().setDocumentationUrl(
file("/projects/spring-cloud-static/").toURI().toString());
this.properties.getGit().setDocumentationUrl(file("/projects/spring-cloud-static/").toURI().toString());
this.handler = new ProjectGitHandler(this.properties);
this.clonedDocProject = this.handler.cloneDocumentationProject();
this.gitHubHandler = new ProjectGitHubHandler(this.properties,
Collections.singletonList(
SpringCloudGithubIssuesAccessor.springCloud(this.properties)));
Collections.singletonList(SpringCloudGithubIssuesAccessor.springCloud(this.properties)));
}
@NotNull
private DocumentationUpdater projectDocumentationUpdater(
ReleaserProperties properties) {
return new DocumentationUpdater(this.handler, properties,
templateGenerator(properties),
Collections.singletonList(
new SpringCloudCustomProjectDocumentationUpdater(this.handler,
properties)));
private DocumentationUpdater projectDocumentationUpdater(ReleaserProperties properties) {
return new DocumentationUpdater(this.handler, properties, templateGenerator(properties),
Collections.singletonList(new SpringCloudCustomProjectDocumentationUpdater(this.handler, properties)));
}
@NotNull
@@ -97,56 +91,43 @@ public class SpringCloudCustomProjectDocumentationUpdaterTests {
@Test
public void should_not_update_current_version_in_the_docs_if_current_release_starts_with_v_and_then_lower_letter_than_the_stored_release()
throws URISyntaxException, IOException {
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release",
"Finchley.SR33");
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release", "Finchley.SR33");
ReleaserProperties properties = new ReleaserProperties();
properties.getGit().setDocumentationUrl(
file("/projects/spring-cloud-static/").toURI().toString());
properties.getGit().setDocumentationUrl(file("/projects/spring-cloud-static/").toURI().toString());
File updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(
new ProjectGitHandler(properties), properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject,
releaseTrainVersion, projects(), "vFinchley.SR33");
File updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(new ProjectGitHandler(properties),
properties).updateDocsRepoForReleaseTrain(this.clonedDocProject, releaseTrainVersion, projects(),
"vFinchley.SR33");
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath())
.doesNotExist();
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath()).doesNotExist();
Path current = new File(updatedDocs, "current/").toPath();
BDDAssertions.then(current).isSymbolicLink();
BDDAssertions.then(Files.readSymbolicLink(current).toString())
.isEqualTo("Finchley.SR33");
BDDAssertions.then(Files.readSymbolicLink(current).toString()).isEqualTo("Finchley.SR33");
releaseTrainVersion = new ProjectVersion("spring-cloud-release", "Angel.SR33");
properties = new ReleaserProperties();
properties.getGit().setDocumentationUrl(
file("/projects/spring-cloud-static/").toURI().toString());
properties.getGit().setDocumentationUrl(file("/projects/spring-cloud-static/").toURI().toString());
updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(
new ProjectGitHandler(properties), properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject,
releaseTrainVersion, projects(), "vAngel.SR33");
updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(new ProjectGitHandler(properties), properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject, releaseTrainVersion, projects(), "vAngel.SR33");
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath())
.doesNotExist();
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath()).doesNotExist();
current = new File(updatedDocs, "current/").toPath();
BDDAssertions.then(current).isSymbolicLink();
BDDAssertions.then(Files.readSymbolicLink(current).toString())
.isNotEqualTo("Angel.SR33");
BDDAssertions.then(Files.readSymbolicLink(current).toString()).isNotEqualTo("Angel.SR33");
}
@Test
public void should_not_commit_if_the_same_version_is_already_there() {
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release",
"Dalston.SR3");
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release", "Dalston.SR3");
ReleaserProperties properties = new ReleaserProperties();
properties.getGit().setDocumentationUrl(this.clonedDocProject.toURI().toString());
ProjectGitHandler handler = BDDMockito.spy(new ProjectGitHandler(properties));
new SpringCloudCustomProjectDocumentationUpdater(handler, properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject, releaseTrainVersion,
projects(), "vDalston.SR3");
.updateDocsRepoForReleaseTrain(this.clonedDocProject, releaseTrainVersion, projects(), "vDalston.SR3");
BDDMockito.then(handler).should(BDDMockito.never())
.commit(BDDMockito.any(File.class), BDDMockito.anyString());
BDDMockito.then(handler).should(BDDMockito.never()).commit(BDDMockito.any(File.class), BDDMockito.anyString());
}
@Test
@@ -157,11 +138,9 @@ public class SpringCloudCustomProjectDocumentationUpdaterTests {
ProjectGitHandler handler = BDDMockito.spy(new ProjectGitHandler(properties));
new SpringCloudCustomProjectDocumentationUpdater(handler, properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject, springBootVersion,
bootProject(), "vDalston.SR3");
.updateDocsRepoForReleaseTrain(this.clonedDocProject, springBootVersion, bootProject(), "vDalston.SR3");
BDDMockito.then(handler).should(BDDMockito.never())
.commit(BDDMockito.any(File.class), BDDMockito.anyString());
BDDMockito.then(handler).should(BDDMockito.never()).commit(BDDMockito.any(File.class), BDDMockito.anyString());
}
@Test
@@ -172,37 +151,30 @@ public class SpringCloudCustomProjectDocumentationUpdaterTests {
ProjectGitHandler handler = BDDMockito.spy(new ProjectGitHandler(properties));
new SpringCloudCustomProjectDocumentationUpdater(handler, properties)
.updateDocsRepoForSingleProject(this.clonedDocProject, springBootVersion,
bootProject());
.updateDocsRepoForSingleProject(this.clonedDocProject, springBootVersion, bootProject());
BDDMockito.then(handler).should(BDDMockito.never())
.commit(BDDMockito.any(File.class), BDDMockito.anyString());
BDDMockito.then(handler).should(BDDMockito.never()).commit(BDDMockito.any(File.class), BDDMockito.anyString());
}
@Test
public void should_not_update_current_version_in_the_docs_if_current_release_starts_with_lower_letter_than_the_stored_release()
throws IOException {
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release",
"Angel.SR33");
ProjectVersion releaseTrainVersion = new ProjectVersion("spring-cloud-release", "Angel.SR33");
ReleaserProperties properties = new ReleaserProperties();
properties.getGit().setDocumentationUrl(this.clonedDocProject.toURI().toString());
File updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(
new ProjectGitHandler(properties), properties)
.updateDocsRepoForReleaseTrain(this.clonedDocProject,
releaseTrainVersion, projects(), "Angel.SR33");
File updatedDocs = new SpringCloudCustomProjectDocumentationUpdater(new ProjectGitHandler(properties),
properties).updateDocsRepoForReleaseTrain(this.clonedDocProject, releaseTrainVersion, projects(),
"Angel.SR33");
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath())
.doesNotExist();
BDDAssertions.then(new File(updatedDocs, "current/index.html").toPath()).doesNotExist();
Path current = new File(updatedDocs, "current/").toPath();
BDDAssertions.then(current).isSymbolicLink();
BDDAssertions.then(Files.readSymbolicLink(current).toString())
.isNotEqualTo("Angel.SR33");
BDDAssertions.then(Files.readSymbolicLink(current).toString()).isNotEqualTo("Angel.SR33");
}
private File file(String relativePath) throws URISyntaxException {
return new File(SpringCloudCustomProjectDocumentationUpdater.class
.getResource(relativePath).toURI());
return new File(SpringCloudCustomProjectDocumentationUpdater.class.getResource(relativePath).toURI());
}
private Projects projects() {

View File

@@ -36,8 +36,7 @@ public final class TestUtils {
prepareLocalRepo("target/test-classes/projects/", "spring-cloud-static");
}
private static void prepareLocalRepo(String buildDir, String repoPath)
throws IOException {
private static void prepareLocalRepo(String buildDir, String repoPath) throws IOException {
File dotGit = new File(buildDir + repoPath + "/.git");
File git = new File(buildDir + repoPath + "/git");
if (git.exists()) {

View File

@@ -22,8 +22,7 @@ import releaser.internal.github.CustomGithubIssues;
public class SpringCloudGithubIssuesAccessor {
public static CustomGithubIssues springCloud(Github github,
ReleaserProperties releaserProperties) {
public static CustomGithubIssues springCloud(Github github, ReleaserProperties releaserProperties) {
return new SpringCloudGithubIssues(github, releaserProperties);
}

View File

@@ -74,14 +74,12 @@ public class SpringCloudGithubIssuesTests {
Github github = BDDMockito.mock(Github.class);
CustomGithubIssues githubIssues = new SpringCloudGithubIssues(github, properties);
githubIssues
.fileIssueInSpringGuides(
new Projects(new ProjectVersion("foo", "1.0.0.BUILD-SNAPSHOT"),
new ProjectVersion("spring-cloud-build",
"2.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("sc-release", "Edgware.BUILD-SNAPSHOT"));
githubIssues.fileIssueInSpringGuides(
new Projects(new ProjectVersion("foo", "1.0.0.BUILD-SNAPSHOT"),
new ProjectVersion("spring-cloud-build", "2.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("sc-release", "Edgware.BUILD-SNAPSHOT"));
BDDMockito.then(github).shouldHaveZeroInteractions();
BDDMockito.then(github).shouldHaveNoInteractions();
}
@Test
@@ -92,20 +90,18 @@ public class SpringCloudGithubIssuesTests {
issues.fileIssueInSpringGuides(
new Projects(new ProjectVersion("spring-cloud-foo", "1.0.0.RELEASE"),
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"),
new ProjectVersion("bar", "2.0.0.RELEASE"),
new ProjectVersion("baz", "3.0.0.RELEASE")),
new ProjectVersion("bar", "2.0.0.RELEASE"), new ProjectVersion("baz", "3.0.0.RELEASE")),
new ProjectVersion("sc-release", "Edgware.RELEASE"));
Issue issue = this.github.repos()
.get(new Coordinates.Simple("spring-guides", "getting-started-guides"))
Issue issue = this.github.repos().get(new Coordinates.Simple("spring-guides", "getting-started-guides"))
.issues().get(1);
then(issue.exists()).isTrue();
Issue.Smart smartIssue = new Issue.Smart(issue);
then(smartIssue.title()).isEqualTo("Upgrade to Spring Cloud Edgware.RELEASE");
then(smartIssue.body()).contains(
"Release train [spring-cloud-release] in version [Edgware.RELEASE] released with the following projects")
.contains("spring-cloud-foo : `1.0.0.RELEASE`")
.contains("bar : `2.0.0.RELEASE`").contains("baz : `3.0.0.RELEASE`");
.contains("spring-cloud-foo : `1.0.0.RELEASE`").contains("bar : `2.0.0.RELEASE`")
.contains("baz : `3.0.0.RELEASE`");
}
@Test
@@ -114,16 +110,13 @@ public class SpringCloudGithubIssuesTests {
CustomGithubIssues issues = new SpringCloudGithubIssues(github, properties);
thenThrownBy(() -> issues.fileIssueInSpringGuides(
new Projects(Collections.singletonList(
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"))),
nonGaSleuthProject())).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"You have to pass Github OAuth token for milestone closing to be operational");
new Projects(Collections.singletonList(new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"))),
nonGaSleuthProject())).isInstanceOf(IllegalArgumentException.class).hasMessageContaining(
"You have to pass Github OAuth token for milestone closing to be operational");
}
@Test
public void should_not_do_anything_for_non_release_train_version_when_updating_startspringio()
throws IOException {
public void should_not_do_anything_for_non_release_train_version_when_updating_startspringio() throws IOException {
setupStartSpringIo();
Github github = BDDMockito.mock(Github.class);
CustomGithubIssues issues = new SpringCloudGithubIssues(github, properties);
@@ -133,27 +126,21 @@ public class SpringCloudGithubIssuesTests {
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE")),
new ProjectVersion("sc-release", "Edgware.BUILD-SNAPSHOT"));
BDDMockito.then(github).shouldHaveZeroInteractions();
BDDMockito.then(github).shouldHaveNoInteractions();
}
@Test
public void should_file_an_issue_for_release_version_when_updating_startspringio()
throws IOException {
public void should_file_an_issue_for_release_version_when_updating_startspringio() throws IOException {
setupStartSpringIo();
CustomGithubIssues issues = new SpringCloudGithubIssues(github, properties);
properties.getPom().setBranch("vEdgware.RELEASE");
issues.fileIssueInStartSpringIo(
new Projects(new ProjectVersion("spring-cloud-foo", "1.0.0.RELEASE"),
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"),
new ProjectVersion("bar", "2.0.0.RELEASE"),
new ProjectVersion("baz", "3.0.0.RELEASE"),
new ProjectVersion("spring-boot", "1.2.3.RELEASE")),
issues.fileIssueInStartSpringIo(new Projects(new ProjectVersion("spring-cloud-foo", "1.0.0.RELEASE"),
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"), new ProjectVersion("bar", "2.0.0.RELEASE"),
new ProjectVersion("baz", "3.0.0.RELEASE"), new ProjectVersion("spring-boot", "1.2.3.RELEASE")),
new ProjectVersion("sc-release", "Edgware.RELEASE"));
Issue issue = this.github.repos()
.get(new Coordinates.Simple("spring-io", "start.spring.io")).issues()
.get(1);
Issue issue = this.github.repos().get(new Coordinates.Simple("spring-io", "start.spring.io")).issues().get(1);
then(issue.exists()).isTrue();
Issue.Smart smartIssue = new Issue.Smart(issue);
then(smartIssue.title()).isEqualTo("Upgrade to Spring Cloud Edgware.RELEASE");
@@ -162,23 +149,19 @@ public class SpringCloudGithubIssuesTests {
}
@Test
public void should_throw_exception_when_no_token_was_passed_when_updating_startspringio()
throws IOException {
public void should_throw_exception_when_no_token_was_passed_when_updating_startspringio() throws IOException {
setupStartSpringIo();
properties.getGit().setOauthToken("");
CustomGithubIssues issues = new SpringCloudGithubIssues(github, properties);
thenThrownBy(() -> issues.fileIssueInStartSpringIo(
new Projects(Collections.singletonList(
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"))),
nonGaSleuthProject())).isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining(
"You have to pass Github OAuth token for milestone closing to be operational");
new Projects(Collections.singletonList(new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"))),
nonGaSleuthProject())).isInstanceOf(IllegalArgumentException.class).hasMessageContaining(
"You have to pass Github OAuth token for milestone closing to be operational");
}
private Repo createGettingStartedGuides(MkGithub github) throws IOException {
return github.repos()
.create(new Repos.RepoCreate("getting-started-guides", false));
return github.repos().create(new Repos.RepoCreate("getting-started-guides", false));
}
private Repo createStartSpringIo(MkGithub github) throws IOException {

View File

@@ -36,10 +36,10 @@ public class AbstractSpringCloudAcceptanceTests extends AbstractSpringAcceptance
@Before
public void setupCloud() throws Exception {
this.temporaryFolder = this.tmp.newFolder();
this.springCloudConsulProject = new File(AbstractSpringAcceptanceTests.class
.getResource("/projects/spring-cloud-consul").toURI());
this.springCloudBuildProject = new File(AbstractSpringAcceptanceTests.class
.getResource("/projects/spring-cloud-build").toURI());
this.springCloudConsulProject = new File(
AbstractSpringAcceptanceTests.class.getResource("/projects/spring-cloud-consul").toURI());
this.springCloudBuildProject = new File(
AbstractSpringAcceptanceTests.class.getResource("/projects/spring-cloud-build").toURI());
TestUtils.prepareLocalRepo();
FileSystemUtils.copyRecursively(file("/projects/"), this.temporaryFolder);
}
@@ -51,12 +51,9 @@ public class AbstractSpringCloudAcceptanceTests extends AbstractSpringAcceptance
public void thenAllDryRunStepsWereExecutedForEachProject(
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler) {
nonAssertingTestProjectGitHandler.clonedProjects.stream()
.filter(f -> !f.getName().contains("angel")
&& !f.getName().equals("spring-cloud"))
.forEach(project -> {
then(Arrays.asList("spring-cloud-starter-build",
"spring-cloud-consul"))
.contains(pom(project).getArtifactId());
.filter(f -> !f.getName().contains("angel") && !f.getName().equals("spring-cloud")).forEach(project -> {
then(Arrays.asList("spring-cloud-starter-build", "spring-cloud-consul"))
.contains(pom(project).getArtifactId());
then(new File("/tmp/executed_build")).exists();
then(new File("/tmp/executed_deploy")).doesNotExist();
then(new File("/tmp/executed_docs")).doesNotExist();

View File

@@ -24,8 +24,7 @@ import releaser.internal.spring.meta.AbstractSpringMetaReleaseAcceptanceTests;
import static org.assertj.core.api.BDDAssertions.then;
public class AbstractSpringCloudMetaAcceptanceTests
extends AbstractSpringMetaReleaseAcceptanceTests {
public class AbstractSpringCloudMetaAcceptanceTests extends AbstractSpringMetaReleaseAcceptanceTests {
public File springCloudConsulProject;
@@ -34,11 +33,9 @@ public class AbstractSpringCloudMetaAcceptanceTests
@Before
public void setupCloud() throws Exception {
this.springCloudConsulProject = new File(
AbstractSpringCloudMetaAcceptanceTests.class
.getResource("/projects/spring-cloud-consul").toURI());
AbstractSpringCloudMetaAcceptanceTests.class.getResource("/projects/spring-cloud-consul").toURI());
this.springCloudBuildProject = new File(
AbstractSpringCloudMetaAcceptanceTests.class
.getResource("/projects/spring-cloud-build").toURI());
AbstractSpringCloudMetaAcceptanceTests.class.getResource("/projects/spring-cloud-build").toURI());
}
public void consulPomParentVersionIsEqualTo(File project, String expected) {
@@ -48,12 +45,9 @@ public class AbstractSpringCloudMetaAcceptanceTests
public void thenAllDryRunStepsWereExecutedForEachProject(
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler) {
nonAssertingTestProjectGitHandler.clonedProjects.stream()
.filter(f -> !f.getName().contains("angel")
&& !f.getName().equals("spring-cloud"))
.forEach(project -> {
then(Arrays.asList("spring-cloud-starter-build",
"spring-cloud-consul"))
.contains(pom(project).getArtifactId());
.filter(f -> !f.getName().contains("angel") && !f.getName().equals("spring-cloud")).forEach(project -> {
then(Arrays.asList("spring-cloud-starter-build", "spring-cloud-consul"))
.contains(pom(project).getArtifactId());
then(new File("/tmp/executed_build")).exists();
then(new File("/tmp/executed_deploy")).doesNotExist();
then(new File("/tmp/executed_docs")).doesNotExist();

View File

@@ -54,18 +54,18 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.BDDMockito.given;
/**
* @author Marcin Grzejszczak
*/
public class SpringMetaReleaseAcceptanceTests
extends AbstractSpringCloudMetaAcceptanceTests {
public class SpringMetaReleaseAcceptanceTests extends AbstractSpringCloudMetaAcceptanceTests {
@Test
public void should_perform_a_meta_release_of_sc_release_and_consul()
throws Exception {
public void should_perform_a_meta_release_of_sc_release_and_consul() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -73,21 +73,18 @@ public class SpringMetaReleaseAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(defaultRunner(),
properties("debug=true").properties("test.metarelease=true")
.properties(metaReleaseArgs(project).bomBranch("vGreenwich.SR2")
.addFixedVersions(edgwareSr10()).build()),
properties("debugx=true").properties("test.metarelease=true").properties(
metaReleaseArgs(project).bomBranch("vGreenwich.SR2").addFixedVersions(edgwareSr10()).build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler = context
.getBean(NonAssertingTestProjectGitHandler.class);
SaganUpdater saganUpdater = context.getBean(SaganUpdater.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().metaRelease(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -97,46 +94,41 @@ public class SpringMetaReleaseAcceptanceTests
// consul, release
then(nonAssertingTestProjectGitHandler.clonedProjects).hasSize(2);
// don't want to verify the docs
thenAllStepsWereExecutedForEachProject(
nonAssertingTestProjectGitHandler);
thenAllStepsWereExecutedForEachProject(nonAssertingTestProjectGitHandler);
thenSaganWasCalled(saganUpdater);
then(clonedProject(nonAssertingTestProjectGitHandler,
"spring-cloud-consul").tagList().call()).extracting("name")
.contains("refs/tags/v5.3.5.RELEASE");
then(clonedProject(nonAssertingTestProjectGitHandler, "spring-cloud-consul").tagList().call())
.extracting("name").contains("refs/tags/v5.3.5.RELEASE");
thenRunUpdatedTestsWereCalled(postReleaseActions);
thenUpdateReleaseTrainDocsWasCalled(postReleaseActions);
});
}
@Test
public void should_perform_a_meta_release_of_sc_release_and_consul_in_parallel()
throws Exception {
public void should_perform_a_meta_release_of_sc_release_and_consul_in_parallel() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
File project = cloneToTemporaryDirectory(tmpFile("spring-cloud-consul"));
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(defaultRunner(), properties("debug=true").properties("test.metarelease=true")
.properties(metaReleaseArgsForParallel(project)
.bomBranch("vGreenwich.SR2").addFixedVersions(edgwareSr10())
.metaReleaseGroups("example1,example2",
"spring-cloud-build,spring-cloud-consul,spring-cloud-release")
.build()),
run(defaultRunner(),
properties("debugx=true").properties("test.metarelease=true")
.properties(metaReleaseArgsForParallel(project).bomBranch("vGreenwich.SR2")
.addFixedVersions(edgwareSr10())
.metaReleaseGroups("example1,example2",
"spring-cloud-build,spring-cloud-consul,spring-cloud-release")
.build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler = context
.getBean(NonAssertingTestProjectGitHandler.class);
SaganUpdater saganUpdater = context.getBean(SaganUpdater.class);
DocumentationUpdater testDocumentationUpdater = context
.getBean(DocumentationUpdater.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
DocumentationUpdater testDocumentationUpdater = context.getBean(DocumentationUpdater.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().metaRelease(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -150,17 +142,15 @@ public class SpringMetaReleaseAcceptanceTests
// thenAllStepsWereExecutedForEachProject(
// nonAssertingTestProjectGitHandler);
thenSaganWasCalled(saganUpdater);
then(clonedProject(nonAssertingTestProjectGitHandler,
"spring-cloud-consul").tagList().call()).extracting("name")
.contains("refs/tags/v5.3.5.RELEASE");
then(clonedProject(nonAssertingTestProjectGitHandler, "spring-cloud-consul").tagList().call())
.extracting("name").contains("refs/tags/v5.3.5.RELEASE");
thenRunUpdatedTestsWereCalled(postReleaseActions);
thenUpdateReleaseTrainDocsWasCalled(postReleaseActions);
});
}
@Test
public void should_perform_a_meta_release_dry_run_of_sc_release_and_consul()
throws Exception {
public void should_perform_a_meta_release_dry_run_of_sc_release_and_consul() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -168,23 +158,20 @@ public class SpringMetaReleaseAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(defaultRunner(),
properties("debug=true").properties("test.metarelease=true")
.properties(metaReleaseArgs(project).bomBranch("vGreenwich.SR2")
.addFixedVersions(edgwareSr10()).build()),
properties("debugx=true").properties("test.metarelease=true").properties(
metaReleaseArgs(project).bomBranch("vGreenwich.SR2").addFixedVersions(edgwareSr10()).build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler = context
.getBean(NonAssertingTestProjectGitHandler.class);
SaganUpdater saganUpdater = context.getBean(SaganUpdater.class);
DocumentationUpdater testDocumentationUpdater = context
.getBean(DocumentationUpdater.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
DocumentationUpdater testDocumentationUpdater = context.getBean(DocumentationUpdater.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser.release(new OptionsBuilder()
.metaRelease(true).dryRun(true).options());
ExecutionResult result = releaser
.release(new OptionsBuilder().metaRelease(true).dryRun(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -194,20 +181,17 @@ public class SpringMetaReleaseAcceptanceTests
// consul, release
then(nonAssertingTestProjectGitHandler.clonedProjects).hasSize(2);
// only dry run tasks were called
thenAllDryRunStepsWereExecutedForEachProject(
nonAssertingTestProjectGitHandler);
thenAllDryRunStepsWereExecutedForEachProject(nonAssertingTestProjectGitHandler);
thenSaganWasNotCalled(saganUpdater);
then(clonedProject(nonAssertingTestProjectGitHandler,
"spring-cloud-consul").tagList().call()).extracting("name")
.doesNotContain("refs/tags/v5.3.5.RELEASE");
then(clonedProject(nonAssertingTestProjectGitHandler, "spring-cloud-consul").tagList().call())
.extracting("name").doesNotContain("refs/tags/v5.3.5.RELEASE");
thenRunUpdatedTestsWereNotCalled(postReleaseActions);
thenUpdateReleaseTrainDocsWasNotCalled(postReleaseActions);
});
}
@Test
public void should_not_release_any_projects_when_they_are_on_list_of_projects_to_skip()
throws Exception {
public void should_not_release_any_projects_when_they_are_on_list_of_projects_to_skip() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -215,23 +199,17 @@ public class SpringMetaReleaseAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
File temporaryDestination = this.tmp.newFolder();
run(defaultRunner(),
properties("debug=true")
.properties("test.metarelease=true", "test.mockBuild=true")
.properties(metaReleaseArgs(project).bomBranch("Greenwich")
.addFixedVersions(consulAndReleaseSnapshots())
.updateReleaseTrainWiki(false)
.cloneDestinationDirectory(temporaryDestination)
.projectsToSkip("spring-cloud-consul").build()),
run(defaultRunner(), properties("debugx=true").properties("test.metarelease=true", "test.mockBuild=true")
.properties(metaReleaseArgs(project).bomBranch("Greenwich")
.addFixedVersions(consulAndReleaseSnapshots()).updateReleaseTrainWiki(false)
.cloneDestinationDirectory(temporaryDestination).projectsToSkip("spring-cloud-consul").build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
BuildProjectReleaseTask build = context
.getBean(BuildProjectReleaseTask.class);
BuildProjectReleaseTask build = context.getBean(BuildProjectReleaseTask.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().metaRelease(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -244,8 +222,7 @@ public class SpringMetaReleaseAcceptanceTests
}
@Test
public void should_perform_a_meta_release_of_consul_only_when_run_from_got_passed()
throws Exception {
public void should_perform_a_meta_release_of_consul_only_when_run_from_got_passed() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -254,24 +231,20 @@ public class SpringMetaReleaseAcceptanceTests
File temporaryDestination = this.tmp.newFolder();
run(defaultRunner(),
properties("debug=true")
.properties("test.metarelease=true", "test.mockBuild=true")
properties("debugx=true").properties("test.metarelease=true", "test.mockBuild=true")
.properties(metaReleaseArgs(project).bomBranch("Greenwich")
.addFixedVersions(releaseConsulBuildSnapshots())
.cloneDestinationDirectory(temporaryDestination).build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
BuildProjectReleaseTask build = context
.getBean(BuildProjectReleaseTask.class);
BuildProjectReleaseTask build = context.getBean(BuildProjectReleaseTask.class);
SaganUpdater saganUpdater = context.getBean(SaganUpdater.class);
DocumentationUpdater testDocumentationUpdater = context
.getBean(DocumentationUpdater.class);
DocumentationUpdater testDocumentationUpdater = context.getBean(DocumentationUpdater.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().startFrom("spring-cloud-consul")
.metaRelease(true).options());
.release(new OptionsBuilder().startFrom("spring-cloud-consul").metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -290,8 +263,7 @@ public class SpringMetaReleaseAcceptanceTests
}
@Test
public void should_perform_a_meta_release_of_consul_only_when_task_names_got_passed()
throws Exception {
public void should_perform_a_meta_release_of_consul_only_when_task_names_got_passed() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -300,24 +272,20 @@ public class SpringMetaReleaseAcceptanceTests
File temporaryDestination = this.tmp.newFolder();
run(defaultRunner(),
properties("debug=true")
.properties("test.metarelease=true", "test.mockBuild=true")
properties("debugx=true").properties("test.metarelease=true", "test.mockBuild=true")
.properties(metaReleaseArgs(project).bomBranch("Greenwich")
.addFixedVersions(releaseConsulBuildSnapshots())
.cloneDestinationDirectory(temporaryDestination).build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
BuildProjectReleaseTask build = context
.getBean(BuildProjectReleaseTask.class);
BuildProjectReleaseTask build = context.getBean(BuildProjectReleaseTask.class);
SaganUpdater saganUpdater = context.getBean(SaganUpdater.class);
DocumentationUpdater testDocumentationUpdater = context
.getBean(DocumentationUpdater.class);
DocumentationUpdater testDocumentationUpdater = context.getBean(DocumentationUpdater.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser.release(new OptionsBuilder()
.taskNames(Collections.singletonList("spring-cloud-consul"))
.metaRelease(true).options());
.taskNames(Collections.singletonList("spring-cloud-consul")).metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -336,19 +304,18 @@ public class SpringMetaReleaseAcceptanceTests
}
@Test
public void should_not_execute_any_subsequent_task_when_first_one_fails()
throws Exception {
public void should_not_execute_any_subsequent_task_when_first_one_fails() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "Greenwich");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
File project = cloneToTemporaryDirectory(tmpFile("spring-cloud-consul"));
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(failingBuildRunner(), properties("debug=true")
run(failingBuildRunner(), properties("debugx=true")
.properties("test.metarelease=true", "test.metarelease.failing=true",
"releaser.flow.default-enabled=false")
.properties(metaReleaseArgs(project).bomBranch("vGreenwich.SR2")
.addFixedVersions(edgwareSr10()).build()),
.properties(
metaReleaseArgs(project).bomBranch("vGreenwich.SR2").addFixedVersions(edgwareSr10()).build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler = context
@@ -357,11 +324,9 @@ public class SpringMetaReleaseAcceptanceTests
.getBean(TestExecutionResultHandler.class);
FirstTask firstTask = context.getBean(FirstTask.class);
SecondTask secondTask = context.getBean(SecondTask.class);
PostReleaseTask postReleaseTask = context
.getBean(PostReleaseTask.class);
PostReleaseTask postReleaseTask = context.getBean(PostReleaseTask.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().metaRelease(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().metaRelease(true).options());
// print results
testExecutionResultHandler.accept(result);
@@ -370,48 +335,40 @@ public class SpringMetaReleaseAcceptanceTests
then(result.isFailureOrUnstable()).isTrue();
// consul
then(nonAssertingTestProjectGitHandler.clonedProjects).hasSize(1);
BDDMockito.then(firstTask).should().runTask(BDDMockito.argThat(
arg -> arg.project.getName().equals("spring-cloud-consul")));
BDDMockito.then(firstTask).should()
.runTask(BDDMockito.argThat(arg -> arg.project.getName().equals("spring-cloud-consul")));
BDDMockito.then(firstTask).should(BDDMockito.never())
.runTask(BDDMockito.argThat(arg -> arg.project.getName()
.equals("spring-cloud-release")));
BDDMockito.then(secondTask).should(BDDMockito.never())
.runTask(BDDMockito.any(Arguments.class));
.runTask(BDDMockito.argThat(arg -> arg.project.getName().equals("spring-cloud-release")));
BDDMockito.then(secondTask).should(BDDMockito.never()).runTask(BDDMockito.any(Arguments.class));
BDDMockito.then(postReleaseTask).should(BDDMockito.never())
.runTask(BDDMockito.any(Arguments.class));
});
}
private SpringApplicationBuilder defaultRunner() {
return new SpringApplicationBuilder(MetaReleaseConfig.class,
MetaReleaseScanningConfiguration.class).web(WebApplicationType.NONE)
.properties("spring.jmx.enabled=false");
return new SpringApplicationBuilder(MetaReleaseConfig.class, MetaReleaseScanningConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.jmx.enabled=false");
}
private SpringApplicationBuilder failingBuildRunner() {
return new SpringApplicationBuilder(
SpringMetaReleaseAcceptanceTests.MetaReleaseConfig.class,
return new SpringApplicationBuilder(SpringMetaReleaseAcceptanceTests.MetaReleaseConfig.class,
SpringMetaReleaseAcceptanceTests.MetaReleaseFailingTasksScanningConfiguration.class)
.web(WebApplicationType.NONE)
.properties("spring.jmx.enabled=false");
.web(WebApplicationType.NONE).properties("spring.jmx.enabled=false");
}
private void thenWikiPageWasUpdated(DocumentationUpdater documentationUpdater) {
BDDMockito.then(documentationUpdater).should()
.updateReleaseTrainWiki(BDDMockito.any(Projects.class));
BDDMockito.then(documentationUpdater).should().updateReleaseTrainWiki(BDDMockito.any(Projects.class));
}
private void thenBuildWasCalledFor(BuildProjectReleaseTask build,
String projectName) {
BDDMockito.then(build).should().apply(argThat(
argument -> argument.originalVersion.projectName.equals(projectName)
private void thenBuildWasCalledFor(BuildProjectReleaseTask build, String projectName) {
BDDMockito.then(build).should()
.apply(argThat(argument -> argument.originalVersion.projectName.equals(projectName)
|| argument.project.getAbsolutePath().endsWith(projectName)));
}
private void thenBuildWasNeverCalledFor(BuildProjectReleaseTask build,
String projectName) {
BDDMockito.then(build).should(BDDMockito.never()).apply(argThat(
argument -> argument.originalVersion.projectName.equals(projectName)
private void thenBuildWasNeverCalledFor(BuildProjectReleaseTask build, String projectName) {
BDDMockito.then(build).should(BDDMockito.never())
.apply(argThat(argument -> argument.originalVersion.projectName.equals(projectName)
|| argument.project.getAbsolutePath().endsWith(projectName)));
}
@@ -438,8 +395,9 @@ public class SpringMetaReleaseAcceptanceTests
@Bean
SaganClient testSaganClient() {
SaganClient saganClient = BDDMockito.mock(SaganClient.class);
BDDMockito.given(saganClient.getProject(anyString()))
.willReturn(newProject());
given(saganClient.getProject(anyString())).willReturn(newProject());
given(saganClient.addRelease(anyString(), any())).willReturn(true);
given(saganClient.deleteRelease(anyString(), anyString())).willReturn(true);
return saganClient;
}
@@ -450,33 +408,27 @@ public class SpringMetaReleaseAcceptanceTests
}
@Bean
SaganUpdater testSaganUpdater(SaganClient saganClient,
ReleaserProperties properties) {
SaganUpdater testSaganUpdater(SaganClient saganClient, ReleaserProperties properties) {
return BDDMockito.spy(new SaganUpdater(saganClient, properties));
}
@Bean
PostReleaseActions myPostReleaseActions() {
return BDDMockito
.mock(PostReleaseActions.class,
invocation -> invocation.getMethod().getReturnType()
.equals(ExecutionResult.class)
? ExecutionResult.success() : null);
return BDDMockito.mock(PostReleaseActions.class,
invocation -> invocation.getMethod().getReturnType().equals(ExecutionResult.class)
? ExecutionResult.success() : null);
}
@Bean
NonAssertingTestProjectGitHubHandler testProjectGitHubHandler(
ReleaserProperties releaserProperties) {
NonAssertingTestProjectGitHubHandler testProjectGitHubHandler(ReleaserProperties releaserProperties) {
return new NonAssertingTestProjectGitHubHandler(releaserProperties);
}
@Bean
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler(
ReleaserProperties releaserProperties,
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler(ReleaserProperties releaserProperties,
@Value("${test.projectName}") String projectName) {
return new NonAssertingTestProjectGitHandler(releaserProperties,
file -> FileSystemUtils
.deleteRecursively(new File(file, projectName)));
file -> FileSystemUtils.deleteRecursively(new File(file, projectName)));
}
@Bean
@@ -487,8 +439,7 @@ public class SpringMetaReleaseAcceptanceTests
}
@Configuration
@ConditionalOnProperty(value = "test.metarelease", havingValue = "true",
matchIfMissing = true)
@ConditionalOnProperty(value = "test.metarelease", havingValue = "true", matchIfMissing = true)
@ComponentScan({ "releaser.internal", "releaser.cloud" })
static class MetaReleaseScanningConfiguration {
@@ -551,8 +502,7 @@ class FirstTask implements ReleaseReleaserTask {
}
@Override
public ExecutionResult runTask(Arguments args)
throws BuildUnstableException, RuntimeException {
public ExecutionResult runTask(Arguments args) throws BuildUnstableException, RuntimeException {
return ExecutionResult.failure(new IllegalStateException("Failure"));
}
@@ -586,8 +536,7 @@ class SecondTask implements ReleaseReleaserTask {
}
@Override
public ExecutionResult runTask(Arguments args)
throws BuildUnstableException, RuntimeException {
public ExecutionResult runTask(Arguments args) throws BuildUnstableException, RuntimeException {
return ExecutionResult.success();
}
@@ -621,8 +570,7 @@ class PostReleaseTask implements TrainPostReleaseReleaserTask {
}
@Override
public ExecutionResult runTask(Arguments args)
throws BuildUnstableException, RuntimeException {
public ExecutionResult runTask(Arguments args) throws BuildUnstableException, RuntimeException {
return ExecutionResult.success();
}

View File

@@ -49,34 +49,33 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.util.FileSystemUtils;
import static org.assertj.core.api.BDDAssertions.then;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.times;
/**
* @author Marcin Grzejszczak
*/
public class SpringSingleProjectAcceptanceTests
extends AbstractSpringCloudAcceptanceTests {
public class SpringSingleProjectAcceptanceTests extends AbstractSpringCloudAcceptanceTests {
SpringApplicationBuilder runner = new SpringApplicationBuilder(
SpringSingleProjectAcceptanceTests.SingleProjectReleaseConfig.class,
SpringSingleProjectAcceptanceTests.SingleProjectScanningConfiguration.class)
.web(WebApplicationType.NONE).properties("spring.jmx.enabled=false");
SpringSingleProjectAcceptanceTests.SingleProjectScanningConfiguration.class).web(WebApplicationType.NONE)
.properties("spring.jmx.enabled=false");
@Test
public void should_fail_to_perform_a_release_of_consul_when_sc_release_contains_snapshots()
throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release-with-snapshot/",
"vCamden.SR5.BROKEN");
public void should_fail_to_perform_a_release_of_consul_when_sc_release_contains_snapshots() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release-with-snapshot/", "vCamden.SR5.BROKEN");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
File project = cloneToTemporaryDirectory(tmpFile("spring-cloud-consul"));
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
properties("debugx=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release-with-snapshot/")
.bomBranch("vCamden.SR5.BROKEN").expectedVersion("1.1.2.RELEASE")
.build()),
.bomBranch("vCamden.SR5.BROKEN").expectedVersion("1.1.2.RELEASE").build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
BDDAssertions.thenThrownBy(releaser::release).hasMessageContaining(
@@ -94,28 +93,23 @@ public class SpringSingleProjectAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vGreenwich.SR2").expectedVersion("2.1.2.RELEASE")
.build()),
properties("debugx=true").properties(
new ArgsBuilder(project, this.tmp).releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vGreenwich.SR2").expectedVersion("2.1.2.RELEASE").build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
TestProjectGitHubHandler gitHubHandler = context
.getBean(TestProjectGitHubHandler.class);
TestProjectGitHubHandler gitHubHandler = context.getBean(TestProjectGitHubHandler.class);
SaganClient saganClient = context.getBean(SaganClient.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().interactive(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().interactive(true).options());
Iterable<RevCommit> commits = listOfCommits(project);
Iterator<RevCommit> iterator = commits.iterator();
tagIsPresentInOrigin(origin, "v2.1.2.RELEASE");
commitIsPresent(iterator,
"Bumping versions to 2.1.3.SNAPSHOT after release");
commitIsPresent(iterator, "Bumping versions to 2.1.3.SNAPSHOT after release");
commitIsPresent(iterator, "Going back to snapshots");
commitIsPresent(iterator, "Update SNAPSHOT to 2.1.2.RELEASE");
pomVersionIsEqualTo(project, "2.1.3.SNAPSHOT");
@@ -127,11 +121,10 @@ public class SpringSingleProjectAcceptanceTests
then(releaseNotesTemplate()).doesNotExist();
// once for updating GA
// second time to update SNAPSHOT
BDDMockito.then(saganClient).should(BDDMockito.times(2))
.updateRelease(BDDMockito.eq("spring-cloud-consul"),
BDDMockito.anyList());
BDDMockito.then(saganClient).should()
.deleteRelease("spring-cloud-consul", "2.1.2.BUILD-SNAPSHOT");
BDDMockito.then(saganClient).should(times(2)).addRelease(BDDMockito.eq("spring-cloud-consul"),
BDDMockito.any());
BDDMockito.then(saganClient).should(times(2)).getProject("spring-cloud-consul");
BDDMockito.then(saganClient).should().deleteRelease("spring-cloud-consul", "2.1.2.BUILD-SNAPSHOT");
then(gitHubHandler.issueCreatedInSpringGuides).isFalse();
then(gitHubHandler.issueCreatedInStartSpringIo).isFalse();
thenRunUpdatedTestsWereNotCalled(postReleaseActions);
@@ -152,34 +145,28 @@ public class SpringSingleProjectAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vGreenwich.SR2").projectName("spring-cloud-build")
.expectedVersion("2.1.6.RELEASE").build()),
properties("debugx=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/").bomBranch("vGreenwich.SR2")
.projectName("spring-cloud-build").expectedVersion("2.1.6.RELEASE").build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
TestProjectGitHubHandler gitHubHandler = context
.getBean(TestProjectGitHubHandler.class);
TestProjectGitHubHandler gitHubHandler = context.getBean(TestProjectGitHubHandler.class);
SaganClient saganClient = context.getBean(SaganClient.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().interactive(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().interactive(true).options());
Iterable<RevCommit> commits = listOfCommits(project);
Iterator<RevCommit> iterator = commits.iterator();
tagIsPresentInOrigin(origin, "v2.1.6.RELEASE");
// we're running against camden sc-release
commitIsPresent(iterator,
"Bumping versions to 2.1.7.SNAPSHOT after release");
commitIsPresent(iterator, "Bumping versions to 2.1.7.SNAPSHOT after release");
commitIsPresent(iterator, "Going back to snapshots");
commitIsPresent(iterator, "Update SNAPSHOT to 2.1.6.RELEASE");
pomVersionIsEqualTo(project, "2.1.7.SNAPSHOT");
pomParentVersionIsEqualTo(project, "spring-cloud-build-dependencies",
"2.1.6.RELEASE");
pomParentVersionIsEqualTo(project, "spring-cloud-build-dependencies", "2.1.6.RELEASE");
then(gitHubHandler.closedMilestones).isTrue();
then(emailTemplate()).doesNotExist();
then(blogTemplate()).doesNotExist();
@@ -187,11 +174,9 @@ public class SpringSingleProjectAcceptanceTests
then(releaseNotesTemplate()).doesNotExist();
// once for updating GA
// second time to update SNAPSHOT
BDDMockito.then(saganClient).should(BDDMockito.times(2))
.updateRelease(BDDMockito.eq("spring-cloud-build"),
BDDMockito.anyList());
BDDMockito.then(saganClient).should()
.deleteRelease("spring-cloud-build", "2.1.6.BUILD-SNAPSHOT");
BDDMockito.then(saganClient).should(times(2)).addRelease(BDDMockito.eq("spring-cloud-build"),
BDDMockito.any());
BDDMockito.then(saganClient).should().deleteRelease("spring-cloud-build", "2.1.6.BUILD-SNAPSHOT");
then(gitHubHandler.issueCreatedInSpringGuides).isFalse();
then(gitHubHandler.issueCreatedInStartSpringIo).isFalse();
thenRunUpdatedTestsWereNotCalled(postReleaseActions);
@@ -211,26 +196,22 @@ public class SpringSingleProjectAcceptanceTests
GitTestUtils.setOriginOnProjectToTmp(origin, project);
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vDalston.RC1").expectedVersion("1.2.0.RC1").build()),
properties("debugx=true").properties(
new ArgsBuilder(project, this.tmp).releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vDalston.RC1").expectedVersion("1.2.0.RC1").build()),
context -> {
SpringReleaser releaser = context.getBean(SpringReleaser.class);
TestProjectGitHubHandler gitHubHandler = context
.getBean(TestProjectGitHubHandler.class);
TestProjectGitHubHandler gitHubHandler = context.getBean(TestProjectGitHubHandler.class);
SaganClient saganClient = context.getBean(SaganClient.class);
PostReleaseActions postReleaseActions = context
.getBean(PostReleaseActions.class);
PostReleaseActions postReleaseActions = context.getBean(PostReleaseActions.class);
TestExecutionResultHandler testExecutionResultHandler = context
.getBean(TestExecutionResultHandler.class);
ExecutionResult result = releaser
.release(new OptionsBuilder().interactive(true).options());
ExecutionResult result = releaser.release(new OptionsBuilder().interactive(true).options());
Iterable<RevCommit> commits = listOfCommits(project);
tagIsPresentInOrigin(origin, "v1.2.0.RC1");
commitIsNotPresent(commits,
"Bumping versions to 1.2.1.SNAPSHOT after release");
commitIsNotPresent(commits, "Bumping versions to 1.2.1.SNAPSHOT after release");
Iterator<RevCommit> iterator = listOfCommits(project).iterator();
commitIsPresent(iterator, "Going back to snapshots");
commitIsPresent(iterator, "Update SNAPSHOT to 1.2.0.RC1");
@@ -241,12 +222,11 @@ public class SpringSingleProjectAcceptanceTests
then(blogTemplate()).doesNotExist();
then(tweetTemplate()).doesNotExist();
then(releaseNotesTemplate()).doesNotExist();
BDDMockito.then(saganClient).should().updateRelease(
BDDMockito.eq("spring-cloud-consul"), BDDMockito.anyList());
BDDMockito.then(saganClient).should()
.deleteRelease("spring-cloud-consul", "1.2.0.M8");
BDDMockito.then(saganClient).should()
.deleteRelease("spring-cloud-consul", "1.2.0.RC1");
BDDMockito.then(saganClient).should().addRelease(BDDMockito.eq("spring-cloud-consul"),
BDDMockito.any());
BDDMockito.then(saganClient).should(times(2)).getProject("spring-cloud-consul");
BDDMockito.then(saganClient).should().deleteRelease("spring-cloud-consul", "1.2.0.M8");
BDDMockito.then(saganClient).should().deleteRelease("spring-cloud-consul", "1.2.0.SNAPSHOT");
// we update guides only for SR / RELEASE
then(gitHubHandler.issueCreatedInSpringGuides).isFalse();
then(gitHubHandler.issueCreatedInStartSpringIo).isFalse();
@@ -259,8 +239,7 @@ public class SpringSingleProjectAcceptanceTests
}
@Test
public void should_not_clone_when_option_not_to_clone_was_switched_on()
throws Exception {
public void should_not_clone_when_option_not_to_clone_was_switched_on() throws Exception {
checkoutReleaseTrainBranch("/projects/spring-cloud-release/", "master");
File origin = cloneToTemporaryDirectory(this.springCloudConsulProject);
assertThatClonedConsulProjectIsInSnapshots(origin);
@@ -269,12 +248,11 @@ public class SpringSingleProjectAcceptanceTests
final File temporaryDestination = this.tmp.newFolder();
run(this.runner,
properties("debug=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/")
.bomBranch("vCamden.SR5").expectedVersion("1.1.2.RELEASE")
properties("debugx=true").properties(new ArgsBuilder(project, this.tmp)
.releaseTrainUrl("/projects/spring-cloud-release/").bomBranch("vCamden.SR5")
.expectedVersion("1.1.2.RELEASE")
// just build
.chosenOption("6").fetchVersionsFromGit(false)
.cloneDestinationDirectory(temporaryDestination)
.chosenOption("6").fetchVersionsFromGit(false).cloneDestinationDirectory(temporaryDestination)
.addFixedVersion("spring-cloud-release", "Finchley.RELEASE")
.addFixedVersion("spring-cloud-consul", "2.3.4.RELEASE").build()),
context -> {
@@ -288,8 +266,7 @@ public class SpringSingleProjectAcceptanceTests
private void assertThatClonedBuildProjectIsInSnapshots(File origin) {
pomVersionIsEqualTo(origin, "1.3.7.BUILD-SNAPSHOT");
pomParentVersionIsEqualTo(origin, "spring-cloud-build-dependencies",
"1.5.9.RELEASE");
pomParentVersionIsEqualTo(origin, "spring-cloud-build-dependencies", "1.5.9.RELEASE");
}
// @formatter:on
@@ -305,8 +282,7 @@ public class SpringSingleProjectAcceptanceTests
boolean issueCreatedInStartSpringIo = false;
TestProjectGitHubHandler(ReleaserProperties properties, String expectedVersion,
String projectName) {
TestProjectGitHubHandler(ReleaserProperties properties, String expectedVersion, String projectName) {
super(properties, Collections.emptyList());
this.expectedVersion = expectedVersion;
this.projectName = projectName;
@@ -325,8 +301,7 @@ public class SpringSingleProjectAcceptanceTests
}
@Override
public void createIssueInStartSpringIo(Projects projects,
ProjectVersion version) {
public void createIssueInStartSpringIo(Projects projects, ProjectVersion version) {
this.issueCreatedInStartSpringIo = true;
}
@@ -339,15 +314,15 @@ public class SpringSingleProjectAcceptanceTests
@Configuration
@EnableAutoConfiguration
@ConditionalOnProperty(value = "test.metarelease", havingValue = "false",
matchIfMissing = true)
@ConditionalOnProperty(value = "test.metarelease", havingValue = "false", matchIfMissing = true)
static class SingleProjectReleaseConfig extends DefaultTestConfiguration {
@Bean
SaganClient testSaganClient() {
SaganClient saganClient = BDDMockito.mock(SaganClient.class);
BDDMockito.given(saganClient.getProject(anyString()))
.willReturn(newProject());
given(saganClient.getProject(anyString())).willReturn(newProject());
given(saganClient.addRelease(anyString(), any())).willReturn(true);
given(saganClient.deleteRelease(anyString(), anyString())).willReturn(true);
return saganClient;
}
@@ -357,21 +332,17 @@ public class SpringSingleProjectAcceptanceTests
}
@Bean
TestProjectGitHubHandler testProjectGitHubHandler(
ReleaserProperties releaserProperties,
TestProjectGitHubHandler testProjectGitHubHandler(ReleaserProperties releaserProperties,
@Value("${test.expectedVersion}") String expectedVersion,
@Value("${test.projectName}") String projectName) {
return new TestProjectGitHubHandler(releaserProperties, expectedVersion,
projectName);
return new TestProjectGitHubHandler(releaserProperties, expectedVersion, projectName);
}
@Bean
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler(
ReleaserProperties releaserProperties,
NonAssertingTestProjectGitHandler nonAssertingTestProjectGitHandler(ReleaserProperties releaserProperties,
@Value("${test.projectName}") String projectName) {
return new NonAssertingTestProjectGitHandler(releaserProperties,
file -> FileSystemUtils
.deleteRecursively(new File(file, projectName)));
file -> FileSystemUtils.deleteRecursively(new File(file, projectName)));
}
@Bean
@@ -382,8 +353,7 @@ public class SpringSingleProjectAcceptanceTests
}
@Configuration
@ConditionalOnProperty(value = "test.metarelease", havingValue = "false",
matchIfMissing = true)
@ConditionalOnProperty(value = "test.metarelease", havingValue = "false", matchIfMissing = true)
@ComponentScan({ "releaser.internal", "releaser.cloud" })
static class SingleProjectScanningConfiguration {

View File

@@ -115,9 +115,13 @@
<version>${awaitility.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>sagan</groupId>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.spring.sagan</groupId>
<artifactId>sagan-site</artifactId>
<classifier>stubs</classifier>
<version>${sagan-site.version}</version>

View File

@@ -69,12 +69,9 @@ public class Releaser {
private ReleaserProperties releaserProperties;
public Releaser(ReleaserProperties releaserProperties,
ProjectPomUpdater projectPomUpdater,
ProjectCommandExecutor projectCommandExecutor,
ProjectGitHandler projectGitHandler,
ProjectGitHubHandler projectGitHubHandler,
TemplateGenerator templateGenerator, GradleUpdater gradleUpdater,
public Releaser(ReleaserProperties releaserProperties, ProjectPomUpdater projectPomUpdater,
ProjectCommandExecutor projectCommandExecutor, ProjectGitHandler projectGitHandler,
ProjectGitHubHandler projectGitHubHandler, TemplateGenerator templateGenerator, GradleUpdater gradleUpdater,
SaganUpdater saganUpdater, DocumentationUpdater documentationUpdater,
PostReleaseActions postReleaseActions) {
this.releaserProperties = releaserProperties;
@@ -101,56 +98,51 @@ public class Releaser {
return this.projectPomUpdater.fixedVersions();
}
public ExecutionResult updateProjectFromBom(File project, Projects versions,
ProjectVersion versionFromBom) {
public ExecutionResult updateProjectFromBom(File project, Projects versions, ProjectVersion versionFromBom) {
return updateProjectFromBom(project, versions, versionFromBom, ASSERT_SNAPSHOTS);
}
private ExecutionResult updateProjectFromBom(File project, Projects versions,
ProjectVersion versionFromBom, boolean assertSnapshots) {
private ExecutionResult updateProjectFromBom(File project, Projects versions, ProjectVersion versionFromBom,
boolean assertSnapshots) {
log.info("Will update the project with versions [{}]", versions);
ReleaserProperties updatedProperties = new ReleaserPropertiesUpdater()
.updateProperties(this.releaserProperties, project);
this.projectPomUpdater.updateProjectFromReleaseTrain(project, versions,
versionFromBom, assertSnapshots);
this.gradleUpdater.updateProjectFromReleaseTrain(updatedProperties, project,
versions, versionFromBom, assertSnapshots);
ReleaserProperties updatedProperties = new ReleaserPropertiesUpdater().updateProperties(this.releaserProperties,
project);
this.projectPomUpdater.updateProjectFromReleaseTrain(project, versions, versionFromBom, assertSnapshots);
this.gradleUpdater.updateProjectFromReleaseTrain(updatedProperties, project, versions, versionFromBom,
assertSnapshots);
ProjectVersion changedVersion = new ProjectVersion(project);
log.info("\n\nProject was successfully updated to [{}]", changedVersion.version);
return ExecutionResult.success();
}
public ExecutionResult buildProject(ReleaserProperties properties,
ProjectVersion originalVersion, ProjectVersion versionFromBom) {
public ExecutionResult buildProject(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion versionFromBom) {
this.projectCommandExecutor.build(properties, originalVersion, versionFromBom);
log.info("\nProject was successfully built");
return ExecutionResult.success();
}
public ExecutionResult commitAndPushTags(File project,
ProjectVersion changedVersion) {
public ExecutionResult commitAndPushTags(File project, ProjectVersion changedVersion) {
this.projectGitHandler.commitAndTagIfApplicable(project, changedVersion);
log.info("\nCommit was made and tag was pushed successfully");
return ExecutionResult.success();
}
public ExecutionResult deploy(ReleaserProperties properties,
ProjectVersion originalVersion, ProjectVersion versionFromBom) {
public ExecutionResult deploy(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion versionFromBom) {
this.projectCommandExecutor.deploy(properties, originalVersion, versionFromBom);
log.info("\nThe artifact was deployed successfully");
return ExecutionResult.success();
}
public ExecutionResult publishDocs(ReleaserProperties properties,
ProjectVersion originalVersion, ProjectVersion changedVersion) {
this.projectCommandExecutor.publishDocs(properties, originalVersion,
changedVersion);
public ExecutionResult publishDocs(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion changedVersion) {
this.projectCommandExecutor.publishDocs(properties, originalVersion, changedVersion);
log.info("\nThe docs were published successfully");
return ExecutionResult.success();
}
public ExecutionResult rollbackReleaseVersion(File project, Projects projects,
ProjectVersion scReleaseVersion) {
public ExecutionResult rollbackReleaseVersion(File project, Projects projects, ProjectVersion scReleaseVersion) {
if (scReleaseVersion.isSnapshot()) {
log.info("\nWon't rollback a snapshot version");
return ExecutionResult.skipped();
@@ -158,34 +150,29 @@ public class Releaser {
this.projectGitHandler.revertChangesIfApplicable(project, scReleaseVersion);
ProjectVersion originalVersion = originalVersion(project);
log.info("Original project version is [{}]", originalVersion);
if ((scReleaseVersion.isRelease() || scReleaseVersion.isServiceRelease())
&& originalVersion.isSnapshot()) {
if ((scReleaseVersion.isRelease() || scReleaseVersion.isServiceRelease()) && originalVersion.isSnapshot()) {
updateBumpedVersions(project, projects, originalVersion);
}
else {
log.info(
"\nSuccessfully reverted the commit and came back to snapshot versions");
log.info("\nSuccessfully reverted the commit and came back to snapshot versions");
}
return ExecutionResult.success();
}
private ExecutionResult updateBumpedVersions(File project, Projects projects,
ProjectVersion originalVersion) {
private ExecutionResult updateBumpedVersions(File project, Projects projects, ProjectVersion originalVersion) {
Projects newProjects = Projects.forRollback(releaserProperties, projects);
ProjectVersion bumpedProject = bumpProject(originalVersion, newProjects);
log.info("Will bump versions \n{}", newProjects);
updateProjectFromBom(project, newProjects, originalVersion,
SKIP_SNAPSHOT_ASSERTION);
updateProjectFromBom(project, newProjects, originalVersion, SKIP_SNAPSHOT_ASSERTION);
this.projectGitHandler.commitAfterBumpingVersions(project, bumpedProject);
log.info("\nSuccessfully reverted the commit and bumped snapshot versions");
return ExecutionResult.success();
}
private ProjectVersion bumpProject(ProjectVersion originalVersion,
Projects newProjects) {
private ProjectVersion bumpProject(ProjectVersion originalVersion, Projects newProjects) {
return newProjects.containsProject(originalVersion.projectName)
? newProjects.forName(originalVersion.projectName) : new ProjectVersion(
originalVersion.projectName, originalVersion.bumpedVersion());
? newProjects.forName(originalVersion.projectName)
: new ProjectVersion(originalVersion.projectName, originalVersion.bumpedVersion());
}
ProjectVersion originalVersion(File project) {
@@ -214,10 +201,8 @@ public class Releaser {
}
public ExecutionResult createEmail(ProjectVersion releaseVersion, Projects projects) {
Assert.notNull(releaseVersion,
"You must provide a release version for your project");
Assert.notNull(releaseVersion.version,
"You must provide a release version for your project");
Assert.notNull(releaseVersion, "You must provide a release version for your project");
Assert.notNull(releaseVersion.version, "You must provide a release version for your project");
if (releaseVersion.isSnapshot()) {
log.info("\nWon't create email template for a SNAPSHOT version");
return ExecutionResult.skipped();
@@ -229,13 +214,11 @@ public class Releaser {
return ExecutionResult.success();
}
else {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create an email template"));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create an email template"));
}
}
catch (Exception ex) {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create an email template", ex));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create an email template", ex));
}
}
@@ -251,53 +234,44 @@ public class Releaser {
return ExecutionResult.success();
}
else {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create a blog template"));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create a blog template"));
}
}
catch (Exception ex) {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create a blog template", ex));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create a blog template", ex));
}
}
public ExecutionResult updateSpringGuides(ProjectVersion releaseVersion,
Projects projects, List<ProcessedProject> processedProjects) {
public ExecutionResult updateSpringGuides(ProjectVersion releaseVersion, Projects projects,
List<ProcessedProject> processedProjects) {
if (!(releaseVersion.isRelease() || releaseVersion.isServiceRelease())) {
log.info(
"\nWon't update Spring Guides for a non Release / Service Release version");
log.info("\nWon't update Spring Guides for a non Release / Service Release version");
return ExecutionResult.skipped();
}
Exception springGuidesException = createIssueInSpringGuides(releaseVersion,
projects);
Exception springGuidesException = createIssueInSpringGuides(releaseVersion, projects);
Exception deployGuidesException = deployGuides(processedProjects);
if (springGuidesException != null || deployGuidesException != null) {
return ExecutionResult.unstable(new BuildUnstableException(
"Failed to update Spring Guides. Spring Guides updated successfully ["
+ (springGuidesException != null)
+ "] deployed guides successfully ["
return ExecutionResult.unstable(
new BuildUnstableException("Failed to update Spring Guides. Spring Guides updated successfully ["
+ (springGuidesException != null) + "] deployed guides successfully ["
+ (deployGuidesException != null) + "]"));
}
return ExecutionResult.success();
}
public ExecutionResult updateStartSpringIo(ProjectVersion releaseVersion,
Projects projects) {
public ExecutionResult updateStartSpringIo(ProjectVersion releaseVersion, Projects projects) {
if (!(releaseVersion.isRelease() || releaseVersion.isServiceRelease())) {
log.info(
"\nWon't update start.spring.io for a non Release / Service Release version");
log.info("\nWon't update start.spring.io for a non Release / Service Release version");
return ExecutionResult.skipped();
}
Exception exception = createIssueInStartSpringIo(releaseVersion, projects);
if (exception != null) {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to update start.spring.io"));
return ExecutionResult.unstable(new BuildUnstableException("Failed to update start.spring.io"));
}
return ExecutionResult.success();
}
private Exception createIssueInSpringGuides(ProjectVersion releaseVersion,
Projects projects) {
private Exception createIssueInSpringGuides(ProjectVersion releaseVersion, Projects projects) {
try {
this.projectGitHubHandler.createIssueInSpringGuides(projects, releaseVersion);
log.info("\nSuccessfully created an issue in Spring Guides");
@@ -309,18 +283,15 @@ public class Releaser {
}
}
private Exception createIssueInStartSpringIo(ProjectVersion releaseVersion,
Projects projects) {
private Exception createIssueInStartSpringIo(ProjectVersion releaseVersion, Projects projects) {
try {
this.projectGitHubHandler.createIssueInStartSpringIo(projects,
releaseVersion);
this.projectGitHubHandler.createIssueInStartSpringIo(projects, releaseVersion);
log.info("\nSuccessfully created an issue in start.spring.io");
return null;
}
catch (Exception ex) {
log.error("Failed to update start.spring.io repo", ex);
return new BuildUnstableException("Failed to update start.spring.io repo",
ex);
return new BuildUnstableException("Failed to update start.spring.io repo", ex);
}
}
@@ -348,18 +319,15 @@ public class Releaser {
return ExecutionResult.success();
}
else {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create a tweet template"));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create a tweet template"));
}
}
catch (Exception ex) {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create a tweet template", ex));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create a tweet template", ex));
}
}
public ExecutionResult createReleaseNotes(ProjectVersion releaseVersion,
Projects projects) {
public ExecutionResult createReleaseNotes(ProjectVersion releaseVersion, Projects projects) {
if (releaseVersion.isSnapshot()) {
log.info("\nWon't create release notes for a SNAPSHOT version");
return ExecutionResult.skipped();
@@ -370,18 +338,15 @@ public class Releaser {
return ExecutionResult.success();
}
catch (Exception ex) {
return ExecutionResult.unstable(
new BuildUnstableException("Failed to create release notes", ex));
return ExecutionResult.unstable(new BuildUnstableException("Failed to create release notes", ex));
}
}
public ExecutionResult updateSagan(File project, ProjectVersion releaseVersion,
Projects projects) {
public ExecutionResult updateSagan(File project, ProjectVersion releaseVersion, Projects projects) {
String currentBranch = this.projectGitHandler.currentBranch(project);
ProjectVersion originalVersion = new ProjectVersion(project);
try {
return this.saganUpdater.updateSagan(project, currentBranch, originalVersion,
releaseVersion, projects);
return this.saganUpdater.updateSagan(project, currentBranch, originalVersion, releaseVersion, projects);
}
catch (Exception ex) {
return ExecutionResult.unstable(new BuildUnstableException(ex));

View File

@@ -87,8 +87,7 @@ public class ReleaserProperties implements Serializable {
private MetaRelease metaRelease = new MetaRelease();
public String getWorkingDir() {
return StringUtils.hasText(this.workingDir) ? this.workingDir
: System.getProperty("user.dir");
return StringUtils.hasText(this.workingDir) ? this.workingDir : System.getProperty("user.dir");
}
public void setWorkingDir(String workingDir) {
@@ -201,10 +200,9 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "ReleaserProperties{" + "workingDir='" + this.workingDir + '\'' + ", git="
+ this.git + ", pom=" + this.pom + ", maven=" + this.maven + ", gradle="
+ this.gradle + ", sagan=" + this.sagan + ", fixedVersions="
+ this.fixedVersions + ", metaRelease=" + this.metaRelease + ", template="
return "ReleaserProperties{" + "workingDir='" + this.workingDir + '\'' + ", git=" + this.git + ", pom="
+ this.pom + ", maven=" + this.maven + ", gradle=" + this.gradle + ", sagan=" + this.sagan
+ ", fixedVersions=" + this.fixedVersions + ", metaRelease=" + this.metaRelease + ", template="
+ this.template + ", versions=" + this.versions + '}';
}
@@ -362,8 +360,7 @@ public class ReleaserProperties implements Serializable {
return this.releaseTrainDependencyNames;
}
public void setReleaseTrainDependencyNames(
List<String> releaseTrainDependencyNames) {
public void setReleaseTrainDependencyNames(List<String> releaseTrainDependencyNames) {
this.releaseTrainDependencyNames = releaseTrainDependencyNames;
}
@@ -401,12 +398,10 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "MetaRelease{" + "enabled=" + enabled + ", releaseTrainProjectName='"
+ releaseTrainProjectName + '\'' + ", releaseTrainDependencyNames="
+ releaseTrainDependencyNames + ", gitOrgUrl='" + gitOrgUrl + '\''
+ ", projectsToSkip=" + projectsToSkip + ", releaseGroups="
+ releaseGroups + ", releaseGroupTimeoutInMinutes="
+ releaseGroupTimeoutInMinutes + ", releaseGroupThreadCount="
return "MetaRelease{" + "enabled=" + enabled + ", releaseTrainProjectName='" + releaseTrainProjectName
+ '\'' + ", releaseTrainDependencyNames=" + releaseTrainDependencyNames + ", gitOrgUrl='"
+ gitOrgUrl + '\'' + ", projectsToSkip=" + projectsToSkip + ", releaseGroups=" + releaseGroups
+ ", releaseGroupTimeoutInMinutes=" + releaseGroupTimeoutInMinutes + ", releaseGroupThreadCount="
+ releaseGroupThreadCount + '}';
}
@@ -823,21 +818,16 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "Git{" + "releaseTrainBomUrl='" + this.releaseTrainBomUrl + '\''
+ ", documentationUrl='" + this.documentationUrl + '\''
+ ", documentationBranch='" + this.documentationBranch + '\''
+ ", releaseTrainBranch='" + this.releaseTrainBranch + '\''
+ ", releaseTrainWikiUrl='" + this.releaseTrainWikiUrl + '\''
+ ", updateDocumentationRepo=" + this.updateDocumentationRepo
+ ", springProjectUrl=" + this.springProjectUrl
+ ", springProjectBranch=" + this.springProjectBranch
+ ", releaseTrainWikiPagePrefix=" + this.releaseTrainWikiPagePrefix
+ ", cloneDestinationDir='" + this.cloneDestinationDir + '\''
+ ", fetchVersionsFromGit=" + this.fetchVersionsFromGit
+ ", numberOfCheckedMilestones=" + this.numberOfCheckedMilestones
+ ", updateSpringGuides=" + this.updateSpringGuides
+ ", updateSpringProject=" + this.updateSpringProject
+ ", sampleUrlsSize=" + this.allTestSampleUrls.size() + '}';
return "Git{" + "releaseTrainBomUrl='" + this.releaseTrainBomUrl + '\'' + ", documentationUrl='"
+ this.documentationUrl + '\'' + ", documentationBranch='" + this.documentationBranch + '\''
+ ", releaseTrainBranch='" + this.releaseTrainBranch + '\'' + ", releaseTrainWikiUrl='"
+ this.releaseTrainWikiUrl + '\'' + ", updateDocumentationRepo=" + this.updateDocumentationRepo
+ ", springProjectUrl=" + this.springProjectUrl + ", springProjectBranch="
+ this.springProjectBranch + ", releaseTrainWikiPagePrefix=" + this.releaseTrainWikiPagePrefix
+ ", cloneDestinationDir='" + this.cloneDestinationDir + '\'' + ", fetchVersionsFromGit="
+ this.fetchVersionsFromGit + ", numberOfCheckedMilestones=" + this.numberOfCheckedMilestones
+ ", updateSpringGuides=" + this.updateSpringGuides + ", updateSpringProject="
+ this.updateSpringProject + ", sampleUrlsSize=" + this.allTestSampleUrls.size() + '}';
}
}
@@ -918,11 +908,10 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "Pom{" + "branch='" + this.branch + '\''
+ ", pomWithBootStarterParent='" + this.pomWithBootStarterParent
+ '\'' + ", thisTrainBom='" + this.thisTrainBom + '\''
+ ", bomVersionPattern='" + this.bomVersionPattern + '\''
+ ", ignoredPomRegex=" + this.ignoredPomRegex + '}';
return "Pom{" + "branch='" + this.branch + '\'' + ", pomWithBootStarterParent='"
+ this.pomWithBootStarterParent + '\'' + ", thisTrainBom='" + this.thisTrainBom + '\''
+ ", bomVersionPattern='" + this.bomVersionPattern + '\'' + ", ignoredPomRegex="
+ this.ignoredPomRegex + '}';
}
}
@@ -1039,8 +1028,7 @@ public class ReleaserProperties implements Serializable {
}
@Override
public void setGenerateReleaseTrainDocsCommand(
String generateReleaseTrainDocsCommand) {
public void setGenerateReleaseTrainDocsCommand(String generateReleaseTrainDocsCommand) {
this.generateReleaseTrainDocsCommand = generateReleaseTrainDocsCommand;
}
@@ -1056,12 +1044,10 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "Maven{" + "buildCommand='" + this.buildCommand + '\''
+ ", deployCommand='" + this.deployCommand + '\''
+ ", publishDocsCommand=" + this.publishDocsCommand
+ "generateReleaseTrainDocsCommand='"
+ this.generateReleaseTrainDocsCommand + '\'' + ", waitTimeInMinutes="
+ this.waitTimeInMinutes + '}';
return "Maven{" + "buildCommand='" + this.buildCommand + '\'' + ", deployCommand='" + this.deployCommand
+ '\'' + ", publishDocsCommand=" + this.publishDocsCommand + "generateReleaseTrainDocsCommand='"
+ this.generateReleaseTrainDocsCommand + '\'' + ", waitTimeInMinutes=" + this.waitTimeInMinutes
+ '}';
}
}
@@ -1173,8 +1159,7 @@ public class ReleaserProperties implements Serializable {
}
@Override
public void setGenerateReleaseTrainDocsCommand(
String generateReleaseTrainDocsCommand) {
public void setGenerateReleaseTrainDocsCommand(String generateReleaseTrainDocsCommand) {
this.generateReleaseTrainDocsCommand = generateReleaseTrainDocsCommand;
}
@@ -1190,12 +1175,10 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "Bash{" + "buildCommand='" + this.buildCommand + '\''
+ ", deployCommand='" + this.deployCommand + '\''
+ ", publishDocsCommand=" + this.publishDocsCommand
+ "generateReleaseTrainDocsCommand='"
+ this.generateReleaseTrainDocsCommand + '\'' + ", waitTimeInMinutes="
+ this.waitTimeInMinutes + '}';
return "Bash{" + "buildCommand='" + this.buildCommand + '\'' + ", deployCommand='" + this.deployCommand
+ '\'' + ", publishDocsCommand=" + this.publishDocsCommand + "generateReleaseTrainDocsCommand='"
+ this.generateReleaseTrainDocsCommand + '\'' + ", waitTimeInMinutes=" + this.waitTimeInMinutes
+ '}';
}
}
@@ -1328,8 +1311,7 @@ public class ReleaserProperties implements Serializable {
}
@Override
public void setGenerateReleaseTrainDocsCommand(
String generateReleaseTrainDocsCommand) {
public void setGenerateReleaseTrainDocsCommand(String generateReleaseTrainDocsCommand) {
this.generateReleaseTrainDocsCommand = generateReleaseTrainDocsCommand;
}
@@ -1347,8 +1329,7 @@ public class ReleaserProperties implements Serializable {
return this.gradlePropsSubstitution;
}
public void setGradlePropsSubstitution(
Map<String, String> gradlePropsSubstitution) {
public void setGradlePropsSubstitution(Map<String, String> gradlePropsSubstitution) {
this.gradlePropsSubstitution = gradlePropsSubstitution;
}
@@ -1364,15 +1345,13 @@ public class ReleaserProperties implements Serializable {
public String toString() {
return new StringJoiner(", ", Gradle.class.getSimpleName() + "[", "]")
.add("gradlePropsSubstitution=" + gradlePropsSubstitution)
.add("ignoredGradleRegex=" + ignoredGradleRegex)
.add("buildCommand='" + buildCommand + "'")
.add("ignoredGradleRegex=" + ignoredGradleRegex).add("buildCommand='" + buildCommand + "'")
.add("deployCommand='" + deployCommand + "'")
.add("deployGuidesCommand='" + deployGuidesCommand + "'")
.add("publishDocsCommand=" + publishDocsCommand)
.add("generateReleaseTrainDocsCommand='"
+ generateReleaseTrainDocsCommand + "'")
.add("systemProperties='" + systemProperties + "'")
.add("waitTimeInMinutes=" + waitTimeInMinutes).toString();
.add("generateReleaseTrainDocsCommand='" + generateReleaseTrainDocsCommand + "'")
.add("systemProperties='" + systemProperties + "'").add("waitTimeInMinutes=" + waitTimeInMinutes)
.toString();
}
}
@@ -1519,8 +1498,8 @@ public class ReleaserProperties implements Serializable {
@Override
public String toString() {
return "Versions{" + "allVersionsFileUrl='" + this.allVersionsFileUrl + '\''
+ ", bomName='" + this.bomName + '\'' + '}';
return "Versions{" + "allVersionsFileUrl='" + this.allVersionsFileUrl + '\'' + ", bomName='" + this.bomName
+ '\'' + '}';
}
}

View File

@@ -41,13 +41,11 @@ import org.springframework.util.StringUtils;
*/
public class ReleaserPropertiesUpdater implements Closeable {
private static final Logger log = LoggerFactory
.getLogger(ReleaserPropertiesUpdater.class);
private static final Logger log = LoggerFactory.getLogger(ReleaserPropertiesUpdater.class);
private static final Map<File, ReleaserProperties> CACHE = new ConcurrentHashMap<>();
public ReleaserProperties updateProperties(ReleaserProperties properties,
File clonedProjectFromOrg) {
public ReleaserProperties updateProperties(ReleaserProperties properties, File clonedProjectFromOrg) {
return CACHE.computeIfAbsent(clonedProjectFromOrg, file -> {
ReleaserProperties props = updatePropertiesFromFile(properties.copy(), file);
props.setWorkingDir(clonedProjectFromOrg.getAbsolutePath());
@@ -56,8 +54,7 @@ public class ReleaserPropertiesUpdater implements Closeable {
});
}
private ReleaserProperties updatePropertiesFromFile(ReleaserProperties copy,
File clonedProjectFromOrg) {
private ReleaserProperties updatePropertiesFromFile(ReleaserProperties copy, File clonedProjectFromOrg) {
File releaserConfig = releaserConfig(clonedProjectFromOrg);
if (releaserConfig.exists()) {
try {
@@ -66,11 +63,8 @@ public class ReleaserPropertiesUpdater implements Closeable {
Properties properties = yamlProcessor.getObject();
ReleaserProperties releaserProperties = new Binder(
new MapConfigurationPropertySource(properties.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString()))))
.bind("releaser",
ReleaserProperties.class)
.get();
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))))
.bind("releaser", ReleaserProperties.class).get();
log.info("config/releaser.yml found. Will update the current properties");
overrideProperties(releaserProperties, copy);
}
@@ -79,17 +73,14 @@ public class ReleaserPropertiesUpdater implements Closeable {
}
}
else {
log.info(
"No config/releaser.yml found. Will NOT update the current properties");
log.info("No config/releaser.yml found. Will NOT update the current properties");
}
log.info("Updating working directory to [{}]",
clonedProjectFromOrg.getAbsolutePath());
log.info("Updating working directory to [{}]", clonedProjectFromOrg.getAbsolutePath());
copy.setWorkingDir(clonedProjectFromOrg.getAbsolutePath());
return copy;
}
private void overrideProperties(ReleaserProperties fromProject,
ReleaserProperties copy) {
private void overrideProperties(ReleaserProperties fromProject, ReleaserProperties copy) {
overrideCommandIfPresent(fromProject.getMaven(), copy.getMaven());
overrideCommandIfPresent(fromProject.getGradle(), copy.getGradle());
overrideMapIfPresent(() -> fromProject.getGradle().getGradlePropsSubstitution(),
@@ -101,45 +92,36 @@ public class ReleaserPropertiesUpdater implements Closeable {
private void overrideCommandIfPresent(ReleaserProperties.Command fromProject,
ReleaserProperties.Command commandCopy) {
overrideStringIfPresent(fromProject::getBuildCommand,
commandCopy::setBuildCommand);
overrideStringIfPresent(fromProject::getDeployCommand,
commandCopy::setDeployCommand);
overrideStringIfPresent(fromProject::getBuildCommand, commandCopy::setBuildCommand);
overrideStringIfPresent(fromProject::getDeployCommand, commandCopy::setDeployCommand);
overrideStringIfPresent(fromProject::getGenerateReleaseTrainDocsCommand,
commandCopy::setGenerateReleaseTrainDocsCommand);
overrideStringIfPresent(fromProject::getPublishDocsCommand,
commandCopy::setPublishDocsCommand);
overrideStringIfPresent(fromProject::getDeployGuidesCommand,
commandCopy::setDeployGuidesCommand);
overrideStringIfPresent(fromProject::getSystemProperties,
commandCopy::setSystemProperties);
overrideStringIfPresent(fromProject::getPublishDocsCommand, commandCopy::setPublishDocsCommand);
overrideStringIfPresent(fromProject::getDeployGuidesCommand, commandCopy::setDeployGuidesCommand);
overrideStringIfPresent(fromProject::getSystemProperties, commandCopy::setSystemProperties);
}
private void overrideStringIfPresent(Supplier<String> predicate,
Consumer<String> consumer) {
private void overrideStringIfPresent(Supplier<String> predicate, Consumer<String> consumer) {
if (StringUtils.hasText(predicate.get())) {
consumer.accept(predicate.get());
}
}
private void overrideArrayIfPresent(Supplier<String[]> predicate,
Consumer<String[]> consumer) {
private void overrideArrayIfPresent(Supplier<String[]> predicate, Consumer<String[]> consumer) {
String[] strings = predicate.get();
if (strings.length > 0) {
consumer.accept(strings);
}
}
private void overrideMapIfPresent(Supplier<Map<String, String>> predicate,
Consumer<Map<String, String>> consumer) {
private void overrideMapIfPresent(Supplier<Map<String, String>> predicate, Consumer<Map<String, String>> consumer) {
Map<String, String> strings = predicate.get();
if (!strings.isEmpty()) {
consumer.accept(strings);
}
}
private void overrideListIfPresent(Supplier<List<String>> predicate,
Consumer<List<String>> consumer) {
private void overrideListIfPresent(Supplier<List<String>> predicate, Consumer<List<String>> consumer) {
List<String> strings = predicate.get();
if (!strings.isEmpty()) {
consumer.accept(strings);

View File

@@ -39,15 +39,13 @@ class CompositeBomParser implements BomParser {
}
private BomParser firstMatching(File thisProjectRoot) {
return this.parsers.stream().filter(b -> b.isApplicable(thisProjectRoot))
.findFirst().orElseThrow(
() -> new IllegalStateException("Can't find a matching parser"));
return this.parsers.stream().filter(b -> b.isApplicable(thisProjectRoot)).findFirst()
.orElseThrow(() -> new IllegalStateException("Can't find a matching parser"));
}
@Override
public List<CustomBomParser> customBomParsers() {
return this.parsers.stream().flatMap(b -> b.customBomParsers().stream())
.collect(Collectors.toList());
return this.parsers.stream().flatMap(b -> b.customBomParsers().stream()).collect(Collectors.toList());
}
}

View File

@@ -28,8 +28,7 @@ import releaser.internal.project.Project;
*/
public interface CustomBomParser {
CustomBomParser NO_OP = (thisProjectRoot,
properties) -> VersionsFromBom.EMPTY_VERSION;
CustomBomParser NO_OP = (thisProjectRoot, properties) -> VersionsFromBom.EMPTY_VERSION;
/**
* When parsing a part of the BOM pom, one can add custom logic to perform project
@@ -48,8 +47,7 @@ public interface CustomBomParser {
* @param version - version of the project
* @return - a new collection with the modified versions from bom
*/
default Set<Project> setVersion(Set<Project> projects, String projectName,
String version) {
default Set<Project> setVersion(Set<Project> projects, String projectName, String version) {
return new LinkedHashSet<>(projects);
}

View File

@@ -33,8 +33,7 @@ class GradleBomParser implements BomParser {
private final GradleProjectNameExtractor extractor = new GradleProjectNameExtractor();
GradleBomParser(ReleaserProperties releaserProperties,
List<CustomBomParser> customParsers) {
GradleBomParser(ReleaserProperties releaserProperties, List<CustomBomParser> customParsers) {
this.properties = releaserProperties;
this.customParsers = customParsers;
}
@@ -55,11 +54,9 @@ class GradleBomParser implements BomParser {
return VersionsFromBom.EMPTY_VERSION;
}
Properties properties = loadProps(gradleProperties);
final Map<String, String> substitution = this.properties.getGradle()
.getGradlePropsSubstitution();
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder()
.thisProjectRoot(thisProjectRoot).releaserProperties(this.properties)
.parsers(this.customParsers).retrieveFromBom();
final Map<String, String> substitution = this.properties.getGradle().getGradlePropsSubstitution();
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder().thisProjectRoot(thisProjectRoot)
.releaserProperties(this.properties).parsers(this.customParsers).retrieveFromBom();
properties.forEach((key, value) -> {
String projectName = this.extractor.projectName(substitution, key);
versionsFromBom.setVersion(projectName, value.toString());

View File

@@ -22,8 +22,7 @@ import java.util.regex.Pattern;
class GradleProjectNameExtractor {
private static final Pattern VERSION_PATTERN = Pattern
.compile("^([a-zA-Z0-9]+)Version$");
private static final Pattern VERSION_PATTERN = Pattern.compile("^([a-zA-Z0-9]+)Version$");
String projectName(Map<String, String> substitution, Object key) {
String projectName = key.toString();

View File

@@ -55,18 +55,16 @@ public class GradleUpdater {
* @param versionFromBom - version for the project from Spring Cloud Release
* @param assertVersions - should snapshots / milestone / rc presence be asserted
*/
public void updateProjectFromReleaseTrain(ReleaserProperties properties,
File projectRoot, Projects projects, ProjectVersion versionFromBom,
boolean assertVersions) {
processAllGradleProps(properties, projectRoot, projects, versionFromBom,
assertVersions);
public void updateProjectFromReleaseTrain(ReleaserProperties properties, File projectRoot, Projects projects,
ProjectVersion versionFromBom, boolean assertVersions) {
processAllGradleProps(properties, projectRoot, projects, versionFromBom, assertVersions);
}
private void processAllGradleProps(ReleaserProperties properties, File projectRoot,
Projects projects, ProjectVersion versionFromBom, boolean assertVersions) {
private void processAllGradleProps(ReleaserProperties properties, File projectRoot, Projects projects,
ProjectVersion versionFromBom, boolean assertVersions) {
try {
Files.walkFileTree(projectRoot.toPath(), new GradlePropertiesWalker(
properties, projects, versionFromBom, assertVersions));
Files.walkFileTree(projectRoot.toPath(),
new GradlePropertiesWalker(properties, projects, versionFromBom, assertVersions));
}
catch (IOException e) {
throw new IllegalStateException(e);
@@ -89,15 +87,13 @@ public class GradleUpdater {
private final GradleProjectNameExtractor extractor = new GradleProjectNameExtractor();
private GradlePropertiesWalker(ReleaserProperties properties, Projects projects,
ProjectVersion versionFromBom, boolean assertVersions) {
private GradlePropertiesWalker(ReleaserProperties properties, Projects projects, ProjectVersion versionFromBom,
boolean assertVersions) {
this.properties = properties;
this.projects = projects;
List<Pattern> unacceptableVersionPatterns = versionFromBom
.unacceptableVersionPatterns();
List<Pattern> unacceptableVersionPatterns = versionFromBom.unacceptableVersionPatterns();
this.unacceptableVersionPatterns = unacceptableVersionPatterns;
this.skipVersionAssert = !assertVersions
|| unacceptableVersionPatterns.isEmpty();
this.skipVersionAssert = !assertVersions || unacceptableVersionPatterns.isEmpty();
this.assertVersions = assertVersions;
}
@@ -106,20 +102,15 @@ public class GradleUpdater {
File file = path.toFile();
if (GRADLE_PROPERTIES.equals(file.getName())) {
if (pathIgnored(file)) {
log.debug(
"Ignoring file [{}] since it's on a list of patterns to ignore",
file);
log.debug("Ignoring file [{}] since it's on a list of patterns to ignore", file);
return FileVisitResult.CONTINUE;
}
String parentName = file.getParentFile().getName();
log.info("Will process the file [{}] and update its gradle properties",
file);
log.info("Will process the file [{}] and update its gradle properties", file);
final String fileContents = asString(path);
final AtomicReference<String> changedString = new AtomicReference<>(
fileContents);
final AtomicReference<String> changedString = new AtomicReference<>(fileContents);
Properties props = loadProps(file);
final Map<String, String> substitution = this.properties.getGradle()
.getGradlePropsSubstitution();
final Map<String, String> substitution = this.properties.getGradle().getGradlePropsSubstitution();
props.forEach((key, value1) -> {
String projectName = projectName(parentName, substitution, key);
if (!this.projects.containsProject(projectName)) {
@@ -130,10 +121,8 @@ public class GradleUpdater {
}
ProjectVersion value = this.projects.forName(projectName);
if (!value.version.equalsIgnoreCase(value1.toString())) {
log.info("Replacing [{}->{}] with [{}->{}]", key, value1, key,
value);
changedString.set(changedString.get().replace(key + "=" + value1,
key + "=" + value));
log.info("Replacing [{}->{}] with [{}->{}]", key, value1, key, value);
changedString.set(changedString.get().replace(key + "=" + value1, key + "=" + value));
}
});
storeString(path, changedString.get());
@@ -142,8 +131,7 @@ public class GradleUpdater {
return FileVisitResult.CONTINUE;
}
private String projectName(String parentName, Map<String, String> substitution,
Object key) {
private String projectName(String parentName, Map<String, String> substitution, Object key) {
// version -> current project version
if (key.equals("version")) {
return parentName;
@@ -155,21 +143,18 @@ public class GradleUpdater {
if (this.assertVersions && !this.skipVersionAssert) {
log.debug(
"Update should check if no wrong versions remained in the gradle prop. List of wrong patterns: {}",
this.unacceptableVersionPatterns.stream().map(Pattern::pattern)
.collect(Collectors.toList()));
this.unacceptableVersionPatterns.stream().map(Pattern::pattern).collect(Collectors.toList()));
Scanner scanner = new Scanner(asString(path));
int lineNumber = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNumber++;
Pattern matchingPattern = this.unacceptableVersionPatterns.stream()
.filter(pattern -> pattern.matcher(line).matches())
.findFirst().orElse(null);
.filter(pattern -> pattern.matcher(line).matches()).findFirst().orElse(null);
if (matchingPattern != null) {
throw new IllegalStateException("The file [" + path
+ "] matches the [ " + matchingPattern.pattern()
+ "] pattern in line number [" + lineNumber + "]\n\n"
+ line);
throw new IllegalStateException(
"The file [" + path + "] matches the [ " + matchingPattern.pattern()
+ "] pattern in line number [" + lineNumber + "]\n\n" + line);
}
}
log.info("No invalid versions remained in the gradle properties");
@@ -178,8 +163,8 @@ public class GradleUpdater {
private boolean pathIgnored(File file) {
String path = file.getPath();
return this.assertVersions && this.properties.getGradle()
.getIgnoredGradleRegex().stream().anyMatch(path::matches);
return this.assertVersions
&& this.properties.getGradle().getIgnoredGradleRegex().stream().anyMatch(path::matches);
}
private Properties loadProps(File file) {

View File

@@ -50,10 +50,8 @@ class MavenBomParser implements BomParser {
MavenBomParser(ReleaserProperties properties, List<CustomBomParser> customParsers) {
this.thisTrainBomLocation = properties.getPom().getThisTrainBom();
this.versionPattern = StringUtils
.hasText(properties.getPom().getBomVersionPattern())
? Pattern.compile(properties.getPom().getBomVersionPattern())
: Pattern.compile(".*");
this.versionPattern = StringUtils.hasText(properties.getPom().getBomVersionPattern())
? Pattern.compile(properties.getPom().getBomVersionPattern()) : Pattern.compile(".*");
this.properties = properties;
this.customParsers = customParsers;
}
@@ -71,13 +69,11 @@ class MavenBomParser implements BomParser {
if (model == null) {
return VersionsFromBom.EMPTY_VERSION;
}
Set<Project> projects = model.getProperties().entrySet().stream()
.filter(propertyMatchesVersionPattern()).map(toProject())
.collect(Collectors.toSet());
Set<Project> projects = model.getProperties().entrySet().stream().filter(propertyMatchesVersionPattern())
.map(toProject()).collect(Collectors.toSet());
String releaseTrainProjectVersion = model.getVersion();
projects.add(
new Project(this.properties.getMetaRelease().getReleaseTrainProjectName(),
releaseTrainProjectVersion));
new Project(this.properties.getMetaRelease().getReleaseTrainProjectName(), releaseTrainProjectVersion));
// @formatter:off
return new VersionsFromBomBuilder()
.thisProjectRoot(thisProjectRoot)

View File

@@ -75,13 +75,10 @@ class PomUpdater {
}
String artifactId = artifactId(model);
if (!versionsFromBom.shouldBeUpdated(artifactId)) {
log.info(
"Skipping project [{}] since it's not on the list of projects to update",
model.getArtifactId());
log.info("Skipping project [{}] since it's not on the list of projects to update", model.getArtifactId());
return false;
}
log.info("Project [{}] will have its dependencies updated",
model.getArtifactId());
log.info("Project [{}] will have its dependencies updated", model.getArtifactId());
return true;
}
@@ -95,8 +92,7 @@ class PomUpdater {
return false;
}
boolean plugins = model.getBuild().getPlugins().stream()
.filter(plugin -> "maven-deploy-plugin"
.equalsIgnoreCase(plugin.getArtifactId()))
.filter(plugin -> "maven-deploy-plugin".equalsIgnoreCase(plugin.getArtifactId()))
.map(this::skipFromConfiguration).findFirst().orElse(false);
if (plugins) {
return true;
@@ -105,8 +101,7 @@ class PomUpdater {
return false;
}
return model.getBuild().getPluginManagement().getPlugins().stream()
.filter(plugin -> "maven-deploy-plugin"
.equalsIgnoreCase(plugin.getArtifactId()))
.filter(plugin -> "maven-deploy-plugin".equalsIgnoreCase(plugin.getArtifactId()))
.map(this::skipFromConfiguration).findFirst().orElse(false);
}
@@ -131,8 +126,7 @@ class PomUpdater {
if (!parent) {
return model.getArtifactId();
}
return model.getArtifactId().substring(0,
model.getArtifactId().indexOf("-parent"));
return model.getArtifactId().substring(0, model.getArtifactId().indexOf("-parent"));
}
ModelWrapper readModel(File pom) {
@@ -146,14 +140,11 @@ class PomUpdater {
* @param versionsFromBom - versions to update
* @return updated model
*/
ModelWrapper updateModel(ModelWrapper rootPom, File pom,
VersionsFromBom versionsFromBom) {
ModelWrapper updateModel(ModelWrapper rootPom, File pom, VersionsFromBom versionsFromBom) {
Model model = PomReader.readPom(pom);
List<VersionChange> sourceChanges = new ArrayList<>();
sourceChanges = updateParentIfPossible(rootPom, versionsFromBom, model,
sourceChanges);
sourceChanges = updateVersionIfPossible(rootPom, versionsFromBom, model,
sourceChanges);
sourceChanges = updateParentIfPossible(rootPom, versionsFromBom, model, sourceChanges);
sourceChanges = updateVersionIfPossible(rootPom, versionsFromBom, model, sourceChanges);
return new ModelWrapper(model, sourceChanges, versionsFromBom, pom);
}
@@ -162,8 +153,7 @@ class PomUpdater {
* changes in the model.
* @return - the pom file
*/
File overwritePomIfDirty(ModelWrapper updatedPomModel,
VersionsFromBom versionsFromBom, File pom) {
File overwritePomIfDirty(ModelWrapper updatedPomModel, VersionsFromBom versionsFromBom, File pom) {
if (updatedPomModel.isDirty()) {
log.debug("There were changes in the pom so file will be overridden");
this.pomWriter.write(updatedPomModel, versionsFromBom, pom);
@@ -172,9 +162,8 @@ class PomUpdater {
return pom;
}
private List<VersionChange> updateParentIfPossible(ModelWrapper wrapper,
VersionsFromBom versionsFromBom, Model model,
List<VersionChange> sourceChanges) {
private List<VersionChange> updateParentIfPossible(ModelWrapper wrapper, VersionsFromBom versionsFromBom,
Model model, List<VersionChange> sourceChanges) {
String rootProjectName = wrapper.projectName();
List<VersionChange> changes = new ArrayList<>(sourceChanges);
if (model.getParent() == null || isEmpty(model.getParent().getVersion())) {
@@ -183,8 +172,7 @@ class PomUpdater {
}
String parentGroupId = model.getParent().getGroupId();
String parentArtifactId = model.getParent().getArtifactId();
log.debug("Searching for a version of parent [{}:{}]", parentGroupId,
parentArtifactId);
log.debug("Searching for a version of parent [{}:{}]", parentGroupId, parentArtifactId);
String oldVersion = model.getParent().getVersion();
String version = versionsFromBom.versionForProject(parentArtifactId);
log.debug("Found version is [{}]", version);
@@ -193,38 +181,32 @@ class PomUpdater {
version = versionsFromBom.versionForProject(rootProjectName);
}
else {
log.warn("There is no info on the [{}:{}] version", parentGroupId,
parentArtifactId);
log.warn("There is no info on the [{}:{}] version", parentGroupId, parentArtifactId);
return changes;
}
}
if (oldVersion.equals(version)) {
log.debug(
"Won't update the version of parent [{}:{}] since you're already using the proper one",
log.debug("Won't update the version of parent [{}:{}] since you're already using the proper one",
parentGroupId, parentArtifactId);
return changes;
}
log.info("Setting version of parent [{}] to [{}] for module [{}]",
parentArtifactId, version, model.getArtifactId());
log.info("Setting version of parent [{}] to [{}] for module [{}]", parentArtifactId, version,
model.getArtifactId());
if (hasText(version)) {
changes.add(new VersionChange(parentGroupId, parentArtifactId, oldVersion,
version));
changes.add(new VersionChange(parentGroupId, parentArtifactId, oldVersion, version));
}
return changes;
}
private List<VersionChange> updateVersionIfPossible(ModelWrapper wrapper,
VersionsFromBom versionsFromBom, Model model,
List<VersionChange> sourceChanges) {
private List<VersionChange> updateVersionIfPossible(ModelWrapper wrapper, VersionsFromBom versionsFromBom,
Model model, List<VersionChange> sourceChanges) {
String rootProjectName = wrapper.projectName();
String rootProjectGroupId = wrapper.groupId();
List<VersionChange> changes = new ArrayList<>(sourceChanges);
String groupId = groupId(model);
String artifactId = model.getArtifactId();
if (model.getGroupId() != null
&& !model.getGroupId().equals(rootProjectGroupId)) {
log.info(
"Will not update project [{}] since its group id [{}] is not equal the parent group id [{}]",
if (model.getGroupId() != null && !model.getGroupId().equals(rootProjectGroupId)) {
log.info("Will not update project [{}] since its group id [{}] is not equal the parent group id [{}]",
model.getArtifactId(), model.getGroupId(), rootProjectGroupId);
return changes;
}
@@ -233,15 +215,13 @@ class PomUpdater {
String version = versionsFromBom.versionForProject(rootProjectName);
log.debug("Found version is [{}]", version);
if (isEmpty(version) || isEmpty(model.getVersion())) {
log.debug(
"There was no version set for project [{}], skipping version setting for module [{}]",
log.debug("There was no version set for project [{}], skipping version setting for module [{}]",
rootProjectName, model.getArtifactId());
return changes;
}
if (oldVersion.equals(version)) {
log.debug(
"Won't update the version of module [{}]:[{}] since you're already using the proper one",
groupId, artifactId);
log.debug("Won't update the version of module [{}]:[{}] since you're already using the proper one", groupId,
artifactId);
return changes;
}
log.info("Setting [{}] version to [{}]", artifactId, version);
@@ -271,8 +251,7 @@ class ModelWrapper {
final File rootFile;
ModelWrapper(Model model, List<VersionChange> sourceChanges,
VersionsFromBom versionsFromBom, File rootFile) {
ModelWrapper(Model model, List<VersionChange> sourceChanges, VersionsFromBom versionsFromBom, File rootFile) {
this.model = model;
this.versionsFromBom = versionsFromBom;
this.sourceChanges.addAll(sourceChanges);
@@ -303,8 +282,7 @@ class ModelWrapper {
}
boolean isDirty() {
return !this.sourceChanges.isEmpty()
|| this.versionsFromBom.shouldSetProperty(this.model.getProperties());
return !this.sourceChanges.isEmpty() || this.versionsFromBom.shouldSetProperty(this.model.getProperties());
}
}
@@ -322,17 +300,13 @@ class PomWriter {
LoggerToMavenLog loggerToMavenLog = new LoggerToMavenLog(PomWriter.log);
versionChangerFactory.setLog(loggerToMavenLog);
versionChangerFactory.setModel(wrapper.model);
log.info(
"Applying version / parent / plugin / project changes to the pom [{}]",
pom);
VersionChanger changer = versionChangerFactory.newVersionChanger(true, true,
true, true);
log.info("Applying version / parent / plugin / project changes to the pom [{}]", pom);
VersionChanger changer = versionChangerFactory.newVersionChanger(true, true, true, true);
for (VersionChange versionChange : wrapper.sourceChanges) {
changer.apply(versionChange);
}
log.debug("Applying properties changes to the pom [{}]", pom);
new PropertyVersionChanger(wrapper, versionsFromBom, parsedPom,
loggerToMavenLog).apply(null);
new PropertyVersionChanger(wrapper, versionsFromBom, parsedPom, loggerToMavenLog).apply(null);
try (BufferedWriter bw = new BufferedWriter(new FileWriter(pom))) {
bw.write(input.toString());
}
@@ -370,15 +344,15 @@ class PropertyVersionChanger extends AbstractVersionChanger {
private final PropertyStorer propertyStorer;
PropertyVersionChanger(ModelWrapper wrapper, VersionsFromBom versionsFromBom,
ModifiedPomXMLEventReader pom, Log log) {
PropertyVersionChanger(ModelWrapper wrapper, VersionsFromBom versionsFromBom, ModifiedPomXMLEventReader pom,
Log log) {
super(wrapper.model, pom, log);
this.versionsFromBom = versionsFromBom;
this.propertyStorer = new PropertyStorer(log, pom);
}
PropertyVersionChanger(ModelWrapper wrapper, VersionsFromBom versionsFromBom,
ModifiedPomXMLEventReader pom, Log log, PropertyStorer propertyStorer) {
PropertyVersionChanger(ModelWrapper wrapper, VersionsFromBom versionsFromBom, ModifiedPomXMLEventReader pom,
Log log, PropertyStorer propertyStorer) {
super(wrapper.model, pom, log);
this.versionsFromBom = versionsFromBom;
this.propertyStorer = propertyStorer;
@@ -417,8 +391,7 @@ class PropertyStorer {
void setPropertyVersionIfApplicable(Project project) {
String propertyName = propertyName(project);
if (setPropertyVersion(propertyName, project.version)) {
this.log.info("Updating property [" + propertyName + "] to version ["
+ project.version + "]");
this.log.info("Updating property [" + propertyName + "] to version [" + project.version + "]");
}
}
@@ -429,8 +402,7 @@ class PropertyStorer {
private boolean setPropertyVersion(String propertyName, String version) {
try {
if (StringUtils.isEmpty(version)) {
this.log.warn(
"Version for [" + propertyName + "] is empty. Will not set it");
this.log.warn("Version for [" + propertyName + "] is empty. Will not set it");
return false;
}
return PomHelper.setPropertyVersion(this.pom, null, propertyName, version);

View File

@@ -46,8 +46,7 @@ import releaser.internal.project.Projects;
*/
public class ProjectPomUpdater implements Closeable {
private static final List<String> IGNORED_SNAPSHOT_LINE_PATTERNS = Arrays.asList(
"^.*replace=.*$",
private static final List<String> IGNORED_SNAPSHOT_LINE_PATTERNS = Arrays.asList("^.*replace=.*$",
// issue [#80]
"^[\\s]*<!--.*-->.*$");
@@ -79,8 +78,7 @@ public class ProjectPomUpdater implements Closeable {
* @return projects retrieved from the release train bom
*/
public Projects retrieveVersionsFromReleaseTrainBom() {
return retrieveVersionsFromReleaseTrainBom(this.properties.getPom().getBranch(),
UPDATE_FIXED_VERSIONS);
return retrieveVersionsFromReleaseTrainBom(this.properties.getPom().getBranch(), UPDATE_FIXED_VERSIONS);
}
/**
@@ -92,12 +90,10 @@ public class ProjectPomUpdater implements Closeable {
* @return projects retrieved from the release train bom
*/
// TODO: I don't like this flag but don't have a better idea
public Projects retrieveVersionsFromReleaseTrainBom(String branch,
boolean updateFixedVersions) {
public Projects retrieveVersionsFromReleaseTrainBom(String branch, boolean updateFixedVersions) {
VersionsFromBom versionsFromBom = cachedVersionFromBom(branch);
if (updateFixedVersions) {
log.info("Will update the following versions manually [{}]",
this.properties.getFixedVersions());
log.info("Will update the following versions manually [{}]", this.properties.getFixedVersions());
this.properties.getFixedVersions().forEach(versionsFromBom::setVersion);
}
log.info("Retrieved the following versions\n{}", versionsFromBom);
@@ -121,14 +117,12 @@ public class ProjectPomUpdater implements Closeable {
*/
public Projects fixedVersions() {
Set<Project> projects = this.properties.getFixedVersions().entrySet().stream()
.map(entry -> new Project(entry.getKey(), entry.getValue()))
.collect(Collectors.toSet());
.map(entry -> new Project(entry.getKey(), entry.getValue())).collect(Collectors.toSet());
if (log.isDebugEnabled()) {
log.debug("Will apply the following fixed versions {}", projects);
}
return new VersionsFromBomBuilder().releaserProperties(this.properties)
.parsers(compositeBomParser().customBomParsers()).projects(projects)
.merged().toProjectVersions();
.parsers(compositeBomParser().customBomParsers()).projects(projects).merged().toProjectVersions();
}
/**
@@ -143,9 +137,8 @@ public class ProjectPomUpdater implements Closeable {
*/
public void updateProjectFromReleaseTrain(File projectRoot, Projects projects,
ProjectVersion versionFromReleaseTrain, boolean assertVersions) {
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder()
.thisProjectRoot(projectRoot).releaserProperties(this.properties)
.projects(projects.asProjects()).merged();
VersionsFromBom versionsFromBom = new VersionsFromBomBuilder().thisProjectRoot(projectRoot)
.releaserProperties(this.properties).projects(projects.asProjects()).merged();
if (!this.pomUpdater.shouldProjectBeUpdated(projectRoot, versionsFromBom)) {
log.debug("Skipping project updating");
return;
@@ -153,16 +146,16 @@ public class ProjectPomUpdater implements Closeable {
updatePoms(projectRoot, versionsFromBom, versionFromReleaseTrain, assertVersions);
}
private void updatePoms(File projectRoot, VersionsFromBom projects,
ProjectVersion versionFromScRelease, boolean assertVersions) {
private void updatePoms(File projectRoot, VersionsFromBom projects, ProjectVersion versionFromScRelease,
boolean assertVersions) {
File rootPom = new File(projectRoot, "pom.xml");
if (!rootPom.exists()) {
log.info("No pom.xml present, skipping!");
return;
}
ModelWrapper rootPomModel = this.pomUpdater.readModel(rootPom);
processAllPoms(projectRoot, new PomWalker(rootPomModel, projects, this.pomUpdater,
this.properties, versionFromScRelease, assertVersions));
processAllPoms(projectRoot, new PomWalker(rootPomModel, projects, this.pomUpdater, this.properties,
versionFromScRelease, assertVersions));
}
private void processAllPoms(File projectRoot, PomWalker pomWalker) {
@@ -197,18 +190,15 @@ public class ProjectPomUpdater implements Closeable {
private final List<Pattern> unacceptableVersionPatterns;
private PomWalker(ModelWrapper rootPom, VersionsFromBom projects,
PomUpdater pomUpdater, ReleaserProperties properties,
ProjectVersion versionFromScRelease, boolean assertVersions) {
private PomWalker(ModelWrapper rootPom, VersionsFromBom projects, PomUpdater pomUpdater,
ReleaserProperties properties, ProjectVersion versionFromScRelease, boolean assertVersions) {
this.rootPom = rootPom;
this.versionsFromBom = projects;
this.pomUpdater = pomUpdater;
this.properties = properties;
List<Pattern> unacceptableVersionPatterns = versionFromScRelease
.unacceptableVersionPatterns();
List<Pattern> unacceptableVersionPatterns = versionFromScRelease.unacceptableVersionPatterns();
this.unacceptableVersionPatterns = unacceptableVersionPatterns;
this.skipVersionAssert = !assertVersions
|| unacceptableVersionPatterns.isEmpty();
this.skipVersionAssert = !assertVersions || unacceptableVersionPatterns.isEmpty();
this.assertVersions = assertVersions;
}
@@ -217,28 +207,21 @@ public class ProjectPomUpdater implements Closeable {
File file = path.toFile();
if (POM_XML.equals(file.getName())) {
if (pathIgnored(file)) {
log.debug(
"Ignoring file [{}] since it's on a list of patterns to ignore",
file);
log.debug("Ignoring file [{}] since it's on a list of patterns to ignore", file);
return FileVisitResult.CONTINUE;
}
ModelWrapper model = this.pomUpdater.updateModel(this.rootPom, file,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(this.rootPom, file, this.versionsFromBom);
this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, file);
if (this.assertVersions && !this.skipVersionAssert
&& !this.pomUpdater.hasSkipDeployment(model.model)) {
log.debug(
"Update is a non-snapshot one. Checking if no snapshot versions remained in the pom");
if (this.assertVersions && !this.skipVersionAssert && !this.pomUpdater.hasSkipDeployment(model.model)) {
log.debug("Update is a non-snapshot one. Checking if no snapshot versions remained in the pom");
String text = asString(path);
Scanner scanner = new Scanner(text);
int lineNumber = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNumber++;
Pattern matchingPattern = this.unacceptableVersionPatterns
.stream()
.filter(pattern -> IGNORED_SNAPSHOT_LINE_PATTERNS.stream()
.noneMatch(line::matches)
Pattern matchingPattern = this.unacceptableVersionPatterns.stream()
.filter(pattern -> IGNORED_SNAPSHOT_LINE_PATTERNS.stream().noneMatch(line::matches)
&& !line.contains(SPECIAL_LINE_IGNORING_COMMENT)
&& pattern.matcher(line).lookingAt())
.findFirst().orElse(null);
@@ -246,10 +229,9 @@ public class ProjectPomUpdater implements Closeable {
if (log.isDebugEnabled()) {
log.debug("File text \n" + text);
}
throw new IllegalStateException("The file [" + path
+ "] matches the [ " + matchingPattern.pattern()
+ "] pattern in line number [" + lineNumber + "]\n\n"
+ line);
throw new IllegalStateException(
"The file [" + path + "] matches the [ " + matchingPattern.pattern()
+ "] pattern in line number [" + lineNumber + "]\n\n" + line);
}
}
log.info("No invalid versions remained in the pom");
@@ -260,8 +242,8 @@ public class ProjectPomUpdater implements Closeable {
private boolean pathIgnored(File file) {
String path = file.getPath();
return this.assertVersions && this.properties.getPom().getIgnoredPomRegex()
.stream().anyMatch(path::matches);
return this.assertVersions
&& this.properties.getPom().getIgnoredPomRegex().stream().anyMatch(path::matches);
}
private String asString(Path path) {

View File

@@ -56,15 +56,13 @@ public class VersionsFromBom {
this.parser = parser;
}
VersionsFromBom(ReleaserProperties releaserProperties, CustomBomParser parser,
Set<Project> projects) {
VersionsFromBom(ReleaserProperties releaserProperties, CustomBomParser parser, Set<Project> projects) {
this.properties = releaserProperties;
this.parser = parser;
projects.forEach(project -> setVersion(project.name, project.version));
}
VersionsFromBom(ReleaserProperties releaserProperties, CustomBomParser parser,
VersionsFromBom... projects) {
VersionsFromBom(ReleaserProperties releaserProperties, CustomBomParser parser, VersionsFromBom... projects) {
this.properties = releaserProperties;
this.parser = parser;
Arrays.stream(projects).forEach(p -> this.projects.addAll(p.projects));
@@ -84,23 +82,20 @@ public class VersionsFromBom {
}
public String versionForProject(String projectName) {
return this.projects.stream().filter(project -> nameMatches(projectName, project))
.findFirst().orElse(Project.EMPTY_PROJECT).version;
return this.projects.stream().filter(project -> nameMatches(projectName, project)).findFirst()
.orElse(Project.EMPTY_PROJECT).version;
}
public boolean shouldBeUpdated(String projectName) {
return this.projects.stream()
.anyMatch(project -> nameMatches(projectName, project));
return this.projects.stream().anyMatch(project -> nameMatches(projectName, project));
}
public boolean shouldSetProperty(Properties properties) {
return this.projects.stream()
.anyMatch(project -> properties.containsKey(project.name + ".version"));
return this.projects.stream().anyMatch(project -> properties.containsKey(project.name + ".version"));
}
public Projects toProjectVersions() {
return this.projects.stream()
.map(project -> new ProjectVersion(project.name, project.version))
return this.projects.stream().map(project -> new ProjectVersion(project.name, project.version))
.collect(Collectors.toCollection(Projects::new));
}
@@ -114,23 +109,18 @@ public class VersionsFromBom {
}
boolean parent = matchesNameWithSuffix(projectName, "-parent", project);
boolean bomArtifactId = comparisonOfBomArtifactAndParent(projectName, project);
return !bomArtifactId && (parent
|| matchesNameWithSuffix(projectName, "-dependencies", project));
return !bomArtifactId && (parent || matchesNameWithSuffix(projectName, "-dependencies", project));
}
private boolean comparisonOfBomArtifactAndParent(String projectName,
Project project) {
return artifactOrParent(projectName, project.name)
|| artifactOrParent(project.name, projectName);
private boolean comparisonOfBomArtifactAndParent(String projectName, Project project) {
return artifactOrParent(projectName, project.name) || artifactOrParent(project.name, projectName);
}
private boolean artifactOrParent(String projectName, String otherProjectName) {
return projectName.equals(dependenciesArtifactId())
&& otherProjectName.equals(dependenciesParentArtifactId());
return projectName.equals(dependenciesArtifactId()) && otherProjectName.equals(dependenciesParentArtifactId());
}
private boolean matchesNameWithSuffix(String projectName, String suffix,
Project project) {
private boolean matchesNameWithSuffix(String projectName, String suffix, Project project) {
boolean containsSuffix = projectName.endsWith(suffix);
if (!containsSuffix) {
return false;
@@ -157,8 +147,7 @@ public class VersionsFromBom {
}
private List<String> bomVersionProjectNames() {
List<String> names = new ArrayList<>(
this.properties.getMetaRelease().getReleaseTrainDependencyNames());
List<String> names = new ArrayList<>(this.properties.getMetaRelease().getReleaseTrainDependencyNames());
names.add(this.properties.getMetaRelease().getReleaseTrainProjectName());
return names;
}
@@ -184,8 +173,7 @@ public class VersionsFromBom {
@Override
public String toString() {
return "Projects=\n\t" + this.projects.stream().map(Object::toString)
.collect(Collectors.joining("\n\t"));
return "Projects=\n\t" + this.projects.stream().map(Object::toString).collect(Collectors.joining("\n\t"));
}
}

View File

@@ -42,8 +42,7 @@ public class VersionsFromBomBuilder {
return this;
}
public VersionsFromBomBuilder releaserProperties(
ReleaserProperties releaserProperties) {
public VersionsFromBomBuilder releaserProperties(ReleaserProperties releaserProperties) {
this.releaserProperties = releaserProperties;
return this;
}
@@ -68,8 +67,7 @@ public class VersionsFromBomBuilder {
if (!this.projects.isEmpty()) {
return new VersionsFromBom(this.releaserProperties, bomParser, this.projects);
}
return new VersionsFromBom(this.releaserProperties, bomParser,
this.versionsFromBom);
return new VersionsFromBom(this.releaserProperties, bomParser, this.versionsFromBom);
}
public VersionsFromBom retrieveFromBom() {
@@ -77,13 +75,11 @@ public class VersionsFromBomBuilder {
CustomBomParser bomParser = parser();
VersionsFromBom versionsFromBom = versionsFromBom(bomParser);
VersionsFromBom customParsing = customParsing(thisProjectRoot);
return new VersionsFromBom(this.releaserProperties, bomParser, versionsFromBom,
customParsing);
return new VersionsFromBom(this.releaserProperties, bomParser, versionsFromBom, customParsing);
}
private File thisProjectRoot() {
return this.thisProjectRoot != null ? this.thisProjectRoot
: new File(this.releaserProperties.getWorkingDir());
return this.thisProjectRoot != null ? this.thisProjectRoot : new File(this.releaserProperties.getWorkingDir());
}
private CustomBomParser parser() {
@@ -95,20 +91,16 @@ public class VersionsFromBomBuilder {
return new VersionsFromBom(this.releaserProperties, bomParser, this.projects);
}
else if (this.versionsFromBom.length != 0) {
return new VersionsFromBom(this.releaserProperties, bomParser,
this.versionsFromBom);
return new VersionsFromBom(this.releaserProperties, bomParser, this.versionsFromBom);
}
return new VersionsFromBom(this.releaserProperties, bomParser);
}
private VersionsFromBom customParsing(File thisProjectRoot) {
return this.parsers.stream()
.map(p -> p.parseBom(thisProjectRoot, this.releaserProperties))
.reduce((versionsFromBom,
versionsFromBom2) -> new VersionsFromBomBuilder()
.parsers(this.parsers).thisProjectRoot(thisProjectRoot)
.releaserProperties(this.releaserProperties)
.projects(versionsFromBom, versionsFromBom2).merged())
return this.parsers.stream().map(p -> p.parseBom(thisProjectRoot, this.releaserProperties))
.reduce((versionsFromBom, versionsFromBom2) -> new VersionsFromBomBuilder().parsers(this.parsers)
.thisProjectRoot(thisProjectRoot).releaserProperties(this.releaserProperties)
.projects(versionsFromBom, versionsFromBom2).merged())
.orElse(VersionsFromBom.EMPTY_VERSION);
}

View File

@@ -32,14 +32,14 @@ public interface CustomProjectDocumentationUpdater {
CustomProjectDocumentationUpdater NO_OP = new CustomProjectDocumentationUpdater() {
@Override
public File updateDocsRepoForReleaseTrain(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects, String bomBranch) {
public File updateDocsRepoForReleaseTrain(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects, String bomBranch) {
return clonedDocumentationProject;
}
@Override
public File updateDocsRepoForSingleProject(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects) {
public File updateDocsRepoForSingleProject(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects) {
return clonedDocumentationProject;
}
};
@@ -53,8 +53,8 @@ public interface CustomProjectDocumentationUpdater {
* @return {@link File cloned temporary directory} - {@code null} if wrong version is
* used
*/
File updateDocsRepoForReleaseTrain(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects, String bomBranch);
File updateDocsRepoForReleaseTrain(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects, String bomBranch);
/**
* Updates the documentation repository for a single project.
@@ -64,7 +64,7 @@ public interface CustomProjectDocumentationUpdater {
* @return {@link File cloned temporary directory} - {@code null} if wrong version is
* used
*/
File updateDocsRepoForSingleProject(File clonedDocumentationProject,
ProjectVersion currentProject, Projects projects);
File updateDocsRepoForSingleProject(File clonedDocumentationProject, ProjectVersion currentProject,
Projects projects);
}

View File

@@ -33,17 +33,13 @@ public class DocumentationUpdater {
private final ReleaseTrainContentsUpdater releaseTrainContentsUpdater;
public DocumentationUpdater(ProjectGitHandler gitHandler,
ReleaserProperties properties, TemplateGenerator templateGenerator,
List<CustomProjectDocumentationUpdater> updaters) {
this.projectDocumentationUpdater = new ProjectDocumentationUpdater(properties,
gitHandler, updaters);
this.releaseTrainContentsUpdater = new ReleaseTrainContentsUpdater(properties,
gitHandler, templateGenerator);
public DocumentationUpdater(ProjectGitHandler gitHandler, ReleaserProperties properties,
TemplateGenerator templateGenerator, List<CustomProjectDocumentationUpdater> updaters) {
this.projectDocumentationUpdater = new ProjectDocumentationUpdater(properties, gitHandler, updaters);
this.releaseTrainContentsUpdater = new ReleaseTrainContentsUpdater(properties, gitHandler, templateGenerator);
}
DocumentationUpdater(ProjectDocumentationUpdater updater,
ReleaseTrainContentsUpdater contentsUpdater) {
DocumentationUpdater(ProjectDocumentationUpdater updater, ReleaseTrainContentsUpdater contentsUpdater) {
this.projectDocumentationUpdater = updater;
this.releaseTrainContentsUpdater = contentsUpdater;
}

View File

@@ -31,8 +31,7 @@ import releaser.internal.project.Projects;
*/
class ProjectDocumentationUpdater {
private static final Logger log = LoggerFactory
.getLogger(ProjectDocumentationUpdater.class);
private static final Logger log = LoggerFactory.getLogger(ProjectDocumentationUpdater.class);
private final ProjectGitHandler gitHandler;
@@ -40,8 +39,7 @@ class ProjectDocumentationUpdater {
private final ReleaserProperties properties;
ProjectDocumentationUpdater(ReleaserProperties properties,
ProjectGitHandler gitHandler,
ProjectDocumentationUpdater(ReleaserProperties properties, ProjectGitHandler gitHandler,
List<CustomProjectDocumentationUpdater> updaters) {
this.gitHandler = gitHandler;
this.properties = properties;
@@ -50,44 +48,38 @@ class ProjectDocumentationUpdater {
// Not needed any more cause all projects publish to docs.spring.io
@Deprecated
public File updateDocsRepo(Projects projects, ProjectVersion currentProject,
String bomBranch) {
public File updateDocsRepo(Projects projects, ProjectVersion currentProject, String bomBranch) {
if (!shouldUpdate(currentProject)) {
return null;
}
File documentationProject = this.gitHandler.cloneDocumentationProject();
log.debug("Cloning the doc project to [{}]", documentationProject);
CustomProjectDocumentationUpdater updater = this.updaters.isEmpty()
? CustomProjectDocumentationUpdater.NO_OP : this.updaters.get(0);
return updater.updateDocsRepoForReleaseTrain(documentationProject, currentProject,
projects, bomBranch);
CustomProjectDocumentationUpdater updater = this.updaters.isEmpty() ? CustomProjectDocumentationUpdater.NO_OP
: this.updaters.get(0);
return updater.updateDocsRepoForReleaseTrain(documentationProject, currentProject, projects, bomBranch);
}
// Not needed any more cause all projects publish to docs.spring.io
@Deprecated
public File updateDocsRepoForSingleProject(Projects projects,
ProjectVersion currentProject) {
public File updateDocsRepoForSingleProject(Projects projects, ProjectVersion currentProject) {
if (!shouldUpdate(currentProject)) {
return null;
}
File documentationProject = this.gitHandler.cloneDocumentationProject();
log.debug("Cloning the doc project to [{}]", documentationProject);
CustomProjectDocumentationUpdater updater = this.updaters.isEmpty()
? CustomProjectDocumentationUpdater.NO_OP : this.updaters.get(0);
return updater.updateDocsRepoForSingleProject(documentationProject,
currentProject, projects);
CustomProjectDocumentationUpdater updater = this.updaters.isEmpty() ? CustomProjectDocumentationUpdater.NO_OP
: this.updaters.get(0);
return updater.updateDocsRepoForSingleProject(documentationProject, currentProject, projects);
}
private boolean shouldUpdate(ProjectVersion currentProject) {
if (!this.properties.getGit().isUpdateDocumentationRepo()) {
log.info(
"Will not update documentation repository, since the switch to do so "
+ "is off. Set [releaser.git.update-documentation-repo] to [true] to change that");
log.info("Will not update documentation repository, since the switch to do so "
+ "is off. Set [releaser.git.update-documentation-repo] to [true] to change that");
return false;
}
if (!currentProject.isReleaseOrServiceRelease()) {
log.info(
"Will not update documentation repository for non release or service release [{}]",
log.info("Will not update documentation repository for non release or service release [{}]",
currentProject.version);
return false;
}

View File

@@ -39,8 +39,7 @@ public class ReleaseTrainContents {
return false;
}
ReleaseTrainContents contents = (ReleaseTrainContents) o;
return Objects.equals(this.title, contents.title)
&& Objects.equals(this.rows, contents.rows);
return Objects.equals(this.title, contents.title) && Objects.equals(this.rows, contents.rows);
}
@Override

View File

@@ -39,8 +39,7 @@ import org.springframework.util.StringUtils;
// TODO: [SPRING-CLOUD]
class ReleaseTrainContentsUpdater {
private static final Logger log = LoggerFactory
.getLogger(ReleaseTrainContentsUpdater.class);
private static final Logger log = LoggerFactory.getLogger(ReleaseTrainContentsUpdater.class);
private final ReleaseTrainContentsGitHandler handler;
@@ -63,45 +62,33 @@ class ReleaseTrainContentsUpdater {
* @param projects - set of project with versions to assert against
*/
File updateReleaseTrainWiki(Projects projects) {
if (!this.properties.getGit().isUpdateReleaseTrainWiki()
|| !this.properties.getMetaRelease().isEnabled()) {
log.info(
"Will not clone and update the release train wiki, since the switch to do so "
+ "is off or it's not a meta-release. Set [releaser.git.update-release-train-wiki] to [true] to change that");
if (!this.properties.getGit().isUpdateReleaseTrainWiki() || !this.properties.getMetaRelease().isEnabled()) {
log.info("Will not clone and update the release train wiki, since the switch to do so "
+ "is off or it's not a meta-release. Set [releaser.git.update-release-train-wiki] to [true] to change that");
return null;
}
File releaseTrainWiki = this.handler.cloneReleaseTrainWiki();
ProjectVersion releaseTrain = projects.releaseTrain(this.properties);
// When using calver this need to be a major plus minor (ie if the release is
// 2020.0.1, the name of the wiki page is 2020.0)
String releaseTrainName = releaseTrain.isCalver() ? releaseTrain.majorAndMinor()
: releaseTrain.major();
String releaseTrainName = releaseTrain.isCalver() ? releaseTrain.majorAndMinor() : releaseTrain.major();
String wikiPagePrefix = this.properties.getGit().getReleaseTrainWikiPagePrefix();
String releaseTrainDocFileName = releaseTrainDocFileName(releaseTrainName,
wikiPagePrefix);
log.info("Reading the file [{}] for the current release train",
releaseTrainDocFileName);
File releaseTrainDocFile = releaseTrainDocFile(releaseTrainWiki,
releaseTrainDocFileName);
String releaseVersionFromCurrentFile = this.parser
.latestReleaseTrainFromWiki(releaseTrainDocFile);
log.info("Latest release train version in the file is [{}]",
releaseVersionFromCurrentFile);
if (!isThisReleaseTrainVersionNewer(releaseTrain,
releaseVersionFromCurrentFile)) {
log.info(
"Current release train version [{}] is not "
+ "newer than the version taken from the wiki [{}]",
String releaseTrainDocFileName = releaseTrainDocFileName(releaseTrainName, wikiPagePrefix);
log.info("Reading the file [{}] for the current release train", releaseTrainDocFileName);
File releaseTrainDocFile = releaseTrainDocFile(releaseTrainWiki, releaseTrainDocFileName);
String releaseVersionFromCurrentFile = this.parser.latestReleaseTrainFromWiki(releaseTrainDocFile);
log.info("Latest release train version in the file is [{}]", releaseVersionFromCurrentFile);
if (!isThisReleaseTrainVersionNewer(releaseTrain, releaseVersionFromCurrentFile)) {
log.info("Current release train version [{}] is not " + "newer than the version taken from the wiki [{}]",
releaseTrain.version, releaseVersionFromCurrentFile);
return releaseTrainWiki;
}
return generateNewWikiEntry(projects, releaseTrainWiki, releaseTrain,
releaseTrainName, releaseTrainDocFile, releaseVersionFromCurrentFile);
return generateNewWikiEntry(projects, releaseTrainWiki, releaseTrain, releaseTrainName, releaseTrainDocFile,
releaseVersionFromCurrentFile);
}
private File generateNewWikiEntry(Projects projects, File releaseTrainWiki,
ProjectVersion releaseTrain, String releaseTrainName,
File releaseTrainDocFile, String releaseVersionFromCurrentFile) {
private File generateNewWikiEntry(Projects projects, File releaseTrainWiki, ProjectVersion releaseTrain,
String releaseTrainName, File releaseTrainDocFile, String releaseVersionFromCurrentFile) {
File releaseNotes = this.templateGenerator.releaseNotes(projects);
try {
List<String> lines = Files.readAllLines(releaseTrainDocFile.toPath());
@@ -111,53 +98,43 @@ class ReleaseTrainContentsUpdater {
break;
}
}
return insertNewWikiContentBeforeTheLatestRelease(releaseTrainWiki,
releaseTrain, releaseTrainName, releaseTrainDocFile, releaseNotes,
lines, lineIndex);
return insertNewWikiContentBeforeTheLatestRelease(releaseTrainWiki, releaseTrain, releaseTrainName,
releaseTrainDocFile, releaseNotes, lines, lineIndex);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
private File insertNewWikiContentBeforeTheLatestRelease(File releaseTrainWiki,
ProjectVersion releaseTrain, String releaseTrainName,
File releaseTrainDocFile, File releaseNotes, List<String> lines,
int lineIndex) throws IOException {
String newContent = new StringJoiner("\n")
.add(String.join("\n", lines.subList(0, lineIndex))).add("\n")
private File insertNewWikiContentBeforeTheLatestRelease(File releaseTrainWiki, ProjectVersion releaseTrain,
String releaseTrainName, File releaseTrainDocFile, File releaseNotes, List<String> lines, int lineIndex)
throws IOException {
String newContent = new StringJoiner("\n").add(String.join("\n", lines.subList(0, lineIndex))).add("\n")
.add(new String(Files.readAllBytes(releaseNotes.toPath())))
.add(String.join("\n", lines.subList(lineIndex, lines.size())))
.toString();
.add(String.join("\n", lines.subList(lineIndex, lines.size()))).toString();
Files.write(releaseTrainDocFile.toPath(), newContent.getBytes());
log.info("Successfully stored new wiki contents for release train [{}]",
releaseTrainName);
log.info("Successfully stored new wiki contents for release train [{}]", releaseTrainName);
this.handler.commitAndPushChanges(releaseTrainWiki, releaseTrain);
return releaseTrainWiki;
}
private String releaseTrainDocFileName(String releaseTrainName,
String wikiPagePrefix) {
return new StringJoiner("-").add(wikiPagePrefix).add(releaseTrainName)
.add("Release-Notes.md").toString();
private String releaseTrainDocFileName(String releaseTrainName, String wikiPagePrefix) {
return new StringJoiner("-").add(wikiPagePrefix).add(releaseTrainName).add("Release-Notes.md").toString();
}
private boolean isThisReleaseTrainVersionNewer(ProjectVersion releaseTrain,
String releaseVersionFromCurrentFile) {
private boolean isThisReleaseTrainVersionNewer(ProjectVersion releaseTrain, String releaseVersionFromCurrentFile) {
if (StringUtils.hasText(releaseVersionFromCurrentFile)) {
return releaseTrain.compareToReleaseTrain(releaseVersionFromCurrentFile) > 0;
}
return true;
}
private File releaseTrainDocFile(File releaseTrainWiki,
String releaseTrainDocFileName) {
private File releaseTrainDocFile(File releaseTrainWiki, String releaseTrainDocFileName) {
File releaseTrainDocFile = new File(releaseTrainWiki, releaseTrainDocFileName);
if (!releaseTrainDocFile.exists()) {
try {
if (!releaseTrainDocFile.createNewFile()) {
throw new IllegalStateException(
"Failed to create releae train doc file");
throw new IllegalStateException("Failed to create releae train doc file");
}
}
catch (IOException e) {
@@ -171,8 +148,7 @@ class ReleaseTrainContentsUpdater {
class ReleaseTrainContentsGitHandler {
private static final Logger log = LoggerFactory
.getLogger(ReleaseTrainContentsGitHandler.class);
private static final Logger log = LoggerFactory.getLogger(ReleaseTrainContentsGitHandler.class);
private static final String PROJECT_PAGE_UPDATED_COMMIT_MSG = "Updating project page to release train [%s]";
@@ -188,8 +164,7 @@ class ReleaseTrainContentsGitHandler {
void commitAndPushChanges(File repo, ProjectVersion releaseTrain) {
log.debug("Committing and pushing changes");
this.handler.commit(repo,
String.format(PROJECT_PAGE_UPDATED_COMMIT_MSG, releaseTrain.version));
this.handler.commit(repo, String.format(PROJECT_PAGE_UPDATED_COMMIT_MSG, releaseTrain.version));
this.handler.pushCurrentBranch(repo);
}
@@ -197,8 +172,7 @@ class ReleaseTrainContentsGitHandler {
class ReleaseTrainContentsParser {
private static final Logger log = LoggerFactory
.getLogger(ReleaseTrainContentsParser.class);
private static final Logger log = LoggerFactory.getLogger(ReleaseTrainContentsParser.class);
ReleaseTrainContents parseProjectPage(File rawHtml) {
try {
@@ -230,9 +204,8 @@ class ReleaseTrainContentsParser {
return Files.readAllLines(rawMd.toPath()).stream()
// We want to find only headers like # Finchley.RELEASE and not any
// custom headers
.filter(s -> s.trim().startsWith("#") && s.contains("."))
.map(s -> s.substring(1).trim()).filter(ProjectVersion::isValid)
.findFirst().orElse("");
.filter(s -> s.trim().startsWith("#") && s.contains(".")).map(s -> s.substring(1).trim())
.filter(ProjectVersion::isValid).findFirst().orElse("");
}
catch (IOException e) {
throw new IllegalStateException(e);

View File

@@ -45,8 +45,7 @@ public class Row {
this.currentSnapshotVersion = row[initialIndex + 3].trim();
}
Row(String componentName, String lastGaVersion, String currentGaVersion,
String currentSnapshotVersion) {
Row(String componentName, String lastGaVersion, String currentGaVersion, String currentSnapshotVersion) {
this.componentName = componentName.trim();
this.lastGaVersion = lastGaVersion.trim();
this.currentGaVersion = currentGaVersion.trim();
@@ -56,8 +55,7 @@ public class Row {
static List<Row> fromProjects(Projects projects, boolean lastGa) {
return projects.stream()
.map(v -> new Row(v.projectName, lastGa ? versionOrEmptyForGa(v) : "",
!lastGa ? versionOrEmptyForGa(v) : "",
v.isSnapshot() ? v.version : ""))
!lastGa ? versionOrEmptyForGa(v) : "", v.isSnapshot() ? v.version : ""))
.collect(Collectors.toCollection(LinkedList::new));
}
@@ -76,14 +74,13 @@ public class Row {
Row row = (Row) o;
return Objects.equals(this.componentName, row.componentName)
&& Objects.equals(this.lastGaVersion, row.lastGaVersion)
&& Objects.equals(this.currentGaVersion, row.currentGaVersion) && Objects
.equals(this.currentSnapshotVersion, row.currentSnapshotVersion);
&& Objects.equals(this.currentGaVersion, row.currentGaVersion)
&& Objects.equals(this.currentSnapshotVersion, row.currentSnapshotVersion);
}
@Override
public int hashCode() {
return Objects.hash(this.componentName, this.lastGaVersion, this.currentGaVersion,
this.currentSnapshotVersion);
return Objects.hash(this.componentName, this.lastGaVersion, this.currentGaVersion, this.currentSnapshotVersion);
}
public String getComponentName() {

View File

@@ -36,8 +36,7 @@ public class Title {
this.currentSnapshotTrainName = row[initialIndex + 2].trim();
}
Title(String lastGaTrainName, String currentGaTrainName,
String currentSnapshotTrainName) {
Title(String lastGaTrainName, String currentGaTrainName, String currentSnapshotTrainName) {
this.lastGaTrainName = lastGaTrainName.trim();
this.currentGaTrainName = currentGaTrainName.trim();
this.currentSnapshotTrainName = currentSnapshotTrainName.trim();
@@ -54,14 +53,12 @@ public class Title {
Title title = (Title) o;
return Objects.equals(this.lastGaTrainName, title.lastGaTrainName)
&& Objects.equals(this.currentGaTrainName, title.currentGaTrainName)
&& Objects.equals(this.currentSnapshotTrainName,
title.currentSnapshotTrainName);
&& Objects.equals(this.currentSnapshotTrainName, title.currentSnapshotTrainName);
}
@Override
public int hashCode() {
return Objects.hash(this.lastGaTrainName, this.currentGaTrainName,
this.currentSnapshotTrainName);
return Objects.hash(this.lastGaTrainName, this.currentGaTrainName, this.currentSnapshotTrainName);
}
public String getLastGaTrainName() {

View File

@@ -109,8 +109,7 @@ class GitRepo {
*/
File cloneProject(URIish projectUri) {
try {
log.info("Cloning repo from [{}] to [{}]", projectUri,
humanishDestination(projectUri, this.basedir));
log.info("Cloning repo from [{}] to [{}]", projectUri, humanishDestination(projectUri, this.basedir));
Git git = cloneToBasedir(projectUri, this.basedir);
if (git != null) {
git.close();
@@ -190,9 +189,8 @@ class GitRepo {
*/
Optional<ObjectId> findTagIdByName(String tagName, boolean unpeel) {
try (Git git = this.gitFactory.open(file(this.basedir))) {
return git.tagList().call().stream()
.filter(ref -> ref.getName().equals("refs/tags/" + tagName))
.findFirst().map(ref -> {
return git.tagList().call().stream().filter(ref -> ref.getName().equals("refs/tags/" + tagName)).findFirst()
.map(ref -> {
if (ref.isPeeled() && unpeel) {
return ref.getPeeledObjectId();
}
@@ -200,8 +198,7 @@ class GitRepo {
});
}
catch (Exception e) {
throw new IllegalStateException(
"Unable to fetch git tag id for refs/tags/" + tagName, e);
throw new IllegalStateException("Unable to fetch git tag id for refs/tags/" + tagName, e);
}
}
@@ -212,8 +209,7 @@ class GitRepo {
*/
List<RevCommit> log(String from, String to) {
try (Git git = this.gitFactory.open(file(this.basedir))) {
final Optional<Ref> fromRevisionOptional = findTagOrBranchHeadRevision(git,
from);
final Optional<Ref> fromRevisionOptional = findTagOrBranchHeadRevision(git, from);
final Optional<Ref> toRevisionOptional = findTagOrBranchHeadRevision(git, to);
ObjectId fromRevision;
@@ -249,8 +245,7 @@ class GitRepo {
return commits;
}
catch (Exception e) {
throw new IllegalStateException(
"Unable to fetch git log for " + from + ".." + to, e);
throw new IllegalStateException("Unable to fetch git log for " + from + ".." + to, e);
}
}
@@ -279,8 +274,7 @@ class GitRepo {
}
return d2.compareTo(d1); // more recent first
});
return allTagsNewestFirst.stream()
.map(ref -> Repository.shortenRefName(ref.getName()));
return allTagsNewestFirst.stream().map(ref -> Repository.shortenRefName(ref.getName()));
}
catch (Exception e) {
throw new IllegalStateException("Unable to fetch git tags", e);
@@ -290,29 +284,24 @@ class GitRepo {
/**
* Look for a tag with the given name, and if not found looks for a branch.
*/
private Optional<Ref> findTagOrBranchHeadRevision(Git git, String tagOrBranch)
throws GitAPIException, IOException {
private Optional<Ref> findTagOrBranchHeadRevision(Git git, String tagOrBranch) throws GitAPIException, IOException {
if (tagOrBranch.equals("HEAD")) {
return Optional.of(git.getRepository().exactRef(Constants.HEAD).getTarget());
}
final Optional<Ref> tag = git.tagList().call().stream()
.filter(ref -> ref.getName().equals("refs/tags/" + tagOrBranch))
.findFirst();
.filter(ref -> ref.getName().equals("refs/tags/" + tagOrBranch)).findFirst();
if (tag.isPresent()) {
return tag;
}
return git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call()
.stream().filter(ref -> ref.getName().equals("refs/heads/" + tagOrBranch))
.findFirst();
return git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call().stream()
.filter(ref -> ref.getName().equals("refs/heads/" + tagOrBranch)).findFirst();
}
boolean hasBranch(String branch) {
try (Git git = this.gitFactory.open(file(this.basedir))) {
List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL)
.call();
boolean present = refs.stream()
.anyMatch(ref -> branch.equals(nameOfBranch(ref.getName())));
List<Ref> refs = git.branchList().setListMode(ListBranchCommand.ListMode.ALL).call();
boolean present = refs.stream().anyMatch(ref -> branch.equals(nameOfBranch(ref.getName())));
if (log.isDebugEnabled()) {
log.debug("Branch [{}] is present [{}]", branch, present);
}
@@ -335,8 +324,7 @@ class GitRepo {
log.info("Printing [{}] last commits for branch [{}]", maxCount, currentBranch);
Iterable<RevCommit> commits = git.log().setMaxCount(maxCount).call();
for (RevCommit commit : commits) {
log.info("Name [{}], msg [{}]", commit.getId().name(),
commit.getShortMessage());
log.info("Name [{}], msg [{}]", commit.getId().name(), commit.getShortMessage());
}
}
@@ -402,9 +390,8 @@ class GitRepo {
String id = commit.getId().getName();
if (!shortMessage.contains("Update SNAPSHOT to ")) {
throw new IllegalStateException(
"Won't revert the commit with id [" + id + "] " + "and message ["
+ shortMessage + "]. Only commit that updated "
+ "snapshot to another version can be reverted");
"Won't revert the commit with id [" + id + "] " + "and message [" + shortMessage
+ "]. Only commit that updated " + "snapshot to another version can be reverted");
}
log.debug("The commit to be reverted is [{}]", commit);
git.revert().include(commit).call();
@@ -429,10 +416,8 @@ class GitRepo {
return ResourceUtils.getFile(project.toURI()).getAbsoluteFile();
}
private Git cloneToBasedir(URIish projectUrl, File destinationFolder)
throws GitAPIException {
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository()
.setURI(projectUrl.toString() + ".git")
private Git cloneToBasedir(URIish projectUrl, File destinationFolder) throws GitAPIException {
CloneCommand command = this.gitFactory.getCloneCommandByCloneRepository().setURI(projectUrl.toString() + ".git")
.setDirectory(humanishDestination(projectUrl, destinationFolder));
try {
return command.call();
@@ -500,8 +485,7 @@ class GitRepo {
}
private void trackBranch(CheckoutCommand checkout, String label) {
checkout.setCreateBranch(true).setName(label)
.setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
checkout.setCreateBranch(true).setName(label).setUpstreamMode(CreateBranchCommand.SetupUpstreamMode.TRACK)
.setStartPoint("origin/" + label);
}
@@ -513,8 +497,7 @@ class GitRepo {
return containsBranch(git, label, null);
}
private boolean containsBranch(Git git, String label,
ListBranchCommand.ListMode listMode) throws GitAPIException {
private boolean containsBranch(Git git, String label, ListBranchCommand.ListMode listMode) throws GitAPIException {
ListBranchCommand command = git.branchList();
if (listMode != null) {
command.setListMode(listMode);
@@ -564,17 +547,14 @@ class GitRepo {
log.info("Successfully connected to an agent");
}
catch (AgentProxyException e) {
log.error(
"Exception occurred while trying to connect to agent. Will create"
+ "the default JSch connection",
e);
log.error("Exception occurred while trying to connect to agent. Will create"
+ "the default JSch connection", e);
return super.createDefaultJSch(fs);
}
final JSch jsch = super.createDefaultJSch(fs);
if (connector != null) {
JSch.setConfig("PreferredAuthentications", "publickey,password");
IdentityRepository identityRepository = new RemoteIdentityRepository(
connector);
IdentityRepository identityRepository = new RemoteIdentityRepository(connector);
jsch.setIdentityRepository(identityRepository);
}
return jsch;
@@ -592,8 +572,7 @@ class GitRepo {
JGitFactory(ReleaserProperties releaserProperties) {
if (StringUtils.hasText(releaserProperties.getGit().getUsername())) {
log.info(
"Passed username and password - will set a custom credentials provider");
log.info("Passed username and password - will set a custom credentials provider");
this.provider = credentialsProvider(releaserProperties);
}
else {
@@ -608,8 +587,8 @@ class GitRepo {
}
CredentialsProvider credentialsProvider(ReleaserProperties properties) {
return new UsernamePasswordCredentialsProvider(
properties.getGit().getUsername(), properties.getGit().getPassword());
return new UsernamePasswordCredentialsProvider(properties.getGit().getUsername(),
properties.getGit().getPassword());
}
CloneCommand getCloneCommandByCloneRepository() {
@@ -618,8 +597,7 @@ class GitRepo {
}
PushCommand push(Git git) {
return git.push().setCredentialsProvider(this.provider)
.setTransportConfigCallback(this.callback);
return git.push().setCredentialsProvider(this.provider).setTransportConfigCallback(this.callback);
}
Git open(File file) {

View File

@@ -70,13 +70,11 @@ public class ProjectGitHandler implements Closeable {
public void commitAndTagIfApplicable(File project, ProjectVersion version) {
GitRepo gitRepo = gitRepo(project);
if (version.isSnapshot()) {
log.info("Snapshot version [{}] found. Will only commit the changed poms",
version);
log.info("Snapshot version [{}] found. Will only commit the changed poms", version);
gitRepo.commit(MSG);
}
else {
log.info(
"NON-snapshot version [{}] found. Will commit the changed poms, tag the version and push the tag",
log.info("NON-snapshot version [{}] found. Will commit the changed poms, tag the version and push the tag",
version);
gitRepo.commit(String.format(PRE_RELEASE_MSG, version.version));
String tagName = "v" + version.version;
@@ -87,8 +85,7 @@ public class ProjectGitHandler implements Closeable {
public void commitAfterBumpingVersions(File project, ProjectVersion bumpedVersion) {
if (bumpedVersion.isSnapshot()) {
log.info("Snapshot version [{}] found. Will only commit the changed poms",
bumpedVersion);
log.info("Snapshot version [{}] found. Will only commit the changed poms", bumpedVersion);
commit(project, String.format(POST_RELEASE_BUMP_MSG, bumpedVersion));
}
else {
@@ -120,8 +117,7 @@ public class ProjectGitHandler implements Closeable {
}
public File cloneReleaseTrainDocumentationProject(String branch) {
return cloneAndCheckOut(this.properties.getGit().getReleaseTrainDocsUrl(),
branch);
return cloneAndCheckOut(this.properties.getGit().getReleaseTrainDocsUrl(), branch);
}
public File cloneDocumentationProject() {
@@ -134,8 +130,7 @@ public class ProjectGitHandler implements Closeable {
this.properties.getGit().getSpringProjectBranch());
}
private File cloneAndCheckOut(String springProjectUrl,
String springProjectUrlBranch) {
private File cloneAndCheckOut(String springProjectUrl, String springProjectUrlBranch) {
File clonedProject = cloneProject(springProjectUrl);
checkout(clonedProject, springProjectUrlBranch);
return clonedProject;
@@ -160,8 +155,7 @@ public class ProjectGitHandler implements Closeable {
String releaseTrainBranch = this.properties.getGit().getReleaseTrainBranch();
if (!StringUtils.isEmpty(releaseTrainBranch)) {
if (log.isDebugEnabled()) {
log.debug("Checking out configured release train branch {}",
releaseTrainBranch);
log.debug("Checking out configured release train branch {}", releaseTrainBranch);
}
if (gitRepo(clonedProject).hasBranch(releaseTrainBranch)) {
log.info("Branch [{}] exists. Will check it out", releaseTrainBranch);
@@ -171,8 +165,7 @@ public class ProjectGitHandler implements Closeable {
}
String version = this.properties.getFixedVersions().get(projectName);
if (StringUtils.isEmpty(version)) {
throw new IllegalStateException(
"You haven't provided a version for project [" + projectName + "]");
throw new IllegalStateException("You haven't provided a version for project [" + projectName + "]");
}
return findAndCheckOutBranchForVersion(clonedProject, new String[] { version });
}
@@ -200,11 +193,10 @@ public class ProjectGitHandler implements Closeable {
log.debug("Checking versions {} for project [{}]", versions, clonedProject);
}
String branchToCheckout = Arrays.stream(versions).map(this::branchFromVersion)
.map(version -> gitRepo(clonedProject).hasBranch(version) ? version : "")
.filter(StringUtils::hasText).findFirst().orElse("main");
.map(version -> gitRepo(clonedProject).hasBranch(version) ? version : "").filter(StringUtils::hasText)
.findFirst().orElse("main");
if ("main".equals(branchToCheckout)) {
log.info(
"None of the versions {} matches a branch. Assuming that should work with main branch",
log.info("None of the versions {} matches a branch. Assuming that should work with main branch",
(Object) versions);
return clonedProject;
}
@@ -221,10 +213,8 @@ public class ProjectGitHandler implements Closeable {
* @param toRef the ref to go to (tag, branch or sha1)
* @return the list of revisions between these two references
*/
public List<SimpleCommit> commitsBetween(File clonedProject, String fromRef,
String toRef) {
return gitRepo(clonedProject).log(fromRef, toRef).stream().map(SimpleCommit::new)
.collect(Collectors.toList());
public List<SimpleCommit> commitsBetween(File clonedProject, String fromRef, String toRef) {
return gitRepo(clonedProject).log(fromRef, toRef).stream().map(SimpleCommit::new).collect(Collectors.toList());
}
/**
@@ -234,8 +224,7 @@ public class ProjectGitHandler implements Closeable {
* @return an {@link Optional} that is valued with the sha1, if found
*/
public Optional<String> findTagSha1(File clonedProject, String tagName) {
return gitRepo(clonedProject).findTagIdByName(tagName, false)
.map(AnyObjectId::getName);
return gitRepo(clonedProject).findTagIdByName(tagName, false).map(AnyObjectId::getName);
}
private String suffixNonHttpRepo(String orgUrl) {
@@ -248,8 +237,7 @@ public class ProjectGitHandler implements Closeable {
// retrieve from cache
// reset any changes and fetch the latest data
File destinationDir = destinationDir();
File clonedProject = CACHE.computeIfAbsent(urIish,
urIish1 -> gitRepo(destinationDir).cloneProject(urIish));
File clonedProject = CACHE.computeIfAbsent(urIish, urIish1 -> gitRepo(destinationDir).cloneProject(urIish));
if (clonedProject.exists()) {
log.info(
"Project has already been cloned. Will try to reset the current branch and fetch the latest changes.");
@@ -309,8 +297,7 @@ public class ProjectGitHandler implements Closeable {
// [Camden] -> [Camden.x]
return splitVersion[0];
}
throw new IllegalStateException(
"Wrong version [" + version + "]. Can't extract semver pieces of it");
throw new IllegalStateException("Wrong version [" + version + "]. Can't extract semver pieces of it");
}
@@ -347,8 +334,7 @@ public class ProjectGitHandler implements Closeable {
* @return a {@link Stream} of the tags whose name match the given {@link Pattern}
*/
public Stream<String> findTagNamesMatching(File clonedProject, Pattern tagPattern) {
return gitRepo(clonedProject).listTags()
.filter(tagName -> tagPattern.matcher(tagName).matches());
return gitRepo(clonedProject).listTags().filter(tagName -> tagPattern.matcher(tagName).matches());
}
}

View File

@@ -71,12 +71,9 @@ public class SimpleCommit {
public final boolean isMergeCommit;
SimpleCommit(RevCommit revCommit) {
this(revCommit.abbreviate(8).name(), revCommit.name(),
revCommit.getShortMessage(), revCommit.getFullMessage(),
revCommit.getAuthorIdent().getName(),
revCommit.getAuthorIdent().getEmailAddress(),
revCommit.getCommitterIdent().getName(),
revCommit.getCommitterIdent().getEmailAddress(),
this(revCommit.abbreviate(8).name(), revCommit.name(), revCommit.getShortMessage(), revCommit.getFullMessage(),
revCommit.getAuthorIdent().getName(), revCommit.getAuthorIdent().getEmailAddress(),
revCommit.getCommitterIdent().getName(), revCommit.getCommitterIdent().getEmailAddress(),
revCommit.getParentCount() > 1);
}
@@ -92,9 +89,8 @@ public class SimpleCommit {
* @param committerEmail the email of the commit's committer
* @param isMergeCommit is the commit a merge commit (with 2 parents)
*/
public SimpleCommit(String abbreviatedSha1, String fullSha1, String title,
String fullMessage, String authorName, String authorEmail,
String committerName, String committerEmail, boolean isMergeCommit) {
public SimpleCommit(String abbreviatedSha1, String fullSha1, String title, String fullMessage, String authorName,
String authorEmail, String committerName, String committerEmail, boolean isMergeCommit) {
this.abbreviatedSha1 = abbreviatedSha1;
this.fullSha1 = fullSha1;
this.title = title;

View File

@@ -167,8 +167,7 @@ class CachingRepos implements Repos, Closeable {
@Override
public Repo get(Coordinates coordinates) {
return CACHE.computeIfAbsent(coordinates,
o -> new CachingRepo(this.delegate.get(coordinates)));
return CACHE.computeIfAbsent(coordinates, o -> new CachingRepo(this.delegate.get(coordinates)));
}
@Override
@@ -216,47 +215,40 @@ class CachingRepo implements Repo, Closeable {
@Override
public Coordinates coordinates() {
return (Coordinates) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "coordinates"),
return (Coordinates) CACHE.computeIfAbsent(new RepoKey(this.delegate, "coordinates"),
s -> this.delegate.coordinates());
}
@Override
public Issues issues() {
return (Issues) CACHE.computeIfAbsent(new RepoKey(this.delegate, "issues"),
s -> this.delegate.issues());
return (Issues) CACHE.computeIfAbsent(new RepoKey(this.delegate, "issues"), s -> this.delegate.issues());
}
@Override
public Milestones milestones() {
return (Milestones) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "milestones"),
return (Milestones) CACHE.computeIfAbsent(new RepoKey(this.delegate, "milestones"),
s -> this.delegate.milestones());
}
@Override
public Pulls pulls() {
return (Pulls) CACHE.computeIfAbsent(new RepoKey(this.delegate, "pulls"),
s -> this.delegate.pulls());
return (Pulls) CACHE.computeIfAbsent(new RepoKey(this.delegate, "pulls"), s -> this.delegate.pulls());
}
@Override
public Hooks hooks() {
return (Hooks) CACHE.computeIfAbsent(new RepoKey(this.delegate, "hooks"),
s -> this.delegate.hooks());
return (Hooks) CACHE.computeIfAbsent(new RepoKey(this.delegate, "hooks"), s -> this.delegate.hooks());
}
@Override
public IssueEvents issueEvents() {
return (IssueEvents) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "issueEvents"),
return (IssueEvents) CACHE.computeIfAbsent(new RepoKey(this.delegate, "issueEvents"),
s -> this.delegate.issueEvents());
}
@Override
public Labels labels() {
return (Labels) CACHE.computeIfAbsent(new RepoKey(this.delegate, "labels"),
s -> this.delegate.labels());
return (Labels) CACHE.computeIfAbsent(new RepoKey(this.delegate, "labels"), s -> this.delegate.labels());
}
@Override
@@ -267,63 +259,54 @@ class CachingRepo implements Repo, Closeable {
@Override
public Releases releases() {
return (Releases) CACHE.computeIfAbsent(new RepoKey(this.delegate, "releases"),
s -> this.delegate.releases());
return (Releases) CACHE.computeIfAbsent(new RepoKey(this.delegate, "releases"), s -> this.delegate.releases());
}
@Override
public DeployKeys keys() {
return (DeployKeys) CACHE.computeIfAbsent(new RepoKey(this.delegate, "keys"),
s -> this.delegate.keys());
return (DeployKeys) CACHE.computeIfAbsent(new RepoKey(this.delegate, "keys"), s -> this.delegate.keys());
}
@Override
public Forks forks() {
return (Forks) CACHE.computeIfAbsent(new RepoKey(this.delegate, "forks"),
s -> this.delegate.forks());
return (Forks) CACHE.computeIfAbsent(new RepoKey(this.delegate, "forks"), s -> this.delegate.forks());
}
@Override
public RepoCommits commits() {
return (RepoCommits) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "repoCommits"), s -> this.delegate.commits());
return (RepoCommits) CACHE.computeIfAbsent(new RepoKey(this.delegate, "repoCommits"),
s -> this.delegate.commits());
}
@Override
public Branches branches() {
return (Branches) CACHE.computeIfAbsent(new RepoKey(this.delegate, "branches"),
s -> this.delegate.branches());
return (Branches) CACHE.computeIfAbsent(new RepoKey(this.delegate, "branches"), s -> this.delegate.branches());
}
@Override
public Contents contents() {
return (Contents) CACHE.computeIfAbsent(new RepoKey(this.delegate, "contents"),
s -> this.delegate.contents());
return (Contents) CACHE.computeIfAbsent(new RepoKey(this.delegate, "contents"), s -> this.delegate.contents());
}
@Override
public Collaborators collaborators() {
return (Collaborators) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "collaborators"),
return (Collaborators) CACHE.computeIfAbsent(new RepoKey(this.delegate, "collaborators"),
s -> this.delegate.collaborators());
}
@Override
public Git git() {
return (Git) CACHE.computeIfAbsent(new RepoKey(this.delegate, "git"),
s -> this.delegate.git());
return (Git) CACHE.computeIfAbsent(new RepoKey(this.delegate, "git"), s -> this.delegate.git());
}
@Override
public Stars stars() {
return (Stars) CACHE.computeIfAbsent(new RepoKey(this.delegate, "stars"),
s -> this.delegate.stars());
return (Stars) CACHE.computeIfAbsent(new RepoKey(this.delegate, "stars"), s -> this.delegate.stars());
}
@Override
public Notifications notifications() {
return (Notifications) CACHE.computeIfAbsent(
new RepoKey(this.delegate, "notifications"),
return (Notifications) CACHE.computeIfAbsent(new RepoKey(this.delegate, "notifications"),
s -> this.delegate.notifications());
}
@@ -334,15 +317,14 @@ class CachingRepo implements Repo, Closeable {
@Override
public JsonObject json() throws IOException {
return (JsonObject) CACHE.computeIfAbsent(new RepoKey(this.delegate, "json"),
s -> {
try {
return this.delegate.json();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
});
return (JsonObject) CACHE.computeIfAbsent(new RepoKey(this.delegate, "json"), s -> {
try {
return this.delegate.json();
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
});
}
@Override
@@ -382,8 +364,7 @@ class RepoKey {
return false;
}
RepoKey repoKey = (RepoKey) o;
return Objects.equals(this.repo, repoKey.repo)
&& Objects.equals(this.key, repoKey.key);
return Objects.equals(this.repo, repoKey.repo) && Objects.equals(this.key, repoKey.key);
}
@Override

View File

@@ -47,8 +47,8 @@ public class GithubIssueFiler {
private final ReleaserProperties properties;
public GithubIssueFiler(ReleaserProperties properties) {
this(new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry()
.through(RetryWire.class)), properties);
this(new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry().through(RetryWire.class)),
properties);
}
public GithubIssueFiler(Github github, ReleaserProperties properties) {
@@ -56,22 +56,20 @@ public class GithubIssueFiler {
this.properties = properties;
}
public void fileAGitHubIssue(String user, String repo, ProjectVersion version,
String issueTitle, String issueText) {
public void fileAGitHubIssue(String user, String repo, ProjectVersion version, String issueTitle,
String issueText) {
Assert.hasText(this.properties.getGit().getOauthToken(),
"You have to pass Github OAuth token for milestone closing to be operational");
// do this only for RELEASE & SR
if (version.isSnapshot()) {
log.info(
"Github issue creation will occur only for non snapshot versions. Your version is [{}]",
log.info("Github issue creation will occur only for non snapshot versions. Your version is [{}]",
parsedVersion());
return;
}
fileAGithubIssue(user, repo, issueTitle, issueText);
}
private void fileAGithubIssue(String user, String repo, String issueTitle,
String issueText) {
private void fileAGithubIssue(String user, String repo, String issueTitle, String issueText) {
Repo ghRepo = this.github.repos().get(new Coordinates.Simple(user, repo));
// check if the issue is not already there
boolean issueAlreadyFiled = issueAlreadyFiled(ghRepo, issueTitle);
@@ -81,9 +79,7 @@ public class GithubIssueFiler {
}
try {
int number = ghRepo.issues().create(issueTitle, issueText).number();
log.info(
"Successfully created an issue with "
+ "title [{}] for the [{}/{}] GitHub repository" + number,
log.info("Successfully created an issue with " + "title [{}] for the [{}/{}] GitHub repository" + number,
issueTitle, user, repo);
}
catch (IOException e) {

View File

@@ -33,8 +33,7 @@ class GithubIssues {
}
private CustomGithubIssues customGithubIssues() {
return this.customGithubIssues.isEmpty() ? CustomGithubIssues.NO_OP
: this.customGithubIssues.get(0);
return this.customGithubIssues.isEmpty() ? CustomGithubIssues.NO_OP : this.customGithubIssues.get(0);
}
void fileIssueInSpringGuides(Projects projects, ProjectVersion version) {

View File

@@ -51,8 +51,8 @@ class GithubMilestones {
private final ReleaserProperties properties;
GithubMilestones(ReleaserProperties properties) {
this(new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry()
.through(RetryWire.class)), properties);
this(new RtGithub(new RtGithub(properties.getGit().getOauthToken()).entry().through(RetryWire.class)),
properties);
}
GithubMilestones(Github github, ReleaserProperties properties) {
@@ -95,8 +95,7 @@ class GithubMilestones {
try {
int counter = 0;
for (Milestone milestone : milestones) {
if (counter++ >= this.properties.getGit()
.getNumberOfCheckedMilestones()) {
if (counter++ >= this.properties.getGit().getNumberOfCheckedMilestones()) {
log.warn(
"No matching milestones were found within the provided threshold [{}] of checked milestones",
this.properties.getGit().getNumberOfCheckedMilestones());
@@ -104,8 +103,7 @@ class GithubMilestones {
}
Milestone.Smart smartMilestone = new Milestone.Smart(milestone);
String title = milestoneTitle(smartMilestone);
if (tagVersion.equals(title)
|| numericVersion(tagVersion).equals(title)) {
if (tagVersion.equals(title) || numericVersion(tagVersion).equals(title)) {
log.info("Found a matching milestone [{}]", smartMilestone.number());
return smartMilestone;
}
@@ -127,15 +125,13 @@ class GithubMilestones {
Assert.hasText(this.properties.getGit().getOauthToken(),
"You have to pass Github OAuth token for milestone closing to be operational");
String tagVersion = version.version;
Milestone.Smart foundMilestone = matchingMilestone(tagVersion,
closedMilestones(version));
Milestone.Smart foundMilestone = matchingMilestone(tagVersion, closedMilestones(version));
String foundUrl = "";
if (foundMilestone != null) {
try {
URL url = foundMilestoneUrl(foundMilestone);
log.info("Found a matching milestone with issues URL [{}]", url);
foundUrl = url.toString()
.replace("https://api.github.com/repos", "https://github.com")
foundUrl = url.toString().replace("https://api.github.com/repos", "https://github.com")
.replace("milestones", "milestone") + "?closed=1";
}
catch (IOException e) {
@@ -150,8 +146,7 @@ class GithubMilestones {
}
private String numericVersion(String version) {
return version.contains("RELEASE")
? version.substring(0, version.lastIndexOf(".")) : "";
return version.contains("RELEASE") ? version.substring(0, version.lastIndexOf(".")) : "";
}
String milestoneTitle(Milestone.Smart milestone) throws IOException {
@@ -162,11 +157,9 @@ class GithubMilestones {
return milestone.url();
}
private Iterable<Milestone> getMilestones(ProjectVersion version,
Map<String, String> map) {
private Iterable<Milestone> getMilestones(ProjectVersion version, Map<String, String> map) {
try {
return this.github.repos()
.get(new Coordinates.Simple(org(), version.projectName)).milestones()
return this.github.repos().get(new Coordinates.Simple(org(), version.projectName)).milestones()
.iterate(map);
}
catch (AssertionError e) {

View File

@@ -40,8 +40,7 @@ public class ProjectGitHubHandler {
private final ReleaserProperties properties;
public ProjectGitHubHandler(ReleaserProperties properties,
List<CustomGithubIssues> customGithubIssues) {
public ProjectGitHubHandler(ReleaserProperties properties, List<CustomGithubIssues> customGithubIssues) {
this.properties = properties;
this.githubMilestones = new GithubMilestones(properties);
this.githubIssues = new GithubIssues(customGithubIssues);
@@ -54,9 +53,8 @@ public class ProjectGitHubHandler {
public void closeMilestone(ProjectVersion releaseVersion) {
if (!this.properties.getGit().isUpdateGithubMilestones()) {
log.info(
"Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-github-milestones] to [true] to change that");
log.info("Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-github-milestones] to [true] to change that");
return;
}
this.githubMilestones.closeMilestone(releaseVersion);
@@ -64,9 +62,8 @@ public class ProjectGitHubHandler {
public void createIssueInSpringGuides(Projects projects, ProjectVersion version) {
if (!this.properties.getGit().isUpdateSpringGuides()) {
log.info(
"Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-spring-guides] to [true] to change that");
log.info("Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-spring-guides] to [true] to change that");
return;
}
this.githubIssues.fileIssueInSpringGuides(projects, version);
@@ -74,9 +71,8 @@ public class ProjectGitHubHandler {
public void createIssueInStartSpringIo(Projects projects, ProjectVersion version) {
if (!this.properties.getGit().isUpdateStartSpringIo()) {
log.info(
"Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-start-spring-io] to [true] to change that");
log.info("Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-start-spring-io] to [true] to change that");
return;
}
this.githubIssues.fileIssueInStartSpringIo(projects, version);

View File

@@ -68,11 +68,9 @@ public class PostReleaseActions implements Closeable {
private final ReleaserPropertiesUpdater releaserPropertiesUpdater;
public PostReleaseActions(ProjectGitHandler projectGitHandler,
ProjectPomUpdater projectPomUpdater, GradleUpdater gradleUpdater,
ProjectCommandExecutor projectCommandExecutor, ReleaserProperties properties,
VersionsFetcher versionsFetcher,
ReleaserPropertiesUpdater releaserPropertiesUpdater) {
public PostReleaseActions(ProjectGitHandler projectGitHandler, ProjectPomUpdater projectPomUpdater,
GradleUpdater gradleUpdater, ProjectCommandExecutor projectCommandExecutor, ReleaserProperties properties,
VersionsFetcher versionsFetcher, ReleaserPropertiesUpdater releaserPropertiesUpdater) {
this.projectGitHandler = projectGitHandler;
this.projectPomUpdater = projectPomUpdater;
this.gradleUpdater = gradleUpdater;
@@ -90,19 +88,15 @@ public class PostReleaseActions implements Closeable {
*/
public ExecutionResult deployGuides(List<ProcessedProject> processedProjects) {
if (!this.properties.getGit().isUpdateSpringGuides()) {
log.info(
"Will not build and deploy latest Spring Guides, since the switch to do so "
+ "is off. Set [releaser.git.update-spring-guides] to [true] to change that");
log.info("Will not build and deploy latest Spring Guides, since the switch to do so "
+ "is off. Set [releaser.git.update-spring-guides] to [true] to change that");
return ExecutionResult.skipped();
}
List<ProcessedProject> latestGaProcessedProjects = processedProjects.stream()
.filter(processedProject -> this.versionsFetcher
.isLatestGa(processedProject.newProjectVersion))
.filter(processedProject -> this.versionsFetcher.isLatestGa(processedProject.newProjectVersion))
.collect(Collectors.toList());
log.info("Found the following latest ga processed projects "
+ latestGaProcessedProjects);
List<ProjectUrlAndException> projectUrlAndExceptions = runDeployGuides(
latestGaProcessedProjects);
log.info("Found the following latest ga processed projects " + latestGaProcessedProjects);
List<ProjectUrlAndException> projectUrlAndExceptions = runDeployGuides(latestGaProcessedProjects);
log.info("Deployed all guides!");
assertExceptions(projectUrlAndExceptions);
return ExecutionResult.success();
@@ -114,8 +108,7 @@ public class PostReleaseActions implements Closeable {
* @return result of the execution
*/
public ExecutionResult runUpdatedTests(Projects projects) {
if (!this.properties.getGit().isRunUpdatedSamples()
|| !this.properties.getMetaRelease().isEnabled()) {
if (!this.properties.getGit().isRunUpdatedSamples() || !this.properties.getMetaRelease().isEnabled()) {
log.info("Will not update and run test samples, since the switch to do so "
+ "is off. Set [releaser.git.run-updated-samples] to [true] to change that");
return ExecutionResult.skipped();
@@ -124,11 +117,9 @@ public class PostReleaseActions implements Closeable {
ReleaserProperties projectProps = projectProps(file);
ProjectVersion projectVersion = newProjectVersion(file);
String releaseTrainVersion = projects.releaseTrain(projectProps).version;
Projects newProjects = addVersionForTestsProject(projects, projectVersion,
releaseTrainVersion);
Projects newProjects = addVersionForTestsProject(projects, projectVersion, releaseTrainVersion);
updateWithVersions(file, newProjects);
this.projectCommandExecutor.build(projectProps, projectVersion, projectVersion,
file.getAbsolutePath());
this.projectCommandExecutor.build(projectProps, projectVersion, projectVersion, file.getAbsolutePath());
return ExecutionResult.success();
}
@@ -144,15 +135,13 @@ public class PostReleaseActions implements Closeable {
* @return result of the execution
*/
public ExecutionResult updateAllTestSamples(Projects projects) {
if (!this.properties.getGit().isUpdateAllTestSamples()
|| !this.properties.getMetaRelease().isEnabled()) {
if (!this.properties.getGit().isUpdateAllTestSamples() || !this.properties.getMetaRelease().isEnabled()) {
log.info("Will not update all test samples, since the switch to do so "
+ "is off. Set [releaser.git.update-all-test-samples] to [true] to change that");
return ExecutionResult.skipped();
}
List<ProjectUrlAndException> projectUrlAndExceptions = this.properties.getGit()
.getAllTestSampleUrls().entrySet().stream()
.map(e -> updateAllProjects(projects, e)).map(this::getResult)
List<ProjectUrlAndException> projectUrlAndExceptions = this.properties.getGit().getAllTestSampleUrls()
.entrySet().stream().map(e -> updateAllProjects(projects, e)).map(this::getResult)
.flatMap(Collection::stream).collect(Collectors.toList());
log.info("Updated all samples!");
assertExceptions(projectUrlAndExceptions);
@@ -160,41 +149,30 @@ public class PostReleaseActions implements Closeable {
}
private void assertExceptions(List<ProjectUrlAndException> projectUrlAndExceptions) {
String exceptionMessages = projectUrlAndExceptions.stream()
.filter(ProjectUrlAndException::hasException)
.map(e -> "Project [" + e.key + "] for url [" + e.url + "] "
+ "has exception [\n\n"
+ Arrays.stream(NestedExceptionUtils.getMostSpecificCause(e.ex)
.getStackTrace()).map(StackTraceElement::toString)
.collect(Collectors.joining("\n"))
String exceptionMessages = projectUrlAndExceptions.stream().filter(ProjectUrlAndException::hasException)
.map(e -> "Project [" + e.key + "] for url [" + e.url + "] " + "has exception [\n\n"
+ Arrays.stream(NestedExceptionUtils.getMostSpecificCause(e.ex).getStackTrace())
.map(StackTraceElement::toString).collect(Collectors.joining("\n"))
+ "]")
.collect(Collectors.joining("\n"));
if (StringUtils.hasText(exceptionMessages)) {
throw new IllegalStateException(
"Exceptions were found while running post release tasks\n"
+ exceptionMessages);
"Exceptions were found while running post release tasks\n" + exceptionMessages);
}
else {
log.info("No exceptions were found while running post release tasks");
}
}
private List<ProjectUrlAndException> runDeployGuides(
List<ProcessedProject> latestGaProcessedProjects) {
private List<ProjectUrlAndException> runDeployGuides(List<ProcessedProject> latestGaProcessedProjects) {
return latestGaProcessedProjects.stream()
.map(processedProject -> run(processedProject.projectName(), "",
() -> SERVICE.submit(() -> {
String tagName = processedProject.newProjectVersion
.releaseTagName();
File clonedProject = this.projectGitHandler
.cloneProjectFromOrg(processedProject.projectName());
this.projectGitHandler.checkout(clonedProject, tagName);
projectBuilder(processedProject).deployGuides(
processedProject.propertiesForProject,
processedProject.originalProjectVersion,
processedProject.newProjectVersion);
})))
.map(this::getSingleResult).collect(Collectors.toList());
.map(processedProject -> run(processedProject.projectName(), "", () -> SERVICE.submit(() -> {
String tagName = processedProject.newProjectVersion.releaseTagName();
File clonedProject = this.projectGitHandler.cloneProjectFromOrg(processedProject.projectName());
this.projectGitHandler.checkout(clonedProject, tagName);
projectBuilder(processedProject).deployGuides(processedProject.propertiesForProject,
processedProject.originalProjectVersion, processedProject.newProjectVersion);
}))).map(this::getSingleResult).collect(Collectors.toList());
}
ProjectCommandExecutor projectBuilder(ProcessedProject processedProject) {
@@ -206,45 +184,37 @@ public class PostReleaseActions implements Closeable {
return SERVICE.submit(() -> {
String key = e.getKey();
List<String> value = e.getValue();
log.info("Running version update for project [{}] and samples {}", key,
value);
log.info("Running version update for project [{}] and samples {}", key, value);
ProjectVersion projectVersionForReleaseTrain = projects.forName(key);
Projects postRelease = getPostReleaseProjects(projects);
log.info("Versions to update the samples with \n" + postRelease.stream()
.map(v -> "[" + v.projectName + " => " + v.version + "]")
.collect(Collectors.joining("\n")));
.map(v -> "[" + v.projectName + " => " + v.version + "]").collect(Collectors.joining("\n")));
return value.stream()
.map(url -> run(key, url,
() -> commitUpdatedProject(projects, key,
projectVersionForReleaseTrain, postRelease, url)))
() -> commitUpdatedProject(projects, key, projectVersionForReleaseTrain, postRelease, url)))
.map(this::getSingleResult).collect(Collectors.toList());
});
}
Projects getPostReleaseProjects(Projects projects) {
return projects.postReleaseSnapshotVersion(
this.properties.getMetaRelease().getProjectsToSkip());
return projects.postReleaseSnapshotVersion(this.properties.getMetaRelease().getProjectsToSkip());
}
private void commitUpdatedProject(Projects projects, String key,
ProjectVersion projectVersionForReleaseTrain, Projects postRelease,
String url) {
private void commitUpdatedProject(Projects projects, String key, ProjectVersion projectVersionForReleaseTrain,
Projects postRelease, String url) {
String releaseTrainVersion = projects.releaseTrain(this.properties).version;
String projectVersion = projects.forName(key).version;
log.info(
"Running version update for project [{}], url [{}], "
+ "release train version [{}] and project version [{}]",
key, url, releaseTrainVersion, projectVersion);
File file = this.projectGitHandler.cloneAndGuessBranch(url, releaseTrainVersion,
projectVersion);
File file = this.projectGitHandler.cloneAndGuessBranch(url, releaseTrainVersion, projectVersion);
Projects newPostRelease = new Projects(postRelease);
ProjectVersion newProjectVersion = newProjectVersion(file);
newPostRelease.add(newProjectVersion);
updateWithVersions(file, newPostRelease);
this.projectGitHandler.commit(file,
"Updated versions after [" + releaseTrainVersion + "] "
+ "release train and [" + projectVersionForReleaseTrain.version
+ "] [" + key + "] project release");
this.projectGitHandler.commit(file, "Updated versions after [" + releaseTrainVersion + "] "
+ "release train and [" + projectVersionForReleaseTrain.version + "] [" + key + "] project release");
this.projectGitHandler.pushCurrentBranch(file);
}
@@ -261,20 +231,17 @@ public class PostReleaseActions implements Closeable {
ProjectVersion projectVersion = ProjectVersion.notMavenProject(file);
String name = projectVersion.projectName;
String version = projectVersion.version;
log.warn(
"Exception occurred while trying to read the pom file. Will assume that the project name is ["
+ name + "] and version [" + version + "]",
ex);
log.warn("Exception occurred while trying to read the pom file. Will assume that the project name is ["
+ name + "] and version [" + version + "]", ex);
return projectVersion;
}
}
private void updateWithVersions(File file, Projects newPostRelease) {
ReleaserProperties updatedProperties = updatedProperties(file);
this.projectPomUpdater.updateProjectFromReleaseTrain(file, newPostRelease,
this.projectPomUpdater.updateProjectFromReleaseTrain(file, newPostRelease, newProjectVersion(file), false);
this.gradleUpdater.updateProjectFromReleaseTrain(updatedProperties, file, newPostRelease,
newProjectVersion(file), false);
this.gradleUpdater.updateProjectFromReleaseTrain(updatedProperties, file,
newPostRelease, newProjectVersion(file), false);
}
private ProjectAndFuture run(String key, String url, Runnable runnable) {
@@ -293,8 +260,7 @@ public class PostReleaseActions implements Closeable {
return new ProjectUrlAndException(projectAndFuture.key, projectAndFuture.url, e);
}
private List<ProjectUrlAndException> getResult(
Future<List<ProjectUrlAndException>> future) {
private List<ProjectUrlAndException> getResult(Future<List<ProjectUrlAndException>> future) {
try {
return future.get(10, TimeUnit.MINUTES);
}
@@ -309,11 +275,9 @@ public class PostReleaseActions implements Closeable {
* @return result of the execution
*/
public ExecutionResult generateReleaseTrainDocumentation(Projects projects) {
if (!this.properties.getGit().isUpdateReleaseTrainDocs()
|| !this.properties.getMetaRelease().isEnabled()) {
log.info(
"Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-release-train-docs] to [true] to change that");
if (!this.properties.getGit().isUpdateReleaseTrainDocs() || !this.properties.getMetaRelease().isEnabled()) {
log.info("Will not update the release train documentation, since the switch to do so "
+ "is off. Set [releaser.git.update-release-train-docs] to [true] to change that");
return ExecutionResult.skipped();
}
ProjectVersion releaseTrain = projects.releaseTrain(this.properties);
@@ -328,16 +292,14 @@ public class PostReleaseActions implements Closeable {
}
ReleaserProperties projectProps = projectProps(file);
String releaseTrainVersion = releaseTrain.version;
this.projectCommandExecutor.generateReleaseTrainDocs(projectProps,
releaseTrainVersion, file.getAbsolutePath());
this.projectCommandExecutor.generateReleaseTrainDocs(projectProps, releaseTrainVersion, file.getAbsolutePath());
return ExecutionResult.success();
}
private Projects addVersionForTestsProject(Projects projects,
ProjectVersion projectVersion, String releaseTrainVersion) {
private Projects addVersionForTestsProject(Projects projects, ProjectVersion projectVersion,
String releaseTrainVersion) {
Projects newProjects = new Projects(projects);
newProjects
.add(new ProjectVersion(projectVersion.projectName, releaseTrainVersion));
newProjects.add(new ProjectVersion(projectVersion.projectName, releaseTrainVersion));
return newProjects;
}

View File

@@ -44,8 +44,8 @@ public class ProcessedProject implements Serializable {
*/
public final ProjectVersion originalProjectVersion;
public ProcessedProject(ReleaserProperties propertiesForProject,
ProjectVersion newProjectVersion, ProjectVersion originalProjectVersion) {
public ProcessedProject(ReleaserProperties propertiesForProject, ProjectVersion newProjectVersion,
ProjectVersion originalProjectVersion) {
this.propertiesForProject = propertiesForProject;
this.newProjectVersion = newProjectVersion;
this.originalProjectVersion = originalProjectVersion;
@@ -53,9 +53,8 @@ public class ProcessedProject implements Serializable {
@Override
public String toString() {
return "ProcessedProject{" + "name=" + this.newProjectVersion.projectName
+ ",version=" + this.newProjectVersion.version + '}'
+ ",originalProjectVersion=" + this.originalProjectVersion + '}';
return "ProcessedProject{" + "name=" + this.newProjectVersion.projectName + ",version="
+ this.newProjectVersion.version + '}' + ",originalProjectVersion=" + this.originalProjectVersion + '}';
}
public String projectName() {

View File

@@ -55,8 +55,7 @@ public class Project {
if (this.name != null ? !this.name.equals(project.name) : project.name != null) {
return false;
}
return this.version != null ? this.version.equals(project.version)
: project.version == null;
return this.version != null ? this.version.equals(project.version) : project.version == null;
}
@Override

View File

@@ -48,8 +48,7 @@ import org.springframework.util.StringUtils;
*/
public class ProjectCommandExecutor {
private static final Logger log = LoggerFactory
.getLogger(ProjectCommandExecutor.class);
private static final Logger log = LoggerFactory.getLogger(ProjectCommandExecutor.class);
private static final String VERSION_MUSTACHE = "{{version}}";
@@ -59,8 +58,7 @@ public class ProjectCommandExecutor {
public void build(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion versionFromReleaseTrain) {
build(properties, originalVersion, versionFromReleaseTrain,
properties.getWorkingDir());
build(properties, originalVersion, versionFromReleaseTrain, properties.getWorkingDir());
}
public String version(ReleaserProperties properties) {
@@ -73,8 +71,7 @@ public class ProjectCommandExecutor {
new CommandPicker(properties, properties.getWorkingDir()).groupId());
}
private String executeCommandWithOutput(ReleaserProperties properties,
String command) {
private String executeCommandWithOutput(ReleaserProperties properties, String command) {
try {
String projectRoot = properties.getWorkingDir();
String[] commands = command.split(" ");
@@ -91,27 +88,22 @@ public class ProjectCommandExecutor {
public void build(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion versionFromReleaseTrain, String projectRoot) {
try {
String command = new CommandPicker(properties, projectRoot)
.buildCommand(versionFromReleaseTrain);
String[] commands = replaceAllPlaceHolders(originalVersion,
versionFromReleaseTrain, command).split(" ");
String command = new CommandPicker(properties, projectRoot).buildCommand(versionFromReleaseTrain);
String[] commands = replaceAllPlaceHolders(originalVersion, versionFromReleaseTrain, command).split(" ");
runCommand(properties, projectRoot, commands);
assertNoHtmlFilesInDocsContainUnresolvedTags(projectRoot);
log.info("No HTML files from docs contain unresolved tags");
}
catch (Exception e) {
String message = properties + "\n" + originalVersion + "\n"
+ versionFromReleaseTrain + "\n" + projectRoot;
String message = properties + "\n" + originalVersion + "\n" + versionFromReleaseTrain + "\n" + projectRoot;
throw new IllegalStateException(message, e);
}
}
public void generateReleaseTrainDocs(ReleaserProperties properties, String version,
String projectRoot) {
public void generateReleaseTrainDocs(ReleaserProperties properties, String version, String projectRoot) {
try {
String updatedCommand = new CommandPicker(properties, projectRoot)
.generateReleaseTrainDocsCommand(
new ProjectVersion(new File(projectRoot)))
.generateReleaseTrainDocsCommand(new ProjectVersion(new File(projectRoot)))
.replace(VERSION_MUSTACHE, version);
runCommand(properties, projectRoot, updatedCommand.split(" "));
assertNoHtmlFilesInDocsContainUnresolvedTags(properties.getWorkingDir());
@@ -135,25 +127,20 @@ public class ProjectCommandExecutor {
}
}
public void deploy(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion version) {
public void deploy(ReleaserProperties properties, ProjectVersion originalVersion, ProjectVersion version) {
doDeploy(properties, originalVersion, version,
new CommandPicker(properties, properties.getWorkingDir())
.deployCommand(version));
new CommandPicker(properties, properties.getWorkingDir()).deployCommand(version));
}
public void deployGuides(ReleaserProperties properties,
ProjectVersion originalVersion, ProjectVersion version) {
public void deployGuides(ReleaserProperties properties, ProjectVersion originalVersion, ProjectVersion version) {
doDeploy(properties, originalVersion, version,
new CommandPicker(properties, properties.getWorkingDir())
.deployGuidesCommand(version));
new CommandPicker(properties, properties.getWorkingDir()).deployGuidesCommand(version));
}
private void doDeploy(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion changedVersion, String command) {
private void doDeploy(ReleaserProperties properties, ProjectVersion originalVersion, ProjectVersion changedVersion,
String command) {
try {
String replacedCommand = replaceAllPlaceHolders(originalVersion,
changedVersion, command);
String replacedCommand = replaceAllPlaceHolders(originalVersion, changedVersion, command);
String[] commands = replacedCommand.split(" ");
runCommand(properties, commands);
log.info("The project has successfully been deployed");
@@ -167,21 +154,16 @@ public class ProjectCommandExecutor {
runCommand(properties, properties.getWorkingDir(), commands);
}
private void runCommand(ReleaserProperties properties, String projectRoot,
String[] commands) {
private void runCommand(ReleaserProperties properties, String projectRoot, String[] commands) {
String[] substitutedCommands = substituteSystemProps(properties, commands);
long waitTimeInMinutes = new CommandPicker(properties, projectRoot)
.waitTimeInMinutes();
long waitTimeInMinutes = new CommandPicker(properties, projectRoot).waitTimeInMinutes();
executor(projectRoot).runCommand(substitutedCommands, waitTimeInMinutes);
}
private String captureCommandOutput(ReleaserProperties properties, String projectRoot,
String[] commands) {
private String captureCommandOutput(ReleaserProperties properties, String projectRoot, String[] commands) {
String[] substitutedCommands = substituteSystemProps(properties, commands);
long waitTimeInMinutes = new CommandPicker(properties, projectRoot)
.waitTimeInMinutes();
return executor(projectRoot).runCommandWithOutput(substitutedCommands,
waitTimeInMinutes);
long waitTimeInMinutes = new CommandPicker(properties, projectRoot).waitTimeInMinutes();
return executor(projectRoot).runCommandWithOutput(substitutedCommands, waitTimeInMinutes);
}
ReleaserProcessExecutor executor(String workDir) {
@@ -191,15 +173,11 @@ public class ProjectCommandExecutor {
public void publishDocs(ReleaserProperties properties, ProjectVersion originalVersion,
ProjectVersion changedVersion) {
try {
String providedCommand = new CommandPicker(properties)
.publishDocsCommand(changedVersion);
log.info("Executing command(s) for publishing docs " + providedCommand + " / "
+ properties);
String[] providedCommands = StringUtils
.delimitedListToStringArray(providedCommand, "&&");
String providedCommand = new CommandPicker(properties).publishDocsCommand(changedVersion);
log.info("Executing command(s) for publishing docs " + providedCommand + " / " + properties);
String[] providedCommands = StringUtils.delimitedListToStringArray(providedCommand, "&&");
for (String command : providedCommands) {
command = replaceAllPlaceHolders(originalVersion, changedVersion,
command.trim());
command = replaceAllPlaceHolders(originalVersion, changedVersion, command.trim());
String[] commands = command.split(" ");
runCommand(properties, commands);
}
@@ -210,8 +188,8 @@ public class ProjectCommandExecutor {
}
}
private String replaceAllPlaceHolders(ProjectVersion originalVersion,
ProjectVersion changedVersion, String command) {
private String replaceAllPlaceHolders(ProjectVersion originalVersion, ProjectVersion changedVersion,
String command) {
return command.replace(VERSION_MUSTACHE, changedVersion.version)
.replace(NEXT_VERSION_MUSTACHE, changedVersion.bumpedVersion())
.replace(OLD_VERSION_MUSTACHE, originalVersion.version);
@@ -221,24 +199,18 @@ public class ProjectCommandExecutor {
* We need to insert the system properties as a list of -Dkey=value entries instead of
* just pasting the String that contains these values.
*/
private String[] substituteSystemProps(ReleaserProperties properties,
String... commands) {
private String[] substituteSystemProps(ReleaserProperties properties, String... commands) {
String systemProperties = new CommandPicker(properties).systemProperties();
String systemPropertiesPlaceholder = new CommandPicker(properties)
.systemPropertiesPlaceholder();
String systemPropertiesPlaceholder = new CommandPicker(properties).systemPropertiesPlaceholder();
boolean containsSystemProps = systemProperties.contains("-D");
String[] splitSystemProps = StringUtils
.delimitedListToStringArray(systemProperties, "-D");
String[] splitSystemProps = StringUtils.delimitedListToStringArray(systemProperties, "-D");
// first element might be empty even though the second one contains values
if (splitSystemProps.length > 1) {
splitSystemProps = StringUtils.isEmpty(splitSystemProps[0])
? Arrays.copyOfRange(splitSystemProps, 1, splitSystemProps.length)
: splitSystemProps;
? Arrays.copyOfRange(splitSystemProps, 1, splitSystemProps.length) : splitSystemProps;
}
String[] systemPropsWithPrefix = containsSystemProps ? Arrays
.stream(splitSystemProps).map(s -> "-D" + s.trim())
.collect(Collectors.toList()).toArray(new String[splitSystemProps.length])
: splitSystemProps;
String[] systemPropsWithPrefix = containsSystemProps ? Arrays.stream(splitSystemProps).map(s -> "-D" + s.trim())
.collect(Collectors.toList()).toArray(new String[splitSystemProps.length]) : splitSystemProps;
final AtomicInteger index = new AtomicInteger(-1);
for (int i = 0; i < commands.length; i++) {
if (commands[i].contains(systemPropertiesPlaceholder)) {
@@ -249,8 +221,7 @@ public class ProjectCommandExecutor {
return toCommandList(systemPropsWithPrefix, index, commands);
}
private String[] toCommandList(String[] systemPropsWithPrefix, AtomicInteger index,
String[] commands) {
private String[] toCommandList(String[] systemPropsWithPrefix, AtomicInteger index, String[] commands) {
List<String> commandsList = new ArrayList<>(Arrays.asList(commands));
List<String> systemPropsList = Arrays.asList(systemPropsWithPrefix);
if (index.get() != -1) {
@@ -273,8 +244,7 @@ public class ProjectCommandExecutor {
class ReleaserProcessExecutor {
private static final Logger log = LoggerFactory
.getLogger(ReleaserProcessExecutor.class);
private static final Logger log = LoggerFactory.getLogger(ReleaserProcessExecutor.class);
private static String[] OS_OPERATORS = { "|", "<", ">", "||", "&&" };
@@ -294,17 +264,15 @@ class ReleaserProcessExecutor {
private ProcessResult doRunCommand(String[] commands, long waitTimeInMinutes) {
String workingDir = this.workingDir;
log.info("Will run the command from [{}] and wait for result for [{}] minutes",
workingDir, waitTimeInMinutes);
log.info("Will run the command from [{}] and wait for result for [{}] minutes", workingDir, waitTimeInMinutes);
try {
ProcessExecutor processExecutor = processExecutor(commands, workingDir)
.timeout(waitTimeInMinutes, TimeUnit.MINUTES);
ProcessExecutor processExecutor = processExecutor(commands, workingDir).timeout(waitTimeInMinutes,
TimeUnit.MINUTES);
final ProcessResult processResult = doExecute(processExecutor);
int processExitValue = processResult.getExitValue();
if (processExitValue != 0) {
throw new IllegalStateException("The process has exited with exit code ["
+ processExitValue + "]");
throw new IllegalStateException("The process has exited with exit code [" + processExitValue + "]");
}
return processResult;
}
@@ -312,10 +280,8 @@ class ReleaserProcessExecutor {
throw new IllegalStateException("Process execution failed", e);
}
catch (TimeoutException e) {
log.error("The command hasn't managed to finish in [{}] minutes",
waitTimeInMinutes);
throw new IllegalStateException("Process waiting time of ["
+ waitTimeInMinutes + "] minutes exceeded", e);
log.error("The command hasn't managed to finish in [{}] minutes", waitTimeInMinutes);
throw new IllegalStateException("Process waiting time of [" + waitTimeInMinutes + "] minutes exceeded", e);
}
}
@@ -331,15 +297,13 @@ class ReleaserProcessExecutor {
commandsToRun = commandToExecute(lastArg);
}
log.info("Will run the command [{}]", Arrays.toString(commandsToRun));
return new ProcessExecutor().command(commandsToRun).destroyOnExit()
.readOutput(true)
return new ProcessExecutor().command(commandsToRun).destroyOnExit().readOutput(true)
// releaser.commands logger should be configured to redirect
// only to a file (with additivity=false). ideally the root logger should
// append to same file on top of whatever root appender, so that file
// contains the most output
.redirectOutputAlsoTo(Slf4jStream.of("releaser.commands").asInfo())
.redirectErrorAlsoTo(Slf4jStream.of("releaser.commands").asWarn())
.directory(new File(workingDir));
.redirectErrorAlsoTo(Slf4jStream.of("releaser.commands").asWarn()).directory(new File(workingDir));
}
String[] commandToExecute(String lastArg) {
@@ -389,12 +353,10 @@ class CommandPicker {
public String publishDocsCommand(ProjectVersion version) {
if (projectType == ProjectType.GRADLE) {
return mavenCommandWithSystemProps(
releaserProperties.getGradle().getPublishDocsCommand(), version);
return mavenCommandWithSystemProps(releaserProperties.getGradle().getPublishDocsCommand(), version);
}
else if (projectType == ProjectType.MAVEN) {
return mavenCommandWithSystemProps(
releaserProperties.getMaven().getPublishDocsCommand(), version);
return mavenCommandWithSystemProps(releaserProperties.getMaven().getPublishDocsCommand(), version);
}
return releaserProperties.getBash().getPublishDocsCommand();
}
@@ -411,12 +373,10 @@ class CommandPicker {
String buildCommand(ProjectVersion version) {
if (projectType == ProjectType.GRADLE) {
return gradleCommandWithSystemProps(
releaserProperties.getGradle().getBuildCommand());
return gradleCommandWithSystemProps(releaserProperties.getGradle().getBuildCommand());
}
else if (projectType == ProjectType.MAVEN) {
return mavenCommandWithSystemProps(
releaserProperties.getMaven().getBuildCommand(), version);
return mavenCommandWithSystemProps(releaserProperties.getMaven().getBuildCommand(), version);
}
return bashCommandWithSystemProps(releaserProperties.getBash().getBuildCommand());
}
@@ -426,9 +386,8 @@ class CommandPicker {
if (projectType == ProjectType.GRADLE) {
return "./gradlew properties | grep version: | awk '{print $2}'";
}
return "./mvnw -q" + " -Dexec.executable=\"echo\""
+ " -Dexec.args=\"\\${project.version}\"" + " --non-recursive"
+ " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1";
return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.version}\""
+ " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1";
}
String groupId() {
@@ -436,50 +395,40 @@ class CommandPicker {
if (projectType == ProjectType.GRADLE) {
return "./gradlew groupId -q | tail -1";
}
return "./mvnw -q" + " -Dexec.executable=\"echo\""
+ " -Dexec.args=\"\\${project.groupId}\"" + " --non-recursive"
+ " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1";
return "./mvnw -q" + " -Dexec.executable=\"echo\"" + " -Dexec.args=\"\\${project.groupId}\""
+ " --non-recursive" + " org.codehaus.mojo:exec-maven-plugin:1.3.1:exec | tail -1";
}
String generateReleaseTrainDocsCommand(ProjectVersion version) {
if (projectType == ProjectType.GRADLE) {
return gradleCommandWithSystemProps(
releaserProperties.getGradle().getGenerateReleaseTrainDocsCommand());
return gradleCommandWithSystemProps(releaserProperties.getGradle().getGenerateReleaseTrainDocsCommand());
}
else if (projectType == ProjectType.MAVEN) {
return mavenCommandWithSystemProps(
releaserProperties.getMaven().getGenerateReleaseTrainDocsCommand(),
return mavenCommandWithSystemProps(releaserProperties.getMaven().getGenerateReleaseTrainDocsCommand(),
version);
}
return bashCommandWithSystemProps(
releaserProperties.getBash().getGenerateReleaseTrainDocsCommand());
return bashCommandWithSystemProps(releaserProperties.getBash().getGenerateReleaseTrainDocsCommand());
}
String deployCommand(ProjectVersion version) {
if (projectType == ProjectType.GRADLE) {
return gradleCommandWithSystemProps(
releaserProperties.getGradle().getDeployCommand());
return gradleCommandWithSystemProps(releaserProperties.getGradle().getDeployCommand());
}
else if (projectType == ProjectType.MAVEN) {
return mavenCommandWithSystemProps(
releaserProperties.getMaven().getDeployCommand(), version);
return mavenCommandWithSystemProps(releaserProperties.getMaven().getDeployCommand(), version);
}
return bashCommandWithSystemProps(
releaserProperties.getBash().getDeployCommand());
return bashCommandWithSystemProps(releaserProperties.getBash().getDeployCommand());
}
String deployGuidesCommand(ProjectVersion version) {
if (projectType == ProjectType.GRADLE) {
return gradleCommandWithSystemProps(
releaserProperties.getGradle().getDeployGuidesCommand());
return gradleCommandWithSystemProps(releaserProperties.getGradle().getDeployGuidesCommand());
}
else if (projectType == ProjectType.MAVEN) {
return mavenCommandWithSystemProps(
releaserProperties.getMaven().getDeployGuidesCommand(), version,
return mavenCommandWithSystemProps(releaserProperties.getMaven().getDeployGuidesCommand(), version,
MavenProfile.GUIDES, MavenProfile.INTEGRATION);
}
return bashCommandWithSystemProps(
releaserProperties.getBash().getDeployGuidesCommand());
return bashCommandWithSystemProps(releaserProperties.getBash().getDeployGuidesCommand());
}
long waitTimeInMinutes() {
@@ -499,13 +448,11 @@ class CommandPicker {
return command + " " + ReleaserProperties.Gradle.SYSTEM_PROPS_PLACEHOLDER;
}
private String mavenCommandWithSystemProps(String command, ProjectVersion version,
MavenProfile... profiles) {
private String mavenCommandWithSystemProps(String command, ProjectVersion version, MavenProfile... profiles) {
if (command.contains(ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER)) {
return appendMavenProfile(command, version, profiles);
}
return appendMavenProfile(command, version, profiles) + " "
+ ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER;
return appendMavenProfile(command, version, profiles) + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER;
}
private String bashCommandWithSystemProps(String command) {
@@ -515,22 +462,18 @@ class CommandPicker {
return command + " " + ReleaserProperties.Maven.SYSTEM_PROPS_PLACEHOLDER;
}
private String appendMavenProfile(String command, ProjectVersion version,
MavenProfile... profiles) {
private String appendMavenProfile(String command, ProjectVersion version, MavenProfile... profiles) {
String trimmedCommand = command.trim();
if (version.isMilestone() || version.isRc()) {
log.info("Adding the milestone profile to the Maven build");
return withProfile(trimmedCommand, MavenProfile.MILESTONE.asMavenProfile(),
profiles);
return withProfile(trimmedCommand, MavenProfile.MILESTONE.asMavenProfile(), profiles);
}
else if (version.isRelease() || version.isServiceRelease()) {
log.info("Adding the central profile to the Maven build");
return withProfile(trimmedCommand, MavenProfile.CENTRAL.asMavenProfile(),
profiles);
return withProfile(trimmedCommand, MavenProfile.CENTRAL.asMavenProfile(), profiles);
}
else {
log.info("The version [" + version.toString()
+ "] is a snapshot one - will not add any profiles");
log.info("The version [" + version.toString() + "] is a snapshot one - will not add any profiles");
}
return trimmedCommand;
}
@@ -548,8 +491,7 @@ class CommandPicker {
}
private String profilesToString(MavenProfile... profiles) {
return Arrays.stream(profiles).map(profile -> "-P" + profile)
.collect(Collectors.joining(" "));
return Arrays.stream(profiles).map(profile -> "-P" + profile).collect(Collectors.joining(" "));
}
private enum ProjectType {
@@ -602,10 +544,8 @@ class HtmlFileWalker extends SimpleFileVisitor<Path> {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attr) {
File file = path.toFile();
if (file.getName().endsWith(HTML_EXTENSION)
&& asString(file).contains("Unresolved")) {
throw new IllegalStateException(
"File [" + file + "] contains a tag that wasn't resolved properly");
if (file.getName().endsWith(HTML_EXTENSION) && asString(file).contains("Unresolved")) {
throw new IllegalStateException("File [" + file + "] contains a tag that wasn't resolved properly");
}
return FileVisitResult.CONTINUE;
}

View File

@@ -51,8 +51,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
private static final Logger log = LoggerFactory.getLogger(ProjectVersion.class);
private static final Pattern SNAPSHOT_PATTERN = Pattern
.compile("^.*[\\.|\\-](BUILD-)?SNAPSHOT.*$");
private static final Pattern SNAPSHOT_PATTERN = Pattern.compile("^.*[\\.|\\-](BUILD-)?SNAPSHOT.*$");
private static final String MILESTONE_REGEX = "^.*[\\.|\\-]M[0-9]+.*$";
@@ -62,12 +61,11 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
private static final String SR_REGEX = "^.*[\\.|\\-]SR[0-9]+.*$";
private static final Pattern SEMVER_PATTERN = Pattern
.compile("(\\d+)\\.(\\d+)\\.(\\d+)");
private static final Pattern SEMVER_PATTERN = Pattern.compile("(\\d+)\\.(\\d+)\\.(\\d+)");
private static final List<Pattern> VALID_PATTERNS = Arrays.asList(SNAPSHOT_PATTERN,
Pattern.compile(MILESTONE_REGEX), Pattern.compile(RC_REGEX),
Pattern.compile(RELEASE_REGEX), Pattern.compile(SR_REGEX));
Pattern.compile(MILESTONE_REGEX), Pattern.compile(RC_REGEX), Pattern.compile(RELEASE_REGEX),
Pattern.compile(SR_REGEX));
/**
* Name of the project.
@@ -164,8 +162,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
if (StringUtils.hasText(model.getGroupId())) {
return model.getGroupId();
}
if (model.getParent() != null
&& StringUtils.hasText(model.getParent().getGroupId())) {
if (model.getParent() != null && StringUtils.hasText(model.getParent().getGroupId())) {
return model.getParent().getGroupId();
}
return "";
@@ -222,8 +219,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
int indexOfFirstHyphen = version.indexOf("-");
boolean buildSnapshot = version.endsWith("BUILD-SNAPSHOT");
if (numberOfHyphens == 1 && !buildSnapshot
|| (numberOfHyphens > 1 && buildSnapshot)) {
if (numberOfHyphens == 1 && !buildSnapshot || (numberOfHyphens > 1 && buildSnapshot)) {
// Dysprosium or 1.0.0
String versionName = version.substring(0, indexOfFirstHyphen);
boolean hasDots = versionName.contains(".");
@@ -243,8 +239,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
return SplitVersion.hyphen(newArray);
}
else {
throw new UnsupportedOperationException(
"Unknown version [" + version + "]");
throw new UnsupportedOperationException("Unknown version [" + version + "]");
}
}
return null;
@@ -319,8 +314,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
}
public String majorAndMinor() {
return this.assertVersion().major + this.assertVersion().delimiter
+ this.assertVersion().minor;
return this.assertVersion().major + this.assertVersion().delimiter + this.assertVersion().minor;
}
/**
@@ -345,15 +339,14 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
patch = Integer.parseInt(splitVersion.patch);
}
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Version " + this.version
+ " doesn't contain a numerical PATCH number", nfe);
throw new IllegalArgumentException("Version " + this.version + " doesn't contain a numerical PATCH number",
nfe);
}
if (patch == 0) {
return Optional.empty();
}
return Optional.of(prefix + splitVersion.major + splitVersion.delimiter
+ splitVersion.minor + splitVersion.delimiter + (patch - 1)
+ splitVersion.delimiter + suffix);
return Optional.of(prefix + splitVersion.major + splitVersion.delimiter + splitVersion.minor
+ splitVersion.delimiter + (patch - 1) + splitVersion.delimiter + suffix);
}
/**
@@ -368,8 +361,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
* previous MAJOR.MINOR, or empty if current MINOR is 0
* @see #computePreviousMajorTagPattern(String, String)
*/
public Optional<Pattern> computePreviousMinorTagPattern(String prefix,
String suffix) {
public Optional<Pattern> computePreviousMinorTagPattern(String prefix, String suffix) {
SplitVersion splitVersion = this.assertVersion();
if (suffix.isEmpty()) {
suffix = splitVersion.suffix;
@@ -380,17 +372,15 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
minor = Integer.parseInt(splitVersion.minor);
}
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Version " + this.version
+ " doesn't contain a numerical MINOR number", nfe);
throw new IllegalArgumentException("Version " + this.version + " doesn't contain a numerical MINOR number",
nfe);
}
if (minor == 0) {
return Optional.empty();
}
Pattern p = Pattern
.compile(Pattern
.quote(prefix + splitVersion.major + splitVersion.delimiter
+ (minor - 1) + splitVersion.delimiter)
+ "\\d+" + quotedSuffix);
Pattern p = Pattern.compile(Pattern
.quote(prefix + splitVersion.major + splitVersion.delimiter + (minor - 1) + splitVersion.delimiter)
+ "\\d+" + quotedSuffix);
return Optional.of(p);
}
@@ -414,16 +404,14 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
major = Integer.parseInt(splitVersion.major);
}
catch (NumberFormatException nfe) {
throw new IllegalArgumentException("Version " + this.version
+ " doesn't contain a numerical MAJOR number", nfe);
throw new IllegalArgumentException("Version " + this.version + " doesn't contain a numerical MAJOR number",
nfe);
}
if (major == 0) {
throw new IllegalArgumentException(
"Cannot compute previous MAJOR pattern with MAJOR of 0");
throw new IllegalArgumentException("Cannot compute previous MAJOR pattern with MAJOR of 0");
}
return Pattern.compile(
Pattern.quote(prefix + (major - 1) + splitVersion.delimiter) + "\\d+"
+ Pattern.quote(splitVersion.delimiter) + "\\d+" + quotedSuffix);
return Pattern.compile(Pattern.quote(prefix + (major - 1) + splitVersion.delimiter) + "\\d+"
+ Pattern.quote(splitVersion.delimiter) + "\\d+" + quotedSuffix);
}
public boolean isSnapshot() {
@@ -511,8 +499,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
private ReleaseType releaseTypeForReleaseTrain() {
try {
SplitVersion splitVersion = assertVersion();
if (StringUtils.isEmpty(splitVersion.suffix)
&& StringUtils.hasText(splitVersion.patch)) {
if (StringUtils.isEmpty(splitVersion.suffix) && StringUtils.hasText(splitVersion.patch)) {
if ("0".equals(splitVersion.patch)) {
return ReleaseType.RELEASE;
}
@@ -537,8 +524,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
SplitVersion thatSplit = that.assertVersion();
int releaseTypeComparison = this.releaseType.compareTo(that.releaseType);
boolean thisReleaseTypeHigher = releaseTypeComparison > 0;
boolean bothGa = this.isReleaseOrServiceRelease()
&& that.isReleaseOrServiceRelease();
boolean bothGa = this.isReleaseOrServiceRelease() && that.isReleaseOrServiceRelease();
// 1.0.1.M2 vs 1.0.0.RELEASE (x)
if (thisReleaseTypeHigher && !bothGa) {
return 1;
@@ -587,8 +573,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
else if (thisVersion.isOldReleaseTrain()) {
return false;
}
return thisVersion.major.equals(thatVersion.major)
&& thisVersion.minor.equals(thatVersion.minor);
return thisVersion.major.equals(thatVersion.major) && thisVersion.minor.equals(thatVersion.minor);
}
private void assertVersionSet() {
@@ -598,8 +583,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
}
public int compareToReleaseTrain(String version) {
return new TrainVersionNumber(this)
.compareTo(new TrainVersionNumber(new ProjectVersion(version)));
return new TrainVersionNumber(this).compareTo(new TrainVersionNumber(new ProjectVersion(version)));
}
/**
@@ -613,11 +597,24 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
return "";
}
/**
* @return the snapshot format of the current version.
*/
public String toSnapshotVersion() {
return assertVersion().withSnapshot().print();
}
@Override
public String toString() {
return this.version;
}
public String toPrettyString() {
return new ToStringCreator(this).append("projectName", projectName).append("version", version)
.append("groupId", groupId).append("artifactId", artifactId).append("releaseType", releaseType)
.toString();
}
@Override
public boolean equals(Object o) {
if (this == o) {
@@ -643,8 +640,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
return Collections.singletonList(SNAPSHOT_PATTERN);
}
// treat like GA
return Arrays.asList(SNAPSHOT_PATTERN, Pattern.compile(MILESTONE_REGEX),
Pattern.compile(RC_REGEX));
return Arrays.asList(SNAPSHOT_PATTERN, Pattern.compile(MILESTONE_REGEX), Pattern.compile(RC_REGEX));
}
@Override
@@ -675,8 +671,7 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
// 1.0.0.RELEASE
// 1.0.0-RELEASE
private SplitVersion(String major, String minor, String patch, String delimiter,
String suffix) {
private SplitVersion(String major, String minor, String patch, String delimiter, String suffix) {
this.major = major;
this.minor = minor;
this.patch = patch;
@@ -764,15 +759,13 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
private SplitVersion fullVersionWithIncrementedPatch() {
int incrementedPatch = Integer.parseInt(patch) + 1;
return new SplitVersion(major, minor, Integer.toString(incrementedPatch),
delimiter, suffix);
return new SplitVersion(major, minor, Integer.toString(incrementedPatch), delimiter, suffix);
}
String print() {
// Finchley.SR2
if (StringUtils.isEmpty(minor)) {
return StringUtils.isEmpty(suffix) ? major
: String.format("%s%s%s", major, delimiter, suffix);
return StringUtils.isEmpty(suffix) ? major : String.format("%s%s%s", major, delimiter, suffix);
}
else if (StringUtils.isEmpty(suffix)) {
return String.format("%s.%s.%s", major, minor, patch);
@@ -790,11 +783,10 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
private boolean tooFewElements() {
// 1 is wrong but Finchley-SR3 is ok
return StringUtils.isEmpty(minor) && StringUtils.isEmpty(patch)
&& StringUtils.isEmpty(suffix);
return StringUtils.isEmpty(minor) && StringUtils.isEmpty(patch) && StringUtils.isEmpty(suffix);
}
private SplitVersion withSnapshot() {
public SplitVersion withSnapshot() {
return new SplitVersion(major, minor, patch, delimiter, suffix());
}
@@ -807,9 +799,8 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
@Override
public String toString() {
return new ToStringCreator(this).append("major", major).append("minor", minor)
.append("patch", patch).append("delimiter", delimiter)
.append("suffix", suffix).toString();
return new ToStringCreator(this).append("major", major).append("minor", minor).append("patch", patch)
.append("delimiter", delimiter).append("suffix", suffix).toString();
}
@@ -859,11 +850,9 @@ public class ProjectVersion implements Comparable<ProjectVersion>, Serializable
}
}
private int compareWithOldTrain(ProjectVersion oldTrain,
ProjectVersion thatVersion) {
private int compareWithOldTrain(ProjectVersion oldTrain, ProjectVersion thatVersion) {
// Hoxton.SR5 > 2020.0.0-M5
if (oldTrain.isReleaseOrServiceRelease()
&& !thatVersion.isReleaseOrServiceRelease()) {
if (oldTrain.isReleaseOrServiceRelease() && !thatVersion.isReleaseOrServiceRelease()) {
return 1;
}
// Hoxton.SR5 < 2020.0.0-RELEASE

View File

@@ -40,8 +40,7 @@ public class Projects extends HashSet<ProjectVersion> {
@SuppressWarnings("unchecked")
public Projects(ProjectVersion... versions) {
addAll(new HashSet<>(Arrays.stream(versions).filter(Objects::nonNull)
.collect(Collectors.toList())));
addAll(new HashSet<>(Arrays.stream(versions).filter(Objects::nonNull).collect(Collectors.toList())));
}
public Projects(List<ProjectVersion> versions) {
@@ -62,36 +61,31 @@ public class Projects extends HashSet<ProjectVersion> {
});
Projects newProjects = new Projects(foundProjectsToSkip);
foundProjectsToBump.forEach(projectVersion -> newProjects
.add(new ProjectVersion(projectVersion.projectName,
projectVersion.postReleaseSnapshotVersion())));
.add(new ProjectVersion(projectVersion.projectName, projectVersion.postReleaseSnapshotVersion())));
newProjects.addAll(foundProjectsToSkip);
return newProjects;
}
private static IllegalStateException exception(Projects projects,
String projectName) {
return new IllegalStateException("Project with name [" + projectName
+ "] is not present in the list of projects [" + projects.asList()
+ "] . " + additionalErrorMessage(projectName));
private static IllegalStateException exception(Projects projects, String projectName) {
return new IllegalStateException(
"Project with name [" + projectName + "] is not present in the list of projects [" + projects.asList()
+ "] . " + additionalErrorMessage(projectName));
}
private static String additionalErrorMessage(String projectName) {
return "Either put it in the BOM or set it via the [--releaser.fixed-versions["
+ projectName + "]=1.0.0.RELEASE] property";
return "Either put it in the BOM or set it via the [--releaser.fixed-versions[" + projectName
+ "]=1.0.0.RELEASE] property";
}
public ProjectVersion releaseTrain(ReleaserProperties properties) {
return stream()
.filter(version -> version.projectName
.equals(properties.getMetaRelease().getReleaseTrainProjectName())
|| properties.getMetaRelease().getReleaseTrainDependencyNames()
.contains(version.projectName))
.filter(version -> version.projectName.equals(properties.getMetaRelease().getReleaseTrainProjectName())
|| properties.getMetaRelease().getReleaseTrainDependencyNames().contains(version.projectName))
.findFirst()
.orElseThrow(() -> new IllegalStateException("Projects " + this
+ " don't contain any of the following release train names ["
+ properties.getMetaRelease().getReleaseTrainProjectName()
+ "] or "
+ properties.getMetaRelease().getReleaseTrainDependencyNames()));
.orElseThrow(() -> new IllegalStateException(
"Projects " + this + " don't contain any of the following release train names ["
+ properties.getMetaRelease().getReleaseTrainProjectName() + "] or "
+ properties.getMetaRelease().getReleaseTrainDependencyNames()));
}
@Override
@@ -110,8 +104,7 @@ public class Projects extends HashSet<ProjectVersion> {
public Projects postReleaseSnapshotVersion(List<String> projectsToSkip) {
Projects projects = this.stream().filter(v -> projectsToSkip(projectsToSkip, v))
.collect(Collectors.toCollection(Projects::new));
Projects bumped = this.stream().map(
v -> new ProjectVersion(v.projectName, v.postReleaseSnapshotVersion()))
Projects bumped = this.stream().map(v -> new ProjectVersion(v.projectName, v.postReleaseSnapshotVersion()))
.collect(Collectors.toCollection(Projects::new));
Projects merged = new Projects(projects);
merged.addAll(bumped);
@@ -129,26 +122,21 @@ public class Projects extends HashSet<ProjectVersion> {
public ProjectVersion forFile(File projectRoot) {
final ProjectVersion thisProject = new ProjectVersion(projectRoot);
return this.stream()
.filter(projectVersion -> projectVersion.projectName
.equals(thisProject.projectName))
return this.stream().filter(projectVersion -> projectVersion.projectName.equals(thisProject.projectName))
.findFirst().orElseThrow(() -> exception(this, thisProject.projectName));
}
public ProjectVersion forName(String projectName) {
return this.stream()
.filter(projectVersion -> projectVersion.projectName.equals(projectName))
.findFirst().orElseThrow(() -> exception(this, projectName));
return this.stream().filter(projectVersion -> projectVersion.projectName.equals(projectName)).findFirst()
.orElseThrow(() -> exception(this, projectName));
}
public boolean containsProject(String projectName) {
return this.stream().anyMatch(
projectVersion -> projectVersion.projectName.equals(projectName));
return this.stream().anyMatch(projectVersion -> projectVersion.projectName.equals(projectName));
}
public List<ProjectVersion> forNameStartingWith(String projectName) {
return this.stream().filter(
projectVersion -> projectVersion.projectName.startsWith(projectName))
return this.stream().filter(projectVersion -> projectVersion.projectName.startsWith(projectName))
.collect(Collectors.toList());
}
@@ -162,14 +150,13 @@ public class Projects extends HashSet<ProjectVersion> {
}
public Set<Project> asProjects() {
return this.stream().map(projectVersion -> new Project(projectVersion.projectName,
projectVersion.version)).collect(Collectors.toSet());
return this.stream().map(projectVersion -> new Project(projectVersion.projectName, projectVersion.version))
.collect(Collectors.toSet());
}
@Override
public String toString() {
return stream().map(v -> "[" + v.projectName + "=>" + v.version + "]")
.collect(Collectors.joining("\n"));
return stream().map(v -> "[" + v.projectName + "=>" + v.version + "]").collect(Collectors.joining("\n"));
}
}

View File

@@ -16,64 +16,73 @@
package releaser.internal.sagan;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.core.style.ToStringCreator;
/**
* @author Marcin Grzejszczak
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Project {
public String id;
private String name;
public String name;
private String slug;
public String repoUrl;
private String repositoryUrl;
public String siteUrl;
private String status;
public String category;
public List<Release> releases;
public String stackOverflowTags;
public String getName() {
return name;
}
public List<Release> projectReleases = new ArrayList<>();
public void setName(String name) {
this.name = name;
}
public Object projectSamples = new Object();
public String getSlug() {
return slug;
}
public Object nonMostCurrentReleases = new ArrayList<>();
public void setSlug(String slug) {
this.slug = slug;
}
public List<String> stackOverflowTagList = new ArrayList<>();
public String getRepositoryUrl() {
return repositoryUrl;
}
public Object mostCurrentRelease = new MostCurrentRelease();
public void setRepositoryUrl(String repositoryUrl) {
this.repositoryUrl = repositoryUrl;
}
public Boolean aggregator;
public String getStatus() {
return status;
}
public String rawBootConfig;
public void setStatus(String status) {
this.status = status;
}
public String rawOverview;
public List<Release> getReleases() {
return this.releases;
}
public int displayOrder = Integer.MAX_VALUE;
public boolean topLevelProject = true;
public void setReleases(List<Release> releases) {
this.releases = releases;
}
@Override
public String toString() {
return "Project{" + "id='" + this.id + '\'' + ", name='" + this.name + '\''
+ ", repoUrl='" + this.repoUrl + '\'' + ", siteUrl='" + this.siteUrl
+ '\'' + ", category='" + this.category + '\'' + ", stackOverflowTags='"
+ this.stackOverflowTags + '\'' + ", projectReleases="
+ this.projectReleases + ", stackOverflowTagList="
+ this.stackOverflowTagList + ", aggregator=" + this.aggregator
+ ", rawBootConfig='" + this.rawBootConfig + '\'' + ", rawOverview='"
+ this.rawOverview + '\'' + '}';
}
static class MostCurrentRelease {
public boolean present;
return new ToStringCreator(this).append("name", name).append("slug", slug)
.append("repositoryUrl", repositoryUrl).append("status", status).append("releases", releases)
.toString();
}

View File

@@ -18,46 +18,69 @@ package releaser.internal.sagan;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.core.style.ToStringCreator;
/**
* @author Marcin Grzejszczak
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Release {
public String releaseStatus = "";
private String version;
public String refDocUrl = "";
private String status;
public String apiDocUrl = "";
private boolean current;
public String groupId = "";
private String referenceDocUrl;
public String artifactId = "";
private String apiDocUrl;
public Repository repository;
public String getVersion() {
return version;
}
public String version = "";
public void setVersion(String version) {
this.version = version;
}
public boolean current;
public String getStatus() {
return status;
}
public boolean generalAvailability;
public void setStatus(String status) {
this.status = status;
}
public boolean preRelease;
public boolean isCurrent() {
return current;
}
public String versionDisplayName = "";
public void setCurrent(boolean current) {
this.current = current;
}
public boolean snapshot;
public String getReferenceDocUrl() {
return referenceDocUrl;
}
public void setReferenceDocUrl(String referenceDocUrl) {
this.referenceDocUrl = referenceDocUrl;
}
public String getApiDocUrl() {
return apiDocUrl;
}
public void setApiDocUrl(String apiDocUrl) {
this.apiDocUrl = apiDocUrl;
}
@Override
public String toString() {
return "Release{" + "releaseStatus='" + this.releaseStatus + '\''
+ ", refDocUrl='" + this.refDocUrl + '\'' + ", apiDocUrl='"
+ this.apiDocUrl + '\'' + ", groupId='" + this.groupId + '\''
+ ", artifactId='" + this.artifactId + '\'' + ", repository="
+ this.repository + ", version='" + this.version + '\'' + ", current="
+ this.current + ", generalAvailability=" + this.generalAvailability
+ ", preRelease=" + this.preRelease + ", versionDisplayName='"
+ this.versionDisplayName + '\'' + ", snapshot=" + this.snapshot + '}';
return new ToStringCreator(this).append("version", version).append("status", status).append("current", current)
.append("referenceDocUrl", referenceDocUrl).append("apiDocUrl", apiDocUrl).toString();
}
}

View File

@@ -18,35 +18,49 @@ package releaser.internal.sagan;
import com.fasterxml.jackson.annotation.JsonInclude;
import org.springframework.core.style.ToStringCreator;
/**
* @author Marcin Grzejszczak
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ReleaseUpdate {
public class ReleaseInput {
public String groupId = "";
private String version = "";
public String artifactId = "";
private String referenceDocUrl = "";
public String version = "";
private String apiDocUrl = "";
public String releaseStatus = "";
public String getVersion() {
return this.version;
}
public String refDocUrl = "";
public void setVersion(String version) {
this.version = version;
}
public String apiDocUrl = "";
public String getReferenceDocUrl() {
return this.referenceDocUrl;
}
public Boolean current;
public void setReferenceDocUrl(String referenceDocUrl) {
this.referenceDocUrl = referenceDocUrl;
}
public Repository repository;
public String getApiDocUrl() {
return this.apiDocUrl;
}
public void setApiDocUrl(String apiDocUrl) {
this.apiDocUrl = apiDocUrl;
}
@Override
public String toString() {
return "ReleaseUpdate{" + "groupId='" + this.groupId + '\'' + ", artifactId='"
+ this.artifactId + '\'' + ", version='" + this.version + '\''
+ ", releaseStatus='" + this.releaseStatus + '\'' + ", refDocUrl='"
+ this.refDocUrl + '\'' + ", apiDocUrl='" + this.apiDocUrl + '\''
+ ", repository=" + this.repository + '}';
return new ToStringCreator(this).append("version", version).append("referenceDocUrl", referenceDocUrl)
.append("apiDocUrl", apiDocUrl).toString();
}
}

View File

@@ -34,9 +34,8 @@ public class Repository {
@Override
public String toString() {
return "Repository{" + "id='" + this.id + '\'' + ", name='" + this.name + '\''
+ ", url='" + this.url + '\'' + ", snapshotsEnabled="
+ this.snapshotsEnabled + '}';
return "Repository{" + "id='" + this.id + '\'' + ", name='" + this.name + '\'' + ", url='" + this.url + '\''
+ ", snapshotsEnabled=" + this.snapshotsEnabled + '}';
}
}

View File

@@ -17,6 +17,7 @@
package releaser.internal.sagan;
import java.net.URI;
import java.util.Collections;
import java.util.List;
import org.slf4j.Logger;
@@ -36,8 +37,7 @@ import org.springframework.web.client.RestTemplate;
*/
class RestTemplateSaganClient implements SaganClient {
private static final Logger log = LoggerFactory
.getLogger(RestTemplateSaganClient.class);
private static final Logger log = LoggerFactory.getLogger(RestTemplateSaganClient.class);
private final RestTemplate restTemplate;
@@ -50,56 +50,91 @@ class RestTemplateSaganClient implements SaganClient {
@Override
public Project getProject(String projectName) {
return this.restTemplate.getForObject(
this.baseUrl + "/project_metadata/{projectName}", Project.class,
projectName);
}
HttpHeaders headers = new HttpHeaders();
headers.put("Accept", Collections.singletonList("application/hal+json"));
Project project = this.restTemplate.exchange(this.baseUrl + "/api/projects/{projectName}", HttpMethod.GET,
new HttpEntity<>(headers), Project.class, projectName).getBody();
if (project == null) {
return null;
}
@Override
public Release getRelease(String projectName, String releaseVersion) {
return this.restTemplate.getForObject(
this.baseUrl
+ "/project_metadata/{projectName}/releases/{releaseVersion}",
Release.class, projectName, releaseVersion);
}
@Override
public Release deleteRelease(String projectName, String releaseVersion) {
ResponseEntity<Release> entity = this.restTemplate.exchange(
this.baseUrl
+ "/project_metadata/{projectName}/releases/{releaseVersion}",
HttpMethod.DELETE, new HttpEntity<>(""), Release.class, projectName,
releaseVersion);
Release release = entity.getBody();
log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, release);
return release;
}
@Override
public Project updateRelease(String projectName, List<ReleaseUpdate> releaseUpdates) {
RequestEntity<List<ReleaseUpdate>> request = RequestEntity
.put(URI.create(
this.baseUrl + "/project_metadata/" + projectName + "/releases"))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
.body(releaseUpdates);
ResponseEntity<Project> entity = this.restTemplate.exchange(request,
Project.class);
Project project = entity.getBody();
log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, project);
EmbeddedProjectReleases body = this.restTemplate.exchange(this.baseUrl + "/api/projects/{projectName}/releases",
HttpMethod.GET, new HttpEntity<>(headers), EmbeddedProjectReleases.class, projectName).getBody();
project.setReleases(body._embedded.releases);
return project;
}
@Override
public Release getRelease(String projectName, String releaseVersion) {
HttpHeaders headers = new HttpHeaders();
headers.put("Accept", Collections.singletonList("application/hal+json"));
return this.restTemplate.exchange(this.baseUrl + "/api/projects/{projectName}/releases/{releaseVersion}",
HttpMethod.GET, new HttpEntity<>(headers), Release.class, projectName, releaseVersion).getBody();
}
@Override
public boolean deleteRelease(String projectName, String releaseVersion) {
ResponseEntity<Release> entity = this.restTemplate.exchange(
this.baseUrl + "/api/projects/{projectName}/releases/{releaseVersion}", HttpMethod.DELETE,
new HttpEntity<>(""), Release.class, projectName, releaseVersion);
boolean deleted = entity.getStatusCode().is2xxSuccessful();
log.info("Response from Sagan\n\n[{}] \n with status [{}]", entity, entity.getStatusCode());
return deleted;
}
@Override
public boolean addRelease(String projectName, ReleaseInput releaseInput) {
RequestEntity<ReleaseInput> request = RequestEntity
.post(URI.create(this.baseUrl + "/api/projects/" + projectName + "/releases"))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE).body(releaseInput);
ResponseEntity<Project> entity = this.restTemplate.exchange(request, Project.class);
boolean added = entity.getStatusCode().is2xxSuccessful();
log.info("Response from Sagan\n\n[{}]", entity);
return added;
}
@Override
public Project patchProject(Project project) {
RequestEntity<Project> request = RequestEntity
.patch(URI.create(this.baseUrl + "/project_metadata/" + project.id))
.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_UTF8_VALUE)
.body(project);
ResponseEntity<Project> entity = this.restTemplate.exchange(request,
Project.class);
Project updatedProject = entity.getBody();
log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity, updatedProject);
return updatedProject;
// RequestEntity<Project> request = RequestEntity
// .patch(URI.create(this.baseUrl + "/project_metadata/" + project.getSlug()))
// .header(HttpHeaders.CONTENT_TYPE,
// MediaType.APPLICATION_JSON_UTF8_VALUE).body(project);
// ResponseEntity<Project> entity = this.restTemplate.exchange(request,
// Project.class);
// Project updatedProject = entity.getBody();
// log.info("Response from Sagan\n\n[{}] \n with body [{}]", entity,
// updatedProject);
// return updatedProject;
// FIXME: no api yet https://github.com/spring-io/sagan/issues/1052
return null;
}
private static class EmbeddedProjectReleases {
private ProjectReleases _embedded;
public ProjectReleases get_embedded() {
return this._embedded;
}
public void set_embedded(ProjectReleases _embedded) {
this._embedded = _embedded;
}
}
private static class ProjectReleases {
private List<Release> releases;
public List<Release> getReleases() {
return this.releases;
}
public void setReleases(List<Release> releases) {
this.releases = releases;
}
}
}

View File

@@ -16,8 +16,6 @@
package releaser.internal.sagan;
import java.util.List;
/**
* @author Marcin Grzejszczak
*/
@@ -27,9 +25,9 @@ public interface SaganClient {
Release getRelease(String projectName, String releaseVersion);
Release deleteRelease(String projectName, String releaseVersion);
boolean deleteRelease(String projectName, String releaseVersion);
Project updateRelease(String projectName, List<ReleaseUpdate> releaseUpdate);
boolean addRelease(String projectName, ReleaseInput releaseInput);
Project patchProject(Project project);

View File

@@ -23,7 +23,6 @@ import java.util.Comparator;
import java.util.Optional;
import java.util.stream.Collectors;
import edu.emory.mathcs.backport.java.util.Collections;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import releaser.internal.ReleaserProperties;
@@ -50,37 +49,34 @@ public class SaganUpdater {
this.releaserProperties = releaserProperties;
}
public ExecutionResult updateSagan(File projectFile, String branch,
ProjectVersion originalVersion, ProjectVersion currentVersion,
Projects projects) {
public ExecutionResult updateSagan(File projectFile, String branch, ProjectVersion originalVersion,
ProjectVersion currentVersion, Projects projects) {
if (!this.releaserProperties.getSagan().isUpdateSagan()) {
log.info("Will not update sagan, since the switch to do so "
+ "is off. Set [releaser.sagan.update-sagan] to [true] to change that");
return ExecutionResult.skipped();
}
ReleaseUpdate update = releaseUpdate(branch, originalVersion, currentVersion,
projects);
Exception updateReleaseException = updateSaganForNonSnapshot(branch,
originalVersion, currentVersion, projects);
ReleaseInput update = releaseUpdate(branch, originalVersion, currentVersion, projects);
Exception updateReleaseException = updateSaganForNonSnapshot(branch, originalVersion, currentVersion, projects);
if (updateReleaseException == null) {
log.info("Updating Sagan releases with \n\n{}", update);
try {
Project project = this.saganClient.updateRelease(
currentVersion.projectName, Collections.singletonList(update));
Optional<ProjectVersion> projectVersion = latestVersion(currentVersion,
project);
log.info("Found the following latest project version [{}]",
projectVersion);
boolean added = this.saganClient.addRelease(currentVersion.projectName, update);
if (!added) {
return ExecutionResult.unstable(
new Exception("Unable to add release for project " + currentVersion.toPrettyString()));
}
Project project = saganClient.getProject(currentVersion.projectName);
Optional<ProjectVersion> projectVersion = latestVersion(currentVersion, project);
log.info("Found the following latest project version [{}]", projectVersion);
boolean present = projectVersion.isPresent();
if (present
&& currentVersionNewerOrEqual(currentVersion, projectVersion)) {
if (present && currentVersionNewerOrEqual(currentVersion, projectVersion)) {
updateDocumentationIfNecessary(projectFile, project);
}
else {
log.info(present
? "Latest version [" + projectVersion.get() + "] present and "
+ "the current version [" + currentVersion
+ "] is older than that one. " + "Will do nothing."
? "Latest version [" + projectVersion.get() + "] present and " + "the current version ["
+ currentVersion + "] is older than that one. " + "Will do nothing."
: "No latest version found. Will do nothing.");
return ExecutionResult.skipped();
}
@@ -91,37 +87,35 @@ public class SaganUpdater {
}
}
return updateReleaseException == null ? ExecutionResult.success()
: ExecutionResult.unstable(
new IllegalStateException(updateReleaseException.getMessage()));
: ExecutionResult.unstable(new IllegalStateException(updateReleaseException.getMessage()));
}
private void updateDocumentationIfNecessary(File projectFile, Project project) {
boolean shouldUpdate = false;
File docsModule = docsModule(projectFile);
File indexDoc = new File(docsModule,
this.releaserProperties.getSagan().getIndexSectionFileName());
File bootDoc = new File(docsModule,
this.releaserProperties.getSagan().getBootSectionFileName());
File indexDoc = new File(docsModule, this.releaserProperties.getSagan().getIndexSectionFileName());
File bootDoc = new File(docsModule, this.releaserProperties.getSagan().getBootSectionFileName());
if (indexDoc.exists()) {
log.debug("Index adoc file exists");
String fileText = fileToText(indexDoc);
if (StringUtils.hasText(fileText) && !fileText.equals(project.rawOverview)) {
log.info(
"Index adoc content differs from the previously stored, will update it");
project.rawOverview = fileText;
shouldUpdate = true;
}
// if (StringUtils.hasText(fileText) && !fileText.equals(project.rawOverview))
// {
// log.info("Index adoc content differs from the previously stored, will
// update it");
// project.rawOverview = fileText;
// shouldUpdate = true;
// }
}
if (bootDoc.exists()) {
log.debug("Boot adoc file exists");
String fileText = fileToText(bootDoc);
if (StringUtils.hasText(fileText)
&& !fileText.equals(project.rawBootConfig)) {
log.info(
"Boot adoc content differs from the previously stored, will update it");
project.rawBootConfig = fileText;
shouldUpdate = true;
}
// if (StringUtils.hasText(fileText) &&
// !fileText.equals(project.rawBootConfig)) {
// log.info("Boot adoc content differs from the previously stored, will update
// it");
// project.rawBootConfig = fileText;
// shouldUpdate = true;
// }
}
if (shouldUpdate) {
this.saganClient.patchProject(project);
@@ -133,8 +127,7 @@ public class SaganUpdater {
}
File docsModule(File projectFile) {
return new File(projectFile,
this.releaserProperties.getSagan().getDocsAdocsFile());
return new File(projectFile, this.releaserProperties.getSagan().getDocsAdocsFile());
}
private String fileToText(File file) {
@@ -146,49 +139,40 @@ public class SaganUpdater {
}
}
private Optional<ProjectVersion> latestVersion(ProjectVersion currentVersion,
Project project) {
private Optional<ProjectVersion> latestVersion(ProjectVersion currentVersion, Project project) {
if (project == null) {
return Optional.empty();
}
return project.projectReleases.stream().filter(release -> release.current)
.map(release -> new ProjectVersion(currentVersion.projectName,
release.version))
return project.getReleases().stream().filter(Release::isCurrent)
.map(release -> new ProjectVersion(currentVersion.projectName, release.getVersion()))
.max(Comparator.comparing(o -> o.version));
}
private boolean currentVersionNewerOrEqual(ProjectVersion currentVersion,
Optional<ProjectVersion> projectVersion) {
private boolean currentVersionNewerOrEqual(ProjectVersion currentVersion, Optional<ProjectVersion> projectVersion) {
return currentVersion.compareTo(projectVersion.get()) >= 0;
}
private Exception updateSaganForNonSnapshot(String branch,
ProjectVersion originalVersion, ProjectVersion version, Projects projects) {
private Exception updateSaganForNonSnapshot(String branch, ProjectVersion originalVersion, ProjectVersion version,
Projects projects) {
Exception updateReleaseException = null;
if (!version.isSnapshot()) {
log.info(
"Version is non snapshot [{}]. Will remove all older versions and mark this as current",
version);
log.info("Version is non snapshot [{}]. Will remove all older versions and mark this as current", version);
Project project = this.saganClient.getProject(version.projectName);
if (project != null) {
removeAllSameMinorVersions(version, project);
}
String snapshot = toSnapshot(version.version);
String snapshot = toSnapshot(version);
removeVersionFromSagan(version, snapshot);
if (version.isRelease() || version.isServiceRelease()) {
try {
String bumpedSnapshot = toSnapshot(version.bumpedVersion());
ReleaseUpdate snapshotUpdate = releaseUpdate(branch, originalVersion,
new ProjectVersion(version.projectName, bumpedSnapshot),
projects);
log.info("Updating Sagan with bumped snapshot \n\n[{}]",
snapshotUpdate);
this.saganClient.updateRelease(version.projectName,
Collections.singletonList(snapshotUpdate));
String bumpedSnapshot = bumpedSnapshot(version);
ReleaseInput snapshotUpdate = releaseUpdate(branch, originalVersion,
new ProjectVersion(version.projectName, bumpedSnapshot), projects);
log.info("Updating Sagan with bumped snapshot \n\n[{}]", snapshotUpdate);
this.saganClient.addRelease(version.projectName, snapshotUpdate);
}
catch (Exception e) {
log.warn("Failed to update [" + version.projectName + "/" + snapshot
+ "] from Sagan", e);
log.warn("Failed to update [" + version.projectName + "/" + snapshot + "] from Sagan", e);
updateReleaseException = e;
}
}
@@ -197,75 +181,61 @@ public class SaganUpdater {
}
private void removeAllSameMinorVersions(ProjectVersion version, Project project) {
project.projectReleases.stream()
.filter(release -> version.isSameMinor(release.version))
.collect(Collectors.toList())
.forEach(release -> removeVersionFromSagan(version, release.version));
project.getReleases().stream().filter(release -> version.isSameMinor(release.getVersion()))
.collect(Collectors.toList()).forEach(release -> removeVersionFromSagan(version, release.getVersion()));
}
private void removeVersionFromSagan(ProjectVersion version, String snapshot) {
log.info("Removing [{}/{}] from Sagan", version.projectName, snapshot);
try {
this.saganClient.deleteRelease(version.projectName, snapshot);
boolean deleted = this.saganClient.deleteRelease(version.projectName, snapshot);
if (!deleted) {
log.warn("Failed to remove [" + version.projectName + "/" + snapshot + "] from Sagan");
}
}
catch (Exception e) {
log.warn("Failed to remove [" + version.projectName + "/" + snapshot
+ "] from Sagan", e);
log.warn("Failed to remove [" + version.projectName + "/" + snapshot + "] from Sagan", e);
}
}
private ReleaseUpdate releaseUpdate(String branch, ProjectVersion originalVersion,
ProjectVersion version, Projects projects) {
ReleaseUpdate update = new ReleaseUpdate();
update.groupId = originalVersion.groupId();
update.artifactId = version.projectName;
update.version = version.version;
update.releaseStatus = version(version);
update.apiDocUrl = referenceUrl(branch, version, projects);
update.refDocUrl = update.apiDocUrl;
update.current = true;
private ReleaseInput releaseUpdate(String branch, ProjectVersion originalVersion, ProjectVersion version,
Projects projects) {
ReleaseInput update = new ReleaseInput();
update.setVersion(version.version);
update.setReferenceDocUrl(referenceUrl(branch, version, projects));
update.setApiDocUrl(null);
return update;
}
private String toSnapshot(String version) {
private String bumpedSnapshot(ProjectVersion projectVersion) {
String bumpedVersion = projectVersion.bumpedVersion();
return toSnapshot(new ProjectVersion("", bumpedVersion));
}
private String toSnapshot(ProjectVersion projectVersion) {
String version = projectVersion.version;
if (version.contains("RELEASE")) {
return version.replace("RELEASE", "BUILD-SNAPSHOT");
}
else if (version.matches(".*SR[0-9]+")) {
return version.substring(0, version.lastIndexOf(".")) + ".BUILD-SNAPSHOT";
}
return version;
}
private String version(ProjectVersion version) {
if (version.isSnapshot()) {
return "SNAPSHOT";
}
else if (version.isMilestone() || version.isRc()) {
return "PRERELEASE";
}
else if (version.isRelease() || version.isServiceRelease()) {
return "GENERAL_AVAILABILITY";
}
return "";
return projectVersion.toSnapshotVersion();
}
private String releaseTrainVersion(Projects projects) {
String releaseTrainProjectName = this.releaserProperties.getMetaRelease()
.getReleaseTrainProjectName();
return projects.containsProject(releaseTrainProjectName)
? projects.forName(releaseTrainProjectName).version : "";
String releaseTrainProjectName = this.releaserProperties.getMetaRelease().getReleaseTrainProjectName();
return projects.containsProject(releaseTrainProjectName) ? projects.forName(releaseTrainProjectName).version
: "";
}
private String referenceUrl(String branch, ProjectVersion version,
Projects projects) {
private String referenceUrl(String branch, ProjectVersion version, Projects projects) {
String releaseTrainVersion = releaseTrainVersion(projects);
// up till Greenwich we have a different URL for docs
// if there's no release train, will assume that 2.2.x is the version that has the
// new docs
boolean hasReleaseTrainVersion = StringUtils.hasText(releaseTrainVersion);
boolean newDocs = hasReleaseTrainVersion
? releaseTrainVersion.toLowerCase().charAt(0) > 'g'
boolean newDocs = hasReleaseTrainVersion ? releaseTrainVersion.toLowerCase().charAt(0) > 'g'
: version.version.compareTo("2.2") > 0;
if (newDocs) {
return newReferenceUrl(branch, version);
@@ -274,30 +244,17 @@ public class SaganUpdater {
}
private String newReferenceUrl(String branch, ProjectVersion version) {
if (!version.isSnapshot()) {
// static/sleuth/{version}/
return "https://cloud.spring.io/spring-cloud-static/" + version.projectName
+ "/{version}/reference/html/";
}
if (branch.toLowerCase().contains("main")) {
// sleuth/
return "https://cloud.spring.io/" + version.projectName + "/reference/html/";
}
// sleuth/1.1.x/
return "https://cloud.spring.io/" + version.projectName + "/" + branch
+ "/reference/html/";
return "https://docs.spring.io/" + version.projectName + "/docs/{version}/reference/html/";
}
private String oldReferenceUrl(String branch, ProjectVersion version) {
if (!version.isSnapshot()) {
// static/sleuth/{version}/
return "https://cloud.spring.io/spring-cloud-static/" + version.projectName
+ "/{version}/";
return "https://cloud.spring.io/spring-cloud-static/" + version.projectName + "/{version}/";
}
if (branch.toLowerCase().contains("main")) {
// sleuth/
return "https://cloud.spring.io/" + version.projectName + "/"
+ version.projectName + ".html";
return "https://cloud.spring.io/" + version.projectName + "/" + version.projectName + ".html";
}
// sleuth/1.1.x/
return "https://cloud.spring.io/" + version.projectName + "/" + branch + "/";

View File

@@ -46,8 +46,7 @@ public class BuildUnstableException extends RuntimeException implements Serializ
*/
public static final String EXIT_CODE = "BUILD_UNSTABLE";
private static final Logger log = LoggerFactory
.getLogger(BuildUnstableException.class);
private static final Logger log = LoggerFactory.getLogger(BuildUnstableException.class);
/**
* List of exceptions causing this instability.
@@ -61,8 +60,7 @@ public class BuildUnstableException extends RuntimeException implements Serializ
}
public BuildUnstableException(String message, List<Throwable> throwables) {
this(throwables.stream().map(BuildUnstableException::breakReferenceChain)
.collect(Collectors.toList()));
this(throwables.stream().map(BuildUnstableException::breakReferenceChain).collect(Collectors.toList()));
log.warn("\n\n" + DESCRIPTION + message + " with causes " + throwables);
}
@@ -72,8 +70,7 @@ public class BuildUnstableException extends RuntimeException implements Serializ
private static Throwable breakReferenceChain(Throwable cause) {
if (cause instanceof HttpServerErrorException) {
return new RuntimeException(
"[Breaking self reference chain] " + cause.toString());
return new RuntimeException("[Breaking self reference chain] " + cause.toString());
}
return cause;
}

View File

@@ -65,23 +65,20 @@ public class ExecutionResult implements Serializable {
}
public static ExecutionResult failure(List<Exception> throwables) {
return new ExecutionResult(throwables.stream()
.map(ExecutionResult::breakReferenceChain).collect(Collectors.toList()));
return new ExecutionResult(
throwables.stream().map(ExecutionResult::breakReferenceChain).collect(Collectors.toList()));
}
private static Exception breakReferenceChain(Exception cause) {
if (cause instanceof HttpServerErrorException
|| cause instanceof HttpClientErrorException) {
if (cause instanceof HttpServerErrorException || cause instanceof HttpClientErrorException) {
System.out.println("Breaking the reference chain. . . i think");
return new RuntimeException(
"[Breaking self reference chain] " + cause.toString());
return new RuntimeException("[Breaking self reference chain] " + cause.toString());
}
return cause;
}
public static ExecutionResult unstable(Exception ex) {
return new ExecutionResult(ex instanceof BuildUnstableException ? ex
: new BuildUnstableException(ex));
return new ExecutionResult(ex instanceof BuildUnstableException ? ex : new BuildUnstableException(ex));
}
public static ExecutionResult skipped() {
@@ -110,18 +107,17 @@ public class ExecutionResult implements Serializable {
}
public boolean isUnstable() {
return !this.exceptions.isEmpty() && this.exceptions.stream()
.allMatch(t -> t instanceof BuildUnstableException);
return !this.exceptions.isEmpty()
&& this.exceptions.stream().allMatch(t -> t instanceof BuildUnstableException);
}
public String toStringResult() {
return isUnstable() ? "UNSTABLE"
: isFailure() ? "FAILURE" : isSkipped() ? "SKIPPED" : "SUCCESS";
return isUnstable() ? "UNSTABLE" : isFailure() ? "FAILURE" : isSkipped() ? "SKIPPED" : "SUCCESS";
}
public boolean isFailure() {
return !this.exceptions.isEmpty() && this.exceptions.stream()
.anyMatch(t -> !(t instanceof BuildUnstableException));
return !this.exceptions.isEmpty()
&& this.exceptions.stream().anyMatch(t -> !(t instanceof BuildUnstableException));
}
public boolean isSuccess() {
@@ -148,8 +144,7 @@ public class ExecutionResult implements Serializable {
this.skipped = skipped;
}
private static final class MergedThrowable extends RuntimeException
implements Serializable {
private static final class MergedThrowable extends RuntimeException implements Serializable {
private MergedThrowable(List<Exception> throwables) {
super("Failed due to the following exceptions " + throwables);
@@ -157,8 +152,7 @@ public class ExecutionResult implements Serializable {
}
private static final class MergedUnstableThrowable extends BuildUnstableException
implements Serializable {
private static final class MergedUnstableThrowable extends BuildUnstableException implements Serializable {
private MergedUnstableThrowable(List<Exception> throwables) {
super("Unstable due to the following exceptions " + throwables);

View File

@@ -34,8 +34,7 @@ public final class HandlebarsHelper {
public static Template template(String templateSubFolder, String templateName) {
try {
Handlebars handlebars = new Handlebars(
new ClassPathTemplateLoader("/templates/" + templateSubFolder));
Handlebars handlebars = new Handlebars(new ClassPathTemplateLoader("/templates/" + templateSubFolder));
handlebars.registerHelper("replace", StringHelpers.replace);
handlebars.registerHelper("capitalizeFirst", StringHelpers.capitalizeFirst);
return handlebars.compile(templateName);

View File

@@ -60,11 +60,9 @@ public final class PomReader {
}
catch (XmlPullParserException | IOException e) {
if (file.isFile() && fileText.length() == 0) {
throw new IllegalStateException(
"File [" + pom.getAbsolutePath() + "] is empty", e);
throw new IllegalStateException("File [" + pom.getAbsolutePath() + "] is empty", e);
}
throw new IllegalStateException(
"Failed to read file: " + pom.getAbsolutePath(), e);
throw new IllegalStateException("Failed to read file: " + pom.getAbsolutePath(), e);
}
}

View File

@@ -65,8 +65,7 @@ public final class TemporaryFileStorage {
if (file.isDirectory()) {
Files.walkFileTree(file.toPath(), new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file,
BasicFileAttributes attrs) throws IOException {
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
if (log.isTraceEnabled()) {
log.trace("Removing file [" + file + "]");
}
@@ -75,8 +74,7 @@ public final class TemporaryFileStorage {
}
@Override
public FileVisitResult postVisitDirectory(Path dir,
IOException exc) throws IOException {
public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
if (log.isTraceEnabled()) {
log.trace("Removing dir [" + dir + "]");
}
@@ -110,9 +108,8 @@ public final class TemporaryFileStorage {
return tempDir;
}
}
throw new IllegalStateException("Failed to create directory within "
+ TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName
+ (TEMP_DIR_ATTEMPTS - 1) + ")");
throw new IllegalStateException("Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried "
+ baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ")");
}
}

View File

@@ -34,8 +34,7 @@ import releaser.internal.project.Projects;
*/
class BlogTemplateGenerator {
private static final Logger log = LoggerFactory
.getLogger(BlogTemplateGenerator.class);
private static final Logger log = LoggerFactory.getLogger(BlogTemplateGenerator.class);
private static final Pattern RC_PATTERN = Pattern.compile("(.*)(RC)([0-9]+)");
@@ -53,8 +52,8 @@ class BlogTemplateGenerator {
private final NotesGenerator notesGenerator;
BlogTemplateGenerator(Template template, String releaseVersion, File blogOutput,
Projects projects, ProjectGitHubHandler handler) {
BlogTemplateGenerator(Template template, String releaseVersion, File blogOutput, Projects projects,
ProjectGitHubHandler handler) {
this.template = template;
this.releaseVersion = releaseVersion;
this.blogOutput = blogOutput;
@@ -75,24 +74,21 @@ class BlogTemplateGenerator {
boolean release = !SR_PATTERN.matcher(this.releaseVersion).matches()
&& !RC_PATTERN.matcher(this.releaseVersion).matches()
&& !MILESTONE_PATTERN.matcher(this.releaseVersion).matches();
boolean nonRelease = !(release
|| SR_PATTERN.matcher(this.releaseVersion).matches());
boolean nonRelease = !(release || SR_PATTERN.matcher(this.releaseVersion).matches());
String availability = availability(release);
String releaseName = parsedReleaseName(this.releaseVersion, release);
String releaseLink = link(nonRelease);
Map<String, Object> map = ImmutableMap.<String, Object>builder()
.put("availability", availability).put("releaseName", releaseName)
.put("releaseLink", releaseLink)
Map<String, Object> map = ImmutableMap.<String, Object>builder().put("availability", availability)
.put("releaseName", releaseName).put("releaseLink", releaseLink)
.put("releaseVersion", this.releaseVersion)
.put("projects", this.notesGenerator.fromProjects(this.projects))
.put("nonRelease", nonRelease).build();
.put("projects", this.notesGenerator.fromProjects(this.projects)).put("nonRelease", nonRelease)
.build();
String blog = this.template.apply(map);
Files.write(this.blogOutput.toPath(), blog.getBytes());
return this.blogOutput;
}
catch (Exception e) {
throw new IllegalStateException(
"Exception occurred while trying to create a blog entry", e);
throw new IllegalStateException("Exception occurred while trying to create a blog entry", e);
}
}
@@ -127,8 +123,7 @@ class BlogTemplateGenerator {
}
if (log.isWarnEnabled()) {
log.warn("Unrecognized release [{}] . "
+ "Hopefully, you know what you're doing. Will treat it as milestone",
this.releaseVersion);
+ "Hopefully, you know what you're doing. Will treat it as milestone", this.releaseVersion);
}
return milestone(milestone);
}
@@ -147,8 +142,7 @@ class BlogTemplateGenerator {
return "[Spring Milestone](https://repo.spring.io/milestone/) repository";
}
return "[Maven Central](https://repo1.maven.org/maven2/"
+ "org/springframework/cloud/spring-cloud-dependencies/"
+ this.releaseVersion + "/)";
+ "org/springframework/cloud/spring-cloud-dependencies/" + this.releaseVersion + "/)";
}
}

View File

@@ -28,8 +28,7 @@ import org.slf4j.LoggerFactory;
*/
class EmailTemplateGenerator {
private static final Logger log = LoggerFactory
.getLogger(EmailTemplateGenerator.class);
private static final Logger log = LoggerFactory.getLogger(EmailTemplateGenerator.class);
private final Template template;
@@ -50,8 +49,7 @@ class EmailTemplateGenerator {
return this.emailOutput;
}
catch (Exception e) {
throw new IllegalStateException(
"Exception occurred while trying to generate an email template", e);
throw new IllegalStateException("Exception occurred while trying to generate an email template", e);
}
}

View File

@@ -37,13 +37,12 @@ class NotesGenerator {
}
Set<Notes> fromProjects(Projects projects) {
return projects.stream().filter(projectVersion -> !projectVersion.projectName
.toLowerCase().contains("boot")).map(projectVersion -> {
return projects.stream().filter(projectVersion -> !projectVersion.projectName.toLowerCase().contains("boot"))
.map(projectVersion -> {
String name = projectVersion.projectName;
String version = projectVersion.version;
String closedMilestoneUrl = this.handler.milestoneUrl(projectVersion);
String convertedName = Arrays.stream(name.split("-"))
.map(StringUtils::capitalize)
String convertedName = Arrays.stream(name.split("-")).map(StringUtils::capitalize)
.collect(Collectors.joining(" "));
return new Notes(convertedName, version, closedMilestoneUrl);
}).collect(Collectors.toSet());
@@ -90,8 +89,7 @@ class Notes {
if (this.name != null ? !this.name.equals(notes.name) : notes.name != null) {
return false;
}
return this.version != null ? this.version.equals(notes.version)
: notes.version == null;
return this.version != null ? this.version.equals(notes.version) : notes.version == null;
}
@Override

View File

@@ -43,8 +43,8 @@ class ReleaseNotesTemplateGenerator {
private final NotesGenerator notesGenerator;
ReleaseNotesTemplateGenerator(Template template, String releaseVersion,
File blogOutput, Projects projects, ProjectGitHubHandler handler) {
ReleaseNotesTemplateGenerator(Template template, String releaseVersion, File blogOutput, Projects projects,
ProjectGitHubHandler handler) {
this.template = template;
this.releaseVersion = releaseVersion;
this.blogOutput = blogOutput;
@@ -57,15 +57,13 @@ class ReleaseNotesTemplateGenerator {
Map<String, Object> map = ImmutableMap.<String, Object>builder()
.put("date", LocalDate.now().format(DateTimeFormatter.ISO_DATE))
.put("releaseVersion", this.releaseVersion)
.put("projects", this.notesGenerator.fromProjects(this.projects))
.build();
.put("projects", this.notesGenerator.fromProjects(this.projects)).build();
String blog = this.template.apply(map);
Files.write(this.blogOutput.toPath(), blog.getBytes());
return this.blogOutput;
}
catch (IOException e) {
throw new IllegalStateException(
"Exception occurred while trying to generate release notes", e);
throw new IllegalStateException("Exception occurred while trying to generate release notes", e);
}
}

View File

@@ -59,8 +59,7 @@ public class TemplateGenerator {
this.releaseNotesOutput = new File("target/notes.md");
}
TemplateGenerator(ReleaserProperties props, File output,
ProjectGitHubHandler handler) {
TemplateGenerator(ReleaserProperties props, File output, ProjectGitHubHandler handler) {
this.props = props;
this.emailOutput = output;
this.blogOutput = output;
@@ -97,8 +96,7 @@ public class TemplateGenerator {
File blogOutput = file(this.blogOutput);
String releaseVersion = parsedVersion(projects);
Template template = template(BLOG_TEMPLATE);
return new BlogTemplateGenerator(template, releaseVersion, blogOutput, projects,
this.handler).blog();
return new BlogTemplateGenerator(template, releaseVersion, blogOutput, projects, this.handler).blog();
}
public File tweet(Projects projects) {
@@ -112,8 +110,8 @@ public class TemplateGenerator {
File output = file(this.releaseNotesOutput);
String releaseVersion = parsedVersion(projects);
Template template = template(RELEASE_NOTES_TEMPLATE);
return new ReleaseNotesTemplateGenerator(template, releaseVersion, output,
projects, this.handler).releaseNotes();
return new ReleaseNotesTemplateGenerator(template, releaseVersion, output, projects, this.handler)
.releaseNotes();
}
private String parsedVersion(Projects projects) {
@@ -128,8 +126,7 @@ public class TemplateGenerator {
}
private Template template(String template) {
return HandlebarsHelper.template(this.props.getTemplate().getTemplateFolder(),
template);
return HandlebarsHelper.template(this.props.getTemplate().getTemplateFolder(), template);
}
}

View File

@@ -28,8 +28,7 @@ import org.slf4j.LoggerFactory;
*/
class TwitterTemplateGenerator {
private static final Logger log = LoggerFactory
.getLogger(TwitterTemplateGenerator.class);
private static final Logger log = LoggerFactory.getLogger(TwitterTemplateGenerator.class);
private final Template template;
@@ -50,8 +49,7 @@ class TwitterTemplateGenerator {
return this.output;
}
catch (Exception e) {
throw new IllegalStateException(
"Exception occurred while trying to generate a twitter template", e);
throw new IllegalStateException("Exception occurred while trying to generate a twitter template", e);
}
}

View File

@@ -60,8 +60,7 @@ public class VersionsFetcher implements Closeable {
private final ReleaserProperties properties;
public VersionsFetcher(ReleaserProperties properties,
ProjectPomUpdater projectPomUpdater) {
public VersionsFetcher(ReleaserProperties properties, ProjectPomUpdater projectPomUpdater) {
this.properties = properties;
this.projectPomUpdater = projectPomUpdater;
this.toPropertiesConverter = new ToPropertiesConverter(new RawGithubRetriever());
@@ -75,8 +74,7 @@ public class VersionsFetcher implements Closeable {
public boolean isLatestGa(ProjectVersion version) {
if (!version.isReleaseOrServiceRelease()) {
if (log.isDebugEnabled()) {
log.debug("Version [" + version.toString()
+ "] is non GA, will not fetch any versions.");
log.debug("Version [" + version.toString() + "] is non GA, will not fetch any versions.");
}
return false;
}
@@ -86,55 +84,44 @@ public class VersionsFetcher implements Closeable {
return false;
}
String latestVersionsUrl = this.properties.getVersions().getAllVersionsFileUrl();
InitializrProperties initializrProperties = this.toPropertiesConverter
.toProperties(latestVersionsUrl);
InitializrProperties initializrProperties = this.toPropertiesConverter.toProperties(latestVersionsUrl);
if (initializrProperties == null) {
return false;
}
ProjectVersion bomVersion = latestBomVersion();
if (bomVersion == null) {
log.info("No BOM mapping with name [{}] found",
this.properties.getVersions().getBomName());
log.info("No BOM mapping with name [{}] found", this.properties.getVersions().getBomName());
return false;
}
Projects projectVersions = null;
try {
projectVersions = this.projectPomUpdater.retrieveVersionsFromReleaseTrainBom(
"v" + bomVersion.toString(), false);
projectVersions = this.projectPomUpdater.retrieveVersionsFromReleaseTrainBom("v" + bomVersion.toString(),
false);
}
catch (Exception ex) {
log.error(
"Failed to check the project versions. Will return that the project is not GA",
ex);
log.error("Failed to check the project versions. Will return that the project is not GA", ex);
return false;
}
boolean containsProject = projectVersions.containsProject(version.projectName);
if (containsProject) {
return bomVersion.compareTo(projectVersions.forName(version.projectName)) > 0;
}
log.info("The project [" + version.projectName
+ "] is not present in the BOM with projects [" + projectVersions.stream()
.map(v -> v.projectName).collect(Collectors.joining(", "))
+ "]");
log.info("The project [" + version.projectName + "] is not present in the BOM with projects ["
+ projectVersions.stream().map(v -> v.projectName).collect(Collectors.joining(", ")) + "]");
return false;
}
private ProjectVersion latestBomVersion() {
String latestVersionsUrl = this.properties.getVersions().getAllVersionsFileUrl();
InitializrProperties initializrProperties = this.toPropertiesConverter
.toProperties(latestVersionsUrl);
InitializrProperties initializrProperties = this.toPropertiesConverter.toProperties(latestVersionsUrl);
if (initializrProperties == null) {
return null;
}
ProjectVersion springCloudVersion = initializrProperties.getEnv().getBoms()
.getOrDefault(
this.properties.getVersions().getBomName(), new BillOfMaterials())
.getMappings().stream()
.map(mapping -> new ProjectVersion(
this.properties.getVersions().getBomName(), mapping.getVersion()))
.filter(ProjectVersion::isReleaseOrServiceRelease)
.max(ProjectVersion::compareTo).orElse(new ProjectVersion(
this.properties.getVersions().getBomName(), ""));
.getOrDefault(this.properties.getVersions().getBomName(), new BillOfMaterials()).getMappings().stream()
.map(mapping -> new ProjectVersion(this.properties.getVersions().getBomName(), mapping.getVersion()))
.filter(ProjectVersion::isReleaseOrServiceRelease).max(ProjectVersion::compareTo)
.orElse(new ProjectVersion(this.properties.getVersions().getBomName(), ""));
log.info("Latest BOM version is [{}]", springCloudVersion.version);
return springCloudVersion;
}
@@ -154,14 +141,13 @@ class RawGithubRetriever {
try {
URL url = new URL(stringUrl);
URLConnection con = url.openConnection();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
con.getInputStream(), StandardCharsets.UTF_8))) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(con.getInputStream(), StandardCharsets.UTF_8))) {
return reader.lines().collect(Collectors.joining("\n"));
}
}
catch (IOException e) {
LOG.warn("Exception occurred while trying to fetch the URL [" + stringUrl
+ "] contents");
LOG.warn("Exception occurred while trying to fetch the URL [" + stringUrl + "] contents");
return null;
}
}
@@ -185,16 +171,12 @@ class ToPropertiesConverter implements Closeable {
return null;
}
YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
yamlProcessor.setResources(new InputStreamResource(new ByteArrayInputStream(
retrievedFile.getBytes(StandardCharsets.UTF_8))));
yamlProcessor.setResources(
new InputStreamResource(new ByteArrayInputStream(retrievedFile.getBytes(StandardCharsets.UTF_8))));
Properties properties = yamlProcessor.getObject();
return new Binder(
new MapConfigurationPropertySource(properties.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString()))))
.bind("initializr",
InitializrProperties.class)
.get();
return new Binder(new MapConfigurationPropertySource(properties.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))))
.bind("initializr", InitializrProperties.class).get();
});
}

View File

@@ -32,17 +32,13 @@ public class SpringCloudReleaserProperties {
public static ReleaserProperties get() {
try {
File releaserConfig = new File(SpringCloudReleaserProperties.class
.getResource("/application.yml").toURI());
File releaserConfig = new File(SpringCloudReleaserProperties.class.getResource("/application.yml").toURI());
YamlPropertiesFactoryBean yamlProcessor = new YamlPropertiesFactoryBean();
yamlProcessor.setResources(new FileSystemResource(releaserConfig));
Properties properties = yamlProcessor.getObject();
ReleaserProperties releaserProperties = new Binder(
new MapConfigurationPropertySource(properties.entrySet().stream()
.collect(Collectors.toMap(e -> e.getKey().toString(),
e -> e.getValue().toString()))))
.bind("releaser", ReleaserProperties.class)
.get();
ReleaserProperties releaserProperties = new Binder(new MapConfigurationPropertySource(properties.entrySet()
.stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> e.getValue().toString()))))
.bind("releaser", ReleaserProperties.class).get();
return releaserProperties;
}
catch (URISyntaxException e) {

View File

@@ -62,25 +62,20 @@ public class PomUpdateAcceptanceTests {
ReleaserProperties releaserProperties = releaserProperties();
releaserProperties.getFixedVersions().put("checkstyle", "100.0.0.RELEASE");
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth");
projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true);
projectPomUpdater.updateProjectFromReleaseTrain(project, projects, projects.forFile(project), true);
then(this.temporaryFolder).exists();
Model rootPom = PomReader.readPom(tmpFile("/spring-cloud-sleuth/pom.xml"));
Model depsPom = PomReader.readPom(
tmpFile("/spring-cloud-sleuth/spring-cloud-sleuth-dependencies/pom.xml"));
Model corePom = PomReader.readPom(
tmpFile("/spring-cloud-sleuth/spring-cloud-sleuth-core/pom.xml"));
Model depsPom = PomReader.readPom(tmpFile("/spring-cloud-sleuth/spring-cloud-sleuth-dependencies/pom.xml"));
Model corePom = PomReader.readPom(tmpFile("/spring-cloud-sleuth/spring-cloud-sleuth-core/pom.xml"));
Model zipkinStreamPom = PomReader.readPom(tmpFile(
"/spring-cloud-sleuth/spring-cloud-sleuth-samples/spring-cloud-sleuth-sample-zipkin-stream/pom.xml"));
then(rootPom.getVersion()).isEqualTo("1.2.0.BUILD-SNAPSHOT");
then(rootPom.getProperties())
.containsEntry("spring-cloud-commons.version", "1.2.0.BUILD-SNAPSHOT")
then(rootPom.getProperties()).containsEntry("spring-cloud-commons.version", "1.2.0.BUILD-SNAPSHOT")
.containsEntry("spring-cloud-stream.version", "Chelsea.BUILD-SNAPSHOT")
.containsEntry("spring-cloud-netflix.version", "1.3.0.BUILD-SNAPSHOT")
.containsEntry("checkstyle.version", "100.0.0.RELEASE");
@@ -95,23 +90,20 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
projects.add(new ProjectVersion("spring-cloud-sleuth-samples", "0.0.5.RELEASE"));
File project = new File(this.temporaryFolder,
"/spring-cloud-sleuth-with-unmatched-property/spring-cloud-sleuth-samples");
addBuildSnapshotToChildPom(project);
projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true);
projectPomUpdater.updateProjectFromReleaseTrain(project, projects, projects.forFile(project), true);
}
private void addBuildSnapshotToChildPom(File project) throws IOException {
File childPom = new File(project, "pom.xml");
String text = new String(Files.readAllBytes(childPom.toPath()));
Files.write(childPom.toPath(),
text.replaceAll("1.19.2", "1.19.2.BUILD-SNAPSHOT").getBytes());
Files.write(childPom.toPath(), text.replaceAll("1.19.2", "1.19.2.BUILD-SNAPSHOT").getBytes());
}
@Test
@@ -119,15 +111,13 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
File project = new File(this.temporaryFolder,
"/spring-cloud-sleuth-with-unmatched-property");
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth-with-unmatched-property");
BDDAssertions
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(
project, projects, projects.forFile(project), true))
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true))
.hasMessageContaining("<version>0.3.1.BUILD-SNAPSHOT</version>");
}
@@ -136,18 +126,15 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
projects.removeIf(projectVersion -> projectVersion.projectName
.contains("spring-cloud-build"));
projects.removeIf(projectVersion -> projectVersion.projectName.contains("spring-cloud-build"));
projects.add(new ProjectVersion("spring-cloud-build", "1.4.2.RELEASE"));
File project = new File(this.temporaryFolder,
"/spring-cloud-sleuth-with-milestone-dep");
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth-with-milestone-dep");
BDDAssertions
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(
project, projects, projects.forFile(project), true))
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true))
.hasMessageContaining("<zipkin.version>1.19.2-M2</zipkin.version>");
}
@@ -156,15 +143,13 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projects(projectPomUpdater);
File project = new File(this.temporaryFolder,
"/spring-cloud-sleuth-with-milestone-dep");
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth-with-milestone-dep");
BDDAssertions
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(
project, projects, projects.forFile(project), true))
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true))
.hasMessageContaining("<zipkin.version>1.19.2-M2</zipkin.version>");
}
@@ -173,35 +158,26 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projects(projectPomUpdater);
File project = new File(this.temporaryFolder,
"/spring-cloud-sleuth-with-ignored-line");
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth-with-ignored-line");
projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true);
projectPomUpdater.updateProjectFromReleaseTrain(project, projects, projects.forFile(project), true);
}
private Projects projects(ProjectPomUpdater projectPomUpdater) {
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
projects.removeIf(
projectVersion -> projectVersion.projectName.equals("spring-cloud"));
projects.removeIf(projectVersion -> projectVersion.projectName.equals("spring-cloud"));
projects.add(new ProjectVersion("spring-cloud", "Camden.RC1"));
projects.removeIf(projectVersion -> projectVersion.projectName
.equals("spring-cloud-dependencies"));
projects.removeIf(projectVersion -> projectVersion.projectName.equals("spring-cloud-dependencies"));
projects.add(new ProjectVersion("spring-cloud-dependencies", "Camden.RC1"));
projects.removeIf(projectVersion -> projectVersion.projectName
.equals("spring-cloud-starter"));
projects.removeIf(projectVersion -> projectVersion.projectName.equals("spring-cloud-starter"));
projects.add(new ProjectVersion("spring-cloud-starter", "Camden.RC1"));
projects.removeIf(projectVersion -> projectVersion.projectName
.equals("spring-cloud-starter-build"));
projects.removeIf(projectVersion -> projectVersion.projectName.equals("spring-cloud-starter-build"));
projects.add(new ProjectVersion("spring-cloud-starter-build", "Camden.RC1"));
projects.removeIf(projectVersion -> projectVersion.projectName
.equals("spring-cloud-release"));
projects.removeIf(projectVersion -> projectVersion.projectName.equals("spring-cloud-release"));
projects.add(new ProjectVersion("spring-cloud-release", "Camden.RC1"));
projects.removeIf(projectVersion -> projectVersion.projectName
.contains("spring-cloud-build"));
projects.removeIf(projectVersion -> projectVersion.projectName.contains("spring-cloud-build"));
projects.add(new ProjectVersion("spring-cloud-build", "1.4.2.RELEASE"));
return projects;
}
@@ -211,26 +187,21 @@ public class PomUpdateAcceptanceTests {
throws Exception {
ReleaserProperties releaserProperties = branchReleaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
projects.removeIf(projectVersion -> projectVersion.projectName
.contains("spring-cloud-build"));
projects.removeIf(projectVersion -> projectVersion.projectName.contains("spring-cloud-build"));
projects.add(new ProjectVersion("spring-cloud-build", "1.4.2.BUILD-SNAPSHOT"));
File project = new File(this.temporaryFolder, "/spring-cloud-sleuth");
BDDAssertions
.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(
project, projects, projects.forFile(project), true))
.hasMessageContaining("BUILD-SNAPSHOT</version>");
BDDAssertions.thenThrownBy(() -> projectPomUpdater.updateProjectFromReleaseTrain(project, projects,
projects.forFile(project), true)).hasMessageContaining("BUILD-SNAPSHOT</version>");
}
@Test
public void should_not_update_a_project_that_is_not_on_the_list() throws Exception {
ReleaserProperties releaserProperties = releaserProperties();
ProjectPomUpdater projectPomUpdater = new ProjectPomUpdater(releaserProperties,
Collections
.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
Collections.singletonList(MavenBomParserAccessor.maven(releaserProperties)));
File beforeProcessing = pom("/projects/project/");
Projects projects = projectPomUpdater.retrieveVersionsFromReleaseTrainBom();
File project = tmpFile("/project/");
@@ -245,8 +216,7 @@ public class PomUpdateAcceptanceTests {
private ReleaserProperties releaserProperties() throws URISyntaxException {
ReleaserProperties releaserProperties = SpringCloudReleaserProperties.get();
releaserProperties.getGit().setReleaseTrainBomUrl(
file("/projects/spring-cloud-release/").toURI().toString());
releaserProperties.getGit().setReleaseTrainBomUrl(file("/projects/spring-cloud-release/").toURI().toString());
return releaserProperties;
}
@@ -265,10 +235,7 @@ public class PomUpdateAcceptanceTests {
}
private File pom(String relativePath) throws URISyntaxException {
return new File(
new File(
PomUpdateAcceptanceTests.class.getResource(relativePath).toURI()),
"pom.xml");
return new File(new File(PomUpdateAcceptanceTests.class.getResource(relativePath).toURI()), "pom.xml");
}
private String asString(File file) throws IOException {

View File

@@ -72,13 +72,10 @@ public class ReleaserPropertiesTests {
BDDAssertions.then(properties.getWorkingDir()).isEqualTo("foo");
BDDAssertions.then(properties.getFixedVersions()).isEqualTo(map());
BDDAssertions.then(properties.getMaven().getBuildCommand()).isEqualTo("foo2");
BDDAssertions.then(properties.getGradle().getIgnoredGradleRegex())
.isEqualTo(Arrays.asList("foo3", "foo4"));
BDDAssertions.then(properties.getMetaRelease().getProjectsToSkip())
.isEqualTo(Arrays.asList("foo5", "foo6"));
BDDAssertions.then(properties.getGradle().getIgnoredGradleRegex()).isEqualTo(Arrays.asList("foo3", "foo4"));
BDDAssertions.then(properties.getMetaRelease().getProjectsToSkip()).isEqualTo(Arrays.asList("foo5", "foo6"));
BDDAssertions.then(properties.getGit().getPassword()).isEqualTo("foo7");
BDDAssertions.then(properties.getPom().getIgnoredPomRegex())
.isEqualTo(Arrays.asList("foo8", "foo9"));
BDDAssertions.then(properties.getPom().getIgnoredPomRegex()).isEqualTo(Arrays.asList("foo8", "foo9"));
BDDAssertions.then(properties.getSagan().getBaseUrl()).isEqualTo("foo10");
}

View File

@@ -42,7 +42,7 @@ import releaser.internal.project.Projects;
import releaser.internal.sagan.SaganUpdater;
import releaser.internal.template.TemplateGenerator;
import org.springframework.boot.test.rule.OutputCapture;
import org.springframework.boot.test.system.OutputCaptureRule;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.BDDMockito.then;
@@ -55,7 +55,7 @@ import static org.mockito.Mockito.never;
public class ReleaserTests {
@Rule
public OutputCapture outputCapture = new OutputCapture();
public OutputCaptureRule outputCapture = new OutputCaptureRule();
@Mock
ProjectPomUpdater projectPomUpdater;
@@ -93,9 +93,8 @@ public class ReleaserTests {
}
Releaser releaser(Supplier<ProjectVersion> originalVersionSupplier) {
return new Releaser(SpringCloudReleaserProperties.get(), this.projectPomUpdater,
this.projectCommandExecutor, this.projectGitHandler,
this.projectGitHubHandler, this.templateGenerator, this.gradleUpdater,
return new Releaser(SpringCloudReleaserProperties.get(), this.projectPomUpdater, this.projectCommandExecutor,
this.projectGitHandler, this.projectGitHubHandler, this.templateGenerator, this.gradleUpdater,
this.saganUpdater, this.documentationUpdater, this.postReleaseActions) {
@Override
ProjectVersion originalVersion(File project) {
@@ -105,71 +104,60 @@ public class ReleaserTests {
}
Releaser releaser() {
return new Releaser(new ReleaserProperties(), this.projectPomUpdater,
this.projectCommandExecutor, this.projectGitHandler,
this.projectGitHubHandler, this.templateGenerator, this.gradleUpdater,
return new Releaser(new ReleaserProperties(), this.projectPomUpdater, this.projectCommandExecutor,
this.projectGitHandler, this.projectGitHubHandler, this.templateGenerator, this.gradleUpdater,
this.saganUpdater, this.documentationUpdater, this.postReleaseActions);
}
@Test
public void should_not_bump_versions_for_original_release_project() {
releaser(() -> new ProjectVersion("original", "1.0.0.RELEASE"))
.rollbackReleaseVersion(this.pom,
new Projects(new ProjectVersion("changed", "1.0.0.RELEASE")),
new ProjectVersion("changed", "1.0.0.RELEASE"));
releaser(() -> new ProjectVersion("original", "1.0.0.RELEASE")).rollbackReleaseVersion(this.pom,
new Projects(new ProjectVersion("changed", "1.0.0.RELEASE")),
new ProjectVersion("changed", "1.0.0.RELEASE"));
BDDAssertions.then(this.outputCapture.toString()).contains(
"Successfully reverted the commit and came back to snapshot versions");
then(this.projectGitHandler).should(never())
.commitAfterBumpingVersions(any(File.class), any(ProjectVersion.class));
BDDAssertions.then(this.outputCapture.toString())
.contains("Successfully reverted the commit and came back to snapshot versions");
then(this.projectGitHandler).should(never()).commitAfterBumpingVersions(any(File.class),
any(ProjectVersion.class));
}
@Test
public void should_not_bump_versions_for_original_snapshot_project_and_current_snapshot() {
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"))
.rollbackReleaseVersion(this.pom,
new Projects(
new ProjectVersion("changed", "1.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("changed", "1.0.0.BUILD-SNAPSHOT"));
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT")).rollbackReleaseVersion(this.pom,
new Projects(new ProjectVersion("changed", "1.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("changed", "1.0.0.BUILD-SNAPSHOT"));
BDDAssertions.then(this.outputCapture.toString())
.contains("Won't rollback a snapshot version");
then(this.projectGitHandler).should(never())
.commitAfterBumpingVersions(any(File.class), any(ProjectVersion.class));
BDDAssertions.then(this.outputCapture.toString()).contains("Won't rollback a snapshot version");
then(this.projectGitHandler).should(never()).commitAfterBumpingVersions(any(File.class),
any(ProjectVersion.class));
}
@Test
public void should_bump_versions_for_original_snapshot_project() {
ProjectVersion scReleaseVersion = new ProjectVersion("changed", "1.0.0.RELEASE");
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"))
.rollbackReleaseVersion(this.pom, new Projects(
new ProjectVersion("changed", "1.0.0.RELEASE"),
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT")).rollbackReleaseVersion(this.pom,
new Projects(new ProjectVersion("changed", "1.0.0.RELEASE"),
new ProjectVersion("spring-cloud-build", "2.0.0.RELEASE"),
new ProjectVersion("spring-boot-starter", "3.0.0.RELEASE")),
scReleaseVersion);
scReleaseVersion);
BDDAssertions.then(this.outputCapture.toString())
.contains("Project was successfully updated")
BDDAssertions.then(this.outputCapture.toString()).contains("Project was successfully updated")
.contains("Successfully reverted the commit and bumped snapshot versions")
.contains("spring-boot-starter=>3.0.0.RELEASE")
.contains("spring-cloud-build=>2.0.1.SNAPSHOT")
.contains("spring-boot-starter=>3.0.0.RELEASE").contains("spring-cloud-build=>2.0.1.SNAPSHOT")
.contains("changed=>1.0.1.SNAPSHOT");
}
@Test
public void should_not_generate_email_for_snapshot_version() {
releaser().createEmail(new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"),
projects());
releaser().createEmail(new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"), projects());
then(this.templateGenerator).should(never()).email(any(Projects.class));
}
@Test
public void should_generate_email_for_release_version() {
BDDMockito.given(this.templateGenerator.email(projects()))
.willReturn(new File("."));
releaser().createEmail(new ProjectVersion("original", "1.0.0.RELEASE"),
projects());
BDDMockito.given(this.templateGenerator.email(projects())).willReturn(new File("."));
releaser().createEmail(new ProjectVersion("original", "1.0.0.RELEASE"), projects());
then(this.templateGenerator).should().email(any(Projects.class));
}
@@ -178,20 +166,17 @@ public class ReleaserTests {
public void should_not_close_milestone_for_snapshots() {
releaser().closeMilestone(new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"));
then(this.projectGitHubHandler).should(never())
.closeMilestone(any(ProjectVersion.class));
then(this.projectGitHubHandler).should(never()).closeMilestone(any(ProjectVersion.class));
}
@Test
public void should_not_rollback_for_snapshots() {
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"))
.rollbackReleaseVersion(null,
new Projects(
new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"));
releaser(() -> new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT")).rollbackReleaseVersion(null,
new Projects(new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT")),
new ProjectVersion("original", "1.0.0.BUILD-SNAPSHOT"));
then(this.projectGitHandler).should(never())
.revertChangesIfApplicable(any(File.class), any(ProjectVersion.class));
then(this.projectGitHandler).should(never()).revertChangesIfApplicable(any(File.class),
any(ProjectVersion.class));
}
Projects projects() {

View File

@@ -30,8 +30,7 @@ class GradleBomParserTests {
@Test
void should_read_versions_from_bom_from_properties() {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(),
new ArrayList<>()) {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(), new ArrayList<>()) {
@Override
public boolean isApplicable(File clonedBom) {
return true;
@@ -52,8 +51,7 @@ class GradleBomParserTests {
VersionsFromBom versionsFromBom = parser.versionsFromBom(new File("."));
BDDAssertions.then(versionsFromBom.versionForProject("spring-cloud-contract"))
.isEqualTo("1.0.0.RELEASE");
BDDAssertions.then(versionsFromBom.versionForProject("spring-cloud-contract")).isEqualTo("1.0.0.RELEASE");
}
@Test
@@ -62,8 +60,7 @@ class GradleBomParserTests {
gradleSubstitution.put("verifierVersion", "spring-cloud-contract");
ReleaserProperties releaserProperties = new ReleaserProperties();
releaserProperties.getGradle().setGradlePropsSubstitution(gradleSubstitution);
GradleBomParser parser = new GradleBomParser(releaserProperties,
new ArrayList<>()) {
GradleBomParser parser = new GradleBomParser(releaserProperties, new ArrayList<>()) {
@Override
public boolean isApplicable(File clonedBom) {
return true;
@@ -84,22 +81,19 @@ class GradleBomParserTests {
VersionsFromBom versionsFromBom = parser.versionsFromBom(new File("."));
BDDAssertions.then(versionsFromBom.versionForProject("spring-cloud-contract"))
.isEqualTo("1.0.0.RELEASE");
BDDAssertions.then(versionsFromBom.versionForProject("spring-cloud-contract")).isEqualTo("1.0.0.RELEASE");
}
@Test
void should_be_not_applicable_when_no_build_gradle_is_present() {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(),
new ArrayList<>());
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(), new ArrayList<>());
BDDAssertions.then(parser.isApplicable(new File("."))).isFalse();
}
@Test
void should_be_applicable_when_build_gradle_is_present() {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(),
new ArrayList<>()) {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(), new ArrayList<>()) {
@Override
File file(File clonedBom, String child) {
return clonedBom;
@@ -111,8 +105,7 @@ class GradleBomParserTests {
@Test
void should_return_empty_version_when_no_gradle_properties_is_present() {
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(),
new ArrayList<>());
GradleBomParser parser = new GradleBomParser(new ReleaserProperties(), new ArrayList<>());
VersionsFromBom versionsFromBom = parser.versionsFromBom(new File("."));

View File

@@ -51,8 +51,7 @@ public class MavenBomParserTests {
BomParser parser = new MavenBomParser(this.properties, Collections.emptyList());
thenThrownBy(() -> parser.versionsFromBom(this.springCloudReleaseProject))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Pom is not present");
}
@Test
@@ -69,8 +68,7 @@ public class MavenBomParserTests {
public void should_throw_exception_when_cloud_pom_is_missing() {
BomParser parser = new MavenBomParser(this.properties, Collections.emptyList());
thenThrownBy(() -> parser.versionsFromBom(new File(".")))
.isInstanceOf(IllegalStateException.class)
thenThrownBy(() -> parser.versionsFromBom(new File("."))).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
}
@@ -81,8 +79,7 @@ public class MavenBomParserTests {
BomParser parser = new MavenBomParser(this.properties, Collections.emptyList());
thenThrownBy(() -> parser.versionsFromBom(this.springCloudReleaseProject))
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Pom is not present");
.isInstanceOf(IllegalStateException.class).hasMessageContaining("Pom is not present");
}
}

View File

@@ -46,12 +46,10 @@ public class PomReaderTests {
@Before
public void setup() throws URISyntaxException {
URI scRelease = GitRepoTests.class.getResource("/projects/spring-cloud-release")
.toURI();
URI scRelease = GitRepoTests.class.getResource("/projects/spring-cloud-release").toURI();
this.springCloudReleaseProject = new File(scRelease);
this.springCloudReleaseProjectPom = new File(scRelease.getPath(), "pom.xml");
this.empty = new File(
GitRepoTests.class.getResource("/projects/project/empty.xml").toURI());
this.empty = new File(GitRepoTests.class.getResource("/projects/project/empty.xml").toURI());
this.licenseFile = new File(scRelease.getPath(), "LICENSE.txt");
}
@@ -78,16 +76,14 @@ public class PomReaderTests {
@Test
public void should_throw_exception_when_file_is_invalid() {
thenThrownBy(() -> PomReader.readPom(this.licenseFile))
.hasMessageStartingWith("Failed to read file: ")
thenThrownBy(() -> PomReader.readPom(this.licenseFile)).hasMessageStartingWith("Failed to read file: ")
.hasCauseInstanceOf(XmlPullParserException.class);
}
@Test
public void should_throw_exception_when_file_is_empty() {
thenThrownBy(() -> PomReader.readPom(this.empty)).hasMessageStartingWith("File [")
.hasMessageContaining("] is empty")
.hasCauseInstanceOf(EOFException.class);
.hasMessageContaining("] is empty").hasCauseInstanceOf(EOFException.class);
}
}

View File

@@ -64,51 +64,40 @@ public class PomUpdaterTests {
}
@Test
public void should_not_update_pom_when_project_is_not_on_the_versions_list()
throws Exception {
public void should_not_update_pom_when_project_is_not_on_the_versions_list() throws Exception {
File springCloudReleasePom = file("/projects/spring-cloud-release");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudReleasePom,
this.versionsFromBom)).isFalse();
}
@Test
public void should_not_update_pom_when_project_with_parent_suffix_is_not_on_the_versions_list()
throws Exception {
File springCloud = pom("/projects/project", "pom_with_parent_suffix.xml");
BDDAssertions.then(
this.pomUpdater.shouldProjectBeUpdated(springCloud, this.versionsFromBom))
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudReleasePom, this.versionsFromBom))
.isFalse();
}
@Test
public void should_update_pom_for_project_with_suffix_when_project_is_on_the_versions_list()
throws Exception {
File springCloud = pom("/projects/project",
"pom_matching_with_parent_suffix.xml");
public void should_not_update_pom_when_project_with_parent_suffix_is_not_on_the_versions_list() throws Exception {
File springCloud = pom("/projects/project", "pom_with_parent_suffix.xml");
BDDAssertions.then(
this.pomUpdater.shouldProjectBeUpdated(springCloud, this.versionsFromBom))
.isTrue();
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloud, this.versionsFromBom)).isFalse();
}
@Test
public void should_update_pom_when_project_is_not_on_the_versions_list()
throws Exception {
public void should_update_pom_for_project_with_suffix_when_project_is_on_the_versions_list() throws Exception {
File springCloud = pom("/projects/project", "pom_matching_with_parent_suffix.xml");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloud, this.versionsFromBom)).isTrue();
}
@Test
public void should_update_pom_when_project_is_not_on_the_versions_list() throws Exception {
File springCloudSleuthPom = file("/projects/spring-cloud-sleuth");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom,
this.versionsFromBom)).isTrue();
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom, this.versionsFromBom)).isTrue();
}
@Test
public void should_not_update_pom_when_project_is_on_the_versions_list_but_there_is_no_pom()
throws Exception {
public void should_not_update_pom_when_project_is_on_the_versions_list_but_there_is_no_pom() throws Exception {
File springCloudSleuthPom = file("/projects/spring-cloud-sleuth/empty-folder");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom,
this.versionsFromBom)).isFalse();
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom, this.versionsFromBom))
.isFalse();
}
@Test
@@ -116,110 +105,85 @@ public class PomUpdaterTests {
File originalPom = pom("/projects/project");
File pomInTemp = tmpFile("/project/pom.xml");
ModelWrapper rootPom = model("foo");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isEqualTo(asString(originalPom));
}
@Test
public void should_update_the_pom_if_only_artifact_id_is_matched_in_the_root_pom()
throws Exception {
public void should_update_the_pom_if_only_artifact_id_is_matched_in_the_root_pom() throws Exception {
File originalPom = pom("/projects/project", "pom_matching_artifact.xml");
File pomInTemp = tmpFile("/project/pom_matching_artifact.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
}
@Test
public void should_update_the_pom_if_parent_is_matched_via_sc_build()
throws Exception {
public void should_update_the_pom_if_parent_is_matched_via_sc_build() throws Exception {
File originalPom = pom("/projects/project", "pom_matching_parent_v2.xml");
File pomInTemp = tmpFile("/project/pom_matching_parent_v2.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(originalPom)).isNotEqualTo(asString(storedPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.2");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.2");
}
@Test
public void should_update_the_pom_if_parent_is_matched_via_sc_dependencies_parent()
throws Exception {
public void should_update_the_pom_if_parent_is_matched_via_sc_dependencies_parent() throws Exception {
File originalPom = pom("/projects/project", "pom_matching_parent.xml");
File pomInTemp = tmpFile("/project/pom_matching_parent.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.2");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.2");
}
@Test
public void should_not_update_child_pom_when_project_is_not_on_the_versions_list()
throws Exception {
public void should_not_update_child_pom_when_project_is_not_on_the_versions_list() throws Exception {
File springCloudReleasePom = file("/projects/spring-cloud-release");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudReleasePom,
this.versionsFromBom)).isFalse();
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudReleasePom, this.versionsFromBom))
.isFalse();
}
@Test
public void should_update_child_pom_when_project_is_not_on_the_versions_list()
throws Exception {
public void should_update_child_pom_when_project_is_not_on_the_versions_list() throws Exception {
File springCloudSleuthPom = file("/projects/spring-cloud-sleuth");
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom,
this.versionsFromBom)).isTrue();
BDDAssertions.then(this.pomUpdater.shouldProjectBeUpdated(springCloudSleuthPom, this.versionsFromBom)).isTrue();
}
@Test
public void should_update_the_child_pom_if_parent_is_matched_via_sc_build()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_matching_parent_v2.xml");
public void should_update_the_child_pom_if_parent_is_matched_via_sc_build() throws Exception {
File originalPom = pom("/projects/project/children", "pom_matching_parent_v2.xml");
File pomInTemp = tmpFile("/project/children/pom_matching_parent_v2.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-foo.version", "1.3.1.BUILD-SNAPSHOT")
@@ -227,26 +191,20 @@ public class PomUpdaterTests {
}
@Test
public void should_update_the_parent_from_properties_even_if_group_ids_dont_match()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_different_group_boot_parent.xml");
public void should_update_the_parent_from_properties_even_if_group_ids_dont_match() throws Exception {
File originalPom = pom("/projects/project/children", "pom_different_group_boot_parent.xml");
File pomInTemp = tmpFile("/project/children/pom_different_group_boot_parent.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getProperties()).containsEntry("spring-cloud-sleuth.version",
"0.0.3.BUILD-SNAPSHOT");
}
@Test
@@ -255,137 +213,104 @@ public class PomUpdaterTests {
File originalPom = pom("/projects/project/children", "pom_different_group.xml");
File pomInTemp = tmpFile("/project/children/pom_different_group.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("1.5.8.RELEASE");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getProperties()).containsEntry("spring-cloud-sleuth.version",
"0.0.3.BUILD-SNAPSHOT");
}
@Test
public void should_update_everything_when_group_ids_dont_match_and_there_is_skip_deployment_property()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_different_group_skip_deployment_prop.xml");
File pomInTemp = tmpFile(
"/project/children/pom_different_group_skip_deployment_prop.xml");
File originalPom = pom("/projects/project/children", "pom_different_group_skip_deployment_prop.xml");
File pomInTemp = tmpFile("/project/children/pom_different_group_skip_deployment_prop.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("1.5.8.RELEASE");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getProperties()).containsEntry("spring-cloud-sleuth.version",
"0.0.3.BUILD-SNAPSHOT");
}
@Test
public void should_update_everything_when_group_ids_dont_match_and_there_is_skip_in_deployment_plugin()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_different_group_skip_deployment_plugin.xml");
File pomInTemp = tmpFile(
"/project/children/pom_different_group_skip_deployment_plugin.xml");
File originalPom = pom("/projects/project/children", "pom_different_group_skip_deployment_plugin.xml");
File pomInTemp = tmpFile("/project/children/pom_different_group_skip_deployment_plugin.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("1.5.8.RELEASE");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getProperties()).containsEntry("spring-cloud-sleuth.version",
"0.0.3.BUILD-SNAPSHOT");
}
@Test
public void should_update_everything_when_group_ids_dont_match_and_there_is_skip_in_deployment_plugin_management()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_different_group_skip_deployment_plugin_mngmnt.xml");
File pomInTemp = tmpFile(
"/project/children/pom_different_group_skip_deployment_plugin_mngmnt.xml");
File originalPom = pom("/projects/project/children", "pom_different_group_skip_deployment_plugin_mngmnt.xml");
File pomInTemp = tmpFile("/project/children/pom_different_group_skip_deployment_plugin_mngmnt.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("1.5.8.RELEASE");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("1.2.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("1.5.8.RELEASE");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getProperties()).containsEntry("spring-cloud-sleuth.version",
"0.0.3.BUILD-SNAPSHOT");
}
@Test
public void should_update_boot_parent_even_if_the_project_group_doesnt_match()
throws Exception {
File originalPom = pom("/projects/project/children",
"pom_case_from_contract.xml");
public void should_update_boot_parent_even_if_the_project_group_doesnt_match() throws Exception {
File originalPom = pom("/projects/project/children", "pom_case_from_contract.xml");
File pomInTemp = tmpFile("/project/children/pom_case_from_contract.xml");
ModelWrapper rootPom = model("spring-cloud-contract",
"org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper rootPom = model("spring-cloud-contract", "org.springframework.cloud");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.2.BUILD-SNAPSHOT");
}
@Test
public void should_update_the_child_pom_if_parent_is_matched_via_sc_dependencies_parent()
throws Exception {
public void should_update_the_child_pom_if_parent_is_matched_via_sc_dependencies_parent() throws Exception {
File originalPom = pom("/projects/project/children", "pom_matching_parent.xml");
File pomInTemp = tmpFile("/project/children/pom_matching_parent.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
// the rest is the same
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-foo.version", "1.3.1.BUILD-SNAPSHOT")
@@ -394,38 +319,30 @@ public class PomUpdaterTests {
@Test
public void should_update_the_child_pom_if_properties_are_matched() throws Exception {
File originalPom = pom("/projects/project/children",
"pom_matching_properties.xml");
File originalPom = pom("/projects/project/children", "pom_matching_properties.xml");
File pomInTemp = tmpFile("/project/children/pom_matching_properties.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.3.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getProperties())
.containsEntry("spring-cloud-sleuth.version", "0.0.3.BUILD-SNAPSHOT")
.containsEntry("spring-cloud-vault.version", "0.0.4.BUILD-SNAPSHOT");
}
@Test
public void should_override_a_pom_when_there_was_a_change_in_the_model()
throws Exception {
File beforeProcessing = pom("/projects/project/children",
"pom_matching_properties.xml");
public void should_override_a_pom_when_there_was_a_change_in_the_model() throws Exception {
File beforeProcessing = pom("/projects/project/children", "pom_matching_properties.xml");
File afterProcessing = tmpFile("/project/children/pom_matching_properties.xml");
ModelWrapper model = this.pomUpdater.updateModel(model("spring-cloud-sleuth"),
afterProcessing, this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(model("spring-cloud-sleuth"), afterProcessing,
this.versionsFromBom);
File processedPom = this.pomUpdater.overwritePomIfDirty(model,
VersionsFromBom.EMPTY_VERSION, afterProcessing);
File processedPom = this.pomUpdater.overwritePomIfDirty(model, VersionsFromBom.EMPTY_VERSION, afterProcessing);
String processedPomText = asString(processedPom);
String beforeProcessingText = asString(beforeProcessing);
@@ -433,51 +350,39 @@ public class PomUpdaterTests {
}
@Test
public void should_not_override_a_pom_when_there_was_no_change_in_the_model()
throws Exception {
public void should_not_override_a_pom_when_there_was_no_change_in_the_model() throws Exception {
File beforeProcessing = pom("/projects/project/");
File afterProcessing = tmpFile("/project/pom.xml");
ModelWrapper model = this.pomUpdater.updateModel(model("foo"), afterProcessing,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(model("foo"), afterProcessing, this.versionsFromBom);
File processedPom = this.pomUpdater.overwritePomIfDirty(model,
VersionsFromBom.EMPTY_VERSION, afterProcessing);
File processedPom = this.pomUpdater.overwritePomIfDirty(model, VersionsFromBom.EMPTY_VERSION, afterProcessing);
BDDAssertions.then(asString(processedPom)).isEqualTo(asString(beforeProcessing));
}
@Test
public void should_update_the_model_when_root_project_has_parent_suffix()
throws Exception {
public void should_update_the_model_when_root_project_has_parent_suffix() throws Exception {
File originalPom = pom("/projects/spring-cloud-contract");
File pomInTemp = tmpFile("/spring-cloud-contract/pom.xml");
ModelWrapper rootPom = model("spring-cloud-contract-parent");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isNotEqualTo(asString(originalPom));
Model overriddenPomModel = PomReader.readPom(storedPom);
BDDAssertions.then(overriddenPomModel.getVersion())
.isEqualTo("0.0.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion())
.isEqualTo("0.0.2");
BDDAssertions.then(overriddenPomModel.getVersion()).isEqualTo("0.0.2.BUILD-SNAPSHOT");
BDDAssertions.then(overriddenPomModel.getParent().getVersion()).isEqualTo("0.0.2");
}
@Test
public void should_not_update_the_model_when_project_uses_same_version_for_artifact()
throws Exception {
File originalPom = pom("/projects/project/",
"pom_matching_artifact_same_version.xml");
public void should_not_update_the_model_when_project_uses_same_version_for_artifact() throws Exception {
File originalPom = pom("/projects/project/", "pom_matching_artifact_same_version.xml");
File pomInTemp = tmpFile("/project/pom_matching_artifact_same_version.xml");
ModelWrapper rootPom = model("spring-cloud-sleuth");
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp,
this.versionsFromBom);
ModelWrapper model = this.pomUpdater.updateModel(rootPom, pomInTemp, this.versionsFromBom);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom,
pomInTemp);
File storedPom = this.pomUpdater.overwritePomIfDirty(model, this.versionsFromBom, pomInTemp);
BDDAssertions.then(asString(storedPom)).isEqualTo(asString(originalPom));
}
@@ -518,8 +423,7 @@ public class PomUpdaterTests {
}
private File pom(String relativePath, String pomName) throws URISyntaxException {
return new File(new File(GitRepoTests.class.getResource(relativePath).toURI()),
pomName);
return new File(new File(GitRepoTests.class.getResource(relativePath).toURI()), pomName);
}
private String asString(File file) throws IOException {

View File

@@ -36,13 +36,12 @@ public class ProjectPomUpdaterTests {
public void should_skip_any_steps_if_there_is_no_pom_xml() {
ReleaserProperties properties = SpringCloudReleaserProperties.get();
ProjectGitHandler handler = BDDMockito.mock(ProjectGitHandler.class);
ProjectPomUpdater updater = new ProjectPomUpdater(properties,
Collections.emptyList());
ProjectPomUpdater updater = new ProjectPomUpdater(properties, Collections.emptyList());
updater.updateProjectFromReleaseTrain(new File("target"), new Projects(),
new ProjectVersion("foo", "1.0.0.RELEASE"), false);
BDDMockito.then(handler).shouldHaveZeroInteractions();
BDDMockito.then(handler).shouldHaveNoInteractions();
}
}

View File

@@ -42,10 +42,8 @@ public class ProjectVersionTests {
@Before
public void setup() throws URISyntaxException {
URI scRelease = GitRepoTests.class.getResource("/projects/spring-cloud-release")
.toURI();
URI scContract = GitRepoTests.class.getResource("/projects/spring-cloud-contract")
.toURI();
URI scRelease = GitRepoTests.class.getResource("/projects/spring-cloud-release").toURI();
URI scContract = GitRepoTests.class.getResource("/projects/spring-cloud-contract").toURI();
this.springCloudReleaseProject = new File(scRelease.getPath(), "pom.xml");
this.springCloudContract = new File(scContract.getPath(), "pom.xml");
}
@@ -60,8 +58,7 @@ public class ProjectVersionTests {
@Test
public void should_build_version_from_file() {
ProjectVersion projectVersion = new ProjectVersion(
this.springCloudReleaseProject);
ProjectVersion projectVersion = new ProjectVersion(this.springCloudReleaseProject);
then(projectVersion.version).isEqualTo("Dalston.BUILD-SNAPSHOT");
then(projectVersion.projectName).isEqualTo("spring-cloud-starter-build");
@@ -86,8 +83,8 @@ public class ProjectVersionTests {
public void should_throw_exception_if_version_is_not_long_enough() {
String version = "1";
thenThrownBy(() -> projectVersion(version).bumpedVersion())
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
thenThrownBy(() -> projectVersion(version).bumpedVersion()).isInstanceOf(IllegalStateException.class)
.hasMessageContaining(
"Version [1] is invalid. Should be of format [1.2.3.A] / [1.2.3-A] or [A.B] / [A-B]");
}
@@ -143,8 +140,8 @@ public class ProjectVersionTests {
public void should_throw_exception_when_trying_to_get_major_from_invalid_version() {
String version = "1";
thenThrownBy(() -> projectVersion(version).major())
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
thenThrownBy(() -> projectVersion(version).major()).isInstanceOf(IllegalStateException.class)
.hasMessageContaining(
"Version [1] is invalid. Should be of format [1.2.3.A] / [1.2.3-A] or [A.B] / [A-B]");
}
@@ -163,88 +160,70 @@ public class ProjectVersionTests {
@Test
public void should_not_bump_version_by_patch_version_when_non_ga_or_sr() {
then(projectVersion("1.0.1-SNAPSHOT").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-M1").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-RC1").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("Finchley-SR1").postReleaseSnapshotVersion())
.isEqualTo("Finchley-SNAPSHOT");
then(projectVersion("1.0.1-SNAPSHOT").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-M1").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-RC1").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("Finchley-SR1").postReleaseSnapshotVersion()).isEqualTo("Finchley-SNAPSHOT");
}
@Test
public void should_not_bump_version_by_patch_version_when_non_ga_or_sr_with_hyphen() {
then(projectVersion("1.0.1-SNAPSHOT").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-M1").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-RC1").postReleaseSnapshotVersion())
.isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("Finchley-SR1").postReleaseSnapshotVersion())
.isEqualTo("Finchley-SNAPSHOT");
then(projectVersion("1.0.1-SNAPSHOT").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-M1").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("1.0.1-RC1").postReleaseSnapshotVersion()).isEqualTo("1.0.1-SNAPSHOT");
then(projectVersion("Finchley-SR1").postReleaseSnapshotVersion()).isEqualTo("Finchley-SNAPSHOT");
}
@Test
public void should_bump_version_by_patch_version_when_bumping_snapshots_for_ga() {
then(projectVersion("1.0.1-RELEASE").postReleaseSnapshotVersion())
.isEqualTo("1.0.2-SNAPSHOT");
then(projectVersion("1.0.1-RELEASE").postReleaseSnapshotVersion()).isEqualTo("1.0.2-SNAPSHOT");
}
@Test
public void should_return_the_previous_version_for_release_train_version_when_bumping_snapshots() {
String version = "Edgware-SNAPSHOT";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("Edgware-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("Edgware-SNAPSHOT");
}
@Test
public void should_return_the_previous_version_for_hyphen_release_train_version_when_bumping_snapshots() {
String version = "Edgware-SNAPSHOT";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("Edgware-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("Edgware-SNAPSHOT");
}
@Test
public void should_bump_version_by_patch_version_when_bumping_releases() {
String version = "1.0.1-RELEASE";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("1.0.2-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("1.0.2-SNAPSHOT");
}
@Test
public void should_bump_version_by_patch_version_when_bumping_releases_with_hyphen() {
String version = "1.0.1-RELEASE";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("1.0.2-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("1.0.2-SNAPSHOT");
version = "3.1.0";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("3.1.1-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("3.1.1-SNAPSHOT");
version = "3.0.0";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("3.0.1-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("3.0.1-SNAPSHOT");
version = "2.0.0";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("2.0.1-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("2.0.1-SNAPSHOT");
version = "3.0.1";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("3.0.2-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("3.0.2-SNAPSHOT");
}
@Test
public void should_return_the_previous_version_for_release_train_version_when_bumping_releases() {
String version = "Edgware-RELEASE";
then(projectVersion(version).postReleaseSnapshotVersion())
.isEqualTo("Edgware-SNAPSHOT");
then(projectVersion(version).postReleaseSnapshotVersion()).isEqualTo("Edgware-SNAPSHOT");
}
@Test
@@ -407,8 +386,7 @@ public class ProjectVersionTests {
String thisVersion = "1.3.2-SR3";
String thatVersion = "1.3.1-SR3";
then(projectVersion(thisVersion).compareTo(projectVersion(thatVersion)))
.isPositive();
then(projectVersion(thisVersion).compareTo(projectVersion(thatVersion))).isPositive();
}
@Test
@@ -416,117 +394,72 @@ public class ProjectVersionTests {
String thisVersion = "1.3.0-RC3";
String thatVersion = "1.3.1-RC3";
then(projectVersion(thisVersion).compareTo(projectVersion(thatVersion)))
.isNegative();
then(projectVersion(thisVersion).compareTo(projectVersion(thatVersion))).isNegative();
}
@Test
public void should_compare_builds_in_terms_of_maturity_for_projects() {
String thisVersion = "1.3.2.RELEASE";
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-SNAPSHOT")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1.RELEASE")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-SNAPSHOT")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1-RC1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.1.RELEASE"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.3.3-RC1"))).isTrue();
}
@Test
public void should_compare_builds_in_terms_of_maturity_for_trains() {
String thisVersion = "Hoxton-SR1";
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-SNAPSHOT")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton.RELEASE")))
.isTrue();
then(projectVersion(thisVersion)
.isMoreMature(projectVersion("Iexample-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SR1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-RC1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton.RELEASE"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-RC1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SR1"))).isFalse();
thisVersion = "Hoxton-SNAPSHOT";
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-SNAPSHOT")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-M1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-RC1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton.RELEASE")))
.isFalse();
then(projectVersion(thisVersion)
.isMoreMature(projectVersion("Iexample-SNAPSHOT"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-M1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-RC1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SR1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-SNAPSHOT"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-M1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton-RC1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Hoxton.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SNAPSHOT"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-M1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-RC1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("Iexample-SR1"))).isFalse();
thisVersion = "1.0.1.RELEASE";
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-SNAPSHOT")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SNAPSHOT")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-M1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-RC1")))
.isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SR1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-RC1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SNAPSHOT"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-M1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-RC1"))).isTrue();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SR1"))).isFalse();
thisVersion = "1.0.1-SNAPSHOT";
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-SNAPSHOT")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-M1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-RC1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SNAPSHOT")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-M1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-RC1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2.RELEASE")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SR1")))
.isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-SNAPSHOT"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-M1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1-RC1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.1.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SNAPSHOT"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-M1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-RC1"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2.RELEASE"))).isFalse();
then(projectVersion(thisVersion).isMoreMature(projectVersion("1.0.2-SR1"))).isFalse();
}
@Test
@@ -711,31 +644,26 @@ public class ProjectVersionTests {
@Test
public void should_return_snapshot_unacceptable_patterns_for_a_milestone_or_rc_version() {
List<Pattern> milestonePatterns = projectVersion("1.0.0-M1")
.unacceptableVersionPatterns();
List<Pattern> milestonePatterns = projectVersion("1.0.0-M1").unacceptableVersionPatterns();
then(milestonePatterns).isNotEmpty();
then(milestonePatterns.get(0).pattern()).contains("SNAPSHOT");
List<Pattern> rcPatterns = projectVersion("1.0.0-RC1")
.unacceptableVersionPatterns();
List<Pattern> rcPatterns = projectVersion("1.0.0-RC1").unacceptableVersionPatterns();
then(rcPatterns).isNotEmpty();
then(rcPatterns.get(0).pattern()).contains("SNAPSHOT");
List<Pattern> milestonePatternsWithDash = projectVersion("1.0.0-M1")
.unacceptableVersionPatterns();
List<Pattern> milestonePatternsWithDash = projectVersion("1.0.0-M1").unacceptableVersionPatterns();
then(milestonePatternsWithDash).isNotEmpty();
then(milestonePatternsWithDash.get(0).pattern()).contains("SNAPSHOT");
List<Pattern> rcPatternsWithDash = projectVersion("1.0.0-RC1")
.unacceptableVersionPatterns();
List<Pattern> rcPatternsWithDash = projectVersion("1.0.0-RC1").unacceptableVersionPatterns();
then(rcPatternsWithDash).isNotEmpty();
then(rcPatternsWithDash.get(0).pattern()).contains("SNAPSHOT");
}
@Test
public void should_return_snapshot_milestone_rc_unacceptable_patterns_for_a_ga_or_sr_version() {
List<Pattern> gaPatterns = projectVersion("1.0.0.RELEASE")
.unacceptableVersionPatterns();
List<Pattern> gaPatterns = projectVersion("1.0.0.RELEASE").unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(gaPatterns);
gaPatterns = projectVersion("1.0.0").unacceptableVersionPatterns();
@@ -744,24 +672,19 @@ public class ProjectVersionTests {
gaPatterns = projectVersion("1.0.0-RELEASE").unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(gaPatterns);
List<Pattern> srPatterns = projectVersion("1.0.0-SR1")
.unacceptableVersionPatterns();
List<Pattern> srPatterns = projectVersion("1.0.0-SR1").unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(srPatterns);
List<Pattern> srPatternsWithDash = projectVersion("1.0.0-SR1")
.unacceptableVersionPatterns();
List<Pattern> srPatternsWithDash = projectVersion("1.0.0-SR1").unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(srPatternsWithDash);
List<Pattern> unknownTypeOfVersion = projectVersion("1.0.0.SOMETHING")
.unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(
unknownTypeOfVersion);
List<Pattern> unknownTypeOfVersion = projectVersion("1.0.0.SOMETHING").unacceptableVersionPatterns();
thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(unknownTypeOfVersion);
}
@Test
public void should_return_v100RELEASE_when_tag_name_is_requested() {
then(projectVersion("1.0.0.RELEASE").releaseTagName())
.isEqualTo("v1.0.0.RELEASE");
then(projectVersion("1.0.0.RELEASE").releaseTagName()).isEqualTo("v1.0.0.RELEASE");
}
@Test
@@ -771,93 +694,77 @@ public class ProjectVersionTests {
@Test
public void should_return_decremented_patch_when_patch_above_zero() {
then(projectVersion("1.2.3.RELEASE").computePreviousPatchTag("v", "RELEASE"))
.contains("v1.2.2.RELEASE");
then(projectVersion("1.2.3.RELEASE").computePreviousPatchTag("v", "RELEASE")).contains("v1.2.2.RELEASE");
}
@Test
public void should_use_current_suffix_if_no_forced_suffix() {
then(projectVersion("1.2.3.WHATEVER").computePreviousPatchTag("v", ""))
.contains("v1.2.2.WHATEVER");
then(projectVersion("1.2.3.WHATEVER").computePreviousPatchTag("v", "")).contains("v1.2.2.WHATEVER");
}
@Test
public void should_replace_suffix() {
then(projectVersion("1.2.3.WHATEVER").computePreviousPatchTag("v", "RELEASE"))
.contains("v1.2.2.RELEASE");
then(projectVersion("1.2.3.WHATEVER").computePreviousPatchTag("v", "RELEASE")).contains("v1.2.2.RELEASE");
}
@Test
public void should_return_empty_when_patch_at_zero() {
then(projectVersion("1.2.0.WHATEVER").computePreviousPatchTag("v", "RELEASE"))
.isEmpty();
then(projectVersion("1.2.0.WHATEVER").computePreviousPatchTag("v", "RELEASE")).isEmpty();
}
@Test
public void should_return_minor_pattern_when_minor_above_zero() {
then(projectVersion("1.2.0.WHATEVER")
.computePreviousMinorTagPattern("v", "RELEASE").get().pattern())
.isEqualTo("\\Qv1.1.\\E\\d+\\Q.RELEASE\\E");
then(projectVersion("1.2.0.WHATEVER").computePreviousMinorTagPattern("v", "RELEASE").get().pattern())
.isEqualTo("\\Qv1.1.\\E\\d+\\Q.RELEASE\\E");
}
@Test
public void should_compute_minor_pattern_with_current_suffix_if_no_forced_suffix() {
then(projectVersion("1.2.0.WHATEVER").computePreviousMinorTagPattern("v", "")
.get().pattern()).isEqualTo("\\Qv1.1.\\E\\d+\\Q.WHATEVER\\E");
then(projectVersion("1.2.0.WHATEVER").computePreviousMinorTagPattern("v", "").get().pattern())
.isEqualTo("\\Qv1.1.\\E\\d+\\Q.WHATEVER\\E");
}
@Test
public void should_return_empty_minor_pattern_when_minor_zero() {
then(projectVersion("1.0.0.WHATEVER").computePreviousMinorTagPattern("v",
"RELEASE")).isEmpty();
then(projectVersion("1.0.0.WHATEVER").computePreviousMinorTagPattern("v", "RELEASE")).isEmpty();
}
@Test
public void should_return_major_pattern_when_major_above_zero() {
then(projectVersion("1.0.0.WHATEVER")
.computePreviousMajorTagPattern("v", "RELEASE").pattern())
.isEqualTo("\\Qv0.\\E\\d+\\Q.\\E\\d+\\Q.RELEASE\\E");
then(projectVersion("1.0.0.WHATEVER").computePreviousMajorTagPattern("v", "RELEASE").pattern())
.isEqualTo("\\Qv0.\\E\\d+\\Q.\\E\\d+\\Q.RELEASE\\E");
}
@Test
public void should_compute_major_pattern_with_current_suffix_if_no_forced_suffix() {
then(projectVersion("1.0.0.WHATEVER").computePreviousMajorTagPattern("v", "")
.pattern()).isEqualTo("\\Qv0.\\E\\d+\\Q.\\E\\d+\\Q.WHATEVER\\E");
then(projectVersion("1.0.0.WHATEVER").computePreviousMajorTagPattern("v", "").pattern())
.isEqualTo("\\Qv0.\\E\\d+\\Q.\\E\\d+\\Q.WHATEVER\\E");
}
@Test
public void should_throw_major_pattern_when_major_zero() {
assertThatIllegalArgumentException()
.isThrownBy(() -> projectVersion("0.0.1.WHATEVER")
.computePreviousMajorTagPattern("v", "RELEASE"));
.isThrownBy(() -> projectVersion("0.0.1.WHATEVER").computePreviousMajorTagPattern("v", "RELEASE"));
}
private void thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(
List<Pattern> unknownTypeOfVersion) {
private void thenPatternsForSnapshotMilestoneAndReleaseCandidateArePresent(List<Pattern> unknownTypeOfVersion) {
then(unknownTypeOfVersion).isNotEmpty();
then(unknownTypeOfVersion.get(0).pattern()).contains("SNAPSHOT");
then(unknownTypeOfVersion.get(1).pattern()).contains("M[0-9]");
then(unknownTypeOfVersion.get(2).pattern()).contains("RC");
then(unknownTypeOfVersion.get(0).matcher("SomeName-SNAPSHOT").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(0).matcher("SomeName.BUILD-SNAPSHOT").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(0)
.matcher("\t\t<version>1.19.2-SNAPSHOT</version>\n").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(0).matcher("SomeName-SNAPSHOT").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(0).matcher("SomeName.BUILD-SNAPSHOT").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(0).matcher("\t\t<version>1.19.2-SNAPSHOT</version>\n").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(1).matcher("SomeName-M3").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(1).matcher("SomeName.M3").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(1)
.matcher("\t\t<zipkin.version>1.19.2-M2</zipkin.version>\n").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(1).matcher("\t\t<zipkin.version>1.19.2-M2</zipkin.version>\n").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(2).matcher("SomeName-RC3").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(2).matcher("SomeName.RC3").lookingAt()).isTrue();
then(unknownTypeOfVersion.get(2)
.matcher("<zipkin.version>1.19.2-RC1</zipkin.version>").lookingAt())
.isTrue();
then(unknownTypeOfVersion.get(2).matcher("<zipkin.version>1.19.2-RC1</zipkin.version>").lookingAt()).isTrue();
}
private ProjectVersion projectVersion(String version) {

View File

@@ -71,8 +71,7 @@ public class ProjectsTests {
projectVersions.add(new ProjectVersion("spring-boot-starter-build", "1.0.0"));
Projects projects = new Projects(projectVersions);
then(projects.forNameStartingWith("spring-boot").get(0).version)
.isEqualTo("1.0.0");
then(projects.forNameStartingWith("spring-boot").get(0).version).isEqualTo("1.0.0");
}
@Test
@@ -82,25 +81,18 @@ public class ProjectsTests {
projectVersions.add(build);
ProjectVersion boot = new ProjectVersion("spring-boot-starter", "2.0.0-RELEASE");
projectVersions.add(boot);
ProjectVersion bootDeps = new ProjectVersion("spring-boot-dependencies",
"2.0.0.RELEASE");
ProjectVersion bootDeps = new ProjectVersion("spring-boot-dependencies", "2.0.0.RELEASE");
projectVersions.add(bootDeps);
ProjectVersion original = new ProjectVersion("spring-cloud-starter-foo",
"3.0.0.BUILD-SNAPSHOT");
ProjectVersion original = new ProjectVersion("spring-cloud-starter-foo", "3.0.0.BUILD-SNAPSHOT");
projectVersions.add(original);
Projects projects = new Projects(projectVersions);
Projects forRollback = Projects.forRollback(SpringCloudReleaserProperties.get(),
projects);
Projects forRollback = Projects.forRollback(SpringCloudReleaserProperties.get(), projects);
then(forRollback.forName("spring-cloud-build").version)
.isEqualTo("1.0.1-SNAPSHOT");
then(forRollback.forName("spring-boot-starter").version)
.isEqualTo("2.0.0-RELEASE");
then(forRollback.forName("spring-boot-dependencies").version)
.isEqualTo("2.0.0.RELEASE");
then(forRollback.forName("spring-cloud-starter-foo").version)
.isEqualTo("3.0.0.BUILD-SNAPSHOT");
then(forRollback.forName("spring-cloud-build").version).isEqualTo("1.0.1-SNAPSHOT");
then(forRollback.forName("spring-boot-starter").version).isEqualTo("2.0.0-RELEASE");
then(forRollback.forName("spring-boot-dependencies").version).isEqualTo("2.0.0.RELEASE");
then(forRollback.forName("spring-cloud-starter-foo").version).isEqualTo("3.0.0.BUILD-SNAPSHOT");
}
@Test
@@ -149,8 +141,7 @@ public class ProjectsTests {
@Test
public void should_return_projects_with_bumped_versions() {
Set<ProjectVersion> projectVersions = new HashSet<>();
projectVersions
.add(new ProjectVersion("spring-boot-dependencies", "2.0.0.RELEASE"));
projectVersions.add(new ProjectVersion("spring-boot-dependencies", "2.0.0.RELEASE"));
projectVersions.add(new ProjectVersion("spring-boot-starter", "2.0.0.RELEASE"));
projectVersions.add(new ProjectVersion("foo", "1.0.0.RELEASE"));
projectVersions.add(new ProjectVersion("bar", "1.0.1.M1"));
@@ -160,11 +151,9 @@ public class ProjectsTests {
projectVersions.add(new ProjectVersion("foo4", "Finchley.SR4"));
Projects projects = new Projects(projectVersions);
Projects bumped = projects
.postReleaseSnapshotVersion(Collections.singletonList("spring-boot"));
Projects bumped = projects.postReleaseSnapshotVersion(Collections.singletonList("spring-boot"));
then(bumped.forName("spring-boot-dependencies").version)
.isEqualTo("2.0.0.RELEASE");
then(bumped.forName("spring-boot-dependencies").version).isEqualTo("2.0.0.RELEASE");
then(bumped.forName("spring-boot-starter").version).isEqualTo("2.0.0.RELEASE");
then(bumped.forName("foo").version).isEqualTo("1.0.1.SNAPSHOT");
then(bumped.forName("bar").version).isEqualTo("1.0.1.SNAPSHOT");
@@ -180,9 +169,8 @@ public class ProjectsTests {
projectVersions.add(new ProjectVersion("foo", "1.0.0"));
Projects projects = new Projects(projectVersions);
thenThrownBy(() -> projects.forFile(this.springCloudReleasePom))
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
"Project with name [spring-cloud-starter-build] is not present");
thenThrownBy(() -> projects.forFile(this.springCloudReleasePom)).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Project with name [spring-cloud-starter-build] is not present");
}
@Test
@@ -191,9 +179,8 @@ public class ProjectsTests {
projectVersions.add(new ProjectVersion("foo", "1.0.0"));
Projects projects = new Projects(projectVersions);
thenThrownBy(() -> projects.forName("spring-cloud-starter-build"))
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
"Project with name [spring-cloud-starter-build] is not present");
thenThrownBy(() -> projects.forName("spring-cloud-starter-build")).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("Project with name [spring-cloud-starter-build] is not present");
}
@Test
@@ -224,9 +211,8 @@ public class ProjectsTests {
projectVersions.add(new ProjectVersion("foo", "1.0.0"));
Projects projects = new Projects(projectVersions);
thenThrownBy(() -> projects.releaseTrain(properties))
.isInstanceOf(IllegalStateException.class).hasMessageContaining(
"don't contain any of the following release train names");
thenThrownBy(() -> projects.releaseTrain(properties)).isInstanceOf(IllegalStateException.class)
.hasMessageContaining("don't contain any of the following release train names");
}
private File file(String relativePath) {

Some files were not shown because too many files have changed in this diff Show More