Changeset in if Block

I have a requriement where I need to initialize few variables based on the folders changed in git repo .
For example, in git repository, if prod/component1/* path is changed, I need to set env as prod and component as component1. There are other paths of this format. Can I use changeset with if block and have it one stage instead of having it in multiple stages by using when block?

Hello @ShadowKing782k and welcome to this community. :wave:

I think you can use the changeset function in a script block within a single stage to check the paths of the changed files and set environment variables accordingly.

Here’s an untested example:

pipeline {
    agent any

    stages {
        stage('Set Variables Based on Changed Paths') {
            steps {
                script {
                    def env
                    def component

                    for (change in currentBuild.changeSets) {
                        for (path in change.paths) {
                            if (path =~ /^prod\/component1\//) {
                                env = 'prod'
                                component = 'component1'
                            // Add more if conditions here for other paths

                    if (env && component) {
                        echo "Environment: ${env}, Component: ${component}"
                        // Set the environment variables
                        env.ENV = env
                        env.COMPONENT = component
                    } else {
                        echo "No matching paths found in the changeset"

Here, the changeset function is used to get the list of changes in the current build. For each change, the paths of the changed files are checked against a regular expression.
If a path matches the regular expression, the environment variables ENV and COMPONENT are set accordingly.