Skip to content

Commit 1b8a7c6

Browse files
committed
refactor: apply ruff formatting and linting to python files and update pyproject.toml
1 parent 7c20525 commit 1b8a7c6

File tree

6 files changed

+597
-198
lines changed

6 files changed

+597
-198
lines changed

pyproject.toml

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,60 @@ description = "Build interactive, portable cheatsheets from YAML."
55
readme = "README.md"
66
requires-python = ">=3.9"
77
dependencies = ["jinja2>=3.1.6", "python-dotenv>=1.1.1", "ruamel-yaml>=0.18.14"]
8+
9+
[dependency-groups]
10+
dev = ["bandit>=1.8.6", "ruff>=0.14.0", "ty>=0.0.1a22", "vulture>=2.14"]
11+
12+
13+
[tool.ruff]
14+
indent-width = 4
15+
line-length = 120
16+
17+
18+
[tool.ruff.lint]
19+
# select = ["ALL"]
20+
ignore = [
21+
"ANN", # flake8-annotations
22+
"COM", # flake8-commas
23+
"C90", # mccabe complexity
24+
"DJ", # django
25+
"EXE", # flake8-executable
26+
"BLE", # blind except
27+
"PTH", # flake8-pathlib
28+
"T10", # debugger
29+
"TID", # flake8-tidy-imports
30+
"D100",
31+
"D101",
32+
"D102",
33+
"D103",
34+
"D104",
35+
"D105",
36+
"D106",
37+
"D107",
38+
"D101",
39+
"D107", # missing docstring in public module
40+
"D102", # missing docstring in public class
41+
"D104", # missing docstring in public package
42+
"D213",
43+
"D203",
44+
"D400",
45+
"D415",
46+
"G004",
47+
"PLR2004",
48+
"E501", # line too long
49+
"TRY",
50+
"SIM105", # faster without contextlib
51+
]
52+
53+
fixable = ["ALL"]
54+
unfixable = []
55+
56+
# Allow unused variables when underscore-prefixed.
57+
dummy-variable-rgx = "^(_+|(_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?))$"
58+
59+
[tool.ruff.format]
60+
quote-style = "double"
61+
indent-style = "space"
62+
line-ending = "auto"
63+
64+
docstring-code-format = false

src/generate_cheatsheet.py

Lines changed: 26 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
from logger import get_logger
88
from pathlib import Path
99

10-
yaml_safe = YAML(typ='safe')
10+
yaml_safe = YAML(typ="safe")
1111
yaml_rw = YAML()
1212
yaml_rw.indent(mapping=2, sequence=4, offset=2)
1313
yaml_rw.preserve_quotes = True
@@ -18,7 +18,7 @@
1818
BASE_DIR = Path(__file__).parent
1919
PROJECT_ROOT = BASE_DIR.parent
2020

21-
OUTPUT_DIR = Path(os.getenv('CHEATSHEET_OUTPUT_DIR') or PROJECT_ROOT / "output")
21+
OUTPUT_DIR = Path(os.getenv("CHEATSHEET_OUTPUT_DIR") or PROJECT_ROOT / "output")
2222
TEMPLATES_DIR = BASE_DIR / "templates"
2323
LAYOUTS_DIR = BASE_DIR / "layouts"
2424
CHEATSHEETS_DIR = PROJECT_ROOT / "cheatsheets"
@@ -30,7 +30,7 @@
3030

3131
def load_yaml(file_path: Path) -> dict | None:
3232
try:
33-
with open(file_path, "r", encoding='utf-8') as file:
33+
with open(file_path, "r", encoding="utf-8") as file:
3434
return yaml_safe.load(file)
3535
except FileNotFoundError:
3636
logging.error(f"Error: YAML file '{file_path}' not found.")
@@ -43,54 +43,50 @@ def load_yaml(file_path: Path) -> dict | None:
4343
def load_layout():
4444
keyboard_layouts = load_yaml(LAYOUTS_DIR / "keyboard_layouts.yaml")
4545
system_mappings = load_yaml(LAYOUTS_DIR / "system_mappings.yaml")
46-
46+
4747
if keyboard_layouts is None or system_mappings is None:
4848
logging.error("Failed to load configuration files.")
4949
return None, None
50-
50+
5151
return keyboard_layouts, system_mappings
5252

53+
5354
def replace_shortcut_names(shortcut, system_mappings):
54-
arrow_key_mappings = {
55-
"Up": "↑",
56-
"Down": "↓",
57-
"Left": "←",
58-
"Right": "→"
59-
}
55+
arrow_key_mappings = {"Up": "↑", "Down": "↓", "Left": "←", "Right": "→"}
6056
try:
6157
processed_parts = []
6258
i = 0
6359
while i < len(shortcut):
64-
if shortcut[i] == '+':
65-
if i + 1 < len(shortcut) and shortcut[i + 1] == '+':
66-
processed_parts.append('+')
60+
if shortcut[i] == "+":
61+
if i + 1 < len(shortcut) and shortcut[i + 1] == "+":
62+
processed_parts.append("+")
6763
i += 2
6864
else:
69-
processed_parts.append('<sep>')
65+
processed_parts.append("<sep>")
7066
i += 1
7167
else:
72-
current_part = ''
73-
while i < len(shortcut) and shortcut[i] != '+':
68+
current_part = ""
69+
while i < len(shortcut) and shortcut[i] != "+":
7470
current_part += shortcut[i]
7571
i += 1
7672
if current_part.strip():
7773
part = current_part.strip()
7874
part = system_mappings.get(part.lower(), part)
79-
if part in ['⌘', '⌥', '⌃', '⇧']:
75+
if part in ["⌘", "⌥", "⌃", "⇧"]:
8076
part = f'<span class="modifier-symbol">{part}</span>'
8177

