Skip to content

Add old and new lines numbers to the Line of TextFragment #53

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed

Add old and new lines numbers to the Line of TextFragment #53

wants to merge 1 commit into from

Conversation

oneumyvakin
Copy link

Hello @bluekeyes , thank you for your work and go-gitdiff package! I'm going to use your package in CI/CD to add comments on lines of changed source code. And to do this I need to know line numbers in git diff.
Feel free to provide any feedback to improve the PR!

@bluekeyes
Copy link
Owner

Thanks for checking out the library! Is there a reason these line numbers need to be part of the gitdiff.Line struct?

Right now, I don't think this is something I'd add to library. One of the design goals is to keep the structures as close to the patch as possible, basically only storing information that is directly encoded to or decoded from the patch text. These line numbers are computed from other information, which means I think you could solve this in your application. Extracting the logic you added here might give something like:

type NumberedLine struct {
	gitdiff.Line
	OldLineNo int64
	NewLineNo int64
}

func NumberLines(frag *gitdiff.TextFragment) []NumberedLine {
	oldLineNo := int64(0)
	newLineNo := int64(0)
	if frag.OldPosition > 0 {
		oldLineNo = frag.OldPosition - 1
	}
	if frag.NewPosition > 0 {
		newLineNo = frag.NewPosition - 1
	}

	lines := make([]NumberedLines, len(frag.Lines))
	for i, line := range frag.Lines {
		switch line.Op {
		case gitdiff.OpContext:
			oldLineNo++
			newLineNo++
		case gitdiff.OpDelete:
			oldLineNo++
		case gitdiff.OpAdd:
			newLineNo++
		}
		lines[i] = NumberedLine{Line: line, OldLineNo: oldLineNo, NewLineNo: newLineNo}
	}
	return lines
}

Depending on what you're doing, you may need additional wrappers or helpers, but I'd encourage you to try a solution that embeds or composes the gitdiff types with your own types to achieve the information you need.

@oneumyvakin
Copy link
Author

@bluekeyes Indeed! I believe it's better! Thank you, for providing complete solution, really appreciated!

@oneumyvakin oneumyvakin deleted the add-lines-numbers-to-line branch December 11, 2024 07:32
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants