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

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

Introduction

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

Prototype

public final String name() 

Source Link

Document

name.

Usage

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

License:Open Source License

static Tree toJsonData(ObjectId id, TreeWalk tw) throws IOException {
    Tree tree = new Tree();
    tree.id = id.name();
    tree.entries = Lists.newArrayList();
    while (tw.next()) {
        Entry e = new Entry();
        FileMode mode = tw.getFileMode(0);
        e.mode = mode.getBits();/* w w  w  . j a v  a 2  s .com*/
        e.type = Constants.typeString(mode.getObjectType());
        e.id = tw.getObjectId(0).name();
        e.name = tw.getNameString();
        tree.entries.add(e);
    }
    return tree;
}

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

License:Open Source License

public Map<String, Object> toSoyData(ObjectId treeId, TreeWalk tw) throws MissingObjectException, IOException {
    List<Object> entries = Lists.newArrayList();
    GitilesView.Builder urlBuilder = GitilesView.path().copyFrom(view);
    while (tw.next()) {
        FileType type = FileType.forEntry(tw);
        String name = tw.getNameString();

        switch (view.getType()) {
        case PATH:
            urlBuilder.setTreePath(view.getTreePath() + "/" + name);
            break;
        case REVISION:
            // Got here from a tag pointing at a tree.
            urlBuilder.setTreePath(name);
            break;
        default:/* www.j  a  v  a2  s.  c  om*/
            throw new IllegalStateException(
                    String.format("Cannot render TreeSoyData from %s view", view.getType()));
        }

        String url = urlBuilder.toUrl();
        if (type == FileType.TREE) {
            name += "/";
            url += "/";
        }
        Map<String, String> entry = Maps.newHashMapWithExpectedSize(4);
        entry.put("type", type.toString());
        entry.put("name", name);
        entry.put("url", url);
        if (type == FileType.SYMLINK) {
            String target = new String(rw.getObjectReader().open(tw.getObjectId(0)).getCachedBytes(),
                    Charsets.UTF_8);
            // TODO(dborowitz): Merge Shawn's changes before copying these methods
            // in.
            entry.put("targetName", getTargetDisplayName(target));
            String targetUrl = resolveTargetUrl(view, target);
            if (targetUrl != null) {
                entry.put("targetUrl", targetUrl);
            }
        }
        entries.add(entry);
    }

    Map<String, Object> data = Maps.newHashMapWithExpectedSize(3);
    data.put("sha", treeId.name());
    data.put("entries", entries);

    if (view.getType() == GitilesView.Type.PATH && view.getRevision().getPeeledType() == OBJ_COMMIT) {
        data.put("logUrl", GitilesView.log().copyFrom(view).toUrl());
    }

    return data;
}

From source file:com.googlesource.gerrit.plugins.changefabricator.ChangeFabricator.java

License:Apache License

@Override
public Response<String> apply(ProjectResource rsrc, Input input)
        throws AuthException, OrmException, InvalidChangeOperationException, IOException {
    String ref = input.ref;//from   w w  w  .  j  ava 2  s  . c  om
    String msg = input.msg;
    if (Strings.isNullOrEmpty(ref)) {
        throw new InvalidChangeOperationException("Change baker: Destination branch cannot be null or empty");
    }

    if (Strings.isNullOrEmpty(msg)) {
        throw new InvalidChangeOperationException("Change baker: Commit message cannot be null or empty");
    }

    if (!userProvider.get().isIdentifiedUser()) {
        throw new AuthException("User must be authenticated to create a change");
    }

    RefControl refControl = rsrc.getControl().controlForRef(ref);
    if (!refControl.canUpload()) {
        throw new AuthException(String.format("Not allowed to create a change to %s", ref));
    }

    Project.NameKey project = rsrc.getNameKey();
    final Repository git;
    try {
        git = gitManager.openRepository(project);
    } catch (RepositoryNotFoundException e) {
        throw new InvalidChangeOperationException("Cannot open repo");
    }

    try {
        RevWalk rw = new RevWalk(git);
        try {
            Ref destRef = git.getRef(ref);
            if (destRef == null) {
                throw new InvalidChangeOperationException("Branch " + ref + " does not exist.");
            }

            RevCommit mergeTip = rw.parseCommit(destRef.getObjectId());

            PersonIdent authorIdent = ((IdentifiedUser) userProvider.get()).newCommitterIdent(myIdent.getWhen(),
                    myIdent.getTimeZone());

            ObjectId computedChangeId = ChangeIdUtil.computeChangeId(mergeTip.getTree(), mergeTip,
                    mergeTip.getAuthorIdent(), myIdent, msg);

            String commitMessage = ChangeIdUtil.insertId(msg, computedChangeId);

            RevCommit emptyCommit;
            ObjectInserter oi = git.newObjectInserter();

            try {
                CommitBuilder commit = new CommitBuilder();
                commit.setTreeId(mergeTip.getTree().getId());
                commit.setParentId(mergeTip);
                commit.setAuthor(authorIdent);
                commit.setCommitter(authorIdent);
                commit.setMessage(commitMessage);
                emptyCommit = rw.parseCommit(insert(oi, commit));
            } finally {
                oi.release();
            }

            if (emptyCommit == null) {
                throw new IllegalStateException("Cannot create empty change");
            }
            Preconditions.checkNotNull(emptyCommit);

            Change.Key changeKey;
            final List<String> idList = emptyCommit.getFooterLines(CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                changeKey = new Change.Key("I" + computedChangeId.name());
            }

            Id changeId = createNewChange(git, rw, changeKey, project, destRef, emptyCommit, refControl);
            return Response.ok(String.valueOf(changeId.get()));
        } finally {
            rw.release();
        }
    } finally {
        git.close();
    }
}

