@Override public ChangeKind load(Key key) throws IOException { if (Objects.equal(key.prior, key.next)) { return ChangeKind.NO_CODE_CHANGE; } RevWalk walk = new RevWalk(key.repo); try { RevCommit prior = walk.parseCommit(key.prior); walk.parseBody(prior); RevCommit next = walk.parseCommit(key.next); walk.parseBody(next); if (!next.getFullMessage().equals(prior.getFullMessage())) { if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { return ChangeKind.NO_CODE_CHANGE; } else { return ChangeKind.REWORK; } } if (prior.getParentCount() != 1 || next.getParentCount() != 1) { // Trivial rebases done by machine only work well on 1 parent. return ChangeKind.REWORK; } if (next.getTree() == prior.getTree() && isSameParents(prior, next)) { return ChangeKind.TRIVIAL_REBASE; } // A trivial rebase can be detected by looking for the next commit // having the same tree as would exist when the prior commit is // cherry-picked onto the next commit's new first parent. ThreeWayMerger merger = MergeUtil.newThreeWayMerger( key.repo, MergeUtil.createDryRunInserter(), key.strategyName); merger.setBase(prior.getParent(0)); if (merger.merge(next.getParent(0), prior) && merger.getResultTreeId().equals(next.getTree())) { return ChangeKind.TRIVIAL_REBASE; } else { return ChangeKind.REWORK; } } finally { key.repo = null; walk.release(); } }
@Override public List<CommitDB> getCommits() { try { Iterable<RevCommit> revCommits; revCommits = git.log().all().call(); List<CommitDB> commits = new ArrayList<CommitDB>(); for (RevCommit revCommit : revCommits) { PersonIdent author = revCommit.getAuthorIdent(); CommitDB commit = new CommitDB(0, author.getWhen(), revCommit.getFullMessage(), revCommit.getName()); CommitterDB committerDb = new CommitterDB(0, author.getEmailAddress(), author.getName()); commit.setCommitter(committerDb); commits.add(commit); } return commits; } catch (GitAPIException e) { throw new VisMinerAPIException(e.getMessage(), e); } catch (IOException e) { throw new VisMinerAPIException(e.getMessage(), e); } }
/* * Use the binary git repo and/or the remote service to figure out * the new commits made since the last pull on source repository. */ public void findNewCommits() throws GitException { // get the history from binary repository Git bingit = Git.wrap(binaryRepository); RevWalk binwalk = new RevWalk(binaryRepository); Iterable<RevCommit> logs; try { logs = bingit.log().call(); Iterator<RevCommit> i = logs.iterator(); while (i.hasNext()) { RevCommit commit = binwalk.parseCommit(i.next()); System.out.println(commit.getFullMessage()); } } catch (NoHeadException e) { // TODO Auto-generated catch block throw new GitException(e); } catch (GitAPIException e) { throw new GitException(e); } catch (MissingObjectException e) { throw new GitException(e); } catch (IncorrectObjectTypeException e) { throw new GitException(e); } catch (IOException e) { throw new GitException(e); } }
private static Set<String> extractJiraIssues(String pattern, Iterable<RevCommit> commits) { HashSet jiraIssues = new LinkedHashSet(); // preserve insertion order for (RevCommit commit : commits) { jiraIssues.addAll(extractJiraIssuesFromString(commit.getFullMessage(), pattern)); } return jiraIssues; }
@Test public void squash() throws Exception { InteractiveHandler messageHandler = new InteractiveHandler() { public void prepareSteps(List<RebaseTodoLine> steps) { // not used } public String modifyCommitMessage(String commit) { return "squashed"; } }; List<RevCommit> commits = Arrays.asList(commit1, commit2, commit3); SquashCommitsOperation op = new SquashCommitsOperation(testRepository.getRepository(), commits, messageHandler); op.execute(new NullProgressMonitor()); assertEquals(2, countCommitsInHead()); LogCommand log = new Git(testRepository.getRepository()).log(); Iterable<RevCommit> logCommits = log.call(); RevCommit latestCommit = logCommits.iterator().next(); assertEquals("squashed", latestCommit.getFullMessage()); }
// 2. Get branch/commit hash for the source repo - the actual source code @Test public void existsIn() throws IOException { // final String repo = "binrepo-devex"; // final String repo = "search_raptor_binary"; // String githubUrl = "https://github.scm.corp.ebay.com/api/v3"; // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc"; final String path = "D:\\dev\\devex\\binrepo-devex\\.git"; File gitDir = new File(path); org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(gitDir); String branch = repository.getBranch(); System.out.println(branch); RevWalk revWalk = new RevWalk(repository); // Pop the most recent commit off from RevWalk // RevCommit commit = revWalk.next(); returns null :-( // System.out.println(commit); ObjectId resolve = repository.resolve(Constants.HEAD); RevCommit commit = revWalk.parseCommit(resolve); String commitHash = commit.getName(); System.out.println(commitHash + "\t" + commit.getFullMessage()); // RefDatabase refDatabase = repository.getRefDatabase(); }
@Test public void testSomeCommits() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { // do 4 commits Git git = new Git(db); git.commit().setMessage("initial commit").call(); git.commit().setMessage("second commit").setCommitter(committer).call(); git.commit().setMessage("third commit").setAuthor(author).call(); git.commit().setMessage("fourth commit").setAuthor(author).setCommitter(committer).call(); Iterable<RevCommit> commits = git.log().call(); // check that all commits came in correctly PersonIdent defaultCommitter = new PersonIdent(db); PersonIdent expectedAuthors[] = new PersonIdent[] {defaultCommitter, committer, author, author}; PersonIdent expectedCommitters[] = new PersonIdent[] {defaultCommitter, committer, defaultCommitter, committer}; String expectedMessages[] = new String[] {"initial commit", "second commit", "third commit", "fourth commit"}; int l = expectedAuthors.length - 1; for (RevCommit c : commits) { assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent().getName()); assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent().getName()); assertEquals(c.getFullMessage(), expectedMessages[l]); l--; } assertEquals(l, -1); }
@Test public void testCommitRange() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException, IncorrectObjectTypeException, MissingObjectException { // do 4 commits and set the range to the second and fourth one Git git = new Git(db); git.commit().setMessage("first commit").call(); RevCommit second = git.commit().setMessage("second commit").setCommitter(committer).call(); git.commit().setMessage("third commit").setAuthor(author).call(); RevCommit last = git.commit().setMessage("fourth commit").setAuthor(author).setCommitter(committer).call(); Iterable<RevCommit> commits = git.log().addRange(second.getId(), last.getId()).call(); // check that we have the third and fourth commit PersonIdent defaultCommitter = new PersonIdent(db); PersonIdent expectedAuthors[] = new PersonIdent[] {author, author}; PersonIdent expectedCommitters[] = new PersonIdent[] {defaultCommitter, committer}; String expectedMessages[] = new String[] {"third commit", "fourth commit"}; int l = expectedAuthors.length - 1; for (RevCommit c : commits) { assertEquals(expectedAuthors[l].getName(), c.getAuthorIdent().getName()); assertEquals(expectedCommitters[l].getName(), c.getCommitterIdent().getName()); assertEquals(c.getFullMessage(), expectedMessages[l]); l--; } assertEquals(l, -1); }
@Override public Sequence eval(Sequence[] args, Sequence contextSequence) throws XPathException { try { String localPath = args[0].getStringValue(); if (!(localPath.endsWith("/"))) localPath += File.separator; // Repository localRepo = new FileRepository(localPath + ".git"); // Git git = new Git(localRepo); Git git = Git.open(new Resource(localPath), FS); MemTreeBuilder builder = context.getDocumentBuilder(); AttributesImpl attribs = new AttributesImpl(); attribs.addAttribute(NAMESPACE_URI, "local-path", PREFIX + ":local-path", "CDATA", localPath); int nodeNr = builder.startElement(LOG_ELEMENT, attribs); for (RevCommit commit : git.log().call()) { // commit.getParentCount(); // commit.getParents(); attribs = new AttributesImpl(); attribs.addAttribute(NAMESPACE_URI, "id", PREFIX + ":id", "CDATA", commit.name()); attribs.addAttribute( NAMESPACE_URI, "time", PREFIX + ":time", "CDATA", String.valueOf(commit.getCommitTime())); builder.startElement(COMMIT_ELEMENT, attribs); PersonIdent authorIdent = commit.getAuthorIdent(); builder.startElement(AUTHOR_ELEMENT, null); builder.startElement(AUTHOR_NAME_ELEMENT, null); builder.characters(authorIdent.getName()); builder.endElement(); builder.startElement(AUTHOR_EMAIL_ELEMENT, null); builder.characters(authorIdent.getEmailAddress()); builder.endElement(); builder.endElement(); builder.startElement(MESSAGE_ELEMENT, null); builder.characters(commit.getFullMessage()); builder.endElement(); builder.endElement(); } builder.endElement(); return builder.getDocument().getNode(nodeNr); } catch (Throwable e) { throw new XPathException(this, Module.EXGIT001, e); } }
public static List<String> getLogForCurrentBranch(final Git repo) throws GitAPIException { List<String> results = new ArrayList<String>(); Iterable<RevCommit> commits = repo.log().call(); for (RevCommit commit : commits) results.add(commit.getFullMessage()); return results; }
private void assertParseFails(RevCommit commit) throws Exception { try (ChangeNotesParser parser = newParser(commit)) { parser.parseAll(); fail("Expected parse to fail:\n" + commit.getFullMessage()); } catch (ConfigInvalidException e) { // Expected } }
private static BlameInfo toBlameInfo(RevCommit commit, PersonIdent sourceAuthor) { BlameInfo blameInfo = new BlameInfo(); blameInfo.author = sourceAuthor.getName(); blameInfo.id = commit.getName(); blameInfo.commitMsg = commit.getFullMessage(); blameInfo.time = commit.getCommitTime(); return blameInfo; }
private Revision asRevision(final RevCommit commit) { final PersonIdent author = commit.getAuthorIdent(); return new RevisionImpl( commit.name(), author.getName(), author.getEmailAddress(), author.getWhen(), commit.getFullMessage()); }
public PatchSetInfo get(RevWalk rw, RevCommit src, PatchSet.Id psi) throws IOException { rw.parseBody(src); PatchSetInfo info = new PatchSetInfo(psi); info.setSubject(src.getShortMessage()); info.setMessage(src.getFullMessage()); info.setAuthor(toUserIdentity(src.getAuthorIdent())); info.setCommitter(toUserIdentity(src.getCommitterIdent())); info.setRevId(src.getName()); return info; }
@Test public void testDefaultMessage() throws Exception { testUtils.addFileToProject(project.getProject(), "foo/a.txt", "some text"); StashCreateOperation stashCreateOperation = new StashCreateOperation(repository); stashCreateOperation.execute(null); RevWalk revWalk = new RevWalk(repository); RevCommit commit = revWalk.parseCommit(repository.resolve("stash@{0}")); assertTrue(commit.getFullMessage().length() > 0); }
@Test public void testCustomMessage() throws Exception { testUtils.addFileToProject(project.getProject(), "foo/a.txt", "some text"); String message = "stash message"; StashCreateOperation stashCreateOperation = new StashCreateOperation(repository, message); stashCreateOperation.execute(null); RevWalk revWalk = new RevWalk(repository); RevCommit commit = revWalk.parseCommit(repository.resolve("stash@{0}")); assertEquals(message, commit.getFullMessage()); }
private Git.Head getHead(final Repository repository) throws IOException { ObjectId revision = repository.resolve(Constants.HEAD); RevCommit commit = new RevWalk(repository).parseCommit(revision); Git.Head head = new Git.Head( revision.getName(), commit.getAuthorIdent().getName(), commit.getAuthorIdent().getEmailAddress(), commit.getCommitterIdent().getName(), commit.getCommitterIdent().getEmailAddress(), commit.getFullMessage()); return head; }
@Test public void testCommitAmend() throws NoHeadException, NoMessageException, UnmergedPathException, ConcurrentRefUpdateException, JGitInternalException, WrongRepositoryStateException { Git git = new Git(db); git.commit().setMessage("first comit").call(); // typo git.commit().setAmend(true).setMessage("first commit").call(); Iterable<RevCommit> commits = git.log().call(); int c = 0; for (RevCommit commit : commits) { assertEquals("first commit", commit.getFullMessage()); c++; } assertEquals(1, c); }
public void log(final int maxHistory) { final Repository repository = getRepository(); final Git git = new Git(repository); try { int counter = 0; LOGGER.warning("---------- Start Git log ----------"); for (final RevCommit commit : git.log().call()) { LOGGER.info("commit id: " + commit.getName()); LOGGER.info("message: " + commit.getFullMessage()); LOGGER.info(""); if (++counter >= maxHistory) { break; } } LOGGER.warning("---------- End Git log ----------"); } catch (final Exception e) { throw new IllegalStateException("Could not parse git log", e); } }
@Test public void testRemote() throws Exception { File binaryRepoFolder = new File("D:\\dev\\rgiroti_search_raptor\\.search_raptor"); Git git = Git.open(binaryRepoFolder); final Iterable<RevCommit> revCommits = git.log().call(); for (RevCommit revCommit : revCommits) { System.out.println( revCommit.getName() + revCommit.getFullMessage() + revCommit.getCommitTime()); } // final org.eclipse.jgit.lib.Repository binRepo = new // org.eclipse.jgit.storage.file.FileRepository(binaryRepoFolder); // final RevWalk binRepoRevWalk = new RevWalk(binRepo); // final ObjectId binRepoResolve = binRepo.resolve(Constants.HEAD); // final RevCommit binRepoResolveCommitRev = git.log().call().iterator().next(); // final String binRepoResolveCommitHash = binRepoResolveCommitRev.getName(); // final String binRepoBranchname = git.getRepository().getBranch(); }
public String getCommitMessage(String commitId) { String commitMessage = null; try { FileRepositoryBuilder builder = new FileRepositoryBuilder(); String repoPath = VerigreenNeededLogic.properties.getProperty("git.repositoryLocation"); Repository repo = builder.setGitDir(new File(repoPath)).setMustExist(true).build(); Git git = new Git(repo); Iterable<RevCommit> log = git.log().call(); Iterator<RevCommit> iterator = log.iterator(); while (commitMessage == null && iterator.hasNext()) { RevCommit rev = iterator.next(); String commit = rev.getName().substring(0, 7); if (commit.equals(commitId)) { commitMessage = rev.getFullMessage(); } } } catch (Exception e) { e.printStackTrace(); } return commitMessage; }
private static void lastCommit(Git git, String path, AnyObjectId revId, JSONObject jsonObject) { JSONObject latestCommitObj = new JSONObject(); JSONObject authorObj = new JSONObject(); JSONObject committerObj = new JSONObject(); Iterable<RevCommit> log = null; try { if (path != null) { log = git.log().addPath(path).setMaxCount(1).call(); } else if (revId != null) { log = git.log().add(revId).setMaxCount(1).call(); } Iterator<RevCommit> it = log.iterator(); while (it.hasNext()) { RevCommit rev = (RevCommit) it.next(); PersonIdent committer = rev.getCommitterIdent(); committerObj.put("Name", committer.getName()); committerObj.put("Email", committer.getEmailAddress()); committerObj.put("Date", committer.getWhen().toString()); PersonIdent author = rev.getAuthorIdent(); authorObj.put("Name", author.getName()); String authorEmail = author.getEmailAddress(); authorObj.put("Email", authorEmail); authorObj.put("Date", author.getWhen().toString()); latestCommitObj.put("Author", authorObj); latestCommitObj.put("Committer", committerObj); latestCommitObj.put("Message", rev.getFullMessage()); latestCommitObj.put("SHA1", rev.getId().getName()); latestCommitObj.put("AvatarURL", getImageLink(authorEmail)); jsonObject.put("LastCommit", latestCommitObj); } } catch (GitAPIException e) { } catch (MissingObjectException e) { } catch (IncorrectObjectTypeException e) { } catch (JSONException e) { } }
public List<CommitDB> getCommitsByTree(String treeName, TreeType type) { Iterable<RevCommit> revCommits = null; if (type == TreeType.BRANCH) { revCommits = getCommitsFromBranch(treeName); } else if (type == TreeType.TAG) { revCommits = getCommitsFromTag(treeName); } List<CommitDB> commits = new ArrayList<CommitDB>(); for (RevCommit revCommit : revCommits) { CommitDB commit = new CommitDB( 0, revCommit.getAuthorIdent().getWhen(), revCommit.getFullMessage(), revCommit.getName()); commits.add(commit); } return commits; }
private void createMessageArea(Composite parent, FormToolkit toolkit, int span) { Section messageSection = createSection(parent, toolkit, span); Composite messageArea = createSectionClient(messageSection, toolkit); messageSection.setText(UIText.CommitEditorPage_SectionMessage); RevCommit commit = getCommit().getRevCommit(); String message = commit.getFullMessage(); PersonIdent author = commit.getAuthorIdent(); if (author != null) message = replaceSignedOffByLine(message, author); PersonIdent committer = commit.getCommitterIdent(); if (committer != null) message = replaceSignedOffByLine(message, committer); SpellcheckableMessageArea textContent = new SpellcheckableMessageArea(messageArea, message, true, toolkit.getBorderStyle()) { @Override protected IAdaptable getDefaultTarget() { return new PlatformObject() { public Object getAdapter(Class adapter) { return Platform.getAdapterManager().getAdapter(getEditorInput(), adapter); } }; } protected void createMarginPainter() { // Disabled intentionally } }; if ((toolkit.getBorderStyle() & SWT.BORDER) == 0) textContent.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER); GridDataFactory.fillDefaults().hint(SWT.DEFAULT, 80).grab(true, true).applyTo(textContent); updateSectionClient(messageSection, messageArea, toolkit); }
protected RevCommit commitThenPush(Git git, String branch, CommitCommand commit) throws Exception { RevCommit answer = commit.call(); if (LOG.isDebugEnabled()) { LOG.debug("Committed " + answer.getId() + " " + answer.getFullMessage()); } if (isPushOnCommit()) { Iterable<PushResult> results = doPush(git); for (PushResult result : results) { if (LOG.isDebugEnabled()) { LOG.debug( "Pushed " + result.getMessages() + " " + result.getURI() + " branch: " + branch + " updates: " + toString(result.getRemoteUpdates())); } } } return answer; }
/** * Update the submodules in one branch of one repository. * * @param subscriber the branch of the repository which should be changed. * @param updates submodule updates which should be updated to. * @throws SubmoduleException */ private void updateGitlinks( ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates) throws SubmoduleException { PersonIdent author = null; Repository pdb = null; RevWalk recRw = null; StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n"); try { boolean sameAuthorForAll = true; pdb = repoManager.openRepository(subscriber.getParentKey()); if (pdb.getRef(subscriber.get()) == null) { throw new SubmoduleException( "The branch was probably deleted from the subscriber repository"); } DirCache dc = readTree(pdb, pdb.getRef(subscriber.get())); DirCacheEditor ed = dc.editor(); for (SubmoduleSubscription s : updates) { try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey()); RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) { Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get()); if (ref == null) { ed.add(new DeletePath(s.getPath())); continue; } final ObjectId updateTo = ref.getObjectId(); RevCommit newCommit = rw.parseCommit(updateTo); if (author == null) { author = newCommit.getAuthorIdent(); } else if (!author.equals(newCommit.getAuthorIdent())) { sameAuthorForAll = false; } DirCacheEntry dce = dc.getEntry(s.getPath()); ObjectId oldId = null; if (dce != null) { if (!dce.getFileMode().equals(FileMode.GITLINK)) { log.error( "Requested to update gitlink " + s.getPath() + " in " + s.getSubmodule().getParentKey().get() + " but entry " + "doesn't have gitlink file mode."); continue; } oldId = dce.getObjectId(); } else { // This submodule did not exist before. We do not want to add // the full submodule history to the commit message, so omit it. oldId = updateTo; } ed.add( new PathEdit(s.getPath()) { @Override public void apply(DirCacheEntry ent) { ent.setFileMode(FileMode.GITLINK); ent.setObjectId(updateTo); } }); if (verboseSuperProject) { msgbuf.append("Project: " + s.getSubmodule().getParentKey().get()); msgbuf.append(" " + s.getSubmodule().getShortName()); msgbuf.append(" " + updateTo.getName()); msgbuf.append("\n\n"); try { rw.markStart(newCommit); if (oldId != null) { rw.markUninteresting(rw.parseCommit(oldId)); } for (RevCommit c : rw) { msgbuf.append(c.getFullMessage() + "\n\n"); } } catch (IOException e) { logAndThrowSubmoduleException( "Could not perform a revwalk to " + "create superproject commit message", e); } } } } ed.finish(); if (!sameAuthorForAll || author == null) { author = myIdent; } ObjectInserter oi = pdb.newObjectInserter(); ObjectId tree = dc.writeTree(oi); ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId(); CommitBuilder commit = new CommitBuilder(); commit.setTreeId(tree); commit.setParentIds(new ObjectId[] {currentCommitId}); commit.setAuthor(author); commit.setCommitter(myIdent); commit.setMessage(msgbuf.toString()); oi.insert(commit); oi.flush(); ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build()); final RefUpdate rfu = pdb.updateRef(subscriber.get()); rfu.setForceUpdate(false); rfu.setNewObjectId(commitId); rfu.setExpectedOldObjectId(currentCommitId); rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true); switch (rfu.update()) { case NEW: case FAST_FORWARD: gitRefUpdated.fire(subscriber.getParentKey(), rfu); changeHooks.doRefUpdatedHook(subscriber, rfu, account); // TODO since this is performed "in the background" no mail will be // sent to inform users about the updated branch break; default: throw new IOException(rfu.getResult().name()); } recRw = new RevWalk(pdb); // Recursive call: update subscribers of the subscriber updateSuperProjects(db, Sets.newHashSet(subscriber)); } catch (IOException e) { throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), e); } finally { if (recRw != null) { recRw.close(); } if (pdb != null) { pdb.close(); } } }
public static CherryPickResult cherryPickNoMerge(final Git git, Ref src) throws GitAPIException, CantMergeCommitWithZeroParentsException { // Does the same as the original git-cherryPick // except commiting after running merger Repository repo = git.getRepository(); RevCommit newHead = null; List<Ref> cherryPickedRefs = new LinkedList<Ref>(); RevWalk revWalk = new RevWalk(repo); try { // get the head commit Ref headRef = repo.getRef(Constants.HEAD); if (headRef == null) throw new NoHeadException(JGitText.get().commitOnRepoWithoutHEADCurrentlyNotSupported); RevCommit headCommit = revWalk.parseCommit(headRef.getObjectId()); newHead = headCommit; // get the commit to be cherry-picked // handle annotated tags ObjectId srcObjectId = src.getPeeledObjectId(); if (srcObjectId == null) srcObjectId = src.getObjectId(); RevCommit srcCommit = revWalk.parseCommit(srcObjectId); // get the parent of the commit to cherry-pick if (srcCommit.getParentCount() == 0) throw new CantMergeCommitWithZeroParentsException( "Commit with zero parents cannot be merged"); if (srcCommit.getParentCount() > 1) throw new MultipleParentsNotAllowedException( MessageFormat.format( JGitText.get().canOnlyCherryPickCommitsWithOneParent, srcCommit.name(), Integer.valueOf(srcCommit.getParentCount()))); RevCommit srcParent = srcCommit.getParent(0); revWalk.parseHeaders(srcParent); ResolveMerger merger = (ResolveMerger) MergeStrategy.RESOLVE.newMerger(repo); merger.setWorkingTreeIterator(new FileTreeIterator(repo)); merger.setBase(srcParent.getTree()); if (merger.merge(headCommit, srcCommit)) { DirCacheCheckout dco = new DirCacheCheckout( repo, headCommit.getTree(), repo.lockDirCache(), merger.getResultTreeId()); dco.setFailOnConflict(true); dco.checkout(); cherryPickedRefs.add(src); } else { if (merger.failed()) return new CherryPickResult(merger.getFailingPaths()); // there are merge conflicts String message = new MergeMessageFormatter() .formatWithConflicts(srcCommit.getFullMessage(), merger.getUnmergedPaths()); repo.writeCherryPickHead(srcCommit.getId()); repo.writeMergeCommitMsg(message); return CherryPickResult.CONFLICT; } } catch (IOException e) { throw new JGitInternalException( MessageFormat.format(JGitText.get().exceptionCaughtDuringExecutionOfCherryPickCommand, e), e); } finally { revWalk.release(); } return new CherryPickResult(newHead, cherryPickedRefs); }
// 2. Get branch/commit hash for the source repo - the actual source code @Test public void existsIn2() throws IOException { final String repo = "binrepo-devex"; // final String repo = "search_raptor_binary"; // String githubUrl = "https://github.scm.corp.ebay.com/api/v3"; // String accessToken = "1cf7d9792235b8592eda18bd7dcc2de37f99b3bc"; final String path = "D:\\dev\\devex\\.binrepo-devex\\.git"; File gitDir = new File(path); org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(gitDir); String branch = repository.getBranch(); System.out.println("Branch=" + branch); final Map<String, Ref> allRefs = repository.getAllRefs(); for (String s : allRefs.keySet()) { System.out.println("Here" + s); } RevWalk revWalk = new RevWalk(repository); ObjectId resolve = repository.resolve(Constants.HEAD); RevCommit commitRev = revWalk.parseCommit(resolve); String commitHash = commitRev.getName(); System.out.println(commitHash + "\t" + commitRev.getFullMessage()); Git binaryRepo = Git.open(gitDir); final ListBranchCommand listBranchCommand = binaryRepo.branchList(); System.out.println(listBranchCommand.getRepository().getFullBranch()); // get "status" final StatusCommand statusCommand = binaryRepo.status(); Collection<String> toadd = GitUtils.getFilesToStage(statusCommand); for (String s : toadd) { System.out.println("To be added:" + s); } // add files to "staging" if (toadd.size() > 0) { AddCommand addCmd = binaryRepo.add(); for (String file : toadd) { addCmd.addFilepattern(file); } try { addCmd.call(); } catch (Exception e) { e.printStackTrace(); } } final StoredConfig config = repository.getConfig(); String url = config.getString("remote", "origin", "url"); if (url != null) { System.out.println("Origin comes from " + url); } // commit final CommitCommand commit = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repo, branch, commitHash, new Date().toString()); commit.setMessage(formattedMsg); try { commit.call(); } catch (Exception e) { e.printStackTrace(); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { e .printStackTrace(); // To change body of catch statement use File | Settings | File // Templates. } }
private boolean isSignedOffBy(PersonIdent person) { RevCommit commit = getCommit().getRevCommit(); return commit.getFullMessage().indexOf(getSignedOffByLine(person)) != -1; }
public void updateBinaryRepository() throws IOException, GitException, MapServiceException { // 1. Check if repository exists remotely [email protected]/Binary/Repo_Binary.git // find the name of the "source repository" final String repoUrl = getSourceRemoteUrl(); // find where ".git" folder is found // SourceRepository = D:\dev\devex\binrepo-devex // BinaryRepository = D:\dev\devex\.binrepo-devex final File srcRepoDir = sourceRepository.getDirectory(); final File sourceDir = srcRepoDir.getParentFile(); final String sourceRepoFolder = srcRepoDir.getParentFile().getCanonicalPath(); final File parent = srcRepoDir.getParentFile().getParentFile(); final File binaryRepoDir = new File(parent, "." + srcRepoDir.getParentFile().getName()); System.out.println( "SourceRepository = " + sourceRepoFolder + "\nBinaryRepository = " + binaryRepoDir.getCanonicalPath()); // 2. Get branch/commit hash for the source repo - the actual source code final org.eclipse.jgit.lib.Repository repository = new org.eclipse.jgit.storage.file.FileRepository(srcRepoDir); final String branch = repository.getBranch(); final RevWalk revWalk = new RevWalk(repository); final ObjectId resolve = repository.resolve(Constants.HEAD); final RevCommit commit = revWalk.parseCommit(resolve); String commitHash = commit.getName(); System.out.println("CommitHash:" + commitHash + "\tMessage:" + commit.getFullMessage()); // 3. Call the BinRepo service and check if a corresponding BinRepo entry exists final String url = getUrlForFindByRepoBranchCommit() + "repourl=" + URLEncoder.encode(repoUrl, UTF_8) + "&branch=" + URLEncoder.encode(branch, UTF_8) + "&commitid=" + URLEncoder.encode(commitHash, UTF_8); System.out.println("svc url : " + url); WebResource webResource = client.resource(url); boolean noContent = false; BinRepoBranchCommitDO binRepoBranchCommitDO1 = null; try { binRepoBranchCommitDO1 = webResource.accept(MediaType.APPLICATION_JSON).get(BinRepoBranchCommitDO.class); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("Service Status Code : " + statusCode); noContent = (statusCode == 204 || statusCode == 404); // HTTP 204 is NO CONTENT which is ok for us } catch (Exception e) { // Catch-all to deal with network problems etc. e.printStackTrace(); } System.out.println( binRepoBranchCommitDO1 != null ? binRepoBranchCommitDO1.toString() : "Resource not found on server"); // 4. If not copy all the target folders from the source repo to the binary repo - root to root // copy of artifacts if (noContent) { System.out.println( "Source Directory:'" + sourceDir.getCanonicalPath() + "' Destination Directory:'" + binaryRepoDir.getCanonicalPath() + "'"); FileUtil.copyBinaries(sourceDir, binaryRepoDir); } // 5. Call git status to get the delta (Use StatusCommand and refine it) Git binaryRepo; try { binaryRepo = Git.open(binaryRepoDir); } catch (IOException e) { throw new GitException("Unable to open repository" + binaryRepoDir, e); } // get "status" final StatusCommand statusCommand = binaryRepo.status(); // TODO: RGIROTI Ask Nambi if we should actually filter this to only add .class files and // nothing else Collection<String> filesToStage = GitUtils.getFilesToStage(statusCommand); /*for (String file : filesToStage) { System.out.println("File to be added:" + file); }*/ // add files to "staging" - if there is nothing to stage none of the other operations make any // sense at all if (filesToStage.size() > 0) { final AddCommand addCmd = binaryRepo.add(); for (String file : filesToStage) { addCmd.addFilepattern(file); } final String[] filesArr = filesToStage.toArray(new String[filesToStage.size()]); final String files = StringUtils.join(filesArr, ","); try { addCmd.call(); } catch (Exception e) { throw new GitException("Unable to add files to repository" + files, e); } // 6. Commit the changes to local and call push after that (use JGit API for this) // 6a. COmmit message should use format "Saving url:branch:commit:UTC time" // commit final CommitCommand commitCommand = binaryRepo.commit(); String msg = "Saving Repo:%s Branch:%s CommitHash:%s Time:%s"; final String formattedMsg = String.format(msg, repoUrl, branch, commitHash, new Date().toString()); commitCommand.setMessage(formattedMsg); String commitHashBinRepo; try { final RevCommit call = commitCommand.call(); commitHashBinRepo = call.getName(); } catch (Exception e) { throw new GitException("Unable to read commit hash from commit command", e); } // push to origin now final PushCommand push = binaryRepo.push(); final String remote = push.getRemote(); final String remoteBranch = push.getRepository().getBranch(); System.out.println("Remote to push to:'" + remote + "'"); try { push.call(); } catch (Exception e) { throw new GitException("Unable to push to remote", e); } // Calculate the remote url for binary repository String binRepoUrl = calculateBinaryRepositoryUrl(); // 7. Call the BinRepo service and create a new entity for this change - repoUrl, branch, and // commit System.out.println( "Update Bin Repo Service with the new changes - POST new object to service"); final BinRepoBranchCommitDO binRepoBranchCommitDO = newInstance(repoUrl, branch, commitHash, binRepoUrl, remoteBranch, commitHashBinRepo); webResource = client.resource(getUrlForPost()); BinRepoBranchCommitDO postedDO = null; try { postedDO = webResource .accept(MediaType.APPLICATION_XML) .post(BinRepoBranchCommitDO.class, binRepoBranchCommitDO); } catch (UniformInterfaceException e) { int statusCode = e.getResponse().getClientResponseStatus().getStatusCode(); System.out.println("status code: " + statusCode); throw new MapServiceException("Unable to register the commit details in update binrepo", e); } System.out.println(postedDO != null ? postedDO.toString() : "Post failed"); } }