You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Jenkins Pipeline拉取Git远程仓库指定文件夹?

Jenkins Pipeline 拉取Git仓库指定文件夹的方法

方法一:Git稀疏检出(保留Git历史)

这是最常用的方案,利用Git的稀疏检出特性,只拉取你需要的文件夹:

pipeline {
    agent any
    stages {
        stage('拉取指定文件夹') {
            steps {
                script {
                    // 初始化本地仓库
                    sh 'git init'
                    // 配置远程仓库(结合Jenkins凭证)
                    withCredentials([usernamePassword(credentialsId: 'abc', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PWD')]) {
                        sh 'git remote add origin https://${GIT_USER}:${GIT_PWD}@github-abc.com/platform-org/abc.git'
                    }
                    // 开启稀疏检出功能
                    sh 'git config core.sparseCheckout true'
                    // 写入要拉取的文件夹路径(替换成你需要的路径,末尾加斜杠表示文件夹)
                    sh 'echo "target-folder-path/" >> .git/info/sparse-checkout'
                    // 拉取指定分支
                    sh 'git pull origin abc'
                }
            }
        }
    }
}

注意:路径要准确,比如你要拉取src/utils文件夹,就写echo "src/utils/" >> .git/info/sparse-checkout,避免匹配到同名文件。

方法二:Git Archive直接下载(无Git历史,更轻量)

如果不需要保留Git版本历史,只想拿到文件内容,可以用Git的archive功能直接打包下载指定文件夹:

pipeline {
    agent any
    stages {
        stage('下载指定文件夹内容') {
            steps {
                script {
                    withCredentials([usernamePassword(credentialsId: 'abc', usernameVariable: 'GIT_USER', passwordVariable: 'GIT_PWD')]) {
                        // 从远程仓库拉取指定分支下的目标文件夹,直接解压到当前目录
                        sh 'git archive --remote=https://${GIT_USER}:${GIT_PWD}@github-abc.com/platform-org/abc.git abc:target-folder-path/ | tar -x'
                    }
                }
            }
        }
    }
}

这种方式不需要初始化本地仓库,速度更快,但不会生成.git目录,适合只需要文件内容的场景。

关键注意点

  • 凭证一定要用Jenkins的withCredentials处理,绝对不能硬编码账号密码。
  • 测试路径时,可以先在本地Git环境执行相关命令,确认路径能正确匹配目标文件夹。
  • 稀疏检出需要Git 1.7.0及以上版本,现在大部分环境都满足这个要求。

内容的提问来源于stack exchange,提问作者user312307

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 02:12:37