From c170abee7607e854e33be3ac00d1ff96fbd3625b Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sat, 28 Nov 2026 14:54:26 +0000 Subject: [PATCH 1/2] feat: move DocSync GitHub syncing to Data Machine --- README.md | 24 +- assets/js/admin-sync.js | 65 +++-- docs/sync-guide.md | 20 ++ inc/Abilities/SyncAbilities.php | 192 +++++++------ inc/Admin/SettingsPage.php | 62 +++-- inc/Api/Controllers/SyncTriggerController.php | 49 ++-- inc/Core/Assets.php | 62 +++-- inc/Sync/ApplyGitHubFileTask.php | 110 ++++++++ inc/Sync/CronSync.php | 90 +++--- inc/Sync/DataMachineSync.php | 256 ++++++++++++++++++ inc/Sync/RepoSync.php | 210 +++++++------- inc/WPCLI/CLI.php | 14 +- inc/WPCLI/Commands/DocsSyncCommand.php | 58 ++-- .../Commands/ProjectFlowsEnsureCommand.php | 51 ++++ phpstan.neon.dist | 3 + tests/data-machine-sync-smoke.php | 204 ++++++++++++++ tests/stubs/data-machine.stub | 45 +++ 17 files changed, 1132 insertions(+), 383 deletions(-) create mode 100644 inc/Sync/ApplyGitHubFileTask.php create mode 100644 inc/Sync/DataMachineSync.php create mode 100644 inc/WPCLI/Commands/ProjectFlowsEnsureCommand.php create mode 100644 phpstan.neon.dist create mode 100644 tests/data-machine-sync-smoke.php create mode 100644 tests/stubs/data-machine.stub diff --git a/README.md b/README.md index 7284400..de56814 100644 --- a/README.md +++ b/README.md @@ -25,14 +25,14 @@ WordPress (documentation CPT) ## Features -- **GitHub sync** — full and incremental sync via commit SHA comparison +- **GitHub sync** — deterministic Data Machine flows with a legacy commit-SHA sync fallback - **Markdown processing** — GitHub Flavored Markdown with internal link resolution - **Hierarchical organization** — `project` and `project_type` taxonomies with deep URL routing - **REST API** — full CRUD under `docsync/v1` with markdown output for AI agents - **WP-CLI** — `wp docsync docs {list, get, search, sync}` and `wp docsync project {ensure, tree}` - **WP Abilities API** — AI agent capabilities for sync, search, and project inspection - **Orphan cleanup** — docs removed from the repo are automatically deleted -- **Scheduled sync** — configurable WP-Cron intervals (hourly / twice daily / daily) +- **Scheduled sync** — daily Data Machine flows, or configurable WP-Cron intervals in fallback mode - **Admin UI** — settings page with GitHub PAT configuration, connection diagnostics, per-project sync controls - **Theme-agnostic** — works on any WordPress theme. Frontend templates are opt-in. @@ -45,15 +45,23 @@ WordPress (documentation CPT) 1. Upload the `docsync` directory to `wp-content/plugins/` 2. Activate the plugin -3. Go to **Documentation → Settings** and enter your GitHub Personal Access Token -4. Create a project term under **Documentation → Projects**, set its GitHub URL -5. Sync: click "Sync" in the admin, use `wp docsync docs sync --all`, or wait for cron +3. Create a top-level project term under **Documentation → Projects** and set its GitHub URL +4. Activate Data Machine and the `data-machine-github` extension, configure GitHub credentials there if needed, then provision daily sync flows: + + ```bash + wp docsync project flows ensure --dry-run + wp docsync project flows ensure + ``` + +5. To queue an immediate run, click **Sync Now** on the project or use `wp docsync docs sync `. + +Use `--project=` to provision a single project. Re-run the command after changing a project's GitHub URL or docs path. See the [Sync Guide](docs/sync-guide.md#data-machine-sync) for setup and monitoring. If Data Machine or its GitHub handler is unavailable, configure a GitHub PAT under **Documentation → Settings** to use DocSync's legacy WP-Cron sync. ## Configuration ### GitHub PAT -Generate a [Personal Access Token](https://github.com/settings/tokens) with `repo` scope (for private repos) or no scope (for public repos only). Enter it at **Documentation → Settings**. +For the legacy fallback, generate a [Personal Access Token](https://github.com/settings/tokens) with `repo` scope (for private repos) or no scope (for public repos only). Enter it at **Documentation → Settings**. ### Adding a Repository @@ -61,11 +69,11 @@ Generate a [Personal Access Token](https://github.com/settings/tokens) with `rep 2. Create or edit a term 3. Set **GitHub URL** (e.g., `https://github.com/your-org/your-repo`) 4. Set **Docs Path** (default: `docs`) — the directory in the repo containing `.md` files -5. Click **Sync** to pull docs +5. If using Data Machine, run `wp docsync project flows ensure --project=` before clicking **Sync Now** ### Sync Intervals -Configure at **Documentation → Settings**: +Data Machine flows are provisioned on a daily schedule. In legacy WP-Cron mode, configure the interval at **Documentation → Settings**: - **Hourly** — best for actively developed projects - **Twice Daily** — good default - **Daily** — for stable projects diff --git a/assets/js/admin-sync.js b/assets/js/admin-sync.js index 0d0c4ea..28f54ef 100644 --- a/assets/js/admin-sync.js +++ b/assets/js/admin-sync.js @@ -4,6 +4,8 @@ * Handles sync operations via REST API on settings and term edit pages. */ +/* global docSyncAdmin:readonly */ + document.addEventListener( 'DOMContentLoaded', function() { 'use strict'; @@ -22,23 +24,23 @@ document.addEventListener( 'DOMContentLoaded', function() { syncAllStatus.textContent = docSyncAdmin.strings.syncing; syncAllStatus.className = ''; - fetch( docSyncAdmin.restUrl + '/abilities/docsync/sync-docs-batch/run', { + fetch( docSyncAdmin.syncAbilityUrl, { method: 'POST', - headers: headers, - body: JSON.stringify( {} ), + headers, + body: JSON.stringify( { input: {} } ), credentials: 'same-origin', } ) .then( response => response.json() ) .then( data => { syncAllButton.disabled = false; - if ( data.errors && data.errors.length > 0 ) { - syncAllStatus.textContent = 'Synced ' + data.repos_synced + ' repos (' + data.errors.length + ' errors)'; - syncAllStatus.className = 'sync-warning'; - } else { - syncAllStatus.textContent = 'Synced ' + data.repos_synced + ' repos'; - syncAllStatus.className = 'sync-success'; + if ( ! data.success ) { + throw new Error( data.error || data.message || 'Sync failed.' ); } + const summary = data.repos_queued ? 'Queued ' + data.repos_queued + ' Data Machine flows' : 'Synced ' + data.repos_synced + ' repos'; + const errors = data.errors || []; + syncAllStatus.textContent = errors.length ? summary + ': ' + errors.join( '; ' ) : summary; + syncAllStatus.className = errors.length ? 'sync-warning' : 'sync-success'; } ) .catch( error => { syncAllButton.disabled = false; @@ -59,7 +61,7 @@ document.addEventListener( 'DOMContentLoaded', function() { fetch( docSyncAdmin.restUrl + '/sync/test-token', { method: 'GET', - headers: headers, + headers, credentials: 'same-origin', } ) .then( response => response.json() ) @@ -106,36 +108,41 @@ document.addEventListener( 'DOMContentLoaded', function() { } termSyncButton.disabled = true; - if ( termTestButton ) termTestButton.disabled = true; + if ( termTestButton ) { + termTestButton.disabled = true; + } termResults.innerHTML = '' + docSyncAdmin.strings.syncing; - fetch( docSyncAdmin.restUrl + '/abilities/docsync/sync-docs/run', { + fetch( docSyncAdmin.syncAbilityUrl, { method: 'POST', - headers: headers, - body: JSON.stringify( { term_id: parseInt( termId ) } ), + headers, + body: JSON.stringify( { input: { term_id: parseInt( termId, 10 ) } } ), credentials: 'same-origin', } ) .then( response => response.json() ) .then( data => { termSyncButton.disabled = false; - if ( termTestButton ) termTestButton.disabled = false; + if ( termTestButton ) { + termTestButton.disabled = false; + } - if ( data.success ) { + if ( ! data.success ) { + termResults.textContent = docSyncAdmin.strings.error + ' ' + ( data.error || data.message || 'Sync failed.' ); + } else if ( data.queued ) { + termResults.textContent = 'Data Machine sync queued (job ' + data.job_id + ').'; + } else { let html = '
'; html += '

' + docSyncAdmin.strings.success + '

'; html += '

Added: ' + data.added.length + ', Updated: ' + data.updated.length + ', Removed: ' + data.removed.length + (data.renamed.length > 0 ? ', Renamed: ' + data.renamed.length : '') + '

'; html += '
'; termResults.innerHTML = html; - } else if ( data.error ) { - let html = '
'; - html += '

' + docSyncAdmin.strings.error + ' ' + data.error + '

