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

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

Introduction

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

Prototype

public final String getName() 

Source Link

Document

Get string form of the SHA-1, in lower case hexadecimal.

Usage

From source file:com.google.gerrit.acceptance.rest.project.CheckMergeabilityIT.java

License:Apache License

@Test
public void checkAlreadyMergedCommit() throws Exception {
    ObjectId c0 = testRepo.branch("HEAD").commit().insertChangeId().message("first commit")
            .add("a.txt", "a contents ").create();
    testRepo.git().push().setRemote("origin").setRefSpecs(new RefSpec("HEAD:refs/heads/master")).call();

    testRepo.branch("HEAD").commit().insertChangeId().message("second commit").add("b.txt", "b contents ")
            .create();//from  www. j  a v  a2  s . c  o m
    testRepo.git().push().setRemote("origin").setRefSpecs(new RefSpec("HEAD:refs/heads/master")).call();

    assertCommitMerged("master", c0.getName(), "");
}

From source file:com.google.gerrit.common.ChangeHookRunner.java

License:Apache License

/**
 * Fire the update hook/*  www  .  j  ava2  s  .  co m*/
 *
 */
@Override
public HookResult doRefUpdateHook(Project project, String refname, Account uploader, ObjectId oldId,
        ObjectId newId) {

    List<String> args = new ArrayList<>();
    addArg(args, "--project", project.getName());
    addArg(args, "--refname", refname);
    addArg(args, "--uploader", getDisplayName(uploader));
    addArg(args, "--oldrev", oldId.getName());
    addArg(args, "--newrev", newId.getName());

    return runSyncHook(project.getNameKey(), refUpdateHook, args);
}

From source file:com.google.gerrit.pgm.rules.PrologCompiler.java

License:Apache License

@Override
public Status call() throws IOException, CompileException {
    ObjectId metaConfig = git.resolve(RefNames.REFS_CONFIG);
    if (metaConfig == null) {
        return Status.NO_RULES;
    }/*from  w  w  w .j  av a 2  s.co  m*/

    ObjectId rulesId = git.resolve(metaConfig.name() + ":rules.pl");
    if (rulesId == null) {
        return Status.NO_RULES;
    }

    if (ruleDir == null) {
        throw new CompileException("Caching not enabled");
    }
    Files.createDirectories(ruleDir);

    File tempDir = File.createTempFile("GerritCodeReview_", ".rulec");
    if (!tempDir.delete() || !tempDir.mkdir()) {
        throw new IOException("Cannot create " + tempDir);
    }
    try {
        // Try to make the directory accessible only by this process.
        // This may help to prevent leaking rule data to outsiders.
        tempDir.setReadable(true, true);
        tempDir.setWritable(true, true);
        tempDir.setExecutable(true, true);

        compileProlog(rulesId, tempDir);
        compileJava(tempDir);

        Path jarPath = ruleDir.resolve("rules-" + rulesId.getName() + ".jar");
        List<String> classFiles = getRelativePaths(tempDir, ".class");
        createJar(jarPath, classFiles, tempDir, metaConfig, rulesId);

        return Status.COMPILED;
    } finally {
        deleteAllFiles(tempDir);
    }
}

From source file:com.google.gerrit.rules.PrologCompiler.java

License:Apache License

@Override
public Status call() throws IOException, CompileException {
    ObjectId metaConfig = git.resolve(RefNames.REFS_CONFIG);
    if (metaConfig == null) {
        return Status.NO_RULES;
    }//from   w ww  .  jav  a  2 s  . c om

    ObjectId rulesId = git.resolve(metaConfig.name() + ":rules.pl");
    if (rulesId == null) {
        return Status.NO_RULES;
    }

    if (ruleDir == null) {
        throw new CompileException("Caching not enabled");
    }
    if (!ruleDir.isDirectory() && !ruleDir.mkdir()) {
        throw new IOException("Cannot create " + ruleDir);
    }

    File tempDir = File.createTempFile("GerritCodeReview_", ".rulec");
    if (!tempDir.delete() || !tempDir.mkdir()) {
        throw new IOException("Cannot create " + tempDir);
    }
    try {
        // Try to make the directory accessible only by this process.
        // This may help to prevent leaking rule data to outsiders.
        tempDir.setReadable(true, true);
        tempDir.setWritable(true, true);
        tempDir.setExecutable(true, true);

        compileProlog(rulesId, tempDir);
        compileJava(tempDir);

        File jarFile = new File(ruleDir, "rules-" + rulesId.getName() + ".jar");
        List<String> classFiles = getRelativePaths(tempDir, ".class");
        createJar(jarFile, classFiles, tempDir, metaConfig, rulesId);

        return Status.COMPILED;
    } finally {
        deleteAllFiles(tempDir);
    }
}

From source file:com.google.gerrit.rules.RulesCache.java

License:Apache License

