the_goth_cardgame_collection/build_scripts/check_multi_class_files.ps1

116 lines
3.9 KiB
PowerShell

#Requires -Version 5.1
<#
.SYNOPSIS
Prueft alle Python-Dateien im Projekt auf mehr als eine Klassendefinition
und gibt den vollen Dateipfad samt Klassennamen aus.
#>
param(
[string]$TargetDir = "",
[switch]$IncludeNested
)
$ErrorActionPreference = "Stop"
[Console]::OutputEncoding = [System.Text.Encoding]::UTF8
if ([string]::IsNullOrWhiteSpace($TargetDir)) {
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition
# Falls das Skript in build_scripts/ liegt, automatisch eine Ebene hoeher starten, sonst im aktuellen Ordner
if ((Split-Path -Leaf $ScriptDir) -ieq "build_scripts") {
$RootPath = (Resolve-Path (Join-Path $ScriptDir "..")).Path
} else {
$RootPath = (Resolve-Path $ScriptDir).Path
}
} else {
$RootPath = (Resolve-Path $TargetDir).Path
}
$ExcludeDirs = @(".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__")
# Versuche Python fuer 100% exaktes AST-Parsing zu finden, sonst Fallback auf Regex
$PyExe = $null
$venvPy = Join-Path $RootPath ".venv\Scripts\python.exe"
if (Test-Path $venvPy) {
$PyExe = $venvPy
} else {
foreach ($cmd in @("python", "python3")) {
$found = Get-Command $cmd -ErrorAction SilentlyContinue
if ($found) { $PyExe = $found.Source; break }
}
}
if ($PyExe) {
$PyScript = @'
# -*- coding: utf-8 -*-
import ast
import os
import sys
from pathlib import Path
root = Path(sys.argv[1]).resolve()
include_nested = "--nested" in sys.argv[2:]
exclude_dirs = {".git", ".venv", ".venv_build_win", ".venv_build_macos", "build", "dist", "__pycache__"}
def get_classes(tree: ast.AST, nested: bool) -> list[str]:
if not nested:
return [node.name for node in getattr(tree, "body", []) if isinstance(node, ast.ClassDef)]
found = []
def walk_node(n, prefix=""):
for child in ast.iter_child_nodes(n):
if isinstance(child, ast.ClassDef):
qual = f"{prefix}.{child.name}" if prefix else child.name
found.append(qual)
walk_node(child, qual)
else:
walk_node(child, prefix)
walk_node(tree)
return found
for dirpath, dirnames, filenames in os.walk(root):
dirnames[:] = sorted(d for d in dirnames if d not in exclude_dirs)
for fn in sorted(filenames):
if not fn.endswith(".py"):
continue
fpath = Path(dirpath) / fn
try:
src = fpath.read_text(encoding="utf-8", errors="replace")
tree = ast.parse(src, filename=str(fpath))
classes = get_classes(tree, include_nested)
if len(classes) > 1:
print(str(fpath))
for cls_name in classes:
print(f"- {cls_name}")
print("")
except SyntaxError:
pass
'@
$pyArgs = @($RootPath)
if ($IncludeNested) { $pyArgs += "--nested" }
$PyScript | & $PyExe - @pyArgs
}
else {
# Reiner PowerShell-Fallback falls kein Python im PATH ist
$ClassRegex = if ($IncludeNested) { '^\s*class\s+([A-Za-z_][A-Za-z0-9_]*)\b' } else { '^class\s+([A-Za-z_][A-Za-z0-9_]*)\b' }
Get-ChildItem -Path $RootPath -Recurse -File -Filter "*.py" | Where-Object {
$full = $_.FullName
$skip = $false
foreach ($ex in $ExcludeDirs) {
if ($full -match ([regex]::Escape("\$ex\"))) { $skip = $true; break }
}
-not $skip
} | Sort-Object FullName | ForEach-Object {
$classes = New-Object System.Collections.Generic.List[string]
foreach ($line in [System.IO.File]::ReadLines($_.FullName)) {
if ($line -match $ClassRegex) {
$classes.Add($Matches[1])
}
}
if ($classes.Count -gt 1) {
Write-Output $_.FullName
foreach ($c in $classes) {
Write-Output "- $c"
}
Write-Output ""
}
}
}