All files / diff/src line.ts

100% Statements 197/197
100% Branches 87/87
100% Functions 6/6
100% Lines 162/162

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 3128x                                                                                               8x   1017x 1017x 1017x 1017x 13097x 10218x 10218x 6235x 6235x 2x 2x     10216x     1017x 9117x 9117x 9117x 9117x 9117x 5137x 5137x   3980x 3980x 3980x   3980x 3980x 3980x 12880x 12880x 3980x 3980x   8900x 8900x     1017x     1017x 1017x 12883x 12883x 12883x 12883x 2240x 2240x 2240x       2240x 718x 350x 567x 567x 567x     567x           16x 16x 16x 16x 16x   551x 784x     12883x                                         12883x 2224x 2224x 2224x 369x 488x 488x   488x 152x 152x 152x 33x   336x 336x 144x 144x       126x 125x 125x 113x 104x 104x 104x 104x 104x 104x 104x           1017x                           8x 1280x 1147x 1045x 1045x 1045x 1008x 1008x 1008x 1008x 1008x 1008x 1008x 1008x 1008x 12868x 12868x 12868x 12868x 12868x   12868x 10345x 12868x 12868x 12868x 953x 675x 675x 675x 278x 119x 119x   159x 159x     11915x 908x 848x 763x       763x 763x   85x 85x     60x 60x     11007x 11007x 11007x 8156x 8156x 2851x 980x 980x 980x 1871x 1012x 1012x   859x 859x       12868x 9156x 93x     12868x     1008x     8x           2747x 2747x 40110x 40110x   20395x   9205x 9205x   9475x 9475x   1035x 1035x        
import * as str from './str';
 
export const enum LINE_PATCH_OP_TYPE {
  /**
   * The whole line is deleted. Delete the current src line and advance the src
   * counter.
   */
  DEL = -1,
 
  /**
   * Lines are equal in src and dst. Keep the line in src and advance, both, src
   * and dst counters.
   */
  EQL = 0,
 
  /**
   * The whole line is inserted. Insert the current dst line and advance the dst
   * counter.
   */
  INS = 1,
 
  /**
   * The line is modified. Execute inner diff between the current src and dst
   * lines. Keep the line in src and advance the src and dst counters.
   */
  MIX = 2,
}
 
export type LinePatchOp = [
  type: LINE_PATCH_OP_TYPE,
  /**
   * Assignment of this operation to the line in the `src` array.
   */
  src: number,
  /**
   * Assignment of this operation to the line in the `dst` array.
   */
  dst: number,
];
 
export type LinePatch = LinePatchOp[];
 
/**
 * Aggregate character-by-character patch into a line-by-line patch.
 *
 * @param patch Character-level patch
 * @returns Line-level patch
 */
