mirror of
https://github.com/opentffoundation/opentf.git
synced 2025-12-25 10:00:44 -05:00
command/views/json: Never generate invalid diagnostic snippet offsets
Because our snippet generator is trying to select whole lines to include in the snippet, it has some edge cases for odd situations where the relevant source range starts or ends directly at a newline, which were previously causing this logic to return out-of-bounds offsets into the code snippet string. Although arguably it'd be better for the original diagnostics to report more reasonable source ranges, it's better for us to report a slightly-inaccurate snippet than to crash altogether, and so we'll extend our existing range checks to check both bounds of the string and thus avoid downstreams having to deal with out-of-bounds indices. For completeness here I also added some similar logic to the human-oriented diagnostic formatter, which consumes the result of the JSON diagnostic builder. That's not really needed with the additional checks in the JSON diagnostic builder, but it's nice to reinforce that this code can't panic (in this way, at least) even if its input isn't valid.
This commit is contained in:
@@ -221,12 +221,23 @@ func NewDiagnostic(diag tfdiags.Diagnostic, sources map[string][]byte) *Diagnost
|
||||
// to the code snippet string.
|
||||
start := highlightRange.Start.Byte - codeStartByte
|
||||
end := start + (highlightRange.End.Byte - highlightRange.Start.Byte)
|
||||
if start > len(codeStr) {
|
||||
|
||||
// We can end up with some quirky results here in edge cases like
|
||||
// when a source range starts or ends at a newline character,
|
||||
// so we'll cap the results at the bounds of the highlight range
|
||||
// so that consumers of this data don't need to contend with
|
||||
// out-of-bounds errors themselves.
|
||||
if start < 0 {
|
||||
start = 0
|
||||
} else if start > len(codeStr) {
|
||||
start = len(codeStr)
|
||||
}
|
||||
if end > len(codeStr) {
|
||||
if end < 0 {
|
||||
end = 0
|
||||
} else if end > len(codeStr) {
|
||||
end = len(codeStr)
|
||||
}
|
||||
|
||||
diagnostic.Snippet.HighlightStartOffset = start
|
||||
diagnostic.Snippet.HighlightEndOffset = end
|
||||
|
||||
|
||||
Reference in New Issue
Block a user