1.6 KB63 lines
Blame
1/**
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8type HunkGroup = {
9 common: string[];
10 removed: string[];
11 added: string[];
12};
13
14/**
15 * We must find the groups within `lines` so that multiline sequences of
16 * modified lines are displayed correctly. A group is defined by:
17 *
18 * - a sequence of 0 or more "common lines" that start with ' '
19 * - a sequence of 0 or more "removed lines" that start with '-'
20 * - a sequence of 0 or more "added lines" that start with '+'
21 *
22 * Therefore, the end of a group is determined by either:
23 *
24 * - reaching the end of a list of lines
25 * - encountering a "common line" after an "added" or "removed" line.
26 */
27export default function organizeLinesIntoGroups(lines: string[]): HunkGroup[] {
28 const groups = [];
29 let group = newGroup();
30 lines.forEach(fullLine => {
31 const firstChar = fullLine.charAt(0);
32 const line = fullLine.slice(1);
33 if (firstChar === ' ') {
34 if (hasDeltas(group)) {
35 // This must be the start of a new group!
36 groups.push(group);
37 group = newGroup();
38 }
39 group.common.push(line);
40 } else if (firstChar === '-') {
41 group.removed.push(line);
42 } else if (firstChar === '+') {
43 group.added.push(line);
44 }
45 });
46
47 groups.push(group);
48
49 return groups;
50}
51
52function hasDeltas(group: HunkGroup): boolean {
53 return group.removed.length !== 0 || group.added.length !== 0;
54}
55
56function newGroup(): HunkGroup {
57 return {
58 common: [],
59 removed: [],
60 added: [],
61 };
62}
63