Search in sources :

Example 26 with MultiBranchProject

use of jenkins.branch.MultiBranchProject in project blueocean-plugin by jenkinsci.

the class PipelineBranchRunStatePreloader method getFetchData.

@Override
protected FetchData getFetchData(@NonNull BlueUrlTokenizer blueUrl) {
    // 
    if (!blueUrl.hasPart(BlueUrlTokenizer.UrlPart.BRANCH) || !blueUrl.hasPart(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_ID)) {
        // Not interested in it
        return null;
    }
    Jenkins jenkins = Jenkins.get();
    String pipelineFullName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE);
    String branchName = blueUrl.getPart(BlueUrlTokenizer.UrlPart.BRANCH);
    String runId = blueUrl.getPart(BlueUrlTokenizer.UrlPart.PIPELINE_RUN_DETAIL_ID);
    Item pipelineJobItem = jenkins.getItemByFullName(pipelineFullName);
    if (pipelineJobItem instanceof MultiBranchProject) {
        try {
            MultiBranchProject pipelineMBP = (MultiBranchProject) pipelineJobItem;
            Job pipelineBranchJob = pipelineMBP.getItem(branchName);
            if (pipelineBranchJob != null) {
                Run run = pipelineBranchJob.getBuild(runId);
                if (run != null) {
                    BlueRun blueRun = BlueRunFactory.getRun(run, BluePipelineFactory.resolve(pipelineBranchJob));
                    if (blueRun != null) {
                        try {
                            return new FetchData(blueRun.getLink().getHref(), Export.toJson(blueRun));
                        } catch (IOException e) {
                            LOGGER.log(Level.FINE, String.format("Unable to preload run for pipeline '%s'. Run serialization error.", run.getUrl()), e);
                            return null;
                        }
                    } else {
                        LOGGER.log(Level.FINE, String.format("Unable to find run %s on branch named %s on pipeline named '%s'.", runId, branchName, pipelineFullName));
                        return null;
                    }
                }
            } else {
                LOGGER.log(Level.FINE, String.format("Unable to find branch named %s on pipeline named '%s'.", branchName, pipelineFullName));
                return null;
            }
        } catch (Exception e) {
            LOGGER.log(Level.FINE, String.format("Unable to find run from pipeline named '%s'.", pipelineFullName), e);
            return null;
        }
    } else {
        LOGGER.log(Level.FINE, String.format("Unable to find pipeline named '%s'.", pipelineFullName));
        return null;
    }
    // Don't preload any data on the page.
    return null;
}
Also used : Jenkins(jenkins.model.Jenkins) Item(hudson.model.Item) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) MultiBranchProject(jenkins.branch.MultiBranchProject) BlueRun(io.jenkins.blueocean.rest.model.BlueRun) Run(hudson.model.Run) IOException(java.io.IOException) Job(hudson.model.Job) IOException(java.io.IOException)

Example 27 with MultiBranchProject

use of jenkins.branch.MultiBranchProject in project blueocean-plugin by jenkinsci.

the class ScriptedPipelineAnalyticsCheck method apply.

@Override
public Boolean apply(Item item) {
    if (!(item instanceof MultiBranchProject)) {
        return false;
    }
    MultiBranchProject project = (MultiBranchProject) item;
    Job resolve = PrimaryBranch.resolve(project);
    return resolve != null && resolve.getAction(DeclarativeJobAction.class) == null;
}
Also used : MultiBranchProject(jenkins.branch.MultiBranchProject) Job(hudson.model.Job)

Example 28 with MultiBranchProject

use of jenkins.branch.MultiBranchProject in project blueocean-plugin by jenkinsci.

the class OrganizationFolderTest method testOrgFolderPipeline.

