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.gitblit.tests.GroovyScriptTest.java

License:Apache License

@Test
public void testProtectRefsDeleteTag() throws Exception {
    MockGitblit gitblit = new MockGitblit();
    MockLogger logger = new MockLogger();
    MockClientLogger clientLogger = new MockClientLogger();
    List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
    ReceiveCommand command = new ReceiveCommand(ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"),
            ObjectId.zeroId(), "refs/tags/v1.0");
    commands.add(command);//from w  w w  . j a v  a 2  s  .c  o  m

    RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());

    test("protect-refs.groovy", gitblit, logger, clientLogger, commands, repository);
    assertEquals(ReceiveCommand.Result.REJECTED_NODELETE, command.getResult());
    assertEquals(0, logger.messages.size());
}

From source file:com.gitblit.tests.GroovyScriptTest.java

License:Apache License

@Test
public void testBlockPush() throws Exception {
    MockGitblit gitblit = new MockGitblit();
    MockLogger logger = new MockLogger();
    MockClientLogger clientLogger = new MockClientLogger();
    List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
    commands.add(new ReceiveCommand(ObjectId.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"),
            ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));

    RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());

    try {/*  w w  w.ja  v  a2s  .c o m*/
        test("blockpush.groovy", gitblit, logger, clientLogger, commands, repository);
        assertTrue("blockpush should have failed!", false);
    } catch (GitBlitException e) {
        assertTrue(e.getMessage().contains("failed"));
    }
}

From source file:com.gitblit.tests.GroovyScriptTest.java

License:Apache License

@Test
public void testClientLogging() throws Exception {
    MockGitblit gitblit = new MockGitblit();
    MockLogger logger = new MockLogger();
    MockClientLogger clientLogger = new MockClientLogger();
    List<ReceiveCommand> commands = new ArrayList<ReceiveCommand>();
    commands.add(new ReceiveCommand(ObjectId.fromString("c18877690322dfc6ae3e37bb7f7085a24e94e887"),
            ObjectId.fromString("3fa7c46d11b11d61f1cbadc6888be5d0eae21969"), "refs/heads/master"));

    RepositoryModel repository = new RepositoryModel("ex@mple.git", "", "admin", new Date());

    File groovyDir = repositories().getHooksFolder();
    File tempScript = File.createTempFile("testClientLogging", "groovy", groovyDir);
    tempScript.deleteOnExit();//from w  ww  .j  a va 2s .c  o m

    BufferedWriter writer = new BufferedWriter(new FileWriter(tempScript));

    writer.write("clientLogger.info('this is a test message')\n");
    writer.flush();
    writer.close();

    test(tempScript.getName(), gitblit, logger, clientLogger, commands, repository);
    assertTrue("Message Missing", clientLogger.messages.contains("this is a test message"));
}

From source file:com.gitblit.tests.JGitUtilsTest.java

License:Apache License

