location.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. _lineNum = lineNum
  22. newLineByteIndex := pair[0]
  23. if prevNewLine <= start && start < newLineByteIndex {
  24. lineSet = true
  25. location.startLine = lineNum
  26. location.endLine = lineNum
  27. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  28. location.startLineIndex = prevNewLine
  29. location.endLineIndex = newLineByteIndex
  30. }
  31. if prevNewLine < end && end <= newLineByteIndex {
  32. location.endLine = lineNum
  33. location.endColumn = (end - prevNewLine)
  34. location.endLineIndex = newLineByteIndex
  35. }
  36. prevNewLine = pair[0]
  37. }
  38. if !lineSet {
  39. // if lines never get set then that means the secret is most likely
  40. // on the last line of the diff output and the diff output does not have
  41. // a newline
  42. location.startColumn = (start - prevNewLine) + 1 // +1 because counting starts at 1
  43. location.endColumn = (end - prevNewLine)
  44. location.startLine = _lineNum + 1
  45. location.endLine = _lineNum + 1
  46. location.startLineIndex = start
  47. // search for new line byte index
  48. i := 0
  49. for end+i < len(fragment.Raw) {
  50. if fragment.Raw[end+i] == '\n' {
  51. break
  52. }
  53. if fragment.Raw[end+i] == '\r' {
  54. break
  55. }
  56. i++
  57. }
  58. location.endLineIndex = end + i
  59. }
  60. return location
  61. }