简体   繁体   中英

How do I clone into a potentially non-empty directory via Jenkinsfile?

I've got a simple Jenkinsfile that clones a Git repo down into one of a number of agents. These agents may not have the repo already, or it may.

Currently here's the Jenkinsfile:

stage("Clone Postman Collection") {
       steps {
           sh "git clone ssh://git@bitbucket.company.com/lol/postman-scripts.git"
       }
   }

Currently this works the first time the repo is cloned, but if the folder isn't empty it causes the job to fail with a pretty understandable error: fatal: destination path 'postman-scripts' already exists and is not an empty directory.

The reason I'm asking this question instead of using one of the other answers from the multitudes of other Stack Overflow questions is that I can't be certain if the Agent this is running on actually has the repo already cloned or not, so there needs to be some sort of IF clause or something.

I'm wondering if there is an elegant way to handle this in the Jenkinsfile. For example, can I:

Force the clone to overwrite files it finds?

Cause the error to be non-fatal?

Catch the specific error and delete, retry?

Force the clone to overwrite files it finds?

The logical conclusion of this line of thought is to delete the workspace or clone every time. There's often good reasons to do this anyway, one of the more compelling of which is "your build process is going to create artifacts that are not going to be in the repo".

But if the repo is big enough I suppose you might really want the cache, so

Cause the error to be non-fatal? Catch the specific error and delete, retry?

You're already running shell script, so you could use shell constructs to add some logic between the result of git clone and the next steps. It seems straight forward to use the destination directory as the flag for whether you clone or fetch / checkout - if the directory exists, clone, otherwise, checkout.

But I recommend against this. Your repos is only going to take a few seconds to clone in your current setup, I'd wager, and your time is worth way more than jenkins's. Delete the repo on every checkout and you lose very little and gain a much simpler runtime consistency guarantee.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM