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.googlesource.gerrit.plugins.smartreviewers.ChangeUpdatedListener.java

License:Apache License

@Override
public void onChangeEvent(ChangeEvent event) {
    if (!(event instanceof PatchSetCreatedEvent)) {
        return;//from   www  . j  a  v  a2 s .  c  om
    }
    PatchSetCreatedEvent e = (PatchSetCreatedEvent) event;
    Project.NameKey projectName = new Project.NameKey(e.change.project);

    int maxReviewers, weightBlame, weightLastReviews, weightWorkload;
    try {
        maxReviewers = cfg.getFromProjectConfigWithInheritance(projectName, pluginName).getInt("maxReviewers",
                3);
        weightBlame = cfg.getFromProjectConfigWithInheritance(projectName, pluginName).getInt("weightBlame", 1);
        weightLastReviews = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getInt("weightLastReviews", 1);
        weightWorkload = cfg.getFromProjectConfigWithInheritance(projectName, pluginName)
                .getInt("weightWorkload", -1);
    } catch (NoSuchProjectException x) {
        log.error(x.getMessage(), x);
        return;
    }
    if (maxReviewers <= 0) {
        return;
    }

    Repository git;
    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 {
            Change.Id changeId = new Change.Id(Integer.parseInt(e.change.number));
            PatchSet.Id psId = new PatchSet.Id(changeId, Integer.parseInt(e.patchSet.number));
            PatchSet ps = reviewDb.patchSets().get(psId);
            if (ps == null) {
                log.warn("Patch set " + psId.get() + " not found.");
                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.revision));

            final Runnable task = smartReviewersFactory.create(commit, change, ps, maxReviewers, weightBlame,
                    weightLastReviews, weightWorkload, git, reviewDb);

            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);
        }
    } catch (OrmException x) {
        log.error(x.getMessage(), x);
    } finally {
        rw.release();
        git.close();
    }
}

From source file:com.googlesource.gerrit.plugins.xdocs.XDocResourceKey.java

License:Apache License

private static ObjectId toObjectId(String id) {
    return !Strings.isNullOrEmpty(id) ? ObjectId.fromString(id) : null;
}

From source file:com.googlesource.gerrit.plugins.zuul.GetCrd.java

License:Apache License

@Override
@SuppressWarnings("unchecked")
public CrdInfo apply(RevisionResource rsrc) throws RepositoryNotFoundException, IOException,
        BadRequestException, AuthException, OrmException, PermissionBackendException {

    CrdInfo out = new CrdInfo();
    out.dependsOn = new ArrayList<>();
    out.neededBy = new ArrayList<>();

    // get depends on info
    Project.NameKey p = rsrc.getChange().getProject();
    try (Repository repo = repoManager.openRepository(p); RevWalk rw = new RevWalk(repo)) {
        String rev = rsrc.getPatchSet().getRevision().get();
        RevCommit commit = rw.parseCommit(ObjectId.fromString(rev));
        String commitMsg = commit.getFullMessage();
        Pattern pattern = Pattern.compile("[Dd]epends-[Oo]n:? (I[0-9a-f]{8,40})", Pattern.DOTALL);
        Matcher matcher = pattern.matcher(commitMsg);
        while (matcher.find()) {
            out.dependsOn.add(matcher.group(1));
        }/*from   w  w  w. ja  v a2  s  . com*/
    }

    // get needed by info
    Change.Key chgKey = rsrc.getChange().getKey();
    QueryChanges query = changes.list();
    String neededByQuery = "message:" + chgKey + " -change:" + chgKey;
    query.addQuery(neededByQuery);
    List<ChangeInfo> changes = (List<ChangeInfo>) query.apply(TopLevelResource.INSTANCE);
    // check for dependency cycles
    for (ChangeInfo change : changes) {
        if (out.dependsOn.contains(change.changeId)) {
            out.cycle = true;
        }
        out.neededBy.add(change.changeId);
    }

    return out;
}

From source file:com.googlesrouce.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   w w  w  .  j  a  va2 s .  c  om

    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()));

        Account.Id pullRequestOwner;
        // It may happen that the user that created the Pull Request has been
        // removed from GitHub: we assume that the commit author was that user
        // as there are no other choices.
        if (pr.getUser() == null) {
            pullRequestOwner = getOrRegisterAccount(db, ghCommitDetail.getCommit().getAuthor());
        } else {
            pullRequestOwner = getOrRegisterAccount(db, pr.getUser());
        }

        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.madgag.agit.GitIntents.java

License:Open Source License

public static ObjectId commitIdFrom(Intent intent) {
    return ObjectId.fromString(intent.getStringExtra("commit"));
}

From source file:com.madgag.agit.matchers.HasGitObjectMatcher.java

License:Open Source License

@Factory
public static <T> Matcher<Repository> hasGitObject(String objectId) {
    return new HasGitObjectMatcher(ObjectId.fromString(objectId));
}

From source file:com.mangosolutions.rcloud.rawgist.repository.git.ReadGistOperation.java

private RevCommit resolveCommit(Repository repository) throws IOException {
    try (RevWalk revWalk = new RevWalk(repository)) {
        if (StringUtils.isEmpty(commitId)) {
            Ref head = repository.exactRef(REF_HEAD_MASTER);
            if (head != null) {
                return revWalk.parseCommit(head.getObjectId());
            }/*from   w  w w  .  j ava2 s .  co  m*/
            return null;
        } else {
            return revWalk.parseCommit(ObjectId.fromString(this.commitId));
        }
    }
}