export const agg = (patch: str.Patch): str.Patch[] => {
  // console.log(patch);
  const lines: str.Patch[] = [];
  const length = patch.length;
  let line: str.Patch = [];
  const push = (type: str.PATCH_OP_TYPE, str: string) => {
    if (!str.length) return;
    const length = line.length;
    if (length) {
      const lastOp = line[length - 1];
      if (lastOp[0] === type) {
        lastOp[1] += str;
        return;
      }
    }
    line.push([type, str]);
  };
  // console.log("PATCH", patch);
  LINES: for (let i = 0; i < length; i++) {
    const op = patch[i];
    const type = op[0];
    const str = op[1];
    const index = str.indexOf('\n');
    if (index < 0) {
      push(type, str);
      continue LINES;
    } else {
      push(type, str.slice(0, index + 1));
      lines.push(line);
      line = [];
    }
    let prevIndex = index;
    const strLen = str.length;
    LINE: while (prevIndex < strLen) {
      const nextIndex = str.indexOf('\n', prevIndex + 1);
      if (nextIndex < 0) {
        push(type, str.slice(prevIndex + 1));
        break LINE;
      }
      lines.push([[type, str.slice(prevIndex + 1, nextIndex + 1)]]);
      prevIndex = nextIndex;
    }
  }
  if (line.length) lines.push(line);
  // console.log("LINES", lines);
  {
    const length = lines.length;
    for (let i = 0; i < length; i++) {
      const line = (lines[i] = str.normalize(lines[i]));
      const lineLength = line.length;
      NORMALIZE_LINE_START: {
        if (lineLength < 2) break NORMALIZE_LINE_START;
        const firstOp = line[0];
        const secondOp = line[1];
        const secondOpType = secondOp[0];
        // After normalize, line[1] following an EQL is always DEL or INS, and
        // a third op always differs from line[1], so only [EQL, edit] lines
        // qualify for the shift.
        if (firstOp[0] !== str.PATCH_OP_TYPE.EQL) break NORMALIZE_LINE_START;
        if (lineLength > 2) break NORMALIZE_LINE_START;
        for (let j = i + 1; j < length; j++) {
          const targetLine = (lines[j] = str.normalize(lines[j]));
          const targetLineLength = targetLine.length;
          const pfx = firstOp[1];
          let targetLineFirstOp: str.PatchOperation;
          let targetLineSecondOp: str.PatchOperation;
          if (
            targetLine.length > 1 &&
            (targetLineFirstOp = targetLine[0])[0] === secondOpType &&
            (targetLineSecondOp = targetLine[1])[0] === str.PATCH_OP_TYPE.EQL &&
            pfx === targetLineFirstOp[1]
          ) {
            line.splice(0, 1);
            secondOp[1] = pfx + secondOp[1];
            targetLineSecondOp[1] = pfx + targetLineSecondOp[1];
            targetLine.splice(0, 1);
            break NORMALIZE_LINE_START;
          } else
            for (let k = 0; k < targetLineLength; k++)
              if (targetLine[k][0] !== secondOpType) break NORMALIZE_LINE_START;
        }
      }
      NORMALIZE_LINE_END: {
        /**
         * Brings forward EQL line ending if equivalent DEL line ending exists
         * in some following line and all inbetween operations are DEL.
         *
         * From:
         *
         * ```
         * Line 1: [EQL, 'Hell'], [DEL, 'o\n']
         * Line 2: [DEL, ' wor'], [DEL, 'ld\n']
         * Line 3: [DEL, 'gog'], [EQL, 'o\n']
         * ```
         *
         * To:
         *
         * ```
         * Line 1: [EQL, 'Hello\n']
         * Line 2: [DEL, ' wor'], [DEL, 'ld\n']
         * Line 3: [DEL, 'gogo\n']
         * ```
         */
        if (line.length < 2) break NORMALIZE_LINE_END;
        const lastOp = line[line.length - 1];
        const lastOpStr = lastOp[1];
        if (lastOp[0] !== str.PATCH_OP_TYPE.DEL) break NORMALIZE_LINE_END;
        NEXT_LINE: for (let j = i + 1; j < length; j++) {
          const targetLine = (lines[j] = str.normalize(lines[j]));
          const targetLineLength = targetLine.length;
          let targetLineLastOp: str.PatchOperation;
          if (targetLineLength === 1) {
            targetLineLastOp = targetLine[0];
            const targetLineLastOpType = targetLineLastOp[0];
            if (targetLineLastOpType === str.PATCH_OP_TYPE.DEL) continue NEXT_LINE;
            if (targetLine[0][0] !== str.PATCH_OP_TYPE.EQL) break NORMALIZE_LINE_END;
          } else {
            targetLineLastOp = targetLine[1];
            if (targetLineLength > 2) break NORMALIZE_LINE_END;
            const first = targetLine[0];
            if (first[0] !== str.PATCH_OP_TYPE.DEL) break NORMALIZE_LINE_END;
          }
          // DEL is impossible here: length-1 lines continued above, and a
          // normalized [DEL, x] line cannot have x === DEL.
          if (targetLineLastOp[0] !== str.PATCH_OP_TYPE.EQL) break NORMALIZE_LINE_END;
          const moveStr = targetLineLastOp[1];
          if (moveStr.length > lastOpStr.length) break NORMALIZE_LINE_END;
          if (!lastOpStr.endsWith(moveStr)) break NORMALIZE_LINE_END;
          const index = lastOpStr.length - moveStr.length;
          lastOp[1] = lastOpStr.slice(0, index);
          line.push([str.PATCH_OP_TYPE.EQL, moveStr]);
          targetLineLastOp[0] = <any>str.PATCH_OP_TYPE.DEL;
          lines[i] = str.normalize(lines[i]);
          lines[j] = str.normalize(lines[j]);
          break NORMALIZE_LINE_END;
        }
      }
    }
  }
  // console.log("NORMALIZED LINES", lines);
  return lines;
};
 
/**
 * Computes a line-level patch between two arrays of lines.
 *
 * Precondition: elements of `src` and `dst` are newline-free lines. The arrays
 * are joined with `'\n'` internally, so an element containing `'\n'` would
 * corrupt the offset-to-line mapping.
 *
 * @param src Source lines
 * @param dst Destination lines
 * @returns Line-level patch
 */
