jenkins.scm.api.SCMHead Java Examples

The following examples show how to use jenkins.scm.api.SCMHead. 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: AllBranchBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener taskListener) {

    if(strategies.isEmpty()){
        return false;
    }

    for (BranchBuildStrategy strategy: strategies) {
        if(!strategy.automaticBuild(
            source,
            head,
            currRevision,
            lastBuiltRevision,
            lastSeenRevision,
            taskListener
        )){
            return false;
        };

    }
    return true;
}
 
Example #2
Source File: NamedBranchBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener taskListener) {
    if (head instanceof ChangeRequestSCMHead) {
        return false;
    }
    if (head instanceof TagSCMHead) {
        return false;
    }
    String name = head.getName();
    for (NameFilter filter: filters) {
        if (filter.isMatch(name)) {
            return true;
        }
    }
    return false;
}
 
Example #3
Source File: TagBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull  TaskListener taskListener) {
    if (!(head instanceof TagSCMHead)) {
        return false;
    }
    if (atLeastMillis >= 0L || atMostMillis >= 0L) {
        if (atMostMillis >= 0L && atLeastMillis > atMostMillis) {
            // stupid configuration that corresponds to never building anything, why did the user add it against
            // our advice?
            return false;
        }
        long tagAge = System.currentTimeMillis() - ((TagSCMHead)head).getTimestamp();
        if (atMostMillis >= 0L && tagAge > atMostMillis) {
            return false;
        }
        if (atLeastMillis >= 0L && tagAge < atLeastMillis) {
            return false;
        }
    }
    return true;
}
 