8278
part = arrow_key_mappings.get(part, part)
8379
processed_parts.append(part)
8480

85-
86-
return ''.join(processed_parts)
81+
return "".join(processed_parts)
8782
except Exception as e:
88-
logging.error(f"Error replacing shortcut names: {e}")
89-
return shortcut
83+
logging.error(f"Error replacing shortcut names: {e}")
84+
return shortcut
85+
9086

9187
def normalize_shortcuts(data, system_mappings):
9288
normalized = {}
93-
allow_text = data.get('AllowText', False)
89+
allow_text = data.get("AllowText", False)
9490
try:
9591
for section, shortcuts in data.get("shortcuts", {}).items():
9692
normalized[section] = {}
@@ -112,17 +108,16 @@ def get_layout_info(data):
112108
"system": layout.get("system", "Darwin"),
113109
}
114110

111+
115112
def generate_html(data, keyboard_layouts, system_mappings):
116113
template_path = "cheatsheets/cheatsheet-template.html"
117114
layout_info = get_layout_info(data)
118-
data["shortcuts"] = normalize_shortcuts(
119-
data, system_mappings.get(layout_info["system"], {})
120-
)
115+
data["shortcuts"] = normalize_shortcuts(data, system_mappings.get(layout_info["system"], {}))
121116
data["layout"] = layout_info
122117
data["keyboard_layout"] = keyboard_layouts.get(layout_info["keyboard"], {}).get("layout")
123118
data["render_keys"] = data.get("RenderKeys", True)
124119
data["allow_text"] = data.get("AllowText", False)
125-
120+
126121
return render_template(template_path, data)
127122

128123

@@ -141,15 +136,17 @@ def validate_and_lint(yaml_file):
141136

142137
return True
143138

139+
144140
def write_html_content(html_output, html_content):
145141
try:
146-
with open(html_output, "w", encoding='utf-8') as file:
142+
with open(html_output, "w", encoding="utf-8") as file:
147143
file.write(html_content)
148144
except IOError as e:
149145
logging.error(f"Error writing to output file: {e}")
150146
return False
151147
return True
152148

149+
153150
def main(yaml_file):
154151
if not validate_and_lint(yaml_file):
155152
return None, None
@@ -199,7 +196,7 @@ def generate_index(cheatsheets):
199196

200197
if cheatsheets:
201198
OUTPUT_DIR.mkdir(exist_ok=True, parents=True)
202-
199+
203200
html_content = generate_index(cheatsheets)
204201
if html_content:
205202
index_output = os.path.join(OUTPUT_DIR, "index.html")

src/logger.py

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111

1212
_logger: Optional[logging.Logger] = None
1313

14+
1415
def setup_logging(
1516
log_file: str = os.getenv("LOG_FILE", DEFAULT_LOG_FILE),
1617
) -> logging.Logger:
@@ -20,7 +21,7 @@ def setup_logging(
2021

2122
logger = logging.getLogger("app")
2223
logger.setLevel(logging.DEBUG)
23-
24+
2425
formatter = logging.Formatter(DEFAULT_FORMAT)
2526

2627
logger.handlers.clear()
@@ -32,10 +33,7 @@ def setup_logging(
3233

3334
try:
3435
file_handler = RotatingFileHandler(
35-
log_file,
36-
maxBytes=DEFAULT_MAX_BYTES,
37-
backupCount=DEFAULT_BACKUP_COUNT,
38-
encoding='utf-8'
36+
log_file, maxBytes=DEFAULT_MAX_BYTES, backupCount=DEFAULT_BACKUP_COUNT, encoding="utf-8"
3937
)
4038
file_handler.setLevel(logging.DEBUG)
4139
file_handler.setFormatter(formatter)
@@ -48,9 +46,9 @@ def setup_logging(
4846
_logger = logger
4947
return logger
5048

49+
5150
def get_logger() -> logging.Logger:
5251
global _logger
5352
if _logger is None:
5453
_logger = setup_logging()
5554
return _logger
56-

src/template_renderer.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -4,21 +4,19 @@
44

55
logging = get_logger()
66

7+
78
def render_template(template_path, data):
89
try:
910
templates_dir = Path(__file__).parent / "templates"
10-
11-
env = Environment(
12-
loader=FileSystemLoader(str(templates_dir))
13-
)
14-
11+
12+
env = Environment(loader=FileSystemLoader(str(templates_dir)))
13+
1514
template = env.get_template(str(template_path))
1615
return template.render(**data)
17-
16+
1817
except FileNotFoundError:
1918
logging.error(f"Error: Template file '{template_path}' not found.")
2019
return None
2120
except Exception as e:
2221
logging.error(f"Error reading template file: {e}")
2322
return None
24-

0 commit comments

Comments
 (0)