-
Notifications
You must be signed in to change notification settings - Fork 0
/
rust-clean.py
executable file
·83 lines (65 loc) · 2.2 KB
/
rust-clean.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#!/usr/bin/env python3
"""
Clean-up build files from Rust projects under the current, or given, folder.
Runs the shell command `cargo clean` in every Rust project that needs it. If a
folder contains a folder called 'target' AND a file called `Cargo.toml` it
is considered to need cleaning.
"""
import contextlib
import os
from pathlib import Path
import subprocess
import sys
from typing import Iterator
@contextlib.contextmanager
def chdir(folder: Path) -> Iterator[None]:
"""
Context manager to temporarily change the current working directory.
Note that as of Python 3.11 the standard library provides its own
`contextlib.chdir()`, which does the same thing.
"""
curdir = os.getcwd()
os.chdir(folder)
try:
yield
finally:
os.chdir(curdir)
def clean(folder: Path) -> str:
"""
Run the 'cargo clean' command in the given folder.
"""
with chdir(folder):
args = ['cargo', 'clean']
result = subprocess.run(args, capture_output=True, check=True, text=True)
message = result.stderr.strip()
return message
def find_unclean(root: Path) -> Iterator[Path]:
"""
Recursive generator over folders found under given root.
Skips hidden folders, ie. those starting with a period, as we don't need
to explore inside `.git`, for example.
Args:
root:
Folder to start searching from.
Returns:
Yields paths to folders containing a `target` subfolder and the
file `Cargo.toml`.
"""
ignored_folders = ('.git', 'src', 'target')
for (dirpath, dirnames, filenames) in root.walk():
# Don't recurse in ignored folders
if dirpath.name.startswith('.'):
dirnames.clear()
continue
# Projects contain a file called 'Cargo.toml' and a folder called 'target'
if 'target' in dirnames and 'Cargo.toml' in filenames:
yield dirpath
def main(root: Path) -> int:
for project in find_unclean(root):
message = clean(project)
folder = os.path.relpath(project, root)
print(f"From {folder}\n {message}", file=sys.stderr)
return 0
if __name__ == '__main__':
root = Path.cwd()
sys.exit(main(root))