Skip to content

Instantly share code, notes, and snippets.

@malte0811
Last active June 11, 2019 09:28
Show Gist options
  • Save malte0811/4862fffe175f254391b0b47de0fd5dbe to your computer and use it in GitHub Desktop.
Save malte0811/4862fffe175f254391b0b47de0fd5dbe to your computer and use it in GitHub Desktop.
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Scanner;
public class Recommit
{
private static Process runAndWait(String cmd) throws InterruptedException, IOException
{
Runtime r = Runtime.getRuntime();
Process p = r.exec(cmd);
if (p.waitFor()!=0) {
InputStream cout = p.getInputStream();
Scanner s = new Scanner(cout).useDelimiter("\\A");
if (s.hasNext())
System.out.println(s.next());
InputStream cerr = p.getErrorStream();
s = new Scanner(cerr).useDelimiter("\\A");
if (s.hasNext())
System.err.println(s.next());
throw new RuntimeException("Command \""+cmd+"\" failed");
}
return p;
}
private static String getOutputFor(String cmd) throws IOException, InterruptedException
{
Process p = runAndWait(cmd);
InputStream cout = p.getInputStream();
Scanner s = new Scanner(cout).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
private static String getLastCommitHash() throws Exception {
return getOutputFor("git log -1 --format=%H");
}
private static List<String> getFilesToCommit() throws IOException, InterruptedException
{
String gitOut = getOutputFor("git status --porcelain");
String[] lines = gitOut.split("[\\r\\n]+");
List<String> ret = new ArrayList<>();
for (String file:lines) {
if (file.startsWith("??"))
continue;
ret.add(file.substring(file.lastIndexOf(' ')+1));
}
return ret;
}
private static void revertCommit() throws IOException, InterruptedException
{
runAndWait("git reset --soft HEAD~1");
}
private static void runActionForFiles(String action, List<String> files) throws IOException, InterruptedException
{
StringBuilder cmd = new StringBuilder("git "+action);
for (String f:files) {
cmd.append(' ').append(f);
}
runAndWait(cmd.toString());
}
private static void commitLike(String commitToImmitate) throws IOException, InterruptedException
{
runAndWait("git commit --reuse-message="+commitToImmitate);
}
public static void main(String[] args) throws Exception {
String lastHash = getLastCommitHash();
revertCommit();
List<String> changed = getFilesToCommit();
runActionForFiles("reset HEAD", changed);
runActionForFiles("add", changed);
commitLike(lastHash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment