How to use the diff.structuredPatch function in diff

To help you get started, we’ve selected a few diff examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github sysgears / larix / packages / larix / src / diff / patch.ts View on Github external
}
        try {
          stat2 = fs.statSync(filePath2);
        } catch (e) {
          // continue, regardless of error
        }
        // if (!stat1 || !stat2) {
        //   console.log(filePath1, filePath2);
        // }
        const text1 = stat1 && stat1.isFile() ? fs.readFileSync(filePath1, 'utf8') : '';
        const text2 = stat2 && stat2.isFile() ? fs.readFileSync(filePath2, 'utf8') : '';
        const mtime1 = stat1 ? getTimestamp(fs.statSync(filePath1).mtime) : '';
        const mtime2 = stat2 ? getTimestamp(fs.statSync(filePath2).mtime) : '';
        const relPath1 = path.relative(basedir1 || file1, filePath1);
        const relPath2 = path.relative(basedir2 || file2, filePath2);
        patch[relPath2] = diff.structuredPatch(relPath1, relPath2, text1, text2, mtime1, mtime2);
        if ((stat1 && stat1.isDirectory()) || (stat2 && stat2.isDirectory())) {
          patch = { ...patch, ...createPatch(filePath1, filePath2, file1, file2) };
        }
      }
    } else {
      const text1 = fs.readFileSync(file1, 'utf8');
      const text2 = fs.readFileSync(file2, 'utf8');
      const mtime1 = getTimestamp(fs.statSync(file1).mtime);
      const mtime2 = getTimestamp(fs.statSync(file2).mtime);
      const relPath1 = path.relative(basedir1 || path.dirname(file1), file1);
      const relPath2 = path.relative(basedir2 || path.dirname(file2), file2);
      patch[relPath2] = diff.structuredPatch(relPath1, relPath2, text1, text2, mtime1, mtime2);
    }
  } catch (e) {
    console.error(e);
  }
