Skip to content

Commit 4b43cdd

Browse files
committed
try pre-commit
1 parent 0240195 commit 4b43cdd

File tree

3 files changed

+92
-45
lines changed

3 files changed

+92
-45
lines changed

.pre-commit-config.yaml

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
repos:
2+
- repo: https://github.com/pre-commit/pre-commit-hooks
3+
rev: v3.2.0
4+
hooks:
5+
- id: trailing-whitespace
6+
- id: end-of-file-fixer
7+
- id: check-yaml
8+
- id: check-added-large-files
9+
- repo: local
10+
hooks:
11+
- id: format
12+
name: format
13+
entry: python py/format_code.py
14+
language: python
15+
types: [mdx]
16+
additional_dependencies: [black-with-tabs, clang-format]

py/format_code.py

100644100755
+72-42
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,15 @@
1-
"""Formats all code snippets in modules using clang-format"""
1+
"""Formats all code snippets in mdx files using clang-format or black-with-tabs"""
22

33
import os
44
import subprocess
55
import sys
6+
import tempfile
7+
import black
8+
from typing import List
9+
610

711
# see https://clang.llvm.org/docs/ClangFormatStyleOptions.html for more options
8-
STYLE = """
12+
CLANG_FORMAT_STYLE = """
913
TabWidth: 4
1014
IndentWidth: 4
1115
UseTab: ForIndentation
@@ -16,17 +20,56 @@
1620
AllowShortLoopsOnASingleLine: true
1721
SpacesBeforeTrailingComments: 2
1822
"""
19-
STYLE = "{" + ", ".join(filter(lambda x: x != "", STYLE.split("\n"))) + "}"
23+
CLANG_FORMAT_STYLE = (
24+
"{" + ", ".join(filter(lambda x: x != "", CLANG_FORMAT_STYLE.split("\n"))) + "}"
25+
)
2026

2127
FORMAT_CPP = True
2228
FORMAT_PYTHON = True
2329
FORMAT_JAVA = True
2430

31+
2532
def lead_white(line):
2633
return len(line) - len(line.lstrip())
2734

35+
2836
def match_indentation(line, prog_line):
29-
return prog_line[min(lead_white(line), lead_white(prog_line)):]
37+
return prog_line[min(lead_white(line), lead_white(prog_line)) :]
38+
39+
40+
def contains_banned_terms(prog: List[str]):
41+
banned = ["CodeSnip", "while (???)"]
42+
return any(ban in prog_line for ban in banned for prog_line in prog)
43+
44+
45+
def format_prog_py(prog: List[str]):
46+
try:
47+
prog = black.format_file_contents("".join(prog), fast=True, mode=black.FileMode()).splitlines(True)
48+
except black.report.NothingChanged:
49+
pass
50+
return prog
51+
52+
53+
def format_prog_clang(lang: str, prog: List[str]):
54+
tmp_file = tempfile.NamedTemporaryFile(suffix=f".{lang}")
55+
with open(tmp_file.name, "w") as f:
56+
f.write("".join(prog))
57+
subprocess.check_output(
58+
[
59+
f"clang-format -i -style='{CLANG_FORMAT_STYLE}' {f.name}"
60+
],
61+
shell=True,
62+
)
63+
with open(tmp_file.name, "r") as f:
64+
return f.readlines()
65+
66+
def format_prog(lang: str, prog: List[str]):
67+
if lang == "py":
68+
return format_prog_py(prog)
69+
else:
70+
assert lang in ['cpp', 'java']
71+
return format_prog_clang(lang, prog)
72+
3073

3174
def format_path(path: str):
3275
print("formatting", path)
@@ -47,38 +90,15 @@ def format_path(path: str):
4790
nlines.append(line)
4891
elif line.strip() == "```":
4992
if lang is not None:
50-
banned = ["CodeSnip", "while (???)"]
51-
if not any(ban in prog_line for ban in banned for prog_line in prog):
52-
TMP_FILE = f"tmp.{lang}"
53-
with open(TMP_FILE, "w") as f:
54-
f.write("".join([match_indentation(line, prog_line) for prog_line in prog]))
55-
found_error = False
56-
try:
57-
if lang == "cpp" or lang == "java":
58-
subprocess.check_output(
59-
[f"clang-format -i -style='{STYLE}' {TMP_FILE}"], shell=True
60-
)
61-
elif lang == "py":
62-
subprocess.check_output(
63-
[f"black --fast {TMP_FILE}"], shell=True # black with tabs
64-
)
65-
else:
66-
assert False
67-
except subprocess.CalledProcessError as e:
68-
print("ERROR!")
69-
print(e)
70-
print("path =", path)
71-
print("".join(prog))
72-
print()
73-
found_error = True
74-
nlines += prog
75-
if not found_error:
76-
with open(TMP_FILE, "r") as f:
77-
whitespace = line[: line.find("```")]
78-
prog_lines = f.readlines()
79-
nlines += [whitespace + line for line in prog_lines]
80-
os.remove(TMP_FILE)
81-
else: # don't format
93+
if not contains_banned_terms(prog):
94+
prog = [
95+
match_indentation(line, prog_line)
96+
for prog_line in prog
97+
]
98+
prog = format_prog(lang, prog)
99+
whitespace = line[: line.find("```")]
100+
nlines += [whitespace + line for line in prog]
101+
else: # don't format
82102
nlines += prog
83103
prog = []
84104
lang = None
@@ -94,9 +114,19 @@ def format_path(path: str):
94114
assert lang is None
95115

96116

97-
# https://stackoverflow.com/questions/2212643/python-recursive-folder-read
98-
for root, subdirs, files in os.walk("/Users/benq/Documents/usaco-guide/content/"):
99-
for file in files:
100-
if file.endswith(".mdx"):
101-
path = os.path.join(root, file)
102-
format_path(path)
117+
def format_dir(dir):
118+
# https://stackoverflow.com/questions/2212643/python-recursive-folder-read
119+
for root, subdirs, files in os.walk(dir):
120+
for file in files:
121+
if file.endswith(".mdx"):
122+
path = os.path.join(root, file)
123+
format_path(path)
124+
125+
126+
if __name__ == "__main__":
127+
"""
128+
Args: paths of files to format
129+
"""
130+
# raise ValueError(sys.argv[1:])
131+
for path in sys.argv[1:]:
132+
format_path(path)

solutions/silver/usaco-919.mdx

+4-3
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,8 @@ int main() {
3131
for (int i = 0; i < rect_num; i++) {
3232
int start_x, start_y, end_x, end_y;
3333
cin >> start_x >> start_y >> end_x >> end_y;
34-
// Set up the prefix sums array with all the corners of the given rectangle
34+
// Set up the prefix sums array with all the corners of the given
35+
// rectangle
3536
barn[start_x][start_y]++;
3637
barn[start_x][end_y]--;
3738
barn[end_x][start_y]--;
@@ -107,7 +108,7 @@ public class PaintBarn {
107108
WIDTH = 1000
108109

109110
barn = [[0 for _ in range(WIDTH + 1)] for _ in range(WIDTH + 1)]
110-
with open('paintbarn.in') as read:
111+
with open("paintbarn.in") as read:
111112
rect_num, paint_req = [int(i) for i in read.readline().split()]
112113
for _ in range(rect_num):
113114
start_x, start_y, end_x, end_y = [int(i) for i in read.readline().split()]
@@ -129,7 +130,7 @@ for x in range(WIDTH + 1):
129130
barn[x][y] -= barn[x - 1][y - 1]
130131
valid_area += barn[x][y] == paint_req
131132

132-
print(valid_area, file=open('paintbarn.out', 'w'))
133+
print(valid_area, file=open("paintbarn.out", "w"))
133134
```
134135
135136
</PySection>

0 commit comments

Comments
 (0)