Example #4
Source File: BranchDiscoveryTrait.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) {
    if (head instanceof BranchSCMHead && request instanceof GitHubSCMSourceRequest) {
        for (GHPullRequest p : ((GitHubSCMSourceRequest) request).getPullRequests()) {
            GHRepository headRepo = p.getHead().getRepository();
            if (headRepo != null // head repo can be null if the PR is from a repo that has been deleted
                    && p.getBase().getRepository().getFullName().equalsIgnoreCase(headRepo.getFullName())
                    && p.getHead().getRef().equals(head.getName())) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #5
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Nonnull
private List<Action> retrieve(@Nonnull SCMRevisionImpl revision, @CheckForNull SCMHeadEvent event, @Nonnull TaskListener listener) throws IOException, InterruptedException {
    List<Action> actions = new ArrayList<>();

    String hash = revision.getHash();
    Action linkAction = GitLabLinkAction.toCommit(source.getProject(), hash);
    actions.add(linkAction);

    SCMHead head = revision.getHead();
    if (head instanceof GitLabSCMMergeRequestHead) {
        actions.add(createHeadMetadataAction(head.getName(), ((GitLabSCMMergeRequestHead) head).getSource(), hash, linkAction.getUrlName()));
    } else if (head instanceof GitLabSCMHead) {
        actions.add(createHeadMetadataAction(head.getName(), (GitLabSCMHead) head, hash, linkAction.getUrlName()));
    }

    if (event instanceof GitLabSCMEvent) {
        actions.add(new GitLabSCMCauseAction(((GitLabSCMEvent) event).getCause()));
    }

    return actions;
}
 
Example #6
Source File: AnyBranchBuildStrategyImpl.java    From basic-branch-build-strategies-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isAutomaticBuild(@NonNull SCMSource source, @NonNull SCMHead head, @NonNull SCMRevision currRevision,
                                @CheckForNull SCMRevision lastBuiltRevision, @CheckForNull SCMRevision lastSeenRevision, @NonNull TaskListener taskListener) {

    if(strategies.isEmpty()){
        return false;
    }

    for (BranchBuildStrategy strategy: strategies) {
        if(strategy.automaticBuild(
            source,
            head,
            currRevision,
            lastBuiltRevision,
            lastSeenRevision,
            taskListener
        )){
            return true;
        };

    }
    return false;
}
 
Example #7
Source File: BitbucketPipelineCreateRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
protected boolean repoHasJenkinsFile(@Nonnull SCMSource scmSource) {
    final JenkinsfileCriteria criteria = new JenkinsfileCriteria();
    try {
        scmSource.fetch(criteria, new SCMHeadObserver() {
            @Override
            public void observe(@Nonnull SCMHead head, @Nonnull SCMRevision revision) throws IOException, InterruptedException {
                //do nothing
            }

            @Override
            public boolean isObserving() {
                //if jenkinsfile is found stop observing
                return !criteria.isJenkinsfileFound();

            }
        }, TaskListener.NULL);
    } catch (IOException | InterruptedException e) {
        logger.warn("Error detecting Jenkinsfile: "+e.getMessage(), e);
    }

    return criteria.isJenkinsfileFound();
}
 
Example #8
Source File: TemplateDrivenBranchProjectFactory.java    From multi-branch-project-plugin with MIT License 6 votes vote down vote up
@Nonnull
@Override
public Branch getBranch(@Nonnull P project) {
    BranchProjectProperty property = project.getProperty(BranchProjectProperty.class);

    /*
     * Ugly hackish stuff, in the event that the user configures a branch project directly, thereby removing the
     * BranchProjectProperty.  The property must exist and we can't bash the @Nonnull return value restriction!
     *
     * Fudge some generic Branch with the expectation that indexing will soon reset the Branch with proper values,
     * or that it will be converted to Branch.Dead and the guessed values for sourceId and properties won't matter.
     */
    if (property == null) {
        Branch branch = new Branch("unknown", new SCMHead(project.getDisplayName()), project.getScm(),
                Collections.<BranchProperty>emptyList());
        setBranch(project, branch);
        return branch;
    }

    return property.getBranch();
}
 
Example #9
Source File: GitHubSourceContext.java    From github-integration-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings({"rawtypes", "unchecked"})
private void forceScheduling(GitHubSCMRevision scmRevision) throws IOException {
    SCMSourceOwner owner = source.getOwner();
    if (owner instanceof MultiBranchProject) {
        MultiBranchProject mb = (MultiBranchProject) owner;
        BranchProjectFactory pf = mb.getProjectFactory();

        SCMHead scmHead = scmRevision.getHead();
        Job j = mb.getItemByBranchName(scmHead.getName());
        if (j != null) {
            SCMRevision rev = pf.getRevision(j);
            // set current rev to dummy to force scheduling
            if (rev != null && rev.equals(scmRevision)) {
                pf.setRevisionHash(j, new DummyRevision(scmHead));
            }
        }
    }
}
 
Example #10
Source File: CachesTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void testPullRequestCacheLoaderWithoutScmHead() throws Exception {
    ObjectMetadataAction metadataAction = new ObjectMetadataAction("A cool PR", "A very cool change", "http://example.com/pr/1");
    when(job.getAction(ObjectMetadataAction.class)).thenReturn(metadataAction);

    ContributorMetadataAction contributorMetadataAction = new ContributorMetadataAction("Hates Cake", "He hates cake", "[email protected]");
    when(job.getAction(ContributorMetadataAction.class)).thenReturn(contributorMetadataAction);

    PowerMockito.mockStatic(ExtensionList.class);

    ExtensionList<SCMHead.HeadByItem> extensionList = mock(ExtensionList.class);
    when(extensionList.iterator()).thenReturn(Lists.<SCMHead.HeadByItem>newArrayList().iterator());
    when(ExtensionList.lookup(SCMHead.HeadByItem.class)).thenReturn(extensionList);

    Caches.PullRequestCacheLoader loader = new Caches.PullRequestCacheLoader(jenkins);
    BranchImpl.PullRequest pr = loader.load(job.getFullName()).orNull();

    assertNull(pr);
}
 
Example #11
Source File: CachesTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void testPullRequestCacheLoaderWithoutObjectMetadataAction() throws Exception {

    ContributorMetadataAction contributorMetadataAction = new ContributorMetadataAction("Hates Cake", "He hates cake", "[email protected]");
    when(job.getAction(ContributorMetadataAction.class)).thenReturn(contributorMetadataAction);

    PowerMockito.mockStatic(ExtensionList.class);

    ExtensionList<SCMHead.HeadByItem> extensionList = mock(ExtensionList.class);
    when(extensionList.iterator()).thenReturn(Lists.<SCMHead.HeadByItem>newArrayList(new HeadByItemForTest()).iterator());
    when(ExtensionList.lookup(SCMHead.HeadByItem.class)).thenReturn(extensionList);

    Caches.PullRequestCacheLoader loader = new Caches.PullRequestCacheLoader(jenkins);
    BranchImpl.PullRequest pr = loader.load(job.getFullName()).orNull();

    assertNotNull(pr);
    assertEquals("Hates Cake", pr.getAuthor());
    assertEquals("1", pr.getId());
    assertNull(pr.getTitle());
    assertNull(pr.getUrl());
}
 
Example #12
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private boolean acceptMergeRequest(SCMHead head) {
    if (head instanceof GitLabSCMMergeRequestHead) {
        GitLabSCMMergeRequestHead mergeRequest = (GitLabSCMMergeRequestHead) head;
        return mergeRequest.isMerged() &&
                source.getSourceSettings().determineMergeRequestStrategyValue(
                        mergeRequest,
                        source.getSourceSettings().getOriginMonitorStrategy().getAcceptMergeRequests(),
                        source.getSourceSettings().getForksMonitorStrategy().getAcceptMergeRequests());
    }
    return false;
}
 
Example #13
Source File: SourceActions.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
private boolean removeSourceBranch(SCMHead head) {
    if (head instanceof GitLabSCMMergeRequestHead) {
        GitLabSCMMergeRequestHead mergeRequest = (GitLabSCMMergeRequestHead) head;
        return mergeRequest.isMerged() && mergeRequest.fromOrigin() && source.getSourceSettings().getOriginMonitorStrategy().getRemoveSourceBranch();
    }

    return false;
}
 
Example #14
Source File: GitLabBranchFilter.java    From gitlab-branch-source-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item : all) {
        if (added.contains(item)) {
            continue;
        }

        SCMHead head = SCMHead.HeadByItem.findHead(item);
        if (head instanceof GitLabSCMBranchHead && filter(item) && filter((GitLabSCMBranchHead) head)) {
            added.add(item);
        }
    }
    return added;
}
 
Example #15
Source File: GitHubSCMBuilder.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param source   the {@link GitHubSCMSource}.
 * @param head     the {@link SCMHead}
 * @param revision the (optional) {@link SCMRevision}
 */
public GitHubSCMBuilder(@NonNull GitHubSCMSource source,
                        @NonNull SCMHead head, @CheckForNull SCMRevision revision) {
    super(head, revision, /*dummy value*/guessRemote(source), source.getCredentialsId());
    this.context = source.getOwner();
    apiUri = StringUtils.defaultIfBlank(source.getApiUri(), GitHubServerConfig.GITHUB_URL);
    repoOwner = source.getRepoOwner();
    repository = source.getRepository();
    repositoryUrl = source.getResolvedRepositoryUrl();
    // now configure the ref specs
    withoutRefSpecs();
    String repoUrl;
    if (head instanceof PullRequestSCMHead) {
        PullRequestSCMHead h = (PullRequestSCMHead) head;
        withRefSpec("+refs/pull/" + h.getId() + "/head:refs/remotes/@{remote}/" + head
                .getName());
        repoUrl = repositoryUrl(h.getSourceOwner(), h.getSourceRepo());
    } else if (head instanceof TagSCMHead) {
        withRefSpec("+refs/tags/" + head.getName() + ":refs/tags/" + head.getName());
        repoUrl = repositoryUrl(repoOwner, repository);
    } else {
        withRefSpec("+refs/heads/" + head.getName() + ":refs/remotes/@{remote}/" + head.getName());
        repoUrl = repositoryUrl(repoOwner, repository);
    }
    // pre-configure the browser
    if (repoUrl != null) {
        withBrowser(new GithubWeb(repoUrl));
    }
    withCredentials(credentialsId(), null);
}
 
Example #16
Source File: PipelineJobFiltersTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void testIsPullRequest(){
    BlueOrganization organization = mockOrganization();
    OrganizationFolder organizationFolder = mockOrgFolder(organization);
    PullRequestSCMHead changeRequestSCMHead = mock(PullRequestSCMHead.class);
    mockStatic(SCMHead.HeadByItem.class);
    when(SCMHead.HeadByItem.findHead(organizationFolder)).thenReturn(changeRequestSCMHead);
    assertTrue(PipelineJobFilters.isPullRequest(organizationFolder));
    assertFalse(new PipelineJobFilters.OriginFilter().getFilter().apply(organizationFolder));
    assertTrue(new PipelineJobFilters.PullRequestFilter().getFilter().apply(organizationFolder));
}
 
Example #17
Source File: ActionableBuilder.java    From office-365-connector-plugin with Apache License 2.0 5 votes vote down vote up
private void pullRequestActionable() {
    Job job = run.getParent();
    SCMHead head = SCMHead.HeadByItem.findHead(job);
    if (head instanceof ChangeRequestSCMHead) {
        String pronoun = StringUtils.defaultIfBlank(
                head.getPronoun(),
                Messages.Office365ConnectorWebhookNotifier_ChangeRequestPronoun()
        );
        String viewHeader = Messages.Office365ConnectorWebhookNotifier_ViewHeader(pronoun);
        String titleHeader = Messages.Office365ConnectorWebhookNotifier_TitleHeader(pronoun);
        String authorHeader = Messages.Office365ConnectorWebhookNotifier_AuthorHeader(pronoun);

        ObjectMetadataAction oma = job.getAction(ObjectMetadataAction.class);
        if (oma != null) {
            String urlString = oma.getObjectUrl();
            PotentialAction viewPRPotentialAction = new PotentialAction(viewHeader, urlString);
            potentialActions.add(viewPRPotentialAction);
            factsBuilder.addFact(titleHeader, oma.getObjectDisplayName());
        }
        ContributorMetadataAction cma = job.getAction(ContributorMetadataAction.class);
        if (cma != null) {
            String contributor = cma.getContributor();
            String contributorDisplayName = cma.getContributorDisplayName();

            if (StringUtils.isNotBlank(contributor) && StringUtils.isNotBlank(contributorDisplayName)) {
                factsBuilder.addFact(authorHeader, String.format("%s (%s)", contributor, contributorDisplayName));
            } else {
                factsBuilder.addFact(authorHeader, StringUtils.defaultIfBlank(contributor, contributorDisplayName));
            }
        }
    }
}
 
Example #18
Source File: ActionableBuilderTest.java    From office-365-connector-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void pullRequestActionable_OnContributorMetadataAction_AddsFact() {

    // given
    // from @Before
    SCMHead head = new SCMHeadBuilder("Pull Request");

    Job job = mock(Job.class);
    when(run.getParent()).thenReturn(job);

    mockStatic(SCMHead.HeadByItem.class);
    when(SCMHead.HeadByItem.findHead(job)).thenReturn(head);

    ObjectMetadataAction objectMetadataAction = mock(ObjectMetadataAction.class);
    when(objectMetadataAction.getObjectUrl()).thenReturn("https://github.com/organization/repository/pull/1");
    when(objectMetadataAction.getObjectDisplayName()).thenReturn("test pull request");
    when(job.getAction(ObjectMetadataAction.class)).thenReturn(objectMetadataAction);

    // when
    Deencapsulation.invoke(actionableBuilder, "pullRequestActionable");

    // then
    assertThat(factsBuilder.collect()).hasSize(1);

    List<PotentialAction> potentialActions = Deencapsulation.getField(actionableBuilder, "potentialActions");
    assertThat(potentialActions).hasSize(1);
}
 
Example #19
Source File: GitHubBranchSCMHeadEvent.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Nonnull
@Override
public Map<SCMHead, SCMRevision> heads(@Nonnull SCMSource source) {
    if (!isMatch(source)) {
        return Collections.emptyMap();
    }
    return Collections.singletonMap(new GitHubBranchSCMHead(getPayload().getBranchName(), source.getId()), null);
}
 
Example #20
Source File: AsIsGitSCMFactory.java    From github-integration-plugin with MIT License 5 votes vote down vote up
@Override
public GitSCM createScm(GitHubSCMSource scmSource, SCMHead scmHead, SCMRevision scmRevision) {
    return new GitSCM(
            gitSCM.getUserRemoteConfigs(),
            gitSCM.getBranches(),
            gitSCM.isDoGenerateSubmoduleConfigurations(),
            gitSCM.getSubmoduleCfg(),
            gitSCM.getBrowser(),
            gitSCM.getGitTool(),
            gitSCM.getExtensions()
    );
}
 
Example #21
Source File: BranchDiscoveryTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) {
    if (head instanceof BranchSCMHead && request instanceof GiteaSCMSourceRequest) {
        for (GiteaPullRequest p : ((GiteaSCMSourceRequest) request).getPullRequests()) {
            if (p.getHead() == null || p.getHead().getRepo() == null
                    || p.getHead().getRepo().getOwner() == null
                    || p.getHead().getRepo().getName() == null
                    || p.getHead().getRef() == null
            ) {
                // the head has already been deleted, so ignore as we cannot build yet JENKINS-60825
                // TODO figure out if we can build a PR who's head has been deleted as it should be possible
                return true;
            }
            if (StringUtils.equalsIgnoreCase(
                    p.getBase().getRepo().getOwner().getUsername(),
                    p.getHead().getRepo().getOwner().getUsername())
                    && StringUtils.equalsIgnoreCase(
                            p.getBase().getRepo().getName(),
                    p.getHead().getRepo().getName())
                    && StringUtils.equals(p.getHead().getRef(), head.getName())) {
                return false;
            }
        }
        return true;
    }
    return false;
}
 
