Skip to content

Commit 090b6ba

Browse files
committed
update pre-commit
- add formatting check - add translations check
1 parent 3cbff45 commit 090b6ba

File tree

5 files changed

+3302
-5
lines changed

5 files changed

+3302
-5
lines changed

.github/workflows/build.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,6 @@ jobs:
4343
run: |
4444
gcc --version
4545
python3 --version
46-
- name: Translations
47-
run: make check-translate
4846
- name: New boards check
4947
run: python3 -u ci_new_boards_check.py
5048
working-directory: tools

.github/workflows/pre-commit.yml

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ name: pre-commit
77
on:
88
pull_request:
99
push:
10-
branches: [main]
1110

1211
jobs:
1312
pre-commit:
@@ -16,10 +15,13 @@ jobs:
1615
- uses: actions/checkout@v1
1716
- uses: actions/setup-python@v1
1817
- name: Install deps
19-
run: sudo apt-get update && sudo apt-get install -y gettext
18+
run: |
19+
sudo apt-add-repository -y -u ppa:pybricks/ppa
20+
sudo apt-get install -y black gettext uncrustify
21+
pip3 install polib
2022
- name: Populate selected submodules
2123
run: git submodule update --init extmod/ulab
22-
- name: set PY
24+
- name: Set PY
2325
run: echo >>$GITHUB_ENV PY="$(python -c 'import hashlib, sys;print(hashlib.sha256(sys.version.encode()+sys.executable.encode()).hexdigest())')"
2426
- uses: actions/cache@v2
2527
with:

.pre-commit-config.yaml

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,3 +11,16 @@ repos:
1111
exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*|ports/esp32s2/esp-idf-config/.*|ports/esp32s2/boards/.*/sdkconfig)'
1212
- id: trailing-whitespace
1313
exclude: '^(tests/.*\.exp|tests/cmdline/.*|tests/.*/data/.*)'
14+
- repo: local
15+
hooks:
16+
- id: translations
17+
name: Translations
18+
entry: sh -c "if ! make check-translate; then make translate; fi"
19+
types: [c]
20+
pass_filenames: false
21+
language: system
22+
- id: formatting
23+
name: Formatting
24+
entry: sh -c "git diff --staged --name-only | xargs python3 tools/codeformat.py"
25+
types_or: [c, python]
26+
language: system

