List of usage examples for org.eclipse.jgit.api Git getRepository
public Repository getRepository()
From source file:ru.nikitenkogleb.androidtools.newappwizard.GitSupport.java
/** Creates new Git Support module */ public GitSupport(String login, String password, String repository, String projectPath, String tempFolder, String initBranch) {//w w w . j av a2 s .co m final String home = System.getProperty("user.home"); if (login == null || login.isEmpty()) { mSshConfigCallback = new SSHConfigCallback(home + Path.SEPARATOR + ".ssh" + Path.SEPARATOR + "id_rsa", new CredentialsProvider(password)); mHttpsCredentialsProvider = null; } else { mSshConfigCallback = null; mHttpsCredentialsProvider = new UsernamePasswordCredentialsProvider(login, password); } try { final CloneCommand cloneCommand = Git.cloneRepository().setURI(repository) .setDirectory(new File(tempFolder)); if (mSshConfigCallback != null) cloneCommand.setTransportConfigCallback(mSshConfigCallback); else cloneCommand.setCredentialsProvider(mHttpsCredentialsProvider); final Git mGit = cloneCommand.call(); try { mGit.checkout().setCreateBranch(true).setName(initBranch).call(); } catch (RefNotFoundException e) { e.printStackTrace(); final StoredConfig config = mGit.getRepository().getConfig(); config.setString("remote", "origin", "url", repository); config.save(); } mGit.close(); move(new File(tempFolder + "/.git"), new File(projectPath + "/.git")); move(new File(tempFolder + "/README.md"), new File(projectPath + "/README.md")); move(new File(tempFolder + "/LICENSE"), new File(projectPath + "/LICENSE")); move(new File(tempFolder + "/.gitignore"), new File(projectPath + "/.gitignore")); new File(tempFolder).delete(); mProjectPath = projectPath; } catch (GitAPIException | IOException e) { e.printStackTrace(); } }
From source file:se.kth.karamel.backend.github.GithubApi.java
/** * Clone an existing github repo./*from w ww.j a v a2 s. c o m*/ * * @param owner * @param repoName * @throws se.kth.karamel.common.exception.KaramelException */ public synchronized static void cloneRepo(String owner, String repoName) throws KaramelException { Git result = null; try { RepositoryService rs = new RepositoryService(client); Repository r = rs.getRepository(owner, repoName); String cloneURL = r.getSshUrl(); // prepare a new folder for the cloned repository File localPath = new File(Settings.COOKBOOKS_PATH + File.separator + repoName); if (localPath.isDirectory() == false) { localPath.mkdirs(); } else { throw new KaramelException("Local directory already exists. Delete it first: " + localPath); } logger.debug("Cloning from " + cloneURL + " to " + localPath); result = Git.cloneRepository().setURI(cloneURL).setDirectory(localPath).call(); // Note: the call() returns an opened repository already which needs to be closed to avoid file handle leaks! logger.debug("Cloned repository: " + result.getRepository().getDirectory()); } catch (IOException | GitAPIException ex) { throw new KaramelException("Problem cloning repo: " + ex.getMessage()); } finally { if (result != null) { result.close(); } } }
From source file:se.lnu.cs.doris.git.GitRepository.java
License:Open Source License
/** * Method to fetch a bare .git repository for local storage. * @throws Exception //from w w w . ja v a 2 s. co m */ public void pullBare() throws Exception { String barePath = this.m_target + "/" + this.m_repoName + "_" + this.m_branch + ".git"; File file = new File(barePath); if (file.exists()) { Utilities.deleteDirectory(file); } try { Git git = Git.cloneRepository().setURI(this.m_uri) .setDirectory(new File(this.m_target, this.m_repoName + "_" + this.m_branch + ".git")) .setCloneAllBranches(true).setBare(true).setBranch(m_branch).call(); this.m_headRepository = git.getRepository(); } catch (Exception e) { this.errorHandlingMining(e, null); } }
From source file:services.player.ZoneManager.java
License:Open Source License
private void loadCommitHistory() { File repoDir = new File("./" + Constants.DOT_GIT); int commitCount = 3; int iterations = 0; try {//from w w w. j a v a2 s .c o m Git git = Git.open(repoDir); Repository repo = git.getRepository(); try { commitHistory = "The " + commitCount + " most recent commits in branch '" + repo.getBranch() + "':\n"; for (RevCommit commit : git.log().setMaxCount(commitCount).call()) { commitHistory += commit.getName().substring(0, 7) + " " + commit.getShortMessage(); if (commitCount > iterations++) commitHistory += "\n"; } } catch (GitAPIException e) { e.printStackTrace(); } } catch (IOException e) { System.err.println("ZoneManager: Failed to open " + repoDir + " to read commit history"); // An exception is thrown if bash isn't installed. // https://www.eclipse.org/forums/index.php/t/1031740/ } }
From source file:sh.isaac.provider.sync.git.SyncServiceGIT.java
License:Apache License
/** * Adds the note.// w w w . j av a 2s .c om * * @param message the message * @param git the git * @throws IOException Signals that an I/O exception has occurred. * @throws GitAPIException the git API exception */ private void addNote(String message, Git git) throws IOException, GitAPIException { try (RevWalk walk = new RevWalk(git.getRepository())) { final Ref head = git.getRepository().exactRef("refs/heads/master"); final RevCommit commit = walk.parseCommit(head.getObjectId()); git.notesAdd().setObjectId(commit).setMessage(message).call(); } }
From source file:uk.ac.cam.cl.dtg.segue.database.GitDbTest.java
License:Apache License
@Test public void getTreeWalk_checkThatBlankPathsAreAllowed_noExceptionThrown() throws IOException { Git git = EasyMock.createMock(Git.class); GitDb db = new GitDb(git); try {/*from w w w . j ava 2s . c om*/ db.getTreeWalk("", ""); fail("Failed to throw required exception on blank sha."); } catch (IllegalArgumentException e) { // Exception correctly thrown. } catch (Exception e) { fail("Wrong type of exception thrown on blank sha"); } try { db.getTreeWalk(null, ""); fail("Failed to throw required exception on null sha."); } catch (NullPointerException e) { // Exception correctly thrown. } catch (Exception e) { fail("Wrong type of exception thrown on null sha"); } try { db.getTreeWalk("sha", null); fail("Failed to throw required exception on null path."); } catch (NullPointerException e) { // Exception correctly thrown. } catch (Exception e) { fail("Wrong type of exception thrown on null path"); } Repository repo = EasyMock.createMock(Repository.class); EasyMock.expect(git.getRepository()).andReturn(repo); EasyMock.expect(repo.resolve("sha")).andReturn(null); EasyMock.replay(git); EasyMock.replay(repo); assertNull(db.getTreeWalk("sha", "")); // Blank path is explicitly allowed. This should not throw an exception. But in this case we've passed an invalid sha, so we should get null back. }
From source file:util.DifferenceComputer.java
License:Apache License
public static void main(String[] args) throws IOException, GitAPIException { /////from w w w . j a va 2s . co m String coreRepoPath = "/Users/Onekin/Desktop/VODPlayer-CoreAssets-2";//args[0]; String branchToLookInto = "develop.coreAssets"; try { Git git = Git.open(new File(coreRepoPath)); Repository repository = git.getRepository(); Ref ref = repository.findRef(branchToLookInto); if (ref == null) { ref = git.checkout().setCreateBranch(true).setName(branchToLookInto) .setUpstreamMode(SetupUpstreamMode.TRACK).setStartPoint("origin/" + branchToLookInto) .call(); } ObjectId parentCommit = repository .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^^{commit}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String) ObjectId currentCommit = repository .resolve(repository.findRef(branchToLookInto).getObjectId().getName() + "^{commit}"); List<DiffEntry> listOfChangedFiles = getChangedFilesBetweenTwoCommits(coreRepoPath, currentCommit, parentCommit); } catch (Exception e) { e.getMessage(); e.printStackTrace(); } }
From source file:util.DifferenceComputer.java
License:Apache License
public static List<DiffEntry> getChangedFilesBetweenTwoCommits(String repoPath, ObjectId ancestor, ObjectId commit) {/*from www . j a v a2 s . com*/ List<DiffEntry> diffs = null; try { // The {tree} will return the underlying tree-id instead of the commit-id itself! // For a description of what the carets do see e.g. http://www.paulboxley.com/blog/2011/06/git-caret-and-tilde // This means we are selecting the parent of the parent of the parent of the parent of current HEAD and // take the tree-ish of it Git git = Git.open(new File(repoPath)); Repository repository = git.getRepository(); //ObjectId oldHead = repository.resolve(repository.findRef(branchToLookInto).getObjectId().getName()+"^^{tree}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String) //ObjectId head = repository.resolve(repository.findRef(branchToLookInto).getObjectId().getName()+"^{tree}"); ObjectId oldHead = repository.resolve(ancestor.getName() + "^{tree}");//http://download.eclipse.org/jgit/site/4.2.0.201601211800-r/apidocs/org/eclipse/jgit/lib/Repository.html#resolve(java.lang.String) ObjectId head = repository.resolve(commit.getName() + "^{tree}"); System.out.println("Printing diff between tree: " + oldHead + "and" + head); // prepare the two iterators to compute the diff between ObjectReader reader = repository.newObjectReader(); CanonicalTreeParser oldTreeIter = new CanonicalTreeParser(); oldTreeIter.reset(reader, oldHead); CanonicalTreeParser newTreeIter = new CanonicalTreeParser(); newTreeIter.reset(reader, head); // finally get the list of changed files git = new Git(repository); diffs = git.diff().setNewTree(newTreeIter).setOldTree(oldTreeIter).call(); int changedFiles = 0; for (DiffEntry diff : diffs) { System.out.println("Entry: " + diff); System.out.println("getNewPath: " + diff.getNewPath()); System.out.println("getScore: " + diff.getScore()); System.out.println("getChangeType: " + diff.getChangeType()); System.out.println("getNewMode: " + diff.getNewMode()); System.out.println("getPath: " + diff.getPath(null)); changedFiles++; } System.out.println("Changed Files: " + changedFiles); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("Done"); return diffs; }
From source file:util.Util.java
public static List<File> listFilesChanges(Git git, RevCommit rev, Project project) { List<File> fileNames = new ArrayList<>(); try {/*from w w w .j a v a2 s . c o m*/ if (rev.getParentCount() > 0) { DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); RevCommit parent = rev.getParent(0); Repository repository = git.getRepository(); df.setRepository(repository); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffs = df.scan(parent.getTree(), rev.getTree()); for (DiffEntry diff : diffs) { if (!diff.getChangeType().name().equalsIgnoreCase("DELETE") && diff.getNewPath().endsWith(".java")) { fileNames.add(new File(project.getAbsolutePath() + "/" + diff.getNewPath())); } } } } catch (Exception e) { e.printStackTrace(); } return fileNames; }