org.eclipse.jgit.lib.ObjectId Java Examples
The following examples show how to use
org.eclipse.jgit.lib.ObjectId.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: GitRepository.java From centraldogma with Apache License 2.0 | 6 votes |
@VisibleForTesting static void doRefUpdate(org.eclipse.jgit.lib.Repository jGitRepository, RevWalk revWalk, String ref, ObjectId commitId) throws IOException { if (ref.startsWith(Constants.R_TAGS)) { final Ref oldRef = jGitRepository.exactRef(ref); if (oldRef != null) { throw new StorageException("tag ref exists already: " + ref); } } final RefUpdate refUpdate = jGitRepository.updateRef(ref); refUpdate.setNewObjectId(commitId); final Result res = refUpdate.update(revWalk); switch (res) { case NEW: case FAST_FORWARD: // Expected break; default: throw new StorageException("unexpected refUpdate state: " + res); } }
Example #2
Source File: GitPushEmbedded.java From git-as-svn with GNU General Public License v2.0 | 6 votes |
@Override public boolean push(@NotNull Repository repository, @NotNull ObjectId ReceiveId, @NotNull String branch, @NotNull User userInfo) throws SVNException, IOException { final RefUpdate refUpdate = repository.updateRef(branch); refUpdate.getOldObjectId(); refUpdate.setNewObjectId(ReceiveId); runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_HOOK_FAILURE, "pre-receive", userInfo); runUpdateHook(repository, refUpdate, "update", userInfo); final RefUpdate.Result result = refUpdate.update(); switch (result) { case REJECTED: case LOCK_FAILURE: return false; case NEW: case FAST_FORWARD: runReceiveHook(repository, refUpdate, SVNErrorCode.REPOS_POST_COMMIT_HOOK_FAILED, "post-receive", userInfo); return true; default: log.error("Unexpected push error: {}", result); throw new SVNException(SVNErrorMessage.create(SVNErrorCode.IO_WRITE_ERROR, result.name())); } }
Example #3
Source File: BlobEditsTest.java From onedev with MIT License | 6 votes |
@Test public void shouldFailIfOldPathIsTreeWhenRename() throws IOException { createDir("client"); addFileAndCommit("client/a.java", "a", "add a"); addFileAndCommit("client/b.java", "b", "add b"); createDir("server/src/com/example/a"); createDir("server/src/com/example/b"); addFileAndCommit("server/src/com/example/a/a.java", "a", "add a"); addFileAndCommit("server/src/com/example/b/b.java", "b", "add b"); String refName = "refs/heads/master"; ObjectId oldCommitId = git.getRepository().resolve(refName); Map<String, BlobContent> newBlobs = new HashMap<>(); newBlobs.put("client/c.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE)); BlobEdits edits = new BlobEdits(Sets.newHashSet("server/src/com/example/a"), newBlobs); ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test rename"); try (RevWalk revWalk = new RevWalk(git.getRepository())) { RevTree revTree = revWalk.parseCommit(newCommitId).getTree(); assertNotNull(TreeWalk.forPath(git.getRepository(), "client/c.java", revTree)); assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree)); } }
Example #4
Source File: GitContentRepository.java From studio with GNU General Public License v3.0 | 6 votes |
@Override public String getRepoLastCommitId(final String site) { String toReturn = EMPTY; Repository repository = helper.getRepository(site, StringUtils.isEmpty(site) ? GLOBAL : SANDBOX); if (repository != null) { synchronized (repository) { Repository repo = helper.getRepository(site, SANDBOX); try { ObjectId commitId = repo.resolve(HEAD); if (commitId != null) { toReturn = commitId.getName(); } } catch (IOException e) { logger.error("Error getting last commit ID for site " + site, e); } } } return toReturn; }
Example #5
Source File: GitRepo.java From git-changelog-lib with Apache License 2.0 | 6 votes |
/** * @param from From, but not including, this commit. Except for the {@link * GitChangelogApiConstants#ZERO_COMMIT}, it is included. * @param to To and including this commit. */ public GitRepoData getGitRepoData( final ObjectId from, final ObjectId to, final String untaggedName, final Optional<String> ignoreTagsIfNameMatches) throws GitChangelogRepositoryException { try { final String originUrl = this.git.getRepository().getConfig().getString("remote", "origin", "url"); final List<GitTag> gitTags = gitTags(from, to, untaggedName, ignoreTagsIfNameMatches); return new GitRepoData(originUrl, gitTags); } catch (final Exception e) { throw new GitChangelogRepositoryException(toString(), e); } }
Example #6
Source File: GitServiceImpl.java From RefactoringMiner with MIT License | 6 votes |
@Override public Churn churn(Repository repository, RevCommit currentCommit) throws Exception { if (currentCommit.getParentCount() > 0) { ObjectId oldTree = currentCommit.getParent(0).getTree(); ObjectId newTree = currentCommit.getTree(); final TreeWalk tw = new TreeWalk(repository); tw.setRecursive(true); tw.addTree(oldTree); tw.addTree(newTree); List<DiffEntry> diffs = DiffEntry.scan(tw); DiffFormatter diffFormatter = new DiffFormatter(DisabledOutputStream.INSTANCE); diffFormatter.setRepository(repository); diffFormatter.setContext(0); int addedLines = 0; int deletedLines = 0; for (DiffEntry entry : diffs) { FileHeader header = diffFormatter.toFileHeader(entry); List<? extends HunkHeader> hunks = header.getHunks(); for (HunkHeader hunkHeader : hunks) { for (Edit edit : hunkHeader.toEditList()) { if (edit.getType() == Type.INSERT) { addedLines += edit.getLengthB(); } else if (edit.getType() == Type.DELETE) { deletedLines += edit.getLengthA(); } else if (edit.getType() == Type.REPLACE) { deletedLines += edit.getLengthA(); addedLines += edit.getLengthB(); } } } } diffFormatter.close(); return new Churn(addedLines, deletedLines); } return null; }
Example #7
Source File: GitProctor.java From proctor with Apache License 2.0 | 6 votes |
@Nonnull @Override public List<Revision> getMatrixHistory(final int start, final int limit) throws StoreException { final LogCommand logCommand; try { final ObjectId branchHead = git.getRepository().resolve(getGitCore().getRefName()); logCommand = git.log() .add(branchHead) .setSkip(start) .setMaxCount(limit); return getHistoryFromLogCommand(logCommand); } catch (final IOException e) { throw new StoreException("Could not get history for starting at " + getGitCore().getRefName(), e); } }
Example #8
Source File: Scenario4WithDefaultsTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_C_commit() { ObjectId cCommit = scenario.getCommits().get("C"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(cCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.0-1")); }
Example #9
Source File: GitAPITestCase.java From git-client-plugin with MIT License | 5 votes |
public void test_revList_tag() throws Exception { w.init(); w.commitEmpty("c1"); Ref commitRefC1 = w.repo().exactRef("HEAD"); w.tag("t1"); Ref tagRefT1 = w.repo().findRef("t1"); Ref head = w.repo().exactRef("HEAD"); assertEquals("head != t1", head.getObjectId(), tagRefT1.getObjectId()); w.commitEmpty("c2"); Ref commitRefC2 = w.repo().exactRef("HEAD"); List<ObjectId> revList = w.git.revList("t1"); assertTrue("c1 not in revList", revList.contains(commitRefC1.getObjectId())); assertEquals("Wrong list size: " + revList, 1, revList.size()); }
Example #10
Source File: GitSCM.java From repositoryminer with Apache License 2.0 | 5 votes |
private List<Change> getChangesForCommitedFiles(String hash) throws IOException { RevWalk revWalk = new RevWalk(git.getRepository()); RevCommit commit = revWalk.parseCommit(ObjectId.fromString(hash)); if (commit.getParentCount() > 1) { revWalk.close(); return new ArrayList<Change>(); } RevCommit parentCommit = commit.getParentCount() > 0 ? revWalk.parseCommit(ObjectId.fromString(commit.getParent(0).getName())) : null; DiffFormatter df = new DiffFormatter(DisabledOutputStream.INSTANCE); df.setBinaryFileThreshold(2048); df.setRepository(git.getRepository()); df.setDiffComparator(RawTextComparator.DEFAULT); df.setDetectRenames(true); List<DiffEntry> diffEntries = df.scan(parentCommit, commit); df.close(); revWalk.close(); List<Change> changes = new ArrayList<Change>(); for (DiffEntry entry : diffEntries) { Change change = new Change(entry.getNewPath(), entry.getOldPath(), 0, 0, ChangeType.valueOf(entry.getChangeType().name())); analyzeDiff(change, entry); changes.add(change); } return changes; }
Example #11
Source File: GitTest.java From orion.server with Eclipse Public License 1.0 | 5 votes |
protected JSONObject getRemoteBranch(String gitRemoteUri, int size, int i, String name) throws IOException, SAXException, JSONException { assertRemoteUri(gitRemoteUri); JSONObject remote = getRemote(gitRemoteUri, 1, 0, Constants.DEFAULT_REMOTE_NAME); String remoteLocation = remote.getString(ProtocolConstants.KEY_LOCATION); WebRequest request = GitRemoteTest.getGetGitRemoteRequest(remoteLocation); WebResponse response = webConversation.getResponse(request); remote = waitForTask(response).getJsonData(); assertNotNull(remote); assertEquals(Constants.DEFAULT_REMOTE_NAME, remote.getString(ProtocolConstants.KEY_NAME)); assertNotNull(remote.getString(ProtocolConstants.KEY_LOCATION)); assertEquals(Remote.TYPE, remote.getString(ProtocolConstants.KEY_TYPE)); JSONArray refsArray = remote.getJSONArray(ProtocolConstants.KEY_CHILDREN); assertEquals(size, refsArray.length()); JSONObject ref = refsArray.getJSONObject(i); assertEquals(Constants.R_REMOTES + Constants.DEFAULT_REMOTE_NAME + "/" + name, ref.getString(ProtocolConstants.KEY_FULL_NAME)); String newRefId = ref.getString(ProtocolConstants.KEY_ID); assertTrue(ObjectId.isId(newRefId)); String remoteBranchLocation = ref.getString(ProtocolConstants.KEY_LOCATION); ref.getString(GitConstants.KEY_COMMIT); request = GitRemoteTest.getGetGitRemoteRequest(remoteBranchLocation); response = webConversation.getResponse(request); JSONObject remoteBranch = waitForTask(response).getJsonData(); assertEquals(RemoteBranch.TYPE, remoteBranch.getString(ProtocolConstants.KEY_TYPE)); assertNotNull(remoteBranch.optString(GitConstants.KEY_COMMIT)); assertNotNull(remoteBranch.optString(GitConstants.KEY_HEAD)); assertNotNull(remoteBranch.optString(GitConstants.KEY_DIFF)); return remoteBranch; }
Example #12
Source File: PullRequest.java From onedev with MIT License | 5 votes |
private boolean contains(ObjectId commitId) { if (commitId.equals(getBaseCommit())) return true; for (PullRequestUpdate update: getUpdates()) { for (RevCommit commit: update.getCommits()) { if (commit.equals(commitId)) return true; } } return false; }
Example #13
Source File: Index.java From orion.server with Eclipse Public License 1.0 | 5 votes |
public ObjectStream toObjectStream() throws IOException { DirCache cache = db.readDirCache(); DirCacheEntry entry = cache.getEntry(pattern); if (entry == null) { return null; } try { ObjectId blobId = entry.getObjectId(); return db.open(blobId, Constants.OBJ_BLOB).openStream(); } catch (MissingObjectException e) { return null; } }
Example #14
Source File: Scenario5WithDefaultsTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_C_commit() { ObjectId cCommit = scenario.getCommits().get("C"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(cCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.0-1")); }
Example #15
Source File: Utils.java From netbeans with Apache License 2.0 | 5 votes |
public static RevCommit findCommit (Repository repository, String revision, RevWalk walk) throws GitException.MissingObjectException, GitException { ObjectId commitId = parseObjectId(repository, revision); if (commitId == null) { throw new GitException.MissingObjectException(revision, GitObjectType.COMMIT); } return findCommit(repository, commitId, walk); }
Example #16
Source File: TextDiffPanel.java From onedev with MIT License | 5 votes |
private ObjectId getNewCommit() { String newRev = change.getNewBlobIdent().revision; if (newRev.equals(ObjectId.zeroId().name().toString())) { return ObjectId.zeroId(); } else { return projectModel.getObject().getRevCommit(newRev, true); } }
Example #17
Source File: Scenario8WithoutGPrefixCommitTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test void version_of_C_commit() { ObjectId cCommit = scenario.getCommits().get("C"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(cCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.1" + "-" + cCommit.name().substring(0,8))); }
Example #18
Source File: Scenario1AutoIncTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_D_commit() { ObjectId cCommit = scenario.getCommits().get("D"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(cCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("2.0.0")); }
Example #19
Source File: Scenario4WithDefaultsTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_A_commit() { ObjectId firstCommit = scenario.getCommits().get("A"); // checkout the first commit in scenario unchecked(() -> git.checkout().setName(firstCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("0.0.0-SNAPSHOT")); }
Example #20
Source File: Scenario5AutoIncTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_D_commit() { ObjectId dCommit = scenario.getCommits().get("D"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(dCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.1-1")); }
Example #21
Source File: Tags.java From gradle-gitsemver with Apache License 2.0 | 5 votes |
private static TagAndVersion findLatestTopoTag(Repository repo, Map<ObjectId, Set<String>> allTags, String prefix) throws MissingObjectException, IncorrectObjectTypeException, IOException { try { RevWalk walk = new RevWalk(repo); walk.markStart(walk.parseCommit(GitRepos.getHeadObjectId(repo))); for (RevCommit commit : walk) { ObjectId commitId = commit.getId(); // Find the very first tag in history if (allTags.containsKey(commitId)) { List<TagAndVersion> foundTags = new LinkedList<TagAndVersion>(); // If there are more than one tag for this commit, choose the lexographically superior one for (String tagName : allTags.get(commitId)) { String tagVersion = GitRepos.stripVFromVersionString(tagName); if (prefix == null) { foundTags.add(new TagAndVersion(tagName, SemanticVersions.parse(tagVersion))); } else { foundTags.add(new TagAndVersion(tagName, SemanticVersions.parse(prefix, tagVersion))); } } Collections.sort(foundTags); return foundTags.get(foundTags.size() - 1); } } // No tags found - return null return null; } catch (NullPointerException e) { return new TagAndVersion("0.0.0", new DefaultSemanticVersion( "0.0.0", 0, 0, 0, null, null)); } }
Example #22
Source File: Scenario5WithMasterAndIntBranchesNonQualifiedTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_B_commit() { ObjectId bCommit = scenario.getCommits().get("B"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(bCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.1-SNAPSHOT")); }
Example #23
Source File: Scenario3WithDefaultsTest.java From jgitver with Apache License 2.0 | 5 votes |
@Test public void version_of_B_commit() { ObjectId bCommit = scenario.getCommits().get("B"); // checkout the commit in scenario unchecked(() -> git.checkout().setName(bCommit.name()).call()); assertThat(versionCalculator.getVersion(), is("1.0.0")); }
Example #24
Source File: GitBlameHandlerV1.java From orion.server with Eclipse Public License 1.0 | 5 votes |
@Override protected boolean handleGet(RequestInfo requestInfo) throws ServletException { HttpServletRequest request = requestInfo.request; HttpServletResponse response = requestInfo.response; try { URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.BLAME); Path Filepath = new Path(requestInfo.filePath.toString()); if (Filepath.hasTrailingSeparator()) { String msg = NLS.bind("Cannot get blame Information on a folder: {0}", requestInfo.filePath.toString()); return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null)); } Blame blame = new Blame(cloneLocation, requestInfo.db); String gitSegment = requestInfo.gitSegment; if (!gitSegment.equalsIgnoreCase("HEAD") && !gitSegment.equalsIgnoreCase("master")) { ObjectId id = ObjectId.fromString(requestInfo.gitSegment); blame.setStartCommit(id); } String path = requestInfo.relativePath; blame.setFilePath(path); blame.setBlameLocation(getURI(request)); doBlame(blame, requestInfo.db); OrionServlet.writeJSONResponse(request, response, blame.toJSON(), JsonURIUnqualificationStrategy.ALL_NO_GIT); return true; } catch (Exception e) { return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating blame response", e)); } }
Example #25
Source File: TreeSnapshotLoadTest.java From ParallelGit with Apache License 2.0 | 5 votes |
@Test public void loadTreeWithSubtree_theSubtreeEntryFileModeShouldBeTree() throws IOException { writeToCache("/dir/some_file.txt"); ObjectId tree = commit().getTree(); TreeSnapshot snapshot = TreeSnapshot.load(tree, repo); assertEquals(TREE, snapshot.getChild("dir").getMode()); }
Example #26
Source File: BlobEditsTest.java From onedev with MIT License | 5 votes |
@Test public void testMoveFiles() throws IOException { createDir("client"); addFileAndCommit("client/a.java", "a", "add a"); addFileAndCommit("client/b.java", "b", "add b"); createDir("server/src/com/example/a"); createDir("server/src/com/example/b"); addFileAndCommit("server/src/com/example/a/a.java", "a", "add a"); addFileAndCommit("server/src/com/example/b/b.java", "b", "add b"); String refName = "refs/heads/master"; ObjectId oldCommitId = git.getRepository().resolve(refName); Set<String> oldPaths = Sets.newHashSet("server/src/com/example/a/a.java", "server/src/com/example/b/b.java"); Map<String, BlobContent> newBlobs = new HashMap<>(); newBlobs.put("client/c.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE)); newBlobs.put("client/d.java", new BlobContent.Immutable("a".getBytes(), FileMode.REGULAR_FILE)); BlobEdits edits = new BlobEdits(oldPaths, newBlobs); ObjectId newCommitId = edits.commit(git.getRepository(), refName, oldCommitId, oldCommitId, user, "test rename"); try (RevWalk revWalk = new RevWalk(git.getRepository())) { RevTree revTree = revWalk.parseCommit(newCommitId).getTree(); assertNotNull(TreeWalk.forPath(git.getRepository(), "client/a.java", revTree)); assertNotNull(TreeWalk.forPath(git.getRepository(), "client/b.java", revTree)); assertNotNull(TreeWalk.forPath(git.getRepository(), "client/c.java", revTree)); assertNotNull(TreeWalk.forPath(git.getRepository(), "client/d.java", revTree)); assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/a", revTree)); assertNull(TreeWalk.forPath(git.getRepository(), "server/src/com/example/b", revTree)); } }
Example #27
Source File: GitAPITestCase.java From git-client-plugin with MIT License | 5 votes |
public void test_getHeadRev_returns_accurate_SHA1_values() throws Exception { /* CliGitAPIImpl had a longstanding bug that it inserted the * same SHA1 in all the values, rather than inserting the SHA1 * which matched the key. */ w = clone(localMirror()); w.git.checkout().ref("master").execute(); final ObjectId master = w.head(); w.git.branch("branch1"); w.git.checkout().ref("branch1").execute(); w.touch("file1", "content1"); w.git.add("file1"); w.git.commit("commit1-branch1"); final ObjectId branch1 = w.head(); w.launchCommand("git", "branch", "branch.2", "master"); w.git.checkout().ref("branch.2").execute(); File f = w.touch("file.2", "content2"); w.git.add("file.2"); w.git.commit("commit2-branch.2"); final ObjectId branchDot2 = w.head(); assertTrue("file.2 does not exist", f.exists()); Map<String,ObjectId> heads = w.git.getHeadRev(w.repoPath()); assertEquals("Wrong master in " + heads, master, heads.get("refs/heads/master")); assertEquals("Wrong branch1 in " + heads, branch1, heads.get("refs/heads/branch1")); assertEquals("Wrong branch.2 in " + heads, branchDot2, heads.get("refs/heads/branch.2")); assertEquals("wildcard branch.2 mismatch", branchDot2, w.git.getHeadRev(w.repoPath(), "br*.2")); check_headRev(w.repoPath(), getMirrorHead()); }
Example #28
Source File: GfsMergeGeneralCaseTest.java From ParallelGit with Apache License 2.0 | 5 votes |
@Test public void whenMergeSucceedWithNewCommit_theParentsAreTheHeadsOfCurrentAndSourceBranch() throws IOException { ObjectId ourHead = getHeadCommit(OURS, repo); ObjectId theirHead = getHeadCommit(THEIRS, repo); Result result = merge(gfs).source(THEIRS).execute(); assertTrue(result.isSuccessful()); assertNotNull(result.getCommit()); assertEquals(ourHead, result.getCommit().getParent(0)); assertEquals(theirHead, result.getCommit().getParent(1)); }
Example #29
Source File: TreeSnapshotLoadTest.java From ParallelGit with Apache License 2.0 | 5 votes |
@Test public void loadTree_theChildrenEntriesShouldHaveTheCorrectIds() throws IOException { ObjectId id1 = writeToCache("/file1.txt"); ObjectId id2 = writeToCache("/file2.txt"); ObjectId tree = commit().getTree(); TreeSnapshot snapshot = TreeSnapshot.load(tree, repo); assertEquals(id1, snapshot.getChild("file1.txt").getId()); assertEquals(id2, snapshot.getChild("file2.txt").getId()); }
Example #30
Source File: GitVersionCalculatorImpl.java From jgitver with Apache License 2.0 | 5 votes |
private ObjectId latestObjectIdOfTags(List<Ref> reachableTags, Function<Ref, ObjectId> refToObjectIdFunction) { try (TagDateExtractor dateExtractor = new TagDateExtractor(repository)) { return reachableTags.stream() .map(r -> new Pair<Ref, Date>(r, dateExtractor.dateOfRef(r))) .max(Comparator.comparing(p -> ((Date) p.getRight()))) .map(p -> (Ref) p.getLeft()) .map(refToObjectIdFunction) .orElseThrow(() -> new IllegalStateException(String.format("could not find most recent tag"))); } }