Example #22
Source File: GiteaSCMSource.java    From gitea-plugin with MIT License 5 votes vote down vote up
@Override
public void record(@NonNull SCMHead head, SCMRevision revision, boolean isMatch) {
    if (isMatch) {
        listener.getLogger().format("    Met criteria%n");
    } else {
        listener.getLogger().format("    Does not meet criteria%n");
    }
}
 
Example #23
Source File: GitHubBranchFilter.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public List<TopLevelItem> filter(List<TopLevelItem> added, List<TopLevelItem> all, View filteringView) {
    for (TopLevelItem item:all) {
        if (added.contains(item)) {
            continue;
        }
        if (SCMHead.HeadByItem.findHead(item) instanceof BranchSCMHead) {
            added.add(item);
        }
    }
    return added;
}
 
Example #24
Source File: GiteaSCMBuilder.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param source   the {@link GiteaSCMSource}.
 * @param head     the {@link SCMHead}
 * @param revision the (optional) {@link SCMRevision}
 */
public GiteaSCMBuilder(@NonNull GiteaSCMSource source,
                       @NonNull SCMHead head, @CheckForNull SCMRevision revision) {
    super(
            head,
            revision,
            checkoutUriTemplate(null, source.getServerUrl(), null, null)
                    .set("owner", source.getRepoOwner())
                    .set("repository", source.getRepository())
                    .expand(),
            source.getCredentialsId()
    );
    this.context = source.getOwner();
    serverUrl = source.getServerUrl();
    repoOwner = source.getRepoOwner();
    repository = source.getRepository();
    sshRemote = source.getSshRemote();
    // now configure the ref specs
    withoutRefSpecs();
    String repoUrl;
    if (head instanceof PullRequestSCMHead) {
        PullRequestSCMHead h = (PullRequestSCMHead) head;
        withRefSpec("+refs/pull/" + h.getId() + "/head:refs/remotes/@{remote}/" + head
                .getName());
        repoUrl = repositoryUrl(h.getOriginOwner(), h.getOriginRepository());
    } else if (head instanceof TagSCMHead) {
        withRefSpec("+refs/tags/" + head.getName() + ":refs/tags/@{remote}/" + head.getName());
        repoUrl = repositoryUrl(repoOwner, repository);
    } else {
        withRefSpec("+refs/heads/" + head.getName() + ":refs/remotes/@{remote}/" + head.getName());
        repoUrl = repositoryUrl(repoOwner, repository);
    }
    // pre-configure the browser
    withBrowser(new GiteaBrowser(repoUrl));
}
 
