Merge pull request 'chore: migrate 7 CLIApp scripts to CliFramework' (#108) from dev into main
Generic: Repo Health / Site Health (push) Has been cancelled
Generic: Repo Health / Access control (push) Has been cancelled
Universal: Cascade Main → Dev / Cascade main → branches (push) Has been cancelled
Generic: Repo Health / Release configuration (push) Has been cancelled
Generic: Repo Health / Scripts governance (push) Has been cancelled
Generic: Repo Health / Repository health (push) Has been cancelled
Platform: moko-platform CI / Gate 1: Code Quality (push) Has been cancelled
Platform: moko-platform CI / Gate 2: Unit Tests (8.1) (push) Has been cancelled
Platform: moko-platform CI / Gate 2: Unit Tests (8.2) (push) Has been cancelled
Platform: moko-platform CI / Gate 2: Unit Tests (8.3) (push) Has been cancelled
Platform: moko-platform CI / Gate 3: Self-Health Check (push) Has been cancelled
Platform: moko-platform CI / Gate 4: Governance (push) Has been cancelled
Platform: moko-platform CI / Gate 5: Template Integrity (push) Has been cancelled
Platform: moko-platform CI / CI Summary (push) Has been cancelled

This commit was merged in pull request #108.
This commit is contained in:
2026-05-26 02:21:08 +00:00
9 changed files with 188 additions and 214 deletions
+32 -38
View File
@@ -30,7 +30,7 @@ require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoEnterprise\{ use MokoEnterprise\{
AuditLogger, AuditLogger,
CLIApp, CliFramework,
Config, Config,
GitPlatformAdapter, GitPlatformAdapter,
MetricsCollector, MetricsCollector,
@@ -47,7 +47,7 @@ use MokoEnterprise\{
* *
* Works with both GitHub and Gitea via the PlatformAdapterFactory. * Works with both GitHub and Gitea via the PlatformAdapterFactory.
*/ */
class BulkJoomlaTemplate extends CLIApp class BulkJoomlaTemplate extends CliFramework
{ {
public const DEFAULT_ORG = 'MokoConsulting'; public const DEFAULT_ORG = 'MokoConsulting';
public const VERSION = '04.06.10'; public const VERSION = '04.06.10';
@@ -56,22 +56,20 @@ class BulkJoomlaTemplate extends CLIApp
private AuditLogger $logger; private AuditLogger $logger;
private Config $config; private Config $config;
protected function setupArguments(): array protected function configure(): void
{ {
return [ $this->setDescription('Bulk Joomla template management');
'org:' => 'Organization (default: ' . self::DEFAULT_ORG . ')', $this->addArgument('--org', 'Organization', self::DEFAULT_ORG);
'scaffold' => 'Create a new Joomla template repository', $this->addArgument('--scaffold', 'Create new template repo', false);
'sync' => 'Sync MokoStandards files to existing template repos', $this->addArgument('--sync', 'Sync files to template repos', false);
'list' => 'List all joomla-template repositories', $this->addArgument('--list', 'List template repos', false);
'name:' => 'Template name for --scaffold (e.g. MokoTheme)', $this->addArgument('--name', 'Template name for scaffold', '');
'client:' => 'Joomla client: site (default) or administrator', $this->addArgument('--client', 'Joomla client: site or admin', 'site');
'repos:' => 'Target repositories for --sync (comma-separated, or use --all)', $this->addArgument('--repos', 'Target repos (comma-separated)', '');
'all' => 'Sync all repos tagged joomla-template', $this->addArgument('--all', 'Sync all tagged repos', false);
'sync-updates' => 'Sync updates.xml between Gitea and GitHub for Joomla repos', $this->addArgument('--sync-updates', 'Sync updates.xml', false);
'private' => 'Create as private repository (--scaffold)', $this->addArgument('--private', 'Create as private repo', false);
'dry-run' => 'Preview changes without making them', $this->addArgument('--yes', 'Auto-confirm', false);
'yes' => 'Auto-confirm prompts',
];
} }
protected function run(): int protected function run(): int
@@ -88,23 +86,23 @@ class BulkJoomlaTemplate extends CLIApp
} }
$this->logger = new AuditLogger('joomla_template'); $this->logger = new AuditLogger('joomla_template');
$org = $this->getOption('org', self::DEFAULT_ORG); $org = $this->getArgument('--org', self::DEFAULT_ORG);
$platform = $this->adapter->getPlatformName(); $platform = $this->adapter->getPlatformName();
$this->log("Platform: {$platform} | Organization: {$org}", 'INFO'); $this->log("Platform: {$platform} | Organization: {$org}", 'INFO');
if ($this->hasOption('list')) { if ($this->getArgument('--list', false)) {
return $this->listTemplateRepos($org); return $this->listTemplateRepos($org);
} }
if ($this->hasOption('scaffold')) { if ($this->getArgument('--scaffold', false)) {
return $this->scaffoldTemplate($org); return $this->scaffoldTemplate($org);
} }
if ($this->hasOption('sync')) { if ($this->getArgument('--sync', false)) {
return $this->syncTemplates($org); return $this->syncTemplates($org);
} }
if ($this->hasOption('sync-updates')) { if ($this->getArgument('--sync-updates', false)) {
return $this->syncUpdatesBetweenPlatforms($org); return $this->syncUpdatesBetweenPlatforms($org);
} }
@@ -138,9 +136,9 @@ class BulkJoomlaTemplate extends CLIApp
private function scaffoldTemplate(string $org): int private function scaffoldTemplate(string $org): int
{ {
$name = $this->getOption('name', ''); $name = $this->getArgument('--name', '');
$client = $this->getOption('client', 'site'); $client = $this->getArgument('--client', 'site');
$dryRun = $this->hasOption('dry-run'); $dryRun = $this->dryRun;
if (empty($name)) { if (empty($name)) {
$this->log("❌ --name is required for --scaffold", 'ERROR'); $this->log("❌ --name is required for --scaffold", 'ERROR');
@@ -176,7 +174,7 @@ class BulkJoomlaTemplate extends CLIApp
} }
// Confirm // Confirm
if (!$this->hasOption('yes')) { if (!$this->getArgument('--yes', false)) {
echo "\nCreate repository {$org}/{$name}? [y/N]: "; echo "\nCreate repository {$org}/{$name}? [y/N]: ";
$handle = fopen('php://stdin', 'r'); $handle = fopen('php://stdin', 'r');
$line = fgets($handle); $line = fgets($handle);
@@ -192,7 +190,7 @@ class BulkJoomlaTemplate extends CLIApp
// Create repository // Create repository
$this->log("\nCreating repository...", 'INFO'); $this->log("\nCreating repository...", 'INFO');
try { try {
$isPrivate = $this->hasOption('private'); $isPrivate = $this->getArgument('--private', false);
$this->adapter->createOrgRepo($org, $name, [ $this->adapter->createOrgRepo($org, $name, [
'description' => "Joomla {$client} template — {$name}", 'description' => "Joomla {$client} template — {$name}",
'private' => $isPrivate, 'private' => $isPrivate,
@@ -263,10 +261,10 @@ class BulkJoomlaTemplate extends CLIApp
{ {
$repos = []; $repos = [];
if ($this->hasOption('all')) { if ($this->getArgument('--all', false)) {
$repos = $this->findTemplateRepos($org); $repos = $this->findTemplateRepos($org);
} else { } else {
$reposArg = $this->getOption('repos', ''); $reposArg = $this->getArgument('--repos', '');
if (empty($reposArg)) { if (empty($reposArg)) {
$this->log("❌ --repos or --all required for --sync", 'ERROR'); $this->log("❌ --repos or --all required for --sync", 'ERROR');
return 1; return 1;
@@ -284,7 +282,7 @@ class BulkJoomlaTemplate extends CLIApp
$this->log("\nSyncing " . count($repos) . " template repo(s)...", 'INFO'); $this->log("\nSyncing " . count($repos) . " template repo(s)...", 'INFO');
$dryRun = $this->hasOption('dry-run'); $dryRun = $this->dryRun;
$success = 0; $success = 0;
$failed = 0; $failed = 0;
@@ -741,7 +739,7 @@ class BulkJoomlaTemplate extends CLIApp
{ {
$repos = []; $repos = [];
if ($this->hasOption('all')) { if ($this->getArgument('--all', false)) {
$repos = $this->findTemplateRepos($org); $repos = $this->findTemplateRepos($org);
// Also include waas-component repos // Also include waas-component repos
$allRepos = $this->adapter->listOrgRepos($org, true); $allRepos = $this->adapter->listOrgRepos($org, true);
@@ -765,7 +763,7 @@ class BulkJoomlaTemplate extends CLIApp
return true; return true;
}); });
} else { } else {
$reposArg = $this->getOption('repos', ''); $reposArg = $this->getArgument('--repos', '');
if (empty($reposArg)) { if (empty($reposArg)) {
$this->log("❌ --repos or --all required for --sync-updates", 'ERROR'); $this->log("❌ --repos or --all required for --sync-updates", 'ERROR');
return 1; return 1;
@@ -791,7 +789,7 @@ class BulkJoomlaTemplate extends CLIApp
$gitea = $adapters['gitea']; $gitea = $adapters['gitea'];
$github = $adapters['github']; $github = $adapters['github'];
$dryRun = $this->hasOption('dry-run'); $dryRun = $this->dryRun;
$this->log("\nSyncing updates.xml across Gitea <-> GitHub for " . count($repos) . " repo(s)...", 'INFO'); $this->log("\nSyncing updates.xml across Gitea <-> GitHub for " . count($repos) . " repo(s)...", 'INFO');
@@ -936,10 +934,6 @@ class BulkJoomlaTemplate extends CLIApp
// Execute if run directly // Execute if run directly
if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) { if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
$app = new BulkJoomlaTemplate( $app = new BulkJoomlaTemplate();
'joomla-template',
'Bulk scaffold and sync Joomla template repositories',
BulkJoomlaTemplate::VERSION
);
exit($app->execute()); exit($app->execute());
} }
+23 -27
View File
@@ -26,7 +26,7 @@ use MokoEnterprise\{
AuditLogger, AuditLogger,
CheckpointManager, CheckpointManager,
CircuitBreakerOpen, CircuitBreakerOpen,
CLIApp, CliFramework,
Config, Config,
GitPlatformAdapter, GitPlatformAdapter,
MetricsCollector, MetricsCollector,
@@ -45,7 +45,7 @@ use MokoEnterprise\{
* Synchronizes MokoStandards files across multiple repositories using * Synchronizes MokoStandards files across multiple repositories using
* the Enterprise library for robust, audited operations. * the Enterprise library for robust, audited operations.
*/ */
class BulkSync extends CLIApp class BulkSync extends CliFramework
{ {
/** /**
* Default organization for bulk sync operations * Default organization for bulk sync operations
@@ -65,6 +65,7 @@ class BulkSync extends CLIApp
private RepositorySynchronizer $synchronizer; private RepositorySynchronizer $synchronizer;
private AuditLogger $logger; private AuditLogger $logger;
private CheckpointManager $checkpoints; private CheckpointManager $checkpoints;
private MetricsCollector $metrics;
private SecurityValidator $security; private SecurityValidator $security;
private PluginFactory $pluginFactory; private PluginFactory $pluginFactory;
private ProjectTypeDetector $typeDetector; private ProjectTypeDetector $typeDetector;
@@ -76,21 +77,20 @@ class BulkSync extends CLIApp
/** /**
* Setup command-line arguments * Setup command-line arguments
*/ */
protected function setupArguments(): array protected function configure(): void
{ {
return [ $this->setDescription('Bulk repository synchronization');
'org:' => 'GitHub organization (default: MokoConsulting)', $this->addArgument('--org', 'Organization', self::DEFAULT_ORG);
'repos:' => 'Specific repositories to sync (space-separated)', $this->addArgument('--repos', 'Specific repos', '');
'exclude:' => 'Repositories to exclude (space-separated)', $this->addArgument('--exclude', 'Repos to exclude', '');
'skip-archived' => 'Skip archived repositories', $this->addArgument('--skip-archived', 'Skip archived repos', false);
'yes' => 'Auto-confirm prompts', $this->addArgument('--yes', 'Auto-confirm', false);
'resume' => 'Resume from last checkpoint, skipping already-processed repositories', $this->addArgument('--resume', 'Resume from checkpoint', false);
'force' => 'Force overwrite of protected files (always_overwrite=false), except truly protected files', $this->addArgument('--force', 'Force overwrite', false);
'protect' => 'Apply/enforce main branch protection rules on all synced repositories', $this->addArgument('--protect', 'Apply branch protection', false);
'no-issue' => 'Skip creating a tracking issue in each target repository', $this->addArgument('--no-issue', 'Skip tracking issue', false);
'update-branches' => 'After sync, merge main into all other open PR branches in each repo', $this->addArgument('--update-branches', 'Merge main into branches', false);
'health' => 'Run repo health checks after sync and include results in the report', $this->addArgument('--health', 'Run health checks', false);
];
} }
/** /**
@@ -106,13 +106,13 @@ class BulkSync extends CLIApp
} }
// Get configuration // Get configuration
$org = $this->getOption('org', self::DEFAULT_ORG); $org = $this->getArgument('--org', self::DEFAULT_ORG);
$skipArchived = $this->hasOption('skip-archived'); $skipArchived = $this->getArgument('--skip-archived', false);
$autoConfirm = $this->hasOption('yes'); $autoConfirm = $this->getArgument('--yes', false);
// Get repository filters // Get repository filters
$specificRepos = $this->parseRepositoryList($this->getOption('repos', '')); $specificRepos = $this->parseRepositoryList($this->getArgument('--repos', ''));
$excludeRepos = $this->parseRepositoryList($this->getOption('exclude', '')); $excludeRepos = $this->parseRepositoryList($this->getArgument('--exclude', ''));
$this->log("Organization: {$org}", 'INFO'); $this->log("Organization: {$org}", 'INFO');
if (!empty($specificRepos)) { if (!empty($specificRepos)) {
@@ -139,7 +139,7 @@ class BulkSync extends CLIApp
// Load resume checkpoint if --resume is set // Load resume checkpoint if --resume is set
$alreadyProcessed = []; $alreadyProcessed = [];
if ($this->hasOption('resume')) { if ($this->getArgument('--resume', false)) {
$checkpoint = $this->checkpoints->loadCheckpoint('bulk_sync'); $checkpoint = $this->checkpoints->loadCheckpoint('bulk_sync');
if ($checkpoint !== null) { if ($checkpoint !== null) {
$alreadyProcessed = array_keys($checkpoint['results']['repositories'] ?? []); $alreadyProcessed = array_keys($checkpoint['results']['repositories'] ?? []);
@@ -1424,10 +1424,6 @@ class BulkSync extends CLIApp
// Execute if run directly // Execute if run directly
if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) { if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
$app = new BulkSync( $app = new BulkSync();
'bulk-sync',
'Enterprise-grade bulk repository synchronization',
BulkSync::VERSION
);
exit($app->execute()); exit($app->execute());
} }
+27 -29
View File
@@ -24,7 +24,7 @@ require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoEnterprise\{ use MokoEnterprise\{
ApiClient, ApiClient,
AuditLogger, AuditLogger,
CLIApp, CliFramework,
Config, Config,
DefinitionParser, DefinitionParser,
GitPlatformAdapter, GitPlatformAdapter,
@@ -51,7 +51,7 @@ use MokoEnterprise\{
* php push_files.php --files=".github/workflows/ci.yml,.github/workflows/codeql-analysis.yml" --repos=MokoCRM,WaasComponent * php push_files.php --files=".github/workflows/ci.yml,.github/workflows/codeql-analysis.yml" --repos=MokoCRM,WaasComponent
* php push_files.php --files=templates/foo.txt:docs/foo.txt --repos=MyRepo --direct * php push_files.php --files=templates/foo.txt:docs/foo.txt --repos=MyRepo --direct
*/ */
class PushFiles extends CLIApp class PushFiles extends CliFramework
{ {
public const DEFAULT_ORG = 'MokoConsulting'; public const DEFAULT_ORG = 'MokoConsulting';
public const VERSION = '04.06.00'; public const VERSION = '04.06.00';
@@ -65,18 +65,17 @@ class PushFiles extends CLIApp
/** /**
* Setup command-line arguments * Setup command-line arguments
*/ */
protected function setupArguments(): array protected function configure(): void
{ {
return [ $this->setDescription('Push files to remote repositories');
'org:' => 'GitHub organization (default: ' . self::DEFAULT_ORG . ')', $this->addArgument('--org', 'GitHub organization', self::DEFAULT_ORG);
'repos:' => 'Target repositories — comma or space-separated (required)', $this->addArgument('--repos', 'Target repos (comma-separated)', '');
'files:' => 'Files to push — destination paths or source:destination pairs, comma/space-separated (required)', $this->addArgument('--files', 'Files to push (comma-separated)', '');
'message:' => 'Custom commit message (optional)', $this->addArgument('--message', 'Custom commit message', '');
'branch:' => 'Target branch for direct pushes (default: repo default branch). Ignored unless --direct is set', $this->addArgument('--branch', 'Target branch for direct pushes', '');
'direct' => 'Push directly to target branch instead of creating a PR', $this->addArgument('--direct', 'Push directly instead of PR', false);
'yes' => 'Auto-confirm without prompting', $this->addArgument('--yes', 'Auto-confirm without prompting', false);
'no-issue' => 'Skip creating a tracking issue in each target repository', $this->addArgument('--no-issue', 'Skip creating tracking issue', false);
];
} }
/** /**
@@ -90,11 +89,11 @@ class PushFiles extends CLIApp
return 1; return 1;
} }
$org = $this->getOption('org', self::DEFAULT_ORG); $org = $this->getArgument('--org', self::DEFAULT_ORG);
$reposArg = $this->getOption('repos', ''); $reposArg = $this->getArgument('--repos', '');
$filesArg = $this->getOption('files', ''); $filesArg = $this->getArgument('--files', '');
$direct = $this->hasOption('direct'); $direct = $this->getArgument('--direct', false);
$autoYes = $this->hasOption('yes'); $autoYes = $this->getArgument('--yes', false);
// Validate required arguments // Validate required arguments
if (empty($reposArg)) { if (empty($reposArg)) {
@@ -127,7 +126,7 @@ class PushFiles extends CLIApp
} }
// Confirm before proceeding // Confirm before proceeding
if (!$autoYes && !$this->confirm($repoFileMaps, $direct)) { if (!$autoYes && !$this->confirmPush($repoFileMaps, $direct)) {
$this->log('❌ Cancelled.', 'INFO'); $this->log('❌ Cancelled.', 'INFO');
return 0; return 0;
} }
@@ -265,7 +264,8 @@ class PushFiles extends CLIApp
// Fall back to live detection // Fall back to live detection
try { try {
$repoData = $this->api->get("/repos/{$org}/{$repo}"); $repoData = $this->api->get("/repos/{$org}/{$repo}");
return $this->typeDetector->detect($repoData, $org, $repo); $result = $this->typeDetector->detect('.');
return $result['type'] ?? 'default';
} catch (\Exception $e) { } catch (\Exception $e) {
$this->log(" ⚠️ Could not detect platform for {$repo}, using 'default'", 'WARN'); $this->log(" ⚠️ Could not detect platform for {$repo}, using 'default'", 'WARN');
return 'default'; return 'default';
@@ -277,7 +277,7 @@ class PushFiles extends CLIApp
* *
* @param array<string, list<array{source: string, destination: string}>> $repoFileMaps * @param array<string, list<array{source: string, destination: string}>> $repoFileMaps
*/ */
private function confirm(array $repoFileMaps, bool $direct): bool private function confirmPush(array $repoFileMaps, bool $direct): bool
{ {
if ($this->quiet) { if ($this->quiet) {
return true; return true;
@@ -322,8 +322,8 @@ class PushFiles extends CLIApp
'repos' => [], 'repos' => [],
]; ];
$customMessage = $this->getOption('message', ''); $customMessage = $this->getArgument('--message', '');
$targetBranch = $this->getOption('branch', ''); $targetBranch = $this->getArgument('--branch', '');
foreach ($repoFileMaps as $repo => $entries) { foreach ($repoFileMaps as $repo => $entries) {
$this->log("\n[{$repo}] Pushing " . count($entries) . ' file(s)...', 'INFO'); $this->log("\n[{$repo}] Pushing " . count($entries) . ' file(s)...', 'INFO');
@@ -520,6 +520,7 @@ class PushFiles extends CLIApp
'direction' => 'desc', 'direction' => 'desc',
]); ]);
$existing = array_values($existing);
if (!empty($existing) && isset($existing[0]['number'])) { if (!empty($existing) && isset($existing[0]['number'])) {
$num = $existing[0]['number']; $num = $existing[0]['number'];
$patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']]; $patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']];
@@ -581,7 +582,7 @@ class PushFiles extends CLIApp
)); ));
$repoList = implode("\n", array_map(fn($r) => "- `{$r}`", $failedRepos)); $repoList = implode("\n", array_map(fn($r) => "- `{$r}`", $failedRepos));
$fileArgs = $this->getOption('files', ''); $fileArgs = $this->getArgument('--files', '');
$title = "fix: push_files failed for {$failed} repo(s) — action required"; $title = "fix: push_files failed for {$failed} repo(s) — action required";
@@ -622,6 +623,7 @@ class PushFiles extends CLIApp
'direction' => 'desc', 'direction' => 'desc',
]); ]);
$existing = array_values($existing);
if (!empty($existing) && isset($existing[0]['number'])) { if (!empty($existing) && isset($existing[0]['number'])) {
$num = $existing[0]['number']; $num = $existing[0]['number'];
$patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']]; $patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']];
@@ -693,10 +695,6 @@ class PushFiles extends CLIApp
// Execute if run directly // Execute if run directly
if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) { if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
$app = new PushFiles( $app = new PushFiles();
'push-files',
'Push one or more specific files to one or more remote repositories',
PushFiles::VERSION
);
exit($app->execute()); exit($app->execute());
} }
+72 -78
View File
@@ -21,7 +21,7 @@ declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/Enterprise/CliFramework.php'; require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoEnterprise\{ApiClient, AuditLogger, CLIApp, Config, GitPlatformAdapter, MetricsCollector, PlatformAdapterFactory}; use MokoEnterprise\{ApiClient, AuditLogger, CliFramework, Config, GitPlatformAdapter, MetricsCollector, PlatformAdapterFactory};
/** /**
* Enterprise Repository Cleanup * Enterprise Repository Cleanup
@@ -36,7 +36,7 @@ use MokoEnterprise\{ApiClient, AuditLogger, CLIApp, Config, GitPlatformAdapter,
* 7. Verify and provision standard labels * 7. Verify and provision standard labels
* 8. Version drift detection * 8. Version drift detection
*/ */
class RepoCleanup extends CLIApp class RepoCleanup extends CliFramework
{ {
private const VERSION = '04.06.00'; private const VERSION = '04.06.00';
private const SYNC_PREFIX = 'chore/sync-mokostandards-'; private const SYNC_PREFIX = 'chore/sync-mokostandards-';
@@ -60,40 +60,34 @@ class RepoCleanup extends CLIApp
private GitPlatformAdapter $adapter; private GitPlatformAdapter $adapter;
private AuditLogger $logger; private AuditLogger $logger;
private MetricsCollector $metrics; private MetricsCollector $metrics;
private bool $dryRun = false; protected bool $dryRun = false;
private float $startTime; private float $startTime;
protected function configure(): void protected function configure(): void
{ {
$this->setName('repo-cleanup'); $this->setDescription('Enterprise repository cleanup');
$this->setDescription('Enterprise repository cleanup — branches, PRs, issues, workflows, labels, logs'); $this->addArgument('--org', 'GitHub organization', 'MokoConsulting');
$this->setVersion(self::VERSION); $this->addArgument('--repos', 'Specific repos (space-separated)', '');
$this->addArgument('--skip-archived', 'Skip archived repos', false);
$this->addOption('org', 'GitHub organization', 'MokoConsulting'); $this->addArgument('--close-issues', 'Close resolved tracking issues', false);
$this->addOption('repos', 'Specific repositories (space-separated)', ''); $this->addArgument('--lock-old-issues', 'Lock issues closed >30 days', false);
$this->addOption('skip-archived', 'Skip archived repositories', false); $this->addArgument('--clean-workflows', 'Delete stale workflow runs', false);
$this->addOption('close-issues', 'Close resolved tracking issues (merged PR = done)', false); $this->addArgument('--clean-logs', 'Delete old workflow logs', false);
$this->addOption('lock-old-issues', 'Lock issues closed >30 days', false); $this->addArgument('--log-days', 'Days to keep logs', '30');
$this->addOption('clean-workflows', 'Delete cancelled/stale workflow runs', false); $this->addArgument('--delete-retired', 'Delete retired workflows', false);
$this->addOption('clean-logs', 'Delete workflow run logs older than --log-days', false); $this->addArgument('--check-labels', 'Verify labels exist', false);
$this->addOption('log-days', 'Days to keep logs (default: 30)', '30'); $this->addArgument('--check-drift', 'Check version drift', false);
$this->addOption('delete-retired', 'Delete retired workflow files from repos', false); $this->addArgument('--all', 'Run all operations', false);
$this->addOption('check-labels', 'Verify mokostandards label exists', false); $this->addArgument('--yes', 'Auto-confirm', false);
$this->addOption('check-drift', 'Check for version drift against README.md', false); $this->addArgument('--json', 'Output as JSON', false);
$this->addOption('all', 'Run all cleanup operations', false);
$this->addOption('yes', 'Auto-confirm prompts', false);
$this->addOption('dry-run', 'Preview changes without making them', false);
$this->addOption('verbose', 'Show detailed output', false);
$this->addOption('quiet', 'Suppress non-error output', false);
$this->addOption('json', 'Output results as JSON', false);
} }
protected function execute(): int protected function run(): int
{ {
$this->startTime = microtime(true); $this->startTime = microtime(true);
$org = $this->getOption('org', 'MokoConsulting'); $org = $this->getArgument('--org', 'MokoConsulting');
$this->dryRun = (bool) $this->getOption('dry-run', false); $this->dryRun = (bool) $this->getArgument('--dry-run', false);
$runAll = (bool) $this->getOption('all', false); $runAll = (bool) $this->getArgument('--all', false);
$config = Config::load(); $config = Config::load();
@@ -101,24 +95,24 @@ class RepoCleanup extends CLIApp
$this->adapter = PlatformAdapterFactory::create($config); $this->adapter = PlatformAdapterFactory::create($config);
$this->api = $this->adapter->getApiClient(); $this->api = $this->adapter->getApiClient();
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Failed to initialize platform adapter: ' . $e->getMessage()); $this->errorMsg('Failed to initialize platform adapter: ' . $e->getMessage());
return 1; return 1;
} }
$this->logger = new AuditLogger('repo_cleanup'); $this->logger = new AuditLogger('repo_cleanup');
$this->metrics = new MetricsCollector('repo_cleanup'); $this->metrics = new MetricsCollector('repo_cleanup');
$this->log("🧹 MokoStandards Repository Cleanup v" . self::VERSION); $this->logMsg("🧹 MokoStandards Repository Cleanup v" . self::VERSION);
$this->log("Organization: {$org}"); $this->logMsg("Organization: {$org}");
$this->log("Current sync branch: " . self::CURRENT_BRANCH); $this->logMsg("Current sync branch: " . self::CURRENT_BRANCH);
if ($this->dryRun) { if ($this->dryRun) {
$this->log("⚠️ DRY RUN — no changes will be made"); $this->logMsg("⚠️ DRY RUN — no changes will be made");
} }
$this->log(''); $this->logMsg('');
$repos = $this->fetchRepositories($org); $repos = $this->fetchRepositories($org);
$this->log("Found " . count($repos) . " repositories"); $this->logMsg("Found " . count($repos) . " repositories");
$this->log(''); $this->logMsg('');
$results = [ $results = [
'repos_processed' => 0, 'repos_processed' => 0,
@@ -140,7 +134,7 @@ class RepoCleanup extends CLIApp
$name = $repo['name']; $name = $repo['name'];
$num = $i + 1; $num = $i + 1;
$total = count($repos); $total = count($repos);
$this->log("[{$num}/{$total}] {$name}"); $this->logMsg("[{$num}/{$total}] {$name}");
$results['repos_processed']++; $results['repos_processed']++;
try { try {
@@ -151,37 +145,37 @@ class RepoCleanup extends CLIApp
$cleaned = $this->cleanBranches($org, $name, $results) || $cleaned; $cleaned = $this->cleanBranches($org, $name, $results) || $cleaned;
// Optional: close resolved issues // Optional: close resolved issues
if ($runAll || $this->getOption('close-issues', false)) { if ($runAll || $this->getArgument('--close-issues', false)) {
$cleaned = $this->closeResolvedIssues($org, $name, $results) || $cleaned; $cleaned = $this->closeResolvedIssues($org, $name, $results) || $cleaned;
} }
// Optional: lock old closed issues // Optional: lock old closed issues
if ($runAll || $this->getOption('lock-old-issues', false)) { if ($runAll || $this->getArgument('--lock-old-issues', false)) {
$cleaned = $this->lockOldIssues($org, $name, $results) || $cleaned; $cleaned = $this->lockOldIssues($org, $name, $results) || $cleaned;
} }
// Optional: delete retired workflow files // Optional: delete retired workflow files
if ($runAll || $this->getOption('delete-retired', false)) { if ($runAll || $this->getArgument('--delete-retired', false)) {
$cleaned = $this->deleteRetiredWorkflows($org, $name, $results) || $cleaned; $cleaned = $this->deleteRetiredWorkflows($org, $name, $results) || $cleaned;
} }
// Optional: clean workflow runs // Optional: clean workflow runs
if ($runAll || $this->getOption('clean-workflows', false)) { if ($runAll || $this->getArgument('--clean-workflows', false)) {
$cleaned = $this->cleanWorkflowRuns($org, $name, $results) || $cleaned; $cleaned = $this->cleanWorkflowRuns($org, $name, $results) || $cleaned;
} }
// Optional: clean old logs // Optional: clean old logs
if ($runAll || $this->getOption('clean-logs', false)) { if ($runAll || $this->getArgument('--clean-logs', false)) {
$cleaned = $this->cleanOldLogs($org, $name, $results) || $cleaned; $cleaned = $this->cleanOldLogs($org, $name, $results) || $cleaned;
} }
// Optional: check labels // Optional: check labels
if ($runAll || $this->getOption('check-labels', false)) { if ($runAll || $this->getArgument('--check-labels', false)) {
$this->checkLabels($org, $name, $results); $this->checkLabels($org, $name, $results);
} }
// Optional: check version drift // Optional: check version drift
if ($runAll || $this->getOption('check-drift', false)) { if ($runAll || $this->getArgument('--check-drift', false)) {
$this->checkVersionDrift($org, $name, $results); $this->checkVersionDrift($org, $name, $results);
} }
@@ -189,32 +183,32 @@ class RepoCleanup extends CLIApp
$results['repos_cleaned']++; $results['repos_cleaned']++;
} }
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error("{$name}: " . $e->getMessage()); $this->errorMsg("{$name}: " . $e->getMessage());
$results['errors']++; $results['errors']++;
} }
} }
$duration = round(microtime(true) - $this->startTime, 1); $duration = round(microtime(true) - $this->startTime, 1);
$this->log(''); $this->logMsg('');
$this->log('============================================================'); $this->logMsg('============================================================');
$this->log("🧹 Cleanup Complete ({$duration}s)"); $this->logMsg("🧹 Cleanup Complete ({$duration}s)");
$this->log('============================================================'); $this->logMsg('============================================================');
$this->log("Repos processed: {$results['repos_processed']}"); $this->logMsg("Repos processed: {$results['repos_processed']}");
$this->log("Repos with changes: {$results['repos_cleaned']}"); $this->logMsg("Repos with changes: {$results['repos_cleaned']}");
$this->log("Branches deleted: {$results['branches_deleted']}"); $this->logMsg("Branches deleted: {$results['branches_deleted']}");
$this->log("PRs closed: {$results['prs_closed']}"); $this->logMsg("PRs closed: {$results['prs_closed']}");
$this->log("Issues closed: {$results['issues_closed']}"); $this->logMsg("Issues closed: {$results['issues_closed']}");
$this->log("Issues locked: {$results['issues_locked']}"); $this->logMsg("Issues locked: {$results['issues_locked']}");
$this->log("Retired files: {$results['retired_files']}"); $this->logMsg("Retired files: {$results['retired_files']}");
$this->log("Workflow runs: {$results['runs_deleted']}"); $this->logMsg("Workflow runs: {$results['runs_deleted']}");
$this->log("Logs cleaned: {$results['logs_deleted']}"); $this->logMsg("Logs cleaned: {$results['logs_deleted']}");
$this->log("Labels missing: {$results['labels_missing']}"); $this->logMsg("Labels missing: {$results['labels_missing']}");
$this->log("Version drift: {$results['version_drift']}"); $this->logMsg("Version drift: {$results['version_drift']}");
$this->log("Errors: {$results['errors']}"); $this->logMsg("Errors: {$results['errors']}");
$this->log('============================================================'); $this->logMsg('============================================================');
if ($this->getOption('json', false)) { if ($this->getArgument('--json', false)) {
$results['duration_seconds'] = $duration; $results['duration_seconds'] = $duration;
echo json_encode($results, JSON_PRETTY_PRINT) . "\n"; echo json_encode($results, JSON_PRETTY_PRINT) . "\n";
} }
@@ -226,8 +220,8 @@ class RepoCleanup extends CLIApp
private function fetchRepositories(string $org): array private function fetchRepositories(string $org): array
{ {
$specificRepos = trim((string) $this->getOption('repos', '')); $specificRepos = trim((string) $this->getArgument('--repos', ''));
$skipArchived = (bool) $this->getOption('skip-archived', false); $skipArchived = (bool) $this->getArgument('--skip-archived', false);
if (!empty($specificRepos)) { if (!empty($specificRepos)) {
$names = preg_split('/[\s,]+/', $specificRepos); $names = preg_split('/[\s,]+/', $specificRepos);
@@ -264,7 +258,7 @@ class RepoCleanup extends CLIApp
if (($pr['number'] ?? 0) > 0 && !$this->dryRun) { if (($pr['number'] ?? 0) > 0 && !$this->dryRun) {
$this->api->patch("/repos/{$org}/{$repo}/pulls/{$pr['number']}", ['state' => 'closed']); $this->api->patch("/repos/{$org}/{$repo}/pulls/{$pr['number']}", ['state' => 'closed']);
} }
$this->log(" 🔒 Closed PR #{$pr['number']} ({$name})"); $this->logMsg(" 🔒 Closed PR #{$pr['number']} ({$name})");
$results['prs_closed']++; $results['prs_closed']++;
$changed = true; $changed = true;
} }
@@ -279,7 +273,7 @@ class RepoCleanup extends CLIApp
continue; continue;
} }
} }
$this->log(" 🗑️ Deleted branch: {$name}"); $this->logMsg(" 🗑️ Deleted branch: {$name}");
$results['branches_deleted']++; $results['branches_deleted']++;
$changed = true; $changed = true;
} }
@@ -312,7 +306,7 @@ class RepoCleanup extends CLIApp
'state' => 'closed', 'state_reason' => 'completed', 'state' => 'closed', 'state_reason' => 'completed',
]); ]);
} }
$this->log(" ✅ Closed issue #{$num} (PR #{$prNum} merged)"); $this->logMsg(" ✅ Closed issue #{$num} (PR #{$prNum} merged)");
$results['issues_closed']++; $results['issues_closed']++;
$changed = true; $changed = true;
} }
@@ -361,7 +355,7 @@ class RepoCleanup extends CLIApp
} }
if ($results['issues_locked'] > 0) { if ($results['issues_locked'] > 0) {
$this->log(" 🔒 Locked {$results['issues_locked']} old closed issue(s)"); $this->logMsg(" 🔒 Locked {$results['issues_locked']} old closed issue(s)");
} }
return $changed; return $changed;
} }
@@ -396,7 +390,7 @@ class RepoCleanup extends CLIApp
'branch' => $defaultBranch, 'branch' => $defaultBranch,
]); ]);
} }
$this->log(" Deleted retired: {$wf} (from {$wfDir})"); $this->logMsg(" Deleted retired: {$wf} (from {$wfDir})");
$results['retired_files']++; $results['retired_files']++;
$changed = true; $changed = true;
} catch (\Exception $e) { } catch (\Exception $e) {
@@ -433,7 +427,7 @@ class RepoCleanup extends CLIApp
} }
} }
if ($results['runs_deleted'] > 0) { if ($results['runs_deleted'] > 0) {
$this->log(" 🔄 Cleaned {$results['runs_deleted']} workflow run(s)"); $this->logMsg(" 🔄 Cleaned {$results['runs_deleted']} workflow run(s)");
} }
return $changed; return $changed;
} }
@@ -441,7 +435,7 @@ class RepoCleanup extends CLIApp
private function cleanOldLogs(string $org, string $repo, array &$results): bool private function cleanOldLogs(string $org, string $repo, array &$results): bool
{ {
$changed = false; $changed = false;
$days = (int) $this->getOption('log-days', '30'); $days = (int) $this->getArgument('--log-days', '30');
$cutoff = date('Y-m-d\TH:i:s\Z', strtotime("-{$days} days")); $cutoff = date('Y-m-d\TH:i:s\Z', strtotime("-{$days} days"));
try { try {
@@ -465,7 +459,7 @@ class RepoCleanup extends CLIApp
} }
if ($results['logs_deleted'] > 0) { if ($results['logs_deleted'] > 0) {
$this->log(" 📋 Cleaned {$results['logs_deleted']} old log(s)"); $this->logMsg(" 📋 Cleaned {$results['logs_deleted']} old log(s)");
} }
return $changed; return $changed;
} }
@@ -475,7 +469,7 @@ class RepoCleanup extends CLIApp
try { try {
$this->api->get("/repos/{$org}/{$repo}/labels/mokostandards"); $this->api->get("/repos/{$org}/{$repo}/labels/mokostandards");
} catch (\Exception $e) { } catch (\Exception $e) {
$this->log(" ⚠️ Missing 'mokostandards' label"); $this->logMsg(" ⚠️ Missing 'mokostandards' label");
$results['labels_missing']++; $results['labels_missing']++;
$this->api->resetCircuitBreaker(); $this->api->resetCircuitBreaker();
} }
@@ -495,7 +489,7 @@ class RepoCleanup extends CLIApp
$mokoContent = base64_decode($mokoFile['content'] ?? ''); $mokoContent = base64_decode($mokoFile['content'] ?? '');
if (preg_match('/standards_version:\s*(\d{2}\.\d{2}\.\d{2})/m', $mokoContent, $vm)) { if (preg_match('/standards_version:\s*(\d{2}\.\d{2}\.\d{2})/m', $mokoContent, $vm)) {
if ($vm[1] !== self::VERSION) { if ($vm[1] !== self::VERSION) {
$this->log(" ⚠️ Standards drift: {$vm[1]} (expected " . self::VERSION . ")"); $this->logMsg(" ⚠️ Standards drift: {$vm[1]} (expected " . self::VERSION . ")");
$results['version_drift']++; $results['version_drift']++;
} }
} }
@@ -510,14 +504,14 @@ class RepoCleanup extends CLIApp
// ─── Helpers ───────────────────────────────────────────────────────── // ─── Helpers ─────────────────────────────────────────────────────────
private function log(string $message): void private function logMsg(string $message): void
{ {
if (!$this->getOption('quiet', false)) { if (!$this->quiet) {
echo $message . "\n"; echo $message . "\n";
} }
} }
private function error(string $message): void private function errorMsg(string $message): void
{ {
fwrite(STDERR, $message . "\n"); fwrite(STDERR, $message . "\n");
} }
+5 -4
View File
@@ -24,9 +24,9 @@ declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../vendor/autoload.php';
use MokoEnterprise\{ApiClient, AuditLogger, CLIApp, Config, PlatformAdapterFactory}; use MokoEnterprise\{ApiClient, AuditLogger, CliFramework, Config, PlatformAdapterFactory};
class JoomlaRelease extends CLIApp class JoomlaRelease extends CliFramework
{ {
private const VERSION = '04.06.00'; private const VERSION = '04.06.00';
private const ORG = 'mokoconsulting-tech'; private const ORG = 'mokoconsulting-tech';
@@ -49,6 +49,7 @@ class JoomlaRelease extends CLIApp
private ApiClient $api; private ApiClient $api;
private AuditLogger $logger; private AuditLogger $logger;
private \MokoEnterprise\GitPlatformAdapter $adapter;
protected function configure(): void protected function configure(): void
{ {
@@ -498,5 +499,5 @@ class JoomlaRelease extends CLIApp
} }
} }
$script = new JoomlaRelease('joomla_release', 'Joomla release pipeline'); $app = new JoomlaRelease();
exit($script->execute()); exit($app->execute());
+2 -2
View File
@@ -261,9 +261,9 @@ class ApiClient
* @throws RateLimitExceeded * @throws RateLimitExceeded
* @throws CircuitBreakerOpen * @throws CircuitBreakerOpen
*/ */
public function delete(string $endpoint): array public function delete(string $endpoint, ?array $body = null): array
{ {
return $this->request('DELETE', $endpoint); return $this->request('DELETE', $endpoint, $body);
} }
/** /**
-4
View File
@@ -16,10 +16,6 @@ parameters:
analyseAndScan: analyseAndScan:
- vendor - vendor
- node_modules (?) - node_modules (?)
# Legacy CLIApp scripts — need migration to CliFramework
- automation/repo_cleanup.php
- automation/push_files.php
- cli/joomla_release.php
reportUnmatchedIgnoredErrors: false reportUnmatchedIgnoredErrors: false
+12 -13
View File
@@ -22,7 +22,7 @@ require_once __DIR__ . '/../../vendor/autoload.php';
require_once __DIR__ . '/../lib/Enterprise/CliFramework.php'; require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoEnterprise\{ use MokoEnterprise\{
CLIApp, CliFramework,
ProjectTypeDetector, ProjectTypeDetector,
PluginFactory, PluginFactory,
PluginRegistry, PluginRegistry,
@@ -36,7 +36,7 @@ use MokoEnterprise\{
* Detects whether a repository is a Joomla/WaaS component, Dolibarr/CRM module, * Detects whether a repository is a Joomla/WaaS component, Dolibarr/CRM module,
* or generic repository, then validates against appropriate schema * or generic repository, then validates against appropriate schema
*/ */
class AutoDetectPlatform extends CLIApp class AutoDetectPlatform extends CliFramework
{ {
private const DETECTION_THRESHOLD = 0.5; // 50% confidence required private const DETECTION_THRESHOLD = 0.5; // 50% confidence required
@@ -62,20 +62,19 @@ class AutoDetectPlatform extends CLIApp
private string $schemaFile = ''; private string $schemaFile = '';
private ?object $detectedPlugin = null; private ?object $detectedPlugin = null;
protected function setupArguments(): array protected function configure(): void
{ {
return [ $this->setDescription('Automatically detect platform type and validate repository');
'repo-path:' => 'Path to repository to analyze (default: current directory)', $this->addArgument('--repo-path', 'Path to repository to analyze', '.');
'schema-dir:' => 'Path to schema definitions directory (default: definitions/default)', $this->addArgument('--schema-dir', 'Path to schema definitions directory', 'definitions/default');
'output-dir:' => 'Directory for output reports (default: var/logs/validation)', $this->addArgument('--output-dir', 'Directory for output reports', 'var/logs/validation');
];
} }
protected function run(): int protected function run(): int
{ {
$repoPath = $this->getOption('repo-path', '.'); $repoPath = $this->getArgument('--repo-path', '.');
$schemaDir = $this->getOption('schema-dir', 'definitions/default'); $schemaDir = $this->getArgument('--schema-dir', 'definitions/default');
$outputDir = $this->getOption('output-dir', 'var/logs/validation'); $outputDir = $this->getArgument('--output-dir', 'var/logs/validation');
// Make paths absolute // Make paths absolute
$repoPath = $this->getAbsolutePath($repoPath); $repoPath = $this->getAbsolutePath($repoPath);
@@ -151,7 +150,7 @@ class AutoDetectPlatform extends CLIApp
} }
// Output results // Output results
if ($this->jsonOutput) { if ($this->getArgument("--json", false)) {
$this->outputJson(); $this->outputJson();
} else { } else {
$this->displayResults(); $this->displayResults();
@@ -953,5 +952,5 @@ class AutoDetectPlatform extends CLIApp
} }
// Run the application // Run the application
$app = new AutoDetectPlatform('auto_detect_platform', 'Automatically detect platform type and validate repository'); $app = new AutoDetectPlatform();
exit($app->execute()); exit($app->execute());
+15 -19
View File
@@ -17,29 +17,24 @@ declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php'; require_once __DIR__ . '/../vendor/autoload.php';
use MokoEnterprise\CLIApp; use MokoEnterprise\CliFramework;
class CheckWikiHealth extends CLIApp class CheckWikiHealth extends CliFramework
{ {
public function __construct() protected function configure(): void
{ {
parent::__construct('check-wiki-health', 'Validate wiki health for a repository', '01.00.00'); $this->setDescription('Validate wiki health for a repository');
} $this->addArgument('--path', 'Repository path (default: current directory)', '.');
$this->addArgument('--gitea-url', 'Gitea base URL', 'https://git.mokoconsulting.tech');
protected function setupArguments(): array $this->addArgument('--token', 'Gitea API token (or set GITEA_TOKEN env var)', '');
{ $this->addArgument('--json', 'Output as JSON', false);
return [
'path:' => 'Repository path (default: current directory)',
'gitea-url:' => 'Gitea base URL (default: https://git.mokoconsulting.tech)',
'token:' => 'Gitea API token (or set GITEA_TOKEN env var)',
];
} }
protected function run(): int protected function run(): int
{ {
$repoPath = realpath($this->getOption('path', '.')) ?: '.'; $repoPath = realpath($this->getArgument('--path', '.')) ?: '.';
$giteaUrl = $this->getOption('gitea-url', 'https://git.mokoconsulting.tech'); $giteaUrl = $this->getArgument('--gitea-url', 'https://git.mokoconsulting.tech');
$token = $this->getOption('token', getenv('GITEA_TOKEN') ?: ''); $token = $this->getArgument('--token', getenv('GITEA_TOKEN') ?: '');
// Detect repo owner/name from git config // Detect repo owner/name from git config
$configFile = $repoPath . '/.git/config'; $configFile = $repoPath . '/.git/config';
@@ -76,7 +71,7 @@ class CheckWikiHealth extends CLIApp
if ($pages === null) { if ($pages === null) {
$this->log(' No wiki found or API error', 'WARNING'); $this->log(' No wiki found or API error', 'WARNING');
$issues++; $issues++;
if ($this->jsonOutput) { if ($this->getArgument("--json", false)) {
echo json_encode(['status' => 'no_wiki', 'issues' => $issues]); echo json_encode(['status' => 'no_wiki', 'issues' => $issues]);
} }
return 0; return 0;
@@ -118,7 +113,7 @@ class CheckWikiHealth extends CLIApp
} }
} }
if ($this->jsonOutput) { if ($this->getArgument("--json", false)) {
echo json_encode([ echo json_encode([
'repo' => "{$owner}/{$repo}", 'repo' => "{$owner}/{$repo}",
'pages' => $pageCount, 'pages' => $pageCount,
@@ -153,4 +148,5 @@ class CheckWikiHealth extends CLIApp
} }
} }
(new CheckWikiHealth())->execute(); $app = new CheckWikiHealth();
exit($app->execute());