当前位置: 首页 > 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.jsqmd.com/news/63969/

相关文章:

  • 重练算法(代码随想录版) day32 - 动态规划part1
  • 2025年辽宁省工商注册机构排行:知名的工商注册品牌企业有哪
  • 什么平台可以修改发布文章的时间?网页的时间可以修改吗?
  • 2025 年 12 月二手压铸机厂家权威推荐榜:力劲/伊之密/锌合金/铝合金/热室/冷室压铸机买卖回收,精选耐用机型与高性价比之选
  • 2025玻璃钢拉挤型材源头厂家TOP5权威推荐:甄选高性价比
  • 2025年辽宁省口碑不错的工商注册公司推荐:服务不错的工商注
  • Obsidian的Bases数据库入门教程,使用数据库实现Todo待办管理系统
  • 2025年12月AI智搜GEO服务商权威推荐榜:福州/莆田/三明地区智能搜索推广与排名优化专家深度解析
  • Proxmox Datacenter Manager 1.0 发布 - 集中管理 Proxmox 虚拟化环境
  • 量化图像“概念相似性”的新方法
  • PbootCMS网站修改CSS样式后自动更新缓存
  • pbootcms模板获取指定栏目下面的所有单页内容(PbootCMS模板获取指定栏目下所有单页内容的方法)
  • 2025 年 12 月软件开发公司权威推荐榜:小程序开发/APP开发,匠心定制与创新技术融合的卓越服务商精选
  • Rocky Linux 9.7 发布 - RHEL 100% 完全兼容免费发行版
  • 2025年玻璃钢拉挤型材推荐厂商排名:正规定制厂家全解析
  • 基于融智学双重形式化的汉字汉语数学建模技巧
  • 2025 年 12 月饲料厂家权威推荐榜:牛羊猪禽反刍特种发酵饲料,东北辽宁地区实力品牌深度解析与选购指南
  • 2025年哈尔滨音乐艺考机构推荐,音乐艺考机构哪家口碑好、选
  • 2025年建筑资质办理服务排名与解析,看看哪家服务专业?
  • Cisco Secure Firewall 3100 Series FTD Software 7.7.11 - 思科 Firepower 威胁防御系统软件
  • Cisco Secure Firewall 4200 Series FTD Software 7.7.11 - 思科 Firepower 威胁防御系统软件
  • Cisco Secure Firewall 1200 Series FTD Software 10.0.0 ASA Software 9.24.1
  • DVWA 靶场全通关
  • STM32外设学习--TIM定时器--输入捕获---测频办法。
  • 2025 年 12 月张力器厂家权威推荐榜:伺服/磁力/张力控制器/张力计/放线架等精密设备源头实力解析
  • Cisco Secure Firewall Threat Defense Virtual 7.7.11 - 思科下一代防火墙虚拟设备 (FTDv)
  • Cisco Firepower 4100 Series FTD Software 7.7.11 - 思科 Firepower 威胁防御系统软件
  • PbootCMS邮件配置修改发件人信息
  • 2025年12月刀模厂家权威推荐榜:雕刻刀模/蚀刻刀模/激光刀模/圆压圆刀模/夹治具/精密模具,匠心工艺与高效定制解决方案深度解析
  • 2025年12月刀模厂家权威推荐榜:雕刻刀模/蚀刻刀模/激光刀模/圆压圆刀模/夹治具/精密模具,匠心工艺与高效定制解决方案深度解析