Files
Jonathan Miller b491241a58
Universal: Sync Feature Branch Versions / Sync feature branches with dev (push) Has been skipped
Merge branch 'main' into dev
# Conflicts:
#	.mokogitea/CLAUDE.md
#	.mokogitea/ISSUE_TEMPLATE/config.yml
#	.mokogitea/ISSUE_TEMPLATE/documentation.md
#	.mokogitea/ISSUE_TEMPLATE/feature_request.md
#	.mokogitea/ISSUE_TEMPLATE/security.md
#	.mokogitea/branch-protection.yml
#	.mokogitea/bulk-repo-sync.yml
#	.mokogitea/pr-branch-check.yml
#	.mokogitea/renovate.yml
#	.mokogitea/sync-wikis.yml
#	.mokogitea/workflows/auto-bump.yml
#	.mokogitea/workflows/auto-release.yml
#	.mokogitea/workflows/ci-platform.yml
#	.mokogitea/workflows/cleanup.yml
#	.mokogitea/workflows/gitleaks.yml
#	.mokogitea/workflows/issue-branch.yml
#	.mokogitea/workflows/notify.yml
#	.mokogitea/workflows/pre-release.yml
#	.mokogitea/workflows/repo-health.yml
#	.mokogitea/workflows/security-audit.yml
#	.script-registry.json
#	CHANGELOG.md
#	PLUGIN_SCRIPTS.md
#	README.md
#	analysis/index.md
#	automation/bulk_joomla_template.php
#	automation/bulk_sync.php
#	automation/enrich_manifest_xml.php
#	automation/enrich_mokostandards_xml.php
#	automation/index.md
#	automation/migrate_to_gitea.php
#	automation/push_files.php
#	automation/push_manifest_xml.php
#	automation/push_mokostandards_xml.php
#	automation/repo_cleanup.php
#	bin/moko
#	cli/archive_repo.php
#	cli/audit_query.php
#	cli/badge_update.php
#	cli/branch_rename.php
#	cli/bulk_workflow_push.php
#	cli/bulk_workflow_trigger.php
#	cli/changelog_promote.php
#	cli/changelog_prune.php
#	cli/client_dashboard.php
#	cli/client_health_check.php
#	cli/client_inventory.php
#	cli/client_provision.php
#	cli/completion.php
#	cli/create_project.php
#	cli/create_repo.php
#	cli/deploy_joomla.php
#	cli/dev_branch_reset.php
#	cli/grafana_dashboard.php
#	cli/joomla_build.php
#	cli/joomla_compat_check.php
#	cli/joomla_metadata_validate.php
#	cli/joomla_release.php
#	cli/license_manage.php
#	cli/manifest_element.php
#	cli/manifest_licensing.php
#	cli/manifest_read.php
#	cli/package_build.php
#	cli/platform_detect.php
#	cli/release.php
#	cli/release_body_update.php
#	cli/release_cascade.php
#	cli/release_create.php
#	cli/release_manage.php
#	cli/release_mirror.php
#	cli/release_notes.php
#	cli/release_package.php
#	cli/release_promote.php
#	cli/release_publish.php
#	cli/release_validate.php
#	cli/release_verify.php
#	cli/scaffold_client.php
#	cli/sync_rulesets.php
#	cli/theme_lint.php
#	cli/updates_xml_build.php
#	cli/updates_xml_sync.php
#	cli/version_auto_bump.php
#	cli/version_bump.php
#	cli/version_bump_remote.php
#	cli/version_check.php
#	cli/version_read.php
#	cli/version_reset_dev.php
#	cli/version_set_platform.php
#	cli/wiki_sync.php
#	cli/workflow_sync.php
#	composer.json
#	deploy/backup-before-deploy.php
#	deploy/deploy-dolibarr.php
#	deploy/deploy-joomla.php
#	deploy/deploy-sftp.php
#	deploy/health-check.php
#	deploy/rollback-joomla.php
#	deploy/sync-joomla.php
#	fix/fix_line_endings.php
#	fix/fix_permissions.php
#	fix/fix_tabs.php
#	fix/fix_trailing_spaces.php
#	fix/index.md
#	index.md
#	lib/CliBase.php
#	lib/Common.php
#	lib/Enterprise/AbstractProjectPlugin.php
#	lib/Enterprise/ApiClient.php
#	lib/Enterprise/AuditLogger.php
#	lib/Enterprise/CheckpointManager.php
#	lib/Enterprise/CliFramework.php
#	lib/Enterprise/Config.php
#	lib/Enterprise/ConfigValidator.php
#	lib/Enterprise/EnterpriseReadinessValidator.php
#	lib/Enterprise/ErrorRecovery.php
#	lib/Enterprise/FileFixUtility.php
#	lib/Enterprise/GitHubAdapter.php
#	lib/Enterprise/GitPlatformAdapter.php
#	lib/Enterprise/InputValidator.php
#	lib/Enterprise/ManifestParser.php
#	lib/Enterprise/ManifestReader.php
#	lib/Enterprise/MetricsCollector.php
#	lib/Enterprise/MokoGiteaAdapter.php
#	lib/Enterprise/PackageBuilder.php
#	lib/Enterprise/PlatformAdapterFactory.php
#	lib/Enterprise/PluginFactory.php
#	lib/Enterprise/PluginRegistry.php
#	lib/Enterprise/Plugins/ApiPlugin.php
#	lib/Enterprise/Plugins/DocumentationPlugin.php
#	lib/Enterprise/Plugins/DolibarrPlugin.php
#	lib/Enterprise/Plugins/GenericPlugin.php
#	lib/Enterprise/Plugins/JoomlaPlugin.php
#	lib/Enterprise/Plugins/McpServerPlugin.php
#	lib/Enterprise/Plugins/MobilePlugin.php
#	lib/Enterprise/Plugins/NodeJsPlugin.php
#	lib/Enterprise/Plugins/PythonPlugin.php
#	lib/Enterprise/Plugins/TerraformPlugin.php
#	lib/Enterprise/Plugins/WordPressPlugin.php
#	lib/Enterprise/ProjectConfigValidator.php
#	lib/Enterprise/ProjectMetricsCollector.php
#	lib/Enterprise/ProjectPluginInterface.php
#	lib/Enterprise/ProjectTypeDetector.php
#	lib/Enterprise/RecoveryError.php
#	lib/Enterprise/RecoveryManager.php
#	lib/Enterprise/RepositoryHealthChecker.php
#	lib/Enterprise/RepositorySynchronizer.php
#	lib/Enterprise/RetryHelper.php
#	lib/Enterprise/SecurityValidator.php
#	lib/Enterprise/SourceResolver.php
#	lib/Enterprise/SynchronizationException.php
#	lib/Enterprise/TransactionManager.php
#	lib/Enterprise/UnifiedValidation.php
#	lib/index.md
#	lib/plugins/Joomla/UpdateXmlGenerator.php
#	maintenance/index.md
#	maintenance/pin_action_shas.php
#	maintenance/repo_inventory.php
#	maintenance/rotate_secrets.php
#	maintenance/setup_labels.php
#	maintenance/sync_dolibarr_readmes.php
#	maintenance/update_repo_inventory.php
#	maintenance/update_sha_hashes.php
#	maintenance/update_version_from_readme.php
#	mcp/config.example.json
#	mcp/package.json
#	mcp/src/config.ts
#	mcp/src/index.ts
#	mcp/src/runner.ts
#	mcp/src/types.ts
#	phpcs.xml
#	plugin_health_check.php
#	plugin_list.php
#	plugin_metrics.php
#	plugin_readiness.php
#	plugin_validate.php
#	release/generate_dolibarr_version_txt.php
#	release/generate_joomla_update_xml.php
#	src/functions.php
#	templates/configs/README.md
#	templates/configs/index.md
#	templates/configs/manifest.xml.template
#	templates/configs/manifest.yml.template
#	templates/configs/mokostandards.xml.template
#	templates/configs/mokostandards.yml.template
#	templates/configs/phpcs.xml
#	templates/docs/README.md
#	templates/docs/extra/README.md
#	templates/docs/extra/index.md
#	templates/docs/index.md
#	templates/docs/required/GOVERNANCE.md
#	templates/docs/required/README.md
#	templates/docs/required/index.md
#	templates/docs/required/template-CONTRIBUTING.md
#	templates/docs/required/template-README.md
#	templates/docs/required/template-SECURITY.md
#	templates/index.md
#	templates/licenses/README.md
#	templates/licenses/index.md
#	templates/makefiles/README.md
#	templates/mokogitea/CLAUDE.dolibarr.md.template
#	templates/mokogitea/CLAUDE.joomla.md.template
#	templates/mokogitea/CLAUDE.md.template
#	templates/mokogitea/ISSUE_TEMPLATE/config.yml
#	templates/mokogitea/ISSUE_TEMPLATE/documentation.md
#	templates/mokogitea/ISSUE_TEMPLATE/dolibarr_module_id_request.md
#	templates/mokogitea/ISSUE_TEMPLATE/feature_request.md
#	templates/mokogitea/ISSUE_TEMPLATE/security.md
#	templates/mokogitea/README.md
#	templates/mokogitea/copilot-instructions.dolibarr.md.template
#	templates/mokogitea/copilot-instructions.joomla.md.template
#	templates/mokogitea/copilot-instructions.md.template
#	templates/mokogitea/dependabot.yml.template
#	templates/mokogitea/override.tf.template
#	templates/required/README.md
#	templates/schemas/README.md
#	templates/schemas/manifest-schema.xsd
#	templates/schemas/moko-platform-schema.xsd
#	templates/schemas/mokostandards-schema.xsd
#	templates/schemas/schemas/README.md
#	templates/schemas/template-repository-structure.xml
#	templates/scripts/README.md
#	templates/scripts/common/CliBase.template.php
#	templates/scripts/fix/index.md
#	templates/scripts/index.md
#	templates/scripts/release/index.md
#	templates/scripts/release/package_dolibarr.php
#	templates/scripts/release/package_joomla.php
#	templates/scripts/sftp-config/README.md
#	templates/scripts/validate/dolibarr_module.php
#	templates/scripts/validate/index.md
#	templates/scripts/validate/validate_manifest.php
#	templates/scripts/validate/validate_structure.php
#	templates/security/README.md
#	templates/security/index.php
#	templates/stubs/dolibarr.php
#	templates/stubs/joomla.php
#	templates/web/index.php
#	tests/Enterprise/GitPlatformAdapterTest.php
#	tests/Unit/VersionBumpTest.php
#	tests/Unit/VersionReadTest.php
#	tests/index.md
#	tests/test_circuit_breaker_handling.php
#	tests/test_enterprise_libraries.php
#	validate/SECURITY_SCANNING.md
#	validate/auto_detect_platform.php
#	validate/check_changelog.php
#	validate/check_client_theme.php
#	validate/check_composer_deps.php
#	validate/check_dolibarr_module.php
#	validate/check_enterprise_readiness.php
#	validate/check_file_integrity.php
#	validate/check_joomla_manifest.php
#	validate/check_language_structure.php
#	validate/check_license_headers.php
#	validate/check_no_secrets.php
#	validate/check_paths.php
#	validate/check_php_syntax.php
#	validate/check_repo_health.php
#	validate/check_structure.php
#	validate/check_tabs.php
#	validate/check_version_consistency.php
#	validate/check_wiki_health.php
#	validate/check_xml_wellformed.php
#	validate/index.md
#	validate/scan_drift.php
#	wrappers/auto_detect_platform.php
#	wrappers/bulk_sync.php
#	wrappers/check_changelog.php
#	wrappers/check_dolibarr_module.php
#	wrappers/check_enterprise_readiness.php
#	wrappers/check_joomla_manifest.php
#	wrappers/check_language_structure.php
#	wrappers/check_license_headers.php
#	wrappers/check_no_secrets.php
#	wrappers/check_paths.php
#	wrappers/check_php_syntax.php
#	wrappers/check_repo_health.php
#	wrappers/check_structure.php
#	wrappers/check_tabs.php
#	wrappers/check_version_consistency.php
#	wrappers/check_xml_wellformed.php
#	wrappers/deploy_sftp.php
#	wrappers/fix_line_endings.php
#	wrappers/fix_permissions.php
#	wrappers/fix_tabs.php
#	wrappers/fix_trailing_spaces.php
#	wrappers/gen_wrappers.php
#	wrappers/index.md
#	wrappers/pin_action_shas.php
#	wrappers/plugin_health_check.php
#	wrappers/plugin_list.php
#	wrappers/plugin_metrics.php
#	wrappers/plugin_readiness.php
#	wrappers/plugin_validate.php
#	wrappers/scan_drift.php
#	wrappers/setup_labels.php
#	wrappers/sync_dolibarr_readmes.php
#	wrappers/update_sha_hashes.php
#	wrappers/update_version_from_readme.php
2026-06-20 21:43:38 -05:00

