def call(Map args = [:]) {
    def branchName = args.branchName ?: env.BRANCH_NAME
    def baseCommit = args.baseCommit ?: env.GIT_PREVIOUS_SUCCESSFUL_COMMIT
    def mainBranch = args.mainBranch ?: 'master'

    def commitToCompare

    if (branchName == mainBranch) {
        // On the main branch, compare against the provided base commit, or the empty tree if base commit is not set (e.g. on the first build)
        commitToCompare = baseCommit ?: sh(script: "git hash-object -t tree /dev/null", returnStdout: true).trim()
    } else {
        // Otherwise, compare against the common ancestor of the current commit and the main branch
        commitToCompare = sh(script: "git merge-base HEAD origin/${mainBranch}", returnStdout: true).trim()
    }

    def gitDiff = sh(script: "git diff --name-only ${commitToCompare}..HEAD", returnStdout: true).trim()
    def changedFiles = gitDiff.tokenize('\n')

    echo "Detected modifications in the following files: ${changedFiles}"

    if (args.paths) {
        echo "Filtering for paths: ${args.paths}"
        return args.paths.findAll { path -> changedFiles.any { it.startsWith(path) } }
    }
    else {
        return changedFiles
    }
}
