Skip to content

Commit 4f8dc8b

Browse files
committed
Enabled linting and fixed issues
Signed-off-by: Ole Herman Schumacher Elgesem <[email protected]>
1 parent 4a9afe4 commit 4f8dc8b

File tree

10 files changed

+72
-32
lines changed

10 files changed

+72
-32
lines changed
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
name: Automatically format with Black and submit PR
1+
name: Format
22
permissions:
33
contents: read
44
pull-requests: write
Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
22
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
33

4-
name: Check formatting with Black
4+
name: Lint
55
on:
66
push:
77
branches: [main]
@@ -25,7 +25,16 @@ jobs:
2525
- name: Install dependencies
2626
run: |
2727
python -m pip install --upgrade pip
28-
python -m pip install black
28+
python -m pip install uv
2929
- name: Check formatting with black
3030
run: |
31-
black --check .
31+
uv tool run black --check .
32+
- name: Run flake8
33+
run: |
34+
uv tool run flake8 src/ --ignore=E203,W503,E722,E731 --max-complexity=100 --max-line-length=160
35+
- name: Run pyflakes
36+
run: |
37+
uv tool run pyflakes src/
38+
- name: Run pyright
39+
run: |
40+
uv tool run pyright src/

.github/workflows/pypi-publish.yml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
name: Publish
12
# Taken from GH docs:
23
on:
34
release:
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# This workflow will install Python dependencies, run tests and lint with a variety of Python versions
22
# For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3-
name: Tests
3+
name: Test
44
on:
55
push:
66
branches: [main]

pyproject.toml

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ cfengine = "cfengine_cli.main:main"
4040
[tool.setuptools]
4141
license-files = [] # Workaround bug in setuptools https://github.com/astral-sh/uv/issues/9513
4242

43+
[tool.pyright]
44+
include = ["src"]
45+
venvPath = "."
46+
venv = ".venv"
47+
4348
[tool.setuptools_scm]
4449

4550
[dependency-groups]

src/cfengine_cli/commands.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -89,5 +89,5 @@ def run() -> int:
8989
return 0
9090

9191

92-
def dev(subcommand) -> int:
93-
return dispatch_dev_subcommand(subcommand)
92+
def dev(subcommand, args) -> int:
93+
return dispatch_dev_subcommand(subcommand, args)

src/cfengine_cli/deptool.py

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -95,11 +95,15 @@ def __init__(
9595
log_info=True,
9696
):
9797
"""
98-
Creates an instance of the class for a Git repository in a given path, cloning from GitHub if the path doesn't exist, then configures it and optionally checks out a requested ref (branch or tag). Arguments:
99-
* `repo_path`: local filesystem path of the Git repository, or of the GitHub repository to clone
98+
Creates an instance of the class for a Git repository in a given path,
99+
cloning from GitHub if the path doesn't exist, then configures it and
100+
optionally checks out a requested ref (branch or tag). Arguments:
101+
* `repo_path`: local filesystem path of the Git repository, or of the
102+
GitHub repository to clone
100103
* `repo_owner`: name of owner of the GitHub repository to clone
101104
* `repo_name`: name of GitHub repository to clone
102-
* `checkout_ref`: optional name of ref to checkout. If not provided, a ref from previous work might be left checked out.
105+
* `checkout_ref`: optional name of ref to checkout. If not provided,
106+
a ref from previous work might be left checked out.
103107
"""
104108
self.repo_path = repo_path
105109