'; - html += '
'; - termResults.innerHTML = html; } } ) .catch( error => { termSyncButton.disabled = false; - if ( termTestButton ) termTestButton.disabled = false; + if ( termTestButton ) { + termTestButton.disabled = false; + } termResults.innerHTML = '
Error: ' + error.message + '
'; } ); } ); @@ -151,19 +158,23 @@ document.addEventListener( 'DOMContentLoaded', function() { } termTestButton.disabled = true; - if ( termSyncButton ) termSyncButton.disabled = true; + if ( termSyncButton ) { + termSyncButton.disabled = true; + } termResults.innerHTML = '' + docSyncAdmin.strings.testingRepo; fetch( docSyncAdmin.restUrl + '/sync/test-repo', { method: 'POST', - headers: headers, + headers, credentials: 'same-origin', body: JSON.stringify( { repo_url: repoUrl } ), } ) .then( response => response.json() ) .then( data => { termTestButton.disabled = false; - if ( termSyncButton ) termSyncButton.disabled = false; + if ( termSyncButton ) { + termSyncButton.disabled = false; + } if ( data.success || data.full_name ) { let html = '
'; @@ -195,7 +206,9 @@ document.addEventListener( 'DOMContentLoaded', function() { } ) .catch( error => { termTestButton.disabled = false; - if ( termSyncButton ) termSyncButton.disabled = false; + if ( termSyncButton ) { + termSyncButton.disabled = false; + } termResults.innerHTML = '
Error: ' + error.message + '
'; } ); } ); diff --git a/docs/sync-guide.md b/docs/sync-guide.md index 8221900..7ab9b1d 100644 --- a/docs/sync-guide.md +++ b/docs/sync-guide.md @@ -8,6 +8,26 @@ For exact request/response shapes and permissions, see the [API Reference](api-r The sync system allows you to automatically import documentation from external repositories, convert Markdown to HTML, and organize content using the project taxonomy. Version 0.2.1 introduces enhanced project-based sync with improved term management and hierarchical subpath support. +## Data Machine sync + +Activate **Data Machine** and **Data Machine GitHub** (`data-machine-github`). Configure GitHub credentials in Data Machine for private repositories or authenticated API limits. DocSync's own PAT is only used by the legacy sync and its diagnostic tools. + +Set `project_github_url` on each top-level `project` term. Set `project_docs_path` to the docs directory (defaults to `docs`), or `.` to fetch from the repository root. Provision the flows with: + +```bash +wp docsync project flows ensure --dry-run +wp docsync project flows ensure +wp docsync project flows ensure --project=my-project +``` + +The `docsync/ensure-sync-flows` ability takes the equivalent optional `project` (slug) and `dry_run` (boolean) inputs. DocSync provisions one **DocSync** pipeline and one daily flow per eligible project, storing the flow ID in `project_dm_flow_id`. Re-run ensure after changing a URL or path to update the existing flow. Changing the source does not automatically purge posts from the previous source. + +The `github` fetch step reads `*.md` files from the default branch. The `docsync_apply_github_file` system task applies additions, edits, and removals without AI. Edits match existing posts by their docs-relative source path within the project, preserving post IDs and URLs. If the configured directory is missing, the fetch step fails rather than reporting a successful sync. + +Use **Sync Now**, `wp docsync docs sync `, or `docsync/sync-docs` to queue a run. Use `wp docsync docs sync --all` for all projects. A queued response means Data Machine accepted the run, not that the documentation has been updated. Check Data Machine's job history for fetch errors, and make sure the site's Action Scheduler queue is running. DocSync updates the project's sync metadata when its apply step runs. + +When both Data Machine and the GitHub handler are available, DocSync disables its `docsync_github_sync` cron event. Provision the flows as part of enabling the extension; projects without a flow will not sync in this mode. Without the integration, DocSync retains its legacy WP-Cron runner, GitHub PAT, and interval settings under **Documentation → Settings**. + ## Key Concepts ### Project Structure diff --git a/inc/Abilities/SyncAbilities.php b/inc/Abilities/SyncAbilities.php index 083986a..0879649 100644 --- a/inc/Abilities/SyncAbilities.php +++ b/inc/Abilities/SyncAbilities.php @@ -8,11 +8,8 @@ namespace DocSync\Abilities; -use DocSync\Sync\RepoSync; use DocSync\Sync\CronSync; -use DocSync\Sync\GitHubClient; -use DocSync\Sync\SyncNotifier; -use DocSync\Core\Project; +use DocSync\Sync\DataMachineSync; if ( ! defined( 'ABSPATH' ) ) { exit; @@ -21,139 +18,140 @@ class SyncAbilities { public static function register(): void { - $pat = get_option( CronSync::OPTION_PAT ); - if ( empty( $pat ) ) { + if ( DataMachineSync::is_available() ) { + wp_register_ability( 'docsync/ensure-sync-flows', array( + 'label' => __( 'Ensure DocSync Flows', 'docsync' ), + 'description' => __( 'Provision daily Data Machine flows for top-level projects with GitHub URLs.', 'docsync' ), + 'category' => 'docsync', + 'input_schema' => array( + 'type' => 'object', + 'properties' => array( + 'project' => array( 'type' => 'string' ), + 'dry_run' => array( 'type' => 'boolean' ), + ), + ), + 'execute_callback' => array( DataMachineSync::class, 'ensure' ), + 'permission_callback' => fn() => current_user_can( 'manage_options' ), + 'meta' => array( 'show_in_rest' => true ), + ) ); + } elseif ( ! get_option( CronSync::OPTION_PAT ) ) { return; } - wp_register_ability( 'docsync/sync-docs', [ + wp_register_ability( 'docsync/sync-docs', array( 'label' => __( 'Sync Documentation', 'docsync' ), 'description' => __( 'Sync documentation from GitHub. Pass term_id for single sync, term_ids for batch, or neither for all syncable terms.', 'docsync' ), 'category' => 'docsync', - 'input_schema' => [ + 'input_schema' => array( 'type' => 'object', - 'properties' => [ - 'term_id' => [ 'type' => 'integer' ], - 'term_ids' => [ + 'properties' => array( + 'term_id' => array( 'type' => 'integer' ), + 'term_ids' => array( 'type' => 'array', - 'items' => [ 'type' => 'integer' ], - ], - ], - ], - 'output_schema' => [ + 'items' => array( 'type' => 'integer' ), + ), + ), + ), + 'output_schema' => array( 'type' => 'object', - 'properties' => [ - 'success' => [ 'type' => 'boolean' ], - 'term_id' => [ 'type' => 'integer' ], - 'repos_synced' => [ 'type' => 'integer' ], - 'total_added' => [ 'type' => 'integer' ], - 'total_updated' => [ 'type' => 'integer' ], - 'total_removed' => [ 'type' => 'integer' ], - 'added' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'updated' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'removed' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'renamed' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'unchanged' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'errors' => [ 'type' => 'array', 'items' => [ 'type' => 'string' ] ], - 'results' => [ 'type' => 'object' ], - 'error' => [ 'type' => 'string' ], - ], - ], - 'execute_callback' => [ self::class, 'sync_callback' ], + 'properties' => array( + 'success' => array( 'type' => 'boolean' ), + 'term_id' => array( 'type' => 'integer' ), + 'queued' => array( 'type' => 'boolean' ), + 'flow_id' => array( 'type' => 'integer' ), + 'job_id' => array( 'type' => 'integer' ), + 'repos_queued' => array( 'type' => 'integer' ), + 'repos_synced' => array( 'type' => 'integer' ), + 'total_added' => array( 'type' => 'integer' ), + 'total_updated' => array( 'type' => 'integer' ), + 'total_removed' => array( 'type' => 'integer' ), + 'added' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'updated' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'removed' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'renamed' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'unchanged' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'errors' => array( + 'type' => 'array', + 'items' => array( 'type' => 'string' ), + ), + 'results' => array( 'type' => 'object' ), + 'error' => array( 'type' => array( 'string', 'null' ) ), + ), + ), + 'execute_callback' => array( self::class, 'sync_callback' ), 'permission_callback' => fn() => current_user_can( 'manage_options' ), - 'meta' => [ 'show_in_rest' => true ], - ] ); + 'meta' => array( 'show_in_rest' => true ), + ) ); } public static function sync_callback( array $input ): array { - $pat = get_option( CronSync::OPTION_PAT ); - if ( empty( $pat ) ) { - return [ - 'success' => false, - 'error' => 'GitHub PAT not configured', - ]; + if ( isset( $input['term_id'] ) ) { + return CronSync::sync_term( (int) $input['term_id'], false ); } - $github = new GitHubClient( $pat ); - $repo_sync = new RepoSync( $github ); - - if ( isset( $input['term_id'] ) ) { - return $repo_sync->sync( $input['term_id'] ); + if ( ! DataMachineSync::is_available() && ! get_option( CronSync::OPTION_PAT ) ) { + return array( + 'success' => false, + 'error' => 'GitHub PAT not configured', + ); } - $term_ids = $input['term_ids'] ?? []; + $term_ids = $input['term_ids'] ?? array(); if ( empty( $term_ids ) ) { - $terms = self::get_syncable_terms(); - $term_ids = wp_list_pluck( $terms, 'term_id' ); + $term_ids = wp_list_pluck( CronSync::get_syncable_terms(), 'term_id' ); } - $notifier = new SyncNotifier(); - $results = []; - + $results = array(); foreach ( $term_ids as $term_id ) { - $result = $repo_sync->sync( $term_id ); - $results[ $term_id ] = $result; - - if ( $result['success'] ) { - $notifier->send( $term_id, $result ); - } + $results[ $term_id ] = CronSync::sync_term( (int) $term_id ); } $total_added = 0; $total_updated = 0; $total_removed = 0; $repos_synced = 0; - $errors = []; + $repos_queued = 0; + $errors = array(); foreach ( $results as $term_id => $result ) { - if ( $result['success'] ) { - $repos_synced++; - $total_added += count( $result['added'] ?? [] ); - $total_updated += count( $result['updated'] ?? [] ); - $total_removed += count( $result['removed'] ?? [] ); + if ( ! empty( $result['queued'] ) ) { + ++$repos_queued; + } elseif ( $result['success'] ) { + ++$repos_synced; + $total_added += count( $result['added'] ?? array() ); + $total_updated += count( $result['updated'] ?? array() ); + $total_removed += count( $result['removed'] ?? array() ); } elseif ( ! empty( $result['error'] ) ) { - $term = get_term( $term_id ); - $name = $term ? $term->name : "Term {$term_id}"; + $term = get_term( $term_id ); + $name = $term instanceof \WP_Term ? $term->name : "Term {$term_id}"; $errors[] = "{$name}: {$result['error']}"; } } - return [ + return array( 'success' => true, 'repos_synced' => $repos_synced, + 'repos_queued' => $repos_queued, 'total_added' => $total_added, 'total_updated' => $total_updated, 'total_removed' => $total_removed, 'errors' => $errors, 'results' => $results, - ]; - } - - private static function get_syncable_terms(): array { - $all_terms = get_terms( [ - 'taxonomy' => Project::TAXONOMY, - 'hide_empty' => false, - ] ); - - if ( is_wp_error( $all_terms ) ) { - return []; - } - - $syncable = []; - - foreach ( $all_terms as $term ) { - if ( Project::get_term_depth( $term ) !== 0 ) { - continue; - } - - $github_url = get_term_meta( $term->term_id, 'project_github_url', true ); - if ( empty( $github_url ) ) { - continue; - } - - $syncable[] = $term; - } - - return $syncable; + ); } } diff --git a/inc/Admin/SettingsPage.php b/inc/Admin/SettingsPage.php index 8fea0c3..90c5bce 100644 --- a/inc/Admin/SettingsPage.php +++ b/inc/Admin/SettingsPage.php @@ -10,15 +10,16 @@ use DocSync\Api\Controllers\SyncTriggerController; use DocSync\Sync\CronSync; +use DocSync\Sync\DataMachineSync; class SettingsPage { - const PAGE_SLUG = 'docsync-settings'; + const PAGE_SLUG = 'docsync-settings'; const OPTION_GROUP = 'docsync_settings'; public static function init(): void { - add_action( 'admin_menu', [ __CLASS__, 'add_menu' ] ); - add_action( 'admin_init', [ __CLASS__, 'register_settings' ] ); + add_action( 'admin_menu', array( __CLASS__, 'add_menu' ) ); + add_action( 'admin_init', array( __CLASS__, 'register_settings' ) ); } /** @@ -31,7 +32,7 @@ public static function add_menu(): void { __( 'Settings', 'docsync' ), 'manage_options', self::PAGE_SLUG, - [ __CLASS__, 'render_page' ] + array( __CLASS__, 'render_page' ) ); } @@ -42,51 +43,51 @@ public static function register_settings(): void { register_setting( self::OPTION_GROUP, CronSync::OPTION_PAT, - [ + array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', - ] + ) ); register_setting( self::OPTION_GROUP, CronSync::OPTION_INTERVAL, - [ + array( 'type' => 'string', 'default' => 'twicedaily', - 'sanitize_callback' => [ __CLASS__, 'sanitize_interval' ], - ] + 'sanitize_callback' => array( __CLASS__, 'sanitize_interval' ), + ) ); register_setting( self::OPTION_GROUP, SyncTriggerController::OPTION_SYNC_TOKEN, - [ + array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', - ] + ) ); register_setting( self::OPTION_GROUP, SyncTriggerController::OPTION_WEBHOOK_SECRET, - [ + array( 'type' => 'string', 'sanitize_callback' => 'sanitize_text_field', - ] + ) ); add_settings_section( 'docsync_github_section', __( 'GitHub Sync', 'docsync' ), - [ __CLASS__, 'render_section' ], + array( __CLASS__, 'render_section' ), self::PAGE_SLUG ); add_settings_field( 'docsync_github_pat', __( 'Personal Access Token', 'docsync' ), - [ __CLASS__, 'render_pat_field' ], + array( __CLASS__, 'render_pat_field' ), self::PAGE_SLUG, 'docsync_github_section' ); @@ -94,7 +95,7 @@ public static function register_settings(): void { add_settings_field( 'docsync_github_test', __( 'Connection Test', 'docsync' ), - [ __CLASS__, 'render_test_field' ], + array( __CLASS__, 'render_test_field' ), self::PAGE_SLUG, 'docsync_github_section' ); @@ -102,7 +103,7 @@ public static function register_settings(): void { add_settings_field( 'docsync_sync_interval', __( 'Sync Interval', 'docsync' ), - [ __CLASS__, 'render_interval_field' ], + array( __CLASS__, 'render_interval_field' ), self::PAGE_SLUG, 'docsync_github_section' ); @@ -111,14 +112,14 @@ public static function register_settings(): void { add_settings_section( 'docsync_sync_trigger_section', __( 'Sync Trigger', 'docsync' ), - [ __CLASS__, 'render_sync_trigger_section' ], + array( __CLASS__, 'render_sync_trigger_section' ), self::PAGE_SLUG ); add_settings_field( 'docsync_sync_token', __( 'Sync Token', 'docsync' ), - [ __CLASS__, 'render_sync_token_field' ], + array( __CLASS__, 'render_sync_token_field' ), self::PAGE_SLUG, 'docsync_sync_trigger_section' ); @@ -126,7 +127,7 @@ public static function register_settings(): void { add_settings_field( 'docsync_webhook_secret', __( 'Webhook Secret', 'docsync' ), - [ __CLASS__, 'render_webhook_secret_field' ], + array( __CLASS__, 'render_webhook_secret_field' ), self::PAGE_SLUG, 'docsync_sync_trigger_section' ); @@ -139,7 +140,7 @@ public static function register_settings(): void { * @return string Sanitized interval. */ public static function sanitize_interval( string $value ): string { - $allowed = [ 'hourly', 'twicedaily', 'daily' ]; + $allowed = array( 'hourly', 'twicedaily', 'daily' ); if ( ! in_array( $value, $allowed, true ) ) { return 'twicedaily'; @@ -166,7 +167,7 @@ public static function render_section(): void { * Render PAT field. */ public static function render_pat_field(): void { - $value = get_option( CronSync::OPTION_PAT, '' ); + $value = get_option( CronSync::OPTION_PAT, '' ); $masked = ! empty( $value ) ? str_repeat( '*', 8 ) . substr( $value, -4 ) : ''; ?> ' . esc_html__( 'Data Machine manages the schedule. Provision project flows with wp docsync project flows ensure.', 'docsync' ) . '

'; + return; + } + + $value = get_option( CronSync::OPTION_INTERVAL, 'twicedaily' ); + $intervals = array( 'hourly' => __( 'Hourly', 'docsync' ), 'twicedaily' => __( 'Twice Daily', 'docsync' ), 'daily' => __( 'Daily', 'docsync' ), - ]; + ); ?> 403 ] + array( 'status' => 403 ) ); } return new WP_Error( 'sync_unauthorized', 'Invalid authentication. Provide a valid Bearer token or GitHub webhook signature.', - [ 'status' => 401 ] + array( 'status' => 401 ) ); } @@ -109,25 +110,31 @@ public static function handle( WP_REST_Request $request ): WP_REST_Response|WP_E return $term; } - $result = CronSync::sync_term( $term->term_id ); + $result = DataMachineSync::is_available() + ? DataMachineSync::run( $term->term_id, true ) + : CronSync::sync_term( $term->term_id ); if ( ! $result['success'] ) { return new WP_Error( 'sync_failed', $result['error'] ?? 'Sync failed', - [ 'status' => 500 ] + array( 'status' => 500 ) ); } - return rest_ensure_response( [ + if ( ! empty( $result['queued'] ) ) { + return new WP_REST_Response( $result + array( 'project' => $term->slug ), 202 ); + } + + return rest_ensure_response( array( 'success' => true, 'project' => $term->slug, 'term_id' => $term->term_id, - 'added' => count( $result['added'] ?? [] ), - 'updated' => count( $result['updated'] ?? [] ), - 'removed' => count( $result['removed'] ?? [] ), - 'unchanged' => count( $result['unchanged'] ?? [] ), - ] ); + 'added' => count( $result['added'] ?? array() ), + 'updated' => count( $result['updated'] ?? array() ), + 'removed' => count( $result['removed'] ?? array() ), + 'unchanged' => count( $result['unchanged'] ?? array() ), + ) ); } /** @@ -165,7 +172,7 @@ private static function resolve_project( WP_REST_Request $request ): \WP_Term|WP return new WP_Error( 'sync_no_project', 'Could not determine which project to sync. Provide "project" (slug), "repo_url", or a GitHub push payload.', - [ 'status' => 400 ] + array( 'status' => 400 ) ); } @@ -182,7 +189,7 @@ private static function find_project_by_slug( string $slug ): \WP_Term|WP_Error return new WP_Error( 'sync_project_not_found', "Project '{$slug}' not found.", - [ 'status' => 404 ] + array( 'status' => 404 ) ); } @@ -192,7 +199,7 @@ private static function find_project_by_slug( string $slug ): \WP_Term|WP_Error return new WP_Error( 'sync_no_github_url', "Project '{$slug}' has no GitHub URL configured.", - [ 'status' => 400 ] + array( 'status' => 400 ) ); } @@ -211,22 +218,22 @@ private static function find_project_by_slug( string $slug ): \WP_Term|WP_Error private static function find_project_by_repo_url( string $repo_url ): \WP_Term|WP_Error { $normalized = self::normalize_github_url( $repo_url ); - $terms = get_terms( [ + $terms = get_terms( array( 'taxonomy' => Project::TAXONOMY, 'hide_empty' => false, - 'meta_query' => [ - [ + 'meta_query' => array( + array( 'key' => 'project_github_url', 'compare' => 'EXISTS', - ], - ], - ] ); + ), + ), + ) ); if ( is_wp_error( $terms ) || empty( $terms ) ) { return new WP_Error( 'sync_project_not_found', 'No projects with GitHub URLs configured.', - [ 'status' => 404 ] + array( 'status' => 404 ) ); } @@ -240,7 +247,7 @@ private static function find_project_by_repo_url( string $repo_url ): \WP_Term|W return new WP_Error( 'sync_project_not_found', "No project found matching repository URL: {$repo_url}", - [ 'status' => 404 ] + array( 'status' => 404 ) ); } diff --git a/inc/Core/Assets.php b/inc/Core/Assets.php index 3d4319e..9d747c6 100644 --- a/inc/Core/Assets.php +++ b/inc/Core/Assets.php @@ -14,8 +14,8 @@ class Assets { * Initialize asset management hooks. */ public static function init() { - add_action( 'wp_enqueue_scripts', [ self::class, 'enqueue_frontend_assets' ] ); - add_action( 'admin_enqueue_scripts', [ self::class, 'enqueue_admin_assets' ] ); + add_action( 'wp_enqueue_scripts', array( self::class, 'enqueue_frontend_assets' ) ); + add_action( 'admin_enqueue_scripts', array( self::class, 'enqueue_admin_assets' ) ); } /** @@ -34,6 +34,11 @@ public static function enqueue_frontend_assets() { self::enqueue_single_assets(); } + private static function asset_version( string $path ): string|false { + $mtime = filemtime( $path ); + return false === $mtime ? false : (string) $mtime; + } + /** * Enqueue design token defaults. * @@ -50,8 +55,8 @@ private static function enqueue_design_tokens() { wp_enqueue_style( 'docsync-tokens', DOCSYNC_URL . 'assets/css/tokens.css', - [], - filemtime( $tokens_path ) + array(), + self::asset_version( $tokens_path ) ); } @@ -71,10 +76,10 @@ private static function enqueue_sync_assets() { return; } - $allowed_screens = [ + $allowed_screens = array( 'documentation_page_docsync-settings', 'edit-project', - ]; + ); if ( ! in_array( $screen->id, $allowed_screens, true ) ) { return; @@ -83,23 +88,24 @@ private static function enqueue_sync_assets() { wp_enqueue_script( 'docsync-sync', DOCSYNC_URL . 'assets/js/admin-sync.js', - [], - filemtime( DOCSYNC_PATH . 'assets/js/admin-sync.js' ), + array(), + self::asset_version( DOCSYNC_PATH . 'assets/js/admin-sync.js' ), true ); - wp_localize_script( 'docsync-sync', 'docSyncAdmin', [ - 'restUrl' => rest_url( 'docsync/v1' ), - 'nonce' => wp_create_nonce( 'wp_rest' ), - 'strings' => [ + wp_localize_script( 'docsync-sync', 'docSyncAdmin', array( + 'restUrl' => rest_url( 'docsync/v1' ), + 'syncAbilityUrl' => rest_url( 'wp-abilities/v1/abilities/docsync/sync-docs/run' ), + 'nonce' => wp_create_nonce( 'wp_rest' ), + 'strings' => array( 'syncing' => __( 'Syncing...', 'docsync' ), 'success' => __( 'Sync complete!', 'docsync' ), 'error' => __( 'Sync failed:', 'docsync' ), 'noRepos' => __( 'No repositories configured for sync.', 'docsync' ), 'testing' => __( 'Testing connection...', 'docsync' ), 'testingRepo' => __( 'Testing repository...', 'docsync' ), - ], - ] ); + ), + ) ); } /** @@ -120,8 +126,8 @@ private static function enqueue_archive_assets() { wp_enqueue_style( 'docsync-archives', DOCSYNC_URL . 'assets/css/archives.css', - [ 'docsync-tokens' ], - filemtime( DOCSYNC_PATH . 'assets/css/archives.css' ) + array( 'docsync-tokens' ), + self::asset_version( DOCSYNC_PATH . 'assets/css/archives.css' ) ); if ( is_post_type_archive( 'documentation' ) ) { @@ -136,20 +142,22 @@ private static function enqueue_search_assets() { wp_enqueue_script( 'docsync-search', DOCSYNC_URL . 'assets/js/docs-search.js', - [], - filemtime( DOCSYNC_PATH . 'assets/js/docs-search.js' ), + array(), + self::asset_version( DOCSYNC_PATH . 'assets/js/docs-search.js' ), true ); - wp_localize_script( 'docsync-search', 'docSyncSearch', [ + wp_localize_script( 'docsync-search', 'docSyncSearch', array( 'restUrl' => rest_url( 'wp/v2/documentation' ), - 'strings' => [ + 'strings' => array( 'loading' => __( 'Searching...', 'docsync' ), 'error' => __( 'Search failed. Please try again.', 'docsync' ), + /* translators: %s: Search query. */ 'noResults' => __( 'No results for "%s"', 'docsync' ), + /* translators: %d: Number of search results. */ 'viewAll' => __( 'View all %d results', 'docsync' ), - ], - ] ); + ), + ) ); } /** @@ -167,8 +175,8 @@ private static function enqueue_single_assets() { wp_enqueue_style( 'docsync-related', DOCSYNC_URL . 'assets/css/related-posts.css', - [ 'docsync-tokens' ], - filemtime( DOCSYNC_PATH . 'assets/css/related-posts.css' ) + array( 'docsync-tokens' ), + self::asset_version( DOCSYNC_PATH . 'assets/css/related-posts.css' ) ); self::enqueue_layout_assets(); @@ -181,8 +189,8 @@ private static function enqueue_layout_assets() { wp_enqueue_style( 'docsync-layout', DOCSYNC_URL . 'assets/css/layout.css', - [ 'docsync-tokens' ], - filemtime( DOCSYNC_PATH . 'assets/css/layout.css' ) + array( 'docsync-tokens' ), + self::asset_version( DOCSYNC_PATH . 'assets/css/layout.css' ) ); } -} \ No newline at end of file +} diff --git a/inc/Sync/ApplyGitHubFileTask.php b/inc/Sync/ApplyGitHubFileTask.php new file mode 100644 index 0000000..e8b3a5c --- /dev/null +++ b/inc/Sync/ApplyGitHubFileTask.php @@ -0,0 +1,110 @@ + 0 ? get_term( $term_id, Project::TAXONOMY ) : null; + if ( ! $term || is_wp_error( $term ) || 0 !== (int) $term->parent ) { + $this->fail_apply( $jobId, 'A top-level DocSync project_term_id is required.' ); + return; + } + + $packets = $params['data_packets'] ?? array(); + if ( array() === $packets ) { + RepoSync::update_sync_status( $term_id, 'success' ); + $this->completeJob( $jobId, array( 'files_synced' => 0 ) ); + return; + } + + RepoSync::update_sync_status( $term_id, 'syncing' ); + $file_sha = ''; + $removal_sha = ''; + $files_synced = 0; + $removed = 0; + + try { + if ( ! is_array( $packets ) ) { + throw new \RuntimeException( 'GitHub data_packets must be an array.' ); + } + foreach ( $packets as $packet ) { + $metadata = $packet['metadata'] ?? array(); + $path = $metadata['github_relative_file_path'] ?? ''; + $change = $metadata['github_change'] ?? ''; + $sha = $metadata['github_commit_sha'] ?? ''; + if ( ! is_string( $path ) || '' === $path || ! is_string( $sha ) || '' === $sha ) { + throw new \RuntimeException( 'GitHub packet is missing its relative file path or commit SHA.' ); + } + + if ( 'removed' === $change ) { + if ( ! RepoSync::delete_by_source_file( $term_id, $path, true ) ) { + throw new \RuntimeException( "Failed to delete documentation: {$path}" ); + } + $removal_sha = $sha; + ++$removed; + continue; + } + + $content = $packet['data']['body'] ?? $packet['data']['content'] ?? null; + if ( ! in_array( $change, array( 'added', 'modified' ), true ) || ! is_string( $content ) ) { + throw new \RuntimeException( "Invalid GitHub change or content for: {$path}" ); + } + + $result = RepoSync::apply_file( $term_id, $path, $content ); + if ( ! $result['success'] ) { + throw new \RuntimeException( $result['error'] ?? "Failed to sync: {$path}" ); + } + $file_sha = $sha; + ++$files_synced; + } + } catch ( \Throwable $error ) { + RepoSync::update_sync_status( $term_id, 'failed', $error->getMessage() ); + $this->fail_apply( $jobId, $error->getMessage() ); + return; + } + + update_term_meta( $term_id, 'project_last_sync_time', time() ); + // Pending removals can belong to an older commit than the fetched files. + update_term_meta( $term_id, 'project_last_sync_sha', '' !== $file_sha ? $file_sha : $removal_sha ); + update_term_meta( $term_id, 'project_files_synced', $files_synced ); + RepoSync::update_sync_status( $term_id, 'success' ); + $this->completeJob( $jobId, array( + 'files_synced' => $files_synced, + 'removed' => $removed, + ) ); + } + + private function fail_apply( int $job_id, string $message ): void { + // SystemTaskStep propagates a child job_status override to its parent. + if ( function_exists( 'datamachine_merge_engine_data' ) ) { + datamachine_merge_engine_data( $job_id, array( 'job_status' => JobStatus::failed( self::TYPE )->toString() ) ); + } + $this->failJob( $job_id, $message ); + } +} diff --git a/inc/Sync/CronSync.php b/inc/Sync/CronSync.php index 3159e7e..80e048a 100644 --- a/inc/Sync/CronSync.php +++ b/inc/Sync/CronSync.php @@ -12,21 +12,29 @@ class CronSync { - const CRON_HOOK = 'docsync_github_sync'; + const CRON_HOOK = 'docsync_github_sync'; const OPTION_INTERVAL = 'docsync_sync_interval'; - const OPTION_PAT = 'docsync_github_pat'; + const OPTION_PAT = 'docsync_github_pat'; public static function init(): void { - add_action( self::CRON_HOOK, [ __CLASS__, 'run' ] ); - add_action( 'admin_init', [ __CLASS__, 'schedule' ] ); - register_deactivation_hook( DOCSYNC_PATH . 'docsync.php', [ __CLASS__, 'unschedule' ] ); + add_action( self::CRON_HOOK, array( __CLASS__, 'run' ) ); + add_action( 'plugins_loaded', array( DataMachineSync::class, 'register_task' ) ); + add_action( 'init', array( __CLASS__, 'reconcile_ownership' ) ); + add_action( 'admin_init', array( __CLASS__, 'schedule' ) ); + register_deactivation_hook( DOCSYNC_PATH . 'docsync.php', array( __CLASS__, 'unschedule' ) ); + } + + public static function reconcile_ownership(): void { + if ( wp_next_scheduled( self::CRON_HOOK ) && DataMachineSync::is_available() ) { + self::unschedule(); + } } /** * Schedule the cron event if not already scheduled. */ public static function schedule(): void { - if ( wp_next_scheduled( self::CRON_HOOK ) ) { + if ( DataMachineSync::is_available() || wp_next_scheduled( self::CRON_HOOK ) ) { return; } @@ -38,10 +46,7 @@ public static function schedule(): void { * Unschedule the cron event. */ public static function unschedule(): void { - $timestamp = wp_next_scheduled( self::CRON_HOOK ); - if ( $timestamp ) { - wp_unschedule_event( $timestamp, self::CRON_HOOK ); - } + wp_clear_scheduled_hook( self::CRON_HOOK ); } /** @@ -51,7 +56,9 @@ public static function unschedule(): void { */ public static function reschedule( string $interval ): void { self::unschedule(); - wp_schedule_event( time(), $interval, self::CRON_HOOK ); + if ( ! DataMachineSync::is_available() ) { + wp_schedule_event( time(), $interval, self::CRON_HOOK ); + } } /** @@ -60,32 +67,41 @@ public static function reschedule( string $interval ): void { * @return array Results for each synced project. */ public static function run(): array { + if ( DataMachineSync::is_available() ) { + self::unschedule(); + return array( + 'success' => true, + 'error' => null, + 'results' => array(), + ); + } + $pat = get_option( self::OPTION_PAT ); if ( empty( $pat ) ) { - return [ + return array( 'success' => false, 'error' => 'GitHub PAT not configured', - 'results' => [], - ]; + 'results' => array(), + ); } $terms = self::get_syncable_terms(); if ( empty( $terms ) ) { - return [ + return array( 'success' => true, 'error' => null, - 'results' => [], - ]; + 'results' => array(), + ); } - $github = new GitHubClient( $pat ); + $github = new GitHubClient( $pat ); $repo_sync = new RepoSync( $github ); - $notifier = new SyncNotifier(); + $notifier = new SyncNotifier(); - $results = []; + $results = array(); foreach ( $terms as $term ) { - $result = $repo_sync->sync( $term->term_id ); + $result = $repo_sync->sync( $term->term_id ); $results[ $term->term_id ] = $result; if ( $result['success'] ) { @@ -93,11 +109,11 @@ public static function run(): array { } } - return [ + return array( 'success' => true, 'error' => null, 'results' => $results, - ]; + ); } /** @@ -106,22 +122,26 @@ public static function run(): array { * @param int $term_id Term ID. * @return array Sync result. */ - public static function sync_term( int $term_id ): array { + public static function sync_term( int $term_id, bool $notify = true ): array { + if ( DataMachineSync::is_available() ) { + return DataMachineSync::run( $term_id ); + } + $pat = get_option( self::OPTION_PAT ); if ( empty( $pat ) ) { - return [ + return array( 'success' => false, 'error' => 'GitHub PAT not configured', - ]; + ); } - $github = new GitHubClient( $pat ); + $github = new GitHubClient( $pat ); $repo_sync = new RepoSync( $github ); - $notifier = new SyncNotifier(); + $notifier = new SyncNotifier(); $result = $repo_sync->sync( $term_id ); - if ( $result['success'] ) { + if ( $notify && $result['success'] ) { $notifier->send( $term_id, $result ); } @@ -134,20 +154,20 @@ public static function sync_term( int $term_id ): array { * * @return array Array of WP_Term objects. */ - private static function get_syncable_terms(): array { - $all_terms = get_terms( [ + public static function get_syncable_terms(): array { + $all_terms = get_terms( array( 'taxonomy' => Project::TAXONOMY, 'hide_empty' => false, - ] ); + ) ); if ( is_wp_error( $all_terms ) ) { - return []; + return array(); } - $syncable = []; + $syncable = array(); foreach ( $all_terms as $term ) { - if ( Project::get_term_depth( $term ) !== 0 ) { + if ( 0 !== (int) $term->parent ) { continue; } diff --git a/inc/Sync/DataMachineSync.php b/inc/Sync/DataMachineSync.php new file mode 100644 index 0000000..af0fe27 --- /dev/null +++ b/inc/Sync/DataMachineSync.php @@ -0,0 +1,256 @@ +getHandler( 'github', 'fetch' ) !== null; + } + + public static function fetch_config( int $term_id ): array|WP_Error { + $url = (string) get_term_meta( $term_id, 'project_github_url', true ); + $repo = GitHubClient::parse_repo_url( $url ); + if ( ! $repo || ! preg_match( '#^[A-Za-z0-9-]+/[A-Za-z0-9_.-]+$#D', $repo['owner'] . '/' . $repo['repo'] ) ) { + return new WP_Error( 'docsync_invalid_repo', 'Invalid GitHub repository URL.' ); + } + + $path = (string) get_term_meta( $term_id, 'project_docs_path', true ); + return array( + 'repo' => $repo['owner'] . '/' . $repo['repo'], + 'branch' => '', + 'file_path' => '.' === $path ? '' : ( '' !== $path ? $path : 'docs' ), + 'file_pattern' => '*.md', + ); + } + + public static function ensure( array $input ): array|WP_Error { + if ( ! self::is_available() ) { + return new WP_Error( 'docsync_dm_unavailable', 'Activate Data Machine and its GitHub extension first.' ); + } + + $slug = $input['project'] ?? ''; + $dry_run = ! empty( $input['dry_run'] ); + $terms = CronSync::get_syncable_terms(); + $projects = array(); + $errors = array(); + + foreach ( $terms as $term ) { + if ( '' !== $slug && $term->slug !== $slug ) { + continue; + } + $config = self::fetch_config( $term->term_id ); + if ( is_wp_error( $config ) ) { + $errors[] = $term->slug . ': ' . $config->get_error_message(); + continue; + } + $projects[] = array( + 'project' => $term->slug, + 'term_id' => (int) $term->term_id, + 'flow_name' => $term->name, + 'flow_id' => (int) get_term_meta( $term->term_id, self::FLOW_META, true ), + 'fetch' => $config, + ); + } + + if ( '' !== $slug && ! $projects && ! $errors ) { + return new WP_Error( 'docsync_project_not_found', 'No top-level project with that slug and a GitHub URL was found.' ); + } + + $pipeline_id = (int) get_option( self::PIPELINE_OPTION ); + $pipeline = $pipeline_id ? ( new Pipelines() )->get_pipeline( $pipeline_id ) : null; + $pipeline_id = $pipeline ? $pipeline_id : 0; + $flows = new Flows(); + + if ( $projects && ! $dry_run && ! $pipeline_id ) { + $created = self::execute( 'create-pipeline', array( + 'pipeline_name' => 'DocSync', + 'steps' => array( array( 'step_type' => 'fetch' ), array( 'step_type' => 'system_task' ) ), + ) ); + if ( is_wp_error( $created ) ) { + return $created; + } + $pipeline_id = (int) $created['pipeline_id']; + update_option( self::PIPELINE_OPTION, $pipeline_id, false ); + } + + foreach ( $projects as &$project ) { + $flow = $project['flow_id'] ? $flows->get_flow( $project['flow_id'] ) : null; + $project['action'] = $flow ? 'update' : 'create'; + if ( $flow && (int) $flow['pipeline_id'] !== $pipeline_id ) { + $errors[] = $project['project'] . ': Stored flow belongs to a different pipeline.'; + $project['action'] = 'failed'; + continue; + } + if ( $dry_run ) { + continue; + } + + $result = self::ensure_project_flow( $pipeline_id, $project, $flow ); + if ( is_wp_error( $result ) ) { + $errors[] = $project['project'] . ': ' . $result->get_error_message(); + $project['action'] = 'failed'; + continue; + } + $project['flow_id'] = $result; + } + unset( $project ); + + return array( + 'success' => ! $errors, + 'dry_run' => $dry_run, + 'pipeline_id' => $pipeline_id, + 'projects' => $projects, + 'errors' => $errors, + ); + } + + private static function ensure_project_flow( int $pipeline_id, array $project, ?array $flow ): int|WP_Error { + $term_id = $project['term_id']; + $settings = array( + 'fetch' => array( + 'handler_slug' => 'github', + 'handler_config' => $project['fetch'], + ), + 'system_task' => array( + 'handler_config' => array( + 'task_type' => ApplyGitHubFileTask::TYPE, + 'params' => array( 'project_term_id' => $term_id ), + ), + ), + ); + + if ( ! $flow ) { + // create-flow takes handler_config for both kinds of step and writes + // the handler-free system task settings to flow_step_settings. + $result = self::execute( 'create-flow', array( + 'pipeline_id' => $pipeline_id, + 'flow_name' => $project['flow_name'], + 'scheduling_config' => array( 'interval' => 'daily' ), + 'step_configs' => $settings, + ) ); + if ( is_wp_error( $result ) ) { + return $result; + } + + $flow_id = (int) $result['flow_id']; + update_term_meta( $term_id, self::FLOW_META, $flow_id ); + return $flow_id; + } + + $step_ids = array_column( $flow['flow_config'], 'flow_step_id', 'step_type' ); + if ( empty( $step_ids['fetch'] ) || empty( $step_ids['system_task'] ) ) { + return new WP_Error( 'docsync_dm_missing_steps', 'The flow is missing the DocSync fetch or system task step.' ); + } + foreach ( $settings as $type => $config ) { + $result = self::execute( 'update-flow-step', array( 'flow_step_id' => $step_ids[ $type ] ) + $config ); + if ( is_wp_error( $result ) ) { + return $result; + } + } + return (int) $flow['flow_id']; + } + + public static function run( int $term_id, bool $webhook = false ): array { + $term = get_term( $term_id, Project::TAXONOMY ); + $flow_id = (int) get_term_meta( $term_id, self::FLOW_META, true ); + if ( ! $term || is_wp_error( $term ) || 0 !== (int) $term->parent || ! $flow_id ) { + return array( + 'success' => false, + 'error' => 'No Data Machine flow provisioned for this project. Run wp docsync project flows ensure first.', + ); + } + + $flow = ( new Flows() )->get_flow( $flow_id ); + $valid = false; + if ( $flow && (int) get_option( self::PIPELINE_OPTION ) === (int) $flow['pipeline_id'] ) { + foreach ( $flow['flow_config'] as $step ) { + $settings = $step['flow_step_settings'] ?? array(); + if ( ( $settings['task_type'] ?? '' ) === ApplyGitHubFileTask::TYPE && (int) ( $settings['params']['project_term_id'] ?? 0 ) === $term_id ) { + $valid = true; + break; + } + } + } + if ( ! $valid ) { + return array( + 'success' => false, + 'error' => 'Invalid DocSync flow mapping. Run wp docsync project flows ensure.', + ); + } + + if ( $webhook ) { + // The authenticated DocSync webhook has no WordPress user. Use Data + // Machine's one-off scheduler hook rather than granting it ability permissions. + $action_id = function_exists( 'as_enqueue_async_action' ) && class_exists( FlowRoutines::class ) + ? as_enqueue_async_action( FlowRoutines::ONE_TIME_HOOK, array( $flow_id ), FlowRoutines::LEGACY_GROUP ) + : 0; + return $action_id + ? array( + 'success' => true, + 'term_id' => $term_id, + 'flow_id' => $flow_id, + 'queued' => true, + ) + : array( + 'success' => false, + 'error' => 'Could not enqueue the Data Machine flow.', + ); + } + + $result = self::execute( 'run-flow', array( 'flow_id' => $flow_id ) ); + if ( is_wp_error( $result ) ) { + return array( + 'success' => false, + 'error' => $result->get_error_message(), + ); + } + if ( empty( $result['job_id'] ) ) { + return array( + 'success' => false, + 'error' => $result['reason'] ?? 'Data Machine did not start a job.', + ); + } + return array( + 'success' => true, + 'term_id' => $term_id, + 'flow_id' => $flow_id, + 'job_id' => (int) $result['job_id'], + 'queued' => true, + ); + } + + private static function execute( string $name, array $input ): array|WP_Error { + $ability = function_exists( 'wp_get_ability' ) ? wp_get_ability( 'datamachine/' . $name ) : null; + if ( ! $ability ) { + return new WP_Error( 'docsync_dm_missing_ability', "Missing Data Machine ability: {$name}." ); + } + $result = $ability->execute( $input ); + if ( is_wp_error( $result ) ) { + return $result; + } + if ( empty( $result['success'] ) ) { + return new WP_Error( 'docsync_dm_ability_failed', $result['error'] ?? "Data Machine {$name} failed." ); + } + return $result; + } +} diff --git a/inc/Sync/RepoSync.php b/inc/Sync/RepoSync.php index 330be12..57e2715 100644 --- a/inc/Sync/RepoSync.php +++ b/inc/Sync/RepoSync.php @@ -25,33 +25,33 @@ public function __construct( GitHubClient $github ) { * @return array Sync results with counts and details. */ public function sync( int $term_id ): array { - $result = [ + $result = array( 'success' => false, 'term_id' => $term_id, - 'added' => [], - 'updated' => [], - 'removed' => [], - 'renamed' => [], - 'unchanged' => [], - 'terms_created' => [], + 'added' => array(), + 'updated' => array(), + 'removed' => array(), + 'renamed' => array(), + 'unchanged' => array(), + 'terms_created' => array(), 'error' => null, 'old_sha' => null, 'new_sha' => null, - ]; + ); - $this->update_sync_status( $term_id, 'syncing' ); + self::update_sync_status( $term_id, 'syncing' ); $github_url = get_term_meta( $term_id, 'project_github_url', true ); if ( empty( $github_url ) ) { $result['error'] = 'No GitHub URL configured'; - $this->update_sync_status( $term_id, 'failed', $result['error'] ); + self::update_sync_status( $term_id, 'failed', $result['error'] ); return $result; } $repo_info = GitHubClient::parse_repo_url( $github_url ); if ( ! $repo_info ) { $result['error'] = 'Invalid GitHub URL format'; - $this->update_sync_status( $term_id, 'failed', $result['error'] ); + self::update_sync_status( $term_id, 'failed', $result['error'] ); return $result; } @@ -66,32 +66,32 @@ public function sync( int $term_id ): array { $new_sha = $this->github->get_latest_commit_sha( $owner, $repo, $branch ); if ( is_wp_error( $new_sha ) ) { $result['error'] = 'GitHub API: ' . $new_sha->get_error_message(); - $this->update_sync_status( $term_id, 'failed', $result['error'] ); + self::update_sync_status( $term_id, 'failed', $result['error'] ); return $result; } if ( ! $new_sha ) { $result['error'] = 'Failed to fetch latest commit from GitHub'; - $this->update_sync_status( $term_id, 'failed', $result['error'] ); + self::update_sync_status( $term_id, 'failed', $result['error'] ); return $result; } $result['new_sha'] = $new_sha; - $old_sha = get_term_meta( $term_id, 'project_last_sync_sha', true ); - $result['old_sha'] = $old_sha ?: null; + $old_sha = get_term_meta( $term_id, 'project_last_sync_sha', true ); + $result['old_sha'] = $old_sha ? $old_sha : null; // Sync repository description to term $description = $this->github->get_repo_description( $owner, $repo ); - if ( $description !== null ) { - wp_update_term( $term_id, Project::TAXONOMY, [ + if ( null !== $description ) { + wp_update_term( $term_id, Project::TAXONOMY, array( 'description' => $description, - ] ); + ) ); } if ( $old_sha === $new_sha ) { $result['success'] = true; - $result['error'] = 'No changes detected'; - $this->update_sync_status( $term_id, 'success' ); + $result['error'] = 'No changes detected'; + self::update_sync_status( $term_id, 'success' ); return $result; } @@ -113,9 +113,9 @@ public function sync( int $term_id ): array { update_term_meta( $term_id, 'project_last_sync_time', time() ); $files_synced = count( $result['added'] ) + count( $result['updated'] ) + count( $result['unchanged'] ); update_term_meta( $term_id, 'project_files_synced', $files_synced ); - $this->update_sync_status( $term_id, 'success' ); + self::update_sync_status( $term_id, 'success' ); } else { - $this->update_sync_status( $term_id, 'failed', $result['error'] ?? 'Unknown error' ); + self::update_sync_status( $term_id, 'failed', $result['error'] ?? 'Unknown error' ); } return $result; @@ -131,26 +131,26 @@ public function sync( int $term_id ): array { * @return array Sync results. */ private function full_sync( int $term_id, string $owner, string $repo, string $sha, string $docs_path = 'docs' ): array { - $result = [ + $result = array( 'success' => true, - 'added' => [], - 'updated' => [], - 'removed' => [], - 'unchanged' => [], - 'terms_created' => [], + 'added' => array(), + 'updated' => array(), + 'removed' => array(), + 'unchanged' => array(), + 'terms_created' => array(), 'error' => null, - ]; + ); - $tree_path = $docs_path === '.' ? '' : $docs_path; - $files = $this->github->get_tree( $owner, $repo, $tree_path, $sha ); + $tree_path = '.' === $docs_path ? '' : $docs_path; + $files = $this->github->get_tree( $owner, $repo, $tree_path, $sha ); if ( empty( $files ) ) { - $path_label = $docs_path === '.' ? 'repository root' : "{$docs_path}/"; - $result['error'] = "No documentation files found in {$path_label} directory"; + $path_label = '.' === $docs_path ? 'repository root' : "{$docs_path}/"; + $result['error'] = "No documentation files found in {$path_label} directory"; $result['success'] = false; return $result; } - $synced_source_files = []; + $synced_source_files = array(); foreach ( $files as $relative_path => $file_info ) { $process_result = $this->process_file( $term_id, $owner, $repo, $relative_path, $sha, $docs_path ); @@ -174,14 +174,14 @@ private function full_sync( int $term_id, string $owner, string $repo, string $s $result['terms_created'] = array_merge( $result['terms_created'], $process_result['terms_created'] ); } } else { - $result['error'] = $process_result['error']; + $result['error'] = $process_result['error']; $result['success'] = false; } } $orphans = $this->find_orphaned_posts( $term_id, $synced_source_files ); foreach ( $orphans as $orphan ) { - if ( $this->delete_post( $orphan['id'] ) ) { + if ( self::delete_post( $orphan['id'] ) ) { $result['removed'][] = $orphan['source_file']; } } @@ -201,19 +201,19 @@ private function full_sync( int $term_id, string $owner, string $repo, string $s * @return array Sync results. */ private function incremental_sync( int $term_id, string $owner, string $repo, string $old_sha, string $new_sha, string $docs_path = 'docs' ): array { - $result = [ + $result = array( 'success' => true, - 'added' => [], - 'updated' => [], - 'removed' => [], - 'renamed' => [], - 'unchanged' => [], - 'terms_created' => [], + 'added' => array(), + 'updated' => array(), + 'removed' => array(), + 'renamed' => array(), + 'unchanged' => array(), + 'terms_created' => array(), 'error' => null, - ]; + ); - $filter_path = $docs_path === '.' ? '' : $docs_path; - $changes = $this->github->compare_commits( $owner, $repo, $old_sha, $new_sha, $filter_path ); + $filter_path = '.' === $docs_path ? '' : $docs_path; + $changes = $this->github->compare_commits( $owner, $repo, $old_sha, $new_sha, $filter_path ); $files_to_process = array_merge( $changes['added'], $changes['modified'] ); @@ -237,18 +237,18 @@ private function incremental_sync( int $term_id, string $owner, string $repo, st $result['terms_created'] = array_merge( $result['terms_created'], $process_result['terms_created'] ); } } else { - $result['error'] = $process_result['error']; + $result['error'] = $process_result['error']; $result['success'] = false; } } foreach ( $changes['removed'] as $relative_path ) { - if ( $this->delete_by_source_file( $term_id, $relative_path ) ) { + if ( self::delete_by_source_file( $term_id, $relative_path ) ) { $result['removed'][] = $relative_path; } } - foreach ( $changes['renamed'] ?? [] as $rename ) { + foreach ( $changes['renamed'] ?? array() as $rename ) { $post_id = SyncManager::find_post_by_source( $rename['previous'], $term_id ); if ( $post_id ) { update_post_meta( $post_id, '_sync_source_file', $rename['new'] ); @@ -256,14 +256,13 @@ private function incremental_sync( int $term_id, string $owner, string $repo, st if ( $process_result['success'] ) { $result['renamed'][] = $rename['new']; } else { - $result['error'] = $process_result['error']; + $result['error'] = $process_result['error']; $result['success'] = false; } } } return $result; - } /** @@ -278,33 +277,37 @@ private function incremental_sync( int $term_id, string $owner, string $repo, st * @return array Process result. */ private function process_file( int $term_id, string $owner, string $repo, string $relative_path, string $ref, string $docs_path = 'docs' ): array { - $result = [ - 'success' => false, - 'action' => null, - 'terms_created' => [], - 'error' => null, - ]; - - $full_path = $docs_path === '.' ? $relative_path : $docs_path . '/' . $relative_path; - $content = $this->github->get_file_content( $owner, $repo, $full_path, $ref ); - - if ( $content === null ) { - $result['error'] = "Failed to fetch file content: {$relative_path}"; - return $result; + $full_path = '.' === $docs_path ? $relative_path : $docs_path . '/' . $relative_path; + $content = $this->github->get_file_content( $owner, $repo, $full_path, $ref ); + + if ( null === $content ) { + return array( + 'success' => false, + 'error' => "Failed to fetch file content: {$relative_path}", + ); } - $title = $this->extract_title( $content ); + return self::apply_file( $term_id, $relative_path, $content ); + } + + /** + * Apply fetched Markdown, using the docs-relative path as its identity. + */ + public static function apply_file( int $term_id, string $relative_path, string $content ): array { + $title = self::extract_title( $content ); if ( ! $title ) { - $result['error'] = "No H1 header found in: {$relative_path}"; - return $result; + return array( + 'success' => false, + 'error' => "No H1 header found in: {$relative_path}", + ); } - $content_body = $this->strip_first_h1( $content ); - $subpath = $this->build_subpath( $relative_path ); - $filesize = strlen( $content ); - $timestamp = gmdate( 'c' ); + $content_body = self::strip_first_h1( $content ); + $subpath = self::build_subpath( $relative_path ); + $filesize = strlen( $content ); + $timestamp = gmdate( 'c' ); - $sync_result = SyncManager::sync_post( + return SyncManager::sync_post( $relative_path, $title, $content_body, @@ -315,15 +318,6 @@ private function process_file( int $term_id, string $owner, string $repo, string '', true ); - - if ( $sync_result['success'] ) { - $result['success'] = true; - $result['action'] = $sync_result['action']; - } else { - $result['error'] = $sync_result['error'] ?? 'Unknown sync error'; - } - - return $result; } /** @@ -332,7 +326,7 @@ private function process_file( int $term_id, string $owner, string $repo, string * @param string $markdown Markdown content. * @return string|null Title or null if not found. */ - private function extract_title( string $markdown ): ?string { + private static function extract_title( string $markdown ): ?string { if ( preg_match( '/^#\s+(.+)/mu', $markdown, $matches ) ) { return trim( $matches[1] ); } @@ -345,7 +339,7 @@ private function extract_title( string $markdown ): ?string { * @param string $markdown Markdown content. * @return string Content without first H1. */ - private function strip_first_h1( string $markdown ): string { + private static function strip_first_h1( string $markdown ): string { return preg_replace( '/^#\s+.+\n*/mu', '', $markdown, 1 ); } @@ -356,14 +350,14 @@ private function strip_first_h1( string $markdown ): string { * @param string $relative_path Relative path (e.g., 'guides/advanced/config.md'). * @return array Subpath array (e.g., ['Guides', 'Advanced']). */ - private function build_subpath( string $relative_path ): array { - $subpath = []; + private static function build_subpath( string $relative_path ): array { + $subpath = array(); $dir_parts = explode( '/', dirname( $relative_path ) ); foreach ( $dir_parts as $part ) { - if ( $part !== '.' && ! empty( $part ) ) { - $clean_part = str_replace( [ '-', '_' ], ' ', $part ); - $subpath[] = mb_convert_case( $clean_part, MB_CASE_TITLE, 'UTF-8' ); + if ( '.' !== $part && ! empty( $part ) ) { + $clean_part = str_replace( array( '-', '_' ), ' ', $part ); + $subpath[] = mb_convert_case( $clean_part, MB_CASE_TITLE, 'UTF-8' ); } } @@ -378,35 +372,35 @@ private function build_subpath( string $relative_path ): array { * @return array Array of orphaned posts with 'id' and 'source_file'. */ private function find_orphaned_posts( int $term_id, array $synced_source_files ): array { - $orphans = []; + $orphans = array(); $term = get_term( $term_id, Project::TAXONOMY ); if ( ! $term || is_wp_error( $term ) ) { return $orphans; } - $posts = get_posts( [ + $posts = get_posts( array( 'post_type' => 'documentation', 'post_status' => 'any', 'posts_per_page' => -1, - 'tax_query' => [ - [ + 'tax_query' => array( + array( 'taxonomy' => Project::TAXONOMY, 'field' => 'term_id', 'terms' => $term_id, 'include_children' => true, - ], - ], - 'fields' => 'ids', - ] ); + ), + ), + 'fields' => 'ids', + ) ); foreach ( $posts as $post_id ) { $source_file = get_post_meta( $post_id, '_sync_source_file', true ); if ( $source_file && ! in_array( $source_file, $synced_source_files, true ) ) { - $orphans[] = [ + $orphans[] = array( 'id' => $post_id, 'source_file' => $source_file, - ]; + ); } } @@ -416,15 +410,13 @@ private function find_orphaned_posts( int $term_id, array $synced_source_files ) /** * Delete a post by its source file path. * - * @param string $source_file Source file path. - * @return bool True if deleted, false otherwise. + * @param int $term_id Project term ID. + * @param string $source_file Source file path. + * @param bool $allow_missing Treat an already-absent post as success on retry. */ - private function delete_by_source_file( int $term_id, string $source_file ): bool { + public static function delete_by_source_file( int $term_id, string $source_file, bool $allow_missing = false ): bool { $post_id = SyncManager::find_post_by_source( $source_file, $term_id ); - if ( $post_id ) { - return $this->delete_post( $post_id ); - } - return false; + return $post_id ? self::delete_post( $post_id ) : $allow_missing; } /** @@ -433,9 +425,9 @@ private function delete_by_source_file( int $term_id, string $source_file ): boo * @param int $post_id Post ID. * @return bool True if deleted, false otherwise. */ - private function delete_post( int $post_id ): bool { + private static function delete_post( int $post_id ): bool { $result = wp_delete_post( $post_id, true ); - return $result !== false && $result !== null; + return false !== $result && null !== $result; } /** @@ -445,11 +437,11 @@ private function delete_post( int $post_id ): bool { * @param string $status Status: 'syncing', 'success', 'failed'. * @param string|null $error Error message if failed. */ - private function update_sync_status( int $term_id, string $status, ?string $error = null ): void { + public static function update_sync_status( int $term_id, string $status, ?string $error = null ): void { update_term_meta( $term_id, 'project_sync_status', $status ); if ( $error ) { update_term_meta( $term_id, 'project_sync_error', $error ); - } elseif ( $status === 'success' ) { + } elseif ( 'success' === $status ) { delete_term_meta( $term_id, 'project_sync_error' ); } } diff --git a/inc/WPCLI/CLI.php b/inc/WPCLI/CLI.php index c373246..d68b1e3 100644 --- a/inc/WPCLI/CLI.php +++ b/inc/WPCLI/CLI.php @@ -7,6 +7,7 @@ use DocSync\WPCLI\Commands\DocsSearchCommand; use DocSync\WPCLI\Commands\DocsSyncCommand; use DocSync\WPCLI\Commands\ProjectEnsureCommand; +use DocSync\WPCLI\Commands\ProjectFlowsEnsureCommand; use DocSync\WPCLI\Commands\ProjectTreeCommand; if ( ! defined( 'ABSPATH' ) ) { @@ -15,11 +16,12 @@ class CLI { public static function register(): void { - \WP_CLI::add_command( 'docsync project ensure', [ ProjectEnsureCommand::class, 'run' ] ); - \WP_CLI::add_command( 'docsync project tree', [ ProjectTreeCommand::class, 'run' ] ); - \WP_CLI::add_command( 'docsync docs sync', [ DocsSyncCommand::class, 'run' ] ); - \WP_CLI::add_command( 'docsync docs list', [ DocsListCommand::class, 'run' ] ); - \WP_CLI::add_command( 'docsync docs get', [ DocsGetCommand::class, 'run' ] ); - \WP_CLI::add_command( 'docsync docs search', [ DocsSearchCommand::class, 'run' ] ); + \WP_CLI::add_command( 'docsync project ensure', array( ProjectEnsureCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync project flows ensure', array( ProjectFlowsEnsureCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync project tree', array( ProjectTreeCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync docs sync', array( DocsSyncCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync docs list', array( DocsListCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync docs get', array( DocsGetCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync docs search', array( DocsSearchCommand::class, 'run' ) ); } } diff --git a/inc/WPCLI/Commands/DocsSyncCommand.php b/inc/WPCLI/Commands/DocsSyncCommand.php index 27b0755..129e287 100644 --- a/inc/WPCLI/Commands/DocsSyncCommand.php +++ b/inc/WPCLI/Commands/DocsSyncCommand.php @@ -29,7 +29,7 @@ class DocsSyncCommand { * : Sync all projects with GitHub URLs configured * * [--force] - * : Force sync even if SHA unchanged + * : Legacy flag; does not reset Data Machine's fetch history. * * [--format=] * : Output format (table, json, yaml) @@ -56,7 +56,7 @@ public static function run( array $args, array $assoc_args ): void { $sync_all = Utils\get_flag_value( $assoc_args, 'all', false ); $format = sanitize_key( $assoc_args['format'] ?? 'table' ); - if ( ! in_array( $format, [ 'table', 'json', 'yaml' ], true ) ) { + if ( ! in_array( $format, array( 'table', 'json', 'yaml' ), true ) ) { WP_CLI::error( '--format must be one of: table, json, yaml' ); } @@ -70,27 +70,32 @@ public static function run( array $args, array $assoc_args ): void { WP_CLI::error( 'Project term ID required (e.g. wp docsync docs sync 123) or use --all' ); } - $force = Utils\get_flag_value( $assoc_args, 'force', false ); - self::sync_single( $term_id, $force, $format ); + self::sync_single( $term_id, $format ); } - private static function sync_single( int $term_id, bool $force, string $format ): void { - $result = CronSync::sync_term( $term_id, $force ); + private static function sync_single( int $term_id, string $format ): void { + $result = CronSync::sync_term( $term_id ); if ( empty( $result['success'] ) ) { WP_CLI::error( $result['error'] ?? 'Sync failed' ); } - $rows = [ - [ + if ( ! empty( $result['queued'] ) ) { + WP_CLI::success( 'Data Machine sync queued.' ); + Utils\format_items( $format, array( $result ), array( 'term_id', 'flow_id', 'job_id' ) ); + return; + } + + $rows = array( + array( 'term_id' => (string) $term_id, - 'added' => (string) count( $result['added'] ?? [] ), - 'updated' => (string) count( $result['updated'] ?? [] ), - 'removed' => (string) count( $result['removed'] ?? [] ), - 'unchanged' => (string) count( $result['unchanged'] ?? [] ), + 'added' => (string) count( $result['added'] ?? array() ), + 'updated' => (string) count( $result['updated'] ?? array() ), + 'removed' => (string) count( $result['removed'] ?? array() ), + 'unchanged' => (string) count( $result['unchanged'] ?? array() ), 'error' => (string) ( $result['error'] ?? '' ), - ], - ]; + ), + ); WP_CLI::success( 'Docs sync complete.' ); Utils\format_items( $format, $rows, array_keys( $rows[0] ) ); @@ -99,33 +104,33 @@ private static function sync_single( int $term_id, bool $force, string $format ) private static function sync_all( string $format ): void { WP_CLI::log( 'Syncing all projects with GitHub URLs...' ); - $result = SyncAbilities::sync_callback( [] ); + $result = SyncAbilities::sync_callback( array() ); if ( empty( $result['success'] ) ) { WP_CLI::error( $result['error'] ?? 'Sync failed' ); } - $rows = []; + $rows = array(); foreach ( $result['results'] as $term_id => $term_result ) { $term = get_term( $term_id ); - $status = $term_result['success'] ? 'OK' : 'FAIL'; + $status = ! empty( $term_result['queued'] ) ? 'QUEUED' : ( $term_result['success'] ? 'OK' : 'FAIL' ); $error = $term_result['error'] ?? ''; // Show inline warning for failed projects if ( ! $term_result['success'] && ! empty( $error ) ) { - $project_name = $term ? $term->name : "term {$term_id}"; + $project_name = $term instanceof \WP_Term ? $term->name : "term {$term_id}"; WP_CLI::warning( "{$project_name}: {$error}" ); } - $rows[] = [ + $rows[] = array( 'term_id' => (string) $term_id, - 'project' => $term ? $term->name : '', - 'added' => (string) count( $term_result['added'] ?? [] ), - 'updated' => (string) count( $term_result['updated'] ?? [] ), - 'removed' => (string) count( $term_result['removed'] ?? [] ), - 'unchanged' => (string) count( $term_result['unchanged'] ?? [] ), + 'project' => $term instanceof \WP_Term ? $term->name : '', + 'added' => (string) count( $term_result['added'] ?? array() ), + 'updated' => (string) count( $term_result['updated'] ?? array() ), + 'removed' => (string) count( $term_result['removed'] ?? array() ), + 'unchanged' => (string) count( $term_result['unchanged'] ?? array() ), 'status' => $status, - ]; + ); } if ( ! empty( $result['errors'] ) ) { @@ -135,7 +140,8 @@ private static function sync_all( string $format ): void { } WP_CLI::success( sprintf( - 'Synced %d repos: %d added, %d updated, %d removed', + 'Queued %d Data Machine flows; synced %d repos directly: %d added, %d updated, %d removed', + $result['repos_queued'], $result['repos_synced'], $result['total_added'], $result['total_updated'], diff --git a/inc/WPCLI/Commands/ProjectFlowsEnsureCommand.php b/inc/WPCLI/Commands/ProjectFlowsEnsureCommand.php new file mode 100644 index 0000000..c1d393d --- /dev/null +++ b/inc/WPCLI/Commands/ProjectFlowsEnsureCommand.php @@ -0,0 +1,51 @@ +] + * : Only provision the given top-level project. + * + * [--dry-run] + * : Show the planned flow configuration without saving changes. + */ + public static function run( array $args, array $assoc_args ): void { + $result = DataMachineSync::ensure( array( + 'project' => $assoc_args['project'] ?? '', + 'dry_run' => Utils\get_flag_value( $assoc_args, 'dry-run', false ), + ) ); + if ( is_wp_error( $result ) ) { + WP_CLI::error( $result->get_error_message() ); + return; + } + + foreach ( $result['projects'] as $project ) { + WP_CLI::log( sprintf( + '%s: %s flow %s (%s, path: %s)', + $project['project'], + $project['action'], + $project['flow_id'] ? $project['flow_id'] : '(new)', + $project['fetch']['repo'], + '' !== $project['fetch']['file_path'] ? $project['fetch']['file_path'] : '(repo root)' + ) ); + } + foreach ( $result['errors'] as $error ) { + WP_CLI::warning( $error ); + } + if ( ! $result['success'] ) { + WP_CLI::error( 'Could not ensure all requested flows.' ); + } + WP_CLI::success( $result['dry_run'] ? 'Dry run complete; no changes saved.' : 'DocSync flows ensured.' ); + } +} diff --git a/phpstan.neon.dist b/phpstan.neon.dist new file mode 100644 index 0000000..f178b82 --- /dev/null +++ b/phpstan.neon.dist @@ -0,0 +1,3 @@ +parameters: + scanFiles: + - tests/stubs/data-machine.stub diff --git a/tests/data-machine-sync-smoke.php b/tests/data-machine-sync-smoke.php new file mode 100644 index 0000000..afdc098 --- /dev/null +++ b/tests/data-machine-sync-smoke.php @@ -0,0 +1,204 @@ +result = [ 'success' => true ] + $data; + } + protected function failJob( int $jobId, string $message ): void { + $this->result = [ 'success' => false, 'error' => $message ]; + } + } +} + +namespace DataMachine\Abilities { + class HandlerAbilities { + public static bool $github = false; + public function getHandler( string $slug, string $type ): ?array { + return self::$github && $slug === 'github' && $type === 'fetch' ? [ 'slug' => $slug ] : null; + } + } +} + +namespace DataMachine\Core\Database\Flows { + class Flows { + public function get_flow( int $id ): ?array { + return $GLOBALS['flows'][ $id ] ?? null; + } + } +} + +namespace DataMachine\Core\Database\Pipelines { + class Pipelines { + public function get_pipeline( int $id ): ?array { + return $GLOBALS['pipelines'][ $id ] ?? null; + } + } +} + +namespace { + use DataMachine\Abilities\HandlerAbilities; + use DocSync\Sync\ApplyGitHubFileTask; + use DocSync\Sync\CronSync; + use DocSync\Sync\DataMachineSync; + + define( 'ABSPATH', __DIR__ ); + require dirname( __DIR__ ) . '/vendor/autoload.php'; + + class WP_Error { + public function __construct( public string $code, public string $message ) {} + public function get_error_message(): string { + return $this->message; + } + } + + function check( bool $condition, string $message ): void { + if ( ! $condition ) { + throw new RuntimeException( $message ); + } + } + + function add_filter( $hook, $callback ): void { $GLOBALS['filters'][ $hook ] = $callback; } + function is_wp_error( $value ): bool { return $value instanceof WP_Error; } + function get_term( $id, $taxonomy ) { return $GLOBALS['terms'][ $id ] ?? null; } + function get_term_meta( $id, $key, $single ) { return $GLOBALS['term_meta'][ $id ][ $key ] ?? ''; } + function update_term_meta( $id, $key, $value ): void { $GLOBALS['term_meta'][ $id ][ $key ] = $value; } + function delete_term_meta( $id, $key ): void { unset( $GLOBALS['term_meta'][ $id ][ $key ] ); } + function get_option( $name, $default = false ) { return $GLOBALS['options'][ $name ] ?? $default; } + function update_option( $name, $value, $autoload ): void { $GLOBALS['options'][ $name ] = $value; } + function wp_next_scheduled( $hook ) { return $GLOBALS['cron'][ $hook ] ?? false; } + function wp_schedule_event( $time, $interval, $hook ): void { $GLOBALS['cron'][ $hook ] = $time; } + function wp_clear_scheduled_hook( $hook ): void { unset( $GLOBALS['cron'][ $hook ] ); } + function wp_strip_all_tags( $html ): string { return strip_tags( $html ); } + function wp_trim_words( $text, $count, $suffix ): string { return trim( $text ); } + function sanitize_title( $text ): string { return str_replace( ' ', '-', strtolower( $text ) ); } + function get_terms( $args ): array { + return array_values( array_filter( $GLOBALS['terms'], fn( $term ) => ! isset( $args['parent'] ) || $args['parent'] === $term->parent ) ); + } + function wp_insert_term( $name, $taxonomy, $args ): array { + $id = count( $GLOBALS['terms'] ) + 1; + $GLOBALS['terms'][ $id ] = (object) [ 'term_id' => $id, 'name' => $name, 'parent' => $args['parent'], 'slug' => $args['slug'] ]; + return [ 'term_id' => $id ]; + } + function wp_insert_post( $post, $error ): int { + $id = count( $GLOBALS['posts'] ) + 1; + $GLOBALS['posts'][ $id ] = (object) ( $post + [ 'ID' => $id, 'post_name' => sanitize_title( $post['post_title'] ) ] ); + return $id; + } + function wp_update_post( $post, $error ): int { + $id = $post['ID']; + $GLOBALS['posts'][ $id ] = (object) ( $post + (array) $GLOBALS['posts'][ $id ] ); + return $id; + } + function wp_set_object_terms( $id, $term_id, $taxonomy ): void { $GLOBALS['post_terms'][ $id ] = $term_id; } + function get_post_meta( $id, $key, $single ) { return $GLOBALS['post_meta'][ $id ][ $key ] ?? ''; } + function update_post_meta( $id, $key, $value ): void { $GLOBALS['post_meta'][ $id ][ $key ] = $value; } + function wp_delete_post( $id, $force ) { + $post = $GLOBALS['posts'][ $id ] ?? null; + unset( $GLOBALS['posts'][ $id ] ); + return $post; + } + function get_posts( $query ): array { + return array_values( array_filter( $GLOBALS['posts'], function ( $post ) use ( $query ) { + $term_id = $GLOBALS['post_terms'][ $post->ID ]; + while ( $term_id && $term_id !== $query['tax_query'][0]['terms'] ) { + $term_id = $GLOBALS['terms'][ $term_id ]->parent; + } + return $term_id && get_post_meta( $post->ID, '_sync_source_file', true ) === $query['meta_query'][0]['value']; + } ) ); + } + + function wp_get_ability( string $name ): object { + return new class( $name ) { + public function __construct( private string $name ) {} + public function execute( array $input ): array { + $GLOBALS['calls'][] = [ $this->name, $input ]; + switch ( $this->name ) { + case 'datamachine/create-pipeline': + $GLOBALS['pipelines'][10] = $input; + return [ 'success' => true, 'pipeline_id' => 10 ]; + case 'datamachine/create-flow': + $GLOBALS['flows'][20] = $input + [ 'flow_id' => 20, 'flow_config' => [ + [ 'flow_step_id' => 'fetch-20', 'step_type' => 'fetch' ], + [ 'flow_step_id' => 'task-20', 'step_type' => 'system_task', 'flow_step_settings' => $input['step_configs']['system_task']['handler_config'] ], + ] ]; + return [ 'success' => true, 'flow_id' => 20 ]; + case 'datamachine/update-flow-step': + return [ 'success' => true ]; + case 'datamachine/run-flow': + check( $input === [ 'flow_id' => 20 ], 'Wrong flow triggered.' ); + return [ 'success' => true, 'job_id' => 30 ]; + default: + throw new RuntimeException( 'Unexpected ability: ' . $this->name ); + } + } + }; + } + + function apply_packet( string $change, string $sha, string $body, int $term = 1 ): array { + $task = new ApplyGitHubFileTask(); + $task->executeTask( 100, [ + 'project_term_id' => $term, + 'data_packets' => [ [ + 'data' => [ 'body' => $body ], + 'metadata' => [ 'github_change' => $change, 'github_commit_sha' => $sha, 'github_relative_file_path' => 'quick-start/install.md' ], + ] ], + ] ); + return $task->result; + } + + $GLOBALS['terms'] = [ + 1 => (object) [ 'term_id' => 1, 'parent' => 0, 'slug' => 'example', 'name' => 'Example' ], + 2 => (object) [ 'term_id' => 2, 'parent' => 0, 'slug' => 'other', 'name' => 'Other' ], + ]; + $GLOBALS['posts'] = []; + $GLOBALS['calls'] = []; + update_term_meta( 1, 'project_github_url', 'https://github.com/org/example.git' ); + check( DataMachineSync::fetch_config( 1 ) === [ 'repo' => 'org/example', 'branch' => '', 'file_path' => 'docs', 'file_pattern' => '*.md' ], 'Incorrect default fetch config.' ); + + CronSync::schedule(); + check( wp_next_scheduled( CronSync::CRON_HOOK ) !== false, 'The legacy runner should be scheduled without the handler.' ); + check( CronSync::run()['error'] === 'GitHub PAT not configured', 'Legacy cron should still run.' ); + DataMachineSync::register_task(); + $tasks = ( $GLOBALS['filters']['datamachine_tasks'] )( [] ); + $task = new $tasks['docsync_apply_github_file'](); + check( $task->needsPipelineContext() && ! $task->requiresAgentContext(), 'Task should use fetch packets without an agent.' ); + + HandlerAbilities::$github = true; + CronSync::reconcile_ownership(); + CronSync::schedule(); + CronSync::reschedule( 'daily' ); + check( wp_next_scheduled( CronSync::CRON_HOOK ) === false, 'Data Machine should disable legacy cron.' ); + wp_schedule_event( time(), 'daily', CronSync::CRON_HOOK ); + check( CronSync::run()['success'] && wp_next_scheduled( CronSync::CRON_HOOK ) === false, 'A stale legacy event should exit and unschedule itself.' ); + check( ! CronSync::sync_term( 1 )['success'], 'An unprovisioned project must not fall back to a second owner.' ); + + $plan = DataMachineSync::ensure( [ 'project' => 'example', 'dry_run' => true ] ); + check( $plan['projects'][0]['action'] === 'create' && $GLOBALS['calls'] === [], 'Dry run made changes.' ); + $provisioned = DataMachineSync::ensure( [] ); + check( $provisioned['success'] && get_term_meta( 1, 'project_dm_flow_id', true ) === 20, 'Flow was not provisioned.' ); + check( $GLOBALS['pipelines'][10]['steps'] === [ [ 'step_type' => 'fetch' ], [ 'step_type' => 'system_task' ] ], 'Wrong pipeline steps.' ); + check( $GLOBALS['flows'][20]['scheduling_config']['interval'] === 'daily', 'Flow should run daily.' ); + update_term_meta( 1, 'project_docs_path', '.' ); + update_term_meta( 1, 'project_github_url', 'https://github.com/org/moved' ); + check( DataMachineSync::ensure( [] )['success'], 'Re-ensuring the flow failed.' ); + check( count( $GLOBALS['calls'] ) === 4 && $GLOBALS['calls'][2][0] === 'datamachine/update-flow-step', 'Re-ensuring should update both steps, not recreate the flow.' ); + check( $GLOBALS['calls'][2][1]['handler_config']['file_path'] === '' && $GLOBALS['calls'][2][1]['handler_config']['repo'] === 'org/moved', 'New URL and root path were not applied.' ); + check( CronSync::sync_term( 1 )['job_id'] === 30, 'Manual sync should start the provisioned flow.' ); + + check( apply_packet( 'added', 'sha1', "# First title\n\nFirst body" )['success'], 'Add failed.' ); + check( $GLOBALS['posts'][1]->post_title === 'First title' && trim( $GLOBALS['posts'][1]->post_content ) === '

First body

', 'Title extraction or body conversion failed.' ); + check( $GLOBALS['terms'][ $GLOBALS['post_terms'][1] ]->name === 'Quick Start', 'Subpath was not resolved.' ); + check( get_post_meta( 1, '_sync_source_file', true ) === 'quick-start/install.md', 'Incorrect source file identity.' ); + check( apply_packet( 'added', 'other', "# Other project\n\nOther body", 2 )['success'], 'Second project add failed.' ); + check( apply_packet( 'modified', 'sha2', "# New title\n\nNew body" )['success'], 'Modify failed.' ); + check( count( $GLOBALS['posts'] ) === 2 && $GLOBALS['posts'][1]->post_title === 'New title' && $GLOBALS['posts'][1]->post_name === 'first-title', 'Modified file changed the post ID or slug.' ); + check( ! apply_packet( 'modified', 'bad-sha', 'Missing H1' )['success'], 'Invalid markdown should fail the job.' ); + check( get_term_meta( 1, 'project_sync_status', true ) === 'failed' && get_term_meta( 1, 'project_last_sync_sha', true ) === 'sha2', 'A failed apply advanced the sync SHA.' ); + check( apply_packet( 'removed', 'sha3', '' )['success'] && ! isset( $GLOBALS['posts'][1] ) && isset( $GLOBALS['posts'][2] ), 'Removal did not respect the project boundary.' ); + check( get_term_meta( 1, 'project_sync_status', true ) === 'success' && get_term_meta( 1, 'project_last_sync_sha', true ) === 'sha3' && get_term_meta( 1, 'project_last_sync_time', true ) > 0, 'Missing success metadata.' ); + + echo "Data Machine sync smoke test passed.\n"; +} diff --git a/tests/stubs/data-machine.stub b/tests/stubs/data-machine.stub new file mode 100644 index 0000000..b3c08b1 --- /dev/null +++ b/tests/stubs/data-machine.stub @@ -0,0 +1,45 @@ + Date: Sat, 28 Nov 2026 15:47:56 +0000 Subject: [PATCH 2/2] refactor!: remove DocSync's legacy GitHub sync engine Data Machine with data-machine-github is now the only sync engine. CronSync and GitHubClient are deleted, RepoSync keeps only per-file apply/delete, the PAT/interval settings and the test-token, test-repo, sync/doc and sync/batch routes are removed. A one-time upgrade moves the PAT into Data Machine's GitHub auth and clears the old options and cron. The content layer still loads without Data Machine; only sync needs it. --- docsync.php | 63 ++- inc/Abilities/Abilities.php | 1 - inc/Abilities/SyncAbilities.php | 135 ++----- inc/Admin/SettingsPage.php | 163 +------- inc/Api/Controllers/SyncController.php | 174 -------- inc/Api/Controllers/SyncTriggerController.php | 64 +-- inc/Api/Routes.php | 110 +---- inc/Sync/ApplyGitHubFileTask.php | 19 +- inc/Sync/CronSync.php | 202 ---------- inc/Sync/DataMachineSync.php | 42 +- inc/Sync/GitHubClient.php | 381 ------------------ inc/Sync/RepoSync.php | 330 +-------------- inc/Sync/SyncNotifier.php | 17 +- inc/Sync/SyncUpgrade.php | 45 +++ inc/WPCLI/CLI.php | 8 +- inc/WPCLI/Commands/DocsSyncCommand.php | 127 +----- 16 files changed, 199 insertions(+), 1682 deletions(-) delete mode 100644 inc/Sync/CronSync.php delete mode 100644 inc/Sync/GitHubClient.php create mode 100644 inc/Sync/SyncUpgrade.php diff --git a/docsync.php b/docsync.php index b61458e..15651cb 100644 --- a/docsync.php +++ b/docsync.php @@ -10,6 +10,7 @@ * Text Domain: docsync * Requires at least: 6.9 * Requires PHP: 8.0 + * Requires Plugins: data-machine, data-machine-github */ // Prevent direct access @@ -40,7 +41,14 @@ use DocSync\Templates\Homepage; use DocSync\Templates\SearchBar; use DocSync\Templates\TableOfContents; -use DocSync\Sync\CronSync; +use DataMachine\Core\Database\Flows\Flows; +use DataMachine\Core\Database\Pipelines\Pipelines; +use DataMachine\Engine\AI\System\Tasks\SystemTask; +use DataMachine\Engine\Scheduling\FlowRoutines; +use DataMachineGitHub\Handlers\GitHub\GitHubFetch; +use DocSync\Sync\DataMachineSync; +use DocSync\Sync\SyncUpgrade; +use DocSync\Abilities\SyncAbilities; use DocSync\Sync\SyncNotifier; use DocSync\Admin\SettingsPage; use DocSync\Admin\ProjectColumns; @@ -57,8 +65,6 @@ ProjectColumns::init(); } ); -CronSync::init(); -SyncNotifier::init(); SettingsPage::init(); DocumentationColumns::init(); @@ -117,41 +123,34 @@ return $post_types; } ); -register_activation_hook( __FILE__, function() { - docsync_maybe_migrate_options(); - flush_rewrite_rules(); -} ); - /** - * Migrate options from the old chubes_docs_ prefix to docsync_ prefix. - * - * Runs on activation. Safe to call multiple times — only migrates - * if old options exist and new ones don't. + * Sync layer — Data Machine owns scheduling, fetch and job history. * - * @since 0.1.0 + * The content layer above works without it; syncing does not exist without it. */ -function docsync_maybe_migrate_options() { - $migrations = [ - 'chubes_docs_github_pat' => 'docsync_github_pat', - 'chubes_docs_sync_interval' => 'docsync_sync_interval', - ]; - - foreach ( $migrations as $old_key => $new_key ) { - $old_value = get_option( $old_key ); - if ( $old_value !== false && get_option( $new_key ) === false ) { - update_option( $new_key, $old_value ); - delete_option( $old_key ); - } +add_action( 'plugins_loaded', static function (): void { + if ( ! class_exists( SystemTask::class ) || ! class_exists( Flows::class ) || ! class_exists( Pipelines::class ) || ! class_exists( FlowRoutines::class ) || ! class_exists( GitHubFetch::class ) ) { + add_action( 'admin_notices', static function (): void { + echo '

' . esc_html__( 'DocSync sync requires Data Machine and Data Machine GitHub to be active.', 'docsync' ) . '

'; + } ); + return; } - // Migrate cron hook. - $old_hook = 'chubes_docs_github_sync'; - $new_hook = 'docsync_github_sync'; - $old_next = wp_next_scheduled( $old_hook ); - if ( $old_next ) { - wp_unschedule_event( $old_next, $old_hook ); + DataMachineSync::register_task(); + SyncNotifier::init(); + add_action( 'admin_init', array( SyncUpgrade::class, 'run' ) ); + add_action( 'wp_abilities_api_init', array( SyncAbilities::class, 'register' ) ); + add_action( 'rest_api_init', array( Routes::class, 'register_sync_trigger_route' ) ); + + if ( defined( 'WP_CLI' ) && WP_CLI ) { + add_action( 'init', array( SyncUpgrade::class, 'run' ) ); + \DocSync\WPCLI\CLI::register_sync(); } -} +}, 30 ); + +register_activation_hook( __FILE__, function() { + flush_rewrite_rules(); +} ); register_deactivation_hook( __FILE__, function() { flush_rewrite_rules(); diff --git a/inc/Abilities/Abilities.php b/inc/Abilities/Abilities.php index 489d5b7..9cbf45a 100644 --- a/inc/Abilities/Abilities.php +++ b/inc/Abilities/Abilities.php @@ -16,7 +16,6 @@ class Abilities { public static function init(): void { add_action( 'wp_abilities_api_categories_init', [ __CLASS__, 'register_categories' ] ); - add_action( 'wp_abilities_api_init', [ SyncAbilities::class, 'register' ] ); add_action( 'wp_abilities_api_init', [ ProjectAbilities::class, 'register' ] ); add_action( 'wp_abilities_api_init', [ SearchAbilities::class, 'register' ] ); add_action( 'wp_abilities_api_init', [ DocsAbilities::class, 'register' ] ); diff --git a/inc/Abilities/SyncAbilities.php b/inc/Abilities/SyncAbilities.php index 0879649..b461ad6 100644 --- a/inc/Abilities/SyncAbilities.php +++ b/inc/Abilities/SyncAbilities.php @@ -1,14 +1,8 @@ __( 'Ensure DocSync Flows', 'docsync' ), - 'description' => __( 'Provision daily Data Machine flows for top-level projects with GitHub URLs.', 'docsync' ), - 'category' => 'docsync', - 'input_schema' => array( - 'type' => 'object', - 'properties' => array( - 'project' => array( 'type' => 'string' ), - 'dry_run' => array( 'type' => 'boolean' ), - ), + wp_register_ability( 'docsync/ensure-sync-flows', array( + 'label' => __( 'Ensure DocSync Flows', 'docsync' ), + 'description' => __( 'Provision daily Data Machine flows for top-level projects with GitHub URLs.', 'docsync' ), + 'category' => 'docsync', + 'input_schema' => array( + 'type' => 'object', + 'properties' => array( + 'project' => array( 'type' => 'string' ), + 'dry_run' => array( 'type' => 'boolean' ), ), - 'execute_callback' => array( DataMachineSync::class, 'ensure' ), - 'permission_callback' => fn() => current_user_can( 'manage_options' ), - 'meta' => array( 'show_in_rest' => true ), - ) ); - } elseif ( ! get_option( CronSync::OPTION_PAT ) ) { - return; - } + ), + 'execute_callback' => array( DataMachineSync::class, 'ensure' ), + 'permission_callback' => fn() => current_user_can( 'manage_options' ), + 'meta' => array( 'show_in_rest' => true ), + ) ); wp_register_ability( 'docsync/sync-docs', array( 'label' => __( 'Sync Documentation', 'docsync' ), - 'description' => __( 'Sync documentation from GitHub. Pass term_id for single sync, term_ids for batch, or neither for all syncable terms.', 'docsync' ), + 'description' => __( 'Queue Data Machine flows. Pass term_id for one project, term_ids for several, or neither for all syncable projects.', 'docsync' ), 'category' => 'docsync', 'input_schema' => array( 'type' => 'object', @@ -55,42 +45,16 @@ public static function register(): void { 'output_schema' => array( 'type' => 'object', 'properties' => array( - 'success' => array( 'type' => 'boolean' ), - 'term_id' => array( 'type' => 'integer' ), - 'queued' => array( 'type' => 'boolean' ), - 'flow_id' => array( 'type' => 'integer' ), - 'job_id' => array( 'type' => 'integer' ), - 'repos_queued' => array( 'type' => 'integer' ), - 'repos_synced' => array( 'type' => 'integer' ), - 'total_added' => array( 'type' => 'integer' ), - 'total_updated' => array( 'type' => 'integer' ), - 'total_removed' => array( 'type' => 'integer' ), - 'added' => array( - 'type' => 'array', - 'items' => array( 'type' => 'string' ), - ), - 'updated' => array( - 'type' => 'array', - 'items' => array( 'type' => 'string' ), - ), - 'removed' => array( - 'type' => 'array', - 'items' => array( 'type' => 'string' ), - ), - 'renamed' => array( + 'success' => array( 'type' => 'boolean' ), + 'repos_queued' => array( 'type' => 'integer' ), + 'errors' => array( 'type' => 'array', 'items' => array( 'type' => 'string' ), ), - 'unchanged' => array( + 'results' => array( 'type' => 'array', - 'items' => array( 'type' => 'string' ), - ), - 'errors' => array( - 'type' => 'array', - 'items' => array( 'type' => 'string' ), + 'items' => array( 'type' => 'object' ), ), - 'results' => array( 'type' => 'object' ), - 'error' => array( 'type' => array( 'string', 'null' ) ), ), ), 'execute_callback' => array( self::class, 'sync_callback' ), @@ -100,43 +64,20 @@ public static function register(): void { } public static function sync_callback( array $input ): array { - if ( isset( $input['term_id'] ) ) { - return CronSync::sync_term( (int) $input['term_id'], false ); - } - - if ( ! DataMachineSync::is_available() && ! get_option( CronSync::OPTION_PAT ) ) { - return array( - 'success' => false, - 'error' => 'GitHub PAT not configured', - ); - } - - $term_ids = $input['term_ids'] ?? array(); - if ( empty( $term_ids ) ) { - $term_ids = wp_list_pluck( CronSync::get_syncable_terms(), 'term_id' ); - } - - $results = array(); - foreach ( $term_ids as $term_id ) { - $results[ $term_id ] = CronSync::sync_term( (int) $term_id ); - } + $term_ids = isset( $input['term_id'] ) + ? array( $input['term_id'] ) + : ( $input['term_ids'] ?? wp_list_pluck( DataMachineSync::get_syncable_terms(), 'term_id' ) ); - $total_added = 0; - $total_updated = 0; - $total_removed = 0; - $repos_synced = 0; - $repos_queued = 0; - $errors = array(); + $results = array(); + $repos_queued = 0; + $errors = array(); - foreach ( $results as $term_id => $result ) { - if ( ! empty( $result['queued'] ) ) { + foreach ( array_unique( $term_ids ) as $term_id ) { + $result = DataMachineSync::run( (int) $term_id ); + $results[] = $result + array( 'term_id' => (int) $term_id ); + if ( $result['success'] ) { ++$repos_queued; - } elseif ( $result['success'] ) { - ++$repos_synced; - $total_added += count( $result['added'] ?? array() ); - $total_updated += count( $result['updated'] ?? array() ); - $total_removed += count( $result['removed'] ?? array() ); - } elseif ( ! empty( $result['error'] ) ) { + } else { $term = get_term( $term_id ); $name = $term instanceof \WP_Term ? $term->name : "Term {$term_id}"; $errors[] = "{$name}: {$result['error']}"; @@ -144,14 +85,10 @@ public static function sync_callback( array $input ): array { } return array( - 'success' => true, - 'repos_synced' => $repos_synced, - 'repos_queued' => $repos_queued, - 'total_added' => $total_added, - 'total_updated' => $total_updated, - 'total_removed' => $total_removed, - 'errors' => $errors, - 'results' => $results, + 'success' => ! $errors, + 'repos_queued' => $repos_queued, + 'errors' => $errors, + 'results' => $results, ); } } diff --git a/inc/Admin/SettingsPage.php b/inc/Admin/SettingsPage.php index 90c5bce..57ec88e 100644 --- a/inc/Admin/SettingsPage.php +++ b/inc/Admin/SettingsPage.php @@ -9,8 +9,6 @@ namespace DocSync\Admin; use DocSync\Api\Controllers\SyncTriggerController; -use DocSync\Sync\CronSync; -use DocSync\Sync\DataMachineSync; class SettingsPage { @@ -40,25 +38,6 @@ public static function add_menu(): void { * Register settings fields. */ public static function register_settings(): void { - register_setting( - self::OPTION_GROUP, - CronSync::OPTION_PAT, - array( - 'type' => 'string', - 'sanitize_callback' => 'sanitize_text_field', - ) - ); - - register_setting( - self::OPTION_GROUP, - CronSync::OPTION_INTERVAL, - array( - 'type' => 'string', - 'default' => 'twicedaily', - 'sanitize_callback' => array( __CLASS__, 'sanitize_interval' ), - ) - ); - register_setting( self::OPTION_GROUP, SyncTriggerController::OPTION_SYNC_TOKEN, @@ -79,35 +58,11 @@ public static function register_settings(): void { add_settings_section( 'docsync_github_section', - __( 'GitHub Sync', 'docsync' ), + __( 'Sync', 'docsync' ), array( __CLASS__, 'render_section' ), self::PAGE_SLUG ); - add_settings_field( - 'docsync_github_pat', - __( 'Personal Access Token', 'docsync' ), - array( __CLASS__, 'render_pat_field' ), - self::PAGE_SLUG, - 'docsync_github_section' - ); - - add_settings_field( - 'docsync_github_test', - __( 'Connection Test', 'docsync' ), - array( __CLASS__, 'render_test_field' ), - self::PAGE_SLUG, - 'docsync_github_section' - ); - - add_settings_field( - 'docsync_sync_interval', - __( 'Sync Interval', 'docsync' ), - array( __CLASS__, 'render_interval_field' ), - self::PAGE_SLUG, - 'docsync_github_section' - ); - // Sync Trigger section. add_settings_section( 'docsync_sync_trigger_section', @@ -134,119 +89,11 @@ public static function register_settings(): void { } /** - * Sanitize interval option. - * - * @param string $value Input value. - * @return string Sanitized interval. - */ - public static function sanitize_interval( string $value ): string { - $allowed = array( 'hourly', 'twicedaily', 'daily' ); - - if ( ! in_array( $value, $allowed, true ) ) { - return 'twicedaily'; - } - - $current = get_option( CronSync::OPTION_INTERVAL, 'twicedaily' ); - if ( $value !== $current ) { - CronSync::reschedule( $value ); - } - - return $value; - } - - /** - * Render section description. + * Describe where project flows and GitHub credentials are managed. */ public static function render_section(): void { - echo '

'; - esc_html_e( 'Configure automatic sync of documentation from GitHub repositories.', 'docsync' ); - echo '

'; - } - - /** - * Render PAT field. - */ - public static function render_pat_field(): void { - $value = get_option( CronSync::OPTION_PAT, '' ); - $masked = ! empty( $value ) ? str_repeat( '*', 8 ) . substr( $value, -4 ) : ''; - ?> - - -

- ' . esc_html( $masked ) . '' - ); - ?> -

- -

- - - - -

- - -
- ' . esc_html__( 'Data Machine manages the schedule. Provision project flows with wp docsync project flows ensure.', 'docsync' ) . '

'; - return; - } - - $value = get_option( CronSync::OPTION_INTERVAL, 'twicedaily' ); - $intervals = array( - 'hourly' => __( 'Hourly', 'docsync' ), - 'twicedaily' => __( 'Twice Daily', 'docsync' ), - 'daily' => __( 'Daily', 'docsync' ), - ); - ?> - - '; - printf( - /* translators: %s: formatted date/time */ - esc_html__( 'Next sync: %s', 'docsync' ), - esc_html( (string) wp_date( 'M j, Y \a\t g:ia', $next ) ) - ); - echo '

'; - } + echo '

' . esc_html__( 'Syncing runs as Data Machine flows, one per project. Manage your flows and GitHub authentication in Data Machine.', 'docsync' ) . '

'; + echo '

' . esc_html__( 'Open Data Machine', 'docsync' ) . '

'; } /** @@ -354,7 +201,7 @@ public static function render_page(): void {

-

+

diff --git a/inc/Api/Controllers/SyncController.php b/inc/Api/Controllers/SyncController.php index a52191c..09d585d 100644 --- a/inc/Api/Controllers/SyncController.php +++ b/inc/Api/Controllers/SyncController.php @@ -3,77 +3,12 @@ namespace DocSync\Api\Controllers; use DocSync\Core\Project; -use DocSync\Sync\CronSync; -use DocSync\Sync\GitHubClient; -use DocSync\Sync\SyncManager; use WP_REST_Request; use WP_REST_Response; use WP_Error; class SyncController { - /** - * Test GitHub token connection. - */ - public static function test_token( WP_REST_Request $request ): WP_REST_Response|WP_Error { - $pat = get_option( CronSync::OPTION_PAT ); - - if ( empty( $pat ) ) { - return new WP_Error( 'no_token', 'No token configured.', [ 'status' => 400 ] ); - } - - $github = new GitHubClient( $pat ); - $diagnostics = $github->test_connection(); - - if ( is_wp_error( $diagnostics ) ) { - return new WP_Error( 'connection_failed', $diagnostics->get_error_message(), [ 'status' => 500 ] ); - } - - return rest_ensure_response( $diagnostics ); - } - - /** - * Test access to a specific repository. - */ - public static function test_repo( WP_REST_Request $request ): WP_REST_Response|WP_Error { - $pat = get_option( CronSync::OPTION_PAT ); - - if ( empty( $pat ) ) { - return new WP_Error( 'no_token', 'No token configured.', [ 'status' => 400 ] ); - } - - $repo_url = $request->get_param( 'repo_url' ); - - if ( empty( $repo_url ) ) { - return new WP_Error( 'no_repo_url', 'No repository URL provided.', [ 'status' => 400 ] ); - } - - $parsed = GitHubClient::parse_repo_url( $repo_url ); - - if ( ! $parsed ) { - return new WP_Error( 'invalid_url', 'Invalid GitHub URL format.', [ 'status' => 400 ] ); - } - - $github = new GitHubClient( $pat ); - $result = $github->test_repo( $parsed['owner'], $parsed['repo'] ); - - if ( is_wp_error( $result ) ) { - $data = $result->get_error_data(); - return new WP_Error( - 'repo_test_failed', - $result->get_error_message(), - [ - 'status' => $data['status'] ?? 500, - 'owner' => $parsed['owner'], - 'repo' => $parsed['repo'], - 'sso_url' => $data['sso_url'] ?? null, - ] - ); - } - - return rest_ensure_response( $result ); - } - public static function setup_project(WP_REST_Request $request): WP_REST_Response|WP_Error { $project_slug = sanitize_title($request->get_param('project_slug')); $project_name = sanitize_text_field($request->get_param('project_name')); @@ -196,113 +131,4 @@ public static function get_status(WP_REST_Request $request): WP_REST_Response|WP 'docs' => $docs, ]); } - - public static function sync_doc(WP_REST_Request $request): WP_REST_Response|WP_Error { - $source_file = sanitize_text_field($request->get_param('source_file')); - $title = sanitize_text_field($request->get_param('title')); - $content = wp_kses_post($request->get_param('content')); - $project_term_id = absint($request->get_param('project_term_id')); - $filesize = absint($request->get_param('filesize')); - $timestamp = sanitize_text_field($request->get_param('timestamp')); - $subpath = $request->get_param('subpath'); - $excerpt = sanitize_textarea_field($request->get_param('excerpt') ?? ''); - $force = (bool) $request->get_param('force'); - - if (empty($source_file) || empty($title) || empty($content) || !$project_term_id) { - return new WP_Error('missing_required_params', 'Missing required parameters', ['status' => 400]); - } - - $result = SyncManager::sync_post( - $source_file, - $title, - $content, - $project_term_id, - $filesize, - $timestamp, - $subpath ?: [], - $excerpt, - $force - ); - - if (!$result['success']) { - return new WP_Error('sync_failed', $result['error'], ['status' => 500]); - } - - return rest_ensure_response($result); - } - - public static function sync_batch(WP_REST_Request $request): WP_REST_Response|WP_Error { - $docs = $request->get_param('docs'); - - if (!is_array($docs) || empty($docs)) { - return new WP_Error('invalid_docs', 'docs parameter must be a non-empty array', ['status' => 400]); - } - - $results = []; - $errors = []; - $counts = [ - 'created' => 0, - 'updated' => 0, - 'unchanged' => 0, - 'failed' => 0, - ]; - - foreach ($docs as $index => $doc) { - $source_file = sanitize_text_field($doc['source_file'] ?? ''); - $title = sanitize_text_field($doc['title'] ?? ''); - $content = wp_kses_post($doc['content'] ?? ''); - $project_term_id = absint($doc['project_term_id'] ?? 0); - $filesize = absint($doc['filesize'] ?? 0); - $timestamp = sanitize_text_field($doc['timestamp'] ?? ''); - $subpath = $doc['subpath'] ?? []; - $excerpt = sanitize_textarea_field($doc['excerpt'] ?? ''); - $force = (bool) ($doc['force'] ?? false); - - if (empty($source_file) || empty($title) || empty($content) || !$project_term_id) { - $errors[] = [ - 'index' => $index, - 'error' => 'Missing required parameters', - ]; - $counts['failed']++; - continue; - } - - $result = SyncManager::sync_post( - $source_file, - $title, - $content, - $project_term_id, - $filesize, - $timestamp, - $subpath, - $excerpt, - $force - ); - - if ($result['success']) { - $results[] = $result; - $action = $result['action'] ?? 'unknown'; - if (isset($counts[$action])) { - $counts[$action]++; - } - } else { - $errors[] = [ - 'index' => $index, - 'source_file' => $source_file, - 'error' => $result['error'], - ]; - $counts['failed']++; - } - } - - return rest_ensure_response([ - 'total' => count($docs), - 'created' => $counts['created'], - 'updated' => $counts['updated'], - 'unchanged' => $counts['unchanged'], - 'failed' => $counts['failed'], - 'results' => $results, - 'errors' => $errors, - ]); - } } diff --git a/inc/Api/Controllers/SyncTriggerController.php b/inc/Api/Controllers/SyncTriggerController.php index 8b5233f..9a2dae0 100644 --- a/inc/Api/Controllers/SyncTriggerController.php +++ b/inc/Api/Controllers/SyncTriggerController.php @@ -22,8 +22,6 @@ namespace DocSync\Api\Controllers; use DocSync\Core\Project; -use DocSync\PluginConfig; -use DocSync\Sync\CronSync; use DocSync\Sync\DataMachineSync; use WP_REST_Request; use WP_REST_Response; @@ -110,9 +108,7 @@ public static function handle( WP_REST_Request $request ): WP_REST_Response|WP_E return $term; } - $result = DataMachineSync::is_available() - ? DataMachineSync::run( $term->term_id, true ) - : CronSync::sync_term( $term->term_id ); + $result = DataMachineSync::run( $term->term_id, true ); if ( ! $result['success'] ) { return new WP_Error( @@ -122,19 +118,7 @@ public static function handle( WP_REST_Request $request ): WP_REST_Response|WP_E ); } - if ( ! empty( $result['queued'] ) ) { - return new WP_REST_Response( $result + array( 'project' => $term->slug ), 202 ); - } - - return rest_ensure_response( array( - 'success' => true, - 'project' => $term->slug, - 'term_id' => $term->term_id, - 'added' => count( $result['added'] ?? array() ), - 'updated' => count( $result['updated'] ?? array() ), - 'removed' => count( $result['removed'] ?? array() ), - 'unchanged' => count( $result['unchanged'] ?? array() ), - ) ); + return new WP_REST_Response( $result + array( 'project' => $term->slug ), 202 ); } /** @@ -216,30 +200,14 @@ private static function find_project_by_slug( string $slug ): \WP_Term|WP_Error * @return \WP_Term|WP_Error The term, or error if not found. */ private static function find_project_by_repo_url( string $repo_url ): \WP_Term|WP_Error { - $normalized = self::normalize_github_url( $repo_url ); - - $terms = get_terms( array( - 'taxonomy' => Project::TAXONOMY, - 'hide_empty' => false, - 'meta_query' => array( - array( - 'key' => 'project_github_url', - 'compare' => 'EXISTS', - ), - ), - ) ); - - if ( is_wp_error( $terms ) || empty( $terms ) ) { - return new WP_Error( - 'sync_project_not_found', - 'No projects with GitHub URLs configured.', - array( 'status' => 404 ) - ); + $repo = DataMachineSync::parse_repo_url( strtolower( $repo_url ) ); + if ( ! $repo ) { + return new WP_Error( 'sync_invalid_repo', 'Invalid GitHub repository URL.', array( 'status' => 400 ) ); } - foreach ( $terms as $term ) { - $stored_url = get_term_meta( $term->term_id, 'project_github_url', true ); - if ( self::normalize_github_url( $stored_url ) === $normalized ) { + foreach ( DataMachineSync::get_syncable_terms() as $term ) { + $stored_url = (string) get_term_meta( $term->term_id, 'project_github_url', true ); + if ( DataMachineSync::parse_repo_url( strtolower( $stored_url ) ) === $repo ) { return $term; } } @@ -251,22 +219,6 @@ private static function find_project_by_repo_url( string $repo_url ): \WP_Term|W ); } - /** - * Normalize a GitHub URL for comparison. - * - * Strips trailing slashes, .git suffix, and lowercases. - * - * @param string $url GitHub URL. - * @return string Normalized URL. - */ - private static function normalize_github_url( string $url ): string { - $url = strtolower( trim( $url ) ); - $url = rtrim( $url, '/' ); - $url = preg_replace( '/\.git$/', '', $url ); - - return $url; - } - /** * Get an option value (wrapper for testability). * diff --git a/inc/Api/Routes.php b/inc/Api/Routes.php index a17d55d..e5cb703 100644 --- a/inc/Api/Routes.php +++ b/inc/Api/Routes.php @@ -14,8 +14,7 @@ class Routes { public static function register(): void { self::register_docs_routes(); self::register_project_routes(); - self::register_sync_trigger_route(); - self::register_test_routes(); + self::register_sync_management_routes(); } private static function register_docs_routes(): void { @@ -175,7 +174,7 @@ private static function register_project_routes(): void { * slug, repo URL, or GitHub push payload. Authenticated via Bearer * token or GitHub webhook signature (no WordPress login required). */ - private static function register_sync_trigger_route(): void { + public static function register_sync_trigger_route(): void { register_rest_route( self::NAMESPACE, '/sync', [ 'methods' => 'POST', 'callback' => [ SyncTriggerController::class, 'handle' ], @@ -183,26 +182,7 @@ private static function register_sync_trigger_route(): void { ] ); } - private static function register_test_routes(): void { - register_rest_route(self::NAMESPACE, '/sync/test-token', [ - 'methods' => 'GET', - 'callback' => [SyncController::class, 'test_token'], - 'permission_callback' => [self::class, 'check_manage_options_permission'], - ]); - - register_rest_route(self::NAMESPACE, '/sync/test-repo', [ - 'methods' => 'POST', - 'callback' => [SyncController::class, 'test_repo'], - 'permission_callback' => [self::class, 'check_manage_options_permission'], - 'args' => [ - 'repo_url' => [ - 'type' => 'string', - 'required' => true, - 'sanitize_callback' => 'sanitize_text_field', - ], - ], - ]); - + private static function register_sync_management_routes(): void { register_rest_route(self::NAMESPACE, '/sync/setup', [ 'methods' => 'POST', 'callback' => [SyncController::class, 'setup_project'], @@ -247,24 +227,6 @@ private static function register_test_routes(): void { ], ], ]); - - register_rest_route(self::NAMESPACE, '/sync/doc', [ - 'methods' => 'POST', - 'callback' => [SyncController::class, 'sync_doc'], - 'permission_callback' => [self::class, 'check_edit_permission'], - 'args' => self::get_sync_doc_args(), - ]); - - register_rest_route(self::NAMESPACE, '/sync/batch', [ - 'methods' => 'POST', - 'callback' => [SyncController::class, 'sync_batch'], - 'permission_callback' => [self::class, 'check_edit_permission'], - 'args' => self::get_sync_batch_args(), - ]); - } - - public static function check_manage_options_permission(): bool { - return current_user_can('manage_options'); } public static function check_edit_permission(): bool { @@ -369,70 +331,4 @@ private static function get_docs_update_args(): array { ], ]; } - - private static function get_sync_doc_args(): array { - return [ - 'source_file' => [ - 'type' => 'string', - 'required' => true, - ], - 'title' => [ - 'type' => 'string', - 'required' => true, - ], - 'content' => [ - 'type' => 'string', - 'required' => true, - ], - 'project_term_id' => [ - 'type' => 'integer', - 'required' => true, - 'sanitize_callback' => 'absint', - ], - 'filesize' => [ - 'type' => 'integer', - 'required' => true, - 'sanitize_callback' => 'absint', - ], - 'timestamp' => [ - 'type' => 'string', - 'required' => true, - ], - 'subpath' => [ - 'type' => 'array', - 'default' => [], - 'items' => ['type' => 'string'], - ], - 'excerpt' => [ - 'type' => 'string', - ], - 'force' => [ - 'type' => 'boolean', - 'default' => false, - ], - ]; - } - - private static function get_sync_batch_args(): array { - return [ - 'docs' => [ - 'type' => 'array', - 'required' => true, - 'items' => [ - 'type' => 'object', - 'properties' => [ - 'source_file' => ['type' => 'string'], - 'title' => ['type' => 'string'], - 'content' => ['type' => 'string'], - 'project_term_id' => ['type' => 'integer'], - 'filesize' => ['type' => 'integer'], - 'timestamp' => ['type' => 'string'], - 'subpath' => ['type' => 'array', 'items' => ['type' => 'string']], - 'excerpt' => ['type' => 'string'], - 'force' => ['type' => 'boolean'], - ], - ], - ], - ]; - } } diff --git a/inc/Sync/ApplyGitHubFileTask.php b/inc/Sync/ApplyGitHubFileTask.php index e8b3a5c..9612806 100644 --- a/inc/Sync/ApplyGitHubFileTask.php +++ b/inc/Sync/ApplyGitHubFileTask.php @@ -47,7 +47,7 @@ public function executeTask( int $jobId, array $params ): void { $file_sha = ''; $removal_sha = ''; $files_synced = 0; - $removed = 0; + $changes = array( 'added' => array(), 'updated' => array(), 'removed' => array() ); try { if ( ! is_array( $packets ) ) { @@ -67,7 +67,7 @@ public function executeTask( int $jobId, array $params ): void { throw new \RuntimeException( "Failed to delete documentation: {$path}" ); } $removal_sha = $sha; - ++$removed; + $changes['removed'][] = $path; continue; } @@ -80,6 +80,8 @@ public function executeTask( int $jobId, array $params ): void { if ( ! $result['success'] ) { throw new \RuntimeException( $result['error'] ?? "Failed to sync: {$path}" ); } + $bucket = 'created' === $result['action'] ? 'added' : 'updated'; + $changes[ $bucket ][] = $path; $file_sha = $sha; ++$files_synced; } @@ -89,14 +91,21 @@ public function executeTask( int $jobId, array $params ): void { return; } - update_term_meta( $term_id, 'project_last_sync_time', time() ); + $old_sha = get_term_meta( $term_id, 'project_last_sync_sha', true ); // Pending removals can belong to an older commit than the fetched files. - update_term_meta( $term_id, 'project_last_sync_sha', '' !== $file_sha ? $file_sha : $removal_sha ); + $new_sha = '' !== $file_sha ? $file_sha : $removal_sha; + update_term_meta( $term_id, 'project_last_sync_time', time() ); + update_term_meta( $term_id, 'project_last_sync_sha', $new_sha ); update_term_meta( $term_id, 'project_files_synced', $files_synced ); RepoSync::update_sync_status( $term_id, 'success' ); + ( new SyncNotifier() )->queue( $term_id, $changes + array( + 'success' => true, + 'old_sha' => $old_sha, + 'new_sha' => $new_sha, + ) ); $this->completeJob( $jobId, array( 'files_synced' => $files_synced, - 'removed' => $removed, + 'removed' => count( $changes['removed'] ), ) ); } diff --git a/inc/Sync/CronSync.php b/inc/Sync/CronSync.php deleted file mode 100644 index 80e048a..0000000 --- a/inc/Sync/CronSync.php +++ /dev/null @@ -1,202 +0,0 @@ - true, - 'error' => null, - 'results' => array(), - ); - } - - $pat = get_option( self::OPTION_PAT ); - if ( empty( $pat ) ) { - return array( - 'success' => false, - 'error' => 'GitHub PAT not configured', - 'results' => array(), - ); - } - - $terms = self::get_syncable_terms(); - if ( empty( $terms ) ) { - return array( - 'success' => true, - 'error' => null, - 'results' => array(), - ); - } - - $github = new GitHubClient( $pat ); - $repo_sync = new RepoSync( $github ); - $notifier = new SyncNotifier(); - - $results = array(); - - foreach ( $terms as $term ) { - $result = $repo_sync->sync( $term->term_id ); - $results[ $term->term_id ] = $result; - - if ( $result['success'] ) { - $notifier->send( $term->term_id, $result ); - } - } - - return array( - 'success' => true, - 'error' => null, - 'results' => $results, - ); - } - - /** - * Sync a single term by ID. - * - * @param int $term_id Term ID. - * @return array Sync result. - */ - public static function sync_term( int $term_id, bool $notify = true ): array { - if ( DataMachineSync::is_available() ) { - return DataMachineSync::run( $term_id ); - } - - $pat = get_option( self::OPTION_PAT ); - if ( empty( $pat ) ) { - return array( - 'success' => false, - 'error' => 'GitHub PAT not configured', - ); - } - - $github = new GitHubClient( $pat ); - $repo_sync = new RepoSync( $github ); - $notifier = new SyncNotifier(); - - $result = $repo_sync->sync( $term_id ); - - if ( $notify && $result['success'] ) { - $notifier->send( $term_id, $result ); - } - - return $result; - } - - /** - * Get all project terms that have a GitHub URL configured. - * Only returns depth-0 terms (top-level projects). - * - * @return array Array of WP_Term objects. - */ - public static function get_syncable_terms(): array { - $all_terms = get_terms( array( - 'taxonomy' => Project::TAXONOMY, - 'hide_empty' => false, - ) ); - - if ( is_wp_error( $all_terms ) ) { - return array(); - } - - $syncable = array(); - - foreach ( $all_terms as $term ) { - if ( 0 !== (int) $term->parent ) { - continue; - } - - $github_url = get_term_meta( $term->term_id, 'project_github_url', true ); - if ( empty( $github_url ) ) { - continue; - } - - $syncable[] = $term; - } - - return $syncable; - } - - /** - * Get next scheduled sync time. - * - * @return int|false Timestamp or false if not scheduled. - */ - public static function get_next_scheduled(): int|false { - return wp_next_scheduled( self::CRON_HOOK ); - } - - /** - * Get current sync interval. - * - * @return string Interval name. - */ - public static function get_interval(): string { - return get_option( self::OPTION_INTERVAL, 'twicedaily' ); - } -} diff --git a/inc/Sync/DataMachineSync.php b/inc/Sync/DataMachineSync.php index af0fe27..8259565 100644 --- a/inc/Sync/DataMachineSync.php +++ b/inc/Sync/DataMachineSync.php @@ -3,10 +3,8 @@ namespace DocSync\Sync; -use DataMachine\Abilities\HandlerAbilities; use DataMachine\Core\Database\Flows\Flows; use DataMachine\Core\Database\Pipelines\Pipelines; -use DataMachine\Engine\AI\System\Tasks\SystemTask; use DataMachine\Engine\Scheduling\FlowRoutines; use DocSync\Core\Project; use WP_Error; @@ -17,20 +15,38 @@ class DataMachineSync { private const PIPELINE_OPTION = 'docsync_dm_pipeline_id'; public static function register_task(): void { - if ( class_exists( SystemTask::class ) ) { - add_filter( 'datamachine_tasks', array( ApplyGitHubFileTask::class, 'registerTask' ) ); + add_filter( 'datamachine_tasks', array( ApplyGitHubFileTask::class, 'registerTask' ) ); + } + + /** Get top-level projects with a configured GitHub URL. */ + public static function get_syncable_terms(): array { + $terms = get_terms( array( + 'taxonomy' => Project::TAXONOMY, + 'hide_empty' => false, + 'parent' => 0, + ) ); + + if ( is_wp_error( $terms ) ) { + return array(); } + + return array_values( array_filter( $terms, static fn( $term ) => ! empty( get_term_meta( $term->term_id, 'project_github_url', true ) ) ) ); } - public static function is_available(): bool { - return class_exists( SystemTask::class ) && class_exists( HandlerAbilities::class ) - && ( new HandlerAbilities() )->getHandler( 'github', 'fetch' ) !== null; + /** Parse an HTTPS or SSH GitHub repository URL into its owner and name. */ + public static function parse_repo_url( string $url ): ?array { + $pattern = '#^(?:(?:https?://|ssh://(?:git@)?)github\.com/|git@github\.com:)([a-z0-9-]+)/([a-z0-9_.-]+?)(?:\.git)?(?:/|$)#i'; + if ( ! preg_match( $pattern, trim( $url ), $matches ) ) { + return null; + } + + return array( 'owner' => $matches[1], 'repo' => $matches[2] ); } public static function fetch_config( int $term_id ): array|WP_Error { $url = (string) get_term_meta( $term_id, 'project_github_url', true ); - $repo = GitHubClient::parse_repo_url( $url ); - if ( ! $repo || ! preg_match( '#^[A-Za-z0-9-]+/[A-Za-z0-9_.-]+$#D', $repo['owner'] . '/' . $repo['repo'] ) ) { + $repo = self::parse_repo_url( $url ); + if ( ! $repo ) { return new WP_Error( 'docsync_invalid_repo', 'Invalid GitHub repository URL.' ); } @@ -44,13 +60,9 @@ public static function fetch_config( int $term_id ): array|WP_Error { } public static function ensure( array $input ): array|WP_Error { - if ( ! self::is_available() ) { - return new WP_Error( 'docsync_dm_unavailable', 'Activate Data Machine and its GitHub extension first.' ); - } - $slug = $input['project'] ?? ''; $dry_run = ! empty( $input['dry_run'] ); - $terms = CronSync::get_syncable_terms(); + $terms = self::get_syncable_terms(); $projects = array(); $errors = array(); @@ -201,7 +213,7 @@ public static function run( int $term_id, bool $webhook = false ): array { if ( $webhook ) { // The authenticated DocSync webhook has no WordPress user. Use Data // Machine's one-off scheduler hook rather than granting it ability permissions. - $action_id = function_exists( 'as_enqueue_async_action' ) && class_exists( FlowRoutines::class ) + $action_id = function_exists( 'as_enqueue_async_action' ) ? as_enqueue_async_action( FlowRoutines::ONE_TIME_HOOK, array( $flow_id ), FlowRoutines::LEGACY_GROUP ) : 0; return $action_id diff --git a/inc/Sync/GitHubClient.php b/inc/Sync/GitHubClient.php deleted file mode 100644 index 6aa04d4..0000000 --- a/inc/Sync/GitHubClient.php +++ /dev/null @@ -1,381 +0,0 @@ -pat = $pat; - } - - /** - * Get the latest commit SHA for a branch. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $branch Branch name. - * @return string|\WP_Error Commit SHA or WP_Error on failure. - */ - public function get_latest_commit_sha( string $owner, string $repo, string $branch = 'main' ) { - $endpoint = "/repos/{$owner}/{$repo}/commits/{$branch}"; - $response = $this->request( $endpoint ); - - if ( is_wp_error( $response ) ) { - return $response; - } - - if ( ! isset( $response['sha'] ) ) { - return new \WP_Error( 'github_missing_sha', 'Commit SHA missing from response' ); - } - - return $response['sha']; - } - - /** - * Get the file tree for a path at a specific ref. - * Returns only .md files within the docs/ directory. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $path Directory path (default: 'docs'). - * @param string $ref Git reference (branch, tag, or SHA). - * @return array Array of file info: ['relative_path' => ['path' => 'full/path', 'sha' => '...', 'size' => 123]] - */ - public function get_tree( string $owner, string $repo, string $path = 'docs', string $ref = 'main' ): array { - $endpoint = "/repos/{$owner}/{$repo}/git/trees/{$ref}?recursive=1"; - $response = $this->request( $endpoint ); - - if ( is_wp_error( $response ) || ! isset( $response['tree'] ) ) { - return []; - } - - $files = []; - $path_prefix = empty( $path ) ? '' : rtrim( $path, '/' ) . '/'; - - foreach ( $response['tree'] as $item ) { - if ( $item['type'] !== 'blob' ) { - continue; - } - - if ( $path_prefix !== '' && strpos( $item['path'], $path_prefix ) !== 0 ) { - continue; - } - - if ( substr( $item['path'], -3 ) !== '.md' ) { - continue; - } - - // Skip root-level README.md when syncing from root - if ( empty( $path ) && $item['path'] === 'README.md' ) { - continue; - } - - $relative_path = $path_prefix !== '' ? substr( $item['path'], strlen( $path_prefix ) ) : $item['path']; - - $files[ $relative_path ] = [ - 'path' => $item['path'], - 'sha' => $item['sha'], - 'size' => $item['size'] ?? 0, - ]; - } - - return $files; - } - - /** - * Get raw file content from a repository. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $path File path within the repository. - * @param string $ref Git reference (branch, tag, or SHA). - * @return string|null File content or null on failure. - */ - public function get_file_content( string $owner, string $repo, string $path, string $ref = 'main' ): ?string { - $endpoint = "/repos/{$owner}/{$repo}/contents/{$path}?ref={$ref}"; - $response = $this->request( $endpoint ); - - if ( is_wp_error( $response ) ) { - return null; - } - - if ( isset( $response['content'] ) && isset( $response['encoding'] ) ) { - if ( $response['encoding'] === 'base64' ) { - return base64_decode( $response['content'] ); - } - } - - return null; - } - - /** - * Compare two commits and get changed files. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $base Base commit SHA. - * @param string $head Head commit SHA. - * @param string $path Filter to files in this path (default: 'docs'). - * @return array ['added' => [...], 'modified' => [...], 'removed' => [...], 'renamed' => [...]] - */ - public function compare_commits( string $owner, string $repo, string $base, string $head, string $path = 'docs' ): array { - $endpoint = "/repos/{$owner}/{$repo}/compare/{$base}...{$head}"; - $response = $this->request( $endpoint ); - - $result = [ - 'added' => [], - 'modified' => [], - 'removed' => [], - 'renamed' => [], - ]; - - if ( is_wp_error( $response ) || ! isset( $response['files'] ) ) { - return $result; - } - - $path_prefix = empty( $path ) ? '' : rtrim( $path, '/' ) . '/'; - - foreach ( $response['files'] as $file ) { - if ( $path_prefix !== '' && strpos( $file['filename'], $path_prefix ) !== 0 ) { - continue; - } - - if ( substr( $file['filename'], -3 ) !== '.md' ) { - continue; - } - - // Skip root-level README.md when syncing from root - if ( empty( $path ) && $file['filename'] === 'README.md' ) { - continue; - } - - $relative_path = $path_prefix !== '' ? substr( $file['filename'], strlen( $path_prefix ) ) : $file['filename']; - - switch ( $file['status'] ) { - case 'added': - $result['added'][] = $relative_path; - break; - case 'modified': - $result['modified'][] = $relative_path; - break; - case 'removed': - $result['removed'][] = $relative_path; - break; - case 'renamed': - $previous = $path_prefix !== '' ? substr( $file['previous_filename'], strlen( $path_prefix ) ) : $file['previous_filename']; - $result['renamed'][] = [ - 'previous' => $previous, - 'new' => $relative_path, - ]; - break; - } - } - - return $result; - } - - /** - * Parse owner and repo from a GitHub URL. - * - * @param string $url GitHub repository URL. - * @return array|null ['owner' => '...', 'repo' => '...'] or null if invalid. - */ - public static function parse_repo_url( string $url ): ?array { - $patterns = [ - '#github\.com/([^/]+)/([^/]+?)(?:\.git)?(?:/|$)#i', - '#github\.com:([^/]+)/([^/]+?)(?:\.git)?$#i', - ]; - - foreach ( $patterns as $pattern ) { - if ( preg_match( $pattern, $url, $matches ) ) { - $repo = $matches[2]; - if ( str_ends_with( $repo, '.git' ) ) { - $repo = substr( $repo, 0, -4 ); - } - return [ - 'owner' => $matches[1], - 'repo' => $repo, - ]; - } - } - - return null; - } - - /** - * Test the connection and return diagnostic info. - * - * @return array|\WP_Error Connection info or WP_Error. - */ - public function test_connection(): array|\WP_Error { - $response = $this->request_with_headers( '/user' ); - - if ( is_wp_error( $response ) ) { - return $response; - } - - $headers = $response['headers']; - $body = $response['body']; - - $orgs_response = $this->request_with_headers( '/user/orgs' ); - $orgs = []; - if ( ! is_wp_error( $orgs_response ) && is_array( $orgs_response['body'] ) ) { - foreach ( $orgs_response['body'] as $org ) { - $orgs[] = $org['login'] ?? 'unknown'; - } - } - - return [ - 'user' => $body['login'] ?? 'unknown', - 'scopes' => array_map( 'trim', explode( ',', $headers['x-oauth-scopes'] ?? '' ) ), - 'orgs' => $orgs, - 'saml_enforced' => isset( $headers['x-github-sso'] ), - 'saml_message' => $headers['x-github-sso'] ?? null, - 'rate_limit' => $headers['x-ratelimit-remaining'] ?? 'unknown', - ]; - } - - /** - * Test access to a specific repository. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @return array|\WP_Error Repository info or WP_Error with details. - */ - public function test_repo( string $owner, string $repo ): array|\WP_Error { - $response = $this->request_with_headers( "/repos/{$owner}/{$repo}" ); - - if ( is_wp_error( $response ) ) { - $data = $response->get_error_data(); - return new \WP_Error( - $response->get_error_code(), - $response->get_error_message(), - [ - 'status' => $data['status'] ?? 'unknown', - 'headers' => $data['headers'] ?? [], - 'sso_url' => $data['headers']['x-github-sso'] ?? null, - ] - ); - } - - $body = $response['body']; - - return [ - 'success' => true, - 'full_name' => $body['full_name'] ?? "{$owner}/{$repo}", - 'private' => $body['private'] ?? false, - 'default_branch' => $body['default_branch'] ?? 'main', - 'permissions' => $body['permissions'] ?? [], - ]; - } - - /** - * Get the default branch for a repository. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @return string|null Default branch name or null on failure. - */ - public function get_default_branch( string $owner, string $repo ): ?string { - $endpoint = "/repos/{$owner}/{$repo}"; - $response = $this->request( $endpoint ); - - if ( is_wp_error( $response ) ) { - return null; - } - - return $response['default_branch'] ?? null; - } - - /** - * Get repository description from GitHub. - * - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @return string|null Description or null on failure/empty. - */ - public function get_repo_description( string $owner, string $repo ): ?string { - $endpoint = "/repos/{$owner}/{$repo}"; - $response = $this->request( $endpoint ); - - if ( is_wp_error( $response ) ) { - return null; - } - - $description = $response['description'] ?? null; - - return ! empty( $description ) ? $description : null; - } - - /** - * Make an authenticated request to the GitHub API. - * - * @param string $endpoint API endpoint (relative to API_BASE). - * @param string $method HTTP method. - * @return array|\WP_Error Response data or WP_Error on failure. - */ - private function request( string $endpoint, string $method = 'GET' ) { - $response = $this->request_with_headers( $endpoint, $method ); - return is_wp_error( $response ) ? $response : $response['body']; - } - - /** - * Make an authenticated request and return both body and headers. - * - * @param string $endpoint API endpoint. - * @param string $method HTTP method. - * @return array|\WP_Error ['body' => ..., 'headers' => ...] or WP_Error. - */ - private function request_with_headers( string $endpoint, string $method = 'GET' ) { - $url = self::API_BASE . $endpoint; - - $args = [ - 'method' => $method, - 'timeout' => 30, - 'headers' => [ - 'Accept' => 'application/vnd.github+json', - 'Authorization' => 'Bearer ' . $this->pat, - 'X-GitHub-Api-Version' => '2022-11-28', - 'User-Agent' => 'DocSync/1.0', - ], - ]; - - $response = wp_remote_request( $url, $args ); - - if ( is_wp_error( $response ) ) { - return $response; - } - - $code = wp_remote_retrieve_response_code( $response ); - $headers = wp_remote_retrieve_headers( $response )->getAll(); - $body = json_decode( wp_remote_retrieve_body( $response ), true ); - - if ( $code >= 400 ) { - $message = $body['message'] ?? "HTTP {$code}"; - - if ( $code === 404 && isset( $headers['x-github-sso'] ) ) { - $message .= ' (SAML SSO authorization required for this organization)'; - } - - return new \WP_Error( 'github_api_error', $message, [ - 'status' => $code, - 'headers' => $headers, - ] ); - } - - return [ - 'body' => $body, - 'headers' => $headers, - ]; - } -} diff --git a/inc/Sync/RepoSync.php b/inc/Sync/RepoSync.php index 57e2715..507ea5b 100644 --- a/inc/Sync/RepoSync.php +++ b/inc/Sync/RepoSync.php @@ -1,295 +1,10 @@ github = $github; - } - - /** - * Sync documentation for a project term. - * - * @param int $term_id The project term ID (project level, depth 1). - * @return array Sync results with counts and details. - */ - public function sync( int $term_id ): array { - $result = array( - 'success' => false, - 'term_id' => $term_id, - 'added' => array(), - 'updated' => array(), - 'removed' => array(), - 'renamed' => array(), - 'unchanged' => array(), - 'terms_created' => array(), - 'error' => null, - 'old_sha' => null, - 'new_sha' => null, - ); - - self::update_sync_status( $term_id, 'syncing' ); - - $github_url = get_term_meta( $term_id, 'project_github_url', true ); - if ( empty( $github_url ) ) { - $result['error'] = 'No GitHub URL configured'; - self::update_sync_status( $term_id, 'failed', $result['error'] ); - return $result; - } - - $repo_info = GitHubClient::parse_repo_url( $github_url ); - if ( ! $repo_info ) { - $result['error'] = 'Invalid GitHub URL format'; - self::update_sync_status( $term_id, 'failed', $result['error'] ); - return $result; - } - - $owner = $repo_info['owner']; - $repo = $repo_info['repo']; - - $branch = $this->github->get_default_branch( $owner, $repo ); - if ( empty( $branch ) ) { - $branch = 'main'; - } - - $new_sha = $this->github->get_latest_commit_sha( $owner, $repo, $branch ); - if ( is_wp_error( $new_sha ) ) { - $result['error'] = 'GitHub API: ' . $new_sha->get_error_message(); - self::update_sync_status( $term_id, 'failed', $result['error'] ); - return $result; - } - - if ( ! $new_sha ) { - $result['error'] = 'Failed to fetch latest commit from GitHub'; - self::update_sync_status( $term_id, 'failed', $result['error'] ); - return $result; - } - - $result['new_sha'] = $new_sha; - $old_sha = get_term_meta( $term_id, 'project_last_sync_sha', true ); - $result['old_sha'] = $old_sha ? $old_sha : null; - - // Sync repository description to term - $description = $this->github->get_repo_description( $owner, $repo ); - if ( null !== $description ) { - wp_update_term( $term_id, Project::TAXONOMY, array( - 'description' => $description, - ) ); - } - - if ( $old_sha === $new_sha ) { - $result['success'] = true; - $result['error'] = 'No changes detected'; - self::update_sync_status( $term_id, 'success' ); - return $result; - } - - $docs_path = get_term_meta( $term_id, 'project_docs_path', true ); - if ( empty( $docs_path ) ) { - $docs_path = 'docs'; - } - - if ( empty( $old_sha ) ) { - $sync_result = $this->full_sync( $term_id, $owner, $repo, $new_sha, $docs_path ); - } else { - $sync_result = $this->incremental_sync( $term_id, $owner, $repo, $old_sha, $new_sha, $docs_path ); - } - - $result = array_merge( $result, $sync_result ); - - if ( $result['success'] ) { - update_term_meta( $term_id, 'project_last_sync_sha', $new_sha ); - update_term_meta( $term_id, 'project_last_sync_time', time() ); - $files_synced = count( $result['added'] ) + count( $result['updated'] ) + count( $result['unchanged'] ); - update_term_meta( $term_id, 'project_files_synced', $files_synced ); - self::update_sync_status( $term_id, 'success' ); - } else { - self::update_sync_status( $term_id, 'failed', $result['error'] ?? 'Unknown error' ); - } - - return $result; - } - - /** - * Perform a full sync of all docs in the repository. - * - * @param int $term_id Project term ID. - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $sha Commit SHA. - * @return array Sync results. - */ - private function full_sync( int $term_id, string $owner, string $repo, string $sha, string $docs_path = 'docs' ): array { - $result = array( - 'success' => true, - 'added' => array(), - 'updated' => array(), - 'removed' => array(), - 'unchanged' => array(), - 'terms_created' => array(), - 'error' => null, - ); - - $tree_path = '.' === $docs_path ? '' : $docs_path; - $files = $this->github->get_tree( $owner, $repo, $tree_path, $sha ); - if ( empty( $files ) ) { - $path_label = '.' === $docs_path ? 'repository root' : "{$docs_path}/"; - $result['error'] = "No documentation files found in {$path_label} directory"; - $result['success'] = false; - return $result; - } - - $synced_source_files = array(); - - foreach ( $files as $relative_path => $file_info ) { - $process_result = $this->process_file( $term_id, $owner, $repo, $relative_path, $sha, $docs_path ); - - if ( $process_result['success'] ) { - $synced_source_files[] = $relative_path; - - switch ( $process_result['action'] ) { - case 'created': - $result['added'][] = $relative_path; - break; - case 'updated': - $result['updated'][] = $relative_path; - break; - case 'unchanged': - $result['unchanged'][] = $relative_path; - break; - } - - if ( ! empty( $process_result['terms_created'] ) ) { - $result['terms_created'] = array_merge( $result['terms_created'], $process_result['terms_created'] ); - } - } else { - $result['error'] = $process_result['error']; - $result['success'] = false; - } - } - - $orphans = $this->find_orphaned_posts( $term_id, $synced_source_files ); - foreach ( $orphans as $orphan ) { - if ( self::delete_post( $orphan['id'] ) ) { - $result['removed'][] = $orphan['source_file']; - } - } - - return $result; - } - - /** - * Perform an incremental sync based on changed files. - * - * @param int $term_id Project term ID. - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $old_sha Previous commit SHA. - * @param string $new_sha New commit SHA. - * @param string $docs_path Path to docs in the repository. - * @return array Sync results. - */ - private function incremental_sync( int $term_id, string $owner, string $repo, string $old_sha, string $new_sha, string $docs_path = 'docs' ): array { - $result = array( - 'success' => true, - 'added' => array(), - 'updated' => array(), - 'removed' => array(), - 'renamed' => array(), - 'unchanged' => array(), - 'terms_created' => array(), - 'error' => null, - ); - - $filter_path = '.' === $docs_path ? '' : $docs_path; - $changes = $this->github->compare_commits( $owner, $repo, $old_sha, $new_sha, $filter_path ); - - $files_to_process = array_merge( $changes['added'], $changes['modified'] ); - - foreach ( $files_to_process as $relative_path ) { - $process_result = $this->process_file( $term_id, $owner, $repo, $relative_path, $new_sha, $docs_path ); - - if ( $process_result['success'] ) { - switch ( $process_result['action'] ) { - case 'created': - $result['added'][] = $relative_path; - break; - case 'updated': - $result['updated'][] = $relative_path; - break; - case 'unchanged': - $result['unchanged'][] = $relative_path; - break; - } - - if ( ! empty( $process_result['terms_created'] ) ) { - $result['terms_created'] = array_merge( $result['terms_created'], $process_result['terms_created'] ); - } - } else { - $result['error'] = $process_result['error']; - $result['success'] = false; - } - } - - foreach ( $changes['removed'] as $relative_path ) { - if ( self::delete_by_source_file( $term_id, $relative_path ) ) { - $result['removed'][] = $relative_path; - } - } - - foreach ( $changes['renamed'] ?? array() as $rename ) { - $post_id = SyncManager::find_post_by_source( $rename['previous'], $term_id ); - if ( $post_id ) { - update_post_meta( $post_id, '_sync_source_file', $rename['new'] ); - $process_result = $this->process_file( $term_id, $owner, $repo, $rename['new'], $new_sha, $docs_path ); - if ( $process_result['success'] ) { - $result['renamed'][] = $rename['new']; - } else { - $result['error'] = $process_result['error']; - $result['success'] = false; - } - } - } - - return $result; - } - - /** - * Process a single documentation file. - * - * @param int $term_id Project term ID. - * @param string $owner Repository owner. - * @param string $repo Repository name. - * @param string $relative_path Relative path within the docs directory. - * @param string $ref Git reference. - * @param string $docs_path Path to docs in the repository. - * @return array Process result. - */ - private function process_file( int $term_id, string $owner, string $repo, string $relative_path, string $ref, string $docs_path = 'docs' ): array { - $full_path = '.' === $docs_path ? $relative_path : $docs_path . '/' . $relative_path; - $content = $this->github->get_file_content( $owner, $repo, $full_path, $ref ); - - if ( null === $content ) { - return array( - 'success' => false, - 'error' => "Failed to fetch file content: {$relative_path}", - ); - } - - return self::apply_file( $term_id, $relative_path, $content ); - } - /** * Apply fetched Markdown, using the docs-relative path as its identity. */ @@ -364,49 +79,6 @@ private static function build_subpath( string $relative_path ): array { return $subpath; } - /** - * Find orphaned posts that no longer exist in the source. - * - * @param int $term_id Project term ID. - * @param array $synced_source_files Array of source files that were synced. - * @return array Array of orphaned posts with 'id' and 'source_file'. - */ - private function find_orphaned_posts( int $term_id, array $synced_source_files ): array { - $orphans = array(); - - $term = get_term( $term_id, Project::TAXONOMY ); - if ( ! $term || is_wp_error( $term ) ) { - return $orphans; - } - - $posts = get_posts( array( - 'post_type' => 'documentation', - 'post_status' => 'any', - 'posts_per_page' => -1, - 'tax_query' => array( - array( - 'taxonomy' => Project::TAXONOMY, - 'field' => 'term_id', - 'terms' => $term_id, - 'include_children' => true, - ), - ), - 'fields' => 'ids', - ) ); - - foreach ( $posts as $post_id ) { - $source_file = get_post_meta( $post_id, '_sync_source_file', true ); - if ( $source_file && ! in_array( $source_file, $synced_source_files, true ) ) { - $orphans[] = array( - 'id' => $post_id, - 'source_file' => $source_file, - ); - } - } - - return $orphans; - } - /** * Delete a post by its source file path. * diff --git a/inc/Sync/SyncNotifier.php b/inc/Sync/SyncNotifier.php index 365564f..2ba9de1 100644 --- a/inc/Sync/SyncNotifier.php +++ b/inc/Sync/SyncNotifier.php @@ -56,23 +56,10 @@ public static function unschedule(): void { } /** - * Queue a sync result for the next daily digest. - * - * Replaces the previous per-sync immediate email. Kept named send() - * so existing call sites continue to work unchanged. - * - * @param int $term_id Project term ID. - * @param array $results Sync results from RepoSync. - */ - public function send( int $term_id, array $results ): void { - $this->queue( $term_id, $results ); - } - - /** - * Add a sync result to the pending digest queue. + * Add a sync result to the pending daily digest queue. * * @param int $term_id Project term ID. - * @param array $results Sync results from RepoSync. + * @param array $results Project results from the Data Machine apply task. */ public function queue( int $term_id, array $results ): void { if ( ! $this->has_changes( $results ) ) { diff --git a/inc/Sync/SyncUpgrade.php b/inc/Sync/SyncUpgrade.php new file mode 100644 index 0000000..8081e91 --- /dev/null +++ b/inc/Sync/SyncUpgrade.php @@ -0,0 +1,45 @@ += self::VERSION ) { + return; + } + + $pat = trim( (string) get_option( 'docsync_github_pat' ) ); + if ( '' === $pat ) { + $pat = trim( (string) get_option( 'chubes_docs_github_pat' ) ); + } + + if ( '' !== $pat ) { + $providers = apply_filters( 'datamachine_auth_providers', array() ); + $github = $providers['github'] ?? null; + // Preserve the saved token so the next request can retry a failed migration. + if ( ! $github ) { + return; + } + $config = $github->get_config(); + if ( empty( $config['access_token'] ) && ! $github->save_config( array( 'access_token' => $pat ) ) ) { + return; + } + } + + foreach ( array( 'docsync_github_sync', 'chubes_docs_github_sync' ) as $hook ) { + if ( false === wp_clear_scheduled_hook( $hook ) ) { + return; + } + } + + foreach ( array( 'docsync_github_pat', 'docsync_sync_interval', 'chubes_docs_github_pat', 'chubes_docs_sync_interval', 'docsync_last_cron_sync' ) as $option ) { + delete_option( $option ); + } + + update_option( 'docsync_db_version', self::VERSION, false ); + } +} diff --git a/inc/WPCLI/CLI.php b/inc/WPCLI/CLI.php index d68b1e3..af938af 100644 --- a/inc/WPCLI/CLI.php +++ b/inc/WPCLI/CLI.php @@ -17,11 +17,15 @@ class CLI { public static function register(): void { \WP_CLI::add_command( 'docsync project ensure', array( ProjectEnsureCommand::class, 'run' ) ); - \WP_CLI::add_command( 'docsync project flows ensure', array( ProjectFlowsEnsureCommand::class, 'run' ) ); \WP_CLI::add_command( 'docsync project tree', array( ProjectTreeCommand::class, 'run' ) ); - \WP_CLI::add_command( 'docsync docs sync', array( DocsSyncCommand::class, 'run' ) ); \WP_CLI::add_command( 'docsync docs list', array( DocsListCommand::class, 'run' ) ); \WP_CLI::add_command( 'docsync docs get', array( DocsGetCommand::class, 'run' ) ); \WP_CLI::add_command( 'docsync docs search', array( DocsSearchCommand::class, 'run' ) ); } + + /** Sync commands; registered only when Data Machine is active. */ + public static function register_sync(): void { + \WP_CLI::add_command( 'docsync project flows ensure', array( ProjectFlowsEnsureCommand::class, 'run' ) ); + \WP_CLI::add_command( 'docsync docs sync', array( DocsSyncCommand::class, 'run' ) ); + } } diff --git a/inc/WPCLI/Commands/DocsSyncCommand.php b/inc/WPCLI/Commands/DocsSyncCommand.php index 129e287..4943224 100644 --- a/inc/WPCLI/Commands/DocsSyncCommand.php +++ b/inc/WPCLI/Commands/DocsSyncCommand.php @@ -1,13 +1,9 @@ ] * : Output format (table, json, yaml) @@ -43,113 +36,35 @@ class DocsSyncCommand { * * ## EXAMPLES * - * # Sync single project - * wp docsync docs sync 42 - * - * # Sync all projects - * wp docsync docs sync --all - * - * @param array $args Positional arguments. - * @param array $assoc_args Associative arguments. + * wp docsync docs sync 42 --user=admin + * wp docsync docs sync --all --user=admin */ public static function run( array $args, array $assoc_args ): void { - $sync_all = Utils\get_flag_value( $assoc_args, 'all', false ); - $format = sanitize_key( $assoc_args['format'] ?? 'table' ); - + $format = sanitize_key( $assoc_args['format'] ?? 'table' ); if ( ! in_array( $format, array( 'table', 'json', 'yaml' ), true ) ) { WP_CLI::error( '--format must be one of: table, json, yaml' ); } - if ( $sync_all ) { - self::sync_all( $format ); - return; - } - - $term_id = absint( $args[0] ?? 0 ); - if ( empty( $term_id ) ) { - WP_CLI::error( 'Project term ID required (e.g. wp docsync docs sync 123) or use --all' ); - } - - self::sync_single( $term_id, $format ); - } - - private static function sync_single( int $term_id, string $format ): void { - $result = CronSync::sync_term( $term_id ); - - if ( empty( $result['success'] ) ) { - WP_CLI::error( $result['error'] ?? 'Sync failed' ); - } - - if ( ! empty( $result['queued'] ) ) { - WP_CLI::success( 'Data Machine sync queued.' ); - Utils\format_items( $format, array( $result ), array( 'term_id', 'flow_id', 'job_id' ) ); - return; - } - - $rows = array( - array( - 'term_id' => (string) $term_id, - 'added' => (string) count( $result['added'] ?? array() ), - 'updated' => (string) count( $result['updated'] ?? array() ), - 'removed' => (string) count( $result['removed'] ?? array() ), - 'unchanged' => (string) count( $result['unchanged'] ?? array() ), - 'error' => (string) ( $result['error'] ?? '' ), - ), - ); - - WP_CLI::success( 'Docs sync complete.' ); - Utils\format_items( $format, $rows, array_keys( $rows[0] ) ); - } - - private static function sync_all( string $format ): void { - WP_CLI::log( 'Syncing all projects with GitHub URLs...' ); - - $result = SyncAbilities::sync_callback( array() ); - - if ( empty( $result['success'] ) ) { - WP_CLI::error( $result['error'] ?? 'Sync failed' ); + $input = array(); + if ( ! Utils\get_flag_value( $assoc_args, 'all', false ) ) { + $input['term_id'] = absint( $args[0] ?? 0 ); + if ( ! $input['term_id'] ) { + WP_CLI::error( 'Project term ID required (e.g. wp docsync docs sync 123) or use --all' ); + } } - $rows = array(); - foreach ( $result['results'] as $term_id => $term_result ) { - $term = get_term( $term_id ); - $status = ! empty( $term_result['queued'] ) ? 'QUEUED' : ( $term_result['success'] ? 'OK' : 'FAIL' ); - $error = $term_result['error'] ?? ''; + $result = SyncAbilities::sync_callback( $input ); + $queued = array_filter( $result['results'], static fn( $project ) => $project['success'] ); + Utils\format_items( $format, array_values( $queued ), array( 'term_id', 'flow_id', 'job_id' ) ); - // Show inline warning for failed projects - if ( ! $term_result['success'] && ! empty( $error ) ) { - $project_name = $term instanceof \WP_Term ? $term->name : "term {$term_id}"; - WP_CLI::warning( "{$project_name}: {$error}" ); - } - - $rows[] = array( - 'term_id' => (string) $term_id, - 'project' => $term instanceof \WP_Term ? $term->name : '', - 'added' => (string) count( $term_result['added'] ?? array() ), - 'updated' => (string) count( $term_result['updated'] ?? array() ), - 'removed' => (string) count( $term_result['removed'] ?? array() ), - 'unchanged' => (string) count( $term_result['unchanged'] ?? array() ), - 'status' => $status, - ); + foreach ( $result['errors'] as $error ) { + WP_CLI::warning( $error ); } - - if ( ! empty( $result['errors'] ) ) { - foreach ( $result['errors'] as $error ) { - WP_CLI::warning( $error ); - } + if ( ! $result['success'] ) { + WP_CLI::error( sprintf( 'Queued %d Data Machine flows; some projects could not be queued.', $result['repos_queued'] ) ); } - - WP_CLI::success( sprintf( - 'Queued %d Data Machine flows; synced %d repos directly: %d added, %d updated, %d removed', - $result['repos_queued'], - $result['repos_synced'], - $result['total_added'], - $result['total_updated'], - $result['total_removed'] - ) ); - - if ( ! empty( $rows ) ) { - Utils\format_items( $format, $rows, array_keys( $rows[0] ) ); + if ( 'table' === $format ) { + WP_CLI::success( sprintf( 'Queued %d Data Machine flows.', $result['repos_queued'] ) ); } } }