Example usage for org.eclipse.jgit.lib ObjectId fromString

List of usage examples for org.eclipse.jgit.lib ObjectId fromString

Introduction

In this page you can find the example usage for org.eclipse.jgit.lib ObjectId fromString.

Prototype

public static ObjectId fromString(String str) 

Source Link

Document

Convert an ObjectId from hex characters.

Usage

From source file:com.google.gitiles.PathServletTest.java

License:Open Source License

@Test
public void gitlinkHtml() throws Exception {
    String gitmodules = "[submodule \"gitiles\"]\n" + "  path = gitiles\n"
            + "  url = https://gerrit.googlesource.com/gitiles\n";
    final String gitilesSha = "2b2f34bba3c2be7e2506ce6b1f040949da350cf9";
    repo.branch("master").commit().add(".gitmodules", gitmodules).edit(new PathEdit("gitiles") {
        @Override/*from  ww w  . j  ava 2s .c om*/
        public void apply(DirCacheEntry ent) {
            ent.setFileMode(FileMode.GITLINK);
            ent.setObjectId(ObjectId.fromString(gitilesSha));
        }
    }).create();

    Map<String, ?> data = buildData("/repo/+/master/gitiles");
    assertEquals("GITLINK", data.get("type"));

    Map<String, ?> linkData = getBlobData(data);
    assertEquals(gitilesSha, linkData.get("sha"));
    assertEquals("https://gerrit.googlesource.com/gitiles", linkData.get("remoteUrl"));
    assertEquals("https://gerrit.googlesource.com/gitiles", linkData.get("httpUrl"));
}

From source file:com.google.gitiles.PathServletTest.java

License:Open Source License

@Test
public void nonBlobText() throws Exception {
    String gitmodules = "[submodule \"gitiles\"]\n" + "  path = gitiles\n"
            + "  url = https://gerrit.googlesource.com/gitiles\n";
    final String gitilesSha = "2b2f34bba3c2be7e2506ce6b1f040949da350cf9";
    repo.branch("master").commit().add("foo/bar", "contents").add(".gitmodules", gitmodules)
            .edit(new PathEdit("gitiles") {
                @Override//w w w  .ja  v  a2 s. com
                public void apply(DirCacheEntry ent) {
                    ent.setFileMode(FileMode.GITLINK);
                    ent.setObjectId(ObjectId.fromString(gitilesSha));
                }
            }).create();

    assertNotFound("/repo/+/master/nonexistent?format=TEXT");
    assertNotFound("/repo/+/master/gitiles?format=TEXT");
}

From source file:com.google.gitiles.TreeSoyDataTest.java

License:Open Source License

public void testResolveTargetUrl() throws Exception {
    ObjectId id = ObjectId.fromString("abcd1234abcd1234abcd1234abcd1234abcd1234");
    GitilesView view = GitilesView.path().setServletPath("/x").setHostName("host").setRepositoryName("repo")
            .setRevision(Revision.unpeeled("m", id)).setTreePath("a/b/c").build();
    assertNull(resolveTargetUrl(view, "/foo"));
    assertEquals("/x/repo/+/m/a", resolveTargetUrl(view, "../../"));
    assertEquals("/x/repo/+/m/a", resolveTargetUrl(view, ".././../"));
    assertEquals("/x/repo/+/m/a", resolveTargetUrl(view, "..//../"));
    assertEquals("/x/repo/+/m/a/d", resolveTargetUrl(view, "../../d"));
    assertEquals("/x/repo/+/m/", resolveTargetUrl(view, "../../.."));
    assertEquals("/x/repo/+/m/a/d/e", resolveTargetUrl(view, "../../d/e"));
    assertEquals("/x/repo/+/m/a/b", resolveTargetUrl(view, "../d/../e/../"));
    assertNull(resolveTargetUrl(view, "../../../../"));
    assertNull(resolveTargetUrl(view, "../../a/../../.."));
}

From source file:com.google.jenkins.plugins.metadata.scm.SourceMetadataBuildListenerTest.java

