Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ci: add K&R code style checker workflow #3005

Open
wants to merge 1 commit into
base: alpha
Choose a base branch
from
Open
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
48 changes: 48 additions & 0 deletions .github/phpcs/kr.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
<?xml version="1.0"?>
<ruleset name="JeedomKRStyle">
<description>Jeedom K and R Coding Standard</description>

<!-- Configuration générale -->
<arg name="tab-width" value="4"/>

<!-- Accolades style K&amp;R -->
<rule ref="Generic.Functions.OpeningFunctionBraceKernighanRitchie"/>

<!-- Indentation -->
<rule ref="Generic.WhiteSpace.ScopeIndent">
<properties>
<property name="indent" value="4"/>
<property name="exact" value="false"/>
<property name="tabIndent" value="true"/>
</properties>
</rule>

<!-- Espaces et formatage -->
<rule ref="Squiz.WhiteSpace.OperatorSpacing">
<properties>
<property name="ignoreNewlines" value="true"/>
</properties>
</rule>
<rule ref="Squiz.WhiteSpace.LogicalOperatorSpacing"/>
<rule ref="Squiz.WhiteSpace.SemicolonSpacing"/>

<!-- Conventions de nommage -->
<rule ref="Generic.NamingConventions.UpperCaseConstantName"/>
<rule ref="Generic.NamingConventions.CamelCapsFunctionName"/>

<!-- Structure du code -->
<rule ref="Squiz.WhiteSpace.FunctionSpacing">
<properties>
<property name="spacing" value="1"/>
</properties>
</rule>
<rule ref="Generic.Functions.FunctionCallArgumentSpacing"/>

<!-- Règles de formatage supplémentaires -->
<rule ref="Generic.Arrays.DisallowLongArraySyntax"/> <!-- Préférer [] à array() -->
<rule ref="Generic.WhiteSpace.IncrementDecrementSpacing"/> <!-- $i++ plutôt que $i ++ -->

