|
| 1 | +package net.coding.ide.git.rebase; |
| 2 | + |
| 3 | +import net.coding.ide.model.RebaseResponse; |
| 4 | +import org.eclipse.jgit.api.Git; |
| 5 | +import org.eclipse.jgit.api.RebaseCommand; |
| 6 | +import org.eclipse.jgit.api.RebaseResult; |
| 7 | +import org.eclipse.jgit.api.errors.GitAPIException; |
| 8 | +import org.eclipse.jgit.lib.RebaseTodoLine; |
| 9 | +import org.eclipse.jgit.lib.Repository; |
| 10 | +import org.eclipse.jgit.util.IO; |
| 11 | + |
| 12 | +import java.io.File; |
| 13 | +import java.io.IOException; |
| 14 | + |
| 15 | +import static net.coding.ide.utils.RebaseStateUtils.createFile; |
| 16 | +import static net.coding.ide.utils.RebaseStateUtils.getRebaseFile; |
| 17 | + |
| 18 | +/** |
| 19 | + * Created by tan on 28/03/2017. |
| 20 | + */ |
| 21 | +public class SquashActionHandler implements RebaseActionHandler { |
| 22 | + |
| 23 | + @Override |
| 24 | + public RebaseTodoLine.Action getAction() { |
| 25 | + return RebaseTodoLine.Action.SQUASH; |
| 26 | + } |
| 27 | + |
| 28 | + @Override |
| 29 | + public RebaseResponse process(Repository repository, String message) throws GitAPIException, IOException { |
| 30 | + |
| 31 | + try (Git git = Git.wrap(repository)) { |
| 32 | + git.commit() |
| 33 | + .setMessage(stripCommentLines(message)) |
| 34 | + .setAmend(true).setNoVerify(true).call(); |
| 35 | + |
| 36 | + getRebaseFile(repository, MESSAGE_SQUASH).delete(); |
| 37 | + getRebaseFile(repository, MESSAGE_FIXUP).delete(); |
| 38 | + |
| 39 | + createFile(repository, MESSAGE, message); |
| 40 | + |
| 41 | + RebaseResult result = git.rebase() |
| 42 | + .setOperation(RebaseCommand.Operation.SKIP) |
| 43 | + .runInteractively(handler) |
| 44 | + .call(); |
| 45 | + |
| 46 | + return new RebaseResponse(result); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + @Override |
| 51 | + public RebaseResponse extractMessage(Repository repository) throws IOException { |
| 52 | + File messageFile = getRebaseFile(repository, MESSAGE_SQUASH); |
| 53 | + RebaseResponse response = new RebaseResponse(false, RebaseResponse.Status.INTERACTIVE_EDIT); |
| 54 | + |
| 55 | + if (messageFile.exists()) { |
| 56 | + response.setMessage(new String(IO.readFully(messageFile))); |
| 57 | + } |
| 58 | + |
| 59 | + return response; |
| 60 | + } |
| 61 | + |
| 62 | + /** |
| 63 | + * @param commitMessage |
| 64 | + * |
| 65 | + * @return |
| 66 | + * |
| 67 | + * @see RebaseCommand#stripCommentLines |
| 68 | + */ |
| 69 | + private static String stripCommentLines(String commitMessage) { |
| 70 | + StringBuilder result = new StringBuilder(); |
| 71 | + for (String line : commitMessage.split("\n")) { //$NON-NLS-1$ |
| 72 | + if (!line.trim().startsWith("#")) //$NON-NLS-1$ |
| 73 | + result.append(line).append("\n"); //$NON-NLS-1$ |
| 74 | + } |
| 75 | + if (!commitMessage.endsWith("\n")) //$NON-NLS-1$ |
| 76 | + result.deleteCharAt(result.length() - 1); |
| 77 | + return result.toString(); |
| 78 | + } |
| 79 | +} |
0 commit comments