export const diff = (src: string[], dst: string[]): LinePatch => {
  if (!dst.length) return src.map((_, i) => [LINE_PATCH_OP_TYPE.DEL, i, -1]);
  if (!src.length) return dst.map((_, i) => [LINE_PATCH_OP_TYPE.INS, -1, i]);
  const srcTxt = src.join('\n') + '\n';
  const dstTxt = dst.join('\n') + '\n';
  if (srcTxt === dstTxt) return [];
  const strPatch = str.diff(srcTxt, dstTxt);
  const lines = agg(strPatch);
  const length = lines.length;
  const patch: LinePatch = [];
  let srcIdx = -1;
  let dstIdx = -1;
  const srcLength = src.length;
  const dstLength = dst.length;
  for (let i = 0; i < length; i++) {
    const line = lines[i];
    let lineLength = line.length;
    const lastOp = line[lineLength - 1];
    const lastOpType = lastOp[0];
    const txt = lastOp[1];
    // The joined text ends with '\n', so every line's last op ends with '\n'.
    if (txt === '\n') line.splice(lineLength - 1, 1);
    else lastOp[1] = txt.slice(0, txt.length - 1);
    let lineType: LINE_PATCH_OP_TYPE = LINE_PATCH_OP_TYPE.EQL;
    lineLength = line.length;
    if (!lineLength) {
      if (lastOpType === str.PATCH_OP_TYPE.EQL) {
        lineType = LINE_PATCH_OP_TYPE.EQL;
        srcIdx++;
        dstIdx++;
      } else if (lastOpType === str.PATCH_OP_TYPE.INS) {
        lineType = LINE_PATCH_OP_TYPE.INS;
        dstIdx++;
      } else {
        lineType = LINE_PATCH_OP_TYPE.DEL;
        srcIdx++;
      }
    } else {
      if (i + 1 === length) {
        if (srcIdx + 1 < srcLength) {
          if (dstIdx + 1 < dstLength) {
            lineType =
              lineLength === 1 && line[0][0] === str.PATCH_OP_TYPE.EQL
                ? LINE_PATCH_OP_TYPE.EQL
                : LINE_PATCH_OP_TYPE.MIX;
            srcIdx++;
            dstIdx++;
          } else {
            lineType = LINE_PATCH_OP_TYPE.DEL;
            srcIdx++;
          }
        } else {
          lineType = LINE_PATCH_OP_TYPE.INS;
          dstIdx++;
        }
      } else {
        const op = line[0];
        const type = op[0];
        if (lineLength === 1 && type === lastOpType && type === str.PATCH_OP_TYPE.EQL) {
          srcIdx++;
          dstIdx++;
        } else if (lastOpType === str.PATCH_OP_TYPE.EQL) {
          lineType = LINE_PATCH_OP_TYPE.MIX;
          srcIdx++;
          dstIdx++;
        } else if (lastOpType === str.PATCH_OP_TYPE.INS) {
          lineType = LINE_PATCH_OP_TYPE.INS;
          dstIdx++;
        } else {
          lineType = LINE_PATCH_OP_TYPE.DEL;
          srcIdx++;
        }
      }
    }
    if (lineType === LINE_PATCH_OP_TYPE.EQL) {
      if (src[srcIdx] !== dst[dstIdx]) {
        lineType = LINE_PATCH_OP_TYPE.MIX;
      }
    }
    patch.push([lineType, srcIdx, dstIdx]);
  }
  // console.log("LINE PATCH", patch);
  return patch;
};
 
export const apply = (
  patch: LinePatch,
  onDelete: (pos: number) => void,
  onInsert: (srcPos: number, dstPos: number) => void,
  onMix: (srcPos: number, dstPos: number) => void,
) => {
  const length = patch.length;
  LOOP: for (let i = length - 1; i >= 0; i--) {
    const [type, posSrc, posDst] = patch[i];
    switch (type) {
      case LINE_PATCH_OP_TYPE.EQL:
        continue LOOP;
      case LINE_PATCH_OP_TYPE.DEL:
        onDelete(posSrc);
        break;
      case LINE_PATCH_OP_TYPE.INS:
        onInsert(posSrc, posDst);
        break;
      case LINE_PATCH_OP_TYPE.MIX:
        onMix(posSrc, posDst);
        break;
    }
  }
};