Skip to content

Commit b106376

Browse files
committed
hack: add a script to reformat the imports
add a helper script which reads the sort ordering expectation from our .golangci.yml (source of truth) and automatically constructs the recommended command line to run to conform. Also add Makefile targets to make the usage trivial: ``` $ make sort-imports ``` Depends on python3 and gci: https://github.com/daixiang0/gci Signed-off-by: Francesco Romani <[email protected]>
1 parent ccf0856 commit b106376

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Makefile

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -148,6 +148,18 @@ test-upgrade-e2e: build-e2e-all
148148
test-must-gather-e2e: build-must-gather-e2e
149149
hack/run-test-must-gather-e2e.sh
150150

151+
# intentional left out:
152+
# api/, because autogeneration
153+
# cmd/, because kubebuilder scaffolding
154+
.PHONY:
155+
sort-imports:
156+
@hack/sort-imports.py -v ./test/
157+
@hack/sort-imports.py -v ./internal/
158+
@hack/sort-imports.py -v ./pkg/
159+
@hack/sort-imports.py -v ./rte/
160+
@hack/sort-imports.py -v ./tools/
161+
@hack/sort-imports.py -v ./nrovalidate/
162+
151163
.PHONY: lint
152164
lint: update-buildinfo golangci-lint ## Run golangci-lint linter
153165
$(GOLANGCI_LINT) --verbose run --print-resources-usage --exclude-dirs test/internal/k8simported

hack/sort-imports.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
#!/usr/bin/env python
2+
3+
import argparse
4+
import os
5+
import subprocess
6+
import sys
7+
import yaml
8+
9+
10+
def make_gci_commandline(tree, ciconfig=".golangci.yml"):
11+
with open(ciconfig) as src:
12+
cfg = yaml.safe_load(src)
13+
try:
14+
sections = cfg['linters-settings']['gci']['sections']
15+
except KeyError:
16+
sys.stderr.write("cannot find gci configuration on %s\n" % ciconfig)
17+
sys.exit(2)
18+
cmdline = [
19+
"gci", "write", "--custom-order",
20+
]
21+
for sect in sections:
22+
cmdline.extend(("-s", sect))
23+
cmdline.append(tree)
24+
return cmdline
25+
26+
27+
def _main(args):
28+
cmdline = make_gci_commandline(args.tree)
29+
if args.verbose and not args.dry_run:
30+
sys.stderr.write("running: [%s]\n" % " ".join(cmdline))
31+
if args.dry_run:
32+
print(" ".join(cmdline))
33+
return
34+
subprocess.run(cmdline)
35+
36+
37+
if __name__ == "__main__":
38+
parser = argparse.ArgumentParser(
39+
prog='sort-imports.py',
40+
description='sort golang imports according to project standards delegating to gci')
41+
parser.add_argument('tree')
42+
parser.add_argument('-v', '--verbose', action='store_true')
43+
parser.add_argument('-D', '--dry-run', action='store_true')
44+
args = parser.parse_args()
45+
_main(args)

0 commit comments

Comments
 (0)