Skip to content
Merged
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
39 changes: 33 additions & 6 deletions .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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"
60 changes: 57 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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).
63 changes: 35 additions & 28 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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 }}
Expand All @@ -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
Expand All @@ -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 = '<!-- devscope-action-comment -->';
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 }}
Expand Down
20 changes: 20 additions & 0 deletions examples/pr-comparison.yml
Original file line number Diff line number Diff line change
@@ -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
28 changes: 28 additions & 0 deletions scripts/comment.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
const fs = require('node:fs');

module.exports = async function postComment({ github, context, core }) {
const env = process.env;
const marker = '<!-- devscope-action-comment -->';
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.');
}
};
69 changes: 69 additions & 0 deletions scripts/compare.py
Original file line number Diff line number Diff line change
@@ -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)
Loading
Loading