diff --git a/.github/workflows/archlens-health.yml b/.github/workflows/archlens-health.yml new file mode 100644 index 0000000..77cdd71 --- /dev/null +++ b/.github/workflows/archlens-health.yml @@ -0,0 +1,31 @@ +name: ArchLens health + +# Runs ArchLens's own action on this repository: on demand and once a week. +# Not on every push: the score reads repository metadata, which rarely changes between commits. +on: + workflow_dispatch: + inputs: + min-score: + description: Fail when the score is below this (0-100). Empty means never fail. + required: false + default: "" + schedule: + - cron: "0 6 * * 1" # Mondays, 06:00 UTC + +permissions: + contents: read + +jobs: + health: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: ArchLens + id: archlens + uses: ./ + with: + min-score: ${{ inputs.min-score }} + - name: Show outputs + run: | + echo "Score: ${{ steps.archlens.outputs.score }} (${{ steps.archlens.outputs.grade }})" + echo "Known vulnerabilities: ${{ steps.archlens.outputs.vulnerabilities }}" diff --git a/CHANGELOG.md b/CHANGELOG.md index 9f26cbe..1488e76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ All notable changes to the ArchLens project will be documented in this file. ## [Unreleased] ### Added +- **GitHub Action:** `action.yml` (composite) runs the CLI on a repository (default: the current one) with the workflow token, writes the Markdown report to the job summary, sets outputs `score`, `grade` and `vulnerabilities`, fails below an optional `min-score`, and optionally posts or updates one pull-request comment. `.github/workflows/archlens-health.yml` runs it on ArchLens itself weekly and on demand. The CLI gained `--format rich|markdown|json`, `--min-score` (exit code 2 below it) and `--output-dir`. - **Dependencies and known vulnerabilities:** reads `requirements*.txt`, `pyproject.toml`, `package.json` (+ lockfile) and `go.mod` from the repository root, lists direct dependencies as pinned or not, and checks pinned versions against OSV.dev with severity, advisory link and the version to upgrade to. Shown on the report page, in the JSON API (`dependency_scan`), the Markdown export and the CLI; stored in a new `metrics.dependencies_json` column (migration `a1c5e8f20b64`). OSV or GitHub trouble degrades to "couldn't check", never a failed analysis. The score formula is unchanged. See `docs/walkthroughs/01-dependency-vulnerabilities.md`. - `docs/roadmap.md` now records the decision to build three features and why the other ideas were dropped or deferred. - **Live progress:** `POST /api/v1/analyze/stream` streams an analysis's progress as newline-delimited JSON (`validate`, `reuse`, one `fetch` event per finished GitHub call, `analyze`, `score`, `save`, then `done` or `error`). The home page's "How it works" steps light up from these events; without JavaScript the form posts as before. diff --git a/README.md b/README.md index f5b7d6f..f7da72e 100644 --- a/README.md +++ b/README.md @@ -110,8 +110,12 @@ From the command line: ```bash archlens analyze psf/requests archlens analyze https://github.com/pallets/flask --profile personal +archlens analyze psf/requests --format json --min-score 70 # machine-readable; exit code 2 if below 70 +archlens analyze psf/requests --format markdown --output-dir out/ # also writes report.md, result.json, comment.md ``` +`--format` is `rich` (default), `markdown` or `json`; the last two print only the report on stdout and send messages to stderr. Exit codes: `0` success, `1` the analysis failed, `2` the score is below `--min-score`. + ### Configuration | Variable | Default | Purpose | @@ -126,6 +130,44 @@ archlens analyze https://github.com/pallets/flask --profile personal Copy `.env.example` to `.env` to set these locally. `python scripts/build_examples.py` regenerates the bundled example reports from live analyses. +## GitHub Action + +ArchLens ships a composite GitHub Action (`action.yml` at the repository root). It installs ArchLens from this repository, analyzes a repository with the workflow's own `GITHUB_TOKEN`, writes the Markdown report to the job summary, exposes outputs, can fail the job below a minimum score and can keep one comment up to date on pull requests. + +```yaml +name: Repository health +on: + pull_request: + schedule: + - cron: "0 6 * * 1" + +permissions: + contents: read + pull-requests: write # only needed for comment: true + +jobs: + archlens: + runs-on: ubuntu-latest + steps: + - uses: vishnuatgit/ArchLens@main + id: health + with: + min-score: 60 # optional: fail the job below this score + comment: true # optional: one comment on pull requests, updated in place + - run: echo "Score ${{ steps.health.outputs.score }} (${{ steps.health.outputs.grade }}), ${{ steps.health.outputs.vulnerabilities }} known vulnerabilities" +``` + +| Input | Default | Meaning | +| :--- | :--- | :--- | +| `repository` | the current repository | `owner/name` to analyze | +| `profile` | `library` | `library`, `personal` or `enterprise` | +| `min-score` | empty (never fails) | fail the job when the score is lower | +| `comment` | `false` | on `pull_request` events, post or update a single ArchLens comment (score, grade, top fixes, dependency summary) | +| `github-token` | `github.token` | token used to read repository metadata | +| `python-version` | `3.11` | Python used to run ArchLens | + +Outputs: `score`, `grade`, and `vulnerabilities` (known vulnerabilities in pinned dependencies; empty when they could not be checked). Notes: use an Ubuntu runner; pull requests from forks get a read-only token, so the comment is skipped with a warning and the rest still works; the score describes the repository's metadata, not the pull request's diff. This repository runs the action on itself weekly and on demand (`.github/workflows/archlens-health.yml`). Details in [docs/walkthroughs/02-github-action.md](docs/walkthroughs/02-github-action.md). + ## Tests The same checks CI runs: diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..e0fc4d7 --- /dev/null +++ b/action.yml @@ -0,0 +1,145 @@ +name: ArchLens health check +description: >- + Score a GitHub repository's engineering health (0-100), write the report to the job summary, + optionally fail below a minimum score, and optionally keep one pull-request comment up to date. +author: vishnuatgit +branding: + icon: activity + color: blue + +inputs: + repository: + description: Repository to analyze as owner/name. Defaults to the repository running the workflow. + required: false + default: ${{ github.repository }} + profile: + description: "Scoring profile: library, personal or enterprise." + required: false + default: library + min-score: + description: Fail the job when the score is below this number (0-100). Leave empty to never fail. + required: false + default: "" + comment: + description: >- + "true" to post or update a single ArchLens comment on pull requests (needs + `pull-requests: write` permission). Ignored on other events. + required: false + default: "false" + github-token: + description: Token used to read repository metadata from the GitHub API. + required: false + default: ${{ github.token }} + python-version: + description: Python version used to run ArchLens (3.11 or newer). + required: false + default: "3.11" + +outputs: + score: + description: The 0-100 health score. + value: ${{ steps.analyze.outputs.score }} + grade: + description: The letter grade, A+ to F. + value: ${{ steps.analyze.outputs.grade }} + vulnerabilities: + description: Number of known vulnerabilities in pinned dependencies. Empty when they could not be checked. + value: ${{ steps.analyze.outputs.vulnerabilities }} + +runs: + using: composite + steps: + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: ${{ inputs.python-version }} + + - name: Install ArchLens + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + run: python -m pip install --quiet --editable "$ACTION_PATH" + + - name: Analyze + id: analyze + shell: bash + env: + ACTION_PATH: ${{ github.action_path }} + GITHUB_TOKEN: ${{ inputs.github-token }} + REPOSITORY: ${{ inputs.repository }} + PROFILE: ${{ inputs.profile }} + MIN_SCORE: ${{ inputs.min-score }} + run: | + out="$RUNNER_TEMP/archlens" + mkdir -p "$out" + # A throwaway database: the CLI stores its report like the web app does + export DATABASE_URL="sqlite:///${out//\\//}/archlens.db" + export OUT_DIR="$out" + alembic -c "$ACTION_PATH/alembic.ini" upgrade head > /dev/null + + args=(analyze "$REPOSITORY" --profile "$PROFILE" --format json --output-dir "$out") + if [ -n "$MIN_SCORE" ]; then args+=(--min-score "$MIN_SCORE"); fi + + set +e + archlens "${args[@]}" + code=$? + set -e + + # 1 means the analysis itself failed; 2 means the score is below min-score + if [ "$code" -eq 1 ]; then + echo "::error::ArchLens could not analyze $REPOSITORY. See the log above." + exit 1 + fi + + python - <<'PY' + import json + import os + + with open(os.path.join(os.environ["OUT_DIR"], "result.json"), encoding="utf-8") as f: + result = json.load(f) + count = result["vulnerability_count"] + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as f: + f.write(f"score={result['score']}\n") + f.write(f"grade={result['grade']}\n") + f.write(f"vulnerabilities={'' if count is None else count}\n") + PY + echo "exit-code=$code" >> "$GITHUB_OUTPUT" + + - name: Write job summary + shell: bash + run: cat "$RUNNER_TEMP/archlens/report.md" >> "$GITHUB_STEP_SUMMARY" + + - name: Post or update the pull-request comment + if: inputs.comment == 'true' && github.event_name == 'pull_request' + # Pull requests from forks get a read-only token and cannot comment: warn, do not fail + continue-on-error: true + uses: actions/github-script@v7 + env: + COMMENT_FILE: ${{ runner.temp }}/archlens/comment.md + with: + github-token: ${{ inputs.github-token }} + script: | + const fs = require('fs'); + const body = fs.readFileSync(process.env.COMMENT_FILE, 'utf8'); + const marker = ''; + const { owner, repo } = context.repo; + const issue_number = context.payload.pull_request.number; + const comments = await github.paginate(github.rest.issues.listComments, { + owner, repo, issue_number, per_page: 100, + }); + const existing = comments.find((c) => c.body && c.body.includes(marker)); + if (existing) { + await github.rest.issues.updateComment({ owner, repo, comment_id: existing.id, body }); + } else { + await github.rest.issues.createComment({ owner, repo, issue_number, body }); + } + + - name: Enforce the minimum score + if: steps.analyze.outputs.exit-code == '2' + shell: bash + env: + SCORE: ${{ steps.analyze.outputs.score }} + MIN_SCORE: ${{ inputs.min-score }} + run: | + echo "::error::ArchLens score $SCORE is below the minimum of $MIN_SCORE." + exit 1 diff --git a/app/cli.py b/app/cli.py index 00bdf9a..7012645 100644 --- a/app/cli.py +++ b/app/cli.py @@ -1,5 +1,9 @@ import asyncio +import json import sys +from contextlib import nullcontext +from enum import StrEnum +from pathlib import Path # Force UTF-8 encoding for Windows console (fixes UnicodeEncodeError for checkmarks) if sys.stdout.encoding.lower() != "utf-8": @@ -16,13 +20,28 @@ RateLimitExceededError, RepositoryNotFoundError, ) +from app.models.db_models import Analysis from app.repositories.db import SessionLocal from app.services.analysis_service import AnalysisService from app.services.dependency_service import SCORE_NOTE, DependencyScan from app.services.metrics_service import DIMENSION_MAX_POINTS, score_tier +from app.services.report_export import report_to_comment, report_to_markdown, report_to_summary +from app.services.report_view import ReportView, build_report_view app = typer.Typer(help="ArchLens CLI - engineering health scoring for GitHub repositories") console = Console() +# Messages that must not mix with a Markdown or JSON report printed on stdout +err_console = Console(stderr=True) + +# Exit codes: 0 success, 1 the analysis failed, 2 the score is below --min-score +EXIT_ERROR = 1 +EXIT_BELOW_MIN_SCORE = 2 + + +class OutputFormat(StrEnum): + RICH = "rich" + MARKDOWN = "markdown" + JSON = "json" @app.callback() @@ -42,7 +61,10 @@ async def async_analyze(url: str, profile: str) -> dict: db = SessionLocal() try: # Run the full pipeline - return await service.run(db=db, url=url, repo_type=profile) + result = await service.run(db=db, url=url, repo_type=profile) + # The stored report feeds the Markdown, JSON and comment outputs + result["report"] = build_report_view(db.get(Analysis, result["analysis_id"])) + return result finally: db.close() await service.github.aclose() @@ -82,53 +104,18 @@ def print_dependencies(scan_data: dict | None) -> None: console.print(f" [dim]{SCORE_NOTE}[/dim]") -@app.command() -def analyze( - url: str = typer.Argument( - ..., - help="The public GitHub repository URL to analyze (e.g., https://github.com/fastapi/fastapi)", - ), - profile: str = typer.Option( - "library", - "--profile", - "-p", - help="Repository profile type: 'library', 'personal', or 'enterprise'", - ), -): - """ - Run an engineering analysis on a GitHub repository. - """ - console.print( - f"[bold cyan]ArchLens CLI[/bold cyan] » Analyzing [bold]{url}[/bold] (Profile: {profile})" +def write_report_files(report: ReportView, directory: Path) -> None: + """Writes report.md, result.json and comment.md for the GitHub Action to publish.""" + directory.mkdir(parents=True, exist_ok=True) + (directory / "report.md").write_text(report_to_markdown(report), encoding="utf-8") + (directory / "result.json").write_text( + json.dumps(report_to_summary(report), indent=2), encoding="utf-8" ) + (directory / "comment.md").write_text(report_to_comment(report), encoding="utf-8") - # Run the analysis with a spinning progress indicator - with console.status( - "[bold green]Fetching repository data and running analysis...", spinner="dots" - ): - try: - result = asyncio.run(async_analyze(url, profile)) - except InvalidRepositoryURLError: - console.print( - f"[bold red]Error:[/bold red] Invalid GitHub repository URL provided: {url}" - ) - raise typer.Exit(code=1) - except RepositoryNotFoundError as e: - console.print(f"[bold red]Error:[/bold red] {str(e)}") - raise typer.Exit(code=1) - except RateLimitExceededError as e: - console.print( - f"[bold red]Error:[/bold red] GitHub API rate limit exceeded. Reset time: {e.reset_epoch}" - ) - raise typer.Exit(code=1) - except ArchLensError as e: - console.print(f"[bold red]Error:[/bold red] {e.message}") - raise typer.Exit(code=1) - except Exception as e: - console.print(f"[bold red]Error:[/bold red] An unexpected error occurred: {str(e)}") - raise typer.Exit(code=1) - # Output formatting +def print_rich_report(result: dict) -> None: + """The terminal report: summary panel, dimension table, findings, dependencies.""" console.print("\n[bold green]✔ Analysis Complete[/bold green]") score = result["score"] @@ -182,5 +169,96 @@ def analyze( console.print("\n") +@app.command() +def analyze( + url: str = typer.Argument( + ..., + help="The public GitHub repository URL to analyze (e.g., https://github.com/fastapi/fastapi)", + ), + profile: str = typer.Option( + "library", + "--profile", + "-p", + help="Repository profile type: 'library', 'personal', or 'enterprise'", + ), + output_format: OutputFormat = typer.Option( + OutputFormat.RICH, + "--format", + "-f", + help="rich (terminal report), markdown or json. The last two print only the report.", + ), + min_score: int | None = typer.Option( + None, + "--min-score", + min=0, + max=100, + help="Exit with code 2 when the score is below this (the report is still printed).", + ), + output_dir: Path | None = typer.Option( + None, + "--output-dir", + help="Also write report.md, result.json and comment.md into this folder.", + ), +): + """ + Run an engineering analysis on a GitHub repository. + """ + rich_output = output_format is OutputFormat.RICH + # A Markdown or JSON report owns stdout, so messages go to stderr instead + notify = console if rich_output else err_console + if rich_output: + console.print( + f"[bold cyan]ArchLens CLI[/bold cyan] » Analyzing [bold]{url}[/bold] (Profile: {profile})" + ) + + # Run the analysis with a spinning progress indicator + spinner = ( + console.status( + "[bold green]Fetching repository data and running analysis...", spinner="dots" + ) + if rich_output + else nullcontext() + ) + with spinner: + try: + result = asyncio.run(async_analyze(url, profile)) + except InvalidRepositoryURLError: + notify.print( + f"[bold red]Error:[/bold red] Invalid GitHub repository URL provided: {url}" + ) + raise typer.Exit(code=EXIT_ERROR) + except RepositoryNotFoundError as e: + notify.print(f"[bold red]Error:[/bold red] {str(e)}") + raise typer.Exit(code=EXIT_ERROR) + except RateLimitExceededError as e: + notify.print( + f"[bold red]Error:[/bold red] GitHub API rate limit exceeded. Reset time: {e.reset_epoch}" + ) + raise typer.Exit(code=EXIT_ERROR) + except ArchLensError as e: + notify.print(f"[bold red]Error:[/bold red] {e.message}") + raise typer.Exit(code=EXIT_ERROR) + except Exception as e: + notify.print(f"[bold red]Error:[/bold red] An unexpected error occurred: {str(e)}") + raise typer.Exit(code=EXIT_ERROR) + + report = result.get("report") + if output_dir is not None and report is not None: + write_report_files(report, output_dir) + + if output_format is OutputFormat.MARKDOWN: + typer.echo(report_to_markdown(report)) + elif output_format is OutputFormat.JSON: + typer.echo(json.dumps(report_to_summary(report), indent=2)) + else: + print_rich_report(result) + + if min_score is not None and result["score"] < min_score: + notify.print( + f"[bold red]Score {result['score']} is below the minimum of {min_score}.[/bold red]" + ) + raise typer.Exit(code=EXIT_BELOW_MIN_SCORE) + + if __name__ == "__main__": app() diff --git a/app/services/report_export.py b/app/services/report_export.py index b418345..0428314 100644 --- a/app/services/report_export.py +++ b/app/services/report_export.py @@ -141,3 +141,78 @@ def report_to_markdown(report: ReportView, report_url: str | None = None) -> str def markdown_filename(report: ReportView) -> str: """A download name such as 'archlens-psf-requests-2026-10-31.md'.""" return f"archlens-{report.owner}-{report.name}-{report.created_at:%Y-%m-%d}.md".lower() + + +# Hidden marker that lets the GitHub Action find its own pull-request comment and update it +COMMENT_MARKER = "" +COMMENT_FIX_LIMIT = 3 + + +def _top_fixes(report: ReportView, limit: int = COMMENT_FIX_LIMIT): + plan = build_fix_plan(report, build_evidence(report)) + return list(plan.fixes[:limit]) if plan else [] + + +def report_to_comment(report: ReportView, report_url: str | None = None) -> str: + """A short Markdown comment for a pull request: score, grade, top fixes, dependencies.""" + lines = [ + COMMENT_MARKER, + f"### ArchLens health: {report.score}/100 ({report.grade})", + "", + f"**{report.full_name}** is rated *{report.tier.label}* under the " + f"{report.profile_label.lower()} profile.", + "", + ] + fixes = _top_fixes(report) + if fixes: + lines += ["**Top fixes**", ""] + lines += [ + f"{number}. {fix.action} ({'' if fix.exact else 'up to '}+{fix.gain} points)" + for number, fix in enumerate(fixes, 1) + ] + lines.append("") + if report.dependency_scan is not None: + lines += [f"**Dependencies:** {report.dependency_scan.summary_line}", ""] + footer = f"Updated by [ArchLens]({SITE['repo_url']})" + if report_url: + footer += f" · [full report]({report_url})" + lines += [f"{footer}", ""] + return "\n".join(lines) + + +def report_to_summary(report: ReportView) -> dict: + """The machine-readable summary printed by `archlens analyze --format json`.""" + scan = report.dependency_scan + checked = scan is not None and scan.vulnerability_check == "ok" + return { + "repository": report.full_name, + "url": report.url, + "profile": report.repo_type, + "score": report.score, + "grade": report.grade, + "tier": report.tier.label, + "analyzed_at": report.created_at.isoformat(timespec="seconds"), + "dimensions": {d.key: {"points": d.points, "max": d.max_points} for d in report.dimensions}, + "top_fixes": [ + { + "action": fix.action, + "gain": fix.gain, + "exact": fix.exact, + "dimension": fix.dimension_label, + } + for fix in _top_fixes(report, limit=10) + ], + "dependencies": ( + None + if scan is None + else { + "status": scan.status, + "total": len(scan.dependencies), + "pinned": scan.pinned_count, + "vulnerability_check": scan.vulnerability_check, + "vulnerabilities": scan.to_dict()["vulnerabilities"] if checked else [], + } + ), + # None when nothing could be checked, so a gate never mistakes "unknown" for "zero" + "vulnerability_count": len(scan.vulnerabilities) if checked else None, + } diff --git a/docs/walkthroughs/02-github-action.md b/docs/walkthroughs/02-github-action.md new file mode 100644 index 0000000..1812c7b --- /dev/null +++ b/docs/walkthroughs/02-github-action.md @@ -0,0 +1,104 @@ +# Walkthrough 2: the GitHub Action health gate + +## What it does and why it matters + +A score on a web page is read once and forgotten. The Action puts ArchLens where the team already looks: + +- the **job summary** of a workflow run shows the full Markdown report; +- **outputs** (`score`, `grade`, `vulnerabilities`) can feed later steps; +- an optional **`min-score`** fails the job when the repository drops below a number, so health becomes a gate; +- an optional **pull-request comment** (`comment: true`) shows the score, grade, top fixes and the dependency + summary, and is **updated in place** instead of adding a new comment on every push. + +By default it analyzes the repository running the workflow, using the workflow's own `GITHUB_TOKEN`. No secrets +and no ArchLens server are needed: it runs the same CLI you run locally. + +Per-pull-request scoring was deliberately not built. ArchLens scores repository metadata (files, activity, +community), which a single pull request barely changes, so a per-PR score would almost always be the same number. +The comment reports the repository's current health and what to fix first. + +## How it works end to end + +``` +workflow step: uses: vishnuatgit/ArchLens@main action.yml (composite) + 1. actions/setup-python Python 3.11 by default + 2. pip install --editable $GITHUB_ACTION_PATH installs ArchLens and its dependencies from the repo + 3. "Analyze" (bash) + alembic upgrade head creates a throwaway SQLite database in RUNNER_TEMP + archlens analyze $REPOSITORY --format json + --output-dir $RUNNER_TEMP/archlens [--min-score N] + -> app/cli.py -> AnalysisService.run() the same pipeline as the web app + -> writes report.md, result.json, comment.md + exit 1 -> the analysis failed: fail the step + exit 2 -> below min-score: remember it, carry on + read result.json -> outputs score, grade, vulnerabilities + 4. "Write job summary" cat report.md >> $GITHUB_STEP_SUMMARY + 5. "Post or update comment" actions/github-script, only if comment == true and the event is pull_request + 6. "Enforce the minimum score" fails the job if step 3 saw exit code 2 +``` + +Files: `action.yml`, `app/cli.py` (`--format`, `--min-score`, `--output-dir`, `write_report_files`), +`app/services/report_export.py` (`report_to_comment`, `report_to_summary`), +`.github/workflows/archlens-health.yml` (the Action running on ArchLens itself on `workflow_dispatch` and a weekly +schedule, not on every push), `tests/unit/test_action.py`, `tests/unit/test_cli.py`. + +Details worth knowing: + +- **Exit codes** are the contract between the CLI and the Action: `0` fine, `1` the analysis failed (not found, rate + limit, GitHub down), `2` the score is below `--min-score`. The gate happens in the last step so that the summary + and the comment are still published when the check fails. That is when people most want to read them. +- **Machine output.** With `--format json` or `markdown` stdout holds only the report; messages go to stderr. The + `result.json` file has the score, grade, dimension points, top fixes, dependency counts and + `vulnerability_count`. That count is `null` (an empty output) when OSV could not be reached, so a gate never + mistakes "unknown" for "zero". +- **One comment, updated.** `comment.md` starts with a hidden marker (``). The + script lists the pull request's comments, finds the one with the marker and updates it, or creates it. +- **Safe inputs.** Inputs reach the shell through `env:`, never pasted into the script text with `${{ }}`. A + pull-request title or repository name containing shell syntax therefore cannot run as code. A test enforces it. +- **Forks.** Pull requests from forks get a read-only token and cannot comment. The comment step has + `continue-on-error: true`, so the job still finishes with the summary and the gate. +- **Database.** The CLI stores reports in a SQLite file; in the Action that file lives in a temporary folder and is + discarded with the runner. + +## Design choices and trade-offs + +| Choice | Why | Cost | +|---|---|---| +| Composite action, not Docker or JavaScript | No image to build or host; reuses the CLI; free | Installs Python packages on every run (about 20-30 seconds); needs a Linux runner for the shell steps | +| `pip install --editable` the action path | The project's packaging lists only the top-level `app` package, so a normal install would miss subpackages; an editable install works from the checked-out action | Not a published wheel | +| Gate in a separate last step | Summary and comment are published even when the gate fails | One more step | +| Exit code 2 for "below minimum" | Separates "the tool broke" from "the repository is below the bar" | Callers must know the two codes | +| `github-script` for the comment | Official action, no extra dependency, a few lines of JavaScript | Needs `pull-requests: write` | +| Weekly + manual dogfood workflow | The score reads metadata that rarely changes between commits, so every push would be noise and API quota | A regression can wait up to a week to show | +| Default token | Works with no setup | The workflow token can only read repositories it has access to, which is what you want for "the current one" | + +## Limits + +- Linux runners (the scripts use bash and POSIX paths). +- The score is about repository metadata, not about the code in the pull request. +- Fork pull requests cannot post the comment. +- Uses `@main` of this repository unless you pin a tag or commit; pin one for reproducible builds. +- GitHub API quota: one analysis costs 7 to 12 requests; the workflow token allows 1,000 per hour per repository. + +## Likely interview questions + +1. **Why a composite action?** It only needs to install and run a Python CLI. A composite action has no image to + build and no JavaScript to maintain, and it reuses the code and tests of the CLI. +2. **How does `min-score` fail the job but still publish the report?** The CLI exits with code 2 after writing its + output. The analyze step records the code and continues; the summary and comment run; a final step fails the + job. Exit 1 (a real error) fails at once. +3. **How do you avoid duplicate comments?** A hidden HTML marker in the body. The script finds the comment that + contains it and updates it; only if none exists does it create one. +4. **Is it safe against injection from inputs?** Inputs go through environment variables and the script quotes + them. Pasting `${{ inputs.x }}` into a script is the classic injection hole, and a unit test fails if anyone + does it. +5. **What happens on a pull request from a fork?** The token is read-only, so the comment request is denied. That + step is `continue-on-error`, so you get a warning and the rest of the job (summary, gate) still works. +6. **Why not run it on every push?** The score reads repository metadata that rarely changes between commits, and + each run spends API quota. A weekly and manual run is enough to catch drift. +7. **How did you test an Action without GitHub?** `action.yml` is parsed in a unit test (composite, inputs and + defaults, outputs wired to real step ids, shells set, pinned versions, comment guard, gate condition). The CLI + behaviour is tested with Typer's runner, and an integration test runs the real pipeline with fake GitHub and + OSV and checks the files the Action publishes. I also ran the Analyze step's script locally against GitHub. +8. **Why did you need `alembic upgrade head` in the Action?** The CLI saves each report to the database like the + web app does, and a fresh runner has an empty file. Alembic creates the schema the same way as in production. diff --git a/pyproject.toml b/pyproject.toml index 18d8f45..71cd4f5 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,6 +37,7 @@ dev = [ "ruff>=0.4.9", "black>=24.4.2", "pre-commit>=3.7.1", + "pyyaml>=6.0", ] [tool.pytest.ini_options] diff --git a/requirements-dev.txt b/requirements-dev.txt index 294fdbe..63be472 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,3 +7,4 @@ pytest-mock>=3.14.0 # Keep in sync with the lint job in .github/workflows/ci.yml ruff==0.17.2 black==26.10.1 +pyyaml>=6.0 diff --git a/tests/integration/test_dependencies_e2e.py b/tests/integration/test_dependencies_e2e.py index 49500f7..3f5a666 100644 --- a/tests/integration/test_dependencies_e2e.py +++ b/tests/integration/test_dependencies_e2e.py @@ -205,3 +205,47 @@ def test_stream_reports_a_dependencies_step(): deps = [e for e in events if e.get("step") == "dependencies" and "vulnerabilities" in e] assert deps and deps[0]["vulnerabilities"] == 1 assert events[-1]["event"] == "done" + + +def test_cli_runs_the_real_pipeline_and_writes_the_files_the_action_publishes( + monkeypatch, tmp_path +): + """The CLI as the GitHub Action runs it: real service and database, fake GitHub and OSV.""" + import json as json_module + + from typer.testing import CliRunner + + from app import cli + + def fake_service(): + service = AnalysisService(osv_client=fake_osv()) + service.github._client = fake_github( + ["README.md", "requirements.txt"], {"requirements.txt": REQUIREMENTS} + ) + return service + + monkeypatch.setattr(cli, "AnalysisService", fake_service) + monkeypatch.setattr(cli, "SessionLocal", TestSessionLocal) + out = tmp_path / "out" + + result = CliRunner().invoke( + cli.app, + [ + "analyze", + "acme/widget", + "--format", + "json", + "--output-dir", + str(out), + "--min-score", + "99", + ], + ) + + assert result.exit_code == 2 # the score is below 99, and the report is still produced + summary = json_module.loads(result.stdout) + assert summary["vulnerability_count"] == 1 + assert json_module.loads((out / "result.json").read_text(encoding="utf-8")) == summary + assert "GHSA-xxxx-yyyy-zzzz" in (out / "report.md").read_text(encoding="utf-8") + comment = (out / "comment.md").read_text(encoding="utf-8") + assert comment.startswith("") and "Top fixes" in comment diff --git a/tests/unit/test_action.py b/tests/unit/test_action.py new file mode 100644 index 0000000..4371fa1 --- /dev/null +++ b/tests/unit/test_action.py @@ -0,0 +1,90 @@ +"""Structure checks for action.yml and the workflow that dogfoods it (no GitHub needed).""" + +import re +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[2] +ACTION = yaml.safe_load((ROOT / "action.yml").read_text(encoding="utf-8")) +WORKFLOW = yaml.safe_load( + (ROOT / ".github" / "workflows" / "archlens-health.yml").read_text(encoding="utf-8") +) +STEPS = ACTION["runs"]["steps"] + + +def test_action_is_a_composite_with_the_documented_inputs_and_outputs(): + assert ACTION["runs"]["using"] == "composite" + assert ACTION["name"] and ACTION["description"] + assert set(ACTION["inputs"]) == { + "repository", + "profile", + "min-score", + "comment", + "github-token", + "python-version", + } + # Sensible defaults: the current repository, the workflow's own token, no gate, no comment + assert ACTION["inputs"]["repository"]["default"] == "${{ github.repository }}" + assert ACTION["inputs"]["github-token"]["default"] == "${{ github.token }}" + assert ACTION["inputs"]["min-score"]["default"] == "" + assert ACTION["inputs"]["comment"]["default"] == "false" + assert set(ACTION["outputs"]) == {"score", "grade", "vulnerabilities"} + + +def test_every_output_points_at_a_step_that_exists_and_sets_it(): + step_ids = {step["id"]: step for step in STEPS if "id" in step} + for name, output in ACTION["outputs"].items(): + match = re.fullmatch(r"\$\{\{ steps\.(\w+)\.outputs\.([\w-]+) \}\}", output["value"]) + assert match, name + step_id, key = match.groups() + assert step_id in step_ids + assert f"{key}=" in step_ids[step_id]["run"] + + +def test_every_run_step_names_its_shell(): + for step in STEPS: + if "run" in step: + assert step.get("shell") == "bash", step.get("name") + + +def test_inputs_reach_scripts_through_env_not_string_interpolation(): + # `${{ inputs.x }}` pasted into a script is a command-injection risk; env vars are not + for step in STEPS: + assert "${{ inputs." not in step.get("run", ""), step.get("name") + + +def test_actions_used_are_pinned_to_a_major_version(): + for step in STEPS: + if "uses" in step: + assert re.search(r"@v\d+$", step["uses"]), step["uses"] + + +def test_comment_step_only_runs_when_asked_on_pull_requests_and_cannot_fail_the_job(): + (step,) = [s for s in STEPS if s.get("uses", "").startswith("actions/github-script")] + assert "inputs.comment == 'true'" in step["if"] + assert "github.event_name == 'pull_request'" in step["if"] + assert step["continue-on-error"] is True + # It updates the one comment it created before, found by a hidden marker + assert "archlens-health-comment" in step["with"]["script"] + assert "updateComment" in step["with"]["script"] and "createComment" in step["with"]["script"] + + +def test_gate_step_fails_the_job_only_for_the_below_minimum_exit_code(): + (step,) = [s for s in STEPS if s.get("name") == "Enforce the minimum score"] + assert step["if"] == "steps.analyze.outputs.exit-code == '2'" + assert "exit 1" in step["run"] + + +def test_summary_step_appends_the_markdown_report(): + (step,) = [s for s in STEPS if s.get("name") == "Write job summary"] + assert "GITHUB_STEP_SUMMARY" in step["run"] and "report.md" in step["run"] + + +def test_workflow_runs_on_demand_and_weekly_but_not_on_push(): + triggers = WORKFLOW[True] if True in WORKFLOW else WORKFLOW["on"] # YAML reads `on` as True + assert set(triggers) == {"workflow_dispatch", "schedule"} + assert re.fullmatch(r"\S+ \S+ \S+ \S+ \S+", triggers["schedule"][0]["cron"]) + assert WORKFLOW["permissions"] == {"contents": "read"} + uses = [step.get("uses") for step in WORKFLOW["jobs"]["health"]["steps"]] + assert "./" in uses # it dogfoods the action in this repository diff --git a/tests/unit/test_cli.py b/tests/unit/test_cli.py index 9531ed6..f611004 100644 --- a/tests/unit/test_cli.py +++ b/tests/unit/test_cli.py @@ -1,3 +1,4 @@ +import json from unittest.mock import patch import pytest @@ -162,3 +163,92 @@ def test_analyze_says_when_a_stored_report_was_never_scanned(mock_async_analyze) "breakdown": {}, } assert "not scanned" in runner.invoke(app, ["analyze", "t/r"]).stdout + + +# --------------------------------------------------------------------------- +# --format, --min-score and --output-dir (used by the GitHub Action) +# --------------------------------------------------------------------------- + + +@pytest.fixture +def stored_result(): + """The CLI's result for a real stored analysis, with its ReportView.""" + from sqlalchemy import create_engine + from sqlalchemy.orm import sessionmaker + + from app.repositories.db import Base + from app.services.dependency_service import DependencyScan + from app.services.report_view import build_report_view + from tests.integration.test_progress_and_pages import add_analysis + + engine = create_engine("sqlite://") + Base.metadata.create_all(bind=engine) + with sessionmaker(bind=engine)() as db: + analysis = add_analysis(db, score=77) + scan = DependencyScan(status="ok", vulnerability_check="ok", checked=2) + analysis.metrics.dependencies_json = json.dumps(scan.to_dict()) + db.commit() + report = build_report_view(analysis) + return { + "owner": "psf", + "name": "requests", + "repo_type": "library", + "score": 77, + "duration": 1.0, + "analysis_id": 1, + "breakdown": {}, + "report": report, + } + + +def test_format_json_prints_only_json(mock_async_analyze, stored_result): + mock_async_analyze.return_value = stored_result + result = runner.invoke(app, ["analyze", "psf/requests", "--format", "json"]) + assert result.exit_code == 0 + data = json.loads(result.stdout) + assert (data["score"], data["grade"], data["repository"]) == (77, "B+", "psf/requests") + assert data["vulnerability_count"] == 0 + assert data["top_fixes"] and {"action", "gain", "exact"} <= set(data["top_fixes"][0]) + + +def test_format_markdown_prints_the_report_document(mock_async_analyze, stored_result): + mock_async_analyze.return_value = stored_result + result = runner.invoke(app, ["analyze", "psf/requests", "-f", "markdown"]) + assert result.exit_code == 0 + assert result.stdout.startswith("# ArchLens report: psf/requests") + assert "## Known vulnerabilities" in result.stdout + + +def test_min_score_exit_code_depends_on_the_score(mock_async_analyze, stored_result): + mock_async_analyze.return_value = stored_result + above = runner.invoke(app, ["analyze", "psf/requests", "-f", "json", "--min-score", "77"]) + below = runner.invoke(app, ["analyze", "psf/requests", "-f", "json", "--min-score", "78"]) + assert above.exit_code == 0 + assert below.exit_code == 2 + assert json.loads(below.stdout)["score"] == 77 # the report is still printed + assert "below the minimum of 78" in below.output + + +def test_min_score_must_be_between_0_and_100(mock_async_analyze): + assert runner.invoke(app, ["analyze", "a/b", "--min-score", "101"]).exit_code == 2 + mock_async_analyze.assert_not_called() + + +def test_output_dir_gets_report_summary_and_comment(mock_async_analyze, stored_result, tmp_path): + mock_async_analyze.return_value = stored_result + out = tmp_path / "out" + result = runner.invoke(app, ["analyze", "psf/requests", "-f", "json", "--output-dir", str(out)]) + assert result.exit_code == 0 + assert (out / "report.md").read_text(encoding="utf-8").startswith("# ArchLens report") + assert json.loads((out / "result.json").read_text(encoding="utf-8"))["score"] == 77 + comment = (out / "comment.md").read_text(encoding="utf-8") + assert comment.startswith("") + assert "77/100 (B+)" in comment and "Top fixes" in comment + + +def test_errors_go_to_stderr_in_machine_formats(mock_async_analyze): + mock_async_analyze.side_effect = RepositoryNotFoundError("a", "b") + result = runner.invoke(app, ["analyze", "a/b", "--format", "json"]) + assert result.exit_code == 1 + assert result.stdout == "" + assert "not found" in result.stderr.lower()