Create unified diff text for diff2html in browser
Asked Answered
K

1

7

Is there a library that produces unified diff from two strings that diff2html can use? I've tried difflib but the output does not seem to fit the requirements that diff2html needs. I need a .js library I can import in the webpage to produce diffs between JSONs.

Tried to play around with the lineterm parameter but was not able to get the tool to work. If I use the string in the docs as an example, then it works:

--- a/server/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go\n+++ b/server/vendor/golang.org/x/sys/unix/zsyscall_linux_mipsle.go\n@@ -1035,6 +1035,17 @@ func Prctl(option int, arg2 uintptr, arg3 uintptr, arg4 uintptr, arg5 uintptr) (\n \n // THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n \n+func Pselect(nfd int, r *FdSet, w *FdSet, e *FdSet, timeout *Timespec, sigmask *Sigset_t) (n int, err error) {\n+\tr0, _, e1 := Syscall6(SYS_PSELECT6, uintptr(nfd), uintptr(unsafe.Pointer(r)), uintptr(unsafe.Pointer(w)), uintptr(unsafe.Pointer(e)), uintptr(unsafe.Pointer(timeout)), uintptr(unsafe.Pointer(sigmask)))\n+\tn = int(r0)\n+\tif e1 != 0 {\n+\t\terr = errnoErr(e1)\n+\t}\n+\treturn\n+}\n+\n+// THIS FILE IS GENERATED BY THE COMMAND AT THE TOP; DO NOT EDIT\n+\n func read(fd int, p []byte) (n int, err error) {\n \tvar _p0 unsafe.Pointer\n \tif len(p) > 0 {\n

But couldn't get any output of difflib to produce anything in diff2html.

Kalli answered 22/2, 2019 at 11:48 Comment(0)
K
28

Ended up using jsdiff.

var diff = Diff.createTwoFilesPatch("file", "file", oldText, newText);

so that it can then be used with diff2html like this:

Diff2Html.getPrettyHtml(diff,
    {inputFormat: 'diff', showFiles: false, matching: 'lines', outputFormat: 'side-by-side'}
);
Kalli answered 25/2, 2019 at 9:33 Comment(1)
hey thanks for this answer, I also want to create a patch for a new file and I'm not sure if jsdiff supports this since its main purpose is to compare files. However I came up with this string replace (and yes it works but it's very hacky): Diff.createPatch('file', '', text2Ref.value).replace('--- file', 'diff --git a/file b/file\nnew file mode 100000 \n--- file'); do anyone have a better way of making patch to show as new file in diff2html?Sanctify

© 2022 - 2024 — McMap. All rights reserved.