# 使用 GitHub Actions 管理 Spaces

您可以使用官方的 [`huggingface/hub-sync`](https://github.com/marketplace/actions/sync-github-to-hugging-face-hub) GitHub Action 来保持您的 Space 与 GitHub 仓库同步。

`hub-sync` 同样适用于模型和数据集。有关一般用法，请参阅 [GitHub Actions](./repositories-github-actions)。

## 设置

1. 创建一个名为 `HF_TOKEN` 的 [GitHub secret](https://docs.github.com/en/actions/security-guides/encrypted-secrets#creating-encrypted-secrets-for-an-environment)，其中包含 Hugging Face [访问令牌](https://huggingface.co/settings/tokens)。
2. 在您的仓库中添加一个工作流文件（例如 `.github/workflows/sync-to-hub.yml`）：

```yaml
name: Sync to Hugging Face Hub
on:
  push:
    branches: [main]

jobs:
  sync:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6
      - uses: huggingface/hub-sync@v0.3.0
        with:
          github_repo_id: ${{ github.repository }}
          huggingface_repo_id: username/my-space
          hf_token: ${{ secrets.HF_TOKEN }}
```

您可以使用 `space_sdk` 配置 Space SDK（默认为 `gradio`）。请参阅 [所有参数](./repositories-github-actions#parameters)。

## 工作原理

该操作使用 `hf` CLI（`hf repos create` + `hf upload`）将您的文件镜像到 Hub。它并非 git 到 git 的同步——它上传文件内容，并自动排除 `.github/` 和 `.git/` 目录。从您的 GitHub 仓库中删除的文件也会从 Hub 中删除。

对于更复杂的工作流（例如构建步骤、自定义逻辑），您可以直接在您的工作流中安装并使用 [`hf` CLI](https://huggingface.co/docs/huggingface_hub/en/guides/cli)。

## 文件大小注意事项

该操作使用 `hf upload` 上传文件内容，因此您无需为 Hub 配置 Git LFS 或 git-xet：大文件会自动存储在 Xet 中。如果您的 GitHub 仓库使用 Git LFS 存储文件（GitHub 要求对超过 100MB 的文件使用 Git LFS），请在 `actions/checkout` 步骤中设置 `lfs: true`，以便该操作上传实际文件而非 LFS 指针。

## 替代方案：手动 git push

如果您更喜欢直接的 git-to-git 同步而非文件镜像，您可以直接推送到您的 Space 的 git 远程仓库。使用 git push 时，大于 10MB 的文件必须通过 [git-xet](./xet/using-xet-storage#git-xet)（推荐）或 Git LFS 进行跟踪：

```yaml
name: Sync to Hugging Face hub
on:
  push:
    branches: [main]
  workflow_dispatch:

jobs:
  sync-to-hub:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
        with:
          fetch-depth: 0
          lfs: true
      - name: Push to hub
        env:
          HF_TOKEN: ${{ secrets.HF_TOKEN }}
        run: git push https://HF_USERNAME:$HF_TOKEN@huggingface.co/spaces/HF_USERNAME/SPACE_NAME main
```

将 `HF_USERNAME` 替换为您的用户名，将 `SPACE_NAME` 替换为您的 Space 名称。

