Git 操作

更新时间:
复制 MD 格式

云沙箱内置 Git 支持,可通过 E2B SDK 在沙箱环境中克隆仓库、管理提交和分支,适用于代码分析、自动修复和构建验证等场景。

适用场景

  • 代码分析:克隆仓库后,运行静态分析工具或 lint 检查。

  • 自动修复:AI Agent 克隆代码、修改文件、创建提交,实现自动化代码修复。

  • 构建验证:在隔离环境内执行构建脚本,验证代码是否可以正常编译。

前提条件

  • 已获取 E2B API Key:用于创建和管理沙箱实例。

  • 已安装 E2B SDK

    • Python:pip install e2b==2.26.0

    • TypeScript:npm i e2b@2.28.0

重要

访问私有仓库时,通过环境变量传递短期有效的 Personal Access Token,不要将 Token 硬编码到代码中。安全注意事项详见「安全建议」章节。克隆公共仓库(如 Gitee 上的公开项目)无需认证。

代码示例

根据使用的开发语言选择对应的示例。以下示例展示克隆仓库、查看状态、创建提交和管理分支的完整流程。

运行前,先在终端配置环境变量(将 e2b_xxxxx 替换为您的实际 API Key):

export E2B_API_URL="https://api.cn-beijing.e2b.fc.aliyuncs.com"
export E2B_DOMAIN="cn-beijing.e2b.fc.aliyuncs.com"
export E2B_API_KEY="e2b_xxxxx"

Python

from e2b import Sandbox

# E2B_API_KEY 为 E2B API 密钥,E2B_CONN_OPTS 为连接配置(如 region 等)
# 建议通过环境变量获取
# E2B_API_KEY = os.environ.get("E2B_API_KEY")
# E2B_CONN_OPTS = {"region": "us-west-1"}

sandbox = None
try:
    sandbox = Sandbox.create(api_key=E2B_API_KEY, timeout=300, **E2B_CONN_OPTS)
    repo_url = "https://gitee.com/aliyunfc/Hello-World.git"
    workdir = "/tmp/git-repo"

    # 克隆仓库(浅克隆)
    sandbox.git.clone(repo_url, workdir, depth=1)

    # 查看仓库状态
    status = sandbox.git.status(workdir)
    print(status.current_branch, status.is_clean)  # 例如:main True

    # 配置 Git 用户信息
    sandbox.git.configure_user("Sandbox Bot", "sandbox@example.com", path=workdir)

    # 创建新文件并提交
    sandbox.files.write(f"{workdir}/sandbox-note.txt", "created in sandbox\n")
    sandbox.git.add(workdir)
    sandbox.git.commit(workdir, "Add sandbox note")

    # 创建并切换分支
    sandbox.git.create_branch(workdir, "feature/sandbox-test")
    sandbox.git.checkout_branch(workdir, "feature/sandbox-test")
    print(sandbox.git.status(workdir).current_branch)
    # 输出:feature/sandbox-test
finally:
    if sandbox is not None:
        sandbox.kill()

TypeScript

import { Sandbox } from 'e2b';

// E2B_API_KEY 为 E2B API 密钥,E2B_CONN_OPTS 为连接配置(如 region 等)
// 建议通过环境变量获取
// const E2B_API_KEY = process.env.E2B_API_KEY;
// const E2B_CONN_OPTS = { region: 'us-west-1' };

const sandbox = await Sandbox.create({
  apiKey: E2B_API_KEY,
  timeout: 300,
  ...E2B_CONN_OPTS,
});

const repoUrl = 'https://gitee.com/aliyunfc/Hello-World.git';
const workdir = '/tmp/git-repo';

try {
  // 克隆仓库(浅克隆)
  await sandbox.git.clone(repoUrl, workdir, { depth: 1 });

  // 查看仓库状态
  const status = await sandbox.git.status(workdir);
  console.log(status.currentBranch, status.isClean);

  // 配置 Git 用户信息
  await sandbox.git.configureUser('Sandbox Bot', 'sandbox@example.com', { path: workdir });

  // 创建新文件并提交
  await sandbox.files.write(`${workdir}/sandbox-note.txt`, 'created in sandbox\n');
  await sandbox.git.add(workdir);
  await sandbox.git.commit(workdir, 'Add sandbox note');

  // 创建并切换分支
  await sandbox.git.createBranch(workdir, 'feature/sandbox-test');
  await sandbox.git.checkoutBranch(workdir, 'feature/sandbox-test');
  const newStatus = await sandbox.git.status(workdir);
  console.log(newStatus.currentBranch); // 输出:feature/sandbox-test
} finally {
  await sandbox.kill();
}

API 方法参考

Python SDK 使用位置参数或关键字参数,TypeScript SDK 使用 options 对象作为最后一个参数。TypeScript 方法名使用驼峰命名(如 createBranchcheckoutBranchconfigureUser)。

方法(Python)

方法(TypeScript)

说明

git.clone(url, path, depth=1)

git.clone(url, path, { depth })

克隆 Git 仓库到指定路径。depth 参数为可选整数,指定浅克隆深度。

git.status(path)

git.status(path)

查看仓库状态。Python 返回包含 current_branch(当前分支)和 is_clean(是否干净)的对象;TypeScript 返回包含 currentBranchisClean 的对象。

git.add(path)

git.add(path)

将工作目录中的变更添加到暂存区。

git.commit(path, message)

git.commit(path, message)

提交暂存区的变更。

git.create_branch(path, branch)

git.createBranch(path, branch)

创建新分支。

git.checkout_branch(path, branch)

git.checkoutBranch(path, branch)

切换到指定分支。

git.configure_user(name, email, path)

git.configureUser(name, email, { path })

配置 Git 用户名和邮箱。path 参数指定 Git 配置的作用范围:传入工作目录路径时仅对该仓库生效,省略时作为全局配置。

验证结果

示例代码中的 git.status() 返回值可用于验证 Git 操作是否成功:

  • is_clean(Python)或 isClean(TypeScript)为 True 时,表示工作目录无未提交变更。

  • current_branch(Python)或 currentBranch(TypeScript)返回当前所在分支名称,可用于确认分支切换是否生效。

安全建议

  • 使用短期 Token:访问私有仓库时,使用短期有效的 Personal Access Token,不要使用长期密码。

  • 不要将 Token 写入 Git 历史:避免将 Token 写入代码文件或提交信息,推荐通过环境变量传递。

  • 克隆公共仓库无需认证:公共仓库(如 Gitee 上的公开项目)可以直接克隆。