当前位置: 首页 > news >正文

部分克隆 + 稀疏检出

部分克隆 + 稀疏检出

一、需求背景

在git使用过程中,为了解决只对目标文件或者目标文件夹以及灵活组合的配置下去维护对应的文件需求,避免工作目录+.git仓库过大的问题

二、脚本实例

# ====== 配置区 =====================================
# 仓库地址
$RepoUrl = "git@github.com:fastapi/fastapi.git"
# 分支名(或主分支)
$Branch = "woshiyigemingzi"
# 想要拉取的文件夹(相对仓库根目录路径)
$TargetDirs = @("我是和git同级别\helloword"
)
# 想要拉取的"单个文件"(相对仓库根目录路径)
# 这个数组必须存在,即使为空
$TargetFiles = @()# 本地工作目录
$WorkDir = "D:\workspace\code\helloword"
# 浅克隆深度(只取最近5次提交)
$Depth = 5
# 私钥路径
$PrivateKey = "D:\xiatianxiatian\qiaoqiaoguoqu\liuxiaxiaomimi"
# ====== 执行区 =========================================# 简单的暂停函数
function Pause-Script {Write-Host "Press any key to continue..."$null = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}# ====== 优化删除确认部分 ======
# 清理工作区(优化后的确认提示)
if (Test-Path $WorkDir) {$items = Get-ChildItem $WorkDir -Recurse -ErrorAction SilentlyContinueif ($items.Count -gt 0) {Write-Host "=" * 60Write-Host "WORKING DIRECTORY WILL BE DELETED" -ForegroundColor RedWrite-Host "=" * 60Write-Host "Directory: $WorkDir" -ForegroundColor YellowWrite-Host "Contains: $($items.Count) items total" -ForegroundColor Yellow# 统计文件和目录数量$files = $items | Where-Object { -not $_.PSIsContainer }$dirs = $items | Where-Object { $_.PSIsContainer }Write-Host "  - Files: $($files.Count)" -ForegroundColor YellowWrite-Host "  - Directories: $($dirs.Count)" -ForegroundColor Yellow# 显示前5个项目if ($items.Count -gt 0) {Write-Host "Top items:" -ForegroundColor Yellow$items | Select-Object -First 5 | ForEach-Object {$type = if ($_.PSIsContainer) { "DIR" } else { "FILE" }$size = if (-not $_.PSIsContainer) { " ($([math]::Round($_.Length/1KB, 2)) KB)" } else { "" }Write-Host "  [$type] $($_.Name)$size" -ForegroundColor Yellow}if ($items.Count -gt 5) {Write-Host "  ... and $($items.Count - 5) more items" -ForegroundColor Yellow}}Write-Host "=" * 60Write-Host "This operation will PERMANENTLY delete the entire directory!" -ForegroundColor RedWrite-Host "=" * 60$confirm = Read-Host "Type 'DELETE' to confirm deletion, or press Enter to cancel"if ($confirm -ne "DELETE") {Write-Host "Operation cancelled by user."exit 1}}# 执行删除try {Remove-Item $WorkDir -Recurse -Force -ErrorAction StopWrite-Host "Directory removed: $WorkDir"}catch {Write-Host "Failed to remove directory: $_" -ForegroundColor RedWrite-Host "Possible reasons:" -ForegroundColor RedWrite-Host "1. Files are open in another program" -ForegroundColor RedWrite-Host "2. Insufficient permissions" -ForegroundColor RedWrite-Host "3. Path too long" -ForegroundColor RedPause-Scriptexit 1}
}# 创建新目录
New-Item -ItemType Directory -Path $WorkDir -Force | Out-Null
Set-Location $WorkDir
Write-Host "Created working directory: $WorkDir"# 配置SSH认证
$env:GIT_SSH_COMMAND = "ssh -i `"$PrivateKey`" -o IdentitiesOnly=yes -o StrictHostKeyChecking=no"
Write-Host "Using SSH key: $PrivateKey"# 执行部分克隆
Write-Host "Cloning repository (partial clone)..."
$cloneResult = git clone --filter=blob:none --no-checkout --depth $Depth -b $Branch $RepoUrl . 2>&1
if ($LASTEXITCODE -ne 0) {Write-Host "Clone failed. Ensure:" -ForegroundColor RedWrite-Host "1. Git version >= 2.19" -ForegroundColor RedWrite-Host "2. Server supports partial clone" -ForegroundColor RedWrite-Host "3. SSH key has repository access" -ForegroundColor RedWrite-Host "Error: $cloneResult" -ForegroundColor RedPause-Scriptexit 1
}# 配置稀疏检出
Write-Host "Configuring sparse checkout..."
git sparse-checkout init --no-cone 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {Write-Host "Sparse checkout init failed"Pause-Scriptexit 1
}# 构造稀疏检出的匹配路径
$includePaths = @()foreach ($dir in $TargetDirs) {if ([string]::IsNullOrWhiteSpace($dir)) { continue }$normalizedDir = $dir.Replace('\', '/').Trim('/')$includePaths += "$normalizedDir"$includePaths += "$normalizedDir/*"Write-Host "Include directory: $normalizedDir"
}foreach ($file in $TargetFiles) {if ([string]::IsNullOrWhiteSpace($file)) { continue }$normalizedFile = $file.Replace('\', '/').TrimStart('/')$includePaths += $normalizedFileWrite-Host "Include file: $normalizedFile"
}if ($includePaths.Count -eq 0) {Write-Host "No directories or files specified."Pause-Scriptexit 1
}# 设置稀疏检出规则
Write-Host "Setting sparse checkout paths..."
git sparse-checkout set @includePaths 2>&1 | Out-Null
if ($LASTEXITCODE -ne 0) {Write-Host "Failed to set sparse checkout paths"Pause-Scriptexit 1
}# 检出文件
Write-Host "Checking out files..."
$checkoutResult = git checkout $Branch 2>&1
if ($LASTEXITCODE -ne 0) {Write-Host "Checkout failed: $checkoutResult"Pause-Scriptexit 1
}# 验证结果
$success = $trueWrite-Host "`nVerifying directories..." -ForegroundColor Cyan
foreach ($dir in $TargetDirs) {if ([string]::IsNullOrWhiteSpace($dir)) { continue }$targetPath = Join-Path $WorkDir $dirif (Test-Path $targetPath -PathType Container) {$fileCount = (Get-ChildItem $targetPath -Recurse -File -ErrorAction SilentlyContinue).CountWrite-Host "[Success]$dir ($fileCount files)" -ForegroundColor Green}else {Write-Host "[FAIL]$dir (not found)" -ForegroundColor Red$success = $false}
}Write-Host "`nVerifying files..." -ForegroundColor Cyan
foreach ($file in $TargetFiles) {if ([string]::IsNullOrWhiteSpace($file)) { continue }$filePath = Join-Path $WorkDir $fileif (Test-Path $filePath -PathType Leaf) {Write-Host "[Success]$file" -ForegroundColor Green}else {Write-Host "[FAIL]$file (not found)" -ForegroundColor Red$success = $false}
}if (-not $success) {Write-Host "`nSome items were not found. Check paths are correct in repository." -ForegroundColor YellowWrite-Host "To view repository structure: git ls-tree -r HEAD --name-only" -ForegroundColor Yellow
}# 清理敏感信息
$env:GIT_SSH_COMMAND = $nullWrite-Host "`nDone." -ForegroundColor Green
exit 0

三、说明

1.对ps1脚本文件调用的时候可以外部使用批处理文件进行,可以跨版本兼容和路径可靠性等

2.配置对应的文件夹和文件的时候,是针对仓库根目录的

3.拉取后尽量不要非常规修改git规则,以免对于后续提交会有影响

4.关于密钥私钥和对应的,windows下属性权限修改

参考资料

http://www.zskr.cn/news/74520.html

相关文章:

  • 重练算法(代码随想录版) day32 - 动态规划part1
  • 2025 年 12 月二手压铸机厂家权威推荐榜:力劲/伊之密/锌合金/铝合金/热室/冷室压铸机买卖回收,精选耐用机型与高性价比之选
  • 2025玻璃钢拉挤型材源头厂家TOP5权威推荐:甄选高性价比
  • 2025年辽宁省口碑不错的工商注册公司推荐:服务不错的工商注
  • 量化图像“概念相似性”的新方法
  • DVWA 靶场全通关
  • Cisco Secure Firewall Threat Defense Virtual 7.7.11 - 思科下一代防火墙虚拟设备 (FTDv)
  • Cisco Firepower 4100 Series FTD Software 7.7.11 - 思科 Firepower 威胁防御系统软件
  • PbootCMS邮件配置修改发件人信息
  • 2025年12月刀模厂家权威推荐榜:雕刻刀模/蚀刻刀模/激光刀模/圆压圆刀模/夹治具/精密模具,匠心工艺与高效定制解决方案深度解析
  • 从资质、工艺到口碑严格筛选,2025年这份上海装修公司精选榜单请收好
  • PbootCMS模版制作:当天发布的文章显示红色的方法
  • 艺术漆品牌真实排名:5大优质品牌,助你轻松打造理想家居空间
  • PbootCMS登入失败:表单提交校验失败,请刷新后重试!
  • 2025权威推荐:十大艺术涂料品牌推广服务商,形象好服务佳
  • 权威揭秘!进口艺术涂料TOP5品牌,哪个才是投资价值NO.1?
  • 地域为根,协作成魂:HEBE 百年制表背后的汝拉社群智慧
  • 如何修改网站文件的发表日期(如何修改网站文章的发表时间)
  • PbootCms模板中怎么写PHP代码(PbootCMS 模板中嵌入 PHP 代码的方法与注意事项)
  • PbootCMS缩略图上传图片被截取变模糊的解决方法
  • 魔珐星云SDK实战测评:从0到1搭建会“思考+互动”的智能数字人客服应用
  • 2025年12月羽毛粉设备厂家推荐:市场主流品牌综合实力排行榜单深度解析
  • 2025年12月羽毛粉设备厂家推荐:全维度实力排行榜单与精准选购策略指南
  • 帝国cms 升级出现Multiple primary key defined错误
  • 2025年度凸轮式转子泵供应五大商推荐,凸轮式转子泵制造厂哪
  • 后台登录提示“登录失败:数据库目录写入权限不足!”
  • 2025转子泵企业TOP5权威推荐:拉法泵业与同行相比优势在
  • pbootcms模板时间格式调用方法详解(PbootCMS时间格式调用指南:列表页与详情页的灵活应用)
  • HTML动态表格
  • 喵喵喵序言