@Test
@WithoutJenkins
public void testOrgFolderPipeline() throws IOException {
    AvatarMetadataAction avatarMetadataAction = mock(AvatarMetadataAction.class);
    when(orgFolder.getAction(AvatarMetadataAction.class)).thenReturn(avatarMetadataAction);
    BlueOrganizationFolder organizationFolder = new OrganizationFolderPipelineImpl(organization, orgFolder, organization.getLink().rel("/pipelines/")) {
    };
    assertEquals(organizationFolder.getName(), organizationFolder.getName());
    assertEquals(organizationFolder.getDisplayName(), organizationFolder.getDisplayName());
    assertEquals(organization.getName(), organizationFolder.getOrganizationName());
    assertNotNull(organizationFolder.getIcon());
    MultiBranchProject multiBranchProject = PowerMockito.mock(MultiBranchProject.class);
    when(orgFolder.getItem("repo1")).thenReturn(multiBranchProject);
    PowerMockito.when(OrganizationFactory.getInstance().getContainingOrg((ItemGroup) multiBranchProject)).thenReturn(organization);
    PowerMockito.when(multiBranchProject.getFullName()).thenReturn("p1");
    PowerMockito.when(multiBranchProject.getName()).thenReturn("p1");
    MultiBranchPipelineContainerImpl multiBranchPipelineContainer = new MultiBranchPipelineContainerImpl(organization, orgFolder, organizationFolder);
    assertEquals(multiBranchProject.getName(), multiBranchPipelineContainer.get("repo1").getName());
    when(orgFolder.getItems()).thenReturn(Collections.singletonList(multiBranchProject));
    assertNotNull(organizationFolder.getPipelineFolderNames());
}
Also used : AvatarMetadataAction(jenkins.scm.api.metadata.AvatarMetadataAction) BlueOrganizationFolder(io.jenkins.blueocean.rest.model.BlueOrganizationFolder) MultiBranchProject(jenkins.branch.MultiBranchProject) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) Test(org.junit.Test) WithoutJenkins(org.jvnet.hudson.test.WithoutJenkins)

Example 29 with MultiBranchProject

use of jenkins.branch.MultiBranchProject in project blueocean-plugin by jenkinsci.

the class AbstractMultiBranchCreateRequest method create.

@Override
@SuppressWarnings("unchecked")
public BluePipeline create(@Nonnull BlueOrganization organization, @Nonnull Reachable parent) throws IOException {
    validateInternal(getName(), scmConfig, organization);
    MultiBranchProject project = createMultiBranchProject(organization);
    assignCredentialToProject(scmConfig, project);
    SCMSource source = createSource(project, scmConfig).withId("blueocean");
    project.setSourcesList(Collections.singletonList(new BranchSource(source)));
    source.afterSave();
    project.save();
    final boolean hasJenkinsfile = repoHasJenkinsFile(source);
    if (!hasJenkinsfile) {
        sendMultibranchIndexingCompleteEvent(project, 5);
        AbstractScmSourceEvent scmSourceEvent = getScmSourceEvent(project, source);
        if (scmSourceEvent != null) {
            SCMSourceEvent.fireNow(scmSourceEvent);
        }
    } else {
        project.scheduleBuild(new Cause.UserIdCause());
    }
    return BluePipelineFactory.getPipelineInstance(project, OrganizationFactory.getInstance().getContainingOrg(project.getItemGroup()));
}
Also used : Cause(hudson.model.Cause) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) MultiBranchProject(jenkins.branch.MultiBranchProject) SCMSource(jenkins.scm.api.SCMSource) BranchSource(jenkins.branch.BranchSource)

Example 30 with MultiBranchProject

use of jenkins.branch.MultiBranchProject in project blueocean-plugin by jenkinsci.

the class GithubScmContentProvider method getContent.

