generated from canonical/starbase
-
Notifications
You must be signed in to change notification settings - Fork 19
feat(linter): add linter service framework #907
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
HamdaanAliQuatil
wants to merge
13
commits into
canonical:main
Choose a base branch
from
HamdaanAliQuatil:feat/linter-service
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,479
−0
Open
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
dafd60c
feat(linter): add linter service framework
HamdaanAliQuatil 63e9920
docs(linter): add documentation for linter
HamdaanAliQuatil f2b5455
test(linter): add integration test for linter
HamdaanAliQuatil db68d12
feat(linter): add lint report per linter
HamdaanAliQuatil fd59c85
feat(testcraft): add sample linters and spread test
HamdaanAliQuatil a9d0ad8
test(spread): copy yaml from suite cwd in lint task
HamdaanAliQuatil 77709e1
fix(lint): configure project before running post-stage lint
HamdaanAliQuatil 3c97adf
refactor(linter): centralize ignore handling, CLI parsing; expose cle…
HamdaanAliQuatil fb804e1
test(linter-service): seed dummy linter via autouse fixture
HamdaanAliQuatil 3f7d420
fix(testcraft): unpack packed artifacts before post-stage lint
HamdaanAliQuatil bd78a02
Merge branch 'main' into feat/linter-service
lengau e07c6f1
refactor(lint): tighten arg parsing and typing casts
HamdaanAliQuatil 698d6be
Merge branch 'main' into feat/linter-service
HamdaanAliQuatil File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| # This file is part of craft-application. | ||
| # | ||
| # Copyright 2025 Canonical Ltd. | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify it | ||
| # under the terms of the GNU Lesser General Public License version 3, as | ||
| # published by the Free Software Foundation. | ||
| # | ||
| # This program is distributed in the hope that it will be useful, but WITHOUT | ||
| # ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, | ||
| # SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See the GNU Lesser General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU Lesser General Public License along | ||
| # with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| """Public CLI command to run the linter service.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import argparse | ||
| from pathlib import Path | ||
| from typing import cast | ||
|
|
||
| from craft_cli import emit | ||
|
|
||
| from craft_application.commands import base | ||
| from craft_application.lint import IgnoreConfig, IgnoreSpec, LintContext, Stage | ||
|
|
||
|
|
||
| def _parse_ignore_rule(value: str) -> tuple[str, str, str | None]: | ||
| """Parse and validate a CLI ignore rule.""" | ||
| if ":" not in value: | ||
| raise argparse.ArgumentTypeError( | ||
| "Lint ignore rules must be in the form 'linter:id' or 'linter:id=glob'." | ||
| ) | ||
| linter, remainder = value.split(":", 1) | ||
| if not linter or not remainder: | ||
| raise argparse.ArgumentTypeError( | ||
| "Lint ignore rules must provide a linter name and issue id." | ||
| ) | ||
|
|
||
| if "=" in remainder: | ||
| issue, glob = remainder.split("=", 1) | ||
| if not issue or not glob: | ||
| raise argparse.ArgumentTypeError( | ||
| "Lint ignore glob rules must be in the form 'linter:id=glob'." | ||
| ) | ||
| return linter, issue, glob | ||
|
|
||
| return linter, remainder, None | ||
|
|
||
|
|
||
| def _build_cli_ignore_config(rules: list[tuple[str, str, str | None]]) -> IgnoreConfig: | ||
| """Convert parsed CLI ignore tuples into an IgnoreConfig.""" | ||
| config: IgnoreConfig = {} | ||
| for linter, issue, glob in rules: | ||
| spec = config.setdefault(linter, IgnoreSpec(ids=set(), by_filename={})) | ||
| if issue == "*": | ||
| spec.ids = "*" | ||
| spec.by_filename.clear() | ||
| continue | ||
| if spec.ids == "*": | ||
| continue | ||
| if glob is None: | ||
| if not isinstance(spec.ids, set): | ||
| spec.ids = set() | ||
| spec.ids.add(issue) | ||
| else: | ||
| spec.by_filename.setdefault(issue, set()).add(glob) | ||
| return config | ||
|
|
||
|
|
||
| class LintCommand(base.AppCommand): | ||
| """Run project linters.""" | ||
|
|
||
| name = "lint" | ||
| help_msg = "Run linters against the project (pre) or artifacts (post)." | ||
| overview = "Run linters against the project (pre) or artifacts (post)." | ||
|
|
||
| def fill_parser(self, parser: argparse.ArgumentParser) -> None: | ||
| """Add command-line arguments for lint configuration.""" | ||
| parser.add_argument( | ||
| "--stage", | ||
| choices=list(Stage), | ||
| default=Stage.PRE, | ||
| type=Stage, | ||
| help="When to lint: 'pre' = source tree, 'post' = built artifacts.", | ||
| ) | ||
| parser.add_argument( | ||
| "--lint-ignore", | ||
| action="append", | ||
| dest="lint_ignores", | ||
| type=_parse_ignore_rule, | ||
| default=[], | ||
| metavar="RULE", | ||
| help=( | ||
| "Ignore rule of the form 'linter:id' (ignore id everywhere) or " | ||
| "'linter:id=glob' (ignore id when filename matches glob). May repeat." | ||
| ), | ||
| ) | ||
| parser.add_argument( | ||
| "--lint-ignore-file", | ||
| action="append", | ||
| type=Path, | ||
| dest="lint_ignore_files", | ||
| default=[], | ||
| metavar="PATH", | ||
| help=("Path to YAML ignore file. May repeat. CLI rules take precedence."), | ||
| ) | ||
|
|
||
| def run(self, parsed_args: argparse.Namespace) -> int | None: | ||
| """Execute lint for the requested stage and return the exit code.""" | ||
| services = self._services | ||
| stage: Stage = parsed_args.stage | ||
|
|
||
| # Resolve project dir | ||
| project_service = services.get("project") | ||
| project_file = project_service.resolve_project_file_path() | ||
| project_dir: Path = project_file.parent | ||
| filename = project_file.name | ||
| if stage == Stage.POST and not project_service.is_configured: | ||
| project_service.configure(platform=None, build_for=None) | ||
| project_service.get() | ||
|
|
||
| artifact_dirs: list[Path] = [] | ||
| if stage == Stage.POST: | ||
| lifecycle = services.get("lifecycle") | ||
| artifact_dirs = [lifecycle.prime_dir] | ||
|
|
||
| ctx = LintContext(project_dir=project_dir, artifact_dirs=artifact_dirs) | ||
|
|
||
| linter = services.get("linter") | ||
| cli_ignore_rules = cast( | ||
| list[tuple[str, str, str | None]], parsed_args.lint_ignores | ||
| ) | ||
| cli_ignore_config = _build_cli_ignore_config(cli_ignore_rules) | ||
| linter.load_ignore_config( | ||
| project_dir=project_dir, | ||
| cli_ignores=cli_ignore_config or None, | ||
| cli_ignore_files=cast(list[Path], parsed_args.lint_ignore_files), | ||
| ) | ||
| issues = list(linter.run(stage, ctx)) | ||
|
|
||
| if issues: | ||
| emit.message("lint results:") | ||
| for linter_name, linter_issues in linter.issues_by_linter.items(): | ||
| emit.message(f"{linter_name}:") | ||
| for issue in linter_issues: | ||
| location = f" ({issue.filename})" if issue.filename else "" | ||
| emit.message( | ||
| f" - [{issue.severity.name}] {issue.id}: {issue.message}{location}" | ||
| ) | ||
|
|
||
| highest = linter.get_highest_severity() | ||
| if highest is None: | ||
| emit.message(f"Linted {filename} successfully.") | ||
| return 0 | ||
| if highest.name == "ERROR": | ||
| emit.message(f"Errors found in {filename}") | ||
| return 2 | ||
|
|
||
| emit.message(f"Possible issues found in {filename}") | ||
| return 0 | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,42 @@ | ||
| # This file is part of craft-application. | ||
| # | ||
| # Copyright 2025 Canonical Ltd. | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify it | ||
| # under the terms of the GNU Lesser General Public License version 3, as | ||
| # published by the Free Software Foundation. | ||
| # | ||
| # This program is distributed in the hope that it will be useful, but WITHOUT | ||
| # ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, | ||
| # SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See the GNU Lesser General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU Lesser General Public License along | ||
| # with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| """Linter framework public API surface.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from ._types import ( | ||
| ExitCode, | ||
| IgnoreConfig, | ||
| IgnoreSpec, | ||
| LintContext, | ||
| LinterIssue, | ||
| Severity, | ||
| Stage, | ||
| should_ignore, | ||
| ) | ||
| from .base import AbstractLinter | ||
|
|
||
| __all__ = [ | ||
| "ExitCode", | ||
| "IgnoreConfig", | ||
| "IgnoreSpec", | ||
| "LintContext", | ||
| "LinterIssue", | ||
| "Severity", | ||
| "Stage", | ||
| "should_ignore", | ||
| "AbstractLinter", | ||
| ] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,104 @@ | ||
| # This file is part of craft-application. | ||
| # | ||
| # Copyright 2025 Canonical Ltd. | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify it | ||
| # under the terms of the GNU Lesser General Public License version 3, as | ||
| # published by the Free Software Foundation. | ||
| # | ||
| # This program is distributed in the hope that it will be useful, but WITHOUT | ||
| # ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, | ||
| # SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See the GNU Lesser General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU Lesser General Public License along | ||
| # with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| """Types and helpers for the linter service.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from enum import Enum, IntEnum | ||
| from fnmatch import fnmatch | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| if TYPE_CHECKING: # pragma: no cover | ||
| from pathlib import Path | ||
|
|
||
|
|
||
| class Stage(str, Enum): | ||
| """Lifecycle stage for linting.""" | ||
|
|
||
| PRE = "pre" | ||
| POST = "post" | ||
|
|
||
|
|
||
| class Severity(IntEnum): | ||
| """Severity level for linter issues.""" | ||
|
|
||
| INFO = 1 | ||
| WARNING = 2 | ||
| ERROR = 3 | ||
|
|
||
|
|
||
| class ExitCode(IntEnum): | ||
| """Exit codes summarising lint results.""" | ||
|
|
||
| OK = 0 | ||
| WARN = 1 | ||
| ERROR = 2 | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class LintContext: | ||
| """Stage-agnostic environment for linters. | ||
|
|
||
| - project_dir: the source tree on disk | ||
| - artifact_dirs: list of directories with built artifacts (may be empty in pre-stage) | ||
| """ | ||
|
|
||
| project_dir: Path | ||
| artifact_dirs: list[Path] | ||
|
|
||
|
|
||
| @dataclass(frozen=True, slots=True) | ||
| class LinterIssue: | ||
| """Single issue reported by a linter.""" | ||
|
|
||
| id: str | ||
| message: str | ||
| severity: Severity | ||
| filename: str | ||
| url: str = "" | ||
|
|
||
|
|
||
| @dataclass(slots=True) | ||
| class IgnoreSpec: | ||
| """Suppression rules for one linter. | ||
|
|
||
| - ids: "*" to ignore every issue, or a set of issue ids | ||
| - by_filename: map of issue id -> set of filename globs | ||
| """ | ||
|
|
||
| ids: str | set[str] | ||
| by_filename: dict[str, set[str]] | ||
|
|
||
|
|
||
| # Map of linter.name -> IgnoreSpec | ||
| IgnoreConfig = dict[str, IgnoreSpec] | ||
|
|
||
|
|
||
| def should_ignore(linter_name: str, issue: LinterIssue, cfg: IgnoreConfig) -> bool: | ||
| """Return True when `issue` is covered by the user's ignore rules. | ||
|
|
||
| Uses issue id and optional shell-style filename globs per the approved design. | ||
| """ | ||
| spec = cfg.get(linter_name) | ||
| if not spec: | ||
| return False | ||
| if spec.ids == "*": | ||
| return True | ||
| if isinstance(spec.ids, set) and issue.id in spec.ids: | ||
| return True | ||
| globs = spec.by_filename.get(issue.id, set()) or set() | ||
| return any(fnmatch(issue.filename, g) for g in globs) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| # This file is part of craft-application. | ||
| # | ||
| # Copyright 2025 Canonical Ltd. | ||
| # | ||
| # This program is free software: you can redistribute it and/or modify it | ||
| # under the terms of the GNU Lesser General Public License version 3, as | ||
| # published by the Free Software Foundation. | ||
| # | ||
| # This program is distributed in the hope that it will be useful, but WITHOUT | ||
| # ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, | ||
| # SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. | ||
| # See the GNU Lesser General Public License for more details. | ||
| # | ||
| # You should have received a copy of the GNU Lesser General Public License along | ||
| # with this program. If not, see <http://www.gnu.org/licenses/>. | ||
| """Abstract base for linters used by the linter service.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import inspect as _inspect | ||
| from abc import ABC, abstractmethod | ||
| from typing import TYPE_CHECKING | ||
|
|
||
| from ._types import Stage as _Stage | ||
|
|
||
| if TYPE_CHECKING: # pragma: no cover | ||
| from collections.abc import Iterable | ||
|
|
||
| from ._types import LintContext, LinterIssue, Stage | ||
|
|
||
|
|
||
| class AbstractLinter(ABC): | ||
| """Base class for all linters. | ||
|
|
||
| Linters should set: | ||
| - name: stable identifier (used in ignore config) | ||
| - stage: Stage.PRE or Stage.POST | ||
| """ | ||
|
|
||
| name: str | ||
| stage: Stage | ||
|
|
||
| def __init_subclass__(cls) -> None: | ||
| """Validate subclass has required attributes.""" | ||
| super().__init_subclass__() | ||
|
|
||
| if _inspect.isabstract(cls): | ||
| return | ||
|
|
||
| if not isinstance(getattr(cls, "name", None), str) or not cls.name: | ||
| raise TypeError("Linter subclass must define a non-empty 'name' string.") | ||
| if not isinstance(getattr(cls, "stage", None), _Stage): | ||
| raise TypeError("Linter subclass must define 'stage' as a Stage enum.") | ||
|
|
||
| @abstractmethod | ||
| def run(self, ctx: LintContext) -> Iterable[LinterIssue]: | ||
| """Execute the linter and yield issues.""" |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
From some initial testing, it seems that YAML syntax errors never reach this code. Instead,
YamlError(I believe) interrupts. Is this expected?Source:
Result:
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, this is expected.
Invalid YAML is treated as a fatal parsing error, so the lint results block isn’t reached. This is expected for now, unless we decide to convert YAML errors into lint issues explicitly.