How to cleanup pipeline before checkout of repository in Jenkinsfile

20k Views Asked by At

I want to make a clean before checkout operation which is described in Jenkins git plugin documentation:

Clean before checkout Clean the workspace before every checkout by deleting all untracked files and directories, including those which are specified in .gitignore. ...

But how can add this option to default checkout step which is doing as first step?

I feel that it should be an option extended by git plugin which can be included to options block of Jenkinsfile as described in docs:

The options directive allows configuring Pipeline-specific options from within the Pipeline itself. Pipeline provides a number of these options, such as buildDiscarder, but they may also be provided by plugins...

But how one should know which options and their names this plugin offer? Didn't find it in docs, also i may be wrong that clean before checkout should be placed in options block of Jenkinsfile.

Please help.

2

There are 2 best solutions below

6
On BEST ANSWER

As already mentioned in the comments the way to go is to use skipDefaultCheckout() (Source) in your pipeline-options to not checkout the repository if the pipeline starts.

skipDefaultCheckout

Skip checking out code from source control by default in the agent directive.

To get the repository manually you can use checkout scm (Source)

pipeline {
    agent any
    options {
        skipDefaultCheckout()
    }
    stages {
        stage('Example') {
            steps {
                // Cleanup before starting the stage
                // deleteDir() / cleanWs() or your own way of cleaning up

                // Checkout the repository
                checkout scm 

                // do whatever you like
            }
        }
    }
}
0
On

One of my jobs I used this:

    def gitCheckoutExtensions = []
    if (cleanWorkspace) {
        println '>>> workspace will be cleaned and retrieved all codes again..!'
        gitCheckoutExtensions.push([$class: 'CleanBeforeCheckout'])
    }

    gitCheckoutExtensions.push([$class: 'LocalBranch', localBranch: srcBranch])

    checkout([
        $class: 'GitSCM',
        branches: [[name: "*/${srcBranch}"]],
        doGenerateSubmoduleConfigurations: false,
        extensions: gitCheckoutExtensions,
        submoduleCfg: [],
        userRemoteConfigs: [
            [
                credentialsId: credId,
                url: url
            ]
        ]
    ])

Longer form of stage is:

@Library('gui_multi_repo@master')_


pipeline {
    agent {
        docker {
            label "DockerAgent"
            image "node:14.21.3"
        }
    }
    
    parameters {
        string(trim: true, name: 'REPO_URL', defaultValue: "http://user.name@server_domain_or_ipAddres", description: 'Repo adresi')
        string(trim: true, name: 'REPO_CRED_ID', defaultValue: RepoCredId, description: 'GIT Repo bağlantısı olacaksa CRED_ID kullanılacak')
        string(trim: true, name: 'REPO_SOURCE_BRANCH_NAME', defaultValue: 'refs/remotes/origin/developer', description: 'Kodları hangi BRANCH üstünden çekeceğini belirtiyoruz')
        string(trim: true, name: 'REPO_TARGET_BRANCH_NAME', defaultValue: 'refs/remotes/origin/master', description: 'Push ile kodun gönderileceği branch')
    }
    
    stages {
        stage("Git İşlemleri") {
            steps {
                script {
                    def credId="${params.REPO_CRED_ID}"
                    def repoUrl="${params.REPO_URL}"
                    def srcBranch="${params.REPO_SOURCE_BRANCH_NAME}"
                    def targetBranch="${params.REPO_TARGET_BRANCH_NAME}"
                    def tagName="cem13"
                    def tagMessage="naber13"
                    
                    echo "credId: $credId"
                    echo "repoUrl: $repoUrl"
                    echo "srcBranch: $srcBranch"
                    echo "targetBranch: $targetBranch"
                    echo "tagName: $tagName"
                    echo "tagMessage: $tagMessage"
                    
                    /** 
                     * CredId ile tanımlanan Git kimlik bilgilerini alır
                     * Artık GIT_USERNAME ve GIT_PASSWORD değişkenleri içinde, verilen credId'nin
                     * kullanıcı adı ve şifresi olacak ve tüm çıktılarda *** ile gizlenecek
                     */
                    
                    checkout([$class: 'GitSCM',
                        branches: [[name: "${srcBranch}"]],
                        extensions: [
                            [$class: 'CleanBeforeCheckout']
                        ],
                        userRemoteConfigs: [[
                            // credId veya gitCredentials.id ile tanımlanan kullanıcı bilgilerinin id değeri verilir
                            credentialsId: "${credId}", 
                            url: "${repoUrl}"
                        ]]
                    ])
                    
                    withCredentials([usernamePassword(credentialsId: "${credId}", passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
                        
                        def gitUrlWithCredentials = repoUrl.replaceFirst(/(http[s]:\/\/).*@(.*)/,"\$1${GIT_USERNAME}:${GIT_PASSWORD}@\$2")
                        echo "gitUrlWithCredentials: ${gitUrlWithCredentials}"
                        
                        sh """
                            #!/bin/sh -e
                            
                            git config --global credential.helper cache
                            git config --global push.default simple
                            
                            # Kullanıcı e-posta adresini ayarlar
                            git config --global user.email "${GIT_USERNAME}@domain.com"
                            
                            # Kullanıcı adını ayarlar
                            git config --global user.name "${GIT_USERNAME.replace('.', ' '}" 
                            
                            # SSL Doğrulama yapmaz
                            git config --global http.sslverify 'false'
                            
                            # Git URL'sinde parolayı kullanarak güncellenmiş URL'yi oluşturun
                            git tag -a ${tagName} -m '${tagMessage}'
                         
                            git push ${gitUrlWithCredentials} ${tagName}
                            
                            git checkout ${targetBranch}
                            
                            # sonra birleştireceğimiz 'kaynak dalını' isteyelim
                            git merge ${srcBranch}
                            
                            git push ${gitUrlWithCredentials} ${targetBranch}
                        """
                    }
                }
            }
        }
        
    }
    
    post { 
        success{
            echo "** Süreç başarıyla tamamlandı"
        }
        failure {
            echo "** Süreç hatalı tamamlandı"
        }
        cleanup{
            echo "** Süreç tamamlandı cleanup zamanı"
        }
        always { 
            echo "** Süreç günahıyla sevabıyla tamamlandı"
        }
    }

}