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:org.eclipse.mylyn.internal.github.ui.pr.PullRequestContextSynchronizer.java

License:Open Source License

public void taskActivated(ITask task) {
    if (task == null)
        return;/*from  w ww .ja  va2s  .  c o m*/
    if (!PullRequestConnector.KIND.equals(task.getConnectorKind()))
        return;
    IInteractionContext context = ContextCore.getContextManager().getActiveContext();
    if (context == null)
        return;

    RevWalk walk = null;
    try {
        TaskData data = TasksUi.getTaskDataManager().getTaskData(task);
        PullRequestComposite prComp = PullRequestConnector.getPullRequest(data);
        if (prComp == null)
            return;
        PullRequest request = prComp.getRequest();
        Repository repository = PullRequestUtils.getRepository(request);
        if (repository == null)
            return;
        walk = new RevWalk(repository);
        TreeWalk diffs = new TreeWalk(walk.getObjectReader());
        diffs.setFilter(TreeFilter.ANY_DIFF);
        diffs.setRecursive(true);
        diffs.addTree(walk.parseCommit(ObjectId.fromString(request.getHead().getSha())).getTree());
        diffs.addTree(walk.parseCommit(ObjectId.fromString(request.getBase().getSha())).getTree());
        Set<IResource> resources = new HashSet<IResource>();
        IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
        String base = repository.getWorkTree().getAbsolutePath() + "/"; //$NON-NLS-1$
        while (diffs.next()) {
            IFile file = root.getFileForLocation(Path.fromOSString(base + diffs.getPathString()));
            if (file != null)
                resources.add(file);
        }
        if (!resources.isEmpty())
            ResourcesUi.addResourceToContext(resources, InteractionEvent.Kind.SELECTION);
    } catch (MissingObjectException ignored) {
        // Ignored
    } catch (IOException e) {
        GitHubUi.logError(e);
    } catch (CoreException e) {
        GitHubUi.logError(e);
    } finally {
        if (walk != null)
            walk.release();
    }
}

From source file:org.eclipse.mylyn.reviews.r4e.core.rfs.ReviewsRFSProxy.java

License:Open Source License

public InputStream getBlobContent(IProgressMonitor monitor, String id) throws ReviewsFileStorageException {
    InputStream resStream = null;

    if (id == null) {
        return null;
    }//from  w  ww. j  ava2 s.  c  o  m

    try {
        ObjectId objId = ObjectId.fromString(id);
        resStream = fRepository.open(objId, Constants.OBJ_BLOB).openStream();
    } catch (Exception e) {
        throw new ReviewsFileStorageException(e);
    }

    return resStream;
}

From source file:org.eclipse.orion.server.git.servlets.GitBlameHandlerV1.java

License:Open Source License

