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: GitPushEmbedded.java    From git-as-svn with GNU General Public License v2.0 6 votes vote down vote up
@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 #2
Source File: GitServiceImpl.java    From RefactoringMiner with MIT License 6 votes vote down vote up
@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 #3
Source File: BlobEditsTest.java    From onedev with MIT License 6 votes vote down vote up
@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: GitRepository.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
@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 #5
Source File: GitContentRepository.java    From studio with GNU General Public License v3.0 6 votes vote down vote up
@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 #6
Source File: GitRepo.java    From git-changelog-lib with Apache License 2.0 6 votes vote down vote up
/**
 * @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 #7
Source File: GitProctor.java    From proctor with Apache License 2.0 6 votes vote down vote up
@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: Scenario6WithSpecificFindTagPatternTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@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("3.0.1-SNAPSHOT"));
}
 
Example #9
Source File: DistanceCalculatorTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void distance_from_head_to_head_is_0() throws Exception {
    ObjectId eCommit = scenario.getCommits().get("E");
    unchecked(() -> git.checkout().setName(eCommit.name()).call());

    ObjectId headId = repository.resolve("HEAD");
    DistanceCalculator distanceCalculator = DistanceCalculator.create(headId, repository);

    Optional<Integer> distanceTo = distanceCalculator.distanceTo(headId);

    assertThat("distance to head should always return a value", distanceTo, notNullValue());
    assertTrue(distanceTo.isPresent(), "distance to head should always return a non empty value");
    assertThat(distanceTo.get(), is(0));
}
 
Example #10
Source File: Scenario4AutoIncTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@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.1-1"));
}
 
Example #11
Source File: Scenario2AutoIncTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@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 #12
Source File: TaskKey.java    From git-lfs-migrate with MIT License 5 votes vote down vote up
public TaskKey(@NotNull GitConverter.TaskType type, @Nullable String path, @NotNull ObjectId objectId) {
  this.type = type;
  this.path = path;
  this.objectId = objectId.copy();
  if (type.needPath() == (path == null)) {
    throw new IllegalStateException();
  }
}
 
Example #13
Source File: DistanceCalculator.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Override
public Optional<Integer> distanceTo(ObjectId target) {
    Objects.requireNonNull(target);
    try (RevWalk walk = new RevWalk(this.repository)) {
        RevCommit startCommit = walk.parseCommit(startId);
        walk.setRetainBody(false);
        walk.markStart(startCommit);
        walk.sort(RevSort.TOPO);

        System.out.printf("from %s :: %s\n", startId.name(), target.name());

        Iterator<? extends RevCommit> commitIterator = walk.iterator();
        int distance = 0;
        while (commitIterator.hasNext()) {
            RevCommit commit = commitIterator.next();

            System.out.printf("%d - %s\n", distance, commit.getId().name());
            if (commit.getId().getName().equals(target.getName())) {
                // we found it
                return Optional.of(distance);
            }

            distance++;

            if (distance > maxDepth) {
                return Optional.empty();
            }
        }
    } catch (Exception ignore) {
        ignore.printStackTrace();
    }

    return Optional.empty();
}
 
Example #14
Source File: TreeUtilsInsertTreeTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void insertTreeIntoRepository_shouldBeAbleToRetrieveChildrenIdsByTreeIdAndFilename() throws IOException {
  initRepository();

  TreeFormatter tf = new TreeFormatter();
  ObjectId nodeObject1 = someObjectId();
  tf.append("file1.txt", REGULAR_FILE, nodeObject1);
  ObjectId nodeObject2 = someObjectId();
  tf.append("file2.txt", REGULAR_FILE, nodeObject2);
  ObjectId tree = TreeUtils.insertTree(tf, repo);

  assertEquals(nodeObject1, TreeUtils.getObjectId("file1.txt", tree, repo));
  assertEquals(nodeObject2, TreeUtils.getObjectId("file2.txt", tree, repo));
}
 
Example #15
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 5 votes vote down vote up
/**
 * revListAll.
 *
 * @return a {@link java.util.List} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 * @throws java.lang.InterruptedException if interrupted.
 */
@Override
public List<ObjectId> revListAll() throws GitException, InterruptedException {
    List<ObjectId> oidList = new ArrayList<>();
    RevListCommand revListCommand = revList_();
    revListCommand.all(true);
    revListCommand.to(oidList);
    revListCommand.execute();
    return oidList;
}
 
Example #16
Source File: CommitInput.java    From onedev with MIT License 5 votes vote down vote up
public static Object convertToObject(List<String> strings) {
	if (strings.size() == 0) {
		return null;
	} else if (strings.size() == 1) {
		String value = strings.iterator().next();
		if (ObjectId.isId(value))
			return value;
		else
			throw new ValidationException("Invalid commit id");
	} else {
		throw new ValidationException("Not eligible for multi-value");
	}
}
 
Example #17
Source File: RepoMerger.java    From git-merge-repos with Apache License 2.0 5 votes vote down vote up
private MergedRef mergeBranch(String branch) throws IOException {

		Map<SubtreeConfig, ObjectId> resolvedRefs = resolveRefs(
				"refs/heads/original/", branch);

		Map<SubtreeConfig, RevCommit> parentCommits = new LinkedHashMap<>();
		try (RevWalk revWalk = new RevWalk(repository)) {
			for (SubtreeConfig config : subtreeConfigs) {
				ObjectId objectId = resolvedRefs.get(config);
				if (objectId != null) {
					RevCommit commit = revWalk.parseCommit(objectId);
					parentCommits.put(config, commit);
				}
			}
		}

		MergedRef mergedRef = getMergedRef("branch", branch, parentCommits.keySet());

		ObjectId mergeCommit = new SubtreeMerger(repository).createMergeCommit(parentCommits,
				mergedRef.getMessage());

		RefUpdate refUpdate = repository.updateRef("refs/heads/" + branch);
		refUpdate.setNewObjectId(mergeCommit);
		refUpdate.update();

		return mergedRef;
	}
 
