How to use the diff.createTwoFilesPatch 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 sourcegraph / sourcegraph / web / src / enterprise / expCampaigns / backend / computeDiff.ts View on Github external
})
            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,
                }),
            })
            const dt = Date.now() - t0
            if (dt > 1000) {
                console.warn(
                    `Computing diff took ${dt}msec for ${uri.toString()} (old ${oldText.length /
                        1024}kb, new ${newText.length / 1024}kb)`
                )
            }
        }
    }
    return fileDiffs
}
github tapjs / node-tap / lib / clean-yaml-object.js View on Github external
else if (f && w && typeof f === 'object' && typeof w === 'object') {
      const s = strict(f, w)
      if (!s.match)
        res.diff = s.diff
      else
        res.note = 'object identities differ'
    } else {
      // some mixed stringly bits
      // XXX tcompare needs better string diffs
      const ff = format(f)
      const fw = format(w)
      const fs = (typeof f === 'string' ? f : ff) + '\n'
      const ws = (typeof w === 'string' ? w : fw) + '\n'
      /* istanbul ignore else - impossible without bug in tcompare */
      if (fw !== ff)
        res.diff = diff.createTwoFilesPatch('expected', 'actual', ws, fs)
          .replace(/^=+\n/, '')
      else
        res.note = 'object identities differ'
    }
    if (res.diff === '--- expected\n+++ actual\n')
      delete res.diff
    if (res.diff) {
      delete res.found
      delete res.wanted
    }
  }

  for (const [key, value] of Object.entries(res)) {
    if (key === 'todo' ||
        key === 'time' ||
        /^_?tapChild/.test(key) ||
github sourcegraph / sourcegraph / web / src / enterprise / expCampaigns / backend / computeDiff.ts View on Github external
`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
                patchWithFullURIs: createTwoFilesPatch(uri, uri, oldText, newText, undefined, undefined, {
                    context: 2,
                }),
            })
            const dt = Date.now() - t0
            if (dt > 1000) {
                console.warn(
                    `Computing diff took ${dt}msec for ${uri.toString()} (old ${oldText.length /
github vpdb / server / src / app / comments / comment.api.ts View on Github external
releaseId = comment._ref.release || comment._ref.release_moderation;

				// assert own permissions
				const isModerator = await acl.isAllowed(ctx.state.user.id, 'releases', 'moderate');
				if (!isModerator && !ctx.state.user._id.equals(comment._from)) {
					throw new ApiError('Access denied, must be moderator or owner.').status(403);
				}

				/* istanbul ignore next: doesn't happen in tests because there is no previous data. */
				if (!comment.edits) {
					comment.edits = [];
				}
				comment.edits.push({
					_edited_by: ctx.state.user._id.toString(),
					edited_at: new Date(),
					diff: createTwoFilesPatch('before', 'after', comment.message, ctx.request.body.message),
				});
				comment.message = ctx.request.body.message;
			}

			// save
			await comment.save();
			if (updates.length > 0) {
				await Promise.all(updates.map(u => u()));
			}

			// return
			const updatedComment = await state.models.Comment.findById(comment._id)
				.populate('_from')
				.populate('_ref.release')
				.populate('_ref.release_moderation')
				.exec();
github tapjs / node-tap / lib / clean-yaml-object.js View on Github external
.concat(lines.slice(res.at.line, endLine))
        const csplit = context.join('\n').trimRight()
        if (csplit)
          res.source = csplit + '\n'
      }
    }
  }

  // show a line by line string diff
  // diff the yaml, to make it more humane, especially
  // when strings or buffers are very large or multi-line
  if (res.found && res.wanted && res.found !== res.wanted && !res.diff) {
    const f = res.found
    const w = res.wanted
    if (typeof f === 'string' && typeof w === 'string')
      res.diff = diff.createTwoFilesPatch('expected', 'actual', w + '\n', f + '\n')
        .replace(/^=+\n/, '')
    else if (f && w && typeof f === 'object' && typeof w === 'object') {
      const s = strict(f, w)
      if (!s.match)
        res.diff = s.diff
      else
        res.note = 'object identities differ'
    } else {
      // some mixed stringly bits
      // XXX tcompare needs better string diffs
      const ff = format(f)
      const fw = format(w)
      const fs = (typeof f === 'string' ? f : ff) + '\n'
      const ws = (typeof w === 'string' ? w : fw) + '\n'
      /* istanbul ignore else - impossible without bug in tcompare */
      if (fw !== ff)
github josephfrazier / prettier-diff / index.js View on Github external
let toPretty = toContent

  // try to format JS files
  try {
    fromPretty = prettier.format(fromContent, prettierOptions)
    toPretty = prettier.format(toContent, prettierOptions)
  } catch (err) {}

  // try to format JSON files
  // prettier doesn't do this currently: https://github.com/prettier/prettier/issues/322
  try {
    fromPretty = jsonPrettify(fromContent)
    toPretty = jsonPrettify(toContent)
  } catch (err) {}

  const patch = diff.createTwoFilesPatch(
    fromPath,
    toPath,
    fromPretty,
    toPretty
  )

  return {fromPretty, toPretty, patch}
}
github ethers-io / ethers.js / admin / index.js View on Github external
async function updateChangelog() {
    let filename = resolve(local.ROOT, "../CHANGELOG.md");

    let lastVersion = await git.getLatestTag();
    let newVersion = "v" + local.getVersion("ethers");

    let current = fs.readFileSync(filename).toString();
    let log = await changelog.generate();
    if (log === current) { return; }

    let changes = diff.createTwoFilesPatch("CHANGELOG-old.md", "CHANGELOG.md", current, log, lastVersion, newVersion);
    console.log(changes);

    try {
        let response = await prompt.getChoice(colorify("Accept changes?", "bold"), "yn", "n");
        if (response === "n") { throw new Error("Not changing."); }
    } catch (error) {
        console.log("Abort: " + error.message);
        return;
    }

    fs.writeFileSync(filename, log);
}
github mozilla-releng / balrog / ui / src / components / DiffRelease / diff.worker.js View on Github external
onmessage = e => {
  const [
    firstFilename,
    secondFilename,
    firstReleaseString,
    secondReleaseString,
  ] = e.data;
  const releaseDiff = createTwoFilesPatch(
    firstFilename,
    secondFilename,
    firstReleaseString,
    secondReleaseString
  );

  postMessage(releaseDiff);
};
github gitlabhq / gitlabhq / app / assets / javascripts / ide / lib / create_file_diff.js View on Github external
const createUpdateFileDiff = (path, oldContent, newContent) => {
  const patch = createTwoFilesPatch(`a/${path}`, `b/${path}`, oldContent, newContent);

  return `${diffHead(path)}
${cleanTwoFilesPatch(patch)}`;
};
github brodybits / prettierx / src / cli / util.js View on Github external
function diff(a, b) {
  return require("diff").createTwoFilesPatch("", "", a, b, "", "", {
    context: 2
  });
}