Skip to content

Commit 4a6b7cf

Browse files
authored
Don't lint a shebang as a comment (#1134)
Tree-sitter reports the `#!` line of a script as a comment, because in Python, Ruby and Julia that is exactly what it looks like. Vale then lints the interpreter path as prose, so `#!/usr/bin/env python3` draws an alert about 'env' that the author has no way to act on. Drop a comment that starts at the first byte of the file and begins with `#!`, which is also all the kernel accepts as a shebang, so a `#!` written anywhere else stays a comment. Fixes #631
1 parent 77179c0 commit 4a6b7cf

2 files changed

Lines changed: 46 additions & 1 deletion

File tree

‎internal/lint/code/comments.go‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,5 +149,26 @@ func GetComments(source []byte, lang *Language) ([]Comment, error) {
149149
})
150150
}
151151

152-
return coalesce(comments), nil
152+
return coalesce(dropShebang(comments)), nil
153+
}
154+
155+
// dropShebang removes a leading `#!` line.
156+
//
157+
// A shebang names the interpreter a script runs under. Languages that use `#`
158+
// for comments give tree-sitter no way to tell the two apart, so it arrives
159+
// here as a comment and is linted as prose -- a path like `/usr/bin/env` then
160+
// draws alerts about words the author never wrote. See #631.
161+
//
162+
// Only the very first line of the file qualifies, which is also all the kernel
163+
// accepts, so a `#!` written anywhere else stays a comment.
164+
func dropShebang(comments []Comment) []Comment {
165+
for i, c := range comments {
166+
if c.Line != 1 || c.Offset != 0 {
167+
continue
168+
} else if !strings.HasPrefix(c.Source, "#!") {
169+
continue
170+
}
171+
return append(comments[:i:i], comments[i+1:]...)
172+
}
173+
return comments
153174
}

‎testdata/e2e/lint.yaml‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,30 @@ cases:
148148
test.py:35:8:vale.Annotations:'NOTE' left in text
149149
test.py:37:5:vale.Annotations:'TODO' left in text
150150
151+
- name: python/shebang
152+
about: "#631 -- a shebang names an interpreter, so it isn't a comment"
153+
files:
154+
.vale.ini: |
155+
StylesPath = styles
156+
MinAlertLevel = suggestion
157+
158+
[*.py]
159+
BasedOnStyles = Test
160+
styles/Test/Env.yml: |
161+
extends: existence
162+
message: "Use 'environment' rather than 'env'."
163+
level: error
164+
tokens:
165+
- env
166+
test.py: |
167+
#!/usr/bin/env python3
168+
# Read the env before starting.
169+
print("hello")
170+
args: test.py
171+
exit: 1
172+
want: |
173+
test.py:2:12:Test.Env:Use 'environment' rather than 'env'.
174+
151175
- name: cpp
152176
args: test.cc
153177
exit: 0

0 commit comments

Comments
 (0)