Skip to content

diff.Diff() with an empty value produces one blank line #22

Open

Description

@thockin

I have a series of blobs to diff, each against the previous. The seed is an empty string. Diffing the first blob against that produces a diff with one "removed" line.

-
+{
+  "apiVersion": "v1",
+  "kind": "Service",
+  "metadata": {

Activity

  1. kylelemons commented on Aug 24, 2019

    @kylelemons
    Owner

    Hmm, yeah that is unfortunate. I think this would be too big of a behavior change for a minor version update, however.

    The reason for this is that Diff is comparing lines from A to lines in B by splitting on \n, so there is no way to get Diff to compare against zero lines on one of its sides.

    To help improve this situation, I've exported Render which can be used directly on the output of DiffChunks, so that you can control this behavior yourself. For example, you could make a helper like this:

    func diffWithEmpty(a, b string) string {
      var aLines, bLines []string
      if a != "" {
        aLines = strings.Split(a, "\n")
      }
      if b != "" {
        bLines = strings.Split(b, "\n")
      }
      return diff.Render(diff.DiffChunks(aLines, bLines))
    }

    to get the behavior you're looking for.

    For the moment, this is only exposed by github.com/kylelemons/godebug@master if you are using go modules; let me know if this works for you, and I can cut a new module release.

    I also highly recommend the cmp package if you are comparing structures, as it actually does proper recursive descent instead of stringifying everything before running a string-based diff algorithm.

  2. thockin commented on Aug 30, 2019

    @thockin
    Author

    This was not a critical issue for me, so frankly I probably won't update or change what we're doing. I thought it was worth filing a bug, but it sounds like it's not something you want to "break" (though IMO that's debatable, but I admire the dedication to not breaking people :).

    Thanks for a great and simple lib that (mostly) just works.

  3. added
    breaking_change
    on Aug 30, 2020
  4. added 2 commits that reference this issue on Apr 14, 2026
    2ab5364
    35218c0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    breaking_change

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions