location.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package detect
  2. // Location represents a location in a file
  3. type Location struct {
  4. startLine int
  5. endLine int
  6. startColumn int
  7. endColumn int
  8. startLineIndex int
  9. endLineIndex int
  10. }
  11. func location(fragment Fragment, matchIndex []int) Location {
  12. var (
  13. prevNewLine int
  14. location Location
  15. lineSet bool
  16. _lineNum int
  17. )
  18. start := matchIndex[0]
  19. end := matchIndex[1]
  20. for lineNum, pair := range fragment.newlineIndices {
  21. newLineByteIndex := pair[0]
  22. if prevNewLine <= start && start < newLineByteIndex {
  23. lineSet = true
  24. location.startLine = lineNum
  25. location.endLine = lineNum
  26. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  27. location.startLineIndex = prevNewLine
  28. location.endLineIndex = newLineByteIndex
  29. }
  30. if prevNewLine < end && end <= newLineByteIndex {
  31. location.endLine = lineNum
  32. location.endColumn = (end - prevNewLine)
  33. location.endLineIndex = newLineByteIndex
  34. }
  35. prevNewLine = pair[0]
  36. }
  37. if !lineSet {
  38. // if lines never get set then that means the secret is most likely
  39. // on the last line of the diff output and the diff output does not have
  40. // a newline
  41. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  42. location.endColumn = (end - prevNewLine)
  43. location.startLine = _lineNum + 1
  44. location.endLine = _lineNum + 1
  45. location.startLineIndex = start
  46. // search for new line byte index
  47. i := 0
  48. for end+i < len(fragment.Raw) {
  49. if fragment.Raw[end+i] == '\n' {
  50. break
  51. }
  52. if fragment.Raw[end+i] == '\r' {
  53. break
  54. }
  55. i++
  56. }
  57. location.endLineIndex = end + i
  58. }
  59. return location
  60. }