Example #25
Source File: GiteaCreateSCMEvent.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public Map<SCMHead, SCMRevision> headsFor(GiteaSCMSource source) {
    String ref = getPayload().getRef();
    ref = ref.startsWith(Constants.R_HEADS) ? ref.substring(Constants.R_HEADS.length()) : ref;
    BranchSCMHead h = new BranchSCMHead(ref);
    return Collections.<SCMHead, SCMRevision>singletonMap(h, new BranchSCMRevision(h, getPayload().getSha()));
}
 
Example #26
Source File: GiteaSCMSourceRequest.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * Constructor.
 *
 * @param source   the source.
 * @param context  the context.
 * @param listener the listener.
 */
GiteaSCMSourceRequest(SCMSource source, GiteaSCMSourceContext context, TaskListener listener) {
    super(source, context, listener);
    fetchBranches = context.wantBranches();
    fetchTags = context.wantTags();
    fetchOriginPRs = context.wantOriginPRs();
    fetchForkPRs = context.wantForkPRs();
    originPRStrategies = fetchOriginPRs && !context.originPRStrategies().isEmpty()
            ? Collections.unmodifiableSet(EnumSet.copyOf(context.originPRStrategies()))
            : Collections.<ChangeRequestCheckoutStrategy>emptySet();
    forkPRStrategies = fetchForkPRs && !context.forkPRStrategies().isEmpty()
            ? Collections.unmodifiableSet(EnumSet.copyOf(context.forkPRStrategies()))
            : Collections.<ChangeRequestCheckoutStrategy>emptySet();
    Set<SCMHead> includes = context.observer().getIncludes();
    if (includes != null) {
        Set<Long> pullRequestNumbers = new HashSet<>(includes.size());
        Set<String> branchNames = new HashSet<>(includes.size());
        Set<String> tagNames = new HashSet<>(includes.size());
        for (SCMHead h : includes) {
            if (h instanceof BranchSCMHead) {
                branchNames.add(h.getName());
            } else if (h instanceof PullRequestSCMHead) {
                pullRequestNumbers.add(Long.parseLong(((PullRequestSCMHead) h).getId()));
                if (SCMHeadOrigin.DEFAULT.equals(h.getOrigin())) {
                    branchNames.add(((PullRequestSCMHead) h).getOriginName());
                }
            } else if (h instanceof TagSCMHead) {
                tagNames.add(h.getName());
            }
        }
        this.requestedPullRequestNumbers = Collections.unmodifiableSet(pullRequestNumbers);
        this.requestedOriginBranchNames = Collections.unmodifiableSet(branchNames);
        this.requestedTagNames = Collections.unmodifiableSet(tagNames);
    } else {
        requestedPullRequestNumbers = null;
        requestedOriginBranchNames = null;
        requestedTagNames = null;
    }
}
 
