I Created My Own Diff CLI in Go!


I recently tackled one of John Crickett's challenges: creating my own diff
tool. It was a pleasant learning and problem-solving experience.
The most enjoyable part for me was implementing the context lines feature, so I will focus on that. While implementing the LCS (Longest Common Subsequence) algorithm was more research oriented, it was equally rewarding.
The Challenge with Context Lines
Adding context lines wasn't a requirement of the challenge, but I was curious and decided to include it.
Initially, I thought I could calculate the context lines for each change independently. However, this approach failed when consecutive changes were closer than the context interval. For example, consider these changes:
- Change at line 1
- Change at line 3
With a context depth of 2, the context for each change would be:
- Line 1:
ctxstart=0
,ctxend=3
- Line 3:
ctxstart=1
,ctxend=6
Using my initial approach, I would display lines 0-3
for the first change. For the second change, the ctxstart
would need to be at least 4
to avoid duplicate context lines. This would result in the context for line 3 being 4-6
, which skips the actual change at line 3. Clearly, this wasn't the right approach.
The Solution: Merging Overlapping Indices
To solve this, I decided to merge overlapping indices. In the example above, the context lines for line 1 and line 3 overlap, so the combined context should be 0-6
. This ensures no information is lost.
It took a few unit tests to get it working correctly, but the result was worth it.
Your Thoughts?
How would you solve this problem? Do you have a better approach?
BTW, did you notice? This story is short. 😄