private PrologMachineCopy createMachine(Project.NameKey project, ObjectId rulesId) throws CompileException {
    // If the rules are available as a complied JAR on local disk, prefer
    // that over dynamic consult as the bytecode will be faster.
    ///*from   ww w .  j a v a 2s. co  m*/
    if (rulesDir != null) {
        Path jarPath = rulesDir.resolve("rules-" + rulesId.getName() + ".jar");
        if (Files.isRegularFile(jarPath)) {
            URL[] cp = new URL[] { toURL(jarPath) };
            return save(newEmptyMachine(new URLClassLoader(cp, systemLoader)));
        }
    }

    // Dynamically consult the rules into the machine's internal database.
    //
    String rules = read(project, rulesId);
    PrologMachineCopy pmc = consultRules("rules.pl", new StringReader(rules));
    if (pmc == null) {
        throw new CompileException("Cannot consult rules of " + project);
    }
    return pmc;
}

From source file:com.google.gerrit.server.events.EventFactory.java

License:Apache License

/**
 * Create a RefUpdateAttribute for the given old ObjectId, new ObjectId, and
 * branch that is suitable for serialization to JSON.
 *
 * @param oldId/*from  ww w . ja  v  a2  s  .  c  om*/
 * @param newId
 * @param refName
 * @return object suitable for serialization to JSON
 */
public RefUpdateAttribute asRefUpdateAttribute(final ObjectId oldId, final ObjectId newId,
        final Branch.NameKey refName) {
    RefUpdateAttribute ru = new RefUpdateAttribute();
    ru.newRev = newId != null ? newId.getName() : ObjectId.zeroId().getName();
    ru.oldRev = oldId != null ? oldId.getName() : ObjectId.zeroId().getName();
    ru.project = refName.getParentKey().get();
    ru.refName = refName.get();
    return ru;
}

From source file:com.google.gerrit.server.git.BanCommit.java

License:Apache License

private static String buildCommitMessage(final List<ObjectId> bannedCommits, final String reason) {
    final StringBuilder commitMsg = new StringBuilder();
    commitMsg.append("Banning ");
    commitMsg.append(bannedCommits.size());
    commitMsg.append(" ");
    commitMsg.append(bannedCommits.size() == 1 ? "commit" : "commits");
    commitMsg.append("\n\n");
    if (reason != null) {
        commitMsg.append("Reason: ");
        commitMsg.append(reason);/*from w  w  w. j a v  a  2  s .  c  o  m*/
        commitMsg.append("\n\n");
    }
    commitMsg.append("The following commits are banned:\n");
    final StringBuilder commitList = new StringBuilder();
    for (final ObjectId c : bannedCommits) {
        if (commitList.length() > 0) {
            commitList.append(",\n");
        }
        commitList.append(c.getName());
    }
    commitMsg.append(commitList);
    return commitMsg.toString();
}

From source file:com.google.gerrit.server.git.SubmoduleOp.java

License:Apache License

/**
 * Update the submodules in one branch of one repository.
 *
 * @param subscriber the branch of the repository which should be changed.
 * @param updates submodule updates which should be updated to.
 * @throws SubmoduleException/*from w  w  w.j av a2 s .com*/
 */
