MCPcopy
hub / github.com/desktop/desktop / formatPatch

Function formatPatch

app/src/lib/patch-formatter.ts:129–232  ·  view source on GitHub ↗
(
  file: WorkingDirectoryFileChange,
  diff: ITextDiff | ILargeTextDiff
)

Source from the content-addressed store, hash-verified

127 * @param diff The source diff
128 */
129export function formatPatch(
130 file: WorkingDirectoryFileChange,
131 diff: ITextDiff | ILargeTextDiff
132): string {
133 let patch = ''
134
135 diff.hunks.forEach((hunk, hunkIndex) => {
136 let hunkBuf = ''
137
138 let oldCount = 0
139 let newCount = 0
140
141 let anyAdditionsOrDeletions = false
142
143 hunk.lines.forEach((line, lineIndex) => {
144 const absoluteIndex = hunk.unifiedDiffStart + lineIndex
145
146 // We write our own hunk headers
147 if (line.type === DiffLineType.Hunk) {
148 return
149 }
150
151 // Context lines can always be let through, they will
152 // never appear for new files.
153 if (line.type === DiffLineType.Context) {
154 hunkBuf += `${line.text}\n`
155 oldCount++
156 newCount++
157 } else if (file.selection.isSelected(absoluteIndex)) {
158 // A line selected for inclusion.
159
160 // Use the line as-is
161 hunkBuf += `${line.text}\n`
162
163 if (line.type === DiffLineType.Add) {
164 newCount++
165 }
166 if (line.type === DiffLineType.Delete) {
167 oldCount++
168 }
169
170 anyAdditionsOrDeletions = true
171 } else {
172 // Unselected lines in new files needs to be ignored. A new file by
173 // definition only consists of additions and therefore so will the
174 // partial patch. If the user has elected not to commit a particular
175 // addition we need to generate a patch that pretends that the line
176 // never existed.
177 if (
178 file.status.kind === AppFileStatusKind.New ||
179 file.status.kind === AppFileStatusKind.Untracked
180 ) {
181 return
182 }
183
184 // An unselected added line has no impact on this patch, pretend
185 // it was never added to the old file by dropping it.
186 if (line.type === DiffLineType.Add) {

Callers 2

applyPatchToIndexFunction · 0.90

Calls 5

assertNeverFunction · 0.90
formatHunkHeaderFunction · 0.85
formatPatchHeaderForFileFunction · 0.85
isSelectedMethod · 0.80
debugMethod · 0.80

Tested by

no test coverage detected