From source file:com.googlesource.gerrit.plugins.download.command.GitDownloadCommand.java

License:Apache License

private String resolveRef(String project, String ref) {
    if (project.startsWith("$") || ref.startsWith("$")) {
        // No real value but placeholders are being used.
        return ref;
    }/*w w  w. j a v  a2 s.  com*/

    try (Repository repo = repoManager.openRepository(new Project.NameKey(project))) {
        Config cfg = repo.getConfig();
        boolean allowSha1InWant = cfg.getBoolean(UPLOADPACK, KEY_ALLOW_TIP_SHA1_IN_WANT, false)
                || cfg.getBoolean(UPLOADPACK, KEY_ALLOW_REACHABLE_SHA1_IN_WANT, false);
        if (allowSha1InWant && Arrays.asList(cfg.getStringList(UPLOADPACK, null, KEY_HIDE_REFS))
                .contains(RefNames.REFS_CHANGES)) {
            ObjectId id = repo.resolve(ref);
            if (id != null) {
                return id.name();
            }
            log.error(String.format("Cannot resolve ref %s in project %s.", ref, project));
            return null;
        }
        return ref;
    } catch (RepositoryNotFoundException e) {
        log.error(String.format("Missing project: %s", project), e);
        return null;
    } catch (IOException e) {
        log.error(String.format("Failed to lookup project %s from cache.", project), e);
        return null;
    }
}

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

License:Apache License

public Change.Id addCommitToChange(final ReviewDb db, final Project project, final Repository git,
        final String destinationBranch, final Account.Id pullRequestOwner, final RevCommit pullRequestCommit,
        final String pullRequestMesage, final String topic, boolean doValidation) throws NoSuchChangeException,
        EmailException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException,
        InvalidChangeOperationException, MergeException, NoSuchProjectException {
    Id newChange = null;//w ww .  j a  v a 2 s  .co m
    if (destinationBranch == null || destinationBranch.length() == 0) {
        throw new InvalidChangeOperationException("Destination branch cannot be null or empty");
    }

    RefControl refControl = projectControlFactory.controlFor(project.getNameKey())
            .controlForRef(destinationBranch);

    try {
        RevWalk revWalk = new RevWalk(git);
        try {
            Ref destRef = git.getRef(destinationBranch);
            if (destRef == null) {
                throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist.");
            }

            String pullRequestSha1 = pullRequestCommit.getId().getName();
            ResultSet<PatchSet> existingPatchSet = db.patchSets().byRevision(new RevId(pullRequestSha1));
            Iterator<PatchSet> patchSetIterator = existingPatchSet.iterator();
            if (patchSetIterator.hasNext()) {
                PatchSet patchSet = patchSetIterator.next();
                LOG.debug("Pull request commit ID " + pullRequestSha1
                        + " has been already uploaded as PatchSetID=" + patchSet.getPatchSetId()
                        + " in ChangeID=" + patchSet.getId());
                return null;
            }

            Change.Key changeKey;
            final List<String> idList = pullRequestCommit.getFooterLines(CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(),
                        pullRequestCommit, pullRequestCommit.getAuthorIdent(),
                        pullRequestCommit.getCommitterIdent(), pullRequestMesage);

                changeKey = new Change.Key("I" + computedChangeId.name());
            }

            List<Change> destChanges = db.changes()
                    .byBranchKey(new Branch.NameKey(project.getNameKey(), destRef.getName()), changeKey)
                    .toList();

            if (destChanges.size() > 1) {
                throw new InvalidChangeOperationException("Multiple Changes with Change-ID " + changeKey
                        + " already exist on the target branch: cannot add a new patch-set "
                        + destinationBranch);
            } else if (destChanges.size() == 1) {
                // The change key exists on the destination branch: adding a new
                // patch-set
                Change destChange = destChanges.get(0);

                ChangeControl changeControl = projectControlFactory.controlFor(project.getNameKey())
                        .controlFor(destChange).forUser(userFactory.create(pullRequestOwner));

                return insertPatchSet(git, revWalk, destChange, pullRequestCommit, changeControl,
                        pullRequestOwner, pullRequestMesage, doValidation);
            } else {
                // Change key not found on destination branch. We can create a new
                // change.
                return (newChange = createNewChange(db, git, revWalk, changeKey, project.getNameKey(), destRef,
                        pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, topic,
                        doValidation));
            }
        } finally {
            revWalk.release();
            if (newChange == null) {
                db.rollback();
            }
        }
    } finally {
        git.close();
    }
}

