GitHub action: report on code dupe #11
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Check for Duplicated Code | |
on: | |
pull_request: | |
branches: | |
- master | |
jobs: | |
check-duplication: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout code | |
uses: actions/checkout@v3 | |
with: | |
fetch-depth: 0 # Fetch all history for all branches | |
- name: Set up Node.js | |
uses: actions/setup-node@v3 | |
with: | |
node-version: '20' | |
- name: Install dependencies | |
run: | | |
npm install -g jscpd diff-so-fancy | |
- name: Run jscpd on entire codebase | |
run: | | |
jscpd --threshold 1 --min-tokens 50 --reporters json --output jscpd-report.json | |
- name: Get the diff | |
run: git diff origin/master...HEAD --name-only > changed_files.txt | |
- name: Filter JavaScript files | |
run: | | |
grep -E '\.js$' changed_files.txt > js_files.txt || true | |
- name: List generated files (debug) | |
run: ls -l | |
- name: Parse jscpd report and set output | |
id: parse-report | |
run: | | |
if [ ! -f jscpd-report.json ]; then | |
echo "jscpd-report.json not found" | |
exit 1 | |
fi | |
DUPLICATIONS=$(jq '.duplicates | length' jscpd-report.json) | |
if [ "$DUPLICATIONS" -gt 0 ]; then | |
COMMENT="Found $DUPLICATIONS duplications in the codebase:\n\n" | |
while read -r file; do | |
COMMENT+=$(jq -r --arg file "$file" '.duplicates[] | select(.firstFile == $file or .secondFile == $file) | "- `\(.firstFile):\(.lines[0])-\(.lines[1])` duplicated in `\(.secondFile):\(.lines[0])-\(.lines[1])`"' jscpd-report.json) | |
done < js_files.txt | |
if [ -z "$COMMENT" ]; then | |
echo "No duplications found in changed files." | |
exit 0 | |
fi | |
echo "comment<<EOF" >> $GITHUB_ENV | |
echo "$COMMENT" >> $GITHUB_ENV | |
echo "EOF" >> $GITHUB_ENV | |
exit 1 | |
else | |
echo "No duplications found." | |
fi | |
- name: Post GitHub comment | |
if: failure() | |
uses: actions/github-script@v6 | |
with: | |
script: | | |
github.rest.issues.createComment({ | |
owner: context.repo.owner, | |
repo: context.repo.repo, | |
issue_number: context.issue.number, | |
body: process.env.comment | |
}) |