Skip to content

Commit 3c9fbcb

Browse files
Filename and Go Mod Tidy checks (#316)
* Add go filename lint like api and go mod tidy * Rename files to conform to linting checks * shfmt GitOrigin-RevId: ab4cf636a69decd55c6b429e4d6d081cf8e09c6c
1 parent 537ceb7 commit 3c9fbcb

4 files changed

Lines changed: 53 additions & 0 deletions

File tree

bin/lint-go-filenames.sh

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
#!/usr/bin/env bash
2+
#
3+
# Checks that the given files conform to our Go file naming conventions.
4+
# Accepts filenames. Directories are recursively traversed for files.
5+
# If no arguments are given, the script defaults to the repo root, i.e.
6+
# checks all files in the repo.
7+
#
8+
# Filenames which do not conform to our conventions are printed.
9+
# Exits with status 1 if any files do not conform; otherwise, 0.
10+
11+
set -o errexit -o nounset -o pipefail
12+
shopt -s extglob
13+
14+
# Go filenames should be lowercase without underscores except for some exceptions
15+
files=("$@")
16+
if [[ ${#files[@]} -eq 0 ]]; then
17+
files=("$(git rev-parse --show-toplevel)")
18+
fi
19+
20+
# these directories are excepted from linting
21+
dir_exceptions=(
22+
third_party # we don't control 3rd party
23+
)
24+
25+
check_go_file_has_no_invalid_chars() {
26+
local filename=$1
27+
if [[ $filename != *.go ]]; then
28+
return
29+
fi
30+
for dir in "${dir_exceptions[@]}"; do
31+
if [[ $filename =~ $dir/* ]]; then
32+
return
33+
fi
34+
done
35+
local basename
36+
basename=$(basename "$filename" .go)
37+
basename=${basename%%_@(test|internal_test|integration_test|gen|generated.deepcopy|rbac|darwin|linux|windows|amd64|arm64)} # remove accepted suffixes
38+
if [[ $basename == *[^a-z0-9]* ]]; then
39+
echo "$filename"
40+
return 1
41+
fi
42+
}
43+
44+
exit_code=0
45+
while read -r filename; do
46+
if ! check_go_file_has_no_invalid_chars "$filename"; then
47+
exit_code=1
48+
fi
49+
done < <(git ls-files -c -m "${files[@]}")
50+
51+
exit $exit_code

prek.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ hooks = [
2929
repo = "local"
3030
hooks = [
3131
{ id = "shfmt", name = "shfmt", entry = "shfmt -l -w -i 2 -bn -ci -sr", language = "system", files = "\\.sh$", priority = 10 },
32+
{ id = "go-mod-tidy", name = "go mod tidy", entry = "go mod tidy", language = "system", pass_filenames = false, files = "\\.(go|mod|sum)$", priority = 10 },
3233
]
3334

3435
# Linters (priority 20 = run last, after formatting)
@@ -43,4 +44,5 @@ hooks = [
4344
repo = "local"
4445
hooks = [
4546
{ id = "shellcheck", name = "shellcheck", entry = "shellcheck", language = "system", types = ["shell"], priority = 20 },
47+
{ id = "go-filenames", name = "go filenames", entry = "bin/lint-go-filenames.sh", language = "script", files = "\\.go$", priority = 20 },
4648
]

0 commit comments

Comments
 (0)