MCPcopy Index your code
hub / github.com/npmx-dev/npmx.dev / parseUnifiedDiff

Function parseUnifiedDiff

shared/utils/diff.ts:166–295  ·  view source on GitHub ↗
(
  diffText: string,
  options: Partial<ParseOptions> = {},
)

Source from the content-addressed store, hash-verified

164}
165
166export function parseUnifiedDiff(
167 diffText: string,
168 options: Partial<ParseOptions> = {},
169): FileDiff[] {
170 const opts = { ...defaultOptions, ...options }
171 const files: FileDiff[] = []
172
173 const lines = diffText.split('\n')
174 let currentFile: FileDiff | null = null
175 let currentHunk: {
176 changes: RawChange[]
177 oldStart: number
178 oldLines: number
179 newStart: number
180 newLines: number
181 content: string
182 } | null = null
183 let oldLine = 0
184 let newLine = 0
185
186 // Track old path from --- line to detect /dev/null (new/deleted files)
187 let lastOldPath = ''
188
189 for (const line of lines) {
190 if (line.startsWith('---')) {
191 if (currentHunk && currentFile) {
192 const hunk = processHunk(currentHunk, opts)
193 currentFile.hunks.push(hunk)
194 }
195 currentHunk = null
196 const oldMatch = line.match(/^--- (?:a\/)?(.*)/)
197 lastOldPath = oldMatch?.[1]?.trimEnd() ?? ''
198 continue
199 }
200
201 if (line.startsWith('+++')) {
202 const match = line.match(/^\+\+\+ (?:b\/)?(.*)/)
203 const path = match?.[1]?.trimEnd() ?? ''
204
205 if (currentFile && currentHunk) {
206 const hunk = processHunk(currentHunk, opts)
207 currentFile.hunks.push(hunk)
208 files.push(currentFile)
209 } else if (currentFile) {
210 files.push(currentFile)
211 }
212
213 // Determine file type from --- / +++ paths:
214 // /dev/null in the old path means a new file; in the new path means deleted
215 let fileType: FileDiff['type'] = 'modify'
216 if (lastOldPath === '/dev/null') fileType = 'add'
217 else if (path === '/dev/null') fileType = 'delete'
218
219 currentFile = {
220 oldPath: lastOldPath === '/dev/null' ? path : lastOldPath || path,
221 newPath: path,
222 type: fileType,
223 hunks: [],

Callers 1

createDiffFunction · 0.85

Calls 1

processHunkFunction · 0.85

Tested by

no test coverage detected