Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions craft_application/commands/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
from .base import AppCommand, ExtensibleCommand
from . import lifecycle
from .init import InitCommand
from .lint import LintCommand
from .lifecycle import get_lifecycle_command_group, LifecycleCommand, TestCommand
from .other import get_other_command_group
from .remote import RemoteBuild # Not part of the default commands.
Expand All @@ -26,6 +27,7 @@
"AppCommand",
"ExtensibleCommand",
"InitCommand",
"LintCommand",
"RemoteBuild",
"lifecycle",
"LifecycleCommand",
Expand Down
163 changes: 163 additions & 0 deletions craft_application/commands/lint.py
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}"
)
Comment on lines +144 to +152
Copy link
Contributor

@medubelko medubelko Dec 18, 2025

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:

name: testcraft-test
version: "1.0"

base: ubuntu@24.04
platforms:
  platform-independent:
    build-on: [amd64, arm64, ppc64el, s390x, riscv64]
    build-for: [all]

parts:
  my-test:
    plugin: nil

parts:

Result:

$ testcraft lint
error parsing '(unknown)': found duplicate key 'parts'
Detailed information: 
while constructing a mapping
found duplicate key 'parts'
  in "<unicode string>", line 1, column 1:
    name: testcraft-test
    ^
Recommended resolution: Ensure (unknown) contains valid YAML

Copy link
Author

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.


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
42 changes: 42 additions & 0 deletions craft_application/lint/__init__.py
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",
]
104 changes: 104 additions & 0 deletions craft_application/lint/_types.py
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)
57 changes: 57 additions & 0 deletions craft_application/lint/base.py
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."""
Loading