From source file:com.meltmedia.cadmium.core.git.GitService.java

License:Apache License

public String getBranchName() throws Exception {
    Repository repository = git.getRepository();
    if (ObjectId.isId(repository.getFullBranch())
            && repository.getFullBranch().equals(repository.resolve("HEAD").getName())) {
        RevWalk revs = null;/*  w w  w.j a  va  2  s.c  o m*/
        try {
            log.trace("Trying to resolve tagname: {}", repository.getFullBranch());
            ObjectId tagRef = ObjectId.fromString(repository.getFullBranch());
            revs = new RevWalk(repository);
            RevCommit commit = revs.parseCommit(tagRef);
            Map<String, Ref> allTags = repository.getTags();
            for (String key : allTags.keySet()) {
                Ref ref = allTags.get(key);
                RevTag tag = revs.parseTag(ref.getObjectId());
                log.trace("Checking ref {}, {}", commit.getName(), tag.getObject());
                if (tag.getObject().equals(commit)) {
                    return key;
                }
            }
        } catch (Exception e) {
            log.warn("Invalid id: {}", repository.getFullBranch(), e);
        } finally {
            revs.release();
        }
    }
    return repository.getBranch();
}

From source file:com.microsoft.gittf.core.config.ChangesetCommitMap.java

License:Open Source License

/**
 * Gets the commit id that this changeset id refers to. If the caller
 * specified the validate flag as true, the method also ensures that the
 * commit id refers to a valid commit. If not NULL is returned.
 * //  w  ww  . j  av a  2  s.c  o  m
 * @param changesetID
 *        the changeset id
 * @param validate
 *        whether or not to validate the object id found
 * @return
 */
public ObjectId getCommitID(int changesetID, boolean validate) {
    Check.isTrue(changesetID >= 0, "changesetID >= 0"); //$NON-NLS-1$

    ensureConfigUptoDate();

    String commitHash = configFile.getString(ConfigurationConstants.CONFIGURATION_SECTION,
            ConfigurationConstants.COMMIT_SUBSECTION, MessageFormat
                    .format(ConfigurationConstants.COMMIT_CHANGESET_FORMAT, Integer.toString(changesetID)));

    if (commitHash == null) {
        return null;
    }

    ObjectId changesetCommitId = ObjectId.fromString(commitHash);

    if (!validate) {
        return changesetCommitId;
    }

    ObjectReader objectReader = null;
    try {
        objectReader = repository.newObjectReader();
        if (changesetCommitId != null && !ObjectId.zeroId().equals(changesetCommitId)) {
            try {
                if (objectReader.has(changesetCommitId)) {
                    return changesetCommitId;
                }
            } catch (IOException exception) {
                return null;
            }
        }

        return null;
    } finally {
        if (objectReader != null) {
            objectReader.release();
        }
    }
}

From source file:com.pramati.gerrit.plugin.helpers.GetFileFromRepo.java

License:Apache License

/**
 * returns the File Stream from the gerrit repository. returns "null" if the
 * given file not found in the repository.<br>
 * patchStr should like in given format::"changeid/patchsetID/filename" <br>
 * eg: 1/2/readme.md/*from w w  w .j av a 2s . c o m*/
 * 
 * @param patchStr
 * @return
 * @throws IOException
 */
public static BufferedInputStream doGetFile(String patchStr) throws IOException {
    final Patch.Key patchKey;
    final Change.Id changeId;
    final Project project;
    final PatchSet patchSet;
    final Repository repo;
    final ReviewDb db;
    final ChangeControl control;
    try {
        patchKey = Patch.Key.parse(patchStr);
    } catch (NumberFormatException e) {
        return null;
    }
    changeId = patchKey.getParentKey().getParentKey();

    try {
        db = requestDb.get();
        control = changeControl.validateFor(changeId);

        project = control.getProject();
        patchSet = db.patchSets().get(patchKey.getParentKey());
        if (patchSet == null) {
            return null;
            // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        }
    } catch (NoSuchChangeException e) {
        // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
        return null;
    } catch (OrmException e) {
        // getServletContext().log("Cannot query database", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    try {
        repo = repoManager.openRepository(project.getNameKey());
    } catch (RepositoryNotFoundException e) {
        // getServletContext().log("Cannot open repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    }

    final ObjectLoader blobLoader;
    final RevCommit fromCommit;
    final String path = patchKey.getFileName();
    try {
        final ObjectReader reader = repo.newObjectReader();
        try {
            final RevWalk rw = new RevWalk(reader);
            final RevCommit c;
            final TreeWalk tw;

            c = rw.parseCommit(ObjectId.fromString(patchSet.getRevision().get()));
            fromCommit = c;

            tw = TreeWalk.forPath(reader, path, fromCommit.getTree());
            if (tw == null) {
                // rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
                return null;
            }

            if (tw.getFileMode(0).getObjectType() == Constants.OBJ_BLOB) {
                blobLoader = reader.open(tw.getObjectId(0), Constants.OBJ_BLOB);

            } else {
                // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return null;
            }
        } finally {
            reader.release();
        }
    } catch (IOException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } catch (RuntimeException e) {
        // getServletContext().log("Cannot read repository", e);
        // rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        return null;
    } finally {
        repo.close();
    }
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    blobLoader.copyTo(out);
    byte[] b = out.toByteArray();
    BufferedInputStream br = new BufferedInputStream(new ByteArrayInputStream(b));
    return br;
}