@@ -128,7 +132,9 @@ def __init__(
128132
self.checkout(checkout_ref)
129133

130134
def run_command(self, *command, **kwargs):
131-
"""Runs a git command in the Git repository. Syntactically this function tries to be as close to `subprocess.run` as possible, just adding `"git"` with some extra parameters at the beginning."""
135+
"""Runs a git command in the Git repository. Syntactically this
136+
function tries to be as close to `subprocess.run` as possible,
137+
just adding `"git"` with some extra parameters at the beginning."""
132138
git_command = [
133139
"git",
134140
"-C",
@@ -286,11 +292,12 @@ def extract_version_from_filename(self, dep, filename):
286292
match = re.search("-([0-9a-z.]*).tar", filename)
287293
if not match:
288294
match = re.search("_([0-9a-z_]*).tar", filename)
295+
assert match is not None
289296
version = match.group(1)
290297
elif dep == "pthreads-w32":
291-
version = re.search("w32-([0-9-]*)-rel", filename).group(1)
298+
version = re.search("w32-([0-9-]*)-rel", filename).group(1) # type: ignore
292299
else:
293-
version = re.search(r"[-_]([0-9.]*)[\.-]", filename).group(1)
300+
version = re.search(r"[-_]([0-9.]*)[\.-]", filename).group(1) # type: ignore
294301
return version
295302

296303
def get_current_version(self, dep):
@@ -325,7 +332,9 @@ def deps_versions(self, ref):
325332
return deps_versions
326333

327334
def deps_dict(self, refs):
328-
"""Returns a 2D dictionary of dependencies and versions from all refs: `deps_dict[dep][ref] = version`, as well as a dictionary of widths of each column (ref)."""
335+
"""Returns a 2D dictionary of dependencies and versions from all refs:
336+
`deps_dict[dep][ref] = version`, as well as a dictionary of widths of
337+
each column (ref)."""
329338

330339
deps_dict = {}
331340
ref_column_widths = {}
@@ -335,7 +344,7 @@ def deps_dict(self, refs):
335344
deps_versions = self.deps_versions(ref)
336345

337346
for dep in deps_versions:
338-
if not dep in deps_dict:
347+
if dep not in deps_dict:
339348
deps_dict[dep] = collections.defaultdict(lambda: "-")
340349
deps_dict[dep][ref] = deps_versions[dep]
341350
ref_column_widths[ref] = max(
@@ -345,7 +354,10 @@ def deps_dict(self, refs):
345354
return deps_dict, ref_column_widths
346355

347356
def updated_deps_markdown_table(self, refs):
348-
"""Code from bot-tom's `depstable` that processes the README table directly, returning the updated README. The updated README will not contain dependencies that were not in the README beforehand, and will not automatically remove dependencies that no longer exist."""
357+
"""Code from bot-tom's `depstable` that processes the README table
358+
directly, returning the updated README. The updated README will not
359+
contain dependencies that were not in the README beforehand, and
360+
will not automatically remove dependencies that no longer exist."""
349361
updated_hub_table_lines = []
350362
updated_agent_table_lines = []
351363

@@ -356,6 +368,7 @@ def updated_deps_markdown_table(self, refs):
356368
readme_lines = readme_file.split("\n")
357369
has_notes = False # flag to say that we're in a table that has "Notes" column
358370
in_hub = False # flag that we're in Hub section
371+
column_widths = None
359372
for i, line in enumerate(readme_lines):
360373
if " Hub " in line:
361374
in_hub = True
@@ -395,6 +408,7 @@ def updated_deps_markdown_table(self, refs):
395408
+ " |"
396409
)
397410
elif line.startswith("| :-"):
411+
assert column_widths is not None
398412
line = (
399413
"| "
400414
+ (" | ".join((":" + "-" * (width - 1) for width in column_widths)))
@@ -423,6 +437,7 @@ def updated_deps_markdown_table(self, refs):
423437
line,
424438
)
425439
deps_dict[dep] = collections.defaultdict(lambda: "-")
440+
note = None
426441
if has_notes:
427442
note = re.search(r"\| ([^|]*) \|$", line)
428443
if not note:
@@ -432,11 +447,13 @@ def updated_deps_markdown_table(self, refs):
432447
note = note.group(1)
433448
if in_hub:
434449
dep = re.sub("-hub$", "", dep)
450+
assert note is not None
435451
row = (
436452
["[%s](%s)" % (dep_title, url)]
437453
+ [deps_dict[dep][ref] for ref in refs]
438454
+ ([note] if has_notes else [])
439455
)
456+
assert column_widths is not None
440457
line = (
441458
"| "
442459
+ (
@@ -562,7 +579,7 @@ def comparison_md_table(self, refs, skip_unchanged=False):
562579

563580
deps_name_urllink_mapping = {
564581
d: (
565-
"[" + HUMAN_NAME.get(d, d) + "](" + HOME_URL[d] + ")"
582+
"[" + HUMAN_NAME.get(d, d) + "](" + HOME_URL[d] + ")" # type: ignore
566583
if d in HOME_URL
567584
else HUMAN_NAME.get(d, d)
568585
)
@@ -728,6 +745,10 @@ def deptool(
728745
if cdx_sbom_path_template:
729746
dr.write_cdx_sboms(cdx_sbom_path_template, refs)
730747

748+
updated_readme = None
749+
updated_agent_table = None
750+
updated_hub_table = None
751+
731752
if patch or not compare:
732753
updated_readme, updated_agent_table, updated_hub_table = (
733754
dr.updated_deps_markdown_table(refs)
@@ -738,8 +759,10 @@ def deptool(
738759
print(comparison_table)
739760
else:
740761
print("### Agent dependencies\n")
762+
assert updated_agent_table is not None
741763
print(updated_agent_table)
742764
print("\n### Enterprise Hub dependencies\n")
765+
assert updated_hub_table is not None
743766
print(updated_hub_table)
744767

745768
if patch:

src/cfengine_cli/docs.py

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ def extract_inline_code(path, languages):
4545
flags = info_string[1:]
4646

4747
if language in languages:
48+
assert child.map is not None
4849
yield {
4950
"language": language,
5051
"flags": flags,
@@ -124,9 +125,7 @@ def fn_check_syntax(origin_path, snippet_path, language, first_line, _last_line)
124125
with open(snippet_abs_path, "r") as f:
125126
json.loads(f.read())
126127
except json.decoder.JSONDecodeError as e:
127-
raise UserError(
128-
f"Unknown error when checking '{snippet_abs_path}': {str(e)}"
129-
)
128+
raise UserError(f"Error when checking '{snippet_abs_path}': {str(e)}")
130129
except Exception as e:
131130
print(str(e))
132131
raise UserError(f"Unknown error when checking '{snippet_abs_path}'")
@@ -215,7 +214,7 @@ def _markdown_code_checker(
215214
cb["last_line"] += offset
216215

217216
language = supported_languages[code_block["language"]]
218-
snippet_path = f"{origin_path}.snippet-{i+1}.{language}"
217+
snippet_path = f"{origin_path}.snippet-{i + 1}.{language}"
219218

220219
if extract and "noextract" not in code_block["flags"]:
221220
fn_extract(
@@ -227,13 +226,18 @@ def _markdown_code_checker(
227226
)
228227

229228
if syntax_check and "novalidate" not in code_block["flags"]:
230-
fn_check_syntax(
231-
origin_path,
232-
snippet_path,
233-
language,
234-
code_block["first_line"],
235-
code_block["last_line"],
236-
)
229+
try:
230+
fn_check_syntax(
231+
origin_path,
232+
snippet_path,
233+
language,
234+
code_block["first_line"],
235+
code_block["last_line"],
236+
)
237+
except Exception as e:
238+
if cleanup:
239+
os.remove(snippet_path)
240+
raise e
237241

238242
if autoformat and "noautoformat" not in code_block["flags"]:
239243
fn_autoformat(

src/cfengine_cli/format.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,5 @@
1-
import sys
21
import tree_sitter_cfengine as tscfengine
3-
from typing import Generator
4-
from tree_sitter import Language, Parser, Node, Tree
2+
from tree_sitter import Language, Parser, Node
53
from cfbs.pretty import pretty_file
64

75

src/cfengine_cli/main.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ def run_command_with_args(args) -> int:
9393
if args.command == "run":
9494
return commands.run()
9595
if args.command == "dev":
96-
return commands.dev(args.dev_command)
96+
return commands.dev(args.dev_command, args)
9797
raise UserError(f"Unknown command: '{args.command}'")
9898

9999

0 commit comments

Comments
 (0)