@Override
public Object getContent(@Nonnull StaplerRequest request, @Nonnull Item item) {
    String path = StringUtils.defaultIfEmpty(request.getParameter("path"), null);
    String type = StringUtils.defaultIfEmpty(request.getParameter("type"), null);
    String repo = StringUtils.defaultIfEmpty(request.getParameter("repo"), null);
    String branch = StringUtils.defaultIfEmpty(request.getParameter("branch"), null);
    List<ErrorMessage.Error> errors = new ArrayList<>();
    if (!(item instanceof MultiBranchProject) && repo == null) {
        errors.add(new ErrorMessage.Error("repo", ErrorMessage.Error.ErrorCodes.MISSING.toString(), String.format("repo and branch parameters are required because pipeline %s is not a multi-branch project ", item.getFullName())));
    }
    if (type != null && !type.equals("file")) {
        errors.add(new ErrorMessage.Error("file", ErrorMessage.Error.ErrorCodes.INVALID.toString(), String.format("type %s not supported. Only 'file' type supported.", type)));
    }
    if (path == null) {
        errors.add(new ErrorMessage.Error("path", ErrorMessage.Error.ErrorCodes.MISSING.toString(), "path is required query parameter"));
    }
    if (!errors.isEmpty()) {
        throw new ServiceException.BadRequestExpception(new ErrorMessage(400, "Failed to load scm file").addAll(errors));
    }
    ScmParamsFromItem scmParamsFromItem = new ScmParamsFromItem(item);
    //if no repo param, then see if its there in given Item.
    if (repo == null && scmParamsFromItem.repo == null) {
        throw new ServiceException.BadRequestExpception("github repo could not be determine from pipeline: " + item.getFullName());
    }
    // If both, repo param and repo in pipeline scm configuration present, they better match
    if (repo != null && scmParamsFromItem.repo != null && !repo.equals(scmParamsFromItem.repo)) {
        throw new ServiceException.BadRequestExpception(String.format("repo parameter %s doesn't match with repo in pipeline %s github configuration repo: %s ", repo, item.getFullName(), scmParamsFromItem.repo));
    }
    if (repo == null) {
        repo = scmParamsFromItem.repo;
    }
    String url = String.format("%s/repos/%s/%s/contents/%s", scmParamsFromItem.apiUrl, scmParamsFromItem.owner, repo, path);
    if (branch != null) {
        //if branch is present fetch this file from branch
        url += "?ref=" + branch;
    }
    try {
        Map ghContent = HttpRequest.get(url).withAuthorization("token " + scmParamsFromItem.accessToken).to(Map.class);
        if (ghContent == null) {
            throw new ServiceException.UnexpectedErrorException("Failed to load file: " + path);
        }
        return new GithubFile(new GithubContent.Builder().sha((String) ghContent.get("sha")).name((String) ghContent.get("name")).repo(repo).owner(scmParamsFromItem.owner).path(path).base64Data((String) ghContent.get("content")).build());
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException(String.format("Failed to load file %s: %s", path, e.getMessage()), e);
    }
}
Also used : ArrayList(java.util.ArrayList) IOException(java.io.IOException) ServiceException(io.jenkins.blueocean.commons.ServiceException) MultiBranchProject(jenkins.branch.MultiBranchProject) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage) Map(java.util.Map)

Aggregations

MultiBranchProject (jenkins.branch.MultiBranchProject)52 Test (org.junit.Test)36 StaplerRequest (org.kohsuke.stapler.StaplerRequest)28 GitContent (io.jenkins.blueocean.rest.impl.pipeline.scm.GitContent)18 BufferedReader (java.io.BufferedReader)16 StringReader (java.io.StringReader)16 JSONObject (net.sf.json.JSONObject)16 ServiceException (io.jenkins.blueocean.commons.ServiceException)14 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)14 User (hudson.model.User)13 Mailer (hudson.tasks.Mailer)12 BitbucketScmSaveFileRequest (io.jenkins.blueocean.blueocean_bitbucket_pipeline.BitbucketScmSaveFileRequest)6 Job (hudson.model.Job)5 DescribableList (hudson.util.DescribableList)5 ScmFile (io.jenkins.blueocean.rest.impl.pipeline.scm.ScmFile)5 Map (java.util.Map)5 GitSCMSource (jenkins.plugins.git.GitSCMSource)5 GitHubSCMSource (org.jenkinsci.plugins.github_branch_source.GitHubSCMSource)5 BitbucketSCMSource (com.cloudbees.jenkins.plugins.bitbucket.BitbucketSCMSource)4 Item (hudson.model.Item)4