addons/shared/SplitDiffView/organizeLinesIntoGroups.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318type HunkGroup = {
b69ab319 common: string[];
b69ab3110 removed: string[];
b69ab3111 added: string[];
b69ab3112};
b69ab3113
b69ab3114/**
b69ab3115 * We must find the groups within `lines` so that multiline sequences of
b69ab3116 * modified lines are displayed correctly. A group is defined by:
b69ab3117 *
b69ab3118 * - a sequence of 0 or more "common lines" that start with ' '
b69ab3119 * - a sequence of 0 or more "removed lines" that start with '-'
b69ab3120 * - a sequence of 0 or more "added lines" that start with '+'
b69ab3121 *
b69ab3122 * Therefore, the end of a group is determined by either:
b69ab3123 *
b69ab3124 * - reaching the end of a list of lines
b69ab3125 * - encountering a "common line" after an "added" or "removed" line.
b69ab3126 */
b69ab3127export default function organizeLinesIntoGroups(lines: string[]): HunkGroup[] {
b69ab3128 const groups = [];
b69ab3129 let group = newGroup();
b69ab3130 lines.forEach(fullLine => {
b69ab3131 const firstChar = fullLine.charAt(0);
b69ab3132 const line = fullLine.slice(1);
b69ab3133 if (firstChar === ' ') {
b69ab3134 if (hasDeltas(group)) {
b69ab3135 // This must be the start of a new group!
b69ab3136 groups.push(group);
b69ab3137 group = newGroup();
b69ab3138 }
b69ab3139 group.common.push(line);
b69ab3140 } else if (firstChar === '-') {
b69ab3141 group.removed.push(line);
b69ab3142 } else if (firstChar === '+') {
b69ab3143 group.added.push(line);
b69ab3144 }
b69ab3145 });
b69ab3146
b69ab3147 groups.push(group);
b69ab3148
b69ab3149 return groups;
b69ab3150}
b69ab3151
b69ab3152function hasDeltas(group: HunkGroup): boolean {
b69ab3153 return group.removed.length !== 0 || group.added.length !== 0;
b69ab3154}
b69ab3155
b69ab3156function newGroup(): HunkGroup {
b69ab3157 return {
b69ab3158 common: [],
b69ab3159 removed: [],
b69ab3160 added: [],
b69ab3161 };
b69ab3162}