Java Code Examples for jenkins.scm.api.SCMRevision#getHead()

The following examples show how to use jenkins.scm.api.SCMRevision#getHead() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GitLabSCMFileSystem.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
protected GitLabSCMFileSystem(
    GitLabApi gitLabApi,
    String projectPath,
    String ref,
    @CheckForNull SCMRevision rev) throws IOException {
    super(rev);
    this.gitLabApi = gitLabApi;
    this.projectPath = projectPath;
    if (rev != null) {
        if (rev.getHead() instanceof MergeRequestSCMHead) {
            this.ref = ((MergeRequestSCMRevision) rev).getOrigin().getHash();
        } else if (rev instanceof BranchSCMRevision) {
            this.ref = ((BranchSCMRevision) rev).getHash();
        } else if (rev instanceof GitTagSCMRevision) {
            this.ref = ((GitTagSCMRevision) rev).getHash();
        } else {
            this.ref = ref;
        }
    } else {
        this.ref = ref;
    }
}
 
Example 2
Source File: GitLabSCMSource.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
@NonNull
@Override
public SCMRevision getTrustedRevision(@NonNull SCMRevision revision, @NonNull TaskListener listener) {
    if (revision instanceof MergeRequestSCMRevision) {
        MergeRequestSCMHead head = (MergeRequestSCMHead) revision.getHead();
        try (GitLabSCMSourceRequest request = new GitLabSCMSourceContext(null, SCMHeadObserver.none())
                .withTraits(traits).newRequest(this, listener)) {
            request.setMembers(getMembers());
            boolean isTrusted = request.isTrusted(head);
            LOGGER.log(Level.FINEST, String.format("Trusted Revision: %s -> %s", head.getOriginOwner(), isTrusted));
            if (isTrusted) {
                return revision;
            }
        } catch (IOException | InterruptedException e) {
            LOGGER.log(Level.SEVERE, "Exception caught: " + e, e);
        }
        MergeRequestSCMRevision rev = (MergeRequestSCMRevision) revision;
        listener.getLogger().format("Loading trusted files from target branch %s at %s rather than %s%n",
                head.getTarget().getName(), rev.getBaseHash(), rev.getHeadHash());
        return new SCMRevisionImpl(head.getTarget(), rev.getBaseHash());
    }
    return revision;
}
 
Example 3
Source File: GiteaSCMFileSystem.java    From gitea-plugin with MIT License 6 votes vote down vote up
protected GiteaSCMFileSystem(GiteaConnection connection, GiteaRepository repo, String ref,
                             @CheckForNull SCMRevision rev) throws IOException {
    super(rev);
    this.connection = connection;
    this.repo = repo;
    if (rev != null) {
        if (rev.getHead() instanceof PullRequestSCMHead) {
            this.ref = ((PullRequestSCMRevision) rev).getOrigin().getHash();
        } else if (rev instanceof BranchSCMRevision) {
            this.ref = ((BranchSCMRevision) rev).getHash();
        } else if (rev instanceof TagSCMRevision) {
            this.ref = ((TagSCMRevision) rev).getHash();
        } else {
            this.ref = ref;
        }
    } else {
        this.ref = ref;
    }
}
 
Example 4
Source File: GitHubSCMFileSystem.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * Constructor.
 *
 * @param gitHub the {@link GitHub}
 * @param repo the {@link GHRepository}
 * @param refName the ref name, e.g. {@code heads/branchName}, {@code tags/tagName}, {@code pull/N/head} or the SHA.
 * @param rev the optional revision.
 * @throws IOException if I/O errors occur.
 */
protected GitHubSCMFileSystem(GitHub gitHub, GHRepository repo, String refName, @CheckForNull SCMRevision rev) throws IOException {
    super(rev);
    this.gitHub = gitHub;
    this.open = true;
    this.repo = repo;
    if (rev != null) {
        if (rev.getHead() instanceof PullRequestSCMHead) {
            PullRequestSCMRevision prRev = (PullRequestSCMRevision) rev;
            PullRequestSCMHead pr = (PullRequestSCMHead) prRev.getHead();
            if (pr.isMerge()) {
                this.ref = prRev.getMergeHash();
            } else {
                this.ref = prRev.getPullHash();
            }
        } else if (rev instanceof AbstractGitSCMSource.SCMRevisionImpl) {
            this.ref = ((AbstractGitSCMSource.SCMRevisionImpl) rev).getHash();
        } else {
            this.ref = refName;
        }
    } else {
        this.ref = refName;
    }
}
 
