From 9bdf6e61dfeb798abc639c769c61747047397b41 Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sat, 28 Nov 2026 14:08:00 +0000 Subject: [PATCH 1/4] feat(data-machine-github): add repository file fetch handler --- .github/workflows/data-machine-github.yml | 83 ++++++ README.md | 9 +- plugins/data-machine-github/.gitignore | 40 +++ plugins/data-machine-github/README.md | 7 + plugins/data-machine-github/composer.json | 20 ++ .../data-machine-github.php | 59 ++++ .../data-machine-github/docs/github-files.md | 42 +++ plugins/data-machine-github/homeboy.json | 36 +++ .../inc/Api/GitHubClient.php | 136 +++++++++ .../inc/Handlers/GitHub/GitHubFetch.php | 241 +++++++++++++++ .../Handlers/GitHub/GitHubFetchSettings.php | 51 ++++ .../inc/OAuth/Providers/GitHubAuth.php | 47 +++ .../tests/github-files-smoke.php | 277 ++++++++++++++++++ plugins/data-machine/README.md | 3 +- tools/check-boundaries.sh | 17 +- 15 files changed, 1058 insertions(+), 10 deletions(-) create mode 100644 .github/workflows/data-machine-github.yml create mode 100644 plugins/data-machine-github/.gitignore create mode 100644 plugins/data-machine-github/README.md create mode 100644 plugins/data-machine-github/composer.json create mode 100644 plugins/data-machine-github/data-machine-github.php create mode 100644 plugins/data-machine-github/docs/github-files.md create mode 100644 plugins/data-machine-github/homeboy.json create mode 100644 plugins/data-machine-github/inc/Api/GitHubClient.php create mode 100644 plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php create mode 100644 plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php create mode 100644 plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php create mode 100644 plugins/data-machine-github/tests/github-files-smoke.php diff --git a/.github/workflows/data-machine-github.yml b/.github/workflows/data-machine-github.yml new file mode 100644 index 000000000..f06943421 --- /dev/null +++ b/.github/workflows/data-machine-github.yml @@ -0,0 +1,83 @@ +name: data-machine-github + +on: + pull_request: + branches: [main] + paths: + - 'plugins/data-machine-github/**' + # Extensions run against the in-tree core, so a core change re-checks them. + - 'plugins/data-machine/**' + - '.github/workflows/data-machine-github.yml' + push: + branches: [main] + paths: + - 'plugins/data-machine-github/**' + # Extensions run against the in-tree core, so a core change re-checks them. + - 'plugins/data-machine/**' + - '.github/workflows/data-machine-github.yml' + workflow_dispatch: + +concurrency: + group: data-machine-github-${{ github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: write + pull-requests: write + issues: write + +jobs: + homeboy: + name: Homeboy (${{ matrix.command }}) + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + command: [review lint, review test] + services: + mysql: + image: mysql:8.0 + env: + MYSQL_ROOT_PASSWORD: '' + MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' + MYSQL_DATABASE: homeboy_wptests + ports: + - 3306:3306 + options: >- + --health-cmd="mysqladmin ping" + --health-interval=10s + --health-timeout=5s + --health-retries=3 + steps: + - uses: actions/checkout@v6 + with: + fetch-depth: 0 + + - name: Generate app token + id: app-token + uses: actions/create-github-app-token@v3 + continue-on-error: true + with: + app-id: ${{ secrets.HOMEBOY_APP_ID }} + private-key: ${{ secrets.HOMEBOY_APP_PRIVATE_KEY }} + + - name: Prepare in-tree Data Machine core + run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist --classmap-authoritative + + - name: Run Homeboy ${{ matrix.command }} + env: + HOMEBOY_SETTINGS_JSON: '{"database_type":"mysql","wp_codebox_database_service":{"provider":"external","engine":"mysql","allowed_hosts":["127.0.0.1:3306"],"secret_env":{"host":"WP_CODEBOX_DB_HOST","port":"WP_CODEBOX_DB_PORT","username":"WP_CODEBOX_DB_USER","password":"WP_CODEBOX_DB_PASSWORD"}},"wp_codebox_multisite":true,"wp_codebox_phpunit_bootstrap_mode":"managed"}' + HOMEBOY_WORDPRESS_DEPENDENCY_PATHS: ${{ github.workspace }}/plugins/data-machine + HOMEBOY_WORDPRESS_MULTISITE: '1' + WP_CODEBOX_DB_HOST: 127.0.0.1 + WP_CODEBOX_DB_PORT: '3306' + WP_CODEBOX_DB_USER: root + WP_CODEBOX_DB_PASSWORD: '' + uses: Extra-Chill/homeboy-action@v2 + with: + component: plugins/data-machine-github + comment-key: data-machine-github + commands: ${{ matrix.command }} + scope: ${{ matrix.command == 'review test' && 'full' || 'auto' }} + app-token: ${{ steps.app-token.outputs.token || '' }} + autofix: 'false' diff --git a/README.md b/README.md index 902998937..6712609ee 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Click the badge above to try core in your browser. Nothing is installed, and not ## What's in this repository -One core plugin and three extensions built on it. Each is a separate WordPress plugin with its own version, releases and activation, so a site installs only what it needs. +One core plugin and four extensions built on it. Each is a separate WordPress plugin with its own version, releases and activation, so a site installs only what it needs. | Plugin | What it adds | |---|---| @@ -18,15 +18,16 @@ One core plugin and three extensions built on it. Each is a separate WordPress p | [`data-machine-events`](plugins/data-machine-events) | **Events.** AI-assisted import from Ticketmaster, Eventbrite, ICS, venue websites and more, with deduplication, venue geocoding and a block-based calendar. | | [`data-machine-socials`](plugins/data-machine-socials) | **Social.** Publishing, reading and engagement across X, Facebook, Instagram, Threads, Bluesky, Mastodon, LinkedIn, Pinterest, Tumblr, TikTok, YouTube and Reddit. | | [`data-machine-business`](plugins/data-machine-business) | **Business.** Google Analytics, Search Console, Bing Webmaster Tools, PageSpeed, Google Sheets and Drive, Slack, Discord, Sendy, Mediavine, Amazon Associates and media maintenance, as abilities and agent tools. | +| [`data-machine-github`](plugins/data-machine-github) | **GitHub.** Fetch added, changed, and removed repository files into pipelines. | The extensions double as the reference for building your own: each registers handlers, abilities and tools through core's public hooks, the same way a third-party plugin would. ## How the pieces fit ```text -data-machine-events data-machine-socials data-machine-business (your extension) - \ | / / - +---------- public hooks, abilities, handlers -------------+ +data-machine-events data-machine-socials data-machine-business data-machine-github + \ | / / + +---------- public hooks, abilities, handlers ----------------+ | data-machine (core) pipelines, flows, jobs, memory, modes, tools, approvals diff --git a/plugins/data-machine-github/.gitignore b/plugins/data-machine-github/.gitignore new file mode 100644 index 000000000..63cadcba7 --- /dev/null +++ b/plugins/data-machine-github/.gitignore @@ -0,0 +1,40 @@ +# WordPress Plugin .gitignore + +# System files +.DS_Store +Thumbs.db +desktop.ini + +# IDE files +.vscode/ +.idea/ +*.swp +*.swo +*~ + +# Dependencies +vendor/ +node_modules/ + +# Log files +*.log + +# Temporary files +*.tmp +*.temp +*.cache + +# Backup files +*.bak +*.backup + +# Build artifacts +build/ +dist/ + +# Plugin specific +*.zip +*.tar.gz + +# Composer +composer.lock diff --git a/plugins/data-machine-github/README.md b/plugins/data-machine-github/README.md new file mode 100644 index 000000000..022db75c5 --- /dev/null +++ b/plugins/data-machine-github/README.md @@ -0,0 +1,7 @@ +# Data Machine GitHub + +Fetch files from public or private GitHub repositories into [Data Machine](../data-machine) pipelines. The **GitHub Files** fetch handler reports additions, modifications, and removals so downstream steps can publish, update, or unpublish content. + +Activate Data Machine and Data Machine GitHub, then add a **GitHub Files** fetch step and set `repo` to `owner/name`. Public repositories work without credentials. For private repositories, save a GitHub personal access token under **Data Machine → Settings → Auth Providers**. + +See [GitHub Files fetch handler](docs/github-files.md) for configuration and the packet contract. diff --git a/plugins/data-machine-github/composer.json b/plugins/data-machine-github/composer.json new file mode 100644 index 000000000..9d4dfdec0 --- /dev/null +++ b/plugins/data-machine-github/composer.json @@ -0,0 +1,20 @@ +{ + "name": "extra-chill/data-machine-github", + "description": "GitHub file fetch integration for Data Machine", + "version": "0.1.0", + "license": "GPL-2.0-or-later", + "require": { + "php": ">=8.2" + }, + "autoload": { + "psr-4": { + "DataMachineGitHub\\": "inc/" + } + }, + "authors": [ + { + "name": "Chris Huber", + "email": "chris@chubes.net" + } + ] +} diff --git a/plugins/data-machine-github/data-machine-github.php b/plugins/data-machine-github/data-machine-github.php new file mode 100644 index 000000000..601101524 --- /dev/null +++ b/plugins/data-machine-github/data-machine-github.php @@ -0,0 +1,59 @@ +

' . esc_html__( 'Data Machine GitHub requires the Data Machine core plugin to be active.', 'data-machine-github' ) . '