@Override
protected boolean handleGet(RequestInfo requestInfo) throws ServletException {
    HttpServletRequest request = requestInfo.request;
    HttpServletResponse response = requestInfo.response;

    try {//from   w  ww.j  a  v  a 2 s . c om

        URI cloneLocation = BaseToCloneConverter.getCloneLocation(getURI(request), BaseToCloneConverter.BLAME);

        Path Filepath = new Path(requestInfo.filePath.toString());
        if (Filepath.hasTrailingSeparator()) {
            String msg = NLS.bind("Cannot get blame Information on a folder: {0}",
                    requestInfo.filePath.toString());
            return statusHandler.handleRequest(request, response,
                    new ServerStatus(IStatus.ERROR, HttpServletResponse.SC_BAD_REQUEST, msg, null));
        }

        Blame blame = new Blame(cloneLocation, requestInfo.db);

        String gitSegment = requestInfo.gitSegment;
        if (!gitSegment.equalsIgnoreCase("HEAD") && !gitSegment.equalsIgnoreCase("master")) {
            ObjectId id = ObjectId.fromString(requestInfo.gitSegment);
            blame.setStartCommit(id);
        }

        String path = requestInfo.relativePath;
        blame.setFilePath(path);
        blame.setBlameLocation(getURI(request));
        doBlame(blame, requestInfo.db);
        OrionServlet.writeJSONResponse(request, response, blame.toJSON(),
                JsonURIUnqualificationStrategy.ALL_NO_GIT);
        return true;
    } catch (Exception e) {
        return statusHandler.handleRequest(request, response, new ServerStatus(IStatus.ERROR,
                HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Error generating blame response", e));
    }
}

From source file:org.flowerplatform.web.git.operation.MergeOperation.java

License:Open Source License

public void execute() {
    ProgressMonitor monitor = ProgressMonitor.create(GitPlugin.getInstance().getMessage("git.merge"), channel);

    try {/*from w ww .  j  ava2 s . c  o m*/
        monitor.beginTask(GitPlugin.getInstance().getMessage("git.merge.title", new Object[] { refName }), 3);
        //         IProject[] validProjects = GitPlugin.getInstance().getUtils().getValidProjects(repository);
        //         
        //         GitPlugin.getInstance().getGitUtils().backupProjectConfigFiles(null, validProjects);
        //                  
        Git git = new Git(repository);
        monitor.worked(1);
        MergeCommand merge;

        FastForwardMode ffmode = FastForwardMode.FF;
        Ref ref = repository.getRef(refName);
        if (ref != null) {
            merge = git.merge().include(ref).setFastForward(ffmode);
        } else {
            merge = git.merge().include(ObjectId.fromString(refName)).setFastForward(ffmode);
        }
        merge.setSquash(squash);

        mergeResult = (MergeResult) GitPlugin.getInstance().getUtils().runGitCommandInUserRepoConfig(repository,
                merge);
        monitor.worked(1);

        //         GitPlugin.getInstance().getUtils().refreshValidProjects(validProjects, new SubProgressMonitor(monitor, 1));      
    } catch (NoHeadException e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.merge.mergeOperation.mergeFailedNoHead"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (ConcurrentRefUpdateException e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        GitPlugin.getInstance().getMessage("git.merge.mergeOperation.mergeFailedRefUpdate"),
                        DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (CheckoutConflictException e) {
        mergeResult = new MergeResult(e.getConflictingPaths());
    } catch (GitAPIException e) {
        channel.appendOrSendCommand(new DisplaySimpleMessageClientCommand(
                CommonPlugin.getInstance().getMessage("error"), e.getLocalizedMessage(),
                e.getCause().getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } catch (Exception e) {
        channel.appendOrSendCommand(
                new DisplaySimpleMessageClientCommand(CommonPlugin.getInstance().getMessage("error"),
                        e.getMessage(), DisplaySimpleMessageClientCommand.ICON_ERROR));
    } finally {
        monitor.done();
        //         GitPlugin.getInstance().getUtils().restoreProjectConfigFiles(repository, null);
    }
}

From source file:org.jenkinsci.plugins.gitclient.GitClientTest.java

@Test
public void testCheckout_String() throws Exception {
    /* Confirm files not visible in empty repo */
    assertEmptyWorkingDir(gitClient);//w  w w.j a v  a 2  s.c om
    /* Fetch from origin repo */
    fetch(gitClient, "origin", "+refs/heads/*:refs/remotes/origin/*");

    /* Checkout a commit after README was added, before src directory was added */
    String ref = "5a865818566c9d03738cdcd49cc0a1543613fd41";
    gitClient.checkout(ref);
    /* Confirm README.md visible, src directory not */
    assertFileInWorkingDir(gitClient, "README.md");
    assertDirNotInWorkingDir(gitClient, "src");
    assertDetachedHead(gitClient, ObjectId.fromString(ref));

    /* Checkout a commit before README was added, before src directory was added */
    String olderRef = "28f42e8d299154cd209cb1c75457fa9966a74f33";
    gitClient.checkout(olderRef);
    assertFileNotInWorkingDir(gitClient, "README.md");
    assertDirNotInWorkingDir(gitClient, "src");
    assertDetachedHead(gitClient, ObjectId.fromString(olderRef));

    /* Checkout a commit after README and src were added */
    String newestRef = "ded4597c18562fabb862f6012fb041a40d0d651a";
    gitClient.checkout(newestRef);
    assertFileInWorkingDir(gitClient, "README.md");
    assertDirInWorkingDir(gitClient, "src");
    assertDetachedHead(gitClient, ObjectId.fromString(newestRef));
}

From source file:org.jenkinsci.plugins.github_branch_source.MergeWithGitSCMExtension.java

License:Open Source License

@Override
public Revision decorateRevisionToBuild(GitSCM scm, Run<?, ?> build, GitClient git, TaskListener listener,
        Revision marked, Revision rev) throws IOException, InterruptedException, GitException {
    ObjectId baseObjectId;//  w w w. ja va2 s.  c om
    if (StringUtils.isBlank(baseHash)) {
        try {
            baseObjectId = git.revParse(Constants.R_REFS + baseName);
        } catch (GitException e) {
            listener.getLogger().printf("Unable to determine head revision of %s prior to merge with PR%n",
                    baseName);
            throw e;
        }
    } else {
        baseObjectId = ObjectId.fromString(baseHash);
    }
    listener.getLogger().printf("Merging %s commit %s into PR head commit %s%n", baseName, baseObjectId.name(),
            rev.getSha1String());
    checkout(scm, build, git, listener, rev);
    try {
        /* could parse out of JenkinsLocationConfiguration.get().getAdminAddress() but seems overkill */
        git.setAuthor("Jenkins", "nobody@nowhere");
        git.setCommitter("Jenkins", "nobody@nowhere");
        MergeCommand cmd = git.merge().setRevisionToMerge(baseObjectId);
        for (GitSCMExtension ext : scm.getExtensions()) {
            // By default we do a regular merge, allowing it to fast-forward.
            ext.decorateMergeCommand(scm, build, git, listener, cmd);
        }
        cmd.execute();
    } catch (GitException x) {
        // Try to revert merge conflict markers.
        // TODO IGitAPI offers a reset(hard) method yet GitClient does not. Why?
        checkout(scm, build, git, listener, rev);
        // TODO would be nicer to throw an AbortException with just the message, but this is actually worse
        // until git-client 1.19.7+
        throw x;
    }
    build.addAction(new MergeRecord(baseName, baseObjectId.getName())); // does not seem to be used, but just in case
    ObjectId mergeRev = git.revParse(Constants.HEAD);
    listener.getLogger().println("Merge succeeded, producing " + mergeRev.name());
    return new Revision(mergeRev, rev.getBranches()); // note that this ensures Build.revision != Build.marked
}

From source file:org.jvnet.hudson.plugins.m2release.ReleaseEnvironment.java

License:Open Source License

private void finalizeSCMRepo(AbstractBuild bld, BuildListener buildListener)
        throws IOException, InterruptedException {
    //merge the release branch into master
    if (bld.getProject().getScm() instanceof GitSCM) {
        GitSCM gitSCM = (GitSCM) bld.getProject().getScm();
        AbstractProject project = bld.getProject();

        final EnvVars environment = GitUtils.getPollEnvironment(project, bld.getWorkspace(), launcher,
                buildListener);/*from  www. ja  va 2 s .co  m*/
        GitClient gitClient = gitSCM.createClient(buildListener, environment, bld, bld.getWorkspace());
        M2ReleaseArgumentsAction args = bld.getAction(M2ReleaseArgumentsAction.class);

        List<UserRemoteConfig> userRemoteConfigs = gitSCM.getUserRemoteConfigs();
        if (userRemoteConfigs.isEmpty()) {
            buildListener.fatalError(
                    "[WSO2 Maven Release] " + "Could not find the git remote URL for the project. \n");
        } else if (userRemoteConfigs.get(0).getCredentialsId() == null) {
            ReleaseUtils.printInfoIntoBuildLog("Credentials are not present in the git configuration",
                    buildListener.getLogger());
        }

        //get release branch head commit
        String remoteUrl = userRemoteConfigs.get(0).getUrl();
        String releaseBranchHeadCommit = gitClient.revParse(M2ReleaseBuildWrapper.DEFAULT_REF).name();
        //local branch name that will be pushed to #remoteBranch
        String localBranchToPush = UUID.randomUUID().toString();

        try {
            // 1) handle build failures
            //we delete the git tag, but keep the release branch as it is in case it needs to be reviewed later
            ReleaseUtils.printSeparator(buildListener);
            ReleaseUtils.printInfoIntoBuildLog("[WSO2 Maven Release] Build Result: " + bld.getResult(),
                    buildListener.getLogger());
            if (bld.getResult() == null || !bld.getResult().isBetterOrEqualTo(Result.SUCCESS)) {
                String scmTag = args.getScmTagName();
                buildListener.getLogger().println("[WSO2 Maven Release] Dropping Git Tag: " + scmTag
                        + ". Reason: " + bld.getResult() + " build.");

                //if exceptions, then remove the remote release tag
                String refspec = ":" + "refs/tags/" + scmTag; // :refs/tags/v4.4.10
                buildListener.getLogger().println();
                ReleaseUtils.printInfoIntoBuildLog("Deleting release tag from remote.",
                        buildListener.getLogger());
                gitClient.push().to(new URIish(remoteUrl)).ref(refspec).execute();

                buildListener.getLogger().println("[WSO2 Maven Release] Dropped git tag - " + scmTag);
                return;
            }
        } catch (URISyntaxException e) {
            buildListener.fatalError(
                    "[WSO2 Maven Release] " + "Could not parse the git remote URL for project: " + remoteUrl);
            bld.keepLog();
            throw new IllegalArgumentException(e.getMessage(), e);
        } catch (GitException e) {
            //this could fail if merging the release commits lead to a conflict.
            ReleaseUtils.printExceptionIntoBuildLog("[ERROR] [WSO2 Maven Release] merging the changes. ", e,
                    buildListener);
            bld.keepLog();
            throw e;
        }

        try {
            // 2) get latest commits from remote to a local branch

            // 2.1) checkout a temporary release branch for git push to remote
            ReleaseUtils.printInfoIntoBuildLog("Checking out a temp local branch named " + localBranchToPush
                    + " at revision " + remoteRevision, buildListener.getLogger());
            gitClient.checkoutBranch(localBranchToPush, remoteRevision);
            ReleaseUtils.printSeparator(buildListener);

            String localFetchBranch = "refs/remotes/origin/" + localBranchToPush;
            String fetchRefspec = remoteBranch + ":" + localFetchBranch;
            ReleaseUtils.printInfoIntoBuildLog(
                    "Fetching latest changes with refspec: " + fetchRefspec
                            + " before merging the release commits into " + localBranchToPush,
                    buildListener.getLogger());

            // 2.2) get latest commits from the remote branch before pushing to avoid outdated wc error
            gitClient.fetch_().from(new URIish(remoteUrl), Collections.singletonList(new RefSpec(fetchRefspec)))
                    .execute();
            String latestRemoteCommit = gitClient.revParse(localFetchBranch).getName();
            ObjectId latestRemoteCommitObject = ObjectId.fromString(latestRemoteCommit);
            ReleaseUtils.printInfoIntoBuildLog("Merging fetched upstream changes into " + localBranchToPush,
                    buildListener.getLogger());
            gitClient.merge().setRevisionToMerge(latestRemoteCommitObject).execute();
            ReleaseUtils.printSeparator(buildListener);
        } catch (URISyntaxException e) {
            buildListener.fatalError(
                    "[WSO2 Maven Release] " + "Could not parse the git remote URL for project: " + remoteUrl);
            throw new IllegalArgumentException(e);
        } catch (GitException e) {
            ReleaseUtils.printExceptionIntoBuildLog("[ERROR] [WSO2 Maven Release] merging the changes. ", e,
                    buildListener);
            gitClient.checkoutBranch(localBranchToPush, remoteRevision);
            //todo kasung does this work?
        }

        try {
            // 3) merge release commits into that local branch
            ReleaseUtils.printInfoIntoBuildLog("Merging release branch HEAD commit, " + releaseBranchHeadCommit
                    + ", into branch " + localBranchToPush, buildListener.getLogger());
            gitClient.merge().setRevisionToMerge(ObjectId.fromString(releaseBranchHeadCommit)).execute();

            // 3.1) push the whole thing into the original remote branch
            String refspec = localBranchToPush + ":" + remoteBranch;
            ReleaseUtils.printInfoIntoBuildLog("Pushing the whole thing into remote.",
                    buildListener.getLogger());
            gitClient.push().to(new URIish(remoteUrl)).ref(refspec).execute();

            // 3.2) if no exceptions, then remove the remote release branch
            refspec = ":" + releaseBranch;
            buildListener.getLogger().println();
            ReleaseUtils.printInfoIntoBuildLog("Deleting release branch from remote.",
                    buildListener.getLogger());
            gitClient.push().to(new URIish(remoteUrl)).ref(refspec).execute();

            String headCommitHashAfterMerge = writeLatestReleaseRevisionNumber(bld, buildListener);
            log.debug("[WSO2 Maven Release] {}-{} : Written the revision {} ", bld.getProject(),
                    bld.getDisplayName(), headCommitHashAfterMerge);
            ReleaseUtils.printInfoIntoBuildLog("Stored last release commit hash : " + headCommitHashAfterMerge,
                    buildListener.getLogger());

            ReleaseUtils.printSeparator(buildListener);

        } catch (URISyntaxException e) {
            buildListener.fatalError(
                    "[WSO2 Maven Release] " + "Could not parse the git remote URL for project: " + remoteUrl);
            throw new IllegalArgumentException(e.getMessage(), e);
        } catch (GitException e) {
            //this could fail if merging the release commits lead to a conflict.
            ReleaseUtils.printExceptionIntoBuildLog("[ERROR] [WSO2 Maven Release] merging the changes. ", e,
                    buildListener);
            bld.keepLog();
            throw e;
            //todo handle kasung
        }
    }
}

From source file:org.kercoin.magrit.core.dao.BuildDAOImplTest.java

License:Open Source License

@Test
public void testSerializeBuildResult_nominal() throws Exception {
    // given//from   ww  w  .  j  a v a 2 s  .  co m
    final BuildResult buildResult = new BuildResult(SHA1);
    buildResult.setStartDate(date(2011, Calendar.SEPTEMBER, 7, 1, 18, 35));
    buildResult.setExitCode(3);
    buildResult.setLog("Oh. Yeah.".getBytes("UTF-8"));
    final Pair<Long, Integer> when = new Pair<Long, Integer>(123450000000L, 120);
    final String who = misterExample.toString();
    final ObjectId logs = ObjectId.fromString("c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3");
    given(time.offsetToString(120)).willReturn("+0200");

    // when
    String text = dao.serializeResult(buildResult, who, when, logs);

    // then
    assertThat(text).isEqualTo( //
            "build 12345" + "\n" + //
                    "log c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3" + "\n" + //
                    "return-code 3" + "\n" + //
                    "author \"Mister Example\" <user@example.org>" + "\n" + //
                    "when 123450000000 +0200\n" //
    );
}

From source file:org.kercoin.magrit.core.dao.BuildDAOImplTest.java

License:Open Source License

@Test
public void testSerializeNote() throws Exception {
    String text = dao.serializeBuildNote(ObjectId.fromString("c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3"));
    assertThat(text).isEqualTo("magrit:built-by c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3c4f3b4b3");
}

From source file:org.kercoin.magrit.sshd.commands.SendBuildCommandTest.java

License:Open Source License

@Test
public void run() throws Exception {
    // given/*  ww w  . ja va2 s.c  o  m*/
    UserIdentity expectedUserIdentity = new UserIdentity("ptitfred@localhost", "ptitfred");
    given(userService.find("ptitfred")).willReturn(expectedUserIdentity);
    command.setForce(false);
    command.setSha1("HEAD");
    command.setCommand("HEAD^");
    command.setRepo(repo);
    ObjectId what = ObjectId.zeroId();
    given(repo.resolve("HEAD")).willReturn(what);
    ObjectId whatElse = ObjectId.fromString("0123456789012345678901234567890123456789");
    given(repo.resolve("HEAD^")).willReturn(whatElse);

    // when
    command.run();

    // then
    verify(userService).find("ptitfred");
    verify(buildQueueService).enqueueBuild(expectedUserIdentity, repo,
            "0000000000000000000000000000000000000000", "0123456789012345678901234567890123456789", false);
}