From source file:com.googlesrouce.gerrit.plugins.github.git.PullRequestCreateChange.java

License:Apache License

public Change.Id addCommitToChange(final ReviewDb db, final Project project, final Repository git,
        final String destinationBranch, final Account.Id pullRequestOwner, final RevCommit pullRequestCommit,
        final String pullRequestMesage, final String topic, boolean doValidation) throws NoSuchChangeException,
        EmailException, OrmException, MissingObjectException, IncorrectObjectTypeException, IOException,
        InvalidChangeOperationException, MergeException, NoSuchProjectException {
    Id newChange = null;/*from w w w  .  java2s.  c o m*/
    if (destinationBranch == null || destinationBranch.length() == 0) {
        throw new InvalidChangeOperationException("Destination branch cannot be null or empty");
    }

    RefControl refControl = projectControlFactor.controlFor(project.getNameKey())
            .controlForRef(destinationBranch);

    try {
        RevWalk revWalk = new RevWalk(git);
        try {
            Ref destRef = git.getRef(destinationBranch);
            if (destRef == null) {
                throw new InvalidChangeOperationException("Branch " + destinationBranch + " does not exist.");
            }

            String pullRequestSha1 = pullRequestCommit.getId().getName();
            ResultSet<PatchSet> existingPatchSet = db.patchSets().byRevision(new RevId(pullRequestSha1));
            Iterator<PatchSet> patchSetIterator = existingPatchSet.iterator();
            if (patchSetIterator.hasNext()) {
                PatchSet patchSet = patchSetIterator.next();
                LOG.debug("Pull request commit ID " + pullRequestSha1
                        + " has been already uploaded as PatchSetID=" + patchSet.getPatchSetId()
                        + " in ChangeID=" + patchSet.getId());
                return null;
            }

            Change.Key changeKey;
            final List<String> idList = pullRequestCommit.getFooterLines(CHANGE_ID);
            if (!idList.isEmpty()) {
                final String idStr = idList.get(idList.size() - 1).trim();
                changeKey = new Change.Key(idStr);
            } else {
                final ObjectId computedChangeId = ChangeIdUtil.computeChangeId(pullRequestCommit.getTree(),
                        pullRequestCommit, pullRequestCommit.getAuthorIdent(),
                        pullRequestCommit.getCommitterIdent(), pullRequestMesage);

                changeKey = new Change.Key("I" + computedChangeId.name());
            }

            List<Change> destChanges = db.changes()
                    .byBranchKey(new Branch.NameKey(project.getNameKey(), destRef.getName()), changeKey)
                    .toList();

            if (destChanges.size() > 1) {
                throw new InvalidChangeOperationException("Multiple Changes with Change-ID " + changeKey
                        + " already exist on the target branch: cannot add a new patch-set "
                        + destinationBranch);
            } else if (destChanges.size() == 1) {
                // The change key exists on the destination branch: adding a new
                // patch-set
                Change destChange = destChanges.get(0);

                ChangeControl changeControl = projectControlFactor.controlFor(project.getNameKey())
                        .controlFor(destChange);

                return insertPatchSet(git, revWalk, destChange, pullRequestCommit, changeControl,
                        pullRequestOwner, pullRequestMesage, doValidation);
            } else {
                // Change key not found on destination branch. We can create a new
                // change.
                return (newChange = createNewChange(db, git, revWalk, changeKey, project.getNameKey(), destRef,
                        pullRequestOwner, pullRequestCommit, refControl, pullRequestMesage, topic,
                        doValidation));
            }
        } finally {
            revWalk.release();
            if (newChange == null) {
                db.rollback();
            }
        }
    } finally {
        git.close();
    }
}

