Search code examples
gitdiffgit-diff

Is there a way to tell git which lines to treat as modified in the diff?


I've modified a file (in Ruby, as it happens, but my question is really about Git) by moving a method up the file. Here's a pseudo-diff:

class A
  # some stuff

+ def b
+ end
+
  private

  def a
  end
- 
- def b
- end
end

However, git insists on framing this change as:

class A
  # some stuff
 
- private
-
- def a
- end
-
  def b
  end
+
+ private
+
+ def a
+ end
end

ie. it sees the private keyword and method a as having moved down instead.

This is equally correct in terms of describing how the file changed, but it doesn't convey the intent of the change nearly as well. It's potentially a bit confusing even: the result of the change is to make method b a public method, but this diff makes it look as if it was method a that has changed.

I think Git has chosen this diff because method a is slightly shorter than method b, so this ends up producing a slightly smaller diff. However, in terms of making my commit easily comprehensible it would be preferable if the diff looked more like the first example here, to make it clear that the relevant change was to method b.

My question is: is there any way of manually editing the hunks that Git has chosen when I stage this change, so I can create a commit whose diff looks like the first example rather than the second one?


Solution

  • My question is: is there any way of manually editing the hunks that Git has chosen when I stage this change, so I can create a commit whose diff looks like the first example rather than the second one?

    No; commits do not store diffs, they store snapshots of the file(s) at a current point in time. So you cannot "create a commit" whose diff looks a certain way; instead, the diff is created instantaneously, when you view it.

    That means that each git client, when it views your commit, would need to understand how to display the diff to your liking. There is no such mechanism to tell git clients how you would prefer it to be seen.

    There are a variety of options that the viewer of your commit can use to indicate how they want to see the change, but there is no mechanism that you can use to tell them how you want them to see the change.