github sourcegraph / sourcegraph / web / src / enterprise / expCampaigns / backend / computeDiff.ts View on Github external
const startOffset = positionToOffset(oldText, edit.range.start)
                    const endOffset = positionToOffset(oldText, edit.range.end)
                    return { offset: startOffset, length: endOffset - startOffset, content: edit.newText }
                })
            )

            if (Math.max(oldText.length, newText.length) > 70000) {
                console.warn(
                    `Skipping computation of large diff for ${uri.toString()} (${Math.max(
                        oldText.length,
                        newText.length
                    ) / 1024}kb)`
                )
                continue
            }
            const { hunks } = structuredPatch(uri.toString(), uri.toString(), oldText, newText, undefined, undefined, {
                context: 2,
            })
            const p = parseRepoURI(uri)
            fileDiffs.push({
                oldPath: uri.toString(),
                newPath: uri.toString(),
                hunks: hunks.map(npmDiffToFileDiffHunk),
                patch: createTwoFilesPatch(
                    'a/' + p.filePath!,
                    'b/' + p.filePath!,
                    oldText,
                    newText,
                    undefined,
                    undefined
                ),
                // TODO!(sqs): hack that we have 2 different patches w/different URIs
github aws / aws-cdk / packages / @aws-cdk / cloudformation-diff / lib / format.ts View on Github external
function _diffStrings(oldStr: string, newStr: string, context: number): string[] {
  const patch: Patch = structuredPatch(null, null, oldStr, newStr, null, null, { context });
  const result = new Array();
  for (const hunk of patch.hunks) {
    result.push(colors.magenta(`@@ -${hunk.oldStart},${hunk.oldLines} +${hunk.newStart},${hunk.newLines} @@`));
    const baseIndent = _findIndent(hunk.lines);
    for (const line of hunk.lines) {
      // Don't care about termination newline.
      if (line === '\\ No newline at end of file') { continue; }
      const marker = line.charAt(0);
      const text = line.slice(1 + baseIndent);
      switch (marker) {
      case ' ':
        result.push(`${CONTEXT} ${text}`);
        break;
      case '+':
        result.push(colors.bold(`${ADDITION} ${colors.green(text)}`));
        break;
github sourcegraph / sourcegraph / web / src / enterprise / threadsOLD / detail / changes / computeDiff.ts View on Github external
}
    }

    const fileDiffs: FileDiff[] = []
    for (const [uri, edits] of editsByUri) {
        const oldText = await extensionsController.services.fileSystem.readFile(new URL(uri))
        const newText = applyEdits(
            oldText,
            edits.map(edit => {
                // TODO!(sqs): doesnt account for multiple edits
                const startOffset = positionToOffset(oldText, edit.range.start)
                const endOffset = positionToOffset(oldText, edit.range.end)
                return { offset: startOffset, length: endOffset - startOffset, content: edit.newText }
            })
        )
        const { hunks } = structuredPatch(uri.toString(), uri.toString(), oldText, newText, undefined, undefined, {
            context: 2,
        })
        const p = parseRepoURI(uri)
        fileDiffs.push({
            oldPath: uri.toString(),
            newPath: uri.toString(),
            hunks: hunks.map(npmDiffToFileDiffHunk),
            patch: createTwoFilesPatch('a/' + p.filePath!, 'b/' + p.filePath!, oldText, newText, undefined, undefined),
            // TODO!(sqs): hack that we have 2 different patches w/different URIs
            patchWithFullURIs: createTwoFilesPatch(uri, uri, oldText, newText, undefined, undefined, { context: 2 }),
        })
    }
    return fileDiffs
}
github sysgears / larix / packages / larix / src / diff / patch.ts View on Github external
const mtime2 = stat2 ? getTimestamp(fs.statSync(filePath2).mtime) : '';
        const relPath1 = path.relative(basedir1 || file1, filePath1);
        const relPath2 = path.relative(basedir2 || file2, filePath2);
        patch[relPath2] = diff.structuredPatch(relPath1, relPath2, text1, text2, mtime1, mtime2);
        if ((stat1 && stat1.isDirectory()) || (stat2 && stat2.isDirectory())) {
          patch = { ...patch, ...createPatch(filePath1, filePath2, file1, file2) };
        }
      }
    } else {
      const text1 = fs.readFileSync(file1, 'utf8');
      const text2 = fs.readFileSync(file2, 'utf8');
      const mtime1 = getTimestamp(fs.statSync(file1).mtime);
      const mtime2 = getTimestamp(fs.statSync(file2).mtime);
      const relPath1 = path.relative(basedir1 || path.dirname(file1), file1);
      const relPath2 = path.relative(basedir2 || path.dirname(file2), file2);
      patch[relPath2] = diff.structuredPatch(relPath1, relPath2, text1, text2, mtime1, mtime2);
    }
  } catch (e) {
    console.error(e);
  }
  return patch;
};
github konstellation-io / science-toolkit / vscode / extensions / ms-vscode.go-0.13.0 / out / src / diffUtils.js View on Github external
function getEdits(fileName, oldStr, newStr) {
    if (process.platform === 'win32') {
        oldStr = oldStr.split('\r\n').join('\n');
        newStr = newStr.split('\r\n').join('\n');
    }
    const unifiedDiffs = jsDiff.structuredPatch(fileName, fileName, oldStr, newStr, '', '');
    const filePatches = parseUniDiffs([unifiedDiffs]);
    return filePatches[0];
}
exports.getEdits = getEdits;
github sompylasar / zmey-gorynych / bin / cli.js View on Github external
compareResult.diffs.forEach(function (diff) {
                if (diff.relativePath === 'package.json') {
                  diff.jsdiff = JsDiff.structuredPatch(
                    'package.json',
                    'package.json',
                    JSON.stringify(packageCtx.localInstallPackageJson, null, 2),
                    JSON.stringify(packageJsonBumped, null, 2),
                    '',
                    ''
                  );
                }
              });
github sompylasar / zmey-gorynych / bin / cli.js View on Github external
path2
                  ? path.relative(packageCtx.packageLocalPublishRootPath, path2)
                  : undefined
              )
          );
          if (!relativePath) {
            return {
              relativePath: undefined,
              jsdiff: undefined,
            };
          }
          var content1 = (path1 ? String(fs.readFileSync(path1)) : '');
          var content2 = (path2 ? String(fs.readFileSync(path2)) : '');
          return {
            relativePath: relativePath,
            jsdiff: JsDiff.structuredPatch(
              relativePath,
              relativePath,
              content1,
              content2,
              '',
              ''
            ),
          };
        }));