From b2058cd71ef51077b36cf1b9e84958f6d4b0a45a Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Fri, 4 Dec 2026 14:10:14 +0300 Subject: [PATCH 1/2] Add opt-in PR comparisons to comments and job summaries --- .github/workflows/test.yml | 39 +++++++++++--- action.yml | 63 ++++++++++++---------- scripts/comment.cjs | 28 ++++++++++ scripts/compare.py | 69 ++++++++++++++++++++++++ tests/comment.test.cjs | 81 ++++++++++++++++++++++++++++ tests/test_comparison.py | 106 +++++++++++++++++++++++++++++++++++++ 6 files changed, 352 insertions(+), 34 deletions(-) create mode 100644 scripts/comment.cjs create mode 100644 scripts/compare.py create mode 100644 tests/comment.test.cjs create mode 100644 tests/test_comparison.py diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 2c9ebea..25e9b35 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -19,10 +19,16 @@ jobs: steps: - name: Checkout action code uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha || github.sha }} - name: Check analysis and threshold scripts shell: bash - run: bash tests/test-action.sh + run: | + bash tests/test-action.sh + python -m unittest discover -s tests -p 'test_*.py' + node --test tests/comment.test.cjs - name: Create test repository shell: bash @@ -77,11 +83,32 @@ jobs: max-risk: High max-onboarding: Hard + - name: Test PR comparison against real CLI + if: github.event_name == 'pull_request' + uses: ./ + id: comparison + with: + compare: 'true' + devscope-ref: d9849fddd644f98a67985115af74c74ff0a5230e + + - name: Verify comparison report + if: github.event_name == 'pull_request' + shell: bash + env: + COMPARISON_REPORT: ${{ steps.comparison.outputs.comparison-report }} + run: python -c "import os, pathlib; report = pathlib.Path(os.environ['COMPARISON_REPORT']).read_text(encoding='utf-8'); assert 'Devscope PR comparison' in report and '| Metric | Base | Head | Delta |' in report" + - name: Report test results if: always() + shell: bash + env: + RESULT_GRADE: ${{ steps.test-basic.outputs.grade }} + RESULT_RISK: ${{ steps.test-basic.outputs.risk }} run: | - echo "### ✅ Action Test Completed" >> $GITHUB_STEP_SUMMARY - echo "" >> $GITHUB_STEP_SUMMARY - echo "Platform: ${{ matrix.os }}" >> $GITHUB_STEP_SUMMARY - echo "Grade: ${{ steps.test-basic.outputs.grade }}" >> $GITHUB_STEP_SUMMARY - echo "Risk: ${{ steps.test-basic.outputs.risk }}" >> $GITHUB_STEP_SUMMARY + { + echo "### Action Test Completed" + echo "" + echo "Platform: $RUNNER_OS" + echo "Grade: $RESULT_GRADE" + echo "Risk: $RESULT_RISK" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/action.yml b/action.yml index ac5f53c..c3ee88e 100644 --- a/action.yml +++ b/action.yml @@ -31,8 +31,19 @@ inputs: description: 'PyPI version of devscope to install' required: false default: '0.1.1' + devscope-ref: + description: 'Optional full commit SHA from EhsanAzish80/Devscope; overrides devscope-version' + required: false + default: '' + compare: + description: 'Include an advisory PR comparison (requires a compare-capable CLI, full history and repository-root path)' + required: false + default: 'false' outputs: + comparison-report: + description: 'Path to the Markdown comparison report (empty when disabled or outside a PR)' + value: ${{ steps.compare.outputs.report-path }} health: description: 'Overall health score (0-100)' value: ${{ steps.analyze.outputs.health }} @@ -58,8 +69,17 @@ runs: shell: bash env: DEVSCOPE_VERSION: ${{ inputs.devscope-version }} + DEVSCOPE_REF: ${{ inputs.devscope-ref }} run: | - python -m pip install --disable-pip-version-check "devscope==$DEVSCOPE_VERSION" + if [[ -n "$DEVSCOPE_REF" ]]; then + if [[ ! "$DEVSCOPE_REF" =~ ^[0-9a-fA-F]{40}$ ]]; then + echo 'devscope-ref must be a full 40-character commit SHA' >&2 + exit 1 + fi + python -m pip install --disable-pip-version-check "devscope @ git+https://github.com/EhsanAzish80/Devscope.git@$DEVSCOPE_REF" + else + python -m pip install --disable-pip-version-check "devscope==$DEVSCOPE_VERSION" + fi - name: Run analysis id: analyze @@ -68,40 +88,27 @@ runs: DEVSCOPE_PATH: ${{ inputs.path }} run: bash "${{ github.action_path }}/scripts/analyze.sh" + - name: Compare PR snapshots + id: compare + if: github.event_name == 'pull_request' && inputs.compare == 'true' + shell: bash + env: + DEVSCOPE_PATH: ${{ inputs.path }} + DEVSCOPE_BASE: ${{ github.event.pull_request.base.sha }} + DEVSCOPE_HEAD: ${{ github.event.pull_request.head.sha }} + run: python "${{ github.action_path }}/scripts/compare.py" + - name: Post PR comment if: github.event_name == 'pull_request' uses: actions/github-script@v7 with: github-token: ${{ inputs.github-token }} script: | - const grade = process.env.DEVSCOPE_GRADE; - const risk = process.env.DEVSCOPE_RISK; - const onboarding = process.env.DEVSCOPE_ONBOARDING; - const scanTime = process.env.DEVSCOPE_SCAN_TIME; - const compact = process.env.DEVSCOPE_COMPACT; - const marker = ''; - const body = `${marker}\n## Devscope Report\n\n**Grade:** ${grade} \n**Risk:** ${risk} \n**Onboarding:** ${onboarding} \n**Scan time:** ${scanTime}s\n\n${compact}`; - try { - const comments = await github.paginate(github.rest.issues.listComments, { - ...context.repo, issue_number: context.issue.number, - }); - const previous = comments.find(comment => - comment.user?.type === 'Bot' && comment.body?.includes(marker) - ); - if (previous) { - await github.rest.issues.updateComment({ - ...context.repo, comment_id: previous.id, body, - }); - } else { - await github.rest.issues.createComment({ - ...context.repo, issue_number: context.issue.number, body, - }); - } - } catch (error) { - if (error.status !== 403) throw error; - core.warning('PR comment skipped: the token has no write permission.'); - } + const postComment = require(process.env.DEVSCOPE_ACTION_PATH + '/scripts/comment.cjs'); + await postComment({ github, context, core }); env: + DEVSCOPE_ACTION_PATH: ${{ github.action_path }} + DEVSCOPE_COMPARISON_REPORT: ${{ steps.compare.outputs.report-path }} DEVSCOPE_GRADE: ${{ steps.analyze.outputs.grade }} DEVSCOPE_RISK: ${{ steps.analyze.outputs.risk }} DEVSCOPE_ONBOARDING: ${{ steps.analyze.outputs.onboarding }} diff --git a/scripts/comment.cjs b/scripts/comment.cjs new file mode 100644 index 0000000..ebe18d7 --- /dev/null +++ b/scripts/comment.cjs @@ -0,0 +1,28 @@ +const fs = require('node:fs'); + +module.exports = async function postComment({ github, context, core }) { + const env = process.env; + const marker = ''; + let comparison = env.DEVSCOPE_COMPARISON_REPORT + ? fs.readFileSync(env.DEVSCOPE_COMPARISON_REPORT, 'utf8') : ''; + if (comparison.length > 50000) { + comparison = comparison.slice(0, 50000) + '\n\n_Comparison truncated; see the full job summary._'; + } + const body = `${marker}\n## Devscope Report\n\n**Heuristic grade:** ${env.DEVSCOPE_GRADE} \n**Risk:** ${env.DEVSCOPE_RISK} \n**Onboarding:** ${env.DEVSCOPE_ONBOARDING} \n**Scan time:** ${env.DEVSCOPE_SCAN_TIME}s\n\n${env.DEVSCOPE_COMPACT}${comparison ? '\n\n' + comparison : ''}`; + try { + const comments = await github.paginate(github.rest.issues.listComments, { + ...context.repo, issue_number: context.issue.number, + }); + const previous = comments.find(comment => + comment.user?.type === 'Bot' && comment.body?.includes(marker) + ); + if (previous) { + await github.rest.issues.updateComment({ ...context.repo, comment_id: previous.id, body }); + } else { + await github.rest.issues.createComment({ ...context.repo, issue_number: context.issue.number, body }); + } + } catch (error) { + if (error.status !== 403) throw error; + core.warning('PR comment skipped: the token has no write permission.'); + } +}; diff --git a/scripts/compare.py b/scripts/compare.py new file mode 100644 index 0000000..a2974d9 --- /dev/null +++ b/scripts/compare.py @@ -0,0 +1,69 @@ +"""Write one committed PR comparison to the job summary and expose its report path.""" + +import os +from pathlib import Path +import re +import subprocess +import sys +import tempfile + + +def main(): + base = os.environ.get("DEVSCOPE_BASE", "") + head = os.environ.get("DEVSCOPE_HEAD", "") + if not all(re.fullmatch(r"[0-9a-fA-F]{40}", ref) for ref in (base, head)): + raise ValueError( + "Comparison requires the pull request's full base and head commit SHAs" + ) + path = Path(os.environ.get("DEVSCOPE_PATH", ".")).resolve() + prefix = subprocess.run( + ["git", "-C", str(path), "rev-parse", "--show-prefix"], + check=True, + capture_output=True, + text=True, + ).stdout.strip() + if prefix: + raise ValueError( + "Comparison path must be a Git repository root; subdirectory comparisons are not supported" + ) + # Capture before writing anything so unavailable refs cannot publish a partial report. + report = subprocess.run( + [ + "devscope", + "compare", + str(path), + "--base", + base, + "--head", + head, + "--format", + "markdown", + ], + check=True, + capture_output=True, + text=True, + encoding="utf-8", + env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}, + ).stdout + directory = Path( + tempfile.mkdtemp( + prefix="devscope-comparison-", dir=os.environ.get("RUNNER_TEMP") + ) + ) + report_path = directory / "comparison.md" + report_path.write_text(report, encoding="utf-8") + with open(os.environ["GITHUB_STEP_SUMMARY"], "a", encoding="utf-8") as summary: + summary.write(report + "\n") + with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as outputs: + outputs.write(f"report-path={report_path}\n") + + +if __name__ == "__main__": + try: + main() + except (ValueError, OSError, subprocess.CalledProcessError): + print( + "PR comparison failed. Use a compare-capable Devscope commit, use a repository-root path, checkout the PR head with fetch-depth: 0, and ensure both refs are available.", + file=sys.stderr, + ) + raise SystemExit(1) diff --git a/tests/comment.test.cjs b/tests/comment.test.cjs new file mode 100644 index 0000000..73e3a2f --- /dev/null +++ b/tests/comment.test.cjs @@ -0,0 +1,81 @@ +const { test, beforeEach, afterEach } = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const postComment = require('../scripts/comment.cjs'); +let directory; +const keys = ['DEVSCOPE_GRADE', 'DEVSCOPE_COMPACT', 'DEVSCOPE_COMPARISON_REPORT']; +let saved; +beforeEach(() => { + saved = Object.fromEntries(keys.map(key => [key, process.env[key]])); + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'devscope-comment-')); + process.env.DEVSCOPE_GRADE = 'B'; + process.env.DEVSCOPE_COMPACT = 'Devscope: B'; + delete process.env.DEVSCOPE_COMPARISON_REPORT; +}); +afterEach(() => { + fs.rmSync(directory, { recursive: true, force: true }); + for (const key of keys) { + if (saved[key] === undefined) delete process.env[key]; + else process.env[key] = saved[key]; + } +}); +function client(comments = []) { + const calls = { created: [], updated: [], warnings: [] }; + const github = { + paginate: async () => comments, + rest: { issues: { + listComments: () => {}, + createComment: async data => calls.created.push(data), + updateComment: async data => calls.updated.push(data), + } }, + }; + return { github, context: { repo: { owner: 'owner', repo: 'repo' }, issue: { number: 7 } }, + core: { warning: message => calls.warnings.push(message) }, calls }; +} +function report(text) { + process.env.DEVSCOPE_COMPARISON_REPORT = path.join(directory, 'comparison.md'); + fs.writeFileSync(process.env.DEVSCOPE_COMPARISON_REPORT, text); +} +test('creates report with literal comparison content', async () => { + const text = '## Devscope PR comparison\n| Lines | 1 | 3 | +2 |\n`file${notExecuted}.py`'; + report(text); + const api = client(); + await postComment(api); + assert.ok(api.calls.created[0].body.includes(text)); + assert.equal(api.calls.created[0].issue_number, 7); +}); +test('updates the existing bot report and ignores matching human comments', async () => { + const api = client([ + { id: 1, user: { type: 'User' }, body: '' }, + { id: 2, user: { type: 'Bot' }, body: '' }, + ]); + await postComment(api); + assert.equal(api.calls.updated[0].comment_id, 2); + assert.equal(api.calls.created.length, 0); +}); +test('without comparison preserves normal report', async () => { + const api = client(); + await postComment(api); + assert.ok(api.calls.created[0].body.includes('**Heuristic grade:** B')); + assert.ok(!api.calls.created[0].body.includes('PR comparison')); +}); +test('read-only tokens skip comments without failing analysis', async () => { + const api = client(); + api.github.paginate = async () => { throw { status: 403 }; }; + await postComment(api); + assert.equal(api.calls.warnings.length, 1); +}); +test('other API failures remain visible', async () => { + const api = client(); + api.github.paginate = async () => { throw { status: 500 }; }; + await assert.rejects(postComment(api)); +}); +test('large comparisons fit comment limits and point to the full summary', async () => { + report('x'.repeat(100000)); + const api = client(); + await postComment(api); + assert.ok(api.calls.created[0].body.length < 60000); + assert.ok(api.calls.created[0].body.includes('full job summary')); +}); diff --git a/tests/test_comparison.py b/tests/test_comparison.py new file mode 100644 index 0000000..2e0be1c --- /dev/null +++ b/tests/test_comparison.py @@ -0,0 +1,106 @@ +"""Checks for comparison invocation and report transport; no CLI installation needed.""" + +import importlib.util +import os +from pathlib import Path +import subprocess +import tempfile +import unittest +from unittest.mock import patch + +spec = importlib.util.spec_from_file_location( + "compare", Path(__file__).parents[1] / "scripts/compare.py" +) +compare = importlib.util.module_from_spec(spec) +spec.loader.exec_module(compare) + + +class ComparisonTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.root = Path(self.directory.name) + self.env = patch.dict( + os.environ, + { + "DEVSCOPE_PATH": str(self.root), + "DEVSCOPE_BASE": "a" * 40, + "DEVSCOPE_HEAD": "b" * 40, + "RUNNER_TEMP": str(self.root), + "GITHUB_STEP_SUMMARY": str(self.root / "summary"), + "GITHUB_OUTPUT": str(self.root / "outputs"), + }, + ) + self.env.start() + self.addCleanup(self.env.stop) + self.addCleanup(self.directory.cleanup) + + def test_explicit_refs_and_report_output(self): + report = "## Devscope PR comparison\n\n| Lines | 1 | 3 | +2 |\n" + with patch.object( + compare.subprocess, + "run", + side_effect=[ + subprocess.CompletedProcess([], 0, stdout=""), + subprocess.CompletedProcess([], 0, stdout=report), + ], + ) as run: + compare.main() + args = run.call_args_list[1].args[0] + self.assertEqual( + args, + [ + "devscope", + "compare", + str(self.root.resolve()), + "--base", + "a" * 40, + "--head", + "b" * 40, + "--format", + "markdown", + ], + ) + report_path = ( + (self.root / "outputs").read_text(encoding="utf-8").strip().split("=", 1)[1] + ) + self.assertEqual(Path(report_path).read_text(encoding="utf-8"), report) + self.assertEqual( + (self.root / "summary").read_text(encoding="utf-8"), report + "\n" + ) + + def test_missing_history_does_not_publish_partial_report(self): + with ( + patch.object( + compare.subprocess, + "run", + side_effect=[ + subprocess.CompletedProcess([], 0, stdout=""), + subprocess.CalledProcessError(1, "devscope", stderr="missing refs"), + ], + ), + self.assertRaises(subprocess.CalledProcessError), + ): + compare.main() + self.assertFalse((self.root / "outputs").exists()) + self.assertFalse((self.root / "summary").exists()) + + def test_subdirectory_is_rejected(self): + with ( + patch.object( + compare.subprocess, + "run", + return_value=subprocess.CompletedProcess([], 0, stdout="src/"), + ) as run, + self.assertRaisesRegex(ValueError, "repository root"), + ): + compare.main() + self.assertEqual(run.call_count, 1) + + def test_invalid_event_refs_are_rejected(self): + with ( + patch.dict(os.environ, {"DEVSCOPE_BASE": "--help"}), + patch.object(compare.subprocess, "run") as run, + self.assertRaises(ValueError), + ): + compare.main() + run.assert_not_called() From 48fb93a2fb0721af572c5e9041bf3ace7e7e8890 Mon Sep 17 00:00:00 2001 From: EhsanAzish80 Date: Fri, 4 Dec 2026 14:11:17 +0300 Subject: [PATCH 2/2] Document pinned PR comparison onboarding --- README.md | 60 ++++++++++++++++++++++++++++++++++++-- examples/pr-comparison.yml | 20 +++++++++++++ 2 files changed, 77 insertions(+), 3 deletions(-) create mode 100644 examples/pr-comparison.yml diff --git a/README.md b/README.md index cf3fb2f..e478baf 100644 --- a/README.md +++ b/README.md @@ -17,13 +17,13 @@ jobs: - uses: actions/checkout@v4 with: fetch-depth: 0 - - uses: EhsanAzish80/devscope-action@v1 + - uses: EhsanAzish80/devscope-action@ee711970e3a18ea07430ca9027f862af4311239c id: devscope with: fail-under: B ``` -The Action installs the published PyPI package. Results are available as `health`, `risk`, `onboarding`, and `grade` outputs. It posts one updated PR comment when the workflow token has write permission. PRs from forks often receive a read-only token; in that case the comment is skipped and the analysis and threshold check still run. +The quick start pins the merged gate fixes; the floating `@v1` tag has not yet been updated. By default, the Action installs the published PyPI package. Results are available as `health`, `risk`, `onboarding`, and `grade` outputs. It posts one updated PR comment when the workflow token has write permission. PRs from forks often receive a read-only token; in that case the comment is skipped and the analysis and threshold check still run. ## Inputs @@ -35,19 +35,73 @@ The Action installs the published PyPI package. Results are available as `health | `max-onboarding` | unset | Highest accepted onboarding label: Easy, Moderate, Hard | | `github-token` | `github.token` | Token for PR comments | | `devscope-version` | `0.1.1` | Published PyPI version to install | +| `devscope-ref` | unset | Full upstream CLI commit SHA to install instead of the PyPI version | +| `compare` | `false` | Add an advisory comparison on `pull_request` events | When a threshold is set, it applies to **both pull requests and pushes**. Analysis errors fail the job instead of producing a default grade. The grade is based on file layout, test-file ratio, Git activity, and hotspots. The test-file ratio is not code coverage. Read [the CLI guide](https://github.com/EhsanAzish80/Devscope#what-the-report-tells-you) before using a grade as a gate. For a fork PR, do not switch to `pull_request_target` and execute untrusted code with a write token. If comments are essential, use a separate privileged workflow that reads an artifact from the unprivileged analysis job. +## PR comparison + +Save this as `.github/workflows/devscope.yml`, or copy the complete +[example workflow](examples/pr-comparison.yml). The Action integration commit is +pinned so the workflow can run before a new Action tag or CLI package is released. + +```yaml +name: Devscope PR comparison +on: pull_request +permissions: + contents: read + pull-requests: write +jobs: + devscope: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} + # Pinned integration commit; @v1 does not include comparison yet. + - uses: EhsanAzish80/devscope-action@b2058cd71ef51077b36cf1b9e84958f6d4b0a45a + id: devscope + with: + compare: 'true' + # Merged CLI commit containing compare; not an unreleased PyPI version. + devscope-ref: d9849fddd644f98a67985115af74c74ff0a5230e +``` + +The report includes count deltas and added, removed or changed review areas from +`merge-base(base.sha, head.sha)` to the PR head. It appears in both the job summary +and the existing bot comment. Positive deltas mean larger counts, not improvements; +removed review areas do not prove that a defect was fixed. The comparison is +advisory; the existing grade/risk/onboarding thresholds remain absolute gates. + +`compare` defaults to `false` and is skipped outside pull requests. When enabled: + +- Use a compare-capable CLI. The pinned `devscope-ref` above is a verified merged + commit; the default PyPI version `0.1.1` does not have `compare`. +- Check out the exact PR head with full history. Both event SHAs must be available. + Shallow or missing history fails the comparison with a setup message. +- Set `path` to the Git repository root. Subdirectory comparisons are not supported. +- Read-only fork tokens skip the comment but retain the job summary. For summary + only on all PRs, use the [CLI-only workflow](https://github.com/EhsanAzish80/Devscope/blob/main/examples/pr-comparison.yml). + +The `comparison-report` output is the local Markdown report path, available to +later steps in the same job. It is empty when comparison is disabled or skipped. +Long comments are truncated with a pointer to the full job summary. Git activity, +symlinks, submodules and Git archive export-ignored files are excluded. + ## Development Run the shell integration checks locally: ```bash bash tests/test-action.sh +python3 -m unittest discover -s tests -p 'test_*.py' +node --test tests/comment.test.cjs ``` -The published `@v1` tag must be updated after this change merges. Until then, workflows using `@v1` keep the prior Action behavior. Once Devscope 0.2.0 is published, set `devscope-version: '0.2.0'` to receive the new report fields; the default stays on the previously published package for reproducible CI. +The published `@v1` tag is unchanged. Use the pinned commits above to try the relevant behavior. Once a CLI package containing `compare` is released, you can use its `devscope-version` and omit `devscope-ref`; until then, the default remains the published `0.1.1` package. CI exercises the comparison against the pinned CLI on Ubuntu, macOS and Windows. MIT licensed. See [LICENSE](LICENSE). diff --git a/examples/pr-comparison.yml b/examples/pr-comparison.yml new file mode 100644 index 0000000..3d39f59 --- /dev/null +++ b/examples/pr-comparison.yml @@ -0,0 +1,20 @@ +name: Devscope PR comparison +on: pull_request +permissions: + contents: read + pull-requests: write +jobs: + devscope: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + ref: ${{ github.event.pull_request.head.sha }} + # Pinned integration commit; @v1 does not include comparison yet. + - uses: EhsanAzish80/devscope-action@b2058cd71ef51077b36cf1b9e84958f6d4b0a45a + id: devscope + with: + compare: 'true' + # Merged CLI commit containing compare; not an unreleased PyPI version. + devscope-ref: d9849fddd644f98a67985115af74c74ff0a5230e