Example #27
Source File: AbstractGiteaSCMHeadEvent.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@NonNull
@Override
public Map<SCMHead, SCMRevision> heads(@NonNull SCMSource source) {
    if (source instanceof GiteaSCMSource) {
        // check the owner, we don't care about the event if the owner isn't a match
        GiteaSCMSource src = (GiteaSCMSource) source;
        return StringUtils.equalsIgnoreCase(getPayload().getRepository().getOwner().getUsername(), src.getRepoOwner())
                && StringUtils.equalsIgnoreCase(getPayload().getRepository().getName(), src.getRepository())
                && GiteaServers.isEventFor(src.getServerUrl(), getPayload().getRepository().getHtmlUrl())
                ? headsFor(src)
                : Collections.<SCMHead, SCMRevision>emptyMap();
    }
    return Collections.emptyMap();
}
 
Example #28
Source File: GitLabTagPushSCMEvent.java    From gitlab-branch-source-plugin with MIT License 5 votes vote down vote up
@NonNull
@Override
public Map<SCMHead, SCMRevision> headsFor(GitLabSCMSource source) {
    String ref = getPayload().getRef();
    ref = ref.startsWith(Constants.R_TAGS) ? ref.substring(Constants.R_TAGS.length()) : ref;
    long time = 0L;
    if (getType() == CREATED) {
        time = getPayload().getCommits().get(0).getTimestamp().getTime();
    }
    GitLabTagSCMHead h = new GitLabTagSCMHead(ref, time);
    String hash = getPayload().getCheckoutSha();
    return Collections.<SCMHead, SCMRevision>singletonMap(h,
        (getType() == CREATED)
            ? new GitTagSCMRevision(h, hash) : null);
}
 