<!-- Exclusions dossiers -->
<exclude-pattern>*/vendor/*</exclude-pattern>
<exclude-pattern>*/tmp/*</exclude-pattern>
</ruleset>
69 changes: 69 additions & 0 deletions .github/scripts/check-style.sh
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
#!/bin/bash

# Script de vérification du style de code K&R
# Vérifie uniquement les lignes modifiées dans les fichiers fournis
# Peut être utilisé en local (utilise git diff HEAD) ou dans GitHub Actions (utilise les diffs pré-générés)

# Vérification des arguments
if [ "$#" -lt 1 ]; then
echo "Usage: $0 <fichiers_php>"
exit 1
fi

# Initialisation des variables
has_errors=0
work_dir=$(pwd)

# Télécharge PHPCS si nécessaire
if [ ! -f "phpcs.phar" ]; then
echo "Téléchargement de phpcs.phar..."
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcs.phar
fi

# Traite chaque fichier PHP fourni
for file in "$@"; do
if [ ! -f "$file" ]; then
echo "Le fichier $file n'existe pas"
continue
fi

# Extraction des numéros de lignes modifiées
echo "Analyse des modifications de $file..."

# Utilise soit le fichier diff pré-généré (GitHub Actions)
# soit git diff en local
if [ -n "$DIFF_DIR" ] && [ -f "$DIFF_DIR/$(basename "$file").diff" ]; then
DIFF_FILE="$DIFF_DIR/$(basename "$file").diff"
cat "$DIFF_FILE"
else
git diff --unified=0 HEAD -- "$file"
fi | grep -E "^@@.*\+" | grep -Eo "\+[0-9]+(,[0-9]+)?" | cut -c2- | while read -r line; do
# Gestion des plages de lignes (format: début,longueur)
if [[ $line == *","* ]]; then
start=${line%,*}
length=${line#*,}
end=$((start + length - 1))
seq $start $end
else
echo $line
fi
done | sort -u > "$file.lines"

# Vérifie le style uniquement sur les lignes modifiées
echo "Vérification du style de $file..."
while IFS="," read -r filename line col level msg rest; do
if [ -n "$line" ] && [ -f "$file.lines" ]; then
# Si la ligne est dans la liste des lignes modifiées
if grep -q "^$line$" "$file.lines"; then
echo "$filename:$line:$col: [$level] $msg"
has_errors=1
fi
fi
done < <(php phpcs.phar --standard="$work_dir/.github/phpcs/kr.xml" --report=csv "$file" 2>/dev/null || true)

# Nettoyage des fichiers temporaires
rm -f "$file.lines"
done

# Retourne 1 si des erreurs ont été trouvées, 0 sinon
exit $has_errors
70 changes: 70 additions & 0 deletions .github/workflows/php-cs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# Workflow de vérification du style de code K&R
# Ne vérifie que les lignes modifiées dans les fichiers PHP des PR
name: PHP K&R Style Check
on:
pull_request:

jobs:
style-check:
name: Check K&R style
runs-on: ubuntu-latest
steps:
# Récupération du code avec l'historique pour pouvoir faire le diff
- name: Checkout code
uses: actions/checkout@v4
with:
fetch-depth: 0

# Identifie les fichiers PHP modifiés et génère leurs diffs
- name: Get changed files and diffs
id: changes
run: |
FILES=$(git diff --name-only --diff-filter=ACMRT origin/${{ github.base_ref }} ${{ github.sha }} | grep "\.php$" || true)
echo "PHP files changed:"
echo "$FILES"
echo "files=$FILES" >> $GITHUB_OUTPUT

mkdir -p .diffs
for file in $FILES; do
git diff --unified=0 origin/${{ github.base_ref }} ${{ github.sha }} -- "$file" > ".diffs/$(basename "$file").diff"
done

# Exécute la vérification de style dans un container Docker
- name: Run PHP CS check
id: style_check
if: steps.changes.outputs.files != ''
continue-on-error: true
run: |
docker run --rm \
-v ${{ github.workspace }}:/app \
-v ${{ github.workspace }}/.diffs:/app/.diffs \
-w /app \
php:8.1-cli \
bash -c 'apt-get update && apt-get install -y git && chmod +x .github/scripts/check-style.sh && DIFF_DIR=/app/.diffs .github/scripts/check-style.sh ${{ steps.changes.outputs.files }}'

# Poste un commentaire avec les instructions en cas d'erreur
- name: Post documentation notice
if: steps.style_check.outcome == 'failure'
uses: actions/github-script@v7
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const message = `## Code Style Errors Detected

Pour corriger ces erreurs, consultez la documentation :
- [Documentation FR](docs/fr_FR/code-styling.md)
- [Documentation EN](docs/en_US/code-styling.md)
- [Documentation DE](docs/de_DE/code-styling.md)
- [Documentation ES](docs/es_ES/code-styling.md)
`;
github.rest.issues.createComment({
issue_number: context.issue.number,
owner: context.repo.owner,
repo: context.repo.repo,
body: message
});

# Faire échouer le workflow si des erreurs sont trouvées
- name: Check for errors
if: steps.style_check.outcome == 'failure'
run: exit 1
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -46,3 +46,5 @@ tmp/*

!.htaccess
.env

/phpcs.phar
91 changes: 91 additions & 0 deletions docs/de_DE/code-styling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# K&R Code-Style-Überprüfung

Dieses System ermöglicht die Überprüfung der K&R-Stilkonformität bei Codeänderungen. Es kann sowohl lokal als auch über GitHub Actions verwendet werden.

## Lokale Verwendung

### Style-Überprüfung

Um nicht committete Änderungen zu überprüfen:
```bash
.github/scripts/check-style.sh file1.php file2.php
```

Um alle geänderten PHP-Dateien zu überprüfen:
```bash
.github/scripts/check-style.sh $(git diff --name-only | grep ".php$")
```

### Automatische Korrektur

PHPCS ermöglicht die automatische Korrektur bestimmter Stilfehler:

1. Laden Sie phpcbf (PHP Code Beautifier) herunter:
```bash
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
```

2. Führen Sie die Korrektur für Ihre Dateien aus:
```bash
php phpcbf.phar --standard=.github/phpcs/kr.xml file1.php file2.php
```

⚠️ **Wichtig:**
- Erstellen Sie immer ein Backup oder Commit vor der automatischen Korrektur
- Überprüfen Sie die Änderungen nach der Korrektur
- Einige Fehler erfordern manuelle Korrektur

### Installation als Pre-Commit Hook

Um den Stil vor jedem Commit automatisch zu überprüfen:

1. Erstellen Sie die Datei `.git/hooks/pre-commit`:
```bash
#!/bin/bash

# PHP-Dateien abrufen, die geändert wurden
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".php$" || true)

if [ -n "$FILES" ]; then
.github/scripts/check-style.sh $FILES
if [ $? -ne 0 ]; then
echo "❌ Stilfehler erkannt. Bitte vor dem Commit korrigieren."
exit 1
fi
fi
```

2. Machen Sie sie ausführbar:
```bash
chmod +x .git/hooks/pre-commit
```

## Code-Stil

Der überprüfte K&R-Stil umfasst:
- 4 Leerzeichen Einrückung
- Geschweifte Klammern in der gleichen Zeile für Funktionen
- (weitere projektspezifische Regeln)

Weitere Details finden Sie in der Datei `.github/phpcs/kr.xml`.

## GitHub Actions

Der GitHub-Workflow überprüft automatisch den Stil der in jedem Pull Request geänderten Dateien. Es werden nur die geänderten Zeilen überprüft, um False Positives im bestehenden Code zu vermeiden.

## Häufige Probleme und Lösungen

### Fehlermeldung "Not a git repository"
- Stellen Sie sicher, dass Sie sich im Projektverzeichnis befinden
- Überprüfen Sie, ob das Verzeichnis ein Git-Repository ist

### Fehler, die nicht von phpcbf korrigiert werden
Einige Fehler erfordern manuelle Korrektur, insbesondere:
- Die Organisation von Methoden in der Klasse
- Benennungsprobleme
- Die allgemeine Codestruktur

### False Positives
Bei False Positives:
1. Überprüfen Sie, ob Sie die neueste Version der Skripte verwenden
2. Stellen Sie sicher, dass die Datei nicht in `kr.xml` ausgeschlossen ist
91 changes: 91 additions & 0 deletions docs/en_US/code-styling.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
# K&R Code Style Checker

This system allows checking K&R style compliance on code modifications. It can be used both locally and through GitHub Actions.

## Local Usage

### Style Checking

To check uncommitted changes:
```bash
.github/scripts/check-style.sh file1.php file2.php
```

To check all modified PHP files:
```bash
.github/scripts/check-style.sh $(git diff --name-only | grep ".php$")
```

### Automatic Fixing

PHPCS allows automatic fixing of certain style errors:

1. Download phpcbf (PHP Code Beautifier):
```bash
curl -OL https://squizlabs.github.io/PHP_CodeSniffer/phpcbf.phar
```

2. Run the fix on your files:
```bash
php phpcbf.phar --standard=.github/phpcs/kr.xml file1.php file2.php
```

⚠️ **Important:**
- Always make a backup or commit before using automatic fixing
- Review changes after fixing
- Some errors require manual fixing

### Installing as Pre-Commit Hook

To automatically check style before each commit:

1. Create the `.git/hooks/pre-commit` file:
```bash
#!/bin/bash

# Get modified PHP files
FILES=$(git diff --cached --name-only --diff-filter=ACM | grep ".php$" || true)

if [ -n "$FILES" ]; then
.github/scripts/check-style.sh $FILES
if [ $? -ne 0 ]; then
echo "❌ Style errors detected. Please fix before committing."
exit 1
fi
fi
```

2. Make it executable:
```bash
chmod +x .git/hooks/pre-commit
```

## Code Style

The checked K&R style includes:
- 4 spaces indentation
- Curly braces on the same line for functions
- (other project-specific rules)

For more details, check the `.github/phpcs/kr.xml` file.

## GitHub Actions

The GitHub workflow automatically checks the style of files modified in each Pull Request. It only checks modified lines to avoid false positives on existing code.

## Common Issues and Solutions

### "Not a git repository" error message
- Make sure you're in the project directory
- Verify that the directory is a git repository

### Errors not fixed by phpcbf
Some errors require manual fixing, particularly:
- Method organization in the class
- Naming issues
- Overall code structure

### False Positives
If you encounter false positives:
1. Check that you're using the latest version of the scripts
2. Ensure the file isn't excluded in `kr.xml`
Loading
Loading