Example 5
Source File: GitLabPipelineStatusNotifier.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Log comment on Commits and Merge Requests upon build complete.
 */
private static void logComment(Run<?, ?> build, TaskListener listener) {
    GitLabSCMSource source = getSource(build);
    if (source == null) {
        return;
    }
    final GitLabSCMSourceContext sourceContext = getSourceContext(build, source);
    if (!sourceContext.logCommentEnabled()) {
        return;
    }
    String url = getRootUrl(build);
    if (url.isEmpty()) {
        listener.getLogger().println(
            "Can not determine Jenkins root URL. Comments are disabled until a root URL is"
                + " configured in Jenkins global configuration.");
        return;
    }
    Result result = build.getResult();
    LOGGER.log(Level.FINE, String.format("Log Comment Result: %s", result));
    String note = "";
    String symbol = "";
    if (Result.SUCCESS.equals(result)) {
        if (!sourceContext.doLogSuccess()) {
            return;
        }
        symbol = ":heavy_check_mark: ";
        note = "The Jenkins CI build passed ";
    } else if (Result.UNSTABLE.equals(result)) {
        symbol = ":heavy_multiplication_x: ";
        note = "The Jenkins CI build failed ";
    } else if (Result.FAILURE.equals(result)) {
        symbol = ":heavy_multiplication_x: ";
        note = "The Jenkins CI build failed ";
    } else if (result != null) { // ABORTED, NOT_BUILT.
        symbol = ":no_entry_sign: ";
        note = "The Jenkins CI build aborted ";
    }
    String suffix = " - [Details](" + url + ")";
    SCMRevision revision = SCMRevisionAction.getRevision(source, build);
    try {
        GitLabApi gitLabApi = GitLabHelper.apiBuilder(source.getServerName());
        String sudoUsername = sourceContext.getSudoUser();
        if (!sudoUsername.isEmpty()) {
            gitLabApi.sudo(sudoUsername);
        }
        final String buildName = "**" + getStatusName(sourceContext, build, revision) + ":** ";
        final String hash;
        if (revision instanceof BranchSCMRevision) {
            hash = ((BranchSCMRevision) revision).getHash();
            gitLabApi.getCommitsApi().addComment(
                source.getProjectPath(),
                hash,
                symbol + buildName + note + suffix
            );
        } else if (revision instanceof MergeRequestSCMRevision) {
            MergeRequestSCMHead head = (MergeRequestSCMHead) revision.getHead();
            gitLabApi.getNotesApi().createMergeRequestNote(
                source.getProjectPath(),
                Integer.valueOf(head.getId()),
                symbol + buildName + note + suffix
            );
        } else if (revision instanceof GitTagSCMRevision) {
            hash = ((GitTagSCMRevision) revision).getHash();
            gitLabApi.getCommitsApi().addComment(
                source.getProjectPath(),
                hash,
                symbol + buildName + note + suffix
            );
        }
    } catch (GitLabApiException e) {
        LOGGER.log(Level.WARNING, "Exception caught:" + e, e);
    }
}
 
Example 6
Source File: GiteaSCMSource.java    From gitea-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public SCMRevision getTrustedRevision(@NonNull SCMRevision revision, @NonNull TaskListener listener)
        throws IOException, InterruptedException {
    if (revision instanceof PullRequestSCMRevision) {
        PullRequestSCMHead head = (PullRequestSCMHead) revision.getHead();
        try (GiteaConnection c = gitea().open()) {
            try (GiteaSCMSourceRequest request = new GiteaSCMSourceContext(null, SCMHeadObserver.none())
                    .withTraits(getTraits())
                    .newRequest(this, listener)) {
                request.setConnection(c);
                Set<String> names = new HashSet<>();
                for (GiteaUser u : c.fetchCollaborators(giteaRepository)) {
                    names.add(u.getUsername());
                }
                request.setCollaboratorNames(names);
                if (request.isTrusted(head)) {
                    return revision;
                }
            }
            PullRequestSCMRevision rev = (PullRequestSCMRevision) revision;
            listener.getLogger().format("Loading trusted files from base branch %s at %s rather than %s%n",
                    head.getTarget().getName(), ((SCMRevisionImpl) rev.getTarget()).getHash(),
                    rev.getOrigin().getHash());
            return rev.getTarget();
        }
    }
    return revision;
}
 