private void updateGitlinks(ReviewDb db, Branch.NameKey subscriber, Collection<SubmoduleSubscription> updates)
        throws SubmoduleException {
    PersonIdent author = null;
    StringBuilder msgbuf = new StringBuilder("Updated git submodules\n\n");
    boolean sameAuthorForAll = true;

    try (Repository pdb = repoManager.openRepository(subscriber.getParentKey())) {
        if (pdb.getRef(subscriber.get()) == null) {
            throw new SubmoduleException("The branch was probably deleted from the subscriber repository");
        }

        DirCache dc = readTree(pdb, pdb.getRef(subscriber.get()));
        DirCacheEditor ed = dc.editor();

        for (SubmoduleSubscription s : updates) {
            try (Repository subrepo = repoManager.openRepository(s.getSubmodule().getParentKey());
                    RevWalk rw = CodeReviewCommit.newRevWalk(subrepo)) {
                Ref ref = subrepo.getRefDatabase().exactRef(s.getSubmodule().get());
                if (ref == null) {
                    ed.add(new DeletePath(s.getPath()));
                    continue;
                }

                final ObjectId updateTo = ref.getObjectId();
                RevCommit newCommit = rw.parseCommit(updateTo);

                if (author == null) {
                    author = newCommit.getAuthorIdent();
                } else if (!author.equals(newCommit.getAuthorIdent())) {
                    sameAuthorForAll = false;
                }

                DirCacheEntry dce = dc.getEntry(s.getPath());
                ObjectId oldId;
                if (dce != null) {
                    if (!dce.getFileMode().equals(FileMode.GITLINK)) {
                        log.error("Requested to update gitlink " + s.getPath() + " in "
                                + s.getSubmodule().getParentKey().get() + " but entry "
                                + "doesn't have gitlink file mode.");
                        continue;
                    }
                    oldId = dce.getObjectId();
                } else {
                    // This submodule did not exist before. We do not want to add
                    // the full submodule history to the commit message, so omit it.
                    oldId = updateTo;
                }

                ed.add(new PathEdit(s.getPath()) {
                    @Override
                    public void apply(DirCacheEntry ent) {
                        ent.setFileMode(FileMode.GITLINK);
                        ent.setObjectId(updateTo);
                    }
                });
                if (verboseSuperProject) {
                    msgbuf.append("Project: " + s.getSubmodule().getParentKey().get());
                    msgbuf.append(" " + s.getSubmodule().getShortName());
                    msgbuf.append(" " + updateTo.getName());
                    msgbuf.append("\n\n");

                    try {
                        rw.markStart(newCommit);
                        rw.markUninteresting(rw.parseCommit(oldId));
                        for (RevCommit c : rw) {
                            msgbuf.append(c.getFullMessage() + "\n\n");
                        }
                    } catch (IOException e) {
                        logAndThrowSubmoduleException(
                                "Could not perform a revwalk to " + "create superproject commit message", e);
                    }
                }
            }
        }
        ed.finish();

        if (!sameAuthorForAll || author == null) {
            author = myIdent;
        }

        ObjectInserter oi = pdb.newObjectInserter();
        ObjectId tree = dc.writeTree(oi);

        ObjectId currentCommitId = pdb.getRef(subscriber.get()).getObjectId();

        CommitBuilder commit = new CommitBuilder();
        commit.setTreeId(tree);
        commit.setParentIds(new ObjectId[] { currentCommitId });
        commit.setAuthor(author);
        commit.setCommitter(myIdent);
        commit.setMessage(msgbuf.toString());
        oi.insert(commit);
        oi.flush();

        ObjectId commitId = oi.idFor(Constants.OBJ_COMMIT, commit.build());

        final RefUpdate rfu = pdb.updateRef(subscriber.get());
        rfu.setForceUpdate(false);
        rfu.setNewObjectId(commitId);
        rfu.setExpectedOldObjectId(currentCommitId);
        rfu.setRefLogMessage("Submit to " + subscriber.getParentKey().get(), true);

        switch (rfu.update()) {
        case NEW:
        case FAST_FORWARD:
            gitRefUpdated.fire(subscriber.getParentKey(), rfu);
            changeHooks.doRefUpdatedHook(subscriber, rfu, account);
            // TODO since this is performed "in the background" no mail will be
            // sent to inform users about the updated branch
            break;

        default:
            throw new IOException(rfu.getResult().name());
        }
        // Recursive call: update subscribers of the subscriber
        updateSuperProjects(db, Sets.newHashSet(subscriber));
    } catch (IOException e) {
        throw new SubmoduleException("Cannot update gitlinks for " + subscriber.get(), e);
    }
}

From source file:com.google.gerrit.server.project.BanCommit.java

License:Apache License

private static List<String> transformCommits(List<ObjectId> commits) {
    if (commits == null || commits.isEmpty()) {
        return null;
    }/*from  w w  w  .  ja  va2 s. com*/

    return Lists.transform(commits, new Function<ObjectId, String>() {
        @Override
        public String apply(ObjectId id) {
            return id.getName();
        }
    });
}

From source file:com.google.gerrit.server.project.CreateBranch.java

License:Apache License

@Override
public BranchInfo apply(ProjectResource rsrc, Input input)
        throws BadRequestException, AuthException, ResourceConflictException, IOException {
    if (input == null) {
        input = new Input();
    }//www .j av a  2  s  .  co  m
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException(
                "not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }

    final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
    final RefControl refControl = rsrc.getControl().controlForRef(name);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        final ObjectId revid = parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        final RevWalk rw = verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);

        if (ref.startsWith(Constants.R_HEADS)) {
            // Ensure that what we start the branch from is a commit. If we
            // were given a tag, deference to the commit instead.
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new BadRequestException("\"" + input.revision + "\" not a commit");
            }
        }

        rw.reset();
        if (!refControl.canCreate(db.get(), rw, object)) {
            throw new AuthException("Cannot create \"" + ref + "\"");
        }

        try {
            final RefUpdate u = repo.updateRef(ref);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            u.setRefLogMessage("created via REST from " + input.revision, false);
            final RefUpdate.Result result = u.update(rw);
            switch (result) {
            case FAST_FORWARD:
            case NEW:
            case NO_CHANGE:
                referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE);
                hooks.doRefUpdatedHook(name, u, identifiedUser.get().getAccount());
                break;
            case LOCK_FAILURE:
                if (repo.getRefDatabase().exactRef(ref) != null) {
                    throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                }
                String refPrefix = getRefPrefix(ref);
                while (!Constants.R_HEADS.equals(refPrefix)) {
                    if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                        throw new ResourceConflictException("Cannot create branch \"" + ref
                                + "\" since it conflicts with branch \"" + refPrefix + "\".");
                    }
                    refPrefix = getRefPrefix(refPrefix);
                }
                //$FALL-THROUGH$
            default: {
                throw new IOException(result.name());
            }
            }

            BranchInfo info = new BranchInfo();
            info.ref = ref;
            info.revision = revid.getName();
            info.canDelete = refControl.canDelete() ? true : null;
            return info;
        } catch (IOException err) {
            log.error("Cannot create branch \"" + name + "\"", err);
            throw err;
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"");
    }
}