Skip to content

Commit

Permalink
Reuse Change-Id from previous commit on amend
Browse files Browse the repository at this point in the history
  • Loading branch information
mtughan committed Sep 5, 2024
1 parent 19458c3 commit cf6f65c
Showing 1 changed file with 25 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -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);
}
Expand Down

0 comments on commit cf6f65c

Please sign in to comment.