Java Code Examples for org.eclipse.jgit.lib.ObjectId#fromString()

The following examples show how to use org.eclipse.jgit.lib.ObjectId#fromString() . 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: GitMergeUtil.java    From MergeProcessor with Apache License 2.0 7 votes vote down vote up
/**
 * {@code git cherryPick}
 * 
 * @throws MergeCancelException
 */
private void cherryPick() {
	final ObjectId id = ObjectId.fromString(mergeUnit.getRevisionInfo());
	try {
		final CherryPickResult result = repo.cherryPick().include(id).setNoCommit(true).call();
		switch (result.getStatus()) {
		case CONFLICTING:
			final Collection<String> conflicts = repo.status().call().getConflicting();
			resolveConflicts(conflicts);
			break;
		case FAILED:
			exception = new MergeUnitException(String.format("Could not cherry pick the given commit '%s'", //$NON-NLS-1$
					mergeUnit.getRevisionInfo()));
			break;
		default:
			break;
		}
	} catch (GitAPIException e) {
		exception = new MergeUnitException(String.format("Could not cherry pick from the given id %s.", id), e); //$NON-NLS-1$
	}
}
 
Example 2
Source File: GitProctor.java    From proctor with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public List<Revision> getHistory(final String test,
                                 final String revision,
                                 final int start,
                                 final int limit) throws StoreException {
    try {
        final ObjectId commitId = ObjectId.fromString(revision);
        final LogCommand logCommand = git.log()
                // TODO: create path to definition.json file, sanitize test name for invalid / relative characters
                .addPath(getTestDefinitionsDirectory() + File.separator + test + File.separator + FileBasedProctorStore.TEST_DEFINITION_FILENAME)
                .add(commitId)
                .setSkip(start)
                .setMaxCount(limit);
        return getHistoryFromLogCommand(logCommand);

    } catch (final IOException e) {
        throw new StoreException("Could not get history for " + test + " starting at " + getGitCore().getRefName(), e);
    }
}
 
Example 3
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 6 votes vote down vote up
/**
 * Test getHeadRev with namespaces in the branch name
 * and branch specs starting with "refs/heads/".
 */
public void test_getHeadRev_namespaces_withRefsHeads() throws Exception {
    File tempRemoteDir = temporaryDirectoryAllocator.allocate();
    extract(new ZipFile("src/test/resources/namespaceBranchRepo.zip"), tempRemoteDir);
    Properties commits = parseLsRemote(new File("src/test/resources/namespaceBranchRepo.ls-remote"));
    w = clone(tempRemoteDir.getAbsolutePath());
    final String remote = tempRemoteDir.getAbsolutePath();

    final String[][] checkBranchSpecs = {
            {"refs/heads/master", commits.getProperty("refs/heads/master")},
            {"refs/heads/a_tests/b_namespace1/master", commits.getProperty("refs/heads/a_tests/b_namespace1/master")},
            {"refs/heads/a_tests/b_namespace2/master", commits.getProperty("refs/heads/a_tests/b_namespace2/master")},
            {"refs/heads/a_tests/b_namespace3/master", commits.getProperty("refs/heads/a_tests/b_namespace3/master")},
            {"refs/heads/b_namespace3/master", commits.getProperty("refs/heads/b_namespace3/master")}
            };

    for(String[] branch : checkBranchSpecs) {
        final ObjectId objectId = ObjectId.fromString(branch[1]);
        final String branchName = branch[0];
        check_getHeadRev(remote, branchName, objectId);
    }
}
 
Example 4
Source File: RevisionTest.java    From git-client-plugin with MIT License 6 votes vote down vote up
@Test
public void testContainsBranchName() {
    assertFalse(revision1.containsBranchName(branchName));

    assertFalse(revision2.containsBranchName(branchName));

    assertTrue(revisionWithBranches.containsBranchName(branchName));
    String myBranchName = "working-branch-name";
    assertFalse(revisionWithBranches.containsBranchName(myBranchName));

    String mySHA1 = "aaaaaaaa72a6433fe503d294ebb7d5691b590269";
    Branch myBranch = new Branch(myBranchName, ObjectId.fromString(mySHA1));
    Collection<Branch> branches = new ArrayList<>();
    Revision rev = new Revision(ObjectId.fromString(sha1a), branches);
    assertFalse(rev.containsBranchName(myBranchName));

    branches.add(myBranch);
    rev.setBranches(branches);
    assertTrue(rev.containsBranchName(myBranchName));
    assertFalse(rev.containsBranchName(branchName));

    branches.add(branch);
    rev.setBranches(branches);
    assertTrue(rev.containsBranchName(branchName));
}
 