Example #29
Source File: BranchDiscoveryTrait.java    From gitea-plugin with MIT License 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public boolean isExcluded(@NonNull SCMSourceRequest request, @NonNull SCMHead head) {
    if (head instanceof BranchSCMHead && request instanceof GiteaSCMSourceRequest) {
        for (GiteaPullRequest p : ((GiteaSCMSourceRequest) request).getPullRequests()) {
            if (p.getHead() == null || p.getHead().getRepo() == null
                    || p.getHead().getRepo().getOwner() == null
                    || p.getHead().getRepo().getName() == null
                    || p.getHead().getRef() == null
            ) {
                // the head has already been deleted, so ignore as we cannot build yet JENKINS-60825
                // TODO figure out if we can build a PR who's head has been deleted as it should be possible
                return true;
            }
            // only match if the pull request is an origin pull request
            if (StringUtils.equalsIgnoreCase(
                    p.getBase().getRepo().getOwner().getUsername(),
                    p.getHead().getRepo().getOwner().getUsername())
                    && StringUtils.equalsIgnoreCase(
                    p.getBase().getRepo().getName(),
                    p.getHead().getRepo().getName())
                    && StringUtils.equals(p.getHead().getRef(), head.getName())) {
                return true;
            }
        }
    }
    return false;
}
 
Example #30
Source File: PendingChecksFilter.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isExcluded(SCMSourceRequest request, SCMHead head)
    throws IOException, InterruptedException {
  if (head instanceof ChangeSCMHead) {
    return !((GerritSCMSourceRequest) request)
        .getPatchsetWithPendingChecks()
        .containsKey(
            String.format(
                "%d/%d",
                ((ChangeSCMHead) head).getChangeNumber(),
                ((ChangeSCMHead) head).getPatchSetNumber()));
  }
  return true;
}