@Test
public void testRelinkBranch() throws Exception {
    Repository repository = GitBlitSuite.getJGitRepository();

    // create/set the branch
    JGitUtils.setBranchRef(repository, "refs/heads/reftest", "3b358ce514ec655d3ff67de1430994d8428cdb04");
    assertEquals(1, JGitUtils.getAllRefs(repository)
            .get(ObjectId.fromString("3b358ce514ec655d3ff67de1430994d8428cdb04")).size());
    assertEquals(null, JGitUtils.getAllRefs(repository)
            .get(ObjectId.fromString("755dfdb40948f5c1ec79e06bde3b0a78c352f27f")));

    // reset the branch
    JGitUtils.setBranchRef(repository, "refs/heads/reftest", "755dfdb40948f5c1ec79e06bde3b0a78c352f27f");
    assertEquals(null, JGitUtils.getAllRefs(repository)
            .get(ObjectId.fromString("3b358ce514ec655d3ff67de1430994d8428cdb04")));
    assertEquals(1, JGitUtils.getAllRefs(repository)
            .get(ObjectId.fromString("755dfdb40948f5c1ec79e06bde3b0a78c352f27f")).size());

    // delete the branch
    assertTrue(JGitUtils.deleteBranchRef(repository, "refs/heads/reftest"));
    repository.close();/*from   w  ww  .  j av  a2  s. c o  m*/
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Gets the raw byte content of the specified blob object.
 *
 * @param repository/*from w ww . j  a v  a2s.co  m*/
 * @param objectId
 * @return byte [] blob content
 */
public static byte[] getByteContent(Repository repository, String objectId) {
    RevWalk rw = new RevWalk(repository);
    byte[] content = null;
    try {
        RevBlob blob = rw.lookupBlob(ObjectId.fromString(objectId));
        ObjectLoader ldr = repository.open(blob.getId(), Constants.OBJ_BLOB);
        content = ldr.getCachedBytes();
    } catch (Throwable t) {
        error(t, repository, "{0} can't find blob {1}", objectId);
    } finally {
        rw.dispose();
    }
    return content;
}

From source file:com.gitblit.utils.JGitUtils.java

License:Apache License

/**
 * Sets the local branch ref to point to the specified commit id.
 *
 * @param repository//  w  ww.  j  a  v  a 2s . c o  m
 * @param branch
 * @param commitId
 * @return true if successful
 */
public static boolean setBranchRef(Repository repository, String branch, String commitId) {
    String branchName = branch;
    if (!branchName.startsWith(Constants.R_REFS)) {
        branchName = Constants.R_HEADS + branch;
    }

    try {
        RefUpdate refUpdate = repository.updateRef(branchName, false);
        refUpdate.setNewObjectId(ObjectId.fromString(commitId));
        RefUpdate.Result result = refUpdate.forceUpdate();

        switch (result) {
        case NEW:
        case FORCED:
        case NO_CHANGE:
        case FAST_FORWARD:
            return true;
        default:
            LOGGER.error(MessageFormat.format("{0} {1} update to {2} returned result {3}",
                    repository.getDirectory().getAbsolutePath(), branchName, commitId, result));
        }
    } catch (Throwable t) {
        error(t, repository, "{0} failed to set {1} to {2}", branchName, commitId);
    }
    return false;
}

From source file:com.github.jenkins.multiLastChanges.MultiLastChangesPublisher.java

License:Open Source License

@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
        throws IOException, InterruptedException {
    MultiLastChangesProjectAction projectAction = new MultiLastChangesProjectAction(build.getParent());
    boolean isPipeline = projectAction.isRunningInPipelineWorkflow();
    ScmType scmType = getScmType(isPipeline, projectAction);
    if (scmType == null) {
        throw new RuntimeException("Git/Svn/MultiSCM must be configured on your job to publish Last Changes.");
    }//from  www.  j a  v a  2 s .  c  o m
    listener.getLogger().println("Publishing build last changes...");

    List<MultiLastChanges> multiLastChangesList = new ArrayList<>();
    if (isPipeline) {
        switch (scmType) {
        case GIT: {
            Callable<List<MultiLastChanges>, IOException> getMultiLastChangesOnSlave = new MasterToSlaveCallable<List<MultiLastChanges>, IOException>() {
                public List<MultiLastChanges> call() throws IOException {
                    List<MultiLastChanges> multiLastChangesList = new ArrayList<>();
                    List<String> gitDirPaths = SCMUtils.findPathsOfGitRepos(workspace.getRemote());
                    //Supplying a revisionID will be ignored if there are more than one gitDir as it's unlikely all of them have the same change id
                    if (endRevision != null && !"".equalsIgnoreCase(endRevision.trim())
                            && gitDirPaths.size() > 1) {
                        listener.getLogger().println("End revision ignored as multiple repos detected.");
                    }
                    for (String gitDirPath : gitDirPaths) {
                        GitLastChanges gitLastChanges = new GitLastChanges(gitDirPath);
                        MultiLastChanges multiLastChanges = gitLastChanges.getLastChanges();
                        multiLastChangesList.add(multiLastChanges);
                    }
                    return multiLastChangesList;
                }
            };

            List<MultiLastChanges> multiLastChangesFromSlave = launcher.getChannel()
                    .call(getMultiLastChangesOnSlave);
            multiLastChangesList.addAll(multiLastChangesFromSlave);
            break;
        }
        default:
            //TODO: implement way to handle potentially multiple SVN projects
            throw new RuntimeException(
                    "Currently pipeline with SVN/MultiSCM projects are not supported on your job to publish Last Changes.");
        }
    } else {
        switch (scmType) {
        case GIT: {
            Callable<List<MultiLastChanges>, IOException> getMultiLastChangesOnSlave = new MasterToSlaveCallable<List<MultiLastChanges>, IOException>() {
                public List<MultiLastChanges> call() throws IOException {
                    List<MultiLastChanges> multiLastChangesList = new ArrayList<>();
                    List<String> gitDirPaths = SCMUtils.findPathsOfGitRepos(workspace.getRemote());
                    GitLastChanges gitLastChanges = new GitLastChanges(gitDirPaths.get(0));
                    if (endRevision != null && !"".equalsIgnoreCase(endRevision.trim())
                            && gitDirPaths.size() > 1) {
                        MultiLastChanges multiLastChanges = gitLastChanges.getChangesOf(
                                gitLastChanges.getCurrentRevision(), ObjectId.fromString(endRevision));
                        multiLastChangesList.add(multiLastChanges);
                    } else {
                        MultiLastChanges multiLastChanges = gitLastChanges.getLastChanges();
                        multiLastChangesList.add(multiLastChanges);
                    }
                    return multiLastChangesList;
                }
            };
            List<MultiLastChanges> multiLastChangesFromSlave = launcher.getChannel()
                    .call(getMultiLastChangesOnSlave);
            multiLastChangesList.addAll(multiLastChangesFromSlave);
            break;
        }
        case SVN: {
            AbstractProject<?, ?> rootProject = (AbstractProject<?, ?>) projectAction.getProject();
            SubversionSCM scm = SubversionSCM.class.cast(rootProject.getScm());
            SvnLastChanges svnLastChanges = new SvnLastChanges(rootProject, scm);
            if (endRevision != null && !"".equals(endRevision.trim())) {
                Long svnRevision = Long.parseLong(endRevision);
                SVNRepository repository = SvnLastChanges.repository(scm, projectAction.getProject());
                try {
                    MultiLastChanges multiLastChanges = svnLastChanges.getChangesOf(repository,
                            repository.getLatestRevision(), svnRevision);
                    multiLastChangesList.add(multiLastChanges);
                } catch (SVNException e) {
                    e.printStackTrace();
                }
            } else {
                MultiLastChanges multiLastChanges = svnLastChanges
                        .getLastChangesOf(SvnLastChanges.repository(scm, projectAction.getProject()));
                multiLastChangesList.add(multiLastChanges);
            }
            break;
        }
        case MULTISCM: {
            Callable<List<MultiLastChanges>, IOException> getMultiLastChangesOnSlave = new MasterToSlaveCallable<List<MultiLastChanges>, IOException>() {
                public List<MultiLastChanges> call() throws IOException {
                    List<MultiLastChanges> multiLastChangesList = new ArrayList<>();
                    MultiScmLastChanges multiScmLastChanges = new MultiScmLastChanges(workspace.getRemote());
                    if (endRevision != null && !"".equalsIgnoreCase(endRevision.trim())) {
                        listener.getLogger().println("End revision ignored as multiple repos detected.");
                    }
                    multiLastChangesList.addAll(multiScmLastChanges.getLastChanges());
                    return multiLastChangesList;
                }
            };
            List<MultiLastChanges> multiLastChangesFromSlave = launcher.getChannel()
                    .call(getMultiLastChangesOnSlave);
            multiLastChangesList.addAll(multiLastChangesFromSlave);
            break;
        }
        }
    }

    MultiLastChangesBuildAction multiLastChangesBuildAction = new MultiLastChangesBuildAction(build,
            multiLastChangesList, new MultiLastChangesConfig(endRevision, format, matching, showFiles,
                    synchronisedScroll, matchWordsThreshold, matchingMaxComparisons));
    build.addAction(multiLastChangesBuildAction);
    listener.hyperlink("../" + build.getNumber() + "/" + MultiLastChangesBaseAction.BASE_URL,
            "Last changes published successfully!");
    listener.getLogger().println("");
    //can clean up now
    build.setResult(Result.SUCCESS);
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.ObjectDaoImpl.java

License:Open Source License

@Override
@Cacheable/* www  .  j  a v  a 2  s. c  o m*/
public Tree[] getTrees(String token, String[] objectIds) throws DaoException {
    try (RevWalk walk = new RevWalk(resolver.getRepository(token))) {
        List<Tree> trees = new ArrayList<>(objectIds.length);
        for (String objectId : objectIds) {
            try {
                RevObject obj = walk.parseAny(ObjectId.fromString(objectId));
                if (obj.getType() != Constants.OBJ_TREE) {
                    String message = new StringBuilder().append("Failed to get a tree in the repository ")
                            .append(token).append(". ").append(objectId).append(" is not a tree.").toString();
                    LOG.error(message + "It's {}.", obj.getClass());
                    throw new DaoException(message);
                }
                trees.add(convertToTree(token, (RevTree) obj));
            } catch (MissingObjectException e) {
                String message = new StringBuilder().append("Failed to get a tree in the repository ")
                        .append(token).append(". ").append(objectId).append(" doesn't exist.").toString();
                LOG.error(message);
                throw new DaoException(message, e);
            } catch (IOException e) {
                String message = new StringBuilder().append("Failed to get a tree ").append(objectId)
                        .append(" in the repository ").append(token).append(" due to an I/O error.").toString();
                LOG.error(message);
                throw new DaoException(message, e);
            }
        }
        return trees.toArray(new Tree[objectIds.length]);
    }
}

From source file:com.github.kaitoy.goslings.server.dao.jgit.ObjectDaoImpl.java

License:Open Source License

@Cacheable
private RawContents getRawContents(String token, String objectId) {
    try {/*  ww w  . j av  a2  s.  co  m*/
        ObjectLoader loader = resolver.getRepository(token).open(ObjectId.fromString(objectId));
        return new RawContents(loader.getType(), loader.getBytes());
    } catch (MissingObjectException e) {
        String message = new StringBuilder().append("The specified object ").append(objectId)
                .append(" doesn't exist in the repository ").append(token).append(".").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    } catch (IOException e) {
        String message = new StringBuilder().append("Failed to get contents of the specified object ")
                .append(objectId).append(" in the repository ").append(token).append(".").toString();
        LOG.error(message, e);
        throw new DaoException(message, e);
    }
}

From source file:com.google.appraise.eclipse.ui.editor.CommitAttributeEditor.java

License:Open Source License

private RepositoryCommit getCommit() throws IOException {
    Repository repository = AppraisePluginUtils.getGitRepoForRepository(this.getModel().getTaskRepository());
    try (RevWalk revWalk = new RevWalk(repository)) {
        RevCommit commit = revWalk.parseCommit(ObjectId.fromString(getValue()));
        if (commit != null) {
            return new RepositoryCommit(repository, commit);
        }//  w  w  w . j  a  v  a  2 s  . co m
    } catch (MissingObjectException e) {
        AppraiseUiPlugin.logError("Commit not found " + getValue(), e);
    } catch (IncorrectObjectTypeException e) {
        AppraiseUiPlugin.logError("Not a commit " + getValue(), e);
    }
    return null;
}