github

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 30, 2026 License: EUPL-1.2 Imports: 12 Imported by: 0

Documentation

Overview

Package github implements infrastructure adapters for GitHub CLI operations.

The github package provides concrete implementations of the OperationProvider port defined in the domain layer, enabling workflow steps to perform declarative GitHub operations (issue retrieval, PR creation) without shell scripting or jq parsing. The provider uses gh CLI as the execution backend.

Architecture Role

In the hexagonal architecture:

  • Implements domain/ports.OperationProvider (GitHubOperationProvider adapter)
  • Registers 8 GitHub operations via OperationRegistry at startup
  • Application layer orchestrates operation steps via the OperationProvider port
  • Domain layer defines operation contracts without GitHub coupling

All GitHub-specific types remain internal to this infrastructure adapter. The domain layer reuses existing OperationSchema, OperationResult, and InputSchema types without requiring new entities. This prevents domain layer pollution while maintaining full compile-time type safety.

Operation Types

## Declarative Operations (operations.go)

Supported GitHub operations:

  • github.get_issue: Retrieve issue metadata (title, body, labels, state)
  • github.get_pr: Retrieve pull request metadata
  • github.create_issue: Create new issue with title, body, labels
  • github.create_pr: Create pull request with title, body, base, head
  • github.add_labels: Add labels to issue or PR
  • github.list_comments: Retrieve issue/PR comments
  • github.add_comment: Add comment to issue or PR
  • github.batch: Execute multiple GitHub operations with concurrency control

Each operation is registered as an OperationSchema with input validation, output schema, and field selection support (FR-002).

Provider Implementation

## GitHubOperationProvider (provider.go)

Operation execution and dispatch:

  • ListOperations: Enumerate registered GitHub operations
  • GetOperation: Retrieve operation schema by name
  • Execute: Dispatch to operation handler based on operation type

The provider uses a central dispatch method with switch-case routing to operation handlers. This keeps all GitHub logic in one cohesive package without requiring interface-per-operation abstractions (ADR-003).

## BatchExecutor (batch.go)

Batch operation processing:

  • Execute: Run multiple GitHub operations with configurable concurrency
  • Strategies: all_succeed, any_succeed, best_effort (US4)
  • Uses golang.org/x/sync/errgroup with semaphore for concurrency control
  • Returns aggregate result with success/failure counts

Batch execution reuses the proven errgroup + semaphore pattern from AWF's parallel step execution (ADR-004).

Client and Authentication

## GitHubClient (client.go)

Backend execution layer:

  • RunGH: Invoke gh CLI with context cancellation via os/exec
  • DetectRepo: Auto-detect repository from git remote URL parsing (uses sync.Once for thread safety)

Uses os/exec for gh CLI invocation. Retry logic for rate limiting is planned but not yet implemented.

## AuthManager (auth.go)

Authentication resolution:

  • DetectAuth: Determine active auth method (gh CLI, GITHUB_TOKEN, none)
  • Priority chain: gh auth status > GITHUB_TOKEN env var > none

Error Handling

Operations return standard Go errors via fmt.Errorf with contextual messages.

Planned: Structured error types for common GitHub failures:

  • github_not_found: Issue/PR does not exist
  • github_auth_error: Authentication failed or missing
  • github_branch_not_found: Head/base branch missing
  • github_rate_limit: Rate limit exceeded
  • github_invalid_field: Invalid project field value

Current implementation wraps errors with fmt.Errorf for basic error context.

Integration Points

## CLI Wiring (internal/interfaces/cli/run.go)

Provider registration at startup:

  • Create GitHubOperationProvider instance
  • Register operations via OperationRegistry
  • Connect to ExecutionService via SetOperationProvider()
  • Follows F039 agent registry wiring pattern

The provider is instantiated in the composition root (run.go) and injected into the application layer via dependency inversion. This enables compile-time wiring without RPC overhead (ADR-001).

Performance and Security

Performance characteristics:

  • Batch concurrency: Planned with configurable concurrency limit
  • Rate limiting: Planned integration with pkg/retry

Security measures:

  • AuthMethod.String() masks tokens in logs (returns "token(***)")
  • DetectAuth never logs token values
  • Input validation prevents command injection via gh CLI argument structure
  • Field selection support planned to limit output size and exposure

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AllOperations

func AllOperations() []pluginmodel.OperationSchema

AllOperations returns all 8 GitHub operation schemas that can be registered with the OperationRegistry. Each operation defines its input/output schema, validation rules, and field selection support.

Operations are organized by priority tier (P1, P2, P3) matching the spec:

  • P1 (Must Have): get_issue, get_pr, create_pr, create_issue
  • P2 (Should Have): add_labels, list_comments, add_comment, batch

Types

type AuthMethod

type AuthMethod struct {
	// Type identifies the authentication method: "gh_cli", "token", or "none"
	Type string

	// Token stores the authentication token when Type is "token"
	// Empty for "gh_cli" and "none" types
	Token string
}

AuthMethod represents the authentication method used for GitHub API access. Supports three-tier authentication chain: gh CLI > GITHUB_TOKEN > none.

func DetectAuth

func DetectAuth(ctx context.Context) (AuthMethod, error)