754 lines
26 KiB
PHP

#!/usr/bin/env php
<?php
/**
* Copyright (C) 2026 Moko Consulting <hello@mokoconsulting.tech>
*
* This file is part of a Moko Consulting project.
*
* SPDX-License-Identifier: GPL-3.0-or-later
*
* FILE INFORMATION
<<<<<<< HEAD
* DEFGROUP: MokoCLI.Automation
* INGROUP: MokoCLI.Scripts
* REPO: https://git.mokoconsulting.tech/MokoConsulting/mokocli
=======
* DEFGROUP: MokoPlatform.Automation
* INGROUP: MokoPlatform.Scripts
* REPO: https://git.mokoconsulting.tech/MokoConsulting/mokoplatform
>>>>>>> main
* PATH: /automation/push_files.php
* BRIEF: Push one or more specific files to one or more remote repositories
*/
declare(strict_types=1);
require_once __DIR__ . '/../vendor/autoload.php';
require_once __DIR__ . '/../lib/Enterprise/CliFramework.php';
use MokoCli\{
ApiClient,
AuditLogger,
CliFramework,
Config,
GitPlatformAdapter,
MetricsCollector,
PlatformAdapterFactory,
ProjectTypeDetector
};
/**
* Targeted File Push Tool
*
<<<<<<< HEAD
* Pushes one or more specific files from MokoCLI templates to one or
=======
* Pushes one or more specific files from mokoplatform templates to one or
>>>>>>> main
* more remote repositories — without running a full sync.
*
* Files are specified by their destination path as they appear in the target
* repository (e.g., ".github/ISSUE_TEMPLATE/config.yml"). The tool looks up
* the matching source template from the appropriate platform definition.
*
* Files may also be given as "source:destination" pairs to bypass definition
* lookup and push any arbitrary local file.
*
* Usage:
* php push_files.php --files=.github/ISSUE_TEMPLATE/config.yml --repos=MokoCRM
* 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
*/
class PushFiles extends CliFramework
{
public const DEFAULT_ORG = 'MokoConsulting';
public const VERSION = '09.23.00';
private ApiClient $api;
private GitPlatformAdapter $adapter;
private AuditLogger $logger;
private ProjectTypeDetector $typeDetector;
/**
* Setup command-line arguments
*/
protected function configure(): void
{
$this->setDescription('Push files to remote repositories');
$this->addArgument('--org', 'GitHub organization', self::DEFAULT_ORG);
$this->addArgument('--repos', 'Target repos (comma-separated)', '');
$this->addArgument('--files', 'Files to push (comma-separated)', '');
$this->addArgument('--message', 'Custom commit message', '');
$this->addArgument('--branch', 'Target branch for direct pushes', '');
$this->addArgument('--direct', 'Push directly instead of PR', false);
$this->addArgument('--yes', 'Auto-confirm without prompting', false);
$this->addArgument('--no-issue', 'Skip creating tracking issue', false);
}
/**
* Main execution
*/
protected function run(): int
{
<<<<<<< HEAD
$this->log('📦 MokoCLI File Push v' . self::VERSION, 'INFO');
=======
$this->log('📦 mokoplatform File Push v' . self::VERSION, 'INFO');
>>>>>>> main
if (!$this->initializeComponents()) {
return 1;
}
$org = $this->getArgument('--org', self::DEFAULT_ORG);
$reposArg = $this->getArgument('--repos', '');
$filesArg = $this->getArgument('--files', '');
$direct = $this->getArgument('--direct', false);
$autoYes = $this->getArgument('--yes', false);
// Validate required arguments
if (empty($reposArg)) {
$this->log('❌ --repos is required. Specify one or more repository names.', 'ERROR');
$this->log(' Example: --repos=MokoCRM,WaasComponent', 'ERROR');
return 1;
}
if (empty($filesArg)) {
$this->log('❌ --files is required. Specify destination paths or source:destination pairs.', 'ERROR');
$this->log(' Example: --files=.github/ISSUE_TEMPLATE/config.yml', 'ERROR');
return 1;
}
$repos = $this->parseList($reposArg);
$files = $this->parseList($filesArg);
$this->log("Organisation: {$org}", 'INFO');
$this->log('Repositories: ' . implode(', ', $repos), 'INFO');
$this->log('Files: ' . implode(', ', $files), 'INFO');
$this->log('Mode: ' . ($direct ? 'direct commit' : 'pull request'), 'INFO');
// Resolve file mappings for each repo
$this->log("\n🔍 Resolving file mappings...", 'INFO');
$repoFileMaps = $this->buildRepoFileMaps($org, $repos, $files);
if (empty($repoFileMaps)) {
$this->log('❌ No files could be resolved. Check file paths and platform definitions.', 'ERROR');
return 1;
}
// Confirm before proceeding
if (!$autoYes && !$this->confirmPush($repoFileMaps, $direct)) {
$this->log('❌ Cancelled.', 'INFO');
return 0;
}
// Execute pushes
$results = $this->executePushes($org, $repoFileMaps, $direct);
$this->displayResults($results);
if ($results['failed'] > 0 && !isset($this->options['no-issue']) && !$this->dryRun) {
$this->createFailureIssue($org, $results);
}
return $results['failed'] > 0 ? 1 : 0;
}
/**
* Initialize enterprise components
*/
private function initializeComponents(): bool
{
$config = Config::load();
try {
$this->adapter = PlatformAdapterFactory::create($config);
$this->api = $this->adapter->getApiClient();
$this->logger = new AuditLogger('push_files');
$this->typeDetector = new ProjectTypeDetector($this->logger);
$platform = $this->adapter->getPlatformName();
$this->log("✓ Components initialized for platform: {$platform}", 'INFO');
return true;
} catch (\Exception $e) {
$this->log('❌ Failed to initialize: ' . $e->getMessage(), 'ERROR');
return false;
}
}
/**
* Parse a comma- or space-separated list into a clean array
*/
private function parseList(string $input): array
{
return array_values(array_filter(
array_map('trim', preg_split('/[\s,]+/', $input)),
fn($v) => $v !== ''
));
}
/**
* Build per-repo file maps: repo → [ [source, destination], … ]
*
* Each entry in $files is either:
* - "destination/path" → looked up in the platform definition
* - "source/path:destination/path" → used as-is (raw mode)
*
* @param string[] $repos
* @param string[] $files
* @return array<string, list<array{source: string, destination: string}>>
*/
private function buildRepoFileMaps(string $org, array $repos, array $files): array
{
$repoRoot = dirname(__DIR__, 2);
$maps = [];
foreach ($repos as $repo) {
// Detect the repo's platform so we load the right definition
$platform = $this->detectRepoPlatform($org, $repo);
$this->log(" {$repo}: platform = {$platform}", 'INFO');
$resolved = [];
foreach ($files as $fileSpec) {
if (str_contains($fileSpec, ':')) {
// Raw source:destination pair
[$src, $dest] = explode(':', $fileSpec, 2);
} else {
// Same path as source and destination
$src = $fileSpec;
$dest = $fileSpec;
}
$dest = ltrim($dest, '/');
$srcAbs = rtrim($repoRoot, '/') . '/' . ltrim($src, '/');
if (!file_exists($srcAbs)) {
$this->log(" ⚠️ Source not found for {$repo}: {$src}", 'WARN');
continue;
}
$resolved[] = ['source' => $srcAbs, 'destination' => $dest];
$this->log(" ✓ {$dest}", 'INFO');
}
if (!empty($resolved)) {
$maps[$repo] = $resolved;
}
}
return $maps;
}
/**
* Detect platform for a repo via manifest or live detection.
*/
private function detectRepoPlatform(string $org, string $repo): string
{
// Read platform from repo's .mokogitea/manifest.xml via API
try {
$fileInfo = $this->adapter->getFileContents($org, $repo, '.mokogitea/manifest.xml', 'main');
$manifestData = isset($fileInfo['content']) ? base64_decode($fileInfo['content']) : '';
if (!empty($manifestData)) {
$xml = @simplexml_load_string($manifestData);
if ($xml !== false) {
$platform = (string)($xml->governance->platform ?? '');
if (!empty($platform)) {
return $platform;
}
}
}
} catch (\Exception $e) {
// Fall through to local detection
}
// Fall back to live detection
try {
$result = $this->typeDetector->detect('.');
return $result['type'] ?? 'default';
} catch (\Exception $e) {
$this->log(" ⚠️ Could not detect platform for {$repo}, using 'default'", 'WARN');
return 'default';
}
}
/**
* Prompt for confirmation before pushing
*
* @param array<string, list<array{source: string, destination: string}>> $repoFileMaps
*/
private function confirmPush(array $repoFileMaps, bool $direct): bool
{
if ($this->quiet) {
return true;
}
$totalFiles = array_sum(array_map('count', $repoFileMaps));
$totalRepos = count($repoFileMaps);
$mode = $direct ? 'direct commit' : 'PR';
echo "\n";
foreach ($repoFileMaps as $repo => $entries) {
echo " {$repo}:\n";
foreach ($entries as $entry) {
echo " → {$entry['destination']}\n";
}
}
echo "\n";
echo "⚠️ About to push {$totalFiles} file(s) to {$totalRepos} repo(s) via {$mode}.\n";
echo "Continue? [y/N]: ";
$handle = fopen('php://stdin', 'r');
$line = fgets($handle);
if ($handle) {
fclose($handle);
}
return is_string($line) && strtolower(trim($line)) === 'y';
}
/**
* Execute all file pushes
*
* @param array<string, list<array{source: string, destination: string}>> $repoFileMaps
* @return array{total: int, success: int, failed: int, repos: array<string, string>}
*/
private function executePushes(string $org, array $repoFileMaps, bool $direct): array
{
$results = [
'total' => count($repoFileMaps),
'success' => 0,
'failed' => 0,
'repos' => [],
];
$customMessage = $this->getArgument('--message', '');
$targetBranch = $this->getArgument('--branch', '');
foreach ($repoFileMaps as $repo => $entries) {
$this->log("\n[{$repo}] Pushing " . count($entries) . ' file(s)...', 'INFO');
try {
// Resolve the default branch
$repoData = $this->adapter->getRepo($org, $repo);
$defaultBranch = $repoData['default_branch'] ?? 'main';
$branch = $direct
? ($targetBranch ?: $defaultBranch)
: $this->createSyncBranch($org, $repo, $defaultBranch);
$pushed = 0;
foreach ($entries as $entry) {
if ($this->pushSingleFile($org, $repo, $entry['source'], $entry['destination'], $branch, $customMessage)) {
$pushed++;
$this->log(" ✓ {$entry['destination']}", 'INFO');
} else {
$this->log(" ✗ {$entry['destination']}", 'ERROR');
}
}
if ($pushed === 0) {
$results['failed']++;
$results['repos'][$repo] = 'failed';
continue;
}
$prNumber = null;
if (!$direct) {
<<<<<<< HEAD
$prTitle = "chore: push " . count($entries) . " file(s) from MokoCLI";
=======
$prTitle = "chore: push " . count($entries) . " file(s) from mokoplatform";
>>>>>>> main
$prBody = $this->buildPRBody($entries);
$pr = $this->adapter->createPullRequest(
$org,
$repo,
$prTitle,
$branch,
$defaultBranch,
$prBody,
['assignees' => ['jmiller']]
);
$prNumber = $pr['number'] ?? null;
$this->log(" 📋 PR #{$prNumber} created", 'INFO');
$results['repos'][$repo] = "pr#{$prNumber}";
} else {
$results['repos'][$repo] = 'pushed';
}
if (!isset($this->options['no-issue']) && !$this->dryRun) {
$this->createTargetRepoIssue($org, $repo, $entries, $prNumber, $direct ? $branch : null);
}
$results['success']++;
} catch (\Exception $e) {
$this->log(" ✗ {$repo}: " . $e->getMessage(), 'ERROR');
$results['failed']++;
$results['repos'][$repo] = 'failed';
}
}
return $results;
}
/**
* Create a uniquely-named sync branch off the default branch
*/
private function createSyncBranch(string $org, string $repo, string $base): string
{
$branchName = 'moko/push-files-' . date('Ymd-His');
// Resolve the base branch to a commit SHA using the adapter
$sha = $this->adapter->resolveRef($org, $repo, $base);
if (empty($sha)) {
throw new \RuntimeException("Cannot resolve SHA for branch {$base} in {$repo}");
}
$this->api->post("/repos/{$org}/{$repo}/git/refs", [
'ref' => "refs/heads/{$branchName}",
'sha' => $sha,
]);
$this->log(" 🌿 Branch created: {$branchName}", 'INFO');
return $branchName;
}
/**
* Push a single file to a repository branch via the Contents API
*
* @return bool True on success
*/
private function pushSingleFile(
string $org,
string $repo,
string $sourcePath,
string $destPath,
string $branch,
string $customMessage
): bool {
$content = file_get_contents($sourcePath);
if ($content === false) {
$this->log(" ⚠️ Cannot read source: {$sourcePath}", 'WARN');
return false;
}
$message = !empty($customMessage)
? $customMessage
<<<<<<< HEAD
: "chore: update {$destPath} from MokoCLI";
=======
: "chore: update {$destPath} from mokoplatform";
>>>>>>> main
// Fetch existing file SHA (needed for updates)
$existingSha = null;
try {
$existing = $this->adapter->getFileContents($org, $repo, $destPath, $branch);
$existingSha = $existing['sha'] ?? null;
} catch (\Exception $e) {
// File does not exist — create it (no sha needed)
$this->adapter->getApiClient()->resetCircuitBreaker();
}
try {
$this->adapter->createOrUpdateFile(
$org,
$repo,
$destPath,
$content,
$message,
$existingSha,
$branch
);
return true;
} catch (\Exception $e) {
$this->log(" ✗ API error pushing {$destPath}: " . $e->getMessage(), 'ERROR');
return false;
}
}
/**
* Create a tracking issue in the target repository after a successful push.
*
* @param list<array{source: string, destination: string}> $entries
*/
private function createTargetRepoIssue(
string $org,
string $repo,
array $entries,
?int $prNumber,
?string $directBranch
): void {
$now = gmdate('Y-m-d H:i:s') . ' UTC';
$version = self::VERSION;
<<<<<<< HEAD
$source = $this->adapter->getRepoWebUrl($org, 'MokoCLI');
$title = "chore: MokoCLI file push tracking";
=======
$source = $this->adapter->getRepoWebUrl($org, 'mokoplatform');
$title = "chore: mokoplatform file push tracking";
>>>>>>> main
$deliveryLine = $prNumber !== null
? "| **Pull request** | [#{$prNumber}](" . $this->adapter->getPullRequestWebUrl($org, $repo, $prNumber) . ") |"
: "| **Delivery** | Direct commit to `{$directBranch}` |";
$fileRows = implode("\n", array_map(
fn($e) => "- `{$e['destination']}`",
$entries
));
$body = <<<MD
<<<<<<< HEAD
## MokoCLI File Push
One or more files were pushed to this repository from MokoCLI.
=======
## mokoplatform File Push
One or more files were pushed to this repository from mokoplatform.
>>>>>>> main
| Field | Value |
|-------|-------|
| **Pushed** | {$now} |
| **Standards version** | `{$version}` |
{$deliveryLine}
| **Source** | [{$source}]({$source}) |
### Files pushed
{$fileRows}
---
<<<<<<< HEAD
*Generated automatically by [MokoCLI]({$source}) `push_files.php`*
=======
*Generated automatically by [mokoplatform]({$source}) `push_files.php`*
>>>>>>> main
MD;
$body = preg_replace('/^ /m', '', $body);
<<<<<<< HEAD
$labels = ['standards-update', 'MokoCLI', 'type: chore', 'automation'];
=======
$labels = ['standards-update', 'mokoplatform', 'type: chore', 'automation'];
>>>>>>> main
try {
$existing = $this->api->get("/repos/{$org}/{$repo}/issues", [
'labels' => 'standards-update',
'state' => 'all',
'per_page' => 1,
'sort' => 'created',
'direction' => 'desc',
]);
$existing = array_values($existing);
if (!empty($existing) && isset($existing[0]['number'])) {
$num = $existing[0]['number'];
$patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']];
if (($existing[0]['state'] ?? 'open') === 'closed') {
$patch['state'] = 'open';
}
$this->api->patch("/repos/{$org}/{$repo}/issues/{$num}", $patch);
try {
$this->api->post("/repos/{$org}/{$repo}/issues/{$num}/labels", ['labels' => $labels]);
} catch (\Exception $le) {
/* non-fatal */
}
$this->log(" 📋 Tracking issue #{$num} updated in {$repo}", 'INFO');
} else {
$issue = $this->api->post("/repos/{$org}/{$repo}/issues", [
'title' => $title,
'body' => $body,
'labels' => $labels,
'assignees' => ['jmiller'],
]);
$num = $issue['number'] ?? null;
$this->log(" 📋 Tracking issue #{$num} created in {$repo}", 'INFO');
}
// Cross-link: patch the sync PR body to reference the tracking issue
// so GitHub shows it in the PR's Development sidebar.
if ($prNumber !== null && is_int($num)) {
try {
$pr = $this->api->get("/repos/{$org}/{$repo}/pulls/{$prNumber}");
$currentBody = $pr['body'] ?? '';
$ref = "Linked to #{$num}";
if (!str_contains($currentBody, $ref)) {
$this->api->patch("/repos/{$org}/{$repo}/pulls/{$prNumber}", [
'body' => $ref . "\n\n" . $currentBody,
]);
}
} catch (\Exception $le) {
/* non-fatal */
}
}
} catch (\Exception $e) {
$this->log(" ⚠️ Could not create/update tracking issue in {$repo}: " . $e->getMessage(), 'WARN');
}
}
/**
<<<<<<< HEAD
* Create or update a failure issue in MokoCLI when repos fail to receive files.
=======
* Create or update a failure issue in mokoplatform when repos fail to receive files.
>>>>>>> main
* Uses the 'push-failure' label. Reopens a closed issue rather than creating a duplicate.
*/
private function createFailureIssue(string $org, array $results): void
{
$now = gmdate('Y-m-d H:i:s') . ' UTC';
$failed = $results['failed'];
$version = self::VERSION;
$failedRepos = array_keys(array_filter(
$results['repos'] ?? [],
fn($s) => $s === 'failed'
));
$repoList = implode("\n", array_map(fn($r) => "- `{$r}`", $failedRepos));
$fileArgs = $this->getArgument('--files', '');
$title = "fix: push_files failed for {$failed} repo(s) — action required";
$body = <<<MD
## File Push Failure
`push_files.php` v{$version} encountered failures pushing files on {$now}.
### Failed repositories
{$repoList}
### Files that were being pushed
```
{$fileArgs}
```
### Next steps
1. Check the output above for the specific error per repo.
2. Fix the underlying issue (API token, branch permissions, file path, etc.).
3. Re-run: `php automation/push_files.php --org={$org} --repos=<repo> --files=<files> --yes`
4. Close this issue once resolved.
---
*Auto-created by `push_files.php` — close once resolved.*
MD;
$body = preg_replace('/^ /m', '', $body);
try {
<<<<<<< HEAD
$existing = $this->api->get("/repos/{$org}/MokoCLI/issues", [
=======
$existing = $this->api->get("/repos/{$org}/mokoplatform/issues", [
>>>>>>> main
'labels' => 'push-failure',
'state' => 'all',
'per_page' => 1,
'sort' => 'created',
'direction' => 'desc',
]);
$existing = array_values($existing);
if (!empty($existing) && isset($existing[0]['number'])) {
$num = $existing[0]['number'];
$patch = ['title' => $title, 'body' => $body, 'assignees' => ['jmiller']];
if (($existing[0]['state'] ?? 'open') === 'closed') {
$patch['state'] = 'open';
}
<<<<<<< HEAD
$this->api->patch("/repos/{$org}/MokoCLI/issues/{$num}", $patch);
$this->log("🚨 Failure issue #{$num} updated: {$org}/MokoCLI#{$num}", 'WARN');
} else {
$issue = $this->api->post("/repos/{$org}/MokoCLI/issues", [
=======
$this->api->patch("/repos/{$org}/mokoplatform/issues/{$num}", $patch);
$this->log("🚨 Failure issue #{$num} updated: {$org}/mokoplatform#{$num}", 'WARN');
} else {
$issue = $this->api->post("/repos/{$org}/mokoplatform/issues", [
>>>>>>> main
'title' => $title,
'body' => $body,
'labels' => ['push-failure'],
'assignees' => ['jmiller'],
]);
$num = $issue['number'] ?? '?';
<<<<<<< HEAD
$this->log("🚨 Failure issue created: {$org}/MokoCLI#{$num}", 'WARN');
=======
$this->log("🚨 Failure issue created: {$org}/mokoplatform#{$num}", 'WARN');
>>>>>>> main
}
} catch (\Exception $e) {
$this->log("⚠️ Could not create/update failure issue: " . $e->getMessage(), 'WARN');
}
}
/**
* Build a markdown PR body listing every pushed file
*
* @param list<array{source: string, destination: string}> $entries
*/
private function buildPRBody(array $entries): string
{
$now = gmdate('Y-m-d H:i:s') . ' UTC';
<<<<<<< HEAD
$lines = ["## MokoCLI File Push\n", "**Pushed:** {$now}\n", '### Files\n'];
=======
$lines = ["## mokoplatform File Push\n", "**Pushed:** {$now}\n", '### Files\n'];
>>>>>>> main
foreach ($entries as $entry) {
$lines[] = "- `{$entry['destination']}`";
}
<<<<<<< HEAD
$sourceUrl = $this->adapter->getRepoWebUrl(self::DEFAULT_ORG, 'MokoCLI');
$lines[] = "\n---\n*Generated by [MokoCLI]({$sourceUrl}) `push_files.php`*";
=======
$sourceUrl = $this->adapter->getRepoWebUrl(self::DEFAULT_ORG, 'mokoplatform');
$lines[] = "\n---\n*Generated by [mokoplatform]({$sourceUrl}) `push_files.php`*";
>>>>>>> main
return implode("\n", $lines);
}
/**
* Display final results
*
* @param array{total: int, success: int, failed: int, repos: array<string, string>} $results
*/
private function displayResults(array $results): void
{
$this->log("\n" . str_repeat('=', 60), 'INFO');
$this->log('📊 Push Complete', 'INFO');
$this->log(str_repeat('=', 60), 'INFO');
$this->log(sprintf('Total: %d repos', $results['total']), 'INFO');
$this->log(sprintf('Success: %d', $results['success']), 'INFO');
$this->log(sprintf('Failed: %d', $results['failed']), 'INFO');
if ($this->verbose) {
$this->log("\n📋 Details:", 'INFO');
foreach ($results['repos'] as $repo => $outcome) {
$icon = str_starts_with($outcome, 'pr#') || $outcome === 'pushed' ? '✓' : '✗';
$this->log(" {$icon} {$repo}: {$outcome}", 'INFO');
}
}
$this->log(str_repeat('=', 60), 'INFO');
}
}
// Execute if run directly
if (php_sapi_name() === 'cli' && isset($argv[0]) && realpath($argv[0]) === __FILE__) {
$app = new PushFiles();
exit($app->execute());
}