Skip to content
This repository has been archived by the owner on Mar 14, 2024. It is now read-only.

Conditional generation of Codestream stages and tasks

glechev edited this page Jun 30, 2021 · 1 revision

Conditional generation of Codestream stages and tasks

Occasionally you can have similar pipeline that differ just a bit by a stage or a task. For example, this is often the case when you're creating pipelines for multiple branches of a project - you may want to add a task that's present only in one of the branch pipelines and not for the rest. This is achieved by using Optional pattern with NoOpTask or NoOpStage respectively.

branches = ["master", "feature-a", "feature-b"]

return branches.stream().map(branch ->
        Pipeline.builder()
                .name("$branch-test")
                .stages([
                        Stage.builder()
                                .name("Build")
                                .tasks([
                                        // Build tasks
                                ])
                                .build(),
                        Optional.of(Stage.builder()
                                .name("Test")
                                .tasks([
                                        JenkinsTask.builder()
                                                .name("Unit")
                                                .job("unit-tests")
                                                .build(),
                                        Optional.of((Task) JenkinsTask.builder()
                                                .name("Integration")
                                                .job("integration-tests")
                                                .build()).filter(t -> branch == "master").orElse(NoOpTask.INSTANCE)
                                ])
                                .build()).filter(s -> branch != "feature-b").orElse(NoOpStage.INSTANCE)
                ])
                .build()).collect(Collectors.toList())

In the above example 3 pipelines will be generated - master-test, feature-a-test and feature-b-test. However, the Integration task will be added only to the master-test pipeline, where for feature-b-test the whole Test stage will be missing.

To break it down, the pattern Optional.of(something).filter(predicate).orElse(somethingElse) will return something if the predicate is true or else somethingElse. NoOpTask and NoOpStage are no-operation entities - they will be removed during generation. That way you can define optional task and stages.