Example 5
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 6 votes vote down vote up
/** {@inheritDoc} */
@Override
public ObjectId getHeadRev(String url, String branchSpec) throws GitException, InterruptedException {
    final String branchName = extractBranchNameFromBranchSpec(branchSpec);
    ArgumentListBuilder args = new ArgumentListBuilder("ls-remote");
    if(!branchName.startsWith("refs/tags/")) {
        args.add("-h");
    }

    StandardCredentials cred = credentials.get(url);
    if (cred == null) cred = defaultCredentials;

    addCheckedRemoteUrl(args, url);

    if (branchName.startsWith("refs/tags/")) {
        args.add(branchName+"^{}"); // JENKINS-23299 - tag SHA1 needs to be converted to commit SHA1
    } else {
        args.add(branchName);
    }
    String result = launchCommandWithCredentials(args, null, cred, url);
    return result.length()>=40 ? ObjectId.fromString(result.substring(0, 40)) : null;
}
 
Example 6
Source File: DefaultBuildManager.java    From onedev with MIT License 6 votes vote down vote up
@SuppressWarnings("unchecked")
private void fillStatus(Project project, Collection<ObjectId> commitIds, 
		Map<ObjectId, Map<String, Collection<Status>>> commitStatuses) {
	Query<?> query = getSession().createQuery("select commitHash, jobName, status from Build "
			+ "where project=:project and commitHash in :commitHashes");
	query.setParameter("project", project);
	query.setParameter("commitHashes", commitIds.stream().map(it->it.name()).collect(Collectors.toList()));
	for (Object[] row: (List<Object[]>)query.list()) {
		ObjectId commitId = ObjectId.fromString((String) row[0]);
		String jobName = (String) row[1];
		Status status = (Status) row[2];
		Map<String, Collection<Status>> commitStatus = commitStatuses.get(commitId);
		if (commitStatus == null) {
			commitStatus = new HashMap<>();
			commitStatuses.put(commitId, commitStatus);
		}
		Collection<Status> jobStatus = commitStatus.get(jobName);
		if (jobStatus == null) {
			jobStatus = new HashSet<>();
			commitStatus.put(jobName, jobStatus);
		}
		jobStatus.add(status);
	}
}
 
Example 7
Source File: MergePreview.java    From onedev with MIT License 5 votes vote down vote up
public void syncRef(PullRequest request) {
	Project project = request.getTargetProject();
	ObjectId mergedId = getMergeCommitHash()!=null? ObjectId.fromString(getMergeCommitHash()): null;
	RefUpdate refUpdate = GitUtils.getRefUpdate(project.getRepository(), request.getMergeRef());
	if (mergedId != null && !mergedId.equals((project.getObjectId(request.getMergeRef(), false)))) {
		refUpdate.setNewObjectId(mergedId);
		GitUtils.updateRef(refUpdate);
	} else if (mergeCommitHash == null && project.getObjectId(request.getMergeRef(), false) != null) {
		GitUtils.deleteRef(refUpdate);
	}		
}
 
Example 8
Source File: PullRequestChangesPage.java    From onedev with MIT License 5 votes vote down vote up
@Nullable
private Mark getPermanentMark(Mark mark) {
	ObjectId oldCommitId = ObjectId.fromString(state.oldCommitHash);
	if (mark.getCommitHash().equals(getComparisonBase().name())) {
		return mark.mapTo(getProject(), oldCommitId);
	} else if (mark.getCommitHash().equals(state.oldCommitHash) 
				|| mark.getCommitHash().equals(state.newCommitHash)) {
		return mark;
	} else {
		return null;
	}
}
 
Example 9
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
private ObjectId getMirrorHead() throws IOException, InterruptedException
{
    if (mirrorHead == null) {
        final String mirrorPath = new File(localMirror()).getAbsolutePath();
        mirrorHead = ObjectId.fromString(w.launchCommand("git", "--git-dir=" + mirrorPath, "rev-parse", "HEAD").substring(0,40));
    }
    return mirrorHead;
}
 
