Skip to content

Commit 2c4ab62

Browse files
committed
Replaced all the os.path usage with Path from pathlib and add types to all functions, && formatted
1 parent 4c17d38 commit 2c4ab62

File tree

1 file changed

+40
-25
lines changed

1 file changed

+40
-25
lines changed

c_formatter_42/__main__.py

Lines changed: 40 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -8,61 +8,75 @@
88
# By: cacharle <me@cacharle.xyz> +#+ +:+ +#+ #
99
# +#+#+#+#+#+ +#+ #
1010
# Created: 2020/10/04 09:53:21 by cacharle #+# #+# #
11-
# Updated: 2020/10/04 09:53:21 by cacharle ### ########.fr #
11+
# Updated: 2020/10/04 09:53:21 by zouddach ### ########.fr #
1212
# #
1313
# ############################################################################ #
1414

15-
#!/usr/bin/env python3
1615
import argparse
17-
import sys
1816
import os
17+
import sys
18+
from pathlib import Path
19+
from typing import Optional
20+
1921
from c_formatter_42.run import run_all
2022

21-
def process_file(filepath, confirm=False):
23+
24+
def process_file(filepath: Path, confirm: bool = False) -> bool:
2225
"""Process a single file with formatting."""
2326
try:
24-
with open(filepath, "r") as file:
27+
with filepath.open("r") as file:
2528
content = file.read()
26-
29+
2730
if confirm:
2831
result = input(f"Are you sure you want to overwrite {filepath}?[y/N] ")
2932
if result != "y":
3033
return True
31-
34+
3235
print(f"Formatting: {filepath}")
33-
with open(filepath, "w") as file:
36+
with filepath.open("w") as file:
3437
file.write(run_all(content))
3538
return True
3639
except OSError as e:
3740
print(f"Error: {e.filename}: {e.strerror}", file=sys.stderr)
3841
return False
3942

40-
def process_path(path, confirm=False, ignore_dirs=None):
43+
44+
def process_path(
45+
path: Path, confirm: bool = False, ignore_dirs: Optional[list[str]] = None
46+
) -> bool:
4147
"""
4248
Process a path (file or directory) recursively.
4349
Formats .c and .h files in the directory.
4450
"""
4551
ignore_dirs = ignore_dirs or []
46-
47-
if os.path.isfile(path):
48-
if path.endswith(('.c', '.h')):
52+
53+
if path.is_file():
54+
if path.suffix in (".c", ".h"):
4955
return process_file(path, confirm)
5056
return True
51-
52-
if os.path.isdir(path):
57+
58+
if path.is_dir():
5359
success = True
5460
for root, dirs, files in os.walk(path):
55-
dirs[:] = [d for d in dirs if not any(ignore_dir in os.path.join(root, d) for ignore_dir in ignore_dirs)]
56-
61+
dirs[:] = [
62+
d
63+
for d in dirs
64+
if not any(
65+
str(Path(root) / d).find(ignore_dir) != -1
66+
for ignore_dir in ignore_dirs
67+
)
68+
]
69+
5770
for file in files:
58-
if file.endswith(('.c', '.h')):
59-
filepath = os.path.join(root, file)
71+
if file.endswith((".c", ".h")):
72+
filepath = Path(root) / file
6073
success &= process_file(filepath, confirm)
6174
return success
62-
75+
6376
print(f"Error: {path} is not a file or directory", file=sys.stderr)
6477
return False
6578

79+
6680
def main() -> int:
6781
arg_parser = argparse.ArgumentParser(
6882
prog="c_formatter_42",
@@ -78,7 +92,7 @@ def main() -> int:
7892
arg_parser.add_argument(
7993
"-i",
8094
"--ignore",
81-
nargs='+',
95+
nargs="+",
8296
default=[],
8397
help="Ignore specified folders (e.g. .git/ .vscode/)",
8498
)
@@ -89,17 +103,18 @@ def main() -> int:
89103
help="Files or directories to format. If no path is provided, read STDIN",
90104
)
91105
args = arg_parser.parse_args()
92-
106+
93107
if len(args.paths) == 0:
94108
content = sys.stdin.read()
95109
print(run_all(content), end="")
96110
return 0
97-
111+
98112
success = True
99113
for path in args.paths:
100-
success &= process_path(path, args.confirm, args.ignore)
101-
114+
success &= process_path(Path(path), args.confirm, args.ignore)
115+
102116
return 0 if success else 1
103117

118+
104119
if __name__ == "__main__":
105-
sys.exit(main())
120+
sys.exit(main())

0 commit comments

Comments
 (0)