# 定义模板
<subtitle>如何创建自己的模板</subtitle>

## 方法链

所有模板方法都返回模板实例，允许流式 API 使用：

```python
template = (
    Template()
    .from_ubuntu_image("22.04")
    .set_workdir("/app")
    .copy("package.json", "/app/package.json")
    .run_cmd("npm install")
    .set_start_cmd("npm start", wait_for_timeout(10_000)))
```

## 用户和工作目录

为模板设置工作目录和用户：

```python
# 设置工作目录
template.set_workdir("/app")

# 设置用户（后续命令以此用户身份运行）
template.set_user("node")
template.set_user("1000:1000")  # 用户 ID 和组 ID
```

## 复制文件

将文件从本地文件系统复制到模板：

```python
# 复制单个文件
template.copy("package.json", "/app/package.json")

# 将多个文件复制到同一目标
template.copy(["file1", "file2"], "/app/file")

# 使用 copy_items 进行多个复制操作
template.copy_items([
    {"src": "src/", "dest": "/app/src/"},
    {"src": "package.json", "dest": "/app/package.json"},
])

# 使用用户和模式选项复制
template.copy("config.json", "/app/config.json", user="appuser", mode=0o644)
```

## 文件操作

在模板构建期间执行各种文件操作：

```python
# 删除文件或目录
template.remove("/tmp/old-file")
template.remove("/tmp/old-dir", recursive=True)
template.remove("/tmp/file", force=True)  # 强制删除

# 重命名文件或目录
template.rename("/old/path", "/new/path")
template.rename("/old/path", "/new/path", force=True)  # 强制重命名

# 创建目录
template.make_dir("/app/data")
template.make_dir("/app/data", mode=0o755)  # 设置权限

# 创建符号链接
template.make_symlink("/path/to/target", "/path/to/link")
```

## 安装包

使用包管理器安装包：

```python
# 安装 Python 包
template.pip_install(["requests", "pandas", "numpy"])

# 安装 Python 包（用户）
template.pip_install(["requests", "pandas", "numpy"], g=False)

# 安装 Node.js 包
template.npm_install(["express", "lodash"])

# 安装 Node.js 包（全局）
template.npm_install(["express", "lodash"], g=True)

# 安装 Bun 包
template.bun_install(["express", "lodash"])

# 安装 Bun 包（全局）
template.bun_install(["express", "lodash"], g=True)

# 安装系统包（Ubuntu/Debian）
template.apt_install(["curl", "wget", "git"])
```

## Git 操作

在模板构建期间克隆 Git 仓库（需要安装 `git`）：

```python
# 克隆仓库
template.git_clone("https://github.com/user/repo.git")

# 将仓库克隆到特定路径
template.git_clone("https://github.com/user/repo.git", "/app/repo")

# 克隆特定分支
template.git_clone("https://github.com/user/repo.git", "/app/repo", branch="main")

# 浅克隆（限制深度）
template.git_clone("https://github.com/user/repo.git", "/app/repo", depth=1)
```

## 环境变量

> 模板定义中设置的环境变量仅在模板构建期间可用。[如何在沙箱中设置环境变量？](/docs/agent-sandbox/sandbox/environment-variables.md)

在模板中设置环境变量：

```python
template.set_envs({
    "NODE_ENV": "production",
    "API_KEY": "your-api-key",
    "DEBUG": "true",
})
```

## 运行命令

在模板构建期间执行 shell 命令：

```python
# 运行单个命令
template.run_cmd("apt-get update && apt-get install -y curl")

# 运行多个命令
template.run_cmd(["apt-get update", "apt-get install -y curl", "curl --version"])

# 以特定用户身份运行命令
template.run_cmd("npm install", user="node")
```
