Code Reader
首页
帮助
设计文档
首页
帮助
设计文档
  • Write 工具

Write 工具

Write 工具用于创建新文件或覆盖现有文件。

概述

Write 工具允许 AI 助手在文件系统中创建或覆盖文件。它支持:

  • 创建新文件
  • 覆盖现有文件(自动创建备份)
  • 支持文本和二进制内容
  • 自动备份被覆盖的文件

定义位置

  • packages/opencode/src/tool/write.ts
  • packages/opencode/src/tool/write.txt

参数说明

参数名类型必填说明
filePathstring是要写入的文件路径
contentstring是要写入的文件内容

TypeScript 类型定义

export type WriteInput = {
  filePath: string
  content: string
}

export type WriteOutput = {
  title: string // 文件路径(相对路径)
  output: string // 写入确认消息
  metadata: {
    summary: FileSummary // 文件操作摘要
  }
}

工作流程

1. 路径解析

let filepath = params.filePath
if (!path.isAbsolute(filepath)) {
  filepath = path.join(process.cwd(), filepath)
}
const title = path.relative(Instance.worktree, filepath)

2. 权限检查

await ctx.ask({
  permission: "write",
  patterns: [filepath],
  always: ["*"],
  metadata: {},
})

3. 备份现有文件

const file = Bun.file(filepath)
if (await file.exists()) {
  // 创建备份
  const backupPath = filepath + ".bak"
  await Bun.file(backupPath).write(await file.text())

  // 重命名
  await fs.rename(backupPath, fileBackupPath)
}

4. 写入内容

await file.write(params.content)

5. 更新文件时间

FileTime.write(ctx.sessionID, filepath)
LSP.touchFile(filepath, true)

典型使用场景

场景 1:创建新文件

await WriteTool.execute(
  {
    filePath: "src/utils/helpers.ts",
    content: `export function formatDate(date: Date): string {
  return date.toISOString()
}
`,
  },
  ctx,
)

场景 2:覆写现有文件

// 现有文件会被自动备份
await WriteTool.execute(
  {
    filePath: "src/config.ts",
    content: `export const config = {
  apiKey: process.env.API_KEY,
  debug: true,
}
`,
  },
  ctx,
)

场景 3:写入二进制内容

const base64Content = "iVBORw0KGgoAAAANSUhEUgAA..."
await WriteTool.execute(
  {
    filePath: "assets/logo.png",
    content: base64Content,
  },
  ctx,
)

错误处理

目录不存在

Error: ENOENT: no such file or directory, mkdir 'src/new'

解决:

  • 先创建目录:mkdir -p src/new
  • 然后写入文件

权限被拒绝

Error: Permission denied for write operation

解决:

  • 检查用户权限配置
  • 确保文件路径在项目目录内

限制和注意事项

自动备份

  • 覆盖文件时自动创建 .bak 备份
  • 备份文件会重命名为带时间戳的名称
  • 最多保留一定数量的备份(根据配置)

文件大小限制

  • 超大文件可能会触发输出截断
  • 建议对大文件使用分批写入或专门处理

权限要求

权限类型说明
write写入文件的权限
external_directory如果文件在项目外,需要此权限

最佳实践

1. 使用绝对路径

// ✅ 好
await WriteTool.execute(
  {
    filePath: "/home/user/project/src/app.ts",
    content: "...",
  },
  ctx,
)

2. 提供有用的文件注释

await WriteTool.execute(
  {
    filePath: "src/api/client.ts",
    content: `/**
 * API Client
 * @module api/client
 * @author AI Assistant
 */

export class ApiClient {
  // ...
}
`,
  },
  ctx,
)

3. 组织文件结构

// 写入完整的文件,包括导入、导出等
await WriteTool.execute(
  {
    filePath: "src/index.ts",
    content: `import { AppConfig } from './config'
import { logger } from './utils'

export { AppConfig, logger }
`,
  },
  ctx,
)

相关文档

  • Tool System - Tool 系统实现机制
  • Read - 读取文件
  • Edit - 编辑文件

变更历史

版本变更内容日期
v1初始 Write 工具-