8

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.

Michael Kemmerzell
  • 4,802
  • 4
  • 27
  • 43
Mikhail Politaev
  • 534
  • 2
  • 7
  • 24
  • 3
    You could `skipDefaultCheckout(true)` and then do an explicit `checkout` to specify options. – zett42 Mar 31 '20 at 21:05

2 Answers2

11

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
            }
        }
    }
}
Michael Kemmerzell
  • 4,802
  • 4
  • 27
  • 43
  • Thanks Michael and zett42! Works! But it's also need specify git url repo in checkout command to make a clean checkout. It can checkout without repo url, but making clean only when repo url is specified. I am looking into var GIT_URL which git plugin has but see error: "No such property: GIT_URL". Is there any other way retrieve git url which specified in Jenkins GUI at job config page? – Mikhail Politaev Apr 01 '20 at 11:20
  • @pleyades Not following. You say it works ... but then imply it doesn't. What works? And what doesn't work? What makes you think you need the URL? I use 'checkout scm' and it uses the URL (and all the other settings) configured in the Pipeline section of the pipeline job config. – steve Apr 02 '21 at 06:39
  • @steve maybe not clear comment, yes. It works in that way as suggested - skip default checkout and add your user defined checkout. However what is not worked - is GIT_URL variable, which i assumed, should be available for your custom checkout step. I have defined GIT_URL in environment section. However if default checkout step is not skipped - GIT_URL is visible, even if not specified in environment section. Any questions? – Mikhail Politaev Apr 26 '21 at 06:01
  • According to this answer (https://stackoverflow.com/a/54020444/104085) we shouldn't use deleteDir command in docker image and cleaWs command before building process has not been done. – uzay95 May 27 '23 at 23:41
  • If you use ``skipDefaultCheckout()``, all of environment variable of git plugins don't completed. – Amirhossein Taheri Aug 21 '23 at 08:37
1

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ı"
        }
    }

}
uzay95
  • 16,052
  • 31
  • 116
  • 182