diff --git a/.github/workflows/e2e-test.yml b/.github/workflows/e2e-test.yml index 90d3488..e822e56 100644 --- a/.github/workflows/e2e-test.yml +++ b/.github/workflows/e2e-test.yml @@ -9,6 +9,8 @@ on: branches: [main] paths: - 'action.yml' + - 'scripts/**' + - 'tests/**' - '.github/workflows/e2e-test.yml' permissions: @@ -49,8 +51,8 @@ jobs: echo "" # Validate outputs are not empty - if [ -z "${{ steps.test-basic.outputs.grade }}" ]; then - echo "::error::Grade output is empty" + if [[ ! "${{ steps.test-basic.outputs.grade }}" =~ ^[A-F]$ ]]; then + echo "::error::Grade output is invalid" exit 1 fi @@ -135,7 +137,7 @@ jobs: git add . git commit -m "Initial commit with poor code" - - name: Run with strict thresholds (should NOT fail - no push event) + - name: Run with strict thresholds (may fail) uses: ./ id: test-strict with: @@ -151,15 +153,16 @@ jobs: echo "Grade: ${{ steps.test-strict.outputs.grade }}" echo "" - # On pull_request, thresholds should NOT cause failure - # (thresholds only enforced on push events) - echo "โœ… Threshold behavior validated (metrics reported, no CI failure)" + if [ "${{ steps.test-strict.outcome }}" != "failure" ]; then + echo "::error::Strict threshold unexpectedly passed" + exit 1 + fi echo "### ๐Ÿ›ก๏ธ Threshold Test Results" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY echo "**Grade:** ${{ steps.test-strict.outputs.grade }}" >> $GITHUB_STEP_SUMMARY echo "" >> $GITHUB_STEP_SUMMARY - echo "โœ… Thresholds validated (show metrics without failing on non-push)" >> $GITHUB_STEP_SUMMARY + echo "Threshold outcome: ${{ steps.test-strict.outcome }}" >> $GITHUB_STEP_SUMMARY test-pr-comment: name: Test PR Comment Creation diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 60aed52..2c9ebea 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -1,8 +1,7 @@ name: Test Action -# This workflow is workflow_dispatch-only to avoid running on every change in this repository. -# Enable push/PR triggers in forks if you want continuous validation. on: + pull_request: workflow_dispatch: jobs: @@ -20,6 +19,10 @@ jobs: steps: - name: Checkout action code uses: actions/checkout@v4 + + - name: Check analysis and threshold scripts + shell: bash + run: bash tests/test-action.sh - name: Create test repository shell: bash @@ -59,8 +62,8 @@ jobs: echo "Onboarding: ${{ steps.test-basic.outputs.onboarding }}" echo "Health: ${{ steps.test-basic.outputs.health }}" - if [ -z "${{ steps.test-basic.outputs.grade }}" ]; then - echo "::error::Grade output is empty" + if [[ ! "${{ steps.test-basic.outputs.grade }}" =~ ^[A-F]$ ]]; then + echo "::error::Grade output is invalid" exit 1 fi @@ -73,7 +76,6 @@ jobs: fail-under: F max-risk: High max-onboarding: Hard - continue-on-error: true - name: Report test results if: always() diff --git a/README.md b/README.md index 8a3f5ec..cf3fb2f 100644 --- a/README.md +++ b/README.md @@ -1,475 +1,53 @@ -# Devscope GitHub Action +# Devscope Action -**Zero-config code health checks for your pull requests** ๐Ÿš€ +Run [Devscope](https://github.com/EhsanAzish80/Devscope) in GitHub Actions. It reports a heuristic repository grade, risk and onboarding labels, and can fail a job when a configured threshold is missed. -Automatically analyze your repository and post maintainability metrics on every PR. No configuration needed โ€” just drop it in your workflow. - -[![GitHub release](https://img.shields.io/github/v/release/EhsanAzish80/devscope-action)](https://github.com/EhsanAzish80/devscope-action/releases) -[![Test Action](https://github.com/EhsanAzish80/devscope-action/workflows/test/badge.svg)](https://github.com/EhsanAzish80/devscope-action/actions) - ---- - -## ๏ฟฝ Why Devscope in CI? - -**Shift-left code quality** โ€” catch maintainability issues before they reach production. - -- โœ… **Instant feedback** โ€” developers see health metrics within seconds on PRs -- โœ… **Preventative maintenance** โ€” block merges when quality drops below thresholds -- โœ… **No configuration required** โ€” works out of the box with sensible defaults -- โœ… **Language agnostic** โ€” analyzes Python, JavaScript, TypeScript, Go, Rust, Java, and more -- โœ… **Fast & cached** โ€” pipx dependencies cached between runs (~5-8s after first run) -- โœ… **Non-intrusive** โ€” sticky PR comments (updates in place, no spam) - -**Use cases:** -- Enforce maintainability standards across teams -- Monitor tech debt trends in CI -- Gate releases on code health thresholds -- Onboard new contributors with clear quality metrics - ---- - -## ๏ฟฝ๐ŸŽฏ Features - -- โœ… **Automatic PR comments** with health metrics -- โœ… **Sticky updates** โ€” no comment spam -- โœ… **CI quality gates** with configurable thresholds -- โœ… **Fast caching** โ€” pipx packages cached between runs -- โœ… **Rich outputs** โ€” use metrics in other workflow steps -- โœ… **Zero config** โ€” works out of the box - ---- - -## ๐Ÿš€ Quick Start - -### Basic PR Health Check - -Add this to `.github/workflows/devscope.yml`: +## Quick start ```yaml -name: Code Health - -on: - pull_request: - push: - branches: [main] - +name: Codebase review +on: [pull_request, push] +permissions: + contents: read + pull-requests: write jobs: - health-check: + devscope: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: - fetch-depth: 0 # Full history for git metrics - + fetch-depth: 0 - uses: EhsanAzish80/devscope-action@v1 -``` - -**That's it!** ๐ŸŽ‰ - -**Example PR Comment:** - -```` -๐Ÿ“Š Devscope Report - -Maintainability: ๐ŸŸข B -Risk: ๐ŸŸข Low -Onboarding: Easy -โšก 0.82s - -
-Full summary โ–ผ - -โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -Devscope: B ยท Low risk ยท Easy onboarding ยท 0.78 tests ยท 0.82s โšก - -Files: 1,247 -Lines: 45,892 -Languages: Python (45%) ยท TypeScript (33%) ยท JavaScript (12%) - -**Metrics:** -- Maintainability Grade: B (82.5/100) -- Risk Level: Low -- Onboarding Difficulty: Easy -- Test Coverage: 78% - -Analyze your repo โ†’ `pipx install devscope` -Updated: Thu, 13 Feb 2026 15:30:00 GMT -
-```` - -**Features:** -- โœ… Emoji indicators ๐ŸŸข green (good), ๐Ÿ”ด red (critical) -- โœ… Sticky updates (edits same comment, no spam) -- โœ… Collapsible full summary -- โœ… Performance timing - ---- - -## ๐Ÿ“– Usage Examples - -### With CI Quality Gate - -Fail the workflow if maintainability drops below B: - -```yaml -- uses: EhsanAzish80/devscope-action@v1 - with: - fail-under: B - max-risk: Medium - max-onboarding: Moderate -``` - -**Exit codes:** -- `0` = All thresholds passed -- `1` = Runtime error -- `2` = Threshold violated (fails CI) - -### Analyze Specific Directory - -```yaml -- uses: EhsanAzish80/devscope-action@v1 - with: - path: ./src -``` - -### Use Outputs in Other Steps - -```yaml -- uses: EhsanAzish80/devscope-action@v1 - id: devscope - -- name: Check grade - run: | - echo "Grade: ${{ steps.devscope.outputs.grade }}" - echo "Risk: ${{ steps.devscope.outputs.risk }}" - - if [ "${{ steps.devscope.outputs.grade }}" == "F" ]; then - echo "::warning::Code health is critical!" - fi -``` - -### Custom GitHub Token - -For private repos or fine-grained permissions: - -```yaml -- uses: EhsanAzish80/devscope-action@v1 - with: - github-token: ${{ secrets.CUSTOM_PAT }} -``` - ---- - -## ๐Ÿ”ง Configuration - -### Inputs - -| Input | Description | Default | Required | -|-------|-------------|---------|----------| -| `path` | Directory to analyze | `.` | No | -| `fail-under` | Minimum grade (A, B, C, D, F) | (none) | No | -| `max-risk` | Maximum risk level (Low, Medium, High) | (none) | No | -| `max-onboarding` | Max onboarding difficulty (Easy, Moderate, Hard) | (none) | No | -| `github-token` | GitHub token for PR comments | `${{ github.token }}` | No | - -### Outputs - -| Output | Description | Example | -|--------|-------------|---------| -| `health` | Overall health score (0-100) | `82.5` | -| `risk` | Risk level | `Low` | -| `onboarding` | Onboarding difficulty | `Easy` | -| `grade` | Maintainability grade | `B` | - ---- - -## ๐ŸŽจ PR Comment Format - -The action posts a beautifully formatted comment on PRs: - -**Collapsed view:** -``` -๐Ÿ“Š Devscope Report - -Maintainability: ๐ŸŸข B -Risk: ๐ŸŸข Low -Onboarding: Easy -โšก 0.82s -``` - -**Expanded view:** -``` -๐Ÿ“Š Devscope Report - -Maintainability: ๐ŸŸข B -Risk: ๐ŸŸข Low -Onboarding: Easy -โšก 0.82s - -Full summary โ–ผ -โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -Devscope: B ยท Low risk ยท Easy onboarding ยท 0.78 tests ยท 0.82s โšก - -Files: 1,247 -Lines: 45,892 -Languages: Python (45%) ยท TypeScript (33%) ยท JavaScript (12%) - -Analyze your repo โ†’ pipx install devscope -Updated: Thu, 13 Feb 2026 15:30:00 GMT -``` - -**Features:** -- โœ… Emoji indicators (๐ŸŸข green = good, ๐Ÿ”ด red = bad) -- โœ… Sticky updates (same comment, no spam) -- โœ… Collapsible full summary -- โœ… Timestamp tracking - ---- - -## ๐Ÿ“Š Example Workflows - -### Full CI/CD Pipeline - -```yaml -name: Code Quality - -on: - pull_request: - push: - branches: [main, develop] - -jobs: - health-check: - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - - steps: - - name: Checkout code - uses: actions/checkout@v4 - with: - fetch-depth: 0 # Required for git metrics - - - name: Run Devscope - uses: EhsanAzish80/devscope-action@v1 id: devscope with: fail-under: B - max-risk: Medium - - - name: Upload metrics - if: always() - run: | - echo "Health: ${{ steps.devscope.outputs.health }}" - echo "Grade: ${{ steps.devscope.outputs.grade }}" - echo "Risk: ${{ steps.devscope.outputs.risk }}" -``` - -### Monorepo (Multiple Directories) - -```yaml -jobs: - health-check: - strategy: - matrix: - service: [frontend, backend, shared] - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v4 - with: - fetch-depth: 0 - - - uses: EhsanAzish80/devscope-action@v1 - with: - path: ./services/${{ matrix.service }} - fail-under: C ``` -### Different Thresholds by Branch +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. -```yaml -- uses: EhsanAzish80/devscope-action@v1 - with: - fail-under: ${{ github.ref == 'refs/heads/main' && 'A' || 'B' }} - max-risk: ${{ github.ref == 'refs/heads/main' && 'Low' || 'Medium' }} -``` - ---- - -## โšก Performance - -This action uses **aggressive caching** for fast runs: - -| Phase | First Run | Cached Runs | -|-------|-----------|-------------| -| Setup Python | ~5s | ~2s (cached) | -| Install devscope | ~10-15s | ~3-5s (pipx cache) | -| Analysis | ~0.5-2s | ~0.5-2s | -| **Total** | **~15-20s** | **~5-8s** โšก | +## Inputs -**Optimization tips:** -- Use `fetch-depth: 0` for accurate git metrics -- Enable pipx caching (automatic in this action) -- Run on push + PR for best cache hits +| Input | Default | Meaning | +| --- | --- | --- | +| `path` | `.` | Directory to analyze | +| `fail-under` | unset | Lowest accepted grade, A through F | +| `max-risk` | unset | Highest accepted risk label: Low, Medium, High | +| `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 | -Most runs complete in **under 10 seconds** after initial setup โšก +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. -## ๐Ÿ”’ Permissions +## Development -### Required Permissions +Run the shell integration checks locally: -```yaml -permissions: - contents: read # Read repository code - pull-requests: write # Post PR comments -``` - -**Minimal setup:** -```yaml -jobs: - health-check: - runs-on: ubuntu-latest - permissions: - contents: read - pull-requests: write - steps: - - uses: actions/checkout@v4 - - uses: EhsanAzish80/devscope-action@v1 -``` - -### For Forks - -If you want to support PRs from forks: - -```yaml -on: - pull_request_target: # Use with caution! - -permissions: - contents: read - pull-requests: write -``` - -โš ๏ธ **Security note:** `pull_request_target` runs with write access. Only use if you trust fork contributors or implement additional checks. - ---- - -## ๐Ÿ› Troubleshooting - -### Comment not appearing on PR - -**Check permissions:** -```yaml -permissions: - pull-requests: write -``` - -**Verify trigger:** -```yaml -on: - pull_request: # Must include this -``` - -### Action fails with "command not found: devscope" - -The action installs devscope automatically. If it fails: - -1. Check Python version (requires 3.9+) -2. Clear cache: Go to Actions โ†’ Caches โ†’ Delete all caches -3. Re-run workflow - -### Thresholds not enforced - -Thresholds only apply on **push events**, not PRs. PRs show metrics but don't fail. - -To enforce on PRs: -```yaml -on: - pull_request: - push: - branches: [main] -``` - -### Slow analysis - -Enable caching: -```yaml -- uses: actions/checkout@v4 - with: - fetch-depth: 0 # Faster git operations -``` - ---- - -## ๐Ÿ”„ Versioning - -This action follows semantic versioning: - -- `@v1` โ€” Latest v1.x.x (recommended, auto-updates) -- `@v1.0.0` โ€” Exact version (pinned, no updates) -- `@main` โ€” Latest commit (unstable, for testing) - -**Recommended:** -```yaml -- uses: EhsanAzish80/devscope-action@v1 -``` - ---- - -## ๐Ÿ“ฆ What's Included - -This action: -- Installs [devscope](https://github.com/EhsanAzish80/Devscope) via pipx -- Caches Python dependencies for speed -- Analyzes your codebase (Python, JS, TS, Go, Rust, Java, etc.) -- Posts formatted PR comments -- Enforces quality gates on push events -- Provides structured outputs for custom workflows - ---- - -## ๐Ÿค Contributing - -Contributions welcome! Please: - -1. Fork the repo -2. Create a feature branch -3. Test locally with [act](https://github.com/nektos/act) -4. Submit a PR - -**Local testing:** ```bash -# Install act -brew install act - -# Test workflow -act pull_request -j health-check +bash tests/test-action.sh ``` ---- - -## ๐Ÿ“„ License - -MIT License - see [LICENSE](LICENSE) file. - ---- - -## ๐Ÿ™ Acknowledgments - -Built with: -- [devscope](https://github.com/EhsanAzish80/Devscope) โ€” The analysis engine -- [actions/github-script](https://github.com/actions/github-script) โ€” PR comment management -- [actions/setup-python](https://github.com/actions/setup-python) โ€” Python setup with caching - ---- - -## ๐Ÿ“ž Support - -- ๐Ÿ› [Report a bug](https://github.com/EhsanAzish80/devscope-action/issues) -- ๐Ÿ’ก [Request a feature](https://github.com/EhsanAzish80/devscope-action/issues) -- ๐Ÿ’ฌ [Discussions](https://github.com/EhsanAzish80/devscope-action/discussions) +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. ---- +MIT licensed. See [LICENSE](LICENSE). diff --git a/action.yml b/action.yml index fee1bec..ac5f53c 100644 --- a/action.yml +++ b/action.yml @@ -12,7 +12,7 @@ inputs: required: false default: '.' fail-under: - description: 'Minimum grade required (A, B, C, D, F)' + description: 'Minimum grade required (A, B, C, D, E, F)' required: false default: '' max-risk: @@ -27,6 +27,10 @@ inputs: description: 'GitHub token for posting PR comments' required: false default: ${{ github.token }} + devscope-version: + description: 'PyPI version of devscope to install' + required: false + default: '0.1.1' outputs: health: @@ -49,65 +53,20 @@ runs: uses: actions/setup-python@v5 with: python-version: '3.12' - cache: 'pip' - - - name: Install pipx - shell: bash - run: | - python -m pip install --user pipx - python -m pipx ensurepath - echo "$HOME/.local/bin" >> $GITHUB_PATH - - - name: Cache pipx packages - uses: actions/cache@v4 - with: - path: ~/.local/pipx - key: ${{ runner.os }}-pipx-devscope-${{ hashFiles('**/requirements*.txt', '**/pyproject.toml') }} - restore-keys: | - ${{ runner.os }}-pipx-devscope- - name: Install devscope shell: bash + env: + DEVSCOPE_VERSION: ${{ inputs.devscope-version }} run: | - if ! command -v devscope &> /dev/null; then - pipx install devscope - fi + python -m pip install --disable-pip-version-check "devscope==$DEVSCOPE_VERSION" - name: Run analysis id: analyze shell: bash - run: | - cd "${{ inputs.path }}" - - # Run compact summary for output - COMPACT_OUTPUT=$(devscope summary --compact 2>&1 || echo "Analysis failed") - - # Run JSON for structured data - if devscope summary --json > /tmp/devscope.json 2>&1; then - HEALTH=$(jq -r '.health_score.score_breakdown.overall // "0"' /tmp/devscope.json) - RISK=$(jq -r '.health_score.risk_level // "Unknown"' /tmp/devscope.json) - ONBOARDING=$(jq -r '.health_score.onboarding_difficulty // "Unknown"' /tmp/devscope.json) - GRADE=$(jq -r '.health_score.maintainability_grade // "F"' /tmp/devscope.json) - SCAN_TIME=$(jq -r '.scan_time // "0"' /tmp/devscope.json) - else - HEALTH="0" - RISK="Unknown" - ONBOARDING="Unknown" - GRADE="F" - SCAN_TIME="0" - fi - - # Escape for GitHub Actions - COMPACT_OUTPUT="${COMPACT_OUTPUT//'%'/'%25'}" - COMPACT_OUTPUT="${COMPACT_OUTPUT//$'\n'/'%0A'}" - COMPACT_OUTPUT="${COMPACT_OUTPUT//$'\r'/'%0D'}" - - echo "health=$HEALTH" >> $GITHUB_OUTPUT - echo "risk=$RISK" >> $GITHUB_OUTPUT - echo "onboarding=$ONBOARDING" >> $GITHUB_OUTPUT - echo "grade=$GRADE" >> $GITHUB_OUTPUT - echo "compact=$COMPACT_OUTPUT" >> $GITHUB_OUTPUT - echo "scan_time=$SCAN_TIME" >> $GITHUB_OUTPUT + env: + DEVSCOPE_PATH: ${{ inputs.path }} + run: bash "${{ github.action_path }}/scripts/analyze.sh" - name: Post PR comment if: github.event_name == 'pull_request' @@ -115,89 +74,46 @@ runs: with: github-token: ${{ inputs.github-token }} script: | - const compact = `${{ steps.analyze.outputs.compact }}`; - const grade = `${{ steps.analyze.outputs.grade }}`; - const risk = `${{ steps.analyze.outputs.risk }}`; - const onboarding = `${{ steps.analyze.outputs.onboarding }}`; - const scanTime = `${{ steps.analyze.outputs.scan_time }}`; - - const gradeEmoji = { - 'A': '๐ŸŸข', 'B': '๐ŸŸข', 'C': '๐ŸŸก', 'D': '๐ŸŸ ', 'F': '๐Ÿ”ด' - }[grade] || 'โšช'; - - const riskEmoji = { - 'Low': '๐ŸŸข', 'Medium': '๐ŸŸก', 'High': '๐Ÿ”ด' - }[risk] || 'โšช'; - + 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 commentBody = `${marker} - ## ๐Ÿ“Š Devscope Report - - **Maintainability:** ${gradeEmoji} **${grade}** - **Risk:** ${riskEmoji} **${risk}** - **Onboarding:** **${onboarding}** - โšก **${scanTime}s** - -
- Full summary - - \`\`\` - ${compact} - \`\`\` -
- - --- - - *Analyze your repo โ†’ \`pipx install devscope\`* - *Updated: ${new Date().toUTCString()}* - `; - - // Find existing comment - const { data: comments } = await github.rest.issues.listComments({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - }); - - const existingComment = comments.find(c => c.body?.includes(marker)); - - if (existingComment) { - await github.rest.issues.updateComment({ - owner: context.repo.owner, - repo: context.repo.repo, - comment_id: existingComment.id, - body: commentBody, + 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, }); - console.log('Updated existing comment'); - } else { - await github.rest.issues.createComment({ - owner: context.repo.owner, - repo: context.repo.repo, - issue_number: context.issue.number, - body: commentBody, - }); - console.log('Created new comment'); + 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.'); } + env: + DEVSCOPE_GRADE: ${{ steps.analyze.outputs.grade }} + DEVSCOPE_RISK: ${{ steps.analyze.outputs.risk }} + DEVSCOPE_ONBOARDING: ${{ steps.analyze.outputs.onboarding }} + DEVSCOPE_SCAN_TIME: ${{ steps.analyze.outputs.scan_time }} + DEVSCOPE_COMPACT: ${{ steps.analyze.outputs.compact }} - name: Check thresholds - if: | - github.event_name == 'push' && - (inputs.fail-under != '' || inputs.max-risk != '' || inputs.max-onboarding != '') + if: inputs.fail-under != '' || inputs.max-risk != '' || inputs.max-onboarding != '' shell: bash - run: | - cd "${{ inputs.path }}" - - ARGS="" - if [ -n "${{ inputs.fail-under }}" ]; then - ARGS="$ARGS --fail-under ${{ inputs.fail-under }}" - fi - if [ -n "${{ inputs.max-risk }}" ]; then - ARGS="$ARGS --max-risk ${{ inputs.max-risk }}" - fi - if [ -n "${{ inputs.max-onboarding }}" ]; then - ARGS="$ARGS --max-onboarding ${{ inputs.max-onboarding }}" - fi - - echo "Running: devscope ci . $ARGS" - devscope ci . $ARGS + env: + DEVSCOPE_PATH: ${{ inputs.path }} + DEVSCOPE_FAIL_UNDER: ${{ inputs.fail-under }} + DEVSCOPE_MAX_RISK: ${{ inputs.max-risk }} + DEVSCOPE_MAX_ONBOARDING: ${{ inputs.max-onboarding }} + run: bash "${{ github.action_path }}/scripts/check-thresholds.sh" diff --git a/scripts/analyze.sh b/scripts/analyze.sh new file mode 100644 index 0000000..b7b0fc4 --- /dev/null +++ b/scripts/analyze.sh @@ -0,0 +1,23 @@ +#!/usr/bin/env bash +set -euo pipefail + +cd "${DEVSCOPE_PATH:-.}" +report=$(mktemp) +trap 'rm -f "$report"' EXIT +devscope summary --json > "$report" + +# summary --json exposes health.grade/score/risk/onboarding, not health_score. +fields=$(jq -er ' + [.health.score, .health.risk, .health.onboarding, .health.grade, .scan_time] + | if any(.[]; . == null) then error("incomplete summary") else map(tostring) | @tsv end +' "$report") +IFS=$'\t' read -r health risk onboarding grade scan_time <<< "$fields" + +{ + printf 'health=%s\n' "$health" + printf 'risk=%s\n' "$risk" + printf 'onboarding=%s\n' "$onboarding" + printf 'grade=%s\n' "$grade" + printf 'scan_time=%s\n' "$scan_time" + printf 'compact=Devscope: %s ยท %s risk ยท %s onboarding\n' "$grade" "$risk" "$onboarding" +} >> "$GITHUB_OUTPUT" diff --git a/scripts/check-thresholds.sh b/scripts/check-thresholds.sh new file mode 100644 index 0000000..7f6a28c --- /dev/null +++ b/scripts/check-thresholds.sh @@ -0,0 +1,9 @@ +#!/usr/bin/env bash +set -euo pipefail + +args=() +[[ -z "${DEVSCOPE_FAIL_UNDER:-}" ]] || args+=(--fail-under "$DEVSCOPE_FAIL_UNDER") +[[ -z "${DEVSCOPE_MAX_RISK:-}" ]] || args+=(--max-risk "$DEVSCOPE_MAX_RISK") +[[ -z "${DEVSCOPE_MAX_ONBOARDING:-}" ]] || args+=(--max-onboarding "$DEVSCOPE_MAX_ONBOARDING") + +devscope ci "${DEVSCOPE_PATH:-.}" --json "${args[@]}" diff --git a/tests/test-action.sh b/tests/test-action.sh new file mode 100644 index 0000000..5269747 --- /dev/null +++ b/tests/test-action.sh @@ -0,0 +1,50 @@ +#!/usr/bin/env bash +set -euo pipefail + +fixture=$(mktemp -d) +trap 'rm -rf "$fixture"' EXIT +mkdir "$fixture/bin" "$fixture/repo" +cat > "$fixture/bin/devscope" <<'SH' +#!/usr/bin/env bash +if [[ "$1" == summary ]]; then + cat "$MOCK_SUMMARY" +elif [[ "$1" == ci ]]; then + printf '%s\n' "$@" > "$MOCK_CI_ARGS" + exit "${MOCK_CI_STATUS:-0}" +else + exit 1 +fi +SH +chmod +x "$fixture/bin/devscope" + +export PATH="$fixture/bin:$PATH" +export DEVSCOPE_PATH="$fixture/repo" +export GITHUB_OUTPUT="$fixture/outputs" +export MOCK_SUMMARY="$fixture/summary.json" +export MOCK_CI_ARGS="$fixture/ci-args" + +cat > "$MOCK_SUMMARY" <<'JSON' +{"health":{"grade":"B","score":83.5,"risk":"Medium","onboarding":"Moderate"},"scan_time":0.2} +JSON +bash scripts/analyze.sh +grep -qx 'health=83.5' "$GITHUB_OUTPUT" +grep -qx 'grade=B' "$GITHUB_OUTPUT" +grep -qx 'risk=Medium' "$GITHUB_OUTPUT" + +echo '{"health":{"grade":"B"}}' > "$MOCK_SUMMARY" +if bash scripts/analyze.sh; then + echo 'Incomplete analysis unexpectedly passed' >&2 + exit 1 +fi + +export DEVSCOPE_FAIL_UNDER=B DEVSCOPE_MAX_RISK=Medium +export MOCK_CI_STATUS=2 +if bash scripts/check-thresholds.sh; then + echo 'A failed threshold unexpectedly passed' >&2 + exit 1 +fi +grep -qx -- '--json' "$MOCK_CI_ARGS" +grep -qx -- '--fail-under' "$MOCK_CI_ARGS" +grep -qx -- '--max-risk' "$MOCK_CI_ARGS" + +echo 'Action scripts passed.'