From source file:com.madgag.agit.views.ObjectIdView.java

License:Open Source License

public void setObjectId(final ObjectId objectId) {
    setText(objectId.abbreviate(8).name());
    setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            String idText = objectId.name();
            clipboardManager.setText(idText);
            String htmlMessage = "<small><small><b><tt>" + objectId.name()
                    + "</tt></b></small><br />(copied to clipboard!)</small>";
            Toast.makeText(getContext(), centered(htmlMessage), LENGTH_SHORT).show();
        }//from w ww .ja  va  2 s  .  c o  m
    });
}

From source file:com.microsoft.gittf.core.util.TfsBranchUtil.java

License:Open Source License

/**
 * Updates the remote tracking branch and branch to point at the commit
 * specified.//ww  w  .ja v a2s .c om
 * 
 * @param repository
 * @param commitId
 * @throws IOException
 * @throws RefAlreadyExistsException
 * @throws RefNotFoundException
 * @throws InvalidRefNameException
 * @throws GitAPIException
 */
public static void update(Repository repository, ObjectId commitId) throws IOException,
        RefAlreadyExistsException, RefNotFoundException, InvalidRefNameException, GitAPIException {
    if (repository.isBare()) {
        Ref tfsBranchRef = repository.getRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        if (tfsBranchRef == null) {
            create(repository);
        }

        RefUpdate ref = repository.updateRef(Constants.R_HEADS + GitTFConstants.GIT_TF_BRANCHNAME);
        ref.setNewObjectId(commitId);
        ref.setForceUpdate(true);
        ref.update();
    }

    TfsRemoteReferenceUpdate remoteRefUpdate = new TfsRemoteReferenceUpdate(repository, commitId.name());
    remoteRefUpdate.update();

}

From source file:com.redhat.jenkins.nodesharing.ConfigRepo.java

License:Open Source License

/**
 * Get snapshot or remote repo state or the last working.
 *
 * @return Latest snapshot or the most recent working one if latest can not be get.
 * @throws InterruptedException     When thread was interrupted while creating snapshot.
 * @throws IOException              When failed to create the log file for the operation.
 * @throws TaskLog.TaskFailed       When there ware problems reading the snapshot.
 *//*from   w w w .  ja  va 2s.  c om*/
public @Nonnull Snapshot getSnapshot() throws InterruptedException, IOException, TaskLog.TaskFailed {
    Files.createDirectories(workingDir.toPath());
    TaskLog taskLog = new TaskLog(new File(workingDir.getAbsolutePath() + ".log"));
    try {
        ObjectId currentHead = getRemoteHead(taskLog);
        synchronized (repoLock) {
            if (snapshot != null && currentHead.equals(snapshot.source)) {
                LOGGER.fine("No config update in " + url + " after: " + snapshot.source.name());
            } else {
                taskLog.getLogger().printf("Node sharing config changes discovered %s%nPulling %s to %s%n",
                        currentHead.name(), url, workingDir);
                fetchChanges(taskLog);
                ObjectId checkedOutHead = getClient(taskLog).revParse("HEAD");
                assert currentHead.equals(checkedOutHead) : "What was discovered was in fact checked out";
                snapshot = readConfig(currentHead, taskLog);
            }
        }
    } catch (IOException | GitException ex) {
        taskLog.error(ex, "Unable to update config repo from %s", url);
    } finally {
        taskLog.close();
    }

    taskLog.throwIfFailed("Unable to read snapshot from " + url);
    assert snapshot != null;
    return snapshot;
}

From source file:com.rimerosolutions.ant.git.tasks.CurrentBranchTask.java

License:Apache License

@Override
protected void doExecute() {
    try {//ww  w  .j  a  va 2 s .c o m
        Repository repository = git.getRepository();
        String branch = repository.getBranch();
        // Backward compatibility
        getProject().setProperty(outputProperty, branch);

        ObjectId objectId = repository.getRef(Constants.HEAD).getObjectId();
        // Extended (nested) properties
        if (objectId != null) {
            getProject().setProperty(outputProperty + ".name", branch);
            getProject().setProperty(outputProperty + ".id", objectId.name());
            getProject().setProperty(outputProperty + ".shortId", objectId.abbreviate(8).name());
        }
    } catch (IOException e) {
        throw new GitBuildException("Could not query the current branch.", e);
    }
}