为什么要这个功能

近期我滴好朋友们的Github账号被莫名其妙送上ban位,虽然笔者代码没有什么高科技含量,但毕竟也是一下一下码出来的,所以笔者配合AI写了个同步脚本。废话不多说上脚本!

脚本教程

前置工作

本脚本支持同步自己的仓库和starred仓库,使用前请确保你的电脑已经安装了git,并且能够正常的拉取自己仓库中的代码。

Token获取方式

  1. 跳转到 https://github.com/settings/tokens
  2. 点击 Generate new token
  3. 建议给全部权限,不然可能会出现同步不全的情况
  4. 令牌失效时间拉满,防止经常维护

powershell脚本


# 你的GitHub Personal Access Token
$token = "<your_token>"

# 设置请求头部
$headers = @{
    "Authorization" = "token $token"
}

# -----------------------------------------------------------------
# 同步自己的仓库
# -----------------------------------------------------------------
Write-Host "开始同步自己的仓库"
# 初始化仓库列表和页面
$repoList = @()
$page = 1
$perPage = 100  # 每页请求的仓库数量,最大为100

# 请求GitHub API获取仓库列表,处理分页
do {
    $apiUrl = "https://api.github.com/user/repos?visibility=all&page=$page&per_page=$perPage"
    $response = Invoke-RestMethod -Uri $apiUrl -Method Get -Headers $headers
    $repoList += $response
    $page++
} while ($response.Length -eq $perPage)

# 确保当前工作目录是你想要克隆仓库的地方
$cloneDirectory = "F:\Github本地缓存"
Set-Location -Path $cloneDirectory

# 遍历仓库列表并克隆每个仓库
foreach ($repo in $repoList) {
    # 获取仓库的克隆URL
    $cloneUrl = $repo.clone_url
    # 仓库名称,用于创建本地目录
    $repoName = $repo.name

    # 如果本地已经存在该仓库目录,则跳过
    if (Test-Path $repoName) {
        Write-Host "Repository $repoName already exists. Updating..."
        Push-Location -Path $repoName
        & git pull
        Pop-Location
    } else {
        # 使用git clone命令克隆仓库
        Write-Host "Cloning $repoName..."
        & git clone $cloneUrl
    }
}

# -----------------------------------------------------------------
# 同步starred仓库
# -----------------------------------------------------------------
Write-Host "开始同步starred仓库"
# 文件路径
$filePath = "starred.txt"

# 如果文件已存在,则删除
if (Test-Path $filePath) {
    Remove-Item $filePath
}

# 初始化变量
$starredRepos = @()
$page = 1
$perPage = 100  # 每页请求的仓库数量,最大为100

# 循环获取所有star过的仓库
do {
    $response = Invoke-RestMethod -Uri "https://api.github.com/user/starred?page=$page&per_page=$perPage" -Method Get -Headers $headers
    $starredRepos += $response
    $page++
    Start-Sleep -Seconds 2  # 简单的速率限制处理
} while ($response.Length -eq $perPage)

# 输出star过的仓库列表到文件
foreach ($repo in $starredRepos) {
    Write-Host $repo.html_url
    $repo.html_url | Out-File -FilePath $filePath -Append -Encoding utf8
}

建议

可以在Windows计划任务中设置开机自启,这样就可以实现开机自动同步了。