Example 10
Source File: GitBlameHandlerV1.java    From orion.server with Eclipse Public License 1.0 5 votes vote down vote up
@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 11
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
public void test_show_revision_for_single_commit() throws Exception {
    w = clone(localMirror());
    ObjectId to = ObjectId.fromString("51de9eda47ca8dcf03b2af58dfff7355585f0d0c");
    List<String> revisionDetails = w.git.showRevision(null, to);
    Collection<String> commits = Collections2.filter(revisionDetails, (String detail) -> detail.startsWith("commit "));
    assertEquals(1, commits.size());
    assertTrue(commits.contains("commit 51de9eda47ca8dcf03b2af58dfff7355585f0d0c"));
}
 
Example 12
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-23299")
public void test_getHeadRev() throws Exception {
    Map<String, ObjectId> heads = w.git.getHeadRev(remoteMirrorURL);
    ObjectId master = w.git.getHeadRev(remoteMirrorURL, "refs/heads/master");
    assertEquals("URL is " + remoteMirrorURL + ", heads is " + heads, master, heads.get("refs/heads/master"));

    /* Test with a specific tag reference - JENKINS-23299 */
    ObjectId knownTag = w.git.getHeadRev(remoteMirrorURL, "refs/tags/git-client-1.10.0");
    ObjectId expectedTag = ObjectId.fromString("1fb23708d6b639c22383c8073d6e75051b2a63aa"); // commit SHA1
    assertEquals("Wrong SHA1 for git-client-1.10.0 tag", expectedTag, knownTag);
}
 
Example 13
Source File: GitAPITestCase.java    From git-client-plugin with MIT License 4 votes vote down vote up
public void test_getHeadRev_remote() throws Exception {
    String lsRemote = w.launchCommand("git", "ls-remote", "-h", remoteMirrorURL, "refs/heads/master");
    ObjectId lsRemoteId = ObjectId.fromString(lsRemote.substring(0, 40));
    check_headRev(remoteMirrorURL, lsRemoteId);
}
 
Example 14
Source File: TagTest.java    From git-client-plugin with MIT License 4 votes vote down vote up
@Before
public void assignTag() {
    String tagName = "git-client-1.8.1";
    ObjectId tagSHA1 = ObjectId.fromString("3725b67f3daa6621dd01356c96c08a1f85b90c61");
    tag = new Tag(tagName, tagSHA1);
}
 