License:Open Source License

@Test
public void onChangeLogParsed_git() throws Exception {
    build.addAction(buildData);/*from  w w w.java2s  .  c  o  m*/
    Revision revision = new Revision(ObjectId.fromString(REVISION));
    when(buildData.getRemoteUrls()).thenReturn(ImmutableSet.of(REPO_URL));
    when(buildData.getLastBuiltRevision()).thenReturn(revision);
    when(buildData.getBuildsByBranchName())
            .thenReturn(ImmutableMap.of("wrong-branch", new Build(revision, buildNum + 1, Result.SUCCESS),
                    "right-branch", new Build(revision, buildNum, Result.SUCCESS)));

    underTest.onChangeLogParsed(build, null, null, changes);

    SourceMetadata source = (SourceMetadata) Iterables
            .getOnlyElement(MetadataContainer.getMetadata(build).get(SourceMetadata.SOURCE_KEY));
    assertNotNull(source);
    assertEquals("git", source.getSCM());
    assertEquals("right-branch", source.getBranch());
    assertEquals(REVISION, source.getRevision());
    assertEquals(REPO_URL, source.getRepoUrl());
    assertEquals(AUTHOR_1, source.getLastAuthor());
}

From source file:com.google.jenkins.plugins.metadata.scm.SourceMetadataBuildListenerTest.java

License:Open Source License

@Test
public void onChangeLogParsed_multiSCM() throws Exception {
    project.setScm(multiScm);/*from  www  . j  a v  a 2  s  . com*/
    when(multiScm.getConfiguredSCMs()).thenReturn(ImmutableList.<SCM>of(mercurialScm));
    when(mercurialScm.getBranch()).thenReturn("hg-branch");
    when(mercurialScm.getSource()).thenReturn(REPO_URL);
    when(mercurialScm.getSubdir()).thenReturn("foo");
    build.addAction(new MercurialTagAction(REVISION, "7", "foo"));
    build.addAction(buildData);
    Revision revision = new Revision(ObjectId.fromString(REVISION));
    when(buildData.getRemoteUrls()).thenReturn(ImmutableSet.of(REPO_URL));
    when(buildData.getLastBuiltRevision()).thenReturn(revision);
    when(buildData.getBuildsByBranchName())
            .thenReturn(ImmutableMap.of("git-branch", new Build(revision, buildNum, Result.SUCCESS)));

    underTest.onChangeLogParsed(build, multiScm, null, changes);

    ImmutableList<MetadataValue> metadata = ImmutableList
            .copyOf(MetadataContainer.getMetadata(build).get(SourceMetadata.SOURCE_KEY));
    assertEquals(2, metadata.size());
    assertTrue(metadata.contains(new SourceMetadata("git", REPO_URL, "git-branch", REVISION, AUTHOR_1)));
    assertTrue(metadata.contains(new SourceMetadata("mercurial", REPO_URL, "hg-branch", REVISION, AUTHOR_1)));
}

From source file:com.googlesource.gerrit.plugins.github.git.PullRequestImportJob.java

License:Apache License

private List<Id> addPullRequestToChange(ReviewDb db, GHPullRequest pr, Repository gitRepo) throws Exception {
    String destinationBranch = pr.getBase().getRef();
    List<Id> prChanges = Lists.newArrayList();
    ObjectId baseObjectId = ObjectId.fromString(pr.getBase().getSha());
    ObjectId prHeadObjectId = ObjectId.fromString(pr.getHead().getSha());

    RevWalk walk = new RevWalk(gitRepo);
    walk.markUninteresting(walk.lookupCommit(baseObjectId));
    walk.markStart(walk.lookupCommit(prHeadObjectId));
    walk.sort(RevSort.REVERSE);/*from www  . j  a  v a  2s  .co  m*/

    int patchNr = 1;
    for (GHPullRequestCommitDetail ghCommitDetail : pr.listCommits()) {
        status.update(Code.SYNC, "Patch #" + patchNr,
                "Patch#" + patchNr + ": Inserting PullRequest into Gerrit");
        RevCommit revCommit = walk.parseCommit(ObjectId.fromString(ghCommitDetail.getSha()));

        GHUser prUser = pr.getUser();
        GitUser commitAuthor = ghCommitDetail.getCommit().getAuthor();
        GitHubUser gitHubUser = GitHubUser.from(prUser, commitAuthor);

        Account.Id pullRequestOwner = getOrRegisterAccount(db, gitHubUser);
        Id changeId = createChange.addCommitToChange(db, project, gitRepo, destinationBranch, pullRequestOwner,
                revCommit, getChangeMessage(pr), String.format(TOPIC_FORMAT, pr.getNumber()), false);
        if (changeId != null) {
            prChanges.add(changeId);
        }
    }

    return prChanges;
}