Example #18
Source File: GitChangeResolver.java    From smart-testing with Apache License 2.0 5 votes vote down vote up
private boolean isAnyCommitExists() {
    try {
        final ObjectId head = git.getRepository().resolve("HEAD" + ENSURE_TREE);
        return head != null;
    } catch (IOException e) {
        throw new IllegalArgumentException(e);
    }
}
 
Example #19
Source File: Scenario3WithDefaultsTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void version_of_F_commit() {
    ObjectId fCommit = scenario.getCommits().get("F");
    
    // checkout the commit in scenario
    unchecked(() -> git.checkout().setName(fCommit.name()).call());
    assertThat(versionCalculator.getVersion(), is("3.0.0-SNAPSHOT"));
}
 
Example #20
Source File: BlobUtilsReadBlobTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void getBlobSize_shouldReturnTheLengthOfTheByteArray() throws IOException {
  byte[] bytes = someBytes();
  ObjectId blob = writeToCache(someFilename(), bytes);
  commit();

  assertEquals(bytes.length, BlobUtils.getBlobSize(blob, repo));
}
 
Example #21
Source File: Scenario6WithDefaultsTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@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("2.0.0"));
}
 
Example #22
Source File: Scenario11WithDefaultsTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void version_of_C_commit() {
    ObjectId cCommit = scenario.getCommits().get("C");
    
    // checkout the first commit in scenario
    unchecked(() -> git.checkout().setName(cCommit.name()).call());
    assertThat(versionCalculator.getVersion(), is("0.0.0-2"));
}
 
Example #23
Source File: Scenario15WithMaxVersionTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void version_of_E_commit() {
    ObjectId cCommit = scenario.getCommits().get("E");

    // checkout the commit in scenario
    unchecked(() -> git.checkout().setName(cCommit.name()).call());
    assertThat(versionCalculator.getVersion(), is("4.0.0-2"));
}
 
Example #24
Source File: Scenario12WithDefaultsTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void version_of_D_commit() {
    ObjectId dCommit = scenario.getCommits().get("D");

    // checkout the first commit in scenario
    unchecked(() -> git.checkout().setName(dCommit.name()).call());
    assertThat(versionCalculator.getVersion(), is("1.0.0-SNAPSHOT"));
}
 
Example #25
Source File: TreeSnapshotSaveTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void createSnapshotAndSave_shouldFindChildrenEntriesFromTreeId() throws IOException {
  SortedMap<String, GitFileEntry> children = new TreeMap<>();
  GitFileEntry entry1 = newEntry(someObjectId(), REGULAR_FILE);
  children.put("file1.txt", entry1);
  GitFileEntry entry2 = newEntry(someObjectId(), REGULAR_FILE);
  children.put("file2.txt", entry2);
  ObjectId treeId = TreeSnapshot.capture(children).save(repo);

  assertEquals(entry1, newEntry("file1.txt", treeId, repo));
  assertEquals(entry2, newEntry("file2.txt", treeId, repo));
}
 
Example #26
Source File: Scenario4AutoIncTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@Test
public void version_of_G_commit() {
    ObjectId gCommit = scenario.getCommits().get("G");
    
    // checkout the commit in scenario
    unchecked(() -> git.checkout().setName(gCommit.name()).call());
    assertThat(versionCalculator.getVersion(), is("1.0.1-3"));
}
 
Example #27
Source File: GitRepo.java    From git-changelog-lib with Apache License 2.0 5 votes vote down vote up
private List<Ref> tagsBetweenFromAndTo(final ObjectId from, final ObjectId to) throws Exception {
  final List<Ref> tagList = this.git.tagList().call();
  final List<RevCommit> icludedCommits = newArrayList(this.git.log().addRange(from, to).call());
  final List<Ref> includedTags = newArrayList();
  for (final Ref tag : tagList) {
    final ObjectId peeledTag = getPeeled(tag);
    if (icludedCommits.contains(peeledTag)) {
      includedTags.add(tag);
    }
  }
  return includedTags;
}
 
Example #28
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_revList_remote_branch() throws Exception {
    w = clone(localMirror());
    List<ObjectId> revList = w.git.revList("origin/1.4.x");
    assertEquals("Wrong list size: " + revList, 267, revList.size());
    Ref branchRef = w.repo().findRef("origin/1.4.x");
    assertTrue("origin/1.4.x not in revList", revList.contains(branchRef.getObjectId()));
}
 
Example #29
Source File: Scenario1WithDefaultsTest.java    From jgitver with Apache License 2.0 5 votes vote down vote up
@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 #30
Source File: GfsResetTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test
public void resetWithSoftOption_fileSystemRootTreeShouldNotBeChanged() throws IOException {
  writeSomethingToCache();
  RevCommit revision = commit();
  writeSomethingToGfs();
  ObjectId before = gfs.getFileStore().getRoot().getObjectId(false);
  GfsReset.Result result = Gfs.reset(gfs).revision(revision.getName()).soft(true).execute();
  ObjectId after = gfs.getFileStore().getRoot().getObjectId(false);

  assertTrue(result.isSuccessful());
  assertEquals(before, after);
}