Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions .github/workflows/data-machine-business.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 5 additions & 0 deletions plugins/data-machine-business/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion plugins/data-machine-business/data-machine-business.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
42 changes: 42 additions & 0 deletions plugins/data-machine-business/docs/github.md
Original file line number Diff line number Diff line change
@@ -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_<repo>_files_<path>_<blobsha>`, 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.
3 changes: 2 additions & 1 deletion plugins/data-machine-business/homeboy.json
Original file line number Diff line number Diff line change
Expand Up @@ -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"
]
}
}
Expand Down
139 changes: 139 additions & 0 deletions plugins/data-machine-business/inc/Api/GitHubClient.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,139 @@
<?php
/**
* Read-only GitHub REST client.
*
* @package DataMachineBusiness
*/

namespace DataMachineBusiness\Api;

use DataMachine\Core\HttpClient;
use WP_Error;

defined( 'ABSPATH' ) || exit;

final class GitHubClient {

public function __construct( private readonly string $token = '' ) {}

public static function encode_path( string $path ): string {
return implode( '/', array_map( 'rawurlencode', explode( '/', $path ) ) );
}

public function get_default_branch( string $repo ): string|WP_Error {
return $this->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-business' ) );
}
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-business' ) );
}
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-business' ) );
}

$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-business' ), $status )
: __( 'Could not connect to the GitHub API.', 'data-machine-business' );
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-business' ) );
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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 ),
Expand Down
Loading
Loading