Example 15
Source File: PullRequest.java    From onedev with MIT License 4 votes vote down vote up
public ObjectId getComparisonBase(ObjectId oldCommitId, ObjectId newCommitId) {
	if (isNew() || oldCommitId.equals(newCommitId))
		return oldCommitId;
	
	PullRequestInfoManager infoManager = OneDev.getInstance(PullRequestInfoManager.class);
	ObjectId comparisonBase = infoManager.getComparisonBase(this, oldCommitId, newCommitId);
	if (comparisonBase != null) {
		try {
			if (!getTargetProject().getRepository().getObjectDatabase().has(comparisonBase))
				comparisonBase = null;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	if (comparisonBase == null) {
		for (PullRequestUpdate update: getSortedUpdates()) {
			if (update.getCommits().contains(newCommitId)) {
				ObjectId targetHead = ObjectId.fromString(update.getTargetHeadCommitHash());
				Repository repo = getTargetProject().getRepository();
				ObjectId mergeBase1 = GitUtils.getMergeBase(repo, targetHead, newCommitId);
				if (mergeBase1 != null) {
					ObjectId mergeBase2 = GitUtils.getMergeBase(repo, mergeBase1, oldCommitId);
					if (mergeBase2.equals(mergeBase1)) {
						comparisonBase = oldCommitId;
						break;
					} else if (mergeBase2.equals(oldCommitId)) {
						comparisonBase = mergeBase1;
						break;
					} else {
						PersonIdent person = new PersonIdent("OneDev", "");
						comparisonBase = GitUtils.merge(repo, oldCommitId, mergeBase1, false, 
								person, person, "helper commit", true);
						break;
					}
				} else {
					return oldCommitId;
				}
			}
		}
		if (comparisonBase != null)
			infoManager.cacheComparisonBase(this, oldCommitId, newCommitId, comparisonBase);
		else
			throw new IllegalSelectorException();
	}
	return comparisonBase;
}
 
Example 16
Source File: PullRequestChangesPage.java    From onedev with MIT License 4 votes vote down vote up
@Override
protected ObjectId load() {
	ObjectId oldCommitId = ObjectId.fromString(state.oldCommitHash);
	ObjectId newCommitId = ObjectId.fromString(state.newCommitHash);
	return getPullRequest().getComparisonBase(oldCommitId, newCommitId);
}
 
Example 17
Source File: ObjectIdDeserializer.java    From onedev with MIT License 4 votes vote down vote up
@Override
public ObjectId deserialize(JsonParser jp, DeserializationContext ctxt)
		throws IOException, JsonProcessingException {
	return ObjectId.fromString(jp.getValueAsString());
}
 
Example 18
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
@Nullable
public <C> C getFileContents(
        final Class<C> c,
        final String[] path,
        @Nullable final C defaultValue,
        final String revision
) throws StoreException.ReadException, JsonProcessingException {
    try {
        if (!ObjectId.isId(revision)) {
            throw new StoreException.ReadException("Malformed id " + revision);
        }
        final ObjectId blobOrCommitId = ObjectId.fromString(revision);

        final ObjectLoader loader = git.getRepository().open(blobOrCommitId);

        if (loader.getType() == Constants.OBJ_COMMIT) {
            // look up the file at this revision
            final RevCommit commit = RevCommit.parse(loader.getCachedBytes());

            final TreeWalk treeWalk2 = new TreeWalk(git.getRepository());
            treeWalk2.addTree(commit.getTree());
            treeWalk2.setRecursive(true);
            final String joinedPath = String.join("/", path);
            treeWalk2.setFilter(PathFilter.create(joinedPath));

            if (!treeWalk2.next()) {
                // it did not find expected file `joinPath` so return default value
                return defaultValue;
            }
            final ObjectId blobId = treeWalk2.getObjectId(0);
            return getFileContents(c, blobId);
        } else if (loader.getType() == Constants.OBJ_BLOB) {
            return getFileContents(c, blobOrCommitId);
        } else {
            throw new StoreException.ReadException("Invalid Object Type " + loader.getType() + " for id " + revision);
        }
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}
 
Example 19
Source File: GitProctorCore.java    From proctor with Apache License 2.0 4 votes vote down vote up
@Override
public TestVersionResult determineVersions(final String fetchRevision) throws StoreException.ReadException {
    try {
        final RevWalk walk = new RevWalk(git.getRepository());
        final ObjectId commitId = ObjectId.fromString(fetchRevision);
        final RevCommit headTree = walk.parseCommit(commitId);
        final RevTree tree = headTree.getTree();

        // now use a TreeWalk to iterate over all files in the Tree recursively
        // you can set Filters to narrow down the results if needed
        final TreeWalk treeWalk = new TreeWalk(git.getRepository());
        treeWalk.addTree(tree);
        treeWalk.setFilter(AndTreeFilter
            .create(PathFilter.create(testDefinitionsDirectory), PathSuffixFilter.create("definition.json")));
        treeWalk.setRecursive(true);

        final List<TestVersionResult.Test> tests = Lists.newArrayList();
        while (treeWalk.next()) {
            final ObjectId id = treeWalk.getObjectId(0);
            // final RevTree revTree = walk.lookupTree(id);

            final String path = treeWalk.getPathString();
            final String[] pieces = path.split("/");
            final String testname = pieces[pieces.length - 2]; // tree / parent directory name

            // testname, blobid pair
            // note this is the blobid hash - not a commit hash
            // RevTree.id and RevBlob.id
            tests.add(new TestVersionResult.Test(testname, id.name()));
        }

        walk.dispose();
        return new TestVersionResult(
                tests,
                new Date(Long.valueOf(headTree.getCommitTime()) * 1000 /* convert seconds to milliseconds */),
                determineAuthorId(headTree),
                headTree.toObjectId().getName(),
                headTree.getFullMessage()
        );
    } catch (final IOException e) {
        throw new StoreException.ReadException(e);
    }
}
 
Example 20
Source File: CliGitAPIImpl.java    From git-client-plugin with MIT License 3 votes vote down vote up
/**
 * validateRevision.
 *
 * @param revName a {@link java.lang.String} object.
 * @return a {@link org.eclipse.jgit.lib.ObjectId} object.
 * @throws hudson.plugins.git.GitException if underlying git operation fails.
 * @throws java.lang.InterruptedException if interrupted.
 */
public ObjectId validateRevision(String revName) throws GitException, InterruptedException {
    String result = launchCommand("rev-parse", "--verify", revName);
    String line = StringUtils.trimToNull(result);
    if (line == null)
        throw new GitException("null result from rev-parse(" + revName +")");
    return ObjectId.fromString(line);
}