'; + } + ); + return; + } + + new \DataMachineGitHub\Handlers\GitHub\GitHubFetch(); +} + +add_action( 'plugins_loaded', 'datamachine_github_load_handlers', 20 ); diff --git a/plugins/data-machine-github/docs/github-files.md b/plugins/data-machine-github/docs/github-files.md new file mode 100644 index 000000000..283450f83 --- /dev/null +++ b/plugins/data-machine-github/docs/github-files.md @@ -0,0 +1,42 @@ +# GitHub Files fetch handler + +The `github` fetch handler reads the `files` data source from GitHub.com. It resolves the branch tip, reads its recursive Git tree, and downloads matching blobs by SHA so every file in a fetch comes from the same commit. + +## Configuration + +| Field | Default | Meaning | +| --- | --- | --- | +| `repo` | Required | GitHub repository in `owner/name` format, not a URL. | +| `branch` | Repository default | Use the exact branch name, such as `release/docs`. The default branch name is cached for five minutes. | +| `file_path` | `''` | Fetch from the whole repository, a directory and its descendants, or an exact file. `docs` does not match `docs-extra`. Leading and trailing slashes are ignored. | +| `file_pattern` | `''` | No glob filter. A glob without a slash, such as `*.md`, matches filenames at any depth. With a slash, it matches the path relative to `file_path`, and `*` does not cross a slash. Matching is case-sensitive. | +| `max_file_size` | `1048576` | Maximum file size in bytes (1–104857600). Larger files are skipped before download. | + +For public repositories no credential is required, even though Data Machine may show a **Requires Auth** badge to expose the provider settings. For private repositories, save a GitHub fine-grained personal access token with **Contents: Read-only** access to the selected repository in **Data Machine → Settings → Auth Providers**. The `github` provider stores the PAT as the encrypted `access_token` credential and sends it as a bearer token. Do not put the token in step settings. There is no OAuth flow. + +## Item contract + +The packet's `data.title` is the repository-relative file path (prefixed with `Removed:` for removals), and `data.body` is the decoded file content. A removal has an empty body; use `metadata.github_change` to distinguish it from an empty file. + +| Metadata | Meaning | +| --- | --- | +| `source_type` | `github` | +| `github_repo`, `github_branch` | Repository and resolved branch. | +| `github_commit_sha` | Commit examined by the fetch; for removals, the first commit seen without the file. | +| `github_file_path` | Full repository-relative path, e.g. `docs/setup/install.md`. | +| `github_relative_file_path` | Path relative to `file_path`, e.g. `setup/install.md` when `file_path` is `docs`. With an exact-file prefix this is the filename. | +| `github_file_sha` | Git blob SHA; for a removal, the last tracked blob SHA. | +| `github_url`, `source_url` | The same commit-pinned file URL. For a removal, the URL points at the last tracked revision where the file existed. | +| `github_change` | `added` when the file first enters the snapshot, `modified` when its blob SHA changes, or `removed` when a tracked file disappears. | +| `dedup_key`, `original_id` | `github__files__`, with the full repository-relative path and the blob SHA. | +| `item_identifier` | Internal key for Data Machine's processed-items lifecycle. Removals have a separate identity so a processed file does not suppress its removal. | + +For DocSync, route `removed` items to unpublish and use the repository and full file path to identify the destination. Use the file SHA or `dedup_key` to identify a revision, not as the stable destination key. + +## Change tracking and failures + +A flow step stores its snapshot in Data Machine's Tracked Items ledger. There are no removals on the first run. A successful fetch updates the snapshot; if a GitHub request fails or the tree is truncated, the prior snapshot is retained. Snapshots are separate for each flow step, repository, branch, prefix, and glob. An oversized file still present in the tree does not count as removed. + +The handler checks Data Machine's processed-items ledger before each batch of blob downloads. Once downstream processing completes, a repeat fetch of the same file path and blob SHA skips that revision, even if it reappears later. With an explicit or cached branch, an unchanged, fully processed fetch only requests the commit and tree. Unprocessed removals are retried while the path remains absent. Direct execution has no durable snapshot or deduplication. + +An existing path with no matching files can succeed with no items. A configured prefix that no longer exists fails with `github_missing_file_path`, rather than treating the entire source as removed. For example, to detect deletion of a directory and all its files, use a surviving ancestor (or the repository root) as `file_path`. GitHub API failures and truncated trees also fail the fetch step. diff --git a/plugins/data-machine-github/homeboy.json b/plugins/data-machine-github/homeboy.json new file mode 100644 index 000000000..8b4c18113 --- /dev/null +++ b/plugins/data-machine-github/homeboy.json @@ -0,0 +1,36 @@ +{ + "auto_cleanup": false, + "changelog_target": "docs/CHANGELOG.md", + "extensions": { + "wordpress": { + "php": "8.2", + "settings": { + "validation_dependencies": [ + "../data-machine" + ], + "wordpress_test_paths": [ + "tests/github-files-smoke.php" + ] + } + } + }, + "id": "data-machine-github", + "remote_path": "wp-content/plugins/data-machine-github", + "version_targets": [ + { + "file": "data-machine-github.php", + "pattern": "(?m)^\\s*\\*?\\s*Version:\\s*([0-9.]+)" + }, + { + "file": "data-machine-github.php", + "pattern": "DATAMACHINE_GITHUB_VERSION',\\s*'([0-9.]+)'" + }, + { + "file": "composer.json", + "pattern": "\"version\":\\s*\"([0-9.]+)\"" + } + ], + "github": { + "release_latest": false + } +} diff --git a/plugins/data-machine-github/inc/Api/GitHubClient.php b/plugins/data-machine-github/inc/Api/GitHubClient.php new file mode 100644 index 000000000..b9d9f90c2 --- /dev/null +++ b/plugins/data-machine-github/inc/Api/GitHubClient.php @@ -0,0 +1,136 @@ +get_string( $this->get( $repo ), 'default_branch' ); + } + + public function get_latest_commit_sha( string $repo, string $branch ): string|WP_Error { + return $this->get_string( $this->get_commit( $repo, $branch ), 'sha' ); + } + + /** Return both SHAs so the caller can fetch the pinned tree without another request. */ + public function get_commit( string $repo, string $branch ): array|WP_Error { + $result = $this->get( $repo, '/commits/' . rawurlencode( $branch ) ); + if ( is_wp_error( $result ) ) { + return $result; + } + foreach ( array( $result['sha'] ?? null, $result['commit']['tree']['sha'] ?? null ) as $sha ) { + if ( ! is_string( $sha ) || '' === $sha ) { + return $this->invalid_response(); + } + } + return $result; + } + + public function get_recursive_tree( string $repo, string $sha ): array|WP_Error { + $result = $this->get( $repo, '/git/trees/' . rawurlencode( $sha ) . '?recursive=1' ); + if ( is_wp_error( $result ) ) { + return $result; + } + if ( ! empty( $result['truncated'] ) ) { + return new WP_Error( 'github_tree_truncated', __( 'GitHub truncated the recursive tree. File changes cannot be determined from an incomplete tree.', 'data-machine-github' ) ); + } + if ( ! isset( $result['tree'] ) || ! is_array( $result['tree'] ) || ! array_is_list( $result['tree'] ) ) { + return $this->invalid_response(); + } + foreach ( $result['tree'] as $entry ) { + if ( ! is_string( $entry['path'] ?? null ) || '' === $entry['path'] || ! is_string( $entry['type'] ?? null ) ) { + return $this->invalid_response(); + } + if ( 'blob' === $entry['type'] && ( ! is_string( $entry['sha'] ?? null ) || '' === $entry['sha'] || ! is_int( $entry['size'] ?? null ) || $entry['size'] < 0 ) ) { + return $this->invalid_response(); + } + } + return $result['tree']; + } + + public function get_blob( string $repo, string $sha, int $max_bytes = 1048576 ): string|WP_Error { + // Allow room for base64, JSON escaping, and response metadata. + $result = $this->get( $repo, '/git/blobs/' . rawurlencode( $sha ), 3 * $max_bytes + 4096 ); + $content = $this->decode_contents( $result ); + if ( ! is_wp_error( $content ) && strlen( $content ) > $max_bytes ) { + return new WP_Error( 'github_blob_too_large', __( 'GitHub returned a blob larger than the configured file size limit.', 'data-machine-github' ) ); + } + return $content; + } + + public function get_file_contents( string $repo, string $path, string $ref = '' ): string|WP_Error { + $query = '' === $ref ? '' : '?ref=' . rawurlencode( $ref ); + return $this->decode_contents( $this->get( $repo, '/contents/' . self::encode_path( $path ) . $query ) ); + } + + private function decode_contents( array|WP_Error $result ): string|WP_Error { + if ( is_wp_error( $result ) ) { + return $result; + } + if ( 'base64' !== ( $result['encoding'] ?? null ) || ! is_string( $result['content'] ?? null ) ) { + return $this->invalid_response(); + } + $content = base64_decode( $result['content'], true ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_decode -- GitHub returns base64-encoded content. + return false === $content ? $this->invalid_response() : $content; + } + + private function get_string( array|WP_Error $result, string $key ): string|WP_Error { + if ( is_wp_error( $result ) ) { + return $result; + } + return is_string( $result[ $key ] ?? null ) && '' !== $result[ $key ] ? $result[ $key ] : $this->invalid_response(); + } + + private function get( string $repo, string $endpoint = '', int $response_limit = 0 ): array|WP_Error { + if ( ! preg_match( '#^[a-zA-Z0-9-]+/(?!\.{1,2}$)[a-zA-Z0-9_.-]+$#D', $repo ) ) { + return new WP_Error( 'github_invalid_repo', __( 'GitHub repo must be in owner/name format.', 'data-machine-github' ) ); + } + + $result = HttpClient::get( + 'https://api.github.com/repos/' . self::encode_path( $repo ) . $endpoint, + array( + 'headers' => array( + 'Accept' => 'application/vnd.github+json', + 'X-GitHub-Api-Version' => '2022-11-28', + ), + 'auth' => array( 'type' => 'bearer', 'token' => $this->token ), + 'timeout' => 30, + 'context' => 'GitHub API', + 'limit_response_size' => $response_limit, + 'log_response_body_preview' => false, + ) + ); + + $status = (int) ( $result['status_code'] ?? 0 ); + if ( empty( $result['success'] ) || $status < 200 || $status >= 300 ) { + $message = $status > 0 + /* translators: %d: HTTP status code. */ + ? sprintf( __( 'GitHub API returned HTTP %d. Check repository access, branch or file references, and API rate limits.', 'data-machine-github' ), $status ) + : __( 'Could not connect to the GitHub API.', 'data-machine-github' ); + return new WP_Error( 'github_api_error', $message, array( 'status' => $status ) ); + } + + $data = json_decode( $result['data'], true ); + return is_array( $data ) ? $data : $this->invalid_response(); + } + + private function invalid_response(): WP_Error { + return new WP_Error( 'github_invalid_response', __( 'GitHub API returned an invalid or unsupported response.', 'data-machine-github' ) ); + } +} diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php new file mode 100644 index 000000000..0d297c693 --- /dev/null +++ b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php @@ -0,0 +1,241 @@ + 'files' ) + ); + } + + protected function getDefaultMaxItems(): int { + return 0; + } + + protected function executeFetch( array $config, ExecutionContext $context ): array|WP_Error { + $repo = trim( (string) ( $config['repo'] ?? '' ) ); + $branch = trim( (string) ( $config['branch'] ?? '' ) ); + $prefix = trim( (string) ( $config['file_path'] ?? '' ), '/' ); + $pattern = (string) ( $config['file_pattern'] ?? '' ); + $limit = min( GitHubFetchSettings::MAX_FILE_SIZE, max( 1, (int) ( $config['max_file_size'] ?? GitHubFetchSettings::DEFAULT_MAX_FILE_SIZE ) ) ); + + $provider = $this->getAuthProvider( 'github' ); + $token = $provider instanceof GitHubAuth ? $provider->get_token( $config ) : ''; + $auth_error = $provider instanceof GitHubAuth ? $provider->get_last_decryption_error() : null; + if ( null !== $auth_error ) { + return $auth_error; + } + $client = new GitHubClient( $token ); + if ( '' === $branch ) { + $branch = $this->default_branch( $client, $repo, $token ); + if ( is_wp_error( $branch ) ) { + return $branch; + } + } + + $head = $client->get_commit( $repo, $branch ); + if ( is_wp_error( $head ) ) { + return $head; + } + $commit = $head['sha']; + $tree_sha = $head['commit']['tree']['sha']; + $tree = $client->get_recursive_tree( $repo, $tree_sha ); + if ( is_wp_error( $tree ) ) { + return $tree; + } + + $scope = wp_json_encode( array( $context->getFlowStepId(), strtolower( $repo ), $branch, $prefix, $pattern ), JSON_INVALID_UTF8_SUBSTITUTE ); + $namespace = 'github-files:' . hash( 'sha256', (string) $scope ); + $ledger = $context->isFlow() && $context->getFlowStepId() ? new TrackedItems() : null; + $snapshot = $ledger?->get( $namespace, 'snapshot' ); + $previous = $snapshot['metadata']['paths'] ?? array(); + $pending = $snapshot['metadata']['removals'] ?? array(); + $paths = array(); + $items = array(); + $candidates = array(); + $prefix_exists = '' === $prefix; + + foreach ( $tree as $entry ) { + $path = $entry['path']; + if ( '' !== $prefix && $path !== $prefix && ! str_starts_with( $path, $prefix . '/' ) ) { + continue; + } + $prefix_exists = true; + if ( 'blob' !== $entry['type'] ) { + continue; + } + // The file is still present even if it exceeds the configured download limit. + unset( $pending[ $path ] ); + $relative = self::relative_path( $path, $prefix ); + $subject = str_contains( $pattern, '/' ) ? $relative : self::filename( $relative ); + if ( '' !== $pattern && ! fnmatch( $pattern, $subject, FNM_PATHNAME ) ) { + continue; + } + if ( $entry['size'] > $limit ) { + if ( isset( $previous[ $path ] ) ) { + $paths[ $path ] = $previous[ $path ]; + } + continue; + } + + $sha = $entry['sha']; + $before = $previous[ $path ] ?? null; + $change = null === $before ? 'added' : ( $sha === $before['sha'] ? $before['change'] : 'modified' ); + $paths[ $path ] = array( 'sha' => $sha, 'change' => $change, 'commit' => $commit ); + $candidates[ self::item_identifier( self::dedup_key( $repo, $path, $sha ) ) ] = $path; + } + + if ( ! $prefix_exists ) { + return new WP_Error( + 'github_missing_file_path', + /* translators: %s: configured repository path. */ + sprintf( __( 'GitHub file_path "%s" does not exist in the repository tree.', 'data-machine-github' ), $prefix ) + ); + } + + // Hold tombstones until the downstream pipeline marks them processed so + // caps, in-flight claims and downstream failures cannot drop removals. + foreach ( array_diff_key( $previous, $paths ) as $path => $entry ) { + $pending[ $path ] = array( 'sha' => $entry['sha'], 'old_commit' => $entry['commit'], 'commit' => $commit ); + } + foreach ( $pending as $path => $entry ) { + $path = (string) $path; + $item = $this->file_item( $repo, $branch, $entry['commit'], $path, self::relative_path( $path, $prefix ), $entry['sha'], 'removed', $entry['old_commit'] ); + if ( $context->isItemProcessed( $item['metadata']['item_identifier'] ) ) { + unset( $pending[ $path ] ); + continue; + } + $items[] = $item; + } + + // Match the core batch cap without downloading blobs outside the batch. + $remaining = max( 0, (int) ( $config['max_items'] ?? 0 ) ); + if ( $remaining > 0 ) { + $removals = $context->classifySourceItems( array_column( array_column( $items, 'metadata' ), 'item_identifier' ) ); + $remaining -= count( $removals['selected_identifiers'] ); + if ( $remaining <= 0 ) { + $candidates = array(); + } + } + $selection = $context->classifySourceItems( array_keys( $candidates ), max( 0, $remaining ) ); + foreach ( $selection['selected_identifiers'] as $identifier ) { + $path = $candidates[ $identifier ]; + $entry = $paths[ $path ]; + $content = $client->get_blob( $repo, $entry['sha'], $limit ); + if ( is_wp_error( $content ) ) { + return $content; + } + $item = $this->file_item( $repo, $branch, $commit, $path, self::relative_path( $path, $prefix ), $entry['sha'], $entry['change'], $commit ); + $item['content'] = $content; + $items[] = $item; + } + + $state = array( 'paths' => $paths, 'removals' => $pending ); + if ( $ledger && $state !== ( $snapshot['metadata'] ?? null ) && null === $ledger->upsert( + array( + 'namespace' => $namespace, + 'item_id' => 'snapshot', + 'item_type' => 'github_files_snapshot', + 'source_ref' => $repo, + 'source_revision' => $commit, + 'metadata' => $state, + ) + ) ) { + return new WP_Error( 'github_snapshot_error', __( 'Could not save the GitHub file snapshot for this flow step.', 'data-machine-github' ) ); + } + + return array( 'items' => $items ); + } + + private function default_branch( GitHubClient $client, string $repo, string $token ): string|WP_Error { + $key = 'datamachine_github_branch_' . hash( 'sha256', strtolower( $repo ) . "\0" . $token ); + $branch = get_transient( $key ); + if ( is_string( $branch ) && '' !== $branch ) { + return $branch; + } + $branch = $client->get_default_branch( $repo ); + if ( ! is_wp_error( $branch ) ) { + set_transient( $key, $branch, 300 ); + } + return $branch; + } + + private static function relative_path( string $path, string $prefix ): string { + if ( '' === $prefix ) { + return $path; + } + return $path === $prefix ? self::filename( $path ) : substr( $path, strlen( $prefix ) + 1 ); + } + + private static function filename( string $path ): string { + return substr( strrchr( '/' . $path, '/' ), 1 ); + } + + private static function dedup_key( string $repo, string $path, string $sha ): string { + return "github_{$repo}_files_{$path}_{$sha}"; + } + + private static function item_identifier( string $key, string $removed_at = '' ): string { + // Core's processed-items index has a length limit and case-insensitive collation. + return hash( 'sha256', '' === $removed_at ? $key : "removed\0{$key}\0{$removed_at}" ); + } + + private function file_item( string $repo, string $branch, string $commit, string $path, string $relative, string $sha, string $change, string $url_commit ): array { + $key = self::dedup_key( $repo, $path, $sha ); + $url = 'https://github.com/' . GitHubClient::encode_path( $repo ) . '/blob/' . rawurlencode( $url_commit ) . '/' . GitHubClient::encode_path( $path ); + + return array( + 'title' => 'removed' === $change + /* translators: %s: removed repository path. */ + ? sprintf( __( 'Removed: %s', 'data-machine-github' ), $path ) + : $path, + 'content' => '', + 'metadata' => array( + 'source_type' => 'github', + 'github_repo' => $repo, + 'github_branch' => $branch, + 'github_commit_sha' => $commit, + 'github_file_path' => $path, + 'github_relative_file_path' => $relative, + 'github_file_sha' => $sha, + 'github_change' => $change, + 'github_url' => $url, + 'source_url' => $url, + 'dedup_key' => $key, + 'original_id' => $key, + 'item_identifier' => self::item_identifier( $key, 'removed' === $change ? $commit : '' ), + ), + ); + } +} diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php new file mode 100644 index 000000000..883ca8288 --- /dev/null +++ b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php @@ -0,0 +1,51 @@ + array( + 'type' => 'text', + 'label' => __( 'Repository', 'data-machine-github' ), + 'description' => __( 'GitHub repository in owner/name format.', 'data-machine-github' ), + 'required' => true, + ), + 'branch' => array( + 'type' => 'text', + 'label' => __( 'Branch', 'data-machine-github' ), + 'description' => __( 'Leave blank to use the repository default branch.', 'data-machine-github' ), + ), + 'file_path' => array( + 'type' => 'text', + 'label' => __( 'File Path', 'data-machine-github' ), + 'description' => __( 'Limit to a file or directory path. Leave blank for the entire repository.', 'data-machine-github' ), + ), + 'file_pattern' => array( + 'type' => 'text', + 'label' => __( 'File Pattern', 'data-machine-github' ), + 'description' => __( 'Optional glob, e.g. *.md. Patterns without a slash match filenames at any depth.', 'data-machine-github' ), + ), + 'max_file_size' => array( + 'type' => 'number', + 'label' => __( 'Maximum File Size (bytes)', 'data-machine-github' ), + 'default' => self::DEFAULT_MAX_FILE_SIZE, + 'min' => 1, + 'max' => self::MAX_FILE_SIZE, + ), + ); + } +} diff --git a/plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php b/plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php new file mode 100644 index 000000000..ce1587495 --- /dev/null +++ b/plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php @@ -0,0 +1,47 @@ + array( + 'label' => __( 'Personal Access Token', 'data-machine-github' ), + 'type' => 'password', + 'required' => false, + 'description' => __( 'Optional for public repositories. For private repositories, grant read access to repository contents.', 'data-machine-github' ), + ), + ); + } + + public function is_configured(): bool { + return '' !== $this->get_token(); + } + + public function is_authenticated(): bool { + return $this->is_configured(); + } + + /** The PAT lives in provider config, not an OAuth account slot. */ + public function clear_account(): bool { + return $this->save_config( array() ); + } + + public function get_token( array $context = array() ): string { + return trim( (string) ( $this->get_config( $context )['access_token'] ?? '' ) ); + } +} diff --git a/plugins/data-machine-github/tests/github-files-smoke.php b/plugins/data-machine-github/tests/github-files-smoke.php new file mode 100644 index 000000000..14327c65f --- /dev/null +++ b/plugins/data-machine-github/tests/github-files-smoke.php @@ -0,0 +1,277 @@ +code; + } + public function get_error_message(): string { + return $this->message; + } + } + + function __( $message, $domain ) { + return $message; + } + function is_wp_error( $value ) { + return $value instanceof WP_Error; + } + function wp_json_encode( ...$args ) { + return json_encode( ...$args ); + } + function plugin_dir_path( $file ) { + return dirname( $file ) . '/'; + } + function plugin_dir_url( $file ) { + return 'https://example.test/wp-content/plugins/data-machine-github/'; + } + function home_url() { + return 'https://example.test'; + } + function add_filter( $tag, $callback, $priority = 10, $accepted_args = 1 ) { + $GLOBALS['hooks'][ $tag ][ $priority ][] = array( $callback, $accepted_args ); + } + function add_action( ...$args ) { + add_filter( ...$args ); + } + function apply_filters( $tag, $value, ...$args ) { + $hooks = $GLOBALS['hooks'][ $tag ] ?? array(); + ksort( $hooks ); + foreach ( $hooks as $group ) { + foreach ( $group as list( $callback, $accepted ) ) { + $value = $callback( ...array_slice( array( $value, ...$args ), 0, $accepted ) ); + } + } + return $value; + } + function do_action( $tag, ...$args ) { + foreach ( $GLOBALS['hooks'][ $tag ] ?? array() as $group ) { + foreach ( $group as list( $callback, $accepted ) ) { + $callback( ...array_slice( $args, 0, $accepted ) ); + } + } + } + function did_action( $tag ) { + return 0; + } + function doing_action( $tag ) { + return false; + } + function get_site_option( $name, $default ) { + return $GLOBALS['options'][ $name ] ?? $default; + } + function update_site_option( $name, $value ) { + $GLOBALS['options'][ $name ] = $value; + return true; + } + function wp_salt( $scheme ) { + return 'github-files-smoke-test-salt'; + } + function get_transient( $key ) { + return $GLOBALS['transients'][ $key ] ?? false; + } + function set_transient( $key, $value, $ttl ) { + $GLOBALS['transients'][ $key ] = $value; + } + function wp_remote_get( $url, $args ) { + $prefix = 'https://api.github.com/repos/owner/repo'; + check( str_starts_with( $url, $prefix ), 'Unexpected GitHub URL: ' . $url ); + $route = substr( $url, strlen( $prefix ) ); + $GLOBALS['requests'][] = array( $route, $args ); + check( isset( $GLOBALS['responses'][ $route ] ), 'Unexpected API request: ' . $route ); + list( $status, $body ) = $GLOBALS['responses'][ $route ]; + return array( 'status' => $status, 'body' => json_encode( $body ) ); + } + function wp_remote_retrieve_body( $response ) { + return $response['body']; + } + function wp_remote_retrieve_response_code( $response ) { + return $response['status']; + } + function wp_remote_retrieve_headers( $response ) { + return array(); + } + function check( $condition, $message ) { + if ( ! $condition ) { + fwrite( STDERR, $message . "\n" ); + exit( 1 ); + } + } + + $core = getenv( 'DATA_MACHINE_PATH' ) ?: dirname( __DIR__, 2 ) . '/data-machine'; + spl_autoload_register( + static function ( $class ) use ( $core ) { + if ( str_starts_with( $class, 'DataMachine\\' ) ) { + $file = $core . '/inc/' . str_replace( '\\', '/', substr( $class, strlen( 'DataMachine\\' ) ) ) . '.php'; + if ( is_file( $file ) ) { + require $file; + } + } + } + ); + require dirname( __DIR__ ) . '/data-machine-github.php'; + do_action( 'plugins_loaded' ); + $registration = apply_filters( 'datamachine_handlers', array(), 'fetch' )['github']; + check( 'files' === $registration['meta']['data_source'], 'GitHub files source was not registered.' ); + $handler = new $registration['class'](); + $config = array( + 'repo' => 'owner/repo', + 'file_path' => 'docs/', + 'file_pattern' => '*.md', + 'max_file_size' => 20, + 'flow_id' => 1, + 'pipeline_id' => 1, + 'flow_step_id' => 'github-step', + ); + + function fixture( $commit, $files, $truncated = false, $include_docs = true ) { + $GLOBALS['requests'] = array(); + $GLOBALS['responses'] = array( + '' => array( 200, array( 'default_branch' => 'release/docs' ) ), + '/commits/release%2Fdocs' => array( 200, array( 'sha' => $commit, 'commit' => array( 'tree' => array( 'sha' => 'tree-' . $commit ) ) ) ), + '/git/trees/tree-' . $commit . '?recursive=1' => array( 200, array( 'truncated' => $truncated, 'tree' => array_merge( $include_docs ? array( array( 'path' => 'docs', 'type' => 'tree' ) ) : array(), $files ) ) ), + ); + } + function blob( $path, $sha, $size = 1 ) { + return array( 'path' => $path, 'sha' => $sha, 'type' => 'blob', 'size' => $size ); + } + function content( $sha, $body ) { + $GLOBALS['responses'][ '/git/blobs/' . $sha ] = array( 200, array( 'encoding' => 'base64', 'content' => base64_encode( $body ) ) ); + } + function run_fetch( $override = array() ) { + $packets = $GLOBALS['handler']->get_fetch_data( 1, array_replace( $GLOBALS['config'], $override ), '1' ); + return is_wp_error( $packets ) ? $packets : array_map( static fn ( $packet ) => $packet->addTo( array() )[0], $packets ); + } + function mark_processed( $packet ) { + ProcessedItems::$processed['github-step'][ $packet['metadata']['item_identifier'] ] = array( 'processed' => true ); + } + function routes() { + return array_column( $GLOBALS['requests'], 0 ); + } + + $first = array( blob( 'docs/nested/hello #.md', 'a' ), blob( 'docs/old.md', 'b' ), blob( 'docs/not.txt', 'c' ), blob( 'docs-extra/outside.md', 'd' ), blob( 'docs/large.md', 'e', 21 ) ); + fixture( 'one', $first ); + content( 'a', 'hello' ); + content( 'b', '' ); + $packets = run_fetch(); + check( is_array( $packets ) && 2 === count( $packets ), 'Prefix, glob or size filter picked the wrong files.' ); + check( array( '', '/commits/release%2Fdocs', '/git/trees/tree-one?recursive=1', '/git/blobs/a', '/git/blobs/b' ) === routes(), 'First fetch did not use default branch, pinned tree and matching blobs.' ); + $meta = $packets[0]['metadata']; + check( 'hello' === $packets[0]['data']['body'] && '' === $packets[1]['data']['body'], 'Blob contents (including empty files) were not emitted.' ); + check( 'nested/hello #.md' === $meta['github_relative_file_path'] && 'one' === $meta['github_commit_sha'] && 'release/docs' === $meta['github_branch'], 'File identity metadata is incomplete.' ); + check( 'https://github.com/owner/repo/blob/one/docs/nested/hello%20%23.md' === $meta['source_url'] && $meta['source_url'] === $meta['github_url'], 'URL is not pinned or encoded.' ); + check( 'github_owner/repo_files_docs/nested/hello #.md_a' === $meta['dedup_key'] && $meta['dedup_key'] === $meta['original_id'], 'DocSync identity is incorrect.' ); + foreach ( $packets as $packet ) { + check( 'added' === $packet['metadata']['github_change'], 'First run must only emit additions.' ); + mark_processed( $packet ); + } + check( ! isset( $GLOBALS['requests'][0][1]['headers']['Authorization'] ), 'Public fetch sent an auth header.' ); + + fixture( 'one', $first ); + check( array() === run_fetch(), 'An unchanged run emitted processed files.' ); + check( array( '/commits/release%2Fdocs', '/git/trees/tree-one?recursive=1' ) === routes(), 'An unchanged run requested more than commit and tree.' ); + + fixture( 'no-docs', array(), false, false ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_missing_file_path' === $error->get_error_code(), 'A previously tracked prefix that disappears must fail, not emit mass removals.' ); + + $next = array( blob( 'docs/nested/hello #.md', 'f' ) ); + fixture( 'two', $next ); + $GLOBALS['responses']['/git/blobs/f'] = array( 503, array( 'message' => 'temporarily unavailable' ) ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_api_error' === $error->get_error_code() && str_contains( $error->get_error_message(), '503' ), 'Non-2xx blob response did not fail the run.' ); + + fixture( 'two', $next ); + content( 'f', 'changed' ); + $packets = run_fetch(); + check( is_array( $packets ) && 2 === count( $packets ), 'Expected one removal and one modification after retry.' ); + $meta = $packets[0]['metadata']; + check( 'removed' === $meta['github_change'] && 'docs/old.md' === $meta['github_file_path'] && 'b' === $meta['github_file_sha'] && 'two' === $meta['github_commit_sha'] && '' === $packets[0]['data']['body'], 'Removal packet is incorrect.' ); + check( 'modified' === $packets[1]['metadata']['github_change'] && 'changed' === $packets[1]['data']['body'], 'Modified file packet is incorrect.' ); + mark_processed( $packets[1] ); + fixture( 'two', $next ); + $packets = run_fetch(); + check( 1 === count( $packets ) && 'removed' === $packets[0]['metadata']['github_change'], 'Unprocessed removals should be retried.' ); + mark_processed( $packets[0] ); + fixture( 'two', $next ); + check( array() === run_fetch(), 'A processed removal was repeated.' ); + + fixture( 'two', $next ); + $error = run_fetch( array( 'file_path' => 'missing' ) ); + check( is_wp_error( $error ) && 'github_missing_file_path' === $error->get_error_code(), 'A missing prefix must fail.' ); + check( array() === run_fetch( array( 'file_pattern' => '*.rst' ) ), 'An existing path with no matching glob should succeed empty.' ); + fixture( 'three', array(), true ); + $error = run_fetch(); + check( is_wp_error( $error ) && 'github_tree_truncated' === $error->get_error_code(), 'A truncated tree must fail.' ); + + $provider = apply_filters( 'datamachine_auth_providers', array() )['github']; + check( $provider->save_config( array( 'access_token' => 'test-private-token' ) ), 'Could not save GitHub token.' ); + check( ! str_contains( json_encode( $GLOBALS['options'] ), 'test-private-token' ), 'The GitHub token was stored in the clear.' ); + fixture( 'two', $next ); + content( 'f', 'changed' ); + $packets = run_fetch( array( 'flow_step_id' => 'private-step' ) ); + check( is_array( $packets ) && 1 === count( $packets ) && 'added' === $packets[0]['metadata']['github_change'], 'Private fetch or step isolation failed.' ); + foreach ( $GLOBALS['requests'] as list( $route, $args ) ) { + check( 'Bearer test-private-token' === ( $args['headers']['Authorization'] ?? '' ), 'Missing bearer token on ' . $route ); + } + + $GLOBALS['responses']['/contents/docs/a%20b.md?ref=release%2Fdocs'] = array( 200, array( 'encoding' => 'base64', 'content' => 'b2s=' ) ); + check( 'ok' === ( new GitHubClient() )->get_file_contents( 'owner/repo', 'docs/a b.md', 'release/docs' ), 'Contents-by-path API failed.' ); + echo "GitHub files smoke passed.\n"; +} diff --git a/plugins/data-machine/README.md b/plugins/data-machine/README.md index 63e3588a3..c97691777 100644 --- a/plugins/data-machine/README.md +++ b/plugins/data-machine/README.md @@ -109,7 +109,7 @@ Typed, permissioned functions registered via WordPress's Abilities API. Extensio | `datamachine/run-flow` | Execute a flow programmatically | | ... | Additional core abilities across pipelines, flows, jobs, memory, media, SEO, email, and infrastructure | -Social publishing, workspace, GitHub, and business integration abilities live in extension plugins such as data-machine-socials, data-machine-code, and data-machine-business. +Social publishing, workspace, GitHub, and business integrations live in extension plugins such as data-machine-socials, data-machine-code, data-machine-github, and data-machine-business. ### Agent Bundles @@ -265,6 +265,7 @@ Detailed endpoint docs live under [`docs/api/`](docs/api/). Routes under `wp-jso | [data-machine-code](https://github.com/Extra-Chill/data-machine-code) | Workspace management, GitHub integration, git operations | | [data-machine-socials](../data-machine-socials) | Publish to Instagram (images, carousels, Reels, Stories), Twitter (text + media + video), Facebook, Threads, Bluesky, Pinterest (image + video pins). Reddit fetch. | | [data-machine-business](../data-machine-business) | Google Sheets (fetch + publish), Slack, Discord integrations | +| [data-machine-github](../data-machine-github) | Fetch added, modified, and removed files from GitHub repositories | | [data-machine-editor](https://github.com/Extra-Chill/data-machine-editor) | Gutenberg inline diff visualization, accept/reject review, editor sidebar | | [data-machine-frontend-chat](https://github.com/Extra-Chill/data-machine-frontend-chat) | Floating agent chat widget for any WordPress site | | [data-machine-chat-bridge](https://github.com/Extra-Chill/data-machine-chat-bridge) | Message queue, webhook delivery, and REST API for external chat clients | diff --git a/tools/check-boundaries.sh b/tools/check-boundaries.sh index 587e5325a..1f007cade 100755 --- a/tools/check-boundaries.sh +++ b/tools/check-boundaries.sh @@ -20,16 +20,23 @@ set -euo pipefail root="$(git rev-parse --show-toplevel)" cd "${root}" -extensions=(events socials business) +extensions=(events socials business github) allowlist="tools/boundary-allowlist.txt" # Identifiers owned by the given extensions, e.g. "events socials". pattern_for() { - local names=("$@") lower upper title + local names=("$@") lower title ext constant constants=() lower="$(IFS='|'; echo "${names[*]}")" - upper="$(echo "${lower}" | tr '[:lower:]' '[:upper:]')" - title="$(echo "${lower}" | sed -E 's/(^|\|)([a-z])/\1\u\2/g')" - printf '%s' "DataMachine(${title})\\\\|DATAMACHINE_(${upper})_|data-machine-(${lower})/|data_?machine_?(${lower})\\b|plugins/data-machine-(${lower})" + title="$(echo "${lower}" | sed -E 's/(^|\|)([a-z])/\1\u\2/g; s/Github/GitHub/g')" + for ext in "${names[@]}"; do + constant="${ext^^}_" + if [[ "${ext}" == github ]]; then + # DATAMACHINE_GITHUB_TOKEN already belongs to core's bundle downloader. + constant='GITHUB_(VERSION|PATH|URL)\b' + fi + constants+=("${constant}") + done + printf '%s' "DataMachine(${title})\\\\|DATAMACHINE_($(IFS='|'; echo "${constants[*]}"))|data-machine-(${lower})/|data_?machine_?(${lower})\\b|plugins/data-machine-(${lower})" } # Code only: docs, changelogs and READMEs may describe the ecosystem. From a269dd3c4aba8aeb23987056f1d89d346e2f0e19 Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sat, 28 Nov 2026 14:51:10 +0000 Subject: [PATCH 2/4] fix(data-machine-github): CI lint, phpstan and in-WordPress test split The stub-based files test redeclares WordPress functions, so it runs as plain PHP in its own job. A new contract smoke test runs in WordPress and checks the core APIs the handler depends on. --- .github/workflows/data-machine-github.yml | 15 +++++ plugins/data-machine-github/homeboy.json | 2 +- .../inc/Api/GitHubClient.php | 5 +- .../inc/Handlers/GitHub/GitHubFetch.php | 22 +++++-- .../Handlers/GitHub/GitHubFetchSettings.php | 10 ++-- .../tests/github-handler-contract-smoke.php | 60 +++++++++++++++++++ 6 files changed, 102 insertions(+), 12 deletions(-) create mode 100644 plugins/data-machine-github/tests/github-handler-contract-smoke.php diff --git a/.github/workflows/data-machine-github.yml b/.github/workflows/data-machine-github.yml index f06943421..94b71342f 100644 --- a/.github/workflows/data-machine-github.yml +++ b/.github/workflows/data-machine-github.yml @@ -27,6 +27,21 @@ permissions: issues: write jobs: + unit: + name: Unit (standalone PHP) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + tools: composer + # Stubs core's database classes, so it runs outside WordPress. + - name: Prepare in-tree Data Machine core + run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist + - name: GitHub files unit test + run: php plugins/data-machine-github/tests/github-files-smoke.php + homeboy: name: Homeboy (${{ matrix.command }}) runs-on: ubuntu-latest diff --git a/plugins/data-machine-github/homeboy.json b/plugins/data-machine-github/homeboy.json index 8b4c18113..7a567830c 100644 --- a/plugins/data-machine-github/homeboy.json +++ b/plugins/data-machine-github/homeboy.json @@ -9,7 +9,7 @@ "../data-machine" ], "wordpress_test_paths": [ - "tests/github-files-smoke.php" + "tests/github-handler-contract-smoke.php" ] } } diff --git a/plugins/data-machine-github/inc/Api/GitHubClient.php b/plugins/data-machine-github/inc/Api/GitHubClient.php index b9d9f90c2..2d1a0f41e 100644 --- a/plugins/data-machine-github/inc/Api/GitHubClient.php +++ b/plugins/data-machine-github/inc/Api/GitHubClient.php @@ -109,7 +109,10 @@ private function get( string $repo, string $endpoint = '', int $response_limit = 'Accept' => 'application/vnd.github+json', 'X-GitHub-Api-Version' => '2022-11-28', ), - 'auth' => array( 'type' => 'bearer', 'token' => $this->token ), + 'auth' => array( + 'type' => 'bearer', + 'token' => $this->token, + ), 'timeout' => 30, 'context' => 'GitHub API', 'limit_response_size' => $response_limit, diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php index 0d297c693..f7fd738fd 100644 --- a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php +++ b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php @@ -112,7 +112,11 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr $sha = $entry['sha']; $before = $previous[ $path ] ?? null; $change = null === $before ? 'added' : ( $sha === $before['sha'] ? $before['change'] : 'modified' ); - $paths[ $path ] = array( 'sha' => $sha, 'change' => $change, 'commit' => $commit ); + $paths[ $path ] = array( + 'sha' => $sha, + 'change' => $change, + 'commit' => $commit, + ); $candidates[ self::item_identifier( self::dedup_key( $repo, $path, $sha ) ) ] = $path; } @@ -127,7 +131,11 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr // Hold tombstones until the downstream pipeline marks them processed so // caps, in-flight claims and downstream failures cannot drop removals. foreach ( array_diff_key( $previous, $paths ) as $path => $entry ) { - $pending[ $path ] = array( 'sha' => $entry['sha'], 'old_commit' => $entry['commit'], 'commit' => $commit ); + $pending[ $path ] = array( + 'sha' => $entry['sha'], + 'old_commit' => $entry['commit'], + 'commit' => $commit, + ); } foreach ( $pending as $path => $entry ) { $path = (string) $path; @@ -161,8 +169,11 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr $items[] = $item; } - $state = array( 'paths' => $paths, 'removals' => $pending ); - if ( $ledger && $state !== ( $snapshot['metadata'] ?? null ) && null === $ledger->upsert( + $state = array( + 'paths' => $paths, + 'removals' => $pending, + ); + if ( $ledger && ( $snapshot['metadata'] ?? null ) !== $state && null === $ledger->upsert( array( 'namespace' => $namespace, 'item_id' => 'snapshot', @@ -199,7 +210,8 @@ private static function relative_path( string $path, string $prefix ): string { } private static function filename( string $path ): string { - return substr( strrchr( '/' . $path, '/' ), 1 ); + $slash = strrpos( $path, '/' ); + return false === $slash ? $path : substr( $path, $slash + 1 ); } private static function dedup_key( string $repo, string $path, string $sha ): string { diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php index 883ca8288..56dfced41 100644 --- a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php +++ b/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php @@ -40,11 +40,11 @@ public static function get_fields(): array { 'description' => __( 'Optional glob, e.g. *.md. Patterns without a slash match filenames at any depth.', 'data-machine-github' ), ), 'max_file_size' => array( - 'type' => 'number', - 'label' => __( 'Maximum File Size (bytes)', 'data-machine-github' ), - 'default' => self::DEFAULT_MAX_FILE_SIZE, - 'min' => 1, - 'max' => self::MAX_FILE_SIZE, + 'type' => 'number', + 'label' => __( 'Maximum File Size (bytes)', 'data-machine-github' ), + 'default' => self::DEFAULT_MAX_FILE_SIZE, + 'min' => 1, + 'max' => self::MAX_FILE_SIZE, ), ); } diff --git a/plugins/data-machine-github/tests/github-handler-contract-smoke.php b/plugins/data-machine-github/tests/github-handler-contract-smoke.php new file mode 100644 index 000000000..b1e9f9b7e --- /dev/null +++ b/plugins/data-machine-github/tests/github-handler-contract-smoke.php @@ -0,0 +1,60 @@ + array( 'get', 'upsert' ), + \DataMachine\Core\ExecutionContext::class => array( 'isFlow', 'getFlowStepId', 'isItemProcessed', 'classifySourceItems' ), + \DataMachine\Core\Steps\Fetch\Handlers\FetchHandler::class => array( 'getAuthProvider' ), +); +foreach ( $methods as $class => $names ) { + foreach ( $names as $name ) { + $check( method_exists( $class, $name ), "{$class}::{$name}() is missing." ); + } +} + +$upsert = new ReflectionMethod( \DataMachine\Core\Database\TrackedItems\TrackedItems::class, 'upsert' ); +$check( 1 === $upsert->getNumberOfRequiredParameters(), 'TrackedItems::upsert() no longer takes a single row array.' ); + +if ( $failures ) { + fwrite( STDERR, implode( "\n", $failures ) . "\n" ); + exit( 1 ); +} + +echo "GitHub handler contract smoke passed.\n"; From 0fc853e9fcf19944412e00e910351f6678609afb Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sat, 28 Nov 2026 15:08:40 +0000 Subject: [PATCH 3/4] test(data-machine-github): load core in the contract smoke runtime --- .../tests/github-handler-contract-smoke.php | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/plugins/data-machine-github/tests/github-handler-contract-smoke.php b/plugins/data-machine-github/tests/github-handler-contract-smoke.php index b1e9f9b7e..0e15a3594 100644 --- a/plugins/data-machine-github/tests/github-handler-contract-smoke.php +++ b/plugins/data-machine-github/tests/github-handler-contract-smoke.php @@ -17,6 +17,16 @@ require_once $wp_path . '/wp-load.php'; } +// The runtime mounts core as a dependency without activating it. +if ( ! class_exists( \DataMachine\Core\Steps\Fetch\Handlers\FetchHandler::class ) ) { + $datamachine_core = WP_PLUGIN_DIR . '/data-machine/data-machine.php'; + if ( ! is_readable( $datamachine_core ) ) { + fwrite( STDERR, "Data Machine core is not available at {$datamachine_core}.\n" ); + exit( 1 ); + } + require_once $datamachine_core; +} + // The runtime may not activate this plugin; load it and register its handler directly. if ( ! function_exists( 'datamachine_github_load_handlers' ) ) { require_once dirname( __DIR__ ) . '/data-machine-github.php'; @@ -49,8 +59,8 @@ } } -$upsert = new ReflectionMethod( \DataMachine\Core\Database\TrackedItems\TrackedItems::class, 'upsert' ); -$check( 1 === $upsert->getNumberOfRequiredParameters(), 'TrackedItems::upsert() no longer takes a single row array.' ); +$upsert = ! class_exists( \DataMachine\Core\Database\TrackedItems\TrackedItems::class ) ? null : new ReflectionMethod( \DataMachine\Core\Database\TrackedItems\TrackedItems::class, 'upsert' ); +$check( $upsert && 1 === $upsert->getNumberOfRequiredParameters(), 'TrackedItems::upsert() no longer takes a single row array.' ); if ( $failures ) { fwrite( STDERR, implode( "\n", $failures ) . "\n" ); From 3ed6df5aa325b8cd07311c437b2558f46a902c7c Mon Sep 17 00:00:00 2001 From: Chris Huber Date: Sat, 28 Nov 2026 15:54:13 +0000 Subject: [PATCH 4/4] refactor(data-machine-business): move the GitHub fetch handler into business GitHub is a third-party integration like Slack, Discord and Google Sheets, so it ships as a data-machine-business provider module instead of its own plugin. Same code under DataMachineBusiness\, registered as the 'github' provider; the standalone plugin, workflow and boundary entry are removed. --- .github/workflows/data-machine-business.yml | 15 +++ .github/workflows/data-machine-github.yml | 98 ------------------- README.md | 9 +- plugins/data-machine-business/README.md | 5 + .../data-machine-business.php | 2 +- .../docs/github.md} | 0 plugins/data-machine-business/homeboy.json | 3 +- .../inc/Api/GitHubClient.php | 16 +-- .../inc/Bootstrap/ProviderModules.php | 6 ++ .../inc/Handlers/GitHub/GitHubFetch.php | 18 ++-- .../Handlers/GitHub/GitHubFetchSettings.php | 22 ++--- .../inc/OAuth/Providers/GitHubAuth.php | 8 +- .../tests/github-files-smoke.php | 16 ++- .../tests/github-handler-contract-smoke.php | 14 +-- .../tests/provider-bootstrap-smoke.php | 1 + plugins/data-machine-github/.gitignore | 40 -------- plugins/data-machine-github/README.md | 7 -- plugins/data-machine-github/composer.json | 20 ---- .../data-machine-github.php | 59 ----------- plugins/data-machine-github/homeboy.json | 36 ------- plugins/data-machine/README.md | 3 +- tools/check-boundaries.sh | 17 +--- 22 files changed, 90 insertions(+), 325 deletions(-) delete mode 100644 .github/workflows/data-machine-github.yml rename plugins/{data-machine-github/docs/github-files.md => data-machine-business/docs/github.md} (100%) rename plugins/{data-machine-github => data-machine-business}/inc/Api/GitHubClient.php (94%) rename plugins/{data-machine-github => data-machine-business}/inc/Handlers/GitHub/GitHubFetch.php (95%) rename plugins/{data-machine-github => data-machine-business}/inc/Handlers/GitHub/GitHubFetchSettings.php (67%) rename plugins/{data-machine-github => data-machine-business}/inc/OAuth/Providers/GitHubAuth.php (90%) rename plugins/{data-machine-github => data-machine-business}/tests/github-files-smoke.php (96%) rename plugins/{data-machine-github => data-machine-business}/tests/github-handler-contract-smoke.php (85%) delete mode 100644 plugins/data-machine-github/.gitignore delete mode 100644 plugins/data-machine-github/README.md delete mode 100644 plugins/data-machine-github/composer.json delete mode 100644 plugins/data-machine-github/data-machine-github.php delete mode 100644 plugins/data-machine-github/homeboy.json diff --git a/.github/workflows/data-machine-business.yml b/.github/workflows/data-machine-business.yml index 15ad35aa9..e6221abf5 100644 --- a/.github/workflows/data-machine-business.yml +++ b/.github/workflows/data-machine-business.yml @@ -27,6 +27,21 @@ permissions: issues: write jobs: + unit: + name: Unit (standalone PHP) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: shivammathur/setup-php@v2 + with: + php-version: '8.2' + tools: composer + # Stubs core's database classes, so it runs outside WordPress. + - name: Prepare in-tree Data Machine core + run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist + - name: GitHub files unit test + run: php plugins/data-machine-business/tests/github-files-smoke.php + homeboy: name: Homeboy (${{ matrix.command }}) runs-on: ubuntu-latest diff --git a/.github/workflows/data-machine-github.yml b/.github/workflows/data-machine-github.yml deleted file mode 100644 index 94b71342f..000000000 --- a/.github/workflows/data-machine-github.yml +++ /dev/null @@ -1,98 +0,0 @@ -name: data-machine-github - -on: - pull_request: - branches: [main] - paths: - - 'plugins/data-machine-github/**' - # Extensions run against the in-tree core, so a core change re-checks them. - - 'plugins/data-machine/**' - - '.github/workflows/data-machine-github.yml' - push: - branches: [main] - paths: - - 'plugins/data-machine-github/**' - # Extensions run against the in-tree core, so a core change re-checks them. - - 'plugins/data-machine/**' - - '.github/workflows/data-machine-github.yml' - workflow_dispatch: - -concurrency: - group: data-machine-github-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: ${{ github.event_name == 'pull_request' }} - -permissions: - contents: write - pull-requests: write - issues: write - -jobs: - unit: - name: Unit (standalone PHP) - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@v6 - - uses: shivammathur/setup-php@v2 - with: - php-version: '8.2' - tools: composer - # Stubs core's database classes, so it runs outside WordPress. - - name: Prepare in-tree Data Machine core - run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist - - name: GitHub files unit test - run: php plugins/data-machine-github/tests/github-files-smoke.php - - homeboy: - name: Homeboy (${{ matrix.command }}) - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - command: [review lint, review test] - services: - mysql: - image: mysql:8.0 - env: - MYSQL_ROOT_PASSWORD: '' - MYSQL_ALLOW_EMPTY_PASSWORD: 'yes' - MYSQL_DATABASE: homeboy_wptests - ports: - - 3306:3306 - options: >- - --health-cmd="mysqladmin ping" - --health-interval=10s - --health-timeout=5s - --health-retries=3 - steps: - - uses: actions/checkout@v6 - with: - fetch-depth: 0 - - - name: Generate app token - id: app-token - uses: actions/create-github-app-token@v3 - continue-on-error: true - with: - app-id: ${{ secrets.HOMEBOY_APP_ID }} - private-key: ${{ secrets.HOMEBOY_APP_PRIVATE_KEY }} - - - name: Prepare in-tree Data Machine core - run: composer install --working-dir=plugins/data-machine --no-dev --no-interaction --no-progress --prefer-dist --classmap-authoritative - - - name: Run Homeboy ${{ matrix.command }} - env: - HOMEBOY_SETTINGS_JSON: '{"database_type":"mysql","wp_codebox_database_service":{"provider":"external","engine":"mysql","allowed_hosts":["127.0.0.1:3306"],"secret_env":{"host":"WP_CODEBOX_DB_HOST","port":"WP_CODEBOX_DB_PORT","username":"WP_CODEBOX_DB_USER","password":"WP_CODEBOX_DB_PASSWORD"}},"wp_codebox_multisite":true,"wp_codebox_phpunit_bootstrap_mode":"managed"}' - HOMEBOY_WORDPRESS_DEPENDENCY_PATHS: ${{ github.workspace }}/plugins/data-machine - HOMEBOY_WORDPRESS_MULTISITE: '1' - WP_CODEBOX_DB_HOST: 127.0.0.1 - WP_CODEBOX_DB_PORT: '3306' - WP_CODEBOX_DB_USER: root - WP_CODEBOX_DB_PASSWORD: '' - uses: Extra-Chill/homeboy-action@v2 - with: - component: plugins/data-machine-github - comment-key: data-machine-github - commands: ${{ matrix.command }} - scope: ${{ matrix.command == 'review test' && 'full' || 'auto' }} - app-token: ${{ steps.app-token.outputs.token || '' }} - autofix: 'false' diff --git a/README.md b/README.md index 6712609ee..902998937 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ Click the badge above to try core in your browser. Nothing is installed, and not ## What's in this repository -One core plugin and four extensions built on it. Each is a separate WordPress plugin with its own version, releases and activation, so a site installs only what it needs. +One core plugin and three extensions built on it. Each is a separate WordPress plugin with its own version, releases and activation, so a site installs only what it needs. | Plugin | What it adds | |---|---| @@ -18,16 +18,15 @@ One core plugin and four extensions built on it. Each is a separate WordPress pl | [`data-machine-events`](plugins/data-machine-events) | **Events.** AI-assisted import from Ticketmaster, Eventbrite, ICS, venue websites and more, with deduplication, venue geocoding and a block-based calendar. | | [`data-machine-socials`](plugins/data-machine-socials) | **Social.** Publishing, reading and engagement across X, Facebook, Instagram, Threads, Bluesky, Mastodon, LinkedIn, Pinterest, Tumblr, TikTok, YouTube and Reddit. | | [`data-machine-business`](plugins/data-machine-business) | **Business.** Google Analytics, Search Console, Bing Webmaster Tools, PageSpeed, Google Sheets and Drive, Slack, Discord, Sendy, Mediavine, Amazon Associates and media maintenance, as abilities and agent tools. | -| [`data-machine-github`](plugins/data-machine-github) | **GitHub.** Fetch added, changed, and removed repository files into pipelines. | The extensions double as the reference for building your own: each registers handlers, abilities and tools through core's public hooks, the same way a third-party plugin would. ## How the pieces fit ```text -data-machine-events data-machine-socials data-machine-business data-machine-github - \ | / / - +---------- public hooks, abilities, handlers ----------------+ +data-machine-events data-machine-socials data-machine-business (your extension) + \ | / / + +---------- public hooks, abilities, handlers -------------+ | data-machine (core) pipelines, flows, jobs, memory, modes, tools, approvals diff --git a/plugins/data-machine-business/README.md b/plugins/data-machine-business/README.md index fe0f8f121..ddd92a98c 100644 --- a/plugins/data-machine-business/README.md +++ b/plugins/data-machine-business/README.md @@ -30,6 +30,7 @@ Data Machine Business connects WordPress automation, agents, and pipelines to an | Google Drive | List folders, export native Google files, download binaries, and feed files into pipelines | Abilities, fetch handler | | Slack | Fetch channel messages and publish messages or thread replies | Abilities, fetch/publish handlers | | Discord | Fetch channel messages and publish text or embeds | Abilities, fetch/publish handlers | +| GitHub | Fetch repository files, deduplicated by blob SHA, with removal tracking | Fetch handler (`github`) | | Amazon Associates | Search products and generate Creators API affiliate links | AI tool | | Sendy | Subscribe users, create or update campaigns, and read email-funnel metrics | Abilities | | Mediavine | Fetch page, aggregate, device, country, normalized-source, and ad-unit publisher revenue reports | Ability, WP-CLI | @@ -351,6 +352,10 @@ Create a Slack app with a bot token and grant the scopes needed by your flows: Add the bot to each channel it should access, then configure its `xoxb-...` token in Data Machine settings. +### GitHub + +A token is optional for public repositories. For private repositories, add a fine-grained token with read access to contents in the GitHub auth settings. See [docs/github.md](docs/github.md). + ### Discord Create a Discord application and bot, grant it Send Messages and Read Message History in the target channels, and configure the bot token in Data Machine settings. diff --git a/plugins/data-machine-business/data-machine-business.php b/plugins/data-machine-business/data-machine-business.php index e20418818..96ca2366b 100644 --- a/plugins/data-machine-business/data-machine-business.php +++ b/plugins/data-machine-business/data-machine-business.php @@ -2,7 +2,7 @@ /** * Plugin Name: Data Machine Business * Plugin URI: https://github.com/Extra-Chill/data-machine-business - * Description: Business and enterprise integrations for Data Machine. Adds support for Google Analytics, PageSpeed Insights, Google Sheets, Slack, Discord, and other business tools. + * Description: Business and enterprise integrations for Data Machine. Adds support for Google Analytics, PageSpeed Insights, Google Sheets, Slack, Discord, GitHub, and other business tools. * Version: 0.31.1 * Requires at least: 6.9 * Requires PHP: 8.2 diff --git a/plugins/data-machine-github/docs/github-files.md b/plugins/data-machine-business/docs/github.md similarity index 100% rename from plugins/data-machine-github/docs/github-files.md rename to plugins/data-machine-business/docs/github.md diff --git a/plugins/data-machine-business/homeboy.json b/plugins/data-machine-business/homeboy.json index 543ddc1fd..dd408b09f 100644 --- a/plugins/data-machine-business/homeboy.json +++ b/plugins/data-machine-business/homeboy.json @@ -12,7 +12,8 @@ "tests/data-machine-http-client-contract-smoke.php", "tests/google-analytics-aggregate-schema-smoke.php", "tests/google-analytics-tool-schema-smoke.php", - "tests/sendy-list-campaigns-schema-smoke.php" + "tests/sendy-list-campaigns-schema-smoke.php", + "tests/github-handler-contract-smoke.php" ] } } diff --git a/plugins/data-machine-github/inc/Api/GitHubClient.php b/plugins/data-machine-business/inc/Api/GitHubClient.php similarity index 94% rename from plugins/data-machine-github/inc/Api/GitHubClient.php rename to plugins/data-machine-business/inc/Api/GitHubClient.php index 2d1a0f41e..7573e0958 100644 --- a/plugins/data-machine-github/inc/Api/GitHubClient.php +++ b/plugins/data-machine-business/inc/Api/GitHubClient.php @@ -2,10 +2,10 @@ /** * Read-only GitHub REST client. * - * @package DataMachineGitHub + * @package DataMachineBusiness */ -namespace DataMachineGitHub\Api; +namespace DataMachineBusiness\Api; use DataMachine\Core\HttpClient; use WP_Error; @@ -48,7 +48,7 @@ public function get_recursive_tree( string $repo, string $sha ): array|WP_Error return $result; } if ( ! empty( $result['truncated'] ) ) { - return new WP_Error( 'github_tree_truncated', __( 'GitHub truncated the recursive tree. File changes cannot be determined from an incomplete tree.', 'data-machine-github' ) ); + return new WP_Error( 'github_tree_truncated', __( 'GitHub truncated the recursive tree. File changes cannot be determined from an incomplete tree.', 'data-machine-business' ) ); } if ( ! isset( $result['tree'] ) || ! is_array( $result['tree'] ) || ! array_is_list( $result['tree'] ) ) { return $this->invalid_response(); @@ -69,7 +69,7 @@ public function get_blob( string $repo, string $sha, int $max_bytes = 1048576 ): $result = $this->get( $repo, '/git/blobs/' . rawurlencode( $sha ), 3 * $max_bytes + 4096 ); $content = $this->decode_contents( $result ); if ( ! is_wp_error( $content ) && strlen( $content ) > $max_bytes ) { - return new WP_Error( 'github_blob_too_large', __( 'GitHub returned a blob larger than the configured file size limit.', 'data-machine-github' ) ); + return new WP_Error( 'github_blob_too_large', __( 'GitHub returned a blob larger than the configured file size limit.', 'data-machine-business' ) ); } return $content; } @@ -99,7 +99,7 @@ private function get_string( array|WP_Error $result, string $key ): string|WP_Er private function get( string $repo, string $endpoint = '', int $response_limit = 0 ): array|WP_Error { if ( ! preg_match( '#^[a-zA-Z0-9-]+/(?!\.{1,2}$)[a-zA-Z0-9_.-]+$#D', $repo ) ) { - return new WP_Error( 'github_invalid_repo', __( 'GitHub repo must be in owner/name format.', 'data-machine-github' ) ); + return new WP_Error( 'github_invalid_repo', __( 'GitHub repo must be in owner/name format.', 'data-machine-business' ) ); } $result = HttpClient::get( @@ -124,8 +124,8 @@ private function get( string $repo, string $endpoint = '', int $response_limit = if ( empty( $result['success'] ) || $status < 200 || $status >= 300 ) { $message = $status > 0 /* translators: %d: HTTP status code. */ - ? sprintf( __( 'GitHub API returned HTTP %d. Check repository access, branch or file references, and API rate limits.', 'data-machine-github' ), $status ) - : __( 'Could not connect to the GitHub API.', 'data-machine-github' ); + ? sprintf( __( 'GitHub API returned HTTP %d. Check repository access, branch or file references, and API rate limits.', 'data-machine-business' ), $status ) + : __( 'Could not connect to the GitHub API.', 'data-machine-business' ); return new WP_Error( 'github_api_error', $message, array( 'status' => $status ) ); } @@ -134,6 +134,6 @@ private function get( string $repo, string $endpoint = '', int $response_limit = } private function invalid_response(): WP_Error { - return new WP_Error( 'github_invalid_response', __( 'GitHub API returned an invalid or unsupported response.', 'data-machine-github' ) ); + return new WP_Error( 'github_invalid_response', __( 'GitHub API returned an invalid or unsupported response.', 'data-machine-business' ) ); } } diff --git a/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php b/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php index d5cf526df..f53aa56a3 100644 --- a/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php +++ b/plugins/data-machine-business/inc/Bootstrap/ProviderModules.php @@ -177,6 +177,12 @@ static function (): void { new \DataMachineBusiness\Handlers\Discord\DiscordFetch(); } ), + new ProviderModule( + 'github', + $fetch_handlers, + array( 'handler:github' ), + static fn() => new \DataMachineBusiness\Handlers\GitHub\GitHubFetch() + ), new ProviderModule( 'bing-webmaster', array_merge( $abilities, $tools ), diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php similarity index 95% rename from plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php rename to plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php index f7fd738fd..805ddc3ba 100644 --- a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetch.php +++ b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetch.php @@ -2,17 +2,17 @@ /** * Fetch repository files and report deletions from complete GitHub trees. * - * @package DataMachineGitHub + * @package DataMachineBusiness */ -namespace DataMachineGitHub\Handlers\GitHub; +namespace DataMachineBusiness\Handlers\GitHub; use DataMachine\Core\Database\TrackedItems\TrackedItems; use DataMachine\Core\ExecutionContext; use DataMachine\Core\Steps\Fetch\Handlers\FetchHandler; use DataMachine\Core\Steps\HandlerRegistrationTrait; -use DataMachineGitHub\Api\GitHubClient; -use DataMachineGitHub\OAuth\Providers\GitHubAuth; +use DataMachineBusiness\Api\GitHubClient; +use DataMachineBusiness\OAuth\Providers\GitHubAuth; use WP_Error; defined( 'ABSPATH' ) || exit; @@ -28,8 +28,8 @@ public function __construct() { 'github', 'fetch', self::class, - __( 'GitHub Files', 'data-machine-github' ), - __( 'Fetch files from a GitHub repository. A token is optional for public repositories.', 'data-machine-github' ), + __( 'GitHub Files', 'data-machine-business' ), + __( 'Fetch files from a GitHub repository. A token is optional for public repositories.', 'data-machine-business' ), true, GitHubAuth::class, GitHubFetchSettings::class, @@ -124,7 +124,7 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr return new WP_Error( 'github_missing_file_path', /* translators: %s: configured repository path. */ - sprintf( __( 'GitHub file_path "%s" does not exist in the repository tree.', 'data-machine-github' ), $prefix ) + sprintf( __( 'GitHub file_path "%s" does not exist in the repository tree.', 'data-machine-business' ), $prefix ) ); } @@ -183,7 +183,7 @@ protected function executeFetch( array $config, ExecutionContext $context ): arr 'metadata' => $state, ) ) ) { - return new WP_Error( 'github_snapshot_error', __( 'Could not save the GitHub file snapshot for this flow step.', 'data-machine-github' ) ); + return new WP_Error( 'github_snapshot_error', __( 'Could not save the GitHub file snapshot for this flow step.', 'data-machine-business' ) ); } return array( 'items' => $items ); @@ -230,7 +230,7 @@ private function file_item( string $repo, string $branch, string $commit, string return array( 'title' => 'removed' === $change /* translators: %s: removed repository path. */ - ? sprintf( __( 'Removed: %s', 'data-machine-github' ), $path ) + ? sprintf( __( 'Removed: %s', 'data-machine-business' ), $path ) : $path, 'content' => '', 'metadata' => array( diff --git a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php similarity index 67% rename from plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php rename to plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php index 56dfced41..ec04c731f 100644 --- a/plugins/data-machine-github/inc/Handlers/GitHub/GitHubFetchSettings.php +++ b/plugins/data-machine-business/inc/Handlers/GitHub/GitHubFetchSettings.php @@ -2,10 +2,10 @@ /** * Settings for the GitHub files fetch handler. * - * @package DataMachineGitHub + * @package DataMachineBusiness */ -namespace DataMachineGitHub\Handlers\GitHub; +namespace DataMachineBusiness\Handlers\GitHub; use DataMachine\Core\Steps\Settings\SettingsHandler; @@ -20,28 +20,28 @@ public static function get_fields(): array { return array( 'repo' => array( 'type' => 'text', - 'label' => __( 'Repository', 'data-machine-github' ), - 'description' => __( 'GitHub repository in owner/name format.', 'data-machine-github' ), + 'label' => __( 'Repository', 'data-machine-business' ), + 'description' => __( 'GitHub repository in owner/name format.', 'data-machine-business' ), 'required' => true, ), 'branch' => array( 'type' => 'text', - 'label' => __( 'Branch', 'data-machine-github' ), - 'description' => __( 'Leave blank to use the repository default branch.', 'data-machine-github' ), + 'label' => __( 'Branch', 'data-machine-business' ), + 'description' => __( 'Leave blank to use the repository default branch.', 'data-machine-business' ), ), 'file_path' => array( 'type' => 'text', - 'label' => __( 'File Path', 'data-machine-github' ), - 'description' => __( 'Limit to a file or directory path. Leave blank for the entire repository.', 'data-machine-github' ), + 'label' => __( 'File Path', 'data-machine-business' ), + 'description' => __( 'Limit to a file or directory path. Leave blank for the entire repository.', 'data-machine-business' ), ), 'file_pattern' => array( 'type' => 'text', - 'label' => __( 'File Pattern', 'data-machine-github' ), - 'description' => __( 'Optional glob, e.g. *.md. Patterns without a slash match filenames at any depth.', 'data-machine-github' ), + 'label' => __( 'File Pattern', 'data-machine-business' ), + 'description' => __( 'Optional glob, e.g. *.md. Patterns without a slash match filenames at any depth.', 'data-machine-business' ), ), 'max_file_size' => array( 'type' => 'number', - 'label' => __( 'Maximum File Size (bytes)', 'data-machine-github' ), + 'label' => __( 'Maximum File Size (bytes)', 'data-machine-business' ), 'default' => self::DEFAULT_MAX_FILE_SIZE, 'min' => 1, 'max' => self::MAX_FILE_SIZE, diff --git a/plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php b/plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php similarity index 90% rename from plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php rename to plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php index ce1587495..3256ddbcd 100644 --- a/plugins/data-machine-github/inc/OAuth/Providers/GitHubAuth.php +++ b/plugins/data-machine-business/inc/OAuth/Providers/GitHubAuth.php @@ -2,10 +2,10 @@ /** * GitHub personal access token provider (no OAuth flow). * - * @package DataMachineGitHub + * @package DataMachineBusiness */ -namespace DataMachineGitHub\OAuth\Providers; +namespace DataMachineBusiness\OAuth\Providers; use DataMachine\Core\OAuth\BaseAuthProvider; @@ -20,10 +20,10 @@ public function __construct() { public function get_config_fields(): array { return array( 'access_token' => array( - 'label' => __( 'Personal Access Token', 'data-machine-github' ), + 'label' => __( 'Personal Access Token', 'data-machine-business' ), 'type' => 'password', 'required' => false, - 'description' => __( 'Optional for public repositories. For private repositories, grant read access to repository contents.', 'data-machine-github' ), + 'description' => __( 'Optional for public repositories. For private repositories, grant read access to repository contents.', 'data-machine-business' ), ), ); } diff --git a/plugins/data-machine-github/tests/github-files-smoke.php b/plugins/data-machine-business/tests/github-files-smoke.php similarity index 96% rename from plugins/data-machine-github/tests/github-files-smoke.php rename to plugins/data-machine-business/tests/github-files-smoke.php index 14327c65f..b2b76681e 100644 --- a/plugins/data-machine-github/tests/github-files-smoke.php +++ b/plugins/data-machine-business/tests/github-files-smoke.php @@ -3,7 +3,7 @@ * Exercise the real HTTP client and fetch pipeline with in-memory WP transport and storage. * Run with: php tests/github-files-smoke.php * - * @package DataMachineGitHub\Tests + * @package DataMachineBusiness\Tests */ namespace DataMachine\Core\Database\ProcessedItems { @@ -51,7 +51,7 @@ public static function recordStepResult( ...$args ): bool { namespace { use DataMachine\Core\Database\ProcessedItems\ProcessedItems; - use DataMachineGitHub\Api\GitHubClient; + use DataMachineBusiness\Api\GitHubClient; define( 'ABSPATH', __DIR__ ); define( 'WPINC', 'wp-includes' ); @@ -79,7 +79,7 @@ function plugin_dir_path( $file ) { return dirname( $file ) . '/'; } function plugin_dir_url( $file ) { - return 'https://example.test/wp-content/plugins/data-machine-github/'; + return 'https://example.test/wp-content/plugins/data-machine-business/'; } function home_url() { return 'https://example.test'; @@ -157,6 +157,13 @@ function check( $condition, $message ) { $core = getenv( 'DATA_MACHINE_PATH' ) ?: dirname( __DIR__, 2 ) . '/data-machine'; spl_autoload_register( static function ( $class ) use ( $core ) { + if ( str_starts_with( $class, 'DataMachineBusiness\\' ) ) { + $file = dirname( __DIR__ ) . '/inc/' . str_replace( '\\', '/', substr( $class, strlen( 'DataMachineBusiness\\' ) ) ) . '.php'; + if ( is_file( $file ) ) { + require $file; + } + return; + } if ( str_starts_with( $class, 'DataMachine\\' ) ) { $file = $core . '/inc/' . str_replace( '\\', '/', substr( $class, strlen( 'DataMachine\\' ) ) ) . '.php'; if ( is_file( $file ) ) { @@ -165,8 +172,7 @@ static function ( $class ) use ( $core ) { } } ); - require dirname( __DIR__ ) . '/data-machine-github.php'; - do_action( 'plugins_loaded' ); + new DataMachineBusiness\Handlers\GitHub\GitHubFetch(); $registration = apply_filters( 'datamachine_handlers', array(), 'fetch' )['github']; check( 'files' === $registration['meta']['data_source'], 'GitHub files source was not registered.' ); $handler = new $registration['class'](); diff --git a/plugins/data-machine-github/tests/github-handler-contract-smoke.php b/plugins/data-machine-business/tests/github-handler-contract-smoke.php similarity index 85% rename from plugins/data-machine-github/tests/github-handler-contract-smoke.php rename to plugins/data-machine-business/tests/github-handler-contract-smoke.php index 0e15a3594..8776c9377 100644 --- a/plugins/data-machine-github/tests/github-handler-contract-smoke.php +++ b/plugins/data-machine-business/tests/github-handler-contract-smoke.php @@ -5,7 +5,7 @@ * github-files-smoke.php covers behavior with stubbed database classes; this * checks that the core APIs the handler relies on exist with those shapes. * - * @package DataMachineGitHub + * @package DataMachineBusiness */ $wp_path = getenv( 'WP_PATH' ); @@ -27,12 +27,12 @@ require_once $datamachine_core; } -// The runtime may not activate this plugin; load it and register its handler directly. -if ( ! function_exists( 'datamachine_github_load_handlers' ) ) { - require_once dirname( __DIR__ ) . '/data-machine-github.php'; -} +// The runtime may not activate this plugin; register its handler directly. if ( ! isset( apply_filters( 'datamachine_handlers', array(), 'fetch' )['github'] ) ) { - datamachine_github_load_handlers(); + if ( ! defined( 'DATAMACHINE_BUSINESS_VERSION' ) ) { + require_once dirname( __DIR__ ) . '/data-machine-business.php'; + } + new \DataMachineBusiness\Handlers\GitHub\GitHubFetch(); } $failures = array(); @@ -45,7 +45,7 @@ $handlers = apply_filters( 'datamachine_handlers', array(), 'fetch' ); $github = $handlers['github'] ?? null; $check( is_array( $github ), 'The github fetch handler is not registered.' ); -$check( ( $github['class'] ?? '' ) === \DataMachineGitHub\Handlers\GitHub\GitHubFetch::class, 'The github handler class is wrong.' ); +$check( ( $github['class'] ?? '' ) === \DataMachineBusiness\Handlers\GitHub\GitHubFetch::class, 'The github handler class is wrong.' ); $check( ( $github['meta']['data_source'] ?? '' ) === 'files', 'The github handler does not declare the files data source.' ); $methods = array( diff --git a/plugins/data-machine-business/tests/provider-bootstrap-smoke.php b/plugins/data-machine-business/tests/provider-bootstrap-smoke.php index 7de887886..b23469c2c 100644 --- a/plugins/data-machine-business/tests/provider-bootstrap-smoke.php +++ b/plugins/data-machine-business/tests/provider-bootstrap-smoke.php @@ -111,6 +111,7 @@ static function (): void { 'google-search-console', 'slack', 'discord', + 'github', 'bing-webmaster', 'amazon-affiliate', 'media-hygiene', diff --git a/plugins/data-machine-github/.gitignore b/plugins/data-machine-github/.gitignore deleted file mode 100644 index 63cadcba7..000000000 --- a/plugins/data-machine-github/.gitignore +++ /dev/null @@ -1,40 +0,0 @@ -# WordPress Plugin .gitignore - -# System files -.DS_Store -Thumbs.db -desktop.ini - -# IDE files -.vscode/ -.idea/ -*.swp -*.swo -*~ - -# Dependencies -vendor/ -node_modules/ - -# Log files -*.log - -# Temporary files -*.tmp -*.temp -*.cache - -# Backup files -*.bak -*.backup - -# Build artifacts -build/ -dist/ - -# Plugin specific -*.zip -*.tar.gz - -# Composer -composer.lock diff --git a/plugins/data-machine-github/README.md b/plugins/data-machine-github/README.md deleted file mode 100644 index 022db75c5..000000000 --- a/plugins/data-machine-github/README.md +++ /dev/null @@ -1,7 +0,0 @@ -# Data Machine GitHub - -Fetch files from public or private GitHub repositories into [Data Machine](../data-machine) pipelines. The **GitHub Files** fetch handler reports additions, modifications, and removals so downstream steps can publish, update, or unpublish content. - -Activate Data Machine and Data Machine GitHub, then add a **GitHub Files** fetch step and set `repo` to `owner/name`. Public repositories work without credentials. For private repositories, save a GitHub personal access token under **Data Machine → Settings → Auth Providers**. - -See [GitHub Files fetch handler](docs/github-files.md) for configuration and the packet contract. diff --git a/plugins/data-machine-github/composer.json b/plugins/data-machine-github/composer.json deleted file mode 100644 index 9d4dfdec0..000000000 --- a/plugins/data-machine-github/composer.json +++ /dev/null @@ -1,20 +0,0 @@ -{ - "name": "extra-chill/data-machine-github", - "description": "GitHub file fetch integration for Data Machine", - "version": "0.1.0", - "license": "GPL-2.0-or-later", - "require": { - "php": ">=8.2" - }, - "autoload": { - "psr-4": { - "DataMachineGitHub\\": "inc/" - } - }, - "authors": [ - { - "name": "Chris Huber", - "email": "chris@chubes.net" - } - ] -} diff --git a/plugins/data-machine-github/data-machine-github.php b/plugins/data-machine-github/data-machine-github.php deleted file mode 100644 index 601101524..000000000 --- a/plugins/data-machine-github/data-machine-github.php +++ /dev/null @@ -1,59 +0,0 @@ -

' . esc_html__( 'Data Machine GitHub requires the Data Machine core plugin to be active.', 'data-machine-github' ) . '

'; - } - ); - return; - } - - new \DataMachineGitHub\Handlers\GitHub\GitHubFetch(); -} - -add_action( 'plugins_loaded', 'datamachine_github_load_handlers', 20 ); diff --git a/plugins/data-machine-github/homeboy.json b/plugins/data-machine-github/homeboy.json deleted file mode 100644 index 7a567830c..000000000 --- a/plugins/data-machine-github/homeboy.json +++ /dev/null @@ -1,36 +0,0 @@ -{ - "auto_cleanup": false, - "changelog_target": "docs/CHANGELOG.md", - "extensions": { - "wordpress": { - "php": "8.2", - "settings": { - "validation_dependencies": [ - "../data-machine" - ], - "wordpress_test_paths": [ - "tests/github-handler-contract-smoke.php" - ] - } - } - }, - "id": "data-machine-github", - "remote_path": "wp-content/plugins/data-machine-github", - "version_targets": [ - { - "file": "data-machine-github.php", - "pattern": "(?m)^\\s*\\*?\\s*Version:\\s*([0-9.]+)" - }, - { - "file": "data-machine-github.php", - "pattern": "DATAMACHINE_GITHUB_VERSION',\\s*'([0-9.]+)'" - }, - { - "file": "composer.json", - "pattern": "\"version\":\\s*\"([0-9.]+)\"" - } - ], - "github": { - "release_latest": false - } -} diff --git a/plugins/data-machine/README.md b/plugins/data-machine/README.md index c97691777..63e3588a3 100644 --- a/plugins/data-machine/README.md +++ b/plugins/data-machine/README.md @@ -109,7 +109,7 @@ Typed, permissioned functions registered via WordPress's Abilities API. Extensio | `datamachine/run-flow` | Execute a flow programmatically | | ... | Additional core abilities across pipelines, flows, jobs, memory, media, SEO, email, and infrastructure | -Social publishing, workspace, GitHub, and business integrations live in extension plugins such as data-machine-socials, data-machine-code, data-machine-github, and data-machine-business. +Social publishing, workspace, GitHub, and business integration abilities live in extension plugins such as data-machine-socials, data-machine-code, and data-machine-business. ### Agent Bundles @@ -265,7 +265,6 @@ Detailed endpoint docs live under [`docs/api/`](docs/api/). Routes under `wp-jso | [data-machine-code](https://github.com/Extra-Chill/data-machine-code) | Workspace management, GitHub integration, git operations | | [data-machine-socials](../data-machine-socials) | Publish to Instagram (images, carousels, Reels, Stories), Twitter (text + media + video), Facebook, Threads, Bluesky, Pinterest (image + video pins). Reddit fetch. | | [data-machine-business](../data-machine-business) | Google Sheets (fetch + publish), Slack, Discord integrations | -| [data-machine-github](../data-machine-github) | Fetch added, modified, and removed files from GitHub repositories | | [data-machine-editor](https://github.com/Extra-Chill/data-machine-editor) | Gutenberg inline diff visualization, accept/reject review, editor sidebar | | [data-machine-frontend-chat](https://github.com/Extra-Chill/data-machine-frontend-chat) | Floating agent chat widget for any WordPress site | | [data-machine-chat-bridge](https://github.com/Extra-Chill/data-machine-chat-bridge) | Message queue, webhook delivery, and REST API for external chat clients | diff --git a/tools/check-boundaries.sh b/tools/check-boundaries.sh index 1f007cade..587e5325a 100755 --- a/tools/check-boundaries.sh +++ b/tools/check-boundaries.sh @@ -20,23 +20,16 @@ set -euo pipefail root="$(git rev-parse --show-toplevel)" cd "${root}" -extensions=(events socials business github) +extensions=(events socials business) allowlist="tools/boundary-allowlist.txt" # Identifiers owned by the given extensions, e.g. "events socials". pattern_for() { - local names=("$@") lower title ext constant constants=() + local names=("$@") lower upper title lower="$(IFS='|'; echo "${names[*]}")" - title="$(echo "${lower}" | sed -E 's/(^|\|)([a-z])/\1\u\2/g; s/Github/GitHub/g')" - for ext in "${names[@]}"; do - constant="${ext^^}_" - if [[ "${ext}" == github ]]; then - # DATAMACHINE_GITHUB_TOKEN already belongs to core's bundle downloader. - constant='GITHUB_(VERSION|PATH|URL)\b' - fi - constants+=("${constant}") - done - printf '%s' "DataMachine(${title})\\\\|DATAMACHINE_($(IFS='|'; echo "${constants[*]}"))|data-machine-(${lower})/|data_?machine_?(${lower})\\b|plugins/data-machine-(${lower})" + upper="$(echo "${lower}" | tr '[:lower:]' '[:upper:]')" + title="$(echo "${lower}" | sed -E 's/(^|\|)([a-z])/\1\u\2/g')" + printf '%s' "DataMachine(${title})\\\\|DATAMACHINE_(${upper})_|data-machine-(${lower})/|data_?machine_?(${lower})\\b|plugins/data-machine-(${lower})" } # Code only: docs, changelogs and READMEs may describe the ecosystem.