diff --git a/src/test/java/org/jenkinsci/plugins/sonargerrit/test_infrastructure/gerrit/GerritGit.java b/src/test/java/org/jenkinsci/plugins/sonargerrit/test_infrastructure/gerrit/GerritGit.java index 02376b1..9e7fcb6 100644 --- a/src/test/java/org/jenkinsci/plugins/sonargerrit/test_infrastructure/gerrit/GerritGit.java +++ b/src/test/java/org/jenkinsci/plugins/sonargerrit/test_infrastructure/gerrit/GerritGit.java @@ -6,6 +6,7 @@ import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; +import java.util.Arrays; import java.util.UUID; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -15,11 +16,14 @@ import org.eclipse.jgit.api.Git; import org.eclipse.jgit.api.ResetCommand; import org.eclipse.jgit.api.errors.GitAPIException; +import org.eclipse.jgit.lib.Constants; import org.eclipse.jgit.lib.PersonIdent; +import org.eclipse.jgit.lib.Repository; import org.eclipse.jgit.transport.RefSpec; /** @author RĂ©da Housni Alaoui */ public class GerritGit { + private static final String CHANGE_ID = "Change-Id"; private final GerritServer gerrit; private final Git git; @@ -55,11 +59,29 @@ public Path workTree() { return git.getRepository().getWorkTree().toPath(); } - public CommitCommand commit(String message, boolean amend) { - String changeId = "I" + DigestUtils.sha1Hex(String.format("%s|%s", UUID.randomUUID(), message)); + public CommitCommand commit(String message, boolean amend) throws IOException { + String changeId = null; + if (amend) { + Repository repository = git.getRepository(); + String previousMessage = + repository.parseCommit(repository.resolve(Constants.HEAD)).getFullMessage(); + changeId = + Arrays.stream(previousMessage.split("\n")) + .filter(msg -> msg.startsWith(CHANGE_ID)) + .findFirst() + .orElse(null); + } + + if (changeId == null) { + changeId = + CHANGE_ID + + ": I" + + DigestUtils.sha1Hex(String.format("%s|%s", UUID.randomUUID(), message)); + } + return git.commit() .setAmend(amend) - .setMessage(message + "\n\nChange-Id: " + changeId) + .setMessage(message + "\n\n" + changeId) .setAuthor(agent) .setCommitter(agent); }