tools/codeformat.py

Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
#!/usr/bin/env python3
2+
#
3+
# This file is part of the MicroPython project, http://micropython.org/
4+
#
5+
# The MIT License (MIT)
6+
#
7+
# Copyright (c) 2020 Damien P. George
8+
# Copyright (c) 2020 Jim Mussared
9+
#
10+
# Permission is hereby granted, free of charge, to any person obtaining a copy
11+
# of this software and associated documentation files (the "Software"), to deal
12+
# in the Software without restriction, including without limitation the rights
13+
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14+
# copies of the Software, and to permit persons to whom the Software is
15+
# furnished to do so, subject to the following conditions:
16+
#
17+
# The above copyright notice and this permission notice shall be included in
18+
# all copies or substantial portions of the Software.
19+
#
20+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
26+
# THE SOFTWARE.
27+
28+
import argparse
29+
import glob
30+
import itertools
31+
import os
32+
import re
33+
import subprocess
34+
35+
# Relative to top-level repo dir.
36+
PATHS = [
37+
# C
38+
"devices/**/*.[ch]",
39+
"drivers/bus/*.[ch]",
40+
"extmod/*.[ch]",
41+
"lib/netutils/*.[ch]",
42+
"lib/timeutils/*.[ch]",
43+
"lib/utils/*.[ch]",
44+
"mpy-cross/**/*.[ch]",
45+
"ports/**/*.[ch]",
46+
"py/**/*.[ch]",
47+
"shared-bindings/**/*.[ch]",
48+
"shared-module/**/*.[ch]",
49+
"supervisor/**/*.[ch]",
50+
# Python
51+
"extmod/*.py",
52+
"ports/**/*.py",
53+
"py/**/*.py",
54+
"tools/**/*.py",
55+
"tests/**/*.py",
56+
]
57+
58+
EXCLUSIONS = [
59+
# STM32 build includes generated Python code.
60+
"ports/*/build*",
61+
# gitignore in ports/unix ignores *.py, so also do it here.
62+
"ports/unix/*.py",
63+
# not real python files
64+
"tests/**/repl_*.py",
65+
# needs careful attention before applying automatic formatting
66+
"tests/basics/*.py",
67+
]
68+
69+
# Path to repo top-level dir.
70+
TOP = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
71+
72+
UNCRUSTIFY_CFG = os.path.join(TOP, "tools/uncrustify.cfg")
73+
74+
C_EXTS = (
75+
".c",
76+
".h",
77+
)
78+
PY_EXTS = (".py",)
79+
80+
81+
def list_files(paths, exclusions=None, prefix=""):
82+
files = set()
83+
for pattern in paths:
84+
files.update(glob.glob(os.path.join(prefix, pattern), recursive=True))
85+
for pattern in exclusions or []:
86+
files.difference_update(glob.fnmatch.filter(files, os.path.join(prefix, pattern)))
87+
return sorted(files)
88+
89+
90+
def fixup_c(filename):
91+
# Read file.
92+
with open(filename) as f:
93+
lines = f.readlines()
94+
95+
# Write out file with fixups.
96+
with open(filename, "w", newline="") as f:
97+
dedent_stack = []
98+
while lines:
99+
# Get next line.
100+
l = lines.pop(0)
101+
102+
# Dedent #'s to match indent of following line (not previous line).
103+
m = re.match(r"( +)#(if |ifdef |ifndef |elif |else|endif)", l)
104+
if m:
105+
indent = len(m.group(1))
106+
directive = m.group(2)
107+
if directive in ("if ", "ifdef ", "ifndef "):
108+
l_next = lines[0]
109+
indent_next = len(re.match(r"( *)", l_next).group(1))
110+
if indent - 4 == indent_next and re.match(r" +(} else |case )", l_next):
111+
# This #-line (and all associated ones) needs dedenting by 4 spaces.
112+
l = l[4:]
113+
dedent_stack.append(indent - 4)
114+
else:
115+
# This #-line does not need dedenting.
116+
dedent_stack.append(-1)
117+
else:
118+
if dedent_stack:
119+
if dedent_stack[-1] >= 0:
120+
# This associated #-line needs dedenting to match the #if.
121+
indent_diff = indent - dedent_stack[-1]
122+
assert indent_diff >= 0
123+
l = l[indent_diff:]
124+
if directive == "endif":
125+
dedent_stack.pop()
126+
127+
# Write out line.
128+
f.write(l)
129+
130+
assert not dedent_stack, filename
131+
132+
133+
def main():
134+
cmd_parser = argparse.ArgumentParser(description="Auto-format C and Python files.")
135+
cmd_parser.add_argument("-c", action="store_true", help="Format C code only")
136+
cmd_parser.add_argument("-p", action="store_true", help="Format Python code only")
137+
cmd_parser.add_argument("-v", action="store_true", help="Enable verbose output")
138+
cmd_parser.add_argument("files", nargs="*", help="Run on specific globs")
139+
args = cmd_parser.parse_args()
140+
141+
# Setting only one of -c or -p disables the other. If both or neither are set, then do both.
142+
format_c = args.c or not args.p
143+
format_py = args.p or not args.c
144+
145+
# Expand the globs passed on the command line, or use the default globs above.
146+
files = []
147+
if args.files:
148+
files = list_files(args.files)
149+
else:
150+
files = list_files(PATHS, EXCLUSIONS, TOP)
151+
152+
# Extract files matching a specific language.
153+
def lang_files(exts):
154+
for file in files:
155+
if os.path.splitext(file)[1].lower() in exts:
156+
yield file
157+
158+
# Run tool on N files at a time (to avoid making the command line too long).
159+
def batch(cmd, files, N=200):
160+
while True:
161+
file_args = list(itertools.islice(files, N))
162+
if not file_args:
163+
break
164+
subprocess.call(cmd + file_args)
165+
166+
# Format C files with uncrustify.
167+
if format_c:
168+
command = ["uncrustify", "-c", UNCRUSTIFY_CFG, "-lC", "--no-backup"]
169+
if not args.v:
170+
command.append("-q")
171+
batch(command, lang_files(C_EXTS))
172+
for file in lang_files(C_EXTS):
173+
fixup_c(file)
174+
# Revert "// |" back to "//|"
175+
subprocess.call(
176+
"find shared-bindings ports/*/bindings -name '*.c' -exec sed -i 's/\/ |/\/|/' {} \;",
177+
shell=True,
178+
)
179+
180+
# Format Python files with black.
181+
if format_py:
182+
command = ["black", "--fast", "--line-length=99"]
183+
if args.v:
184+
command.append("-v")
185+
else:
186+
command.append("-q")
187+
batch(command, lang_files(PY_EXTS))
188+
189+
190+
if __name__ == "__main__":
191+
main()

0 commit comments

Comments
 (0)