Example 7
Source File: GitHubSCMSource.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Override
public SCMRevision getTrustedRevision(SCMRevision revision, final TaskListener listener)
        throws IOException, InterruptedException {
    if (revision instanceof PullRequestSCMRevision) {
        PullRequestSCMHead head = (PullRequestSCMHead) revision.getHead();

        try (GitHubSCMSourceRequest request = new GitHubSCMSourceContext(null, SCMHeadObserver.none())
                .withTraits(traits)
                .newRequest(this, listener)) {
            if (collaboratorNames != null) {
                request.setCollaboratorNames(collaboratorNames);
            } else {
                request.setCollaboratorNames(new DeferredContributorNames(request, listener));
            }
            request.setPermissionsSource(new DeferredPermissionsSource(listener));
            if (request.isTrusted(head)) {
                return revision;
            }
        } catch (WrappedException wrapped) {
            try {
                wrapped.unwrap();
            } catch (HttpException e) {
                listener.getLogger()
                        .format("It seems %s is unreachable, assuming no trusted collaborators%n",
                                apiUri);
                collaboratorNames = Collections.singleton(repoOwner);
            }
        }
        PullRequestSCMRevision rev = (PullRequestSCMRevision) revision;
        listener.getLogger().format("Loading trusted files from base branch %s at %s rather than %s%n",
                head.getTarget().getName(), rev.getBaseHash(), rev.getPullHash());
        return new SCMRevisionImpl(head.getTarget(), rev.getBaseHash());
    }
    return revision;
}
 
Example 8
Source File: GitHubBuildStatusNotification.java    From github-branch-source-plugin with MIT License 4 votes vote down vote up
private static void createBuildCommitStatus(Run<?, ?> build, TaskListener listener) {
    SCMSource src = SCMSource.SourceByItem.findSource(build.getParent());
    SCMRevision revision = src != null ? SCMRevisionAction.getRevision(src, build) : null;
    if (revision != null) { // only notify if we have a revision to notify
        try {
            GitHub gitHub = lookUpGitHub(build.getParent());
            try {
                GHRepository repo = lookUpRepo(gitHub, build.getParent());
                if (repo != null) {
                    Result result = build.getResult();
                    String revisionToNotify = resolveHeadCommit(revision);
                    SCMHead head = revision.getHead();
                    List<AbstractGitHubNotificationStrategy> strategies = new GitHubSCMSourceContext(null, SCMHeadObserver.none())
                            .withTraits(((GitHubSCMSource) src).getTraits()).notificationStrategies();
                    for (AbstractGitHubNotificationStrategy strategy : strategies) {
                        // TODO allow strategies to combine/cooperate on a notification
                        GitHubNotificationContext notificationContext = GitHubNotificationContext.build(null, build,
                                src, head);
                        List<GitHubNotificationRequest> details = strategy.notifications(notificationContext, listener);
                        for (GitHubNotificationRequest request : details) {
                            boolean ignoreError = request.isIgnoreError();
                            try {
                                repo.createCommitStatus(revisionToNotify, request.getState(), request.getUrl(), request.getMessage(),
                                        request.getContext());
                            } catch (FileNotFoundException fnfe) {
                                if (!ignoreError) {
                                    listener.getLogger().format("%nCould not update commit status, please check if your scan " +
                                            "credentials belong to a member of the organization or a collaborator of the " +
                                            "repository and repo:status scope is selected%n%n");
                                    if (LOGGER.isLoggable(Level.FINE)) {
                                        LOGGER.log(Level.FINE, "Could not update commit status, for run "
                                                + build.getFullDisplayName()
                                                + " please check if your scan "
                                                + "credentials belong to a member of the organization or a "
                                                + "collaborator of the repository and repo:status scope is selected", fnfe);
                                    }
                                }
                            }
                        }
                    }
                    if (result != null) {
                        listener.getLogger().format("%n" + Messages.GitHubBuildStatusNotification_CommitStatusSet() + "%n%n");
                    }
                }
            } finally {
                Connector.release(gitHub);
            }
        } catch (IOException ioe) {
            listener.getLogger().format("%n"
                    + "Could not update commit status. Message: %s%n"
                    + "%n", ioe.getMessage());
            if (LOGGER.isLoggable(Level.FINE)) {
                LOGGER.log(Level.FINE, "Could not update commit status of run " + build.getFullDisplayName(), ioe);
            }
        }
    }
}