Skip to content

Commit af11f1f

Browse files
committed
Add Makefile and format fix script for tritonparse project
Summary: - Introduced a Makefile to streamline project tasks including formatting, linting, testing, and cleaning. - Added a format fix script to automate code formatting and linting using usort, ruff, and black. - Updated pyproject.toml to include configuration for usort and ruff. This enhancement improves development workflow by providing easy-to-use commands for maintaining code quality.
1 parent a2426b3 commit af11f1f

File tree

3 files changed

+262
-0
lines changed

3 files changed

+262
-0
lines changed

Makefile

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
# Makefile for tritonparse project
2+
3+
.PHONY: help format format-check lint lint-check test test-cuda clean install-dev
4+
5+
# Default target
6+
help:
7+
@echo "Available targets:"
8+
@echo " format - Format all Python files"
9+
@echo " format-check - Check formatting without making changes"
10+
@echo " lint - Run all linters"
11+
@echo " lint-check - Check linting without making changes"
12+
@echo " test - Run tests (CPU only)"
13+
@echo " test-cuda - Run tests (including CUDA tests)"
14+
@echo " clean - Clean up cache files"
15+
@echo " install-dev - Install development dependencies"
16+
17+
# Formatting targets
18+
format:
19+
@echo "Running format fix script..."
20+
python -m tritonparse.tools.format_fix --verbose
21+
22+
format-check:
23+
@echo "Checking formatting..."
24+
python -m tritonparse.tools.format_fix --check-only --verbose
25+
26+
# Linting targets
27+
lint:
28+
@echo "Running linters..."
29+
ruff check .
30+
ruff format --check .
31+
32+
lint-check:
33+
@echo "Checking linting..."
34+
ruff check --diff .
35+
ruff format --diff .
36+
37+
# Testing targets
38+
test:
39+
@echo "Running tests (CPU only)..."
40+
pytest tests/ -v -m "not cuda"
41+
42+
test-cuda:
43+
@echo "Running all tests (including CUDA)..."
44+
pytest tests/ -v
45+
46+
# Utility targets
47+
clean:
48+
@echo "Cleaning up cache files..."
49+
find . -type d -name "__pycache__" -exec rm -rf {} + 2>/dev/null || true
50+
find . -type f -name "*.pyc" -delete 2>/dev/null || true
51+
find . -type f -name "*.pyo" -delete 2>/dev/null || true
52+
find . -type f -name ".coverage" -delete 2>/dev/null || true
53+
find . -type d -name "*.egg-info" -exec rm -rf {} + 2>/dev/null || true
54+
find . -type d -name ".pytest_cache" -exec rm -rf {} + 2>/dev/null || true
55+
56+
install-dev:
57+
@echo "Installing development dependencies..."
58+
pip install -e ".[test]"
59+
pip install ruff black usort

pyproject.toml

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,12 @@ line-length = 88
2424
line-length = 88
2525
target-version = ["py310"]
2626

27+
[tool.ufmt]
28+
formatter = "ruff-api"
29+
sorter = "usort"
30+
31+
[tool.usort]
32+
first_party_detection = false
33+
2734
[project.urls]
2835
"Homepage" = "https://github.com/pytorch-labs/tritonparse"

tritonparse/tools/format_fix.py

