patch.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. package tools
  2. import (
  3. "context"
  4. "encoding/json"
  5. "fmt"
  6. "os"
  7. "path/filepath"
  8. "time"
  9. "github.com/kujtimiihoxha/opencode/internal/config"
  10. "github.com/kujtimiihoxha/opencode/internal/diff"
  11. "github.com/kujtimiihoxha/opencode/internal/history"
  12. "github.com/kujtimiihoxha/opencode/internal/logging"
  13. "github.com/kujtimiihoxha/opencode/internal/lsp"
  14. "github.com/kujtimiihoxha/opencode/internal/permission"
  15. )
  16. type PatchParams struct {
  17. PatchText string `json:"patch_text"`
  18. }
  19. type PatchResponseMetadata struct {
  20. FilesChanged []string `json:"files_changed"`
  21. Additions int `json:"additions"`
  22. Removals int `json:"removals"`
  23. }
  24. type patchTool struct {
  25. lspClients map[string]*lsp.Client
  26. permissions permission.Service
  27. files history.Service
  28. }
  29. const (
  30. PatchToolName = "patch"
  31. patchDescription = `Applies a patch to multiple files in one operation. This tool is useful for making coordinated changes across multiple files.
  32. The patch text must follow this format:
  33. *** Begin Patch
  34. *** Update File: /path/to/file
  35. @@ Context line (unique within the file)
  36. Line to keep
  37. -Line to remove
  38. +Line to add
  39. Line to keep
  40. *** Add File: /path/to/new/file
  41. +Content of the new file
  42. +More content
  43. *** Delete File: /path/to/file/to/delete
  44. *** End Patch
  45. Before using this tool:
  46. 1. Use the FileRead tool to understand the files' contents and context
  47. 2. Verify all file paths are correct (use the LS tool)
  48. CRITICAL REQUIREMENTS FOR USING THIS TOOL:
  49. 1. UNIQUENESS: Context lines MUST uniquely identify the specific sections you want to change
  50. 2. PRECISION: All whitespace, indentation, and surrounding code must match exactly
  51. 3. VALIDATION: Ensure edits result in idiomatic, correct code
  52. 4. PATHS: Always use absolute file paths (starting with /)
  53. The tool will apply all changes in a single atomic operation.`
  54. )
  55. func NewPatchTool(lspClients map[string]*lsp.Client, permissions permission.Service, files history.Service) BaseTool {
  56. return &patchTool{
  57. lspClients: lspClients,
  58. permissions: permissions,
  59. files: files,
  60. }
  61. }
  62. func (p *patchTool) Info() ToolInfo {
  63. return ToolInfo{
  64. Name: PatchToolName,
  65. Description: patchDescription,
  66. Parameters: map[string]any{
  67. "patch_text": map[string]any{
  68. "type": "string",
  69. "description": "The full patch text that describes all changes to be made",
  70. },
  71. },
  72. Required: []string{"patch_text"},
  73. }
  74. }
  75. func (p *patchTool) Run(ctx context.Context, call ToolCall) (ToolResponse, error) {
  76. var params PatchParams
  77. if err := json.Unmarshal([]byte(call.Input), &params); err != nil {
  78. return NewTextErrorResponse("invalid parameters"), nil
  79. }
  80. if params.PatchText == "" {
  81. return NewTextErrorResponse("patch_text is required"), nil
  82. }
  83. // Identify all files needed for the patch and verify they've been read
  84. filesToRead := diff.IdentifyFilesNeeded(params.PatchText)
  85. for _, filePath := range filesToRead {
  86. absPath := filePath
  87. if !filepath.IsAbs(absPath) {
  88. wd := config.WorkingDirectory()
  89. absPath = filepath.Join(wd, absPath)
  90. }
  91. if getLastReadTime(absPath).IsZero() {
  92. return NewTextErrorResponse(fmt.Sprintf("you must read the file %s before patching it. Use the FileRead tool first", filePath)), nil
  93. }
  94. fileInfo, err := os.Stat(absPath)
  95. if err != nil {
  96. if os.IsNotExist(err) {
  97. return NewTextErrorResponse(fmt.Sprintf("file not found: %s", absPath)), nil
  98. }
  99. return ToolResponse{}, fmt.Errorf("failed to access file: %w", err)
  100. }
  101. if fileInfo.IsDir() {
  102. return NewTextErrorResponse(fmt.Sprintf("path is a directory, not a file: %s", absPath)), nil
  103. }
  104. modTime := fileInfo.ModTime()
  105. lastRead := getLastReadTime(absPath)
  106. if modTime.After(lastRead) {
  107. return NewTextErrorResponse(
  108. fmt.Sprintf("file %s has been modified since it was last read (mod time: %s, last read: %s)",
  109. absPath, modTime.Format(time.RFC3339), lastRead.Format(time.RFC3339),
  110. )), nil
  111. }
  112. }
  113. // Check for new files to ensure they don't already exist
  114. filesToAdd := diff.IdentifyFilesAdded(params.PatchText)
  115. for _, filePath := range filesToAdd {
  116. absPath := filePath
  117. if !filepath.IsAbs(absPath) {
  118. wd := config.WorkingDirectory()
  119. absPath = filepath.Join(wd, absPath)
  120. }
  121. _, err := os.Stat(absPath)
  122. if err == nil {
  123. return NewTextErrorResponse(fmt.Sprintf("file already exists and cannot be added: %s", absPath)), nil
  124. } else if !os.IsNotExist(err) {
  125. return ToolResponse{}, fmt.Errorf("failed to check file: %w", err)
  126. }
  127. }
  128. // Load all required files
  129. currentFiles := make(map[string]string)
  130. for _, filePath := range filesToRead {
  131. absPath := filePath
  132. if !filepath.IsAbs(absPath) {
  133. wd := config.WorkingDirectory()
  134. absPath = filepath.Join(wd, absPath)
  135. }
  136. content, err := os.ReadFile(absPath)
  137. if err != nil {
  138. return ToolResponse{}, fmt.Errorf("failed to read file %s: %w", absPath, err)
  139. }
  140. currentFiles[filePath] = string(content)
  141. }
  142. // Process the patch
  143. patch, fuzz, err := diff.TextToPatch(params.PatchText, currentFiles)
  144. if err != nil {
  145. return NewTextErrorResponse(fmt.Sprintf("failed to parse patch: %s", err)), nil
  146. }
  147. if fuzz > 3 {
  148. return NewTextErrorResponse(fmt.Sprintf("patch contains fuzzy matches (fuzz level: %d). Please make your context lines more precise", fuzz)), nil
  149. }
  150. // Convert patch to commit
  151. commit, err := diff.PatchToCommit(patch, currentFiles)
  152. if err != nil {
  153. return NewTextErrorResponse(fmt.Sprintf("failed to create commit from patch: %s", err)), nil
  154. }
  155. // Get session ID and message ID
  156. sessionID, messageID := GetContextValues(ctx)
  157. if sessionID == "" || messageID == "" {
  158. return ToolResponse{}, fmt.Errorf("session ID and message ID are required for creating a patch")
  159. }
  160. // Request permission for all changes
  161. for path, change := range commit.Changes {
  162. switch change.Type {
  163. case diff.ActionAdd:
  164. dir := filepath.Dir(path)
  165. patchDiff, _, _ := diff.GenerateDiff("", *change.NewContent, path)
  166. p := p.permissions.Request(
  167. permission.CreatePermissionRequest{
  168. Path: dir,
  169. ToolName: PatchToolName,
  170. Action: "create",
  171. Description: fmt.Sprintf("Create file %s", path),
  172. Params: EditPermissionsParams{
  173. FilePath: path,
  174. Diff: patchDiff,
  175. },
  176. },
  177. )
  178. if !p {
  179. return ToolResponse{}, permission.ErrorPermissionDenied
  180. }
  181. case diff.ActionUpdate:
  182. currentContent := ""
  183. if change.OldContent != nil {
  184. currentContent = *change.OldContent
  185. }
  186. newContent := ""
  187. if change.NewContent != nil {
  188. newContent = *change.NewContent
  189. }
  190. patchDiff, _, _ := diff.GenerateDiff(currentContent, newContent, path)
  191. dir := filepath.Dir(path)
  192. p := p.permissions.Request(
  193. permission.CreatePermissionRequest{
  194. Path: dir,
  195. ToolName: PatchToolName,
  196. Action: "update",
  197. Description: fmt.Sprintf("Update file %s", path),
  198. Params: EditPermissionsParams{
  199. FilePath: path,
  200. Diff: patchDiff,
  201. },
  202. },
  203. )
  204. if !p {
  205. return ToolResponse{}, permission.ErrorPermissionDenied
  206. }
  207. case diff.ActionDelete:
  208. dir := filepath.Dir(path)
  209. patchDiff, _, _ := diff.GenerateDiff(*change.OldContent, "", path)
  210. p := p.permissions.Request(
  211. permission.CreatePermissionRequest{
  212. Path: dir,
  213. ToolName: PatchToolName,
  214. Action: "delete",
  215. Description: fmt.Sprintf("Delete file %s", path),
  216. Params: EditPermissionsParams{
  217. FilePath: path,
  218. Diff: patchDiff,
  219. },
  220. },
  221. )
  222. if !p {
  223. return ToolResponse{}, permission.ErrorPermissionDenied
  224. }
  225. }
  226. }
  227. // Apply the changes to the filesystem
  228. err = diff.ApplyCommit(commit, func(path string, content string) error {
  229. absPath := path
  230. if !filepath.IsAbs(absPath) {
  231. wd := config.WorkingDirectory()
  232. absPath = filepath.Join(wd, absPath)
  233. }
  234. // Create parent directories if needed
  235. dir := filepath.Dir(absPath)
  236. if err := os.MkdirAll(dir, 0o755); err != nil {
  237. return fmt.Errorf("failed to create parent directories for %s: %w", absPath, err)
  238. }
  239. return os.WriteFile(absPath, []byte(content), 0o644)
  240. }, func(path string) error {
  241. absPath := path
  242. if !filepath.IsAbs(absPath) {
  243. wd := config.WorkingDirectory()
  244. absPath = filepath.Join(wd, absPath)
  245. }
  246. return os.Remove(absPath)
  247. })
  248. if err != nil {
  249. return NewTextErrorResponse(fmt.Sprintf("failed to apply patch: %s", err)), nil
  250. }
  251. // Update file history for all modified files
  252. changedFiles := []string{}
  253. totalAdditions := 0
  254. totalRemovals := 0
  255. for path, change := range commit.Changes {
  256. absPath := path
  257. if !filepath.IsAbs(absPath) {
  258. wd := config.WorkingDirectory()
  259. absPath = filepath.Join(wd, absPath)
  260. }
  261. changedFiles = append(changedFiles, absPath)
  262. oldContent := ""
  263. if change.OldContent != nil {
  264. oldContent = *change.OldContent
  265. }
  266. newContent := ""
  267. if change.NewContent != nil {
  268. newContent = *change.NewContent
  269. }
  270. // Calculate diff statistics
  271. _, additions, removals := diff.GenerateDiff(oldContent, newContent, path)
  272. totalAdditions += additions
  273. totalRemovals += removals
  274. // Update history
  275. file, err := p.files.GetByPathAndSession(ctx, absPath, sessionID)
  276. if err != nil && change.Type != diff.ActionAdd {
  277. // If not adding a file, create history entry for existing file
  278. _, err = p.files.Create(ctx, sessionID, absPath, oldContent)
  279. if err != nil {
  280. logging.Debug("Error creating file history", "error", err)
  281. }
  282. }
  283. if err == nil && change.Type != diff.ActionAdd && file.Content != oldContent {
  284. // User manually changed content, store intermediate version
  285. _, err = p.files.CreateVersion(ctx, sessionID, absPath, oldContent)
  286. if err != nil {
  287. logging.Debug("Error creating file history version", "error", err)
  288. }
  289. }
  290. // Store new version
  291. if change.Type == diff.ActionDelete {
  292. _, err = p.files.CreateVersion(ctx, sessionID, absPath, "")
  293. } else {
  294. _, err = p.files.CreateVersion(ctx, sessionID, absPath, newContent)
  295. }
  296. if err != nil {
  297. logging.Debug("Error creating file history version", "error", err)
  298. }
  299. // Record file operations
  300. recordFileWrite(absPath)
  301. recordFileRead(absPath)
  302. }
  303. // Run LSP diagnostics on all changed files
  304. for _, filePath := range changedFiles {
  305. waitForLspDiagnostics(ctx, filePath, p.lspClients)
  306. }
  307. result := fmt.Sprintf("Patch applied successfully. %d files changed, %d additions, %d removals",
  308. len(changedFiles), totalAdditions, totalRemovals)
  309. diagnosticsText := ""
  310. for _, filePath := range changedFiles {
  311. diagnosticsText += getDiagnostics(filePath, p.lspClients)
  312. }
  313. if diagnosticsText != "" {
  314. result += "\n\nDiagnostics:\n" + diagnosticsText
  315. }
  316. return WithResponseMetadata(
  317. NewTextResponse(result),
  318. PatchResponseMetadata{
  319. FilesChanged: changedFiles,
  320. Additions: totalAdditions,
  321. Removals: totalRemovals,
  322. }), nil
  323. }