patch.test.ts 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. import { describe, expect, test } from "bun:test"
  2. import { Patch } from "@opencode-ai/core/patch"
  3. describe("Patch", () => {
  4. test("parses add, update, and delete hunks", () => {
  5. expect(
  6. Patch.parse(
  7. "*** Begin Patch\n*** Add File: add.txt\n+added\n*** Update File: update.txt\n@@ section\n-old\n+new\n*** Delete File: delete.txt\n*** End Patch",
  8. ),
  9. ).toEqual([
  10. { type: "add", path: "add.txt", contents: "added" },
  11. {
  12. type: "update",
  13. path: "update.txt",
  14. chunks: [{ oldLines: ["old"], newLines: ["new"], changeContext: "section", endOfFile: undefined }],
  15. movePath: undefined,
  16. },
  17. { type: "delete", path: "delete.txt" },
  18. ])
  19. })
  20. test("strips a heredoc wrapper", () => {
  21. expect(Patch.parse("cat <<'EOF'\n*** Begin Patch\n*** Add File: add.txt\n+added\n*** End Patch\nEOF")).toEqual([
  22. { type: "add", path: "add.txt", contents: "added" },
  23. ])
  24. })
  25. test("derives fuzzy line updates while preserving BOM", () => {
  26. const update = Patch.derive("update.txt", [{ oldLines: [" old "], newLines: ["new"] }], "\uFEFFold\n")
  27. expect(update).toEqual({ content: "new\n", bom: true })
  28. expect(Patch.joinBom(update.content, update.bom)).toBe("\uFEFFnew\n")
  29. })
  30. test("matches EOF-anchored chunks from the end", () => {
  31. expect(
  32. Patch.derive(
  33. "update.txt",
  34. [{ oldLines: ["marker", "end"], newLines: ["marker changed", "end"], endOfFile: true }],
  35. "marker\nmiddle\nmarker\nend\n",
  36. ).content,
  37. ).toBe("marker\nmiddle\nmarker changed\nend\n")
  38. })
  39. test("parses the EOF marker inside update chunks", () => {
  40. expect(
  41. Patch.parse("*** Begin Patch\n*** Update File: update.txt\n@@\n-last\n+end\n*** End of File\n*** End Patch"),
  42. ).toEqual([
  43. {
  44. type: "update",
  45. path: "update.txt",
  46. movePath: undefined,
  47. chunks: [{ oldLines: ["last"], newLines: ["end"], changeContext: undefined, endOfFile: true }],
  48. },
  49. ])
  50. })
  51. test("rejects malformed hunk bodies", () => {
  52. expect(() => Patch.parse("*** Begin Patch\n*** Add File: add.txt\nmissing plus\n*** End Patch")).toThrow(
  53. "Invalid add file line",
  54. )
  55. expect(() => Patch.parse("*** Begin Patch\n*** Update File: update.txt\n*** End Patch")).toThrow(
  56. "expected at least one @@ chunk",
  57. )
  58. expect(() => Patch.parse("*** Begin Patch\n*** Delete File: delete.txt\nunexpected body\n*** End Patch")).toThrow(
  59. "Invalid patch line",
  60. )
  61. })
  62. })