( file: WorkingDirectoryFileChange, diff: ITextDiff | ILargeTextDiff )
| 127 | * @param diff The source diff |
| 128 | */ |
| 129 | export 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) { |
no test coverage detected