5
5
load ("./common.star" , "FORMATTER_MSG" , "cipd_platform_name" , "get_fuchsia_dir" , "os_exec" )
6
6
7
7
def _pyfmt (ctx ):
8
- """Runs python formatter black on a Python code base.
8
+ """Formats Python code using Black and sorts imports using isort on a Python code base.
9
9
10
10
Args:
11
11
ctx: A ctx instance.
@@ -18,21 +18,39 @@ def _pyfmt(ctx):
18
18
if not py_files :
19
19
return
20
20
21
- procs = []
22
- base_cmd = [
21
+ # Isort and black make conflicting code style changes. To ensure consistent formatting:
22
+ # 1. Run isort to sort imports and apply its formatting rules.
23
+ # 2. Run black on the formatted code to enforce its code style guidelines.
24
+ fuchsia_dir = get_fuchsia_dir (ctx )
25
+
26
+ isort_cmd = [
27
+ "%s/prebuilt/third_party/python3/%s/bin/python3" % (
28
+ fuchsia_dir ,
29
+ cipd_platform_name (ctx ),
30
+ ),
31
+ "%s/third_party/pylibs/isort/main.py" % fuchsia_dir ,
32
+ "--stdout" ,
33
+ ]
34
+ isort_procs = [(f , os_exec (ctx , isort_cmd + [f ])) for f in py_files ]
35
+
36
+ black_cmd = [
23
37
"%s/prebuilt/third_party/black/%s/black" % (
24
- get_fuchsia_dir ( ctx ) ,
38
+ fuchsia_dir ,
25
39
cipd_platform_name (ctx ),
26
40
),
27
41
"--config" ,
28
- "%s/pyproject.toml" % get_fuchsia_dir (ctx ),
42
+ "%s/pyproject.toml" % fuchsia_dir ,
43
+ "-" ,
29
44
]
30
- for filepath in py_files :
31
- original = str (ctx .io .read_file (filepath ))
32
- procs .append (
33
- (filepath , original , os_exec (ctx , base_cmd + ["-" ], stdin = original )),
45
+ black_procs = []
46
+ for filepath , proc in isort_procs :
47
+ isort_formatted = proc .wait ().stdout
48
+ black_procs .append (
49
+ (filepath , os_exec (ctx , black_cmd , stdin = isort_formatted )),
34
50
)
35
- for filepath , original , proc in procs :
51
+
52
+ for filepath , proc in black_procs :
53
+ original = str (ctx .io .read_file (filepath ))
36
54
formatted = proc .wait ().stdout
37
55
if formatted != original :
38
56
ctx .emit .finding (
0 commit comments