Debian Codegraph @

.gitlab-ci/check-style.py

raw symbols SCIP
1 #!/bin/env python3
2 #
3 # Based on check-style.py by
4 # Carlos Garnacho <[email protected]>
5
6 import argparse
7 import os
8 import re
9 import subprocess
10 import sys
11 import tempfile
12
13 # Path relative to this script
14 uncrustify_cfg = ".gitlab-ci/uncrustify.cfg"
15
16
17 def run_diff(sha):
18 proc = subprocess.run(
19 ["git", "diff", "-U0", "--function-context", sha, "HEAD"],
20 stdout=subprocess.PIPE,
21 stderr=subprocess.STDOUT,
22 encoding="utf-8",
23 )
24 return proc.stdout.strip().splitlines()
25
26
27 def find_chunks(diff):
28 file_entry_re = re.compile(r"^\+\+\+ b/(.*)$")
29 diff_chunk_re = re.compile(r"^@@ -\d+,\d+ \+(\d+),(\d+)")
30 file = None
31 chunks = []
32
33 for line in diff:
34 match = file_entry_re.match(line)
35 if match:
36 file = match.group(1)
37
38 match = diff_chunk_re.match(line)
39 if match:
40 start = int(match.group(1))
41 len = int(match.group(2))
42 end = start + len
43
44 if len > 0 and (
45 file.endswith(".c") or file.endswith(".h") or file.endswith(".vala")
46 ):
47 chunks.append({"file": file, "start": start, "end": end})
48
49 return chunks
50
51
52 def reformat_chunks(chunks, rewrite, dry_run):
53 # Creates temp file with INDENT-ON/OFF comments
54 def create_temp_file(file, start, end):
55 with open(file) as f:
56 tmp = tempfile.NamedTemporaryFile()
57 if start > 1:
58 tmp.write(b"/** *INDENT-OFF* **/\n")
59 for i, line in enumerate(f, start=1):
60 if i == start - 1:
61 tmp.write(b"/** *INDENT-ON* **/\n")
62
63 tmp.write(bytes(line, "utf-8"))
64 if i == end - 1:
65 tmp.write(b"/** *INDENT-OFF* **/\n")
66 tmp.seek(0)
67 return tmp
68
69 # Removes uncrustify INDENT-ON/OFF helper comments
70 def remove_indent_comments(output):
71 tmp = tempfile.NamedTemporaryFile()
72 for line in output:
73 if line != b"/** *INDENT-OFF* **/\n" and line != b"/** *INDENT-ON* **/\n":
74 tmp.write(line)
75
76 tmp.seek(0)
77 return tmp
78
79 changed = None
80 for chunk in chunks:
81 # Add INDENT-ON/OFF comments
82 tmp = create_temp_file(chunk["file"], chunk["start"], chunk["end"])
83
84 # uncrustify chunk
85 proc = subprocess.run(
86 ["uncrustify", "-c", uncrustify_cfg, "-f", tmp.name],
87 stdout=subprocess.PIPE,
88 )
89 reindented = proc.stdout.splitlines(keepends=True)
90 if proc.returncode != 0:
91 continue
92
93 tmp.close()
94
95 # Remove INDENT-ON/OFF comments
96 formatted = remove_indent_comments(reindented)
97
98 if dry_run is True:
99 # Show changes
100 proc = subprocess.run(
101 ["diff", "-up", "--color=always", chunk["file"], formatted.name],
102 stdout=subprocess.PIPE,
103 stderr=subprocess.STDOUT,
104 encoding="utf-8",
105 )
106 diff = proc.stdout
107 if diff != "":
108 output = re.sub("\t", "↦\t", diff)
109 print(output)
110 changed = True
111 else:
112 # Apply changes
113 diff = subprocess.run(
114 ["diff", "-up", chunk["file"], formatted.name],
115 stdout=subprocess.PIPE,
116 stderr=subprocess.STDOUT,
117 )
118 subprocess.run(["patch", chunk["file"]], input=diff.stdout)
119
120 formatted.close()
121
122 return changed
123
124
125 def main(argv):
126 parser = argparse.ArgumentParser(
127 description="Check code style. Needs uncrustify installed."
128 )
129 parser.add_argument(
130 "--sha", metavar="SHA", type=str, help="SHA for the commit to compare HEAD with"
131 )
132 parser.add_argument(
133 "--dry-run",
134 "-d",
135 type=bool,
136 action=argparse.BooleanOptionalAction,
137 help="Only print changes to stdout, do not change code",
138 )
139 parser.add_argument(
140 "--rewrite",
141 "-r",
142 type=bool,
143 action=argparse.BooleanOptionalAction,
144 help="Whether to amend the result to the last commit (e.g. 'git rebase --exec \"%(prog)s -r\"')",
145 )
146
147 if not os.path.exists(".git"):
148 print("Not in toplevel of a git repository", fille=sys.stderr)
149 return 1
150
151 args = parser.parse_args(argv)
152 sha = args.sha or "HEAD^"
153
154 diff = run_diff(sha)
155 chunks = find_chunks(diff)
156 changed = reformat_chunks(chunks, args.rewrite, args.dry_run)
157
158 if args.dry_run is not True and args.rewrite is True:
159 proc = subprocess.run(["git", "add", "-p"])
160 if proc.returncode == 0:
161 # Commit the added changes as a squash commit
162 subprocess.run(
163 ["git", "commit", "--squash", "HEAD", "-C", "HEAD"],
164 stdout=subprocess.DEVNULL,
165 )
166 # Delete the unapplied changes
167 subprocess.run(["git", "reset", "--hard"], stdout=subprocess.DEVNULL)
168 return 0
169 elif args.dry_run is True and changed is True:
170 print(
171 f"""
172 Issue the following commands in your local tree to apply the suggested changes:
173
174 $ git rebase {sha} --exec "./.gitlab-ci/check-style.py -r"
175 $ git rebase --autosquash {sha}
176
177 Don't trust uncrustify unconditionally.
178 """
179 )
180 return 1
181 return 0
182
183
184 if __name__ == "__main__":
185 sys.exit(main(sys.argv[1:]))