patch.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. export * as Patch from "./patch.js"
  2. import { Result, Schema } from "effect"
  3. export class BoundaryError extends Schema.TaggedErrorClass<BoundaryError>()("Patch.BoundaryError", {
  4. boundary: Schema.Literals(["first", "last"]),
  5. }) {
  6. override get message() {
  7. return `The ${this.boundary} line of the patch must be '${this.boundary === "first" ? "*** Begin Patch" : "*** End Patch"}'`
  8. }
  9. }
  10. export class InvalidHunkError extends Schema.TaggedErrorClass<InvalidHunkError>()("Patch.InvalidHunkError", {
  11. line: Schema.String,
  12. lineNumber: Schema.Number,
  13. reason: Schema.optional(Schema.String),
  14. }) {
  15. override get message() {
  16. if (this.reason) return `Invalid hunk at line ${this.lineNumber}: ${this.reason}`
  17. return `Invalid hunk at line ${this.lineNumber}: '${this.line}' is not a valid hunk header. Valid hunk headers: '*** Add File: {path}', '*** Delete File: {path}', '*** Update File: {path}'`
  18. }
  19. }
  20. export type ParseError = BoundaryError | InvalidHunkError
  21. export type Hunk =
  22. | { readonly type: "add"; readonly path: string; readonly contents: string }
  23. | { readonly type: "delete"; readonly path: string }
  24. | {
  25. readonly type: "update"
  26. readonly path: string
  27. readonly movePath?: string
  28. readonly chunks: ReadonlyArray<UpdateFileChunk>
  29. }
  30. export interface UpdateFileChunk {
  31. readonly oldLines: ReadonlyArray<string>
  32. readonly newLines: ReadonlyArray<string>
  33. readonly changeContext?: string
  34. readonly endOfFile?: boolean
  35. }
  36. export interface FileUpdate {
  37. readonly content: string
  38. readonly bom: boolean
  39. }
  40. export function parse(patchText: string): Result.Result<ReadonlyArray<Hunk>, ParseError> {
  41. const lines = stripHeredoc(patchText.trim())
  42. .split("\n")
  43. .map((line) => (line.endsWith("\r") ? line.slice(0, -1) : line))
  44. const begin = lines[0]?.trim() === "*** Begin Patch" ? 0 : -1
  45. const end = lines.at(-1)?.trim() === "*** End Patch" ? lines.length - 1 : -1
  46. if (begin === -1) return Result.fail(new BoundaryError({ boundary: "first" }))
  47. if (end === -1 || begin >= end) return Result.fail(new BoundaryError({ boundary: "last" }))
  48. const hunks: Hunk[] = []
  49. let index = begin + 1
  50. while (index < end) {
  51. const line = lines[index]!
  52. const header = line.trim()
  53. if (
  54. index === begin + 1 &&
  55. header.startsWith("*** Environment ID:") &&
  56. header.slice("*** Environment ID:".length).trim()
  57. ) {
  58. index++
  59. continue
  60. }
  61. if (header.startsWith("*** Add File: ")) {
  62. const path = header.slice("*** Add File: ".length).trim()
  63. const parsed = parseAdd(lines, index + 1, end, path)
  64. if ("error" in parsed) return Result.fail(parsed.error)
  65. hunks.push({ type: "add", path, contents: parsed.content })
  66. index = parsed.next
  67. continue
  68. }
  69. if (header.startsWith("*** Delete File: ")) {
  70. const path = header.slice("*** Delete File: ".length).trim()
  71. const next = lines[index + 1]?.trim()
  72. if (index + 1 < end && next !== undefined && !isBoundary(next)) {
  73. if (next.startsWith("*** ")) {
  74. return Result.fail(new InvalidHunkError({ line: next, lineNumber: index + 2 }))
  75. }
  76. return Result.fail(
  77. new InvalidHunkError({
  78. line: next,
  79. lineNumber: index + 2,
  80. reason: `Unexpected line after Delete File '${path}': '${next}'. Delete hunks do not contain body lines`,
  81. }),
  82. )
  83. }
  84. hunks.push({ type: "delete", path })
  85. index++
  86. continue
  87. }
  88. if (header.startsWith("*** Update File: ")) {
  89. const path = header.slice("*** Update File: ".length).trim()
  90. let next = index + 1
  91. let movePath: string | undefined
  92. while (lines[next]?.trimEnd() === "*** End of File") next++
  93. const move = lines[next]?.trimEnd()
  94. if (move === "*** Move to:" || move?.startsWith("*** Move to: ")) {
  95. movePath = move.slice("*** Move to: ".length).trim()
  96. if (!movePath) {
  97. return Result.fail(
  98. new InvalidHunkError({
  99. line: lines[next]!.trim(),
  100. lineNumber: next + 1,
  101. reason: `Move destination for '${path}' must not be empty`,
  102. }),
  103. )
  104. }
  105. next++
  106. }
  107. const parsed = parseUpdate(lines, next, end, path, index)
  108. if ("error" in parsed) return Result.fail(parsed.error)
  109. hunks.push({ type: "update", path, movePath, chunks: parsed.chunks })
  110. index = parsed.next
  111. continue
  112. }
  113. return Result.fail(new InvalidHunkError({ line: header, lineNumber: index + 1 }))
  114. }
  115. return Result.succeed(hunks)
  116. }
  117. export function derive(path: string, chunks: ReadonlyArray<UpdateFileChunk>, original: string): FileUpdate {
  118. const source = splitBom(original)
  119. const lines = source.text.split("\n")
  120. if (lines.at(-1) === "") lines.pop()
  121. const replacements = computeReplacements(lines, path, chunks)
  122. const updated = [...lines]
  123. for (const [start, remove, insert] of replacements.toReversed()) updated.splice(start, remove, ...insert)
  124. if (updated.at(-1) !== "") updated.push("")
  125. const next = splitBom(updated.join("\n"))
  126. return { content: next.text, bom: source.bom || next.bom }
  127. }
  128. export function joinBom(text: string, bom: boolean) {
  129. const stripped = splitBom(text).text
  130. return bom ? `\uFEFF${stripped}` : stripped
  131. }
  132. function parseAdd(
  133. lines: ReadonlyArray<string>,
  134. start: number,
  135. end: number,
  136. path: string,
  137. ): { content: string; next: number } | { error: InvalidHunkError } {
  138. const content: string[] = []
  139. let index = start
  140. while (index < end && !isBoundary(lines[index]!.trim())) {
  141. if (!lines[index]!.startsWith("+")) {
  142. const line = lines[index]!.trim()
  143. return {
  144. error: new InvalidHunkError({
  145. line,
  146. lineNumber: index + 1,
  147. reason: `Invalid Add File line for '${path}': expected a line starting with '+', got '${line}'`,
  148. }),
  149. }
  150. }
  151. content.push(lines[index]!.slice(1))
  152. index++
  153. }
  154. return { content: content.join("\n"), next: index }
  155. }
  156. function parseUpdate(
  157. lines: ReadonlyArray<string>,
  158. start: number,
  159. end: number,
  160. path: string,
  161. hunk: number,
  162. ): { chunks: ReadonlyArray<UpdateFileChunk>; next: number } | { error: InvalidHunkError } {
  163. const chunks: Array<{
  164. oldLines: string[]
  165. newLines: string[]
  166. changeContext?: string
  167. endOfFile?: boolean
  168. }> = []
  169. let index = start
  170. let afterEndOfFile = false
  171. while (index < end) {
  172. const line = lines[index]!
  173. const updateLine = line.trimEnd()
  174. if (afterEndOfFile) {
  175. if (updateLine === "") {
  176. index++
  177. continue
  178. }
  179. if (updateLine === "@@" || updateLine.startsWith("@@ ")) afterEndOfFile = false
  180. else if (isBoundary(updateLine)) break
  181. else {
  182. return {
  183. error: new InvalidHunkError({
  184. line,
  185. lineNumber: index + 1,
  186. reason: `Expected update hunk to start with a @@ context marker, got: '${line}'`,
  187. }),
  188. }
  189. }
  190. }
  191. if (updateLine === "*** End of File") {
  192. const chunk = chunks.at(-1)
  193. if (chunk && chunk.oldLines.length === 0 && chunk.newLines.length === 0) {
  194. return {
  195. error: new InvalidHunkError({
  196. line: updateLine,
  197. lineNumber: index + 1,
  198. reason: "Update hunk does not contain any lines",
  199. }),
  200. }
  201. }
  202. if (chunk) {
  203. chunk.endOfFile = true
  204. afterEndOfFile = true
  205. }
  206. index++
  207. continue
  208. }
  209. if (isBoundary(updateLine)) break
  210. if (updateLine === "@@" || updateLine.startsWith("@@ ")) {
  211. const previous = chunks.at(-1)
  212. if (previous && previous.oldLines.length === 0 && previous.newLines.length === 0) {
  213. return {
  214. error: new InvalidHunkError({
  215. line,
  216. lineNumber: index + 1,
  217. reason: `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
  218. }),
  219. }
  220. }
  221. chunks.push({
  222. oldLines: [],
  223. newLines: [],
  224. changeContext: updateLine === "@@" ? undefined : updateLine.slice("@@ ".length),
  225. })
  226. index++
  227. continue
  228. }
  229. if (chunks.length === 0) chunks.push({ oldLines: [], newLines: [] })
  230. const chunk = chunks.at(-1)!
  231. if (line === "") {
  232. chunk.oldLines.push("")
  233. chunk.newLines.push("")
  234. index++
  235. continue
  236. }
  237. if (line.startsWith(" ")) {
  238. chunk.oldLines.push(line.slice(1))
  239. chunk.newLines.push(line.slice(1))
  240. index++
  241. continue
  242. }
  243. if (line.startsWith("-")) {
  244. chunk.oldLines.push(line.slice(1))
  245. index++
  246. continue
  247. }
  248. if (line.startsWith("+")) {
  249. chunk.newLines.push(line.slice(1))
  250. index++
  251. continue
  252. }
  253. const populated = chunk.oldLines.length > 0 || chunk.newLines.length > 0
  254. return {
  255. error: new InvalidHunkError({
  256. line,
  257. lineNumber: index + 1,
  258. reason: populated
  259. ? `Expected update hunk to start with a @@ context marker, got: '${line}'`
  260. : `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
  261. }),
  262. }
  263. }
  264. if (chunks.length === 0) {
  265. return {
  266. error: new InvalidHunkError({
  267. line: lines[hunk]!.trim(),
  268. lineNumber: hunk + 1,
  269. reason: `Update file hunk for path '${path}' is empty`,
  270. }),
  271. }
  272. }
  273. const last = chunks.at(-1)!
  274. if (last.oldLines.length === 0 && last.newLines.length === 0) {
  275. const line = lines[index]!.trim()
  276. return {
  277. error: new InvalidHunkError({
  278. line,
  279. lineNumber: index + 1,
  280. reason:
  281. line === "*** End Patch"
  282. ? "Update hunk does not contain any lines"
  283. : `Unexpected line found in update hunk: '${line}'. Every line should start with ' ' (context line), '+' (added line), or '-' (removed line)`,
  284. }),
  285. }
  286. }
  287. return { chunks, next: index }
  288. }
  289. function isBoundary(line: string) {
  290. return (
  291. line === "*** End Patch" ||
  292. line.startsWith("*** Add File: ") ||
  293. line.startsWith("*** Delete File: ") ||
  294. line.startsWith("*** Update File: ")
  295. )
  296. }
  297. function computeReplacements(lines: ReadonlyArray<string>, path: string, chunks: ReadonlyArray<UpdateFileChunk>) {
  298. const replacements: Array<readonly [start: number, remove: number, insert: ReadonlyArray<string>]> = []
  299. let lineIndex = 0
  300. for (const chunk of chunks) {
  301. if (chunk.changeContext) {
  302. const context = seek(lines, [chunk.changeContext], lineIndex)
  303. if (context === -1) throw new Error(`Failed to find context '${chunk.changeContext}' in ${path}`)
  304. lineIndex = context + 1
  305. }
  306. if (chunk.oldLines.length === 0) {
  307. replacements.push([lines.length, 0, chunk.newLines])
  308. continue
  309. }
  310. let oldLines = chunk.oldLines
  311. let newLines = chunk.newLines
  312. let found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
  313. if (found === -1 && oldLines.at(-1) === "") {
  314. oldLines = oldLines.slice(0, -1)
  315. if (newLines.at(-1) === "") newLines = newLines.slice(0, -1)
  316. found = seek(lines, oldLines, lineIndex, chunk.endOfFile)
  317. }
  318. if (found === -1 && chunk.oldLines.every((line) => line === "")) {
  319. const expected =
  320. chunk.oldLines.length === 1 ? "an expected blank line" : `${chunk.oldLines.length} consecutive blank lines`
  321. throw new Error(`Failed to find ${expected} in ${path}`)
  322. }
  323. if (found === -1) throw new Error(`Failed to find expected lines in ${path}:\n${chunk.oldLines.join("\n")}`)
  324. replacements.push([found, oldLines.length, newLines])
  325. lineIndex = found + oldLines.length
  326. }
  327. return replacements.toSorted((left, right) => left[0] - right[0])
  328. }
  329. function seek(lines: ReadonlyArray<string>, pattern: ReadonlyArray<string>, start: number, eof = false) {
  330. if (pattern.length === 0) return -1
  331. if (eof) {
  332. const offset = lines.length - pattern.length
  333. if (offset < start) return -1
  334. for (const compare of [exact, rstrip, trim, normalized]) {
  335. if (matches(lines, pattern, offset, compare)) return offset
  336. }
  337. return -1
  338. }
  339. for (const compare of [exact, rstrip, trim, normalized]) {
  340. for (let offset = start; offset <= lines.length - pattern.length; offset++) {
  341. if (matches(lines, pattern, offset, compare)) return offset
  342. }
  343. }
  344. return -1
  345. }
  346. function matches(
  347. lines: ReadonlyArray<string>,
  348. pattern: ReadonlyArray<string>,
  349. offset: number,
  350. compare: (left: string, right: string) => boolean,
  351. ) {
  352. return pattern.every((line, index) => compare(lines[offset + index]!, line))
  353. }
  354. const exact = (left: string, right: string) => left === right
  355. const rstrip = (left: string, right: string) => left.trimEnd() === right.trimEnd()
  356. const trim = (left: string, right: string) => left.trim() === right.trim()
  357. const normalized = (left: string, right: string) => normalize(left.trim()) === normalize(right.trim())
  358. const normalize = (value: string) =>
  359. value
  360. .replace(/[‘’‚‛]/g, "'")
  361. .replace(/[“”„‟]/g, '"')
  362. .replace(/[‐‑‒–—―−]/g, "-")
  363. .replace(/[\u00A0\u2002-\u200A\u202F\u205F\u3000]/g, " ")
  364. const splitBom = (text: string) =>
  365. text.startsWith("\uFEFF") ? { bom: true, text: text.slice(1) } : { bom: false, text }
  366. const stripHeredoc = (input: string) => input.match(/^(?:cat\s+)?<<(['"]?)(\w+)\1\s*\n([\s\S]*?)\n\2\s*$/)?.[3] ?? input