Lines changed: 196 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,196 @@
1+
#!/usr/bin/env python3
2+
"""
3+
Format fix script for tritonparse project.
4+
5+
This script runs all linter tools to format and fix code issues:
6+
- usort: Import sorting
7+
- ruff: Code formatting and linting
8+
- black: Code formatting (fallback)
9+
10+
Usage:
11+
python -m tritonparse.tools.format_fix [options]
12+
13+
Options:
14+
--check-only Only check for issues, don't fix them
15+
--verbose Verbose output
16+
--help Show this help message
17+
"""
18+
19+
import argparse
20+
import subprocess
21+
import sys
22+
from pathlib import Path
23+
from typing import List
24+
25+
26+
def run_command(cmd: List[str], verbose: bool = False) -> bool:
27+
"""Run a command and return success status."""
28+
if verbose:
29+
print(f"Running: {' '.join(cmd)}")
30+
31+
try:
32+
result = subprocess.run(
33+
cmd,
34+
capture_output=True,
35+
text=True,
36+
check=False
37+
)
38+
39+
if result.returncode != 0:
40+
if verbose:
41+
print(f"Command failed with return code {result.returncode}")
42+
if result.stdout:
43+
print("STDOUT:", result.stdout)
44+
if result.stderr:
45+
print("STDERR:", result.stderr)
46+
return False
47+
48+
if verbose and result.stdout:
49+
print(result.stdout)
50+
51+
return True
52+
except Exception as e:
53+
if verbose:
54+
print(f"Error running command: {e}")
55+
return False
56+
57+
58+
def get_python_files() -> List[str]:
59+
"""Get all Python files to format."""
60+
project_root = Path(__file__).parent.parent.parent
61+
python_files = []
62+
63+
# Add main package files
64+
for pattern in ["*.py", "tests/*.py"]:
65+
python_files.extend(str(f) for f in project_root.glob(pattern))
66+
67+
# Filter out __pycache__ and other unwanted directories
68+
python_files = [
69+
f for f in python_files
70+
if "__pycache__" not in f and ".git" not in f
71+
]
72+
73+
return python_files
74+
75+
76+
def run_usort(files: List[str], check_only: bool = False,
77+
verbose: bool = False) -> bool:
78+
"""Run usort for import sorting."""
79+
cmd = ["usort"]
80+
81+
if check_only:
82+
cmd.append("check")
83+
else:
84+
cmd.append("format")
85+
86+
cmd.extend(files)
87+
88+
return run_command(cmd, verbose)
89+
90+
91+
def run_ruff(files: List[str], check_only: bool = False,
92+
verbose: bool = False) -> bool:
93+
"""Run ruff for code formatting and linting."""
94+
cmd = ["ruff"]
95+
96+
if check_only:
97+
cmd.extend(["check", "--diff"])
98+
else:
99+
cmd.extend(["format"])
100+
101+
cmd.extend(files)
102+
103+
return run_command(cmd, verbose)
104+
105+
106+
def run_black(files: List[str], check_only: bool = False,
107+
verbose: bool = False) -> bool:
108+
"""Run black for code formatting (fallback)."""
109+
cmd = ["black"]
110+
111+
if check_only:
112+
cmd.append("--check")
113+
else:
114+
cmd.append("--quiet")
115+
116+
cmd.extend(files)
117+
118+
return run_command(cmd, verbose)
119+
120+
121+
def main():
122+
"""Main function."""
123+
parser = argparse.ArgumentParser(
124+
description="Format fix script for tritonparse project",
125+
epilog="""
126+
Examples:
127+
# Fix all formatting issues
128+
python -m tritonparse.tools.format_fix
129+
130+
# Check for issues without fixing
131+
python -m tritonparse.tools.format_fix --check-only
132+
133+
# Verbose output
134+
python -m tritonparse.tools.format_fix --verbose
135+
"""
136+
)
137+
138+
parser.add_argument(
139+
"--check-only",
140+
action="store_true",
141+
help="Only check for issues, don't fix them"
142+
)
143+
parser.add_argument(
144+
"--verbose",
145+
action="store_true",
146+
help="Verbose output"
147+
)
148+
149+
args = parser.parse_args()
150+
151+
# Get Python files to format
152+
files = get_python_files()
153+
154+
if args.verbose:
155+
print(f"Found {len(files)} Python files to process:")
156+
for f in files:
157+
print(f" {f}")
158+
print()
159+
160+
# Run formatters
161+
success = True
162+
163+
# 1. Run usort for import sorting
164+
print("Running usort for import sorting...")
165+
if not run_usort(files, args.check_only, args.verbose):
166+
print("❌ usort failed")
167+
success = False
168+
else:
169+
print("✅ usort completed")
170+
171+
# 2. Run ruff for code formatting and linting
172+
print("Running ruff for code formatting and linting...")
173+
if not run_ruff(files, args.check_only, args.verbose):
174+
print("❌ ruff failed")
175+
success = False
176+
else:
177+
print("✅ ruff completed")
178+
179+
# 3. Run black as fallback
180+
print("Running black for additional formatting...")
181+
if not run_black(files, args.check_only, args.verbose):
182+
print("❌ black failed")
183+
success = False
184+
else:
185+
print("✅ black completed")
186+
187+
if success:
188+
print("\n🎉 All formatting tools completed successfully!")
189+
return 0
190+
else:
191+
print("\n❌ Some formatting tools failed. Please check the output above.")
192+
return 1
193+
194+
195+
if __name__ == "__main__":
196+
sys.exit(main())

0 commit comments

Comments
 (0)