From source file:com.googlesource.gerrit.plugins.github.wizard.PullRequestListController.java

License:Apache License

private boolean isAnyCommitOfPullRequestToBeImported(ReviewDb db, Repository gitRepo,
        GHPullRequest ghPullRequest) throws IncorrectObjectTypeException, IOException {
    boolean pullRequestToImport = false;
    RevWalk gitWalk = new RevWalk(gitRepo);
    for (GHPullRequestCommitDetail pullRequestCommit : ghPullRequest.listCommits()) {
        ObjectId pullRequestHeadObjectId = ObjectId.fromString(pullRequestCommit.getSha());

        try {// w w  w  .  j a  va 2s . co m
            gitWalk.parseCommit(pullRequestHeadObjectId);

            ResultSet<PatchSet> patchSets;
            try {
                patchSets = db.patchSets().byRevision(new RevId(pullRequestCommit.getSha()));
            } catch (OrmException e) {
                LOG.error("Error whilst fetching patch-sets from DB associated to commit "
                        + pullRequestCommit.getSha());
                return false;
            }
            pullRequestToImport = !patchSets.iterator().hasNext();
            patchSets.close();
        } catch (MissingObjectException e) {
            pullRequestToImport = true;
        }
    }
    return pullRequestToImport;
}

From source file:com.googlesource.gerrit.plugins.refprotection.BackupRef.java

License:Open Source License

