Clean builds with Multibranch Workflow

I run into the same problem and here is my workaround. I created a new scm object for the checkout and extended the extensions with the CleanBeforeCheckout. But i kept the other configurations like branches and userRemoteConfigs.

checkout([
    $class: 'GitSCM',
    branches: scm.branches,
    extensions: scm.extensions + [[$class: 'CleanBeforeCheckout']],
    userRemoteConfigs: scm.userRemoteConfigs
])

It's still not perfect because you have to create a new object :(


workflow behavior

Behaviors can be added when configuring the source. clean before checkout, clean after checkout and Wipe out repository and force clone. This removes the need to add logic to the declarative / scripted pipelines.


First, you can not assume that a workflow job has a workspace as it was for freestyle jobs. Actually, a workflow job can use more than one workspace (one for each node or ws block).

Said that, what I'm going to propose is a kind of hacky: modify the scm object before checkout to set up a CleanCheckout extension (you will have to approve some calls there).

import hudson.plugins.git.extensions.impl.CleanCheckout
scm.extensions.replace(new CleanCheckout())
checkout scm

But I'd prefer Christopher Orr's proposal, use a shell step after checkout (sh 'git clean -fdx').


I'm not sure if this answers the original question or not (I couldn't tell if the intention was to leave some files in the workspace) but why not just remove the workspace first, this would allow a clean checkout:

stage ('Clean') {
    deleteDir()
}

stage ('Checkout') {
    checkout scm 
}