DetectAuth determines the active GitHub authentication method. Priority chain: gh CLI > GITHUB_TOKEN environment variable > none.

Returns:

  • AuthMethod{Type: "gh_cli"} if gh CLI is authenticated
  • AuthMethod{Type: "token", Token: value} if GITHUB_TOKEN is set
  • AuthMethod{Type: "none"} if no auth available
  • error with remediation hints if detection fails

func (AuthMethod) IsAuthenticated

func (a AuthMethod) IsAuthenticated() bool

IsAuthenticated returns true if the auth method can authenticate GitHub API requests. Returns false for Type "none".

func (AuthMethod) String

func (a AuthMethod) String() string

String returns a log-safe string representation of the auth method. Never exposes tokens or secrets.

type BatchConfig

type BatchConfig struct {
	// Strategy determines failure handling: "all_succeed", "any_succeed", "best_effort"
	Strategy string
	// MaxConcurrent limits parallel operation execution (default: 3)
	MaxConcurrent int
}

BatchConfig defines configuration for batch execution.

type BatchExecutor

type BatchExecutor struct {
	// contains filtered or unexported fields
}

BatchExecutor handles batch execution of GitHub operations with configurable concurrency and execution strategies (all_succeed, any_succeed, best_effort).

Follows the proven errgroup + semaphore pattern from AWF's ParallelExecutor. See ADR-004 in the implementation plan for rationale.

func NewBatchExecutor

func NewBatchExecutor(provider *GitHubOperationProvider, logger ports.Logger) *BatchExecutor

NewBatchExecutor creates a new batch executor for GitHub operations.

Parameters:

  • provider: GitHub operation provider for executing individual operations
  • logger: structured logger for operation tracing

Returns:

  • *BatchExecutor: configured executor ready for batch processing

func (*BatchExecutor) Execute

func (e *BatchExecutor) Execute(
	ctx context.Context,
	operations []map[string]any,
	config BatchConfig,
) (*BatchResult, error)

Execute runs multiple GitHub operations in batch according to the configured strategy.

Parameters:

  • ctx: context for cancellation and timeout
  • operations: array of operation definitions (each contains name and inputs)
  • config: batch execution configuration (strategy, concurrency)

Returns:

  • *BatchResult: aggregate results with success/failure counts
  • error: returns error if strategy is "all_succeed" and any operation fails

Strategies:

  • all_succeed: cancel remaining on first failure (errgroup.WithContext)
  • any_succeed: return success if at least one operation succeeds
  • best_effort: complete all operations regardless of individual failures (default)

type BatchResult

type BatchResult struct {
	Total     int                            // Total operations attempted
	Succeeded int                            // Successfully completed operations
	Failed    int                            // Failed operations
	Results   []*pluginmodel.OperationResult // Individual operation results
}

BatchResult represents the aggregate result of batch execution.

type Client

type Client struct {
	// contains filtered or unexported fields
}

Client wraps GitHub API interactions via gh CLI and HTTP API with authentication fallback. Provides structured JSON output parsing and automatic repository detection.

func NewClient

func NewClient(logger ports.Logger) *Client

NewClient creates a new GitHub client with the provided logger.

Parameters:

  • logger: structured logger for client operations

Returns:

  • *Client: configured GitHub client ready for use

func (*Client) DetectRepo

func (c *Client) DetectRepo(ctx context.Context) (string, error)

DetectRepo determines the GitHub repository from git remote configuration. Parses git remote URL to extract owner/repo.

Parameters:

  • ctx: context for cancellation and timeout control

Returns:

  • string: repository in "owner/repo" format
  • error: git command error or parsing error

func (*Client) RunGH

func (c *Client) RunGH(ctx context.Context, args []string) ([]byte, error)

RunGH executes a gh CLI command and returns the raw stdout output.

Parameters:

  • ctx: context for cancellation and timeout control
  • args: command arguments to pass to gh CLI (e.g., ["pr", "create", "--title", "..."])

Returns:

  • []byte: stdout output from gh CLI
  • error: execution error

type GHRunner

type GHRunner interface {
	RunGH(ctx context.Context, args []string) ([]byte, error)
}

GHRunner abstracts GitHub CLI command execution for testability. Production code uses *Client; tests use mockGHRunner.

type GitHubOperationProvider

type GitHubOperationProvider struct {
	// contains filtered or unexported fields
}

GitHubOperationProvider implements ports.OperationProvider for GitHub operations. Dispatches to operation-specific handlers for the 8 GitHub operation types.

Operations are organized by priority tier:

  • P1 (Must Have): get_issue, get_pr, create_pr, create_issue
  • P2 (Should Have): add_labels, list_comments, add_comment, batch

func NewGitHubOperationProvider

func NewGitHubOperationProvider(runner GHRunner, logger ports.Logger) *GitHubOperationProvider

func (*GitHubOperationProvider) Execute

Execute runs a GitHub operation by name with the given inputs. Dispatches to operation-specific handler methods based on operation name.

Implements ports.OperationProvider.

func (*GitHubOperationProvider) GetOperation

func (*GitHubOperationProvider) ListOperations

func (p *GitHubOperationProvider) ListOperations() []*pluginmodel.OperationSchema

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL