Skip to content

Instantly share code, notes, and snippets.

@Maddoc42
Created July 10, 2016 21:20
Show Gist options
  • Save Maddoc42/83f32a4c6517684b0976de650764b25e to your computer and use it in GitHub Desktop.
Save Maddoc42/83f32a4c6517684b0976de650764b25e to your computer and use it in GitHub Desktop.
package org.faudroids.testing;
import org.eclipse.jgit.api.Git;
import org.eclipse.jgit.api.ResetCommand;
import org.eclipse.jgit.api.Status;
import org.eclipse.jgit.lib.Ref;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.revwalk.RevCommit;
import org.eclipse.jgit.storage.file.FileRepositoryBuilder;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class GitClient {
private final Git client;
public GitClient(String remoteUrl, File targetDir) throws Exception {
client = Git.cloneRepository()
.setURI(remoteUrl)
.setDirectory(targetDir)
.call();
}
public GitClient(File repoDir) throws Exception {
Repository repository = FileRepositoryBuilder.create(new File(repoDir, ".git"));
this.client = new Git(repository);
}
public void commitAllChanges(String commitMsg) throws Exception {
System.out.println(client.getRepository().getDirectory().getAbsolutePath());
client
.add()
.addFilepattern(".")
.call();
client.commit().setMessage(commitMsg).call();
}
public List<String> log() throws Exception {
Iterable<RevCommit> logs = client.log().call();
List<String> result = new ArrayList<>();
for (RevCommit log : logs) result.add(log.getShortMessage());
return result;
}
public List<String> branch() throws Exception {
Iterable<Ref> branches = client.branchList().call();
List<String> result = new ArrayList<>();
for (Ref branch : branches) result.add(branch.getName());
return result;
}
public void pull() throws Exception {
client.pull().call();
}
public void push() throws Exception {
client.push().call();
}
public Status status() throws Exception {
return client.status().call();
}
public void checkoutBranch(String branchName) throws Exception {
client.checkout().setName(branchName).call();
}
public void resetHard() throws Exception {
client.reset().setMode(ResetCommand.ResetType.HARD).call();
client.clean().setCleanDirectories(true).call();
}
public static String refToBranchName(String ref) {
return ref.replace("refs/master/", "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment