.github/workflows/check-imports-format.sh
89 lines · 1806 bytes · executable
1#!/bin/sh
2
3while [ $# -gt 0 ]; do
4 # check that all imports for a `use` statement come from the same module
5 import_error=$(sed -n "
6 # only consider use statements with braces
7 /^ *use .*{/ {
8 # load the import until the first closing brace into the pattern space
9 :find-close
10 /^[^}]*$/ {
11 N
12 b find-close
13 }
14
15 # show error if multiple braces exist
16 /{.*{/ {
17 i\\
18invalid import in '$1' line:
19 =
20 i\\
21containing multiple braces in one import:
22 p
23 b
24 }
25
26 # show error if qualified paths exist inside braces
27 /{.*::/ {
28 i\\
29invalid import in '$1' line:
30 =
31 i\\
32containing a qualified import inside braces:
33 p
34 b
35 }
36 }
37 " "$1")
38 if [ -n "$import_error" ]; then
39 printf "%s\n" "$import_error"
40 exit 1
41 fi
42
43 # check that imports are sorted as `std`, `other imports`, `crate` each seperated by a blank line
44 import_pattern=$(sed -n "
45 # include blank lines
46 /^$/ {
47 p
48 d
49 }
50 # include std imports
51 /^use std::/ {
52 i\\
53use std
54 d
55 }
56 # include crate imports
57 /^use crate::/ {
58 i\\
59use crate
60 d
61 }
62 # include other imports without the target
63 s/^use .*/use/p
64 " "$1" | uniq | tr "\n" "_") # remove duplicates; we only care for the order of the imports; also grep doesn't play nice with line breaks
65
66 # check that the pattern if followed
67 printf "%s" "$import_pattern" | grep -q "^_\?\(use std__\)\?\(use__\)\?\(use crate__\)\?_\?$"
68 if [ $? -ne 0 ]; then
69 printf "imports in '%s' dont follow the pattern:
70\`\`\`
71use std::*;
72
73use *;
74
75use crate::*;
76
77\`\`\`
78
79instead is has the pattern:
80\`\`\`
81%s
82\`\`\`
83" "$1" "$import_pattern" | tr "_" "\n" >&2
84 exit 1
85 fi
86
87
88 shift
89done