public void createBackup(RefUpdatedEvent event, ProjectResource project) {
    String refName = event.getRefName();

    try (Repository git = repoManager.openRepository(project.getNameKey())) {
        String backupRef = get(project, refName);

        // No-op if the backup branch name is same as the original
        if (backupRef.equals(refName)) {
            return;
        }/*from ww  w.j  a  v  a  2 s.  co  m*/

        try (RevWalk revWalk = new RevWalk(git)) {
            RefUpdateAttribute refUpdate = event.refUpdate.get();
            if (cfg.getFromGerritConfig(pluginName).getBoolean("createTag", false)) {
                TagBuilder tag = new TagBuilder();
                AccountAttribute submitter = event.submitter.get();
                tag.setTagger(new PersonIdent(submitter.name, submitter.email));
                tag.setObjectId(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)));
                String update = "Non-fast-forward update to";
                if (refUpdate.newRev.equals(ObjectId.zeroId().getName())) {
                    update = "Deleted";
                }
                String type = "branch";
                String fullMessage = "";
                if (refUpdate.refName.startsWith(R_TAGS)) {
                    type = "tag";
                    try {
                        RevTag origTag = revWalk.parseTag(ObjectId.fromString(refUpdate.oldRev));
                        SimpleDateFormat format = new SimpleDateFormat("EEE MMM d HH:mm:ss yyyy ZZZZ");
                        PersonIdent taggerIdent = origTag.getTaggerIdent();
                        String tagger = String.format("Tagger: %s <%s>\nDate:   %s", taggerIdent.getName(),
                                taggerIdent.getEmailAddress(), format.format(taggerIdent.getWhen()));
                        fullMessage = "\n\nOriginal tag:\n" + tagger + "\n\n" + origTag.getFullMessage();
                    } catch (MissingObjectException e) {
                        log.warn("Original tag does not exist", e);
                    } catch (IncorrectObjectTypeException e) {
                        log.warn("Original tag was not a tag", e);
                    } catch (IOException e) {
                        log.warn("Unable to read original tag details", e);
                    }
                }
                tag.setMessage(update + " " + type + " " + refUpdate.refName + fullMessage);
                tag.setTag(backupRef);

                ObjectInserter inserter = git.newObjectInserter();
                ObjectId tagId = inserter.insert(tag);
                inserter.flush();
                RefUpdate tagRef = git.updateRef(tag.getTag());
                tagRef.setNewObjectId(tagId);
                tagRef.setRefLogMessage("tagged deleted branch/tag " + tag.getTag(), false);
                tagRef.setForceUpdate(false);
                Result result = tagRef.update();
                switch (result) {
                case NEW:
                case FORCED:
                    log.debug("Successfully created backup tag");
                    break;

                case LOCK_FAILURE:
                    log.error("Failed to lock repository while creating backup tag");
                    break;

                case REJECTED:
                    log.error("Tag already exists while creating backup tag");
                    break;

                default:
                    log.error("Unknown error while creating backup tag");
                }
            } else {
                BranchInput input = new BranchInput();
                input.ref = backupRef;
                // We need to parse the commit to ensure if it's a tag, we get the
                // commit the tag points to!
                input.revision = ObjectId
                        .toString(revWalk.parseCommit(ObjectId.fromString(refUpdate.oldRev)).getId());

                try {
                    createBranchFactory.create(backupRef).apply(project, input);
                } catch (BadRequestException | AuthException | ResourceConflictException | IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
    } catch (RepositoryNotFoundException e) {
        log.error("Repository does not exist", e);
    } catch (IOException e) {
        log.error("Could not open repository", e);
    }
}

From source file:com.googlesource.gerrit.plugins.reviewersbyblame.ChangeUpdatedListener.java

License:Apache License

@Override
public void onEvent(Event event) {
    if (!(event instanceof PatchSetCreatedEvent)) {
        return;/*from  w ww  .  j a  v  a 2  s .c o m*/
    }
    PatchSetCreatedEvent e = (PatchSetCreatedEvent) event;
    Project.NameKey projectName = e.getProjectNameKey();

    int maxReviewers;
    boolean ignoreDrafts;
    String ignoreSubjectRegEx;
    try {
        maxReviewers = cfg.getFromProjectConfigWithInheritance(projectName, pluginName).getInt("maxReviewers",
                3);
        ignoreDrafts = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getBoolean("ignoreDrafts", false);
        ignoreSubjectRegEx = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getString("ignoreSubjectRegEx", "");
    } catch (NoSuchProjectException x) {
        log.error(x.getMessage(), x);
        return;
    }
    if (maxReviewers <= 0) {
        return;
    }

    try (final Repository git = repoManager.openRepository(projectName)) {
        try (final RevWalk rw = new RevWalk(git)) {
            final ReviewDb reviewDb = schemaFactory.open();
            try {
                Change.Id changeId = new Change.Id(Integer.parseInt(e.change.get().number));
                PatchSet.Id psId = new PatchSet.Id(changeId, Integer.parseInt(e.patchSet.get().number));
                PatchSet ps = reviewDb.patchSets().get(psId);
                if (ps == null) {
                    log.warn("Patch set " + psId.get() + " not found.");
                    return;
                }

                if (ignoreDrafts && ps.isDraft()) {
                    return;
                }

                final Change change = reviewDb.changes().get(psId.getParentKey());
                if (change == null) {
                    log.warn("Change " + changeId.get() + " not found.");
                    return;
                }

                final RevCommit commit = rw.parseCommit(ObjectId.fromString(e.patchSet.get().revision));

                if (!ignoreSubjectRegEx.isEmpty() && commit.getShortMessage().matches(ignoreSubjectRegEx)) {
                    return;
                }

                final Runnable task = reviewersByBlameFactory.create(commit, change, ps, maxReviewers, git);

                workQueue.getDefaultQueue().submit(new Runnable() {
                    @Override
                    public void run() {
                        RequestContext old = tl.setContext(new RequestContext() {

                            @Override
                            public CurrentUser getUser() {
                                return identifiedUserFactory.create(change.getOwner());
                            }

                            @Override
                            public Provider<ReviewDb> getReviewDbProvider() {
                                return new Provider<ReviewDb>() {
                                    @Override
                                    public ReviewDb get() {
                                        if (db == null) {
                                            try {
                                                db = schemaFactory.open();
                                            } catch (OrmException e) {
                                                throw new ProvisionException("Cannot open ReviewDb", e);
                                            }
                                        }
                                        return db;
                                    }
                                };
                            }
                        });
                        try {
                            task.run();
                        } finally {
                            tl.setContext(old);
                            if (db != null) {
                                db.close();
                                db = null;
                            }
                        }
                    }
                });
            } finally {
                reviewDb.close();
            }
        }
    } catch (OrmException | IOException x) {
        log.error(x.getMessage(), x);
    }
}

From source file:com.googlesource.gerrit.plugins.reviewersbyblame.RefUpdateListener.java

License:Apache License

@Override
public void onGitReferenceUpdated(final Event e) {
    Project.NameKey projectName = new Project.NameKey(e.getProjectName());
    Repository git;//  w  w  w.  j a  v  a2 s. co  m
    try {
        git = repoManager.openRepository(projectName);
    } catch (RepositoryNotFoundException x) {
        log.error(x.getMessage(), x);
        return;
    } catch (IOException x) {
        log.error(x.getMessage(), x);
        return;
    }

    final ReviewDb reviewDb;
    final RevWalk rw = new RevWalk(git);

    try {
        reviewDb = schemaFactory.open();
        try {
            for (Update u : e.getUpdates()) {
                if (!u.getRefName().startsWith("refs/changes/")) {
                    continue;
                }

                PatchSet.Id psId = PatchSet.Id.fromRef(u.getRefName());
                PatchSet ps = reviewDb.patchSets().get(psId);
                final Change change = reviewDb.changes().get(psId.getParentKey());

                final RevCommit commit = rw.parseCommit(ObjectId.fromString(u.getNewObjectId()));
                int maxReviewers = 3; //TODO Move to config

                final Runnable task = reviewersByBlameFactory.create(commit, change, ps, maxReviewers, git);

                workQueue.getDefaultQueue().submit(new Runnable() {
                    public void run() {
                        RequestContext old = tl.setContext(new RequestContext() {

                            @Override
                            public CurrentUser getCurrentUser() {
                                return identifiedUserFactory.create(change.getOwner());
                            }

                            @Override
                            public Provider<ReviewDb> getReviewDbProvider() {
                                return new Provider<ReviewDb>() {
                                    @Override
                                    public ReviewDb get() {
                                        if (db == null) {
                                            try {
                                                db = schemaFactory.open();
                                            } catch (OrmException e) {
                                                throw new ProvisionException("Cannot open ReviewDb", e);
                                            }
                                        }
                                        return db;
                                    }
                                };
                            }
                        });
                        try {
                            task.run();
                        } finally {
                            tl.setContext(old);
                            if (db != null) {
                                db.close();
                                db = null;
                            }
                        }
                    }
                });
            }
        } catch (OrmException x) {
            log.error(x.getMessage(), x);
        } catch (MissingObjectException x) {
            log.error(x.getMessage(), x);
        } catch (IncorrectObjectTypeException x) {
            log.error(x.getMessage(), x);
        } catch (IOException x) {
            log.error(x.getMessage(), x);
        } finally {
            reviewDb.close();
        }
    } catch (OrmException x) {
        log.error(x.getMessage(), x);
    } finally {
        rw.release();
        git.close();
    }
}