github

package
v0.0.50 Latest Latest
Warning

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

Go to latest
Published: Apr 10, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultPageSize      = 100
	DefaultBufferSize    = 100
	MaxPageSize          = 1000
	ProgressThreshold    = 0.1 // Send progress every 10% completion
	MaxProgressEvents    = 20  // Maximum progress events per operation
	MaxWaitTime          = 30 * time.Minute
	DefaultRetryAttempts = 3
	DefaultRetryDelay    = 1 * time.Second
	EventSendTimeout     = 100 * time.Millisecond // Max time to wait for event sending
	RateLimitWarning     = 100                    // Warn when rate limit falls below this threshold
)

Production configuration constants

Variables

This section is empty.

Functions

func CalculateBackoffDelay

func CalculateBackoffDelay(attempt int, baseDelay time.Duration) time.Duration

CalculateBackoffDelay implements exponential backoff with jitter for retry operations. Calculates increasing delays for successive retry attempts with a maximum cap to prevent excessively long waits during transient failures.

func EstimatePageCapacity

func EstimatePageCapacity(itemSize, targetMemoryMB int) int

EstimatePageCapacity calculates optimal pagination size based on target memory usage. Takes estimated item size and target memory in MB, returns bounded capacity between reasonable minimum and maximum values for efficient memory utilization.

func ExampleFileOperations

func ExampleFileOperations()

ExampleFileOperations demonstrates file operations

func ExamplePullRequestWorkflow

func ExamplePullRequestWorkflow()

ExamplePullRequestWorkflow demonstrates a typical PR workflow

func ExampleSessionMetadata

func ExampleSessionMetadata()

ExampleSessionMetadata demonstrates session metadata usage

func ExampleUsage

func ExampleUsage()

ExampleUsage demonstrates how to use the GitHub service

func ExampleWithEventStreaming

func ExampleWithEventStreaming()

ExampleWithEventStreaming demonstrates event streaming

func FetchCreate

func FetchCreate[T any, R any](
	ctx context.Context,
	rh *RequestHandler,
	fetcher ResourceSingleFetcher[T],
	converter ResourceConverter[T, R],
	operation string,
) (R, error)

FetchCreate is an alias for FetchSingle optimized for creation operations. Provides the same production-ready features with naming that reflects the semantic intent of creating new GitHub resources.

func FetchPaginated

func FetchPaginated[T any, R any](
	ctx context.Context,
	rh *RequestHandler,
	fetcher ResourceFetcher[T],
	converter ResourceConverter[T, R],
	config *PaginationConfig,
	operation string,
) ([]R, error)

FetchPaginated performs production-ready paginated fetching with intelligent memory management, progress reporting, and context cancellation support. Uses bounded allocations, optimizes final capacity, and provides comprehensive error handling.

func FetchSingle

func FetchSingle[T any, R any](
	ctx context.Context,
	rh *RequestHandler,
	fetcher ResourceSingleFetcher[T],
	converter ResourceConverter[T, R],
	operation string,
) (R, error)

FetchSingle performs production-ready single item fetching with comprehensive validation, context cancellation support, and structured error handling. Validates all inputs and provides type-safe conversion of results.

func LogCritical

func LogCritical(msg string, fields ...LogField)

func LogDebug

func LogDebug(msg string, fields ...LogField)

Package-level logging functions that use the global logger instance. Provide convenient access to logging without explicit logger management.

func LogError

func LogError(msg string, fields ...LogField)

func LogInfo

func LogInfo(msg string, fields ...LogField)

func LogWarn

func LogWarn(msg string, fields ...LogField)

func SetGlobalLogger

func SetGlobalLogger(logger Logger)

SetGlobalLogger sets the global logger instance used by package-level logging functions. Allows applications to inject custom logger implementations for testing or specialized logging requirements.

func ValidateGitHubIdentifier

func ValidateGitHubIdentifier(identifier, fieldName string) error

ValidateGitHubIdentifier validates GitHub usernames, repository names, and similar identifiers according to GitHub's naming rules. Checks length, character validity, and start/end character restrictions to prevent injection attacks.

func ValidateRepositoryPath

func ValidateRepositoryPath(owner, repo string) error

ValidateRepositoryPath validates a complete GitHub repository path (owner/repo). Ensures both owner and repository names meet GitHub's requirements. Used to validate repository references before making API calls.

func ValidateSession

func ValidateSession(session *GitHubSession) error

ValidateSession performs comprehensive validation of a GitHub session's readiness. Checks for nil session, active status, and proper client initialization. Should be called before any API operations to ensure session validity.

Types

type AuthenticationService

type AuthenticationService interface {
	AuthenticateUser(ctx context.Context, session *GitHubSession) (*User, error)
}

AuthenticationService defines GitHub user authentication operations. Provides methods for validating tokens and retrieving authenticated user information with comprehensive error handling and event reporting.

type Branch

type Branch struct {
	Name  string     `json:"ref"`
	SHA   string     `json:"sha"`
	Repo  Repository `json:"repo"`
	User  User       `json:"user"`
	Label string     `json:"label"`
}

Branch represents a GitHub branch reference used in pull requests. Contains the branch name, commit SHA, associated repository, and user information.

type Comment

type Comment struct {
	ID        int64     `json:"id"`
	Body      string    `json:"body"`
	User      User      `json:"user"`
	URL       string    `json:"html_url"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

Comment represents a comment on a GitHub issue or pull request. Contains the comment content, author information, and timestamps.

type CommentService

type CommentService interface {
	AddPullRequestComment(ctx context.Context, session *GitHubSession, owner, repo string, number int, body string) (*Comment, error)
	EditPullRequestComment(ctx context.Context, session *GitHubSession, owner, repo string, commentID int64, body string) (*Comment, error)
	GetPullRequestComments(ctx context.Context, session *GitHubSession, owner, repo string, number int) ([]Comment, error)
}

CommentService defines comment operations

type Commit

type Commit struct {
	SHA       string       `json:"sha"`
	Message   string       `json:"message"`
	Author    CommitAuthor `json:"author"`
	Committer CommitAuthor `json:"committer"`
	URL       string       `json:"html_url"`
	Parents   []CommitRef  `json:"parents"`
	Stats     CommitStats  `json:"stats"`
	Files     []CommitFile `json:"files"`
	CreatedAt time.Time    `json:"created_at"`
}

Commit represents a GitHub commit with full details including author information, file changes, and statistics. Used for repository history and pull request commits.

type CommitAuthor

type CommitAuthor struct {
	Name  string    `json:"name"`
	Email string    `json:"email"`
	Date  time.Time `json:"date"`
}

CommitAuthor represents the author or committer of a Git commit. Contains identity and timestamp information.

type CommitFile

type CommitFile struct {
	Filename  string `json:"filename"`
	Status    string `json:"status"`
	Additions int    `json:"additions"`
	Deletions int    `json:"deletions"`
	Changes   int    `json:"changes"`
	BlobURL   string `json:"blob_url"`
	RawURL    string `json:"raw_url"`
	Patch     string `json:"patch,omitempty"`
}

CommitFile represents a single file modification within a commit. Includes change statistics and URLs for accessing file content and diffs.

type CommitListOptions

type CommitListOptions struct {
	ListOptions
	SHA        string    `json:"sha,omitempty"`
	Path       string    `json:"path,omitempty"`
	Author     string    `json:"author,omitempty"`
	Since      time.Time `json:"since,omitempty"`
	Until      time.Time `json:"until,omitempty"`
	MaxResults int       `json:"max_results,omitempty"`
}

CommitListOptions extends ListOptions with commit history filtering. Supports filtering by SHA, file path, author, and date ranges.

type CommitRef

type CommitRef struct {
	SHA string `json:"sha"`
	URL string `json:"url"`
}

CommitRef represents a lightweight reference to a Git commit. Used in commit parent relationships and tag references.

type CommitService

type CommitService interface {
	GetCommitList(ctx context.Context, session *GitHubSession, owner, repo, path string, options *CommitListOptions) ([]Commit, error)
	GetCommit(ctx context.Context, session *GitHubSession, owner, repo, sha string) (*Commit, error)
	GetCommitRange(ctx context.Context, session *GitHubSession, owner, repo, base, head string) ([]Commit, error)
	GetCommitHistory(ctx context.Context, session *GitHubSession, owner, repo, sha string, forward bool, limit int) ([]Commit, error)
}

CommitService defines commit operations

type CommitStats

type CommitStats struct {
	Additions int `json:"additions"`
	Deletions int `json:"deletions"`
	Total     int `json:"total"`
}

CommitStats represents the statistical summary of changes in a commit. Provides counts for lines added, deleted, and total changes.

type CreatePullRequestRequest

type CreatePullRequestRequest struct {
	Title               string `json:"title"`
	Body                string `json:"body,omitempty"`
	Head                string `json:"head"`
	Base                string `json:"base"`
	MaintainerCanModify bool   `json:"maintainer_can_modify,omitempty"`
	Draft               bool   `json:"draft,omitempty"`
	Issue               int    `json:"issue,omitempty"`
}

CreatePullRequestRequest represents the payload for creating a new pull request. Supports creating from branches, converting issues, and setting draft status.

type CreateTagRequest

type CreateTagRequest struct {
	Tag     string       `json:"tag"`
	Message string       `json:"message"`
	Object  string       `json:"object"`
	Type    string       `json:"type"`
	Tagger  CommitAuthor `json:"tagger,omitempty"`
}

CreateTagRequest represents the payload for creating a Git tag. Supports both lightweight and annotated tags with optional tagger information.

type DefaultHTTPClientProvider

type DefaultHTTPClientProvider struct{}

DefaultHTTPClientProvider is the standard implementation of HTTPClientProvider that creates GitHub API clients with authentication tokens and optional custom HTTP client configuration for different deployment scenarios.

func NewDefaultHTTPClientProvider

func NewDefaultHTTPClientProvider() *DefaultHTTPClientProvider

NewDefaultHTTPClientProvider creates a standard HTTP client provider suitable for most GitHub API operations. Uses the default GitHub client configuration with token-based authentication.

func (*DefaultHTTPClientProvider) GetClient

func (p *DefaultHTTPClientProvider) GetClient(token string) *github.Client

GetClient creates a new GitHub API client with token authentication. Uses the default HTTP client configuration suitable for most applications. The token should be a valid GitHub personal access token or OAuth token.

func (*DefaultHTTPClientProvider) GetClientWithConfig

func (p *DefaultHTTPClientProvider) GetClientWithConfig(token string, config *SessionConfig) *github.Client

GetClientWithConfig creates a GitHub API client with custom configuration. Supports custom HTTP client injection for proxy configuration, timeouts, or other middleware requirements while maintaining token authentication.

type DefaultSessionManager

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

DefaultSessionManager is the production implementation of SessionManager with dependency injection for HTTP client providers, validation services, and logging. Provides comprehensive session creation with security validation.

func NewDefaultSessionManager

func NewDefaultSessionManager(
	httpClientProvider HTTPClientProvider,
	validationService ValidationService,
	logger Logger,
) *DefaultSessionManager

NewDefaultSessionManager creates a production-ready session manager with injected dependencies. Combines HTTP client provider, validation service, and logger for comprehensive session management capabilities.

func (*DefaultSessionManager) CreateSession

func (sm *DefaultSessionManager) CreateSession(token string, config *SessionConfig) GitHubSessionInterface

CreateSession creates a new GitHub session with comprehensive validation. Validates the provided token, creates an HTTP client, and initializes session metadata. Returns nil if validation fails or session creation errors.

func (*DefaultSessionManager) ValidateSession

func (sm *DefaultSessionManager) ValidateSession(session GitHubSessionInterface) error

ValidateSession performs comprehensive validation of a GitHub session. Ensures the session is properly initialized, active, and ready for API operations. Uses type assertion to work with the concrete GitHubSession implementation.

type DefaultValidationService

type DefaultValidationService struct{}

DefaultValidationService is the standard implementation of ValidationService that provides comprehensive validation for GitHub tokens, identifiers, and repository paths according to GitHub's API requirements and security best practices.

func NewDefaultValidationService

func NewDefaultValidationService() *DefaultValidationService

NewDefaultValidationService creates a standard validation service with GitHub-compliant validation rules. Suitable for most applications requiring input validation for GitHub API operations.

func (*DefaultValidationService) ValidateGitHubIdentifier

func (v *DefaultValidationService) ValidateGitHubIdentifier(identifier, fieldName string) error

ValidateGitHubIdentifier validates GitHub usernames, repository names, and other identifiers according to GitHub's naming conventions. Delegates to the utility function while maintaining interface compliance.

func (*DefaultValidationService) ValidateOperation

func (v *DefaultValidationService) ValidateOperation(operation string) error

ValidateOperation validates operation names used in logging and event reporting. Ensures operation names are reasonable length and safe for use in structured logging and monitoring systems.

func (*DefaultValidationService) ValidateRepositoryPath

func (v *DefaultValidationService) ValidateRepositoryPath(owner, repo string) error

ValidateRepositoryPath validates complete GitHub repository paths (owner/repo). Ensures both components meet GitHub's requirements and are safe for API operations. Delegates to the utility function while maintaining interface compliance.

func (*DefaultValidationService) ValidateToken

func (v *DefaultValidationService) ValidateToken(token string) error

ValidateToken performs basic validation of GitHub authentication tokens. Checks token length and format to prevent obviously invalid tokens from being used in API operations. Does not verify token validity with GitHub.

type Event

type Event struct {
	ID         string                 `json:"id"`
	Type       EventType              `json:"type"`
	Status     EventStatus            `json:"status"`
	Message    string                 `json:"message"`
	SessionID  string                 `json:"session_id"`
	Repository string                 `json:"repository,omitempty"`
	Owner      string                 `json:"owner,omitempty"`
	Operation  string                 `json:"operation"`
	Timestamp  time.Time              `json:"timestamp"`
	Duration   time.Duration          `json:"duration,omitempty"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	Progress   *ProgressInfo          `json:"progress,omitempty"`
	RateLimit  *RateLimitInfo         `json:"rate_limit,omitempty"`
}

Event represents a GitHub service event with metadata

type EventBuilder

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

EventBuilder helps build events with common metadata

func NewEventBuilder

func NewEventBuilder(sessionID, operation string, eventType EventType) *EventBuilder

NewEventBuilder creates a new event builder

func (*EventBuilder) BuildCompleteEvent

func (eb *EventBuilder) BuildCompleteEvent(message string) Event

BuildCompleteEvent creates a completion event

func (*EventBuilder) BuildError

func (eb *EventBuilder) BuildError(message string, err error, statusCode int) GitHubError

BuildError creates a GitHub error

func (*EventBuilder) BuildProgressEvent

func (eb *EventBuilder) BuildProgressEvent(message string) Event

BuildProgressEvent creates a progress event

func (*EventBuilder) BuildStartEvent

func (eb *EventBuilder) BuildStartEvent(message string) Event

BuildStartEvent creates a start event

func (*EventBuilder) WithMetadata

func (eb *EventBuilder) WithMetadata(key string, value interface{}) *EventBuilder

WithMetadata adds metadata to the event

func (*EventBuilder) WithProgress

func (eb *EventBuilder) WithProgress(current, total int) *EventBuilder

WithProgress adds progress information

func (*EventBuilder) WithRateLimit

func (eb *EventBuilder) WithRateLimit(limit, remaining int, reset time.Time) *EventBuilder

WithRateLimit adds rate limit information

func (*EventBuilder) WithRepository

func (eb *EventBuilder) WithRepository(owner, repo string) *EventBuilder

WithRepository sets the repository context

type EventChannelManager

type EventChannelManager interface {
	CreateEventChannels(bufferSize int) *EventChannels
	SendEvent(channels *EventChannels, event Event) error
	SendError(channels *EventChannels, err GitHubError) error
}

EventChannelManager defines the interface for creating and managing event channels. Abstracts event channel creation and provides safe event sending with error handling for different event types (events, errors) in the GitHub service.

type EventChannels

type EventChannels struct {
	Events chan Event       `json:"-"`
	Errors chan GitHubError `json:"-"`
}

EventChannels represents the dual channel system for events and errors

func NewEventChannels

func NewEventChannels(bufferSize int) *EventChannels

NewEventChannels creates a new set of event channels with the specified buffer size

func (*EventChannels) Close

func (ec *EventChannels) Close()

Close closes both event channels

type EventStatus

type EventStatus string

EventStatus represents the status of an operation

const (
	EventStatusStarted    EventStatus = "started"
	EventStatusInProgress EventStatus = "in_progress"
	EventStatusCompleted  EventStatus = "completed"
	EventStatusFailed     EventStatus = "failed"
)

type EventType

type EventType string

EventType represents the type of GitHub operation event

const (
	// Repository events
	EventTypeRepositoryList EventType = "repository_list"
	EventTypeRepositoryGet  EventType = "repository_get"

	// Organization events
	EventTypeOrganizationList EventType = "organization_list"
	EventTypeOrganizationGet  EventType = "organization_get"

	// Pull request events
	EventTypePullRequestList   EventType = "pull_request_list"
	EventTypePullRequestGet    EventType = "pull_request_get"
	EventTypePullRequestCreate EventType = "pull_request_create"
	EventTypePullRequestMerge  EventType = "pull_request_merge"

	// Comment events
	EventTypeCommentAdd  EventType = "comment_add"
	EventTypeCommentEdit EventType = "comment_edit"
	EventTypeCommentGet  EventType = "comment_get"

	// Commit events
	EventTypeCommitList EventType = "commit_list"
	EventTypeCommitGet  EventType = "commit_get"

	// File events
	EventTypeFileGet        EventType = "file_get"
	EventTypeFileGetContent EventType = "file_get_content"

	// Tag events
	EventTypeTagCreate EventType = "tag_create"
	EventTypeTagList   EventType = "tag_list"

	// Authentication events
	EventTypeAuthUser EventType = "auth_user"

	// General events
	EventTypeOperationStart    EventType = "operation_start"
	EventTypeOperationComplete EventType = "operation_complete"
	EventTypeOperationProgress EventType = "operation_progress"
)

type FileContent

type FileContent struct {
	Name        string `json:"name"`
	Path        string `json:"path"`
	SHA         string `json:"sha"`
	Size        int    `json:"size"`
	Content     string `json:"content"`
	Encoding    string `json:"encoding"`
	Type        string `json:"type"`
	DownloadURL string `json:"download_url"`
	URL         string `json:"url"`
}

FileContent represents the content and metadata of a file retrieved from a GitHub repository. Includes file size, encoding type, and download URLs for accessing the raw content.

type FileHistoryOptions added in v0.0.50

type FileHistoryOptions struct {
	BaseCommit      string `json:"base_commit,omitempty"`
	Limit           int    `json:"limit,omitempty"`
	LimitDays       *int   `json:"limit_days,omitempty"`
	ForceCutoff     bool   `json:"force_cutoff,omitempty"`
	SizeThresholdKB int    `json:"size_threshold_kb,omitempty"`
	MaxDownloadSize int64  `json:"max_download_size,omitempty"`
	MaxWorkers      int    `json:"max_workers,omitempty"`
}

FileHistoryOptions controls retrieval of a file's revision history. LimitDays is expressed in whole days to match user-facing history filters.

type FileHistoryService added in v0.0.50

type FileHistoryService interface {
	GetFileHistory(ctx context.Context, session *GitHubSession, owner, repo, path string, options *FileHistoryOptions) ([]*FileRevision, error)
}

FileHistoryService defines higher-level file history operations that combine commit listing, commit detail inspection, and file content retrieval.

type FileRevision added in v0.0.50

type FileRevision struct {
	Commit    Commit `json:"commit"`
	FileBytes []byte `json:"-"`
}

FileRevision represents the contents of a file at a specific commit. Used for building a file's revision history across GitHub commits.

type FileService

type FileService interface {
	GetFileContent(ctx context.Context, session *GitHubSession, owner, repo, path, ref string) (*FileContent, error)
	GetFileRevision(ctx context.Context, session *GitHubSession, owner, repo, path, sha string) (*FileContent, error)
}

FileService defines file operations

type GitHubError

type GitHubError struct {
	ID         string                 `json:"id"`
	Type       EventType              `json:"type"`
	Operation  string                 `json:"operation"`
	Message    string                 `json:"message"`
	Err        error                  `json:"error"`
	SessionID  string                 `json:"session_id"`
	Repository string                 `json:"repository,omitempty"`
	Owner      string                 `json:"owner,omitempty"`
	Timestamp  time.Time              `json:"timestamp"`
	StatusCode int                    `json:"status_code,omitempty"`
	Metadata   map[string]interface{} `json:"metadata,omitempty"`
	RateLimit  *RateLimitInfo         `json:"rate_limit,omitempty"`
}

GitHubError represents a GitHub service error with context

func (*GitHubError) Error

func (e *GitHubError) Error() string

Error implements the error interface

func (*GitHubError) Unwrap

func (e *GitHubError) Unwrap() error

Unwrap returns the underlying error

type GitHubService

type GitHubService interface {
	// Session management
	CreateSession(token string, config *SessionConfig) *GitHubSession
	CreateAnonymousSession(config *SessionConfig) *GitHubSession
	CreateSessionWithOptionalToken(token string, config *SessionConfig) *GitHubSession

	// Authentication operations
	AuthenticationService

	// Repository operations
	RepositoryService

	// Organization operations
	OrganizationService

	// Commit operations
	CommitService

	// File operations
	FileService

	// File history operations
	FileHistoryService

	// Pull request operations
	PullRequestService

	// Comment operations
	CommentService

	// Tag operations
	TagService
}

GitHubService provides a comprehensive interface for GitHub API operations. Combines session management with specialized services for repositories, pull requests, commits, files, tags, and user authentication. All methods are goroutine-safe.

func NewGitHubService

func NewGitHubService() GitHubService

NewGitHubService creates a GitHub service with production-ready default dependencies. Uses default session manager, validation service, no-op metrics collector, and global logger. Suitable for most applications that don't require custom dependency injection.

func NewGitHubServiceWithDependencies

func NewGitHubServiceWithDependencies(
	sessionManager SessionManager,
	validationService ValidationService,
	metricsCollector MetricsCollector,
	logger Logger,
) GitHubService

NewGitHubServiceWithDependencies creates a GitHub service with custom dependencies. Allows injection of custom session managers, validation services, metrics collectors, and loggers for testing, monitoring, or specialized deployment requirements.

type GitHubSession

type GitHubSession struct {
	ID       string           `json:"id"`
	Token    string           `json:"-"` // Never serialize the token
	Client   *github.Client   `json:"-"`
	Metadata *SessionMetadata `json:"metadata"`
	Config   *SessionConfig   `json:"config"`
	// contains filtered or unexported fields
}

GitHubSession represents an authenticated GitHub API session with comprehensive metadata tracking, event reporting, and thread-safe operations. Sessions maintain user information, request statistics, and rate limit data throughout their lifecycle.

func NewAnonymousGitHubSession added in v0.0.50

func NewAnonymousGitHubSession(config *SessionConfig) *GitHubSession

NewAnonymousGitHubSession creates a new unauthenticated GitHub session suitable for public repository access. The session is active and validated like an authenticated session, but carries no token and uses an anonymous GitHub client.

func NewGitHubSession

func NewGitHubSession(token string, config *SessionConfig) *GitHubSession

NewGitHubSession creates a new authenticated GitHub session with security validation. Validates token format, creates GitHub client, and initializes session metadata. Returns nil if token validation fails. Use Initialize() to fetch user information.

func (*GitHubSession) Close

func (s *GitHubSession) Close() error

Close gracefully shuts down the session, sends a close event, and cleans up resources. Closes event channels with a timeout to prevent blocking. Once closed, the session cannot be reused. This method is goroutine-safe and idempotent.

func (*GitHubSession) GetCustomMetadata

func (s *GitHubSession) GetCustomMetadata(key string) (interface{}, bool)

GetCustomMetadata retrieves a custom metadata value by key. Returns the value and a boolean indicating if the key exists. This method is goroutine-safe.

func (*GitHubSession) GetEventChannels

func (s *GitHubSession) GetEventChannels() *EventChannels

GetEventChannels returns the event channels associated with this session. Returns nil if event reporting is disabled. The returned channels should not be closed directly - use Close() instead. This method is goroutine-safe.

func (*GitHubSession) GetID

func (s *GitHubSession) GetID() string

GetID returns the unique session identifier. This method is goroutine-safe.

func (*GitHubSession) GetMetadata

func (s *GitHubSession) GetMetadata() *SessionMetadata

GetMetadata returns a deep copy of the session metadata to prevent race conditions. The returned metadata is safe to read and modify without affecting the original. Custom metadata map is also deep-copied for complete isolation.

func (*GitHubSession) GetRateLimit

func (s *GitHubSession) GetRateLimit() *RateLimitInfo

GetRateLimit returns a copy of the current rate limit information. Returns nil if no rate limit data is available. The returned data is safe to read and modify without affecting the session. This method is goroutine-safe.

func (*GitHubSession) GetToken

func (s *GitHubSession) GetToken() string

GetToken returns the GitHub authentication token for this session. This method is goroutine-safe. Never log or expose the returned token.

func (*GitHubSession) IncrementErrorCount

func (s *GitHubSession) IncrementErrorCount()

IncrementErrorCount increments the error counter for this session. Called automatically when API operations fail for monitoring purposes. This method is goroutine-safe.

func (*GitHubSession) IncrementRequestCount

func (s *GitHubSession) IncrementRequestCount()

IncrementRequestCount increments the total request counter for this session. Called automatically by successful API operations for usage tracking. This method is goroutine-safe.

func (*GitHubSession) Initialize

func (s *GitHubSession) Initialize(ctx context.Context) error

Initialize fetches the authenticated user's information from GitHub and validates the provided token. This method should be called after NewGitHubSession to complete session setup. Returns error if token is invalid or API call fails.

func (*GitHubSession) IsActive

func (s *GitHubSession) IsActive() bool

IsActive returns true if the session is active and can be used for API operations. Returns false if the session has been closed or is in an invalid state. This method is goroutine-safe.

func (*GitHubSession) SetCustomMetadata

func (s *GitHubSession) SetCustomMetadata(key string, value interface{})

SetCustomMetadata sets a custom key-value pair in the session metadata. This method is goroutine-safe and can be called concurrently.

func (*GitHubSession) String

func (s *GitHubSession) String() string

String returns a human-readable representation of the session including session ID, username, active status, and usage statistics. This method is goroutine-safe.

func (*GitHubSession) UpdateActivity

func (s *GitHubSession) UpdateActivity()

UpdateActivity updates the last activity timestamp to the current time. Called automatically by API operations to track session usage. This method is goroutine-safe.

func (*GitHubSession) WaitForRateLimit

func (s *GitHubSession) WaitForRateLimit(ctx context.Context) error

WaitForRateLimit blocks if the rate limit has been exceeded, waiting until the limit resets. Sends progress events during the wait. Returns immediately if rate limit allows more requests. Respects context cancellation.

type GitHubSessionInterface

type GitHubSessionInterface interface {
	GetID() string
	GetToken() string
	// GetClient() *github.Client // Removed to avoid coupling
	GetMetadata() *SessionMetadata
	GetEventChannels() *EventChannels
	GetRateLimit() *RateLimitInfo
	Initialize(ctx context.Context) error
	IsActive() bool
	Close() error
	UpdateActivity()
	IncrementRequestCount()
	IncrementErrorCount()
	SetCustomMetadata(key string, value interface{})
	GetCustomMetadata(key string) (interface{}, bool)
	WaitForRateLimit(ctx context.Context) error
	String() string
}

GitHubSessionInterface defines the complete interface for GitHub session operations. Provides access to session metadata, event channels, rate limiting, and lifecycle management while maintaining abstraction from concrete implementation details.

type HTTPClientProvider

type HTTPClientProvider interface {
	GetClient(token string) *github.Client
	GetClientWithConfig(token string, config *SessionConfig) *github.Client
}

HTTPClientProvider defines the interface for creating configured GitHub HTTP clients. Abstracts client creation with token authentication and custom configuration to support different HTTP client implementations and middleware.

type Label

type Label struct {
	ID          int64  `json:"id"`
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	Color       string `json:"color"`
	Default     bool   `json:"default"`
}

Label represents a GitHub issue or pull request label with color and metadata. Used for categorizing and filtering issues and pull requests.

type ListOptions

type ListOptions struct {
	Page    int `json:"page,omitempty"`
	PerPage int `json:"per_page,omitempty"`
}

ListOptions provides common pagination parameters for GitHub API list operations. Used as a base for more specific list option types.

type LogField

type LogField struct {
	Key   string
	Value interface{}
}

LogField represents a key-value pair for structured logging. Enables rich contextual information in log entries for better observability and debugging in production environments.

func CountField

func CountField(count int) LogField

CountField creates a structured log field for count/quantity values. Provides consistent naming for numeric count fields in log entries.

func DurationField

func DurationField(duration time.Duration) LogField

DurationField creates a structured log field for duration measurements. Formats durations in a human-readable string format for timing analysis.

func ErrorField

func ErrorField(err error) LogField

ErrorField creates a structured log field for error information. Safely handles nil errors and extracts error messages for structured logging.

func Field

func Field(key string, value interface{}) LogField

Helper functions for creating commonly used structured log fields. Provide type-safe field creation with consistent naming conventions. Field creates a structured log field with the specified key and value. Provides a convenient way to add arbitrary structured data to log entries.

func StatusCodeField

func StatusCodeField(code int) LogField

StatusCodeField creates a structured log field for HTTP status codes. Provides consistent naming for status code fields in API operation logs.

type LogLevel

type LogLevel int

LogLevel represents the severity level of log messages in the structured logging system. Supports standard log levels from debug to critical with hierarchical filtering.

const (
	LogLevelDebug LogLevel = iota
	LogLevelInfo
	LogLevelWarn
	LogLevelError
	LogLevelCritical
)

func (LogLevel) String

func (l LogLevel) String() string

String returns the standardized string representation of a log level. Used for consistent log formatting across different output destinations.

type Logger

type Logger interface {
	Debug(msg string, fields ...LogField)
	Info(msg string, fields ...LogField)
	Warn(msg string, fields ...LogField)
	Error(msg string, fields ...LogField)
	Critical(msg string, fields ...LogField)
	WithContext(ctx context.Context) Logger
	WithSession(sessionID string) Logger
	WithOperation(operationID string) Logger
}

Logger defines the interface for structured logging with contextual information. Supports hierarchical log levels, structured fields, and contextual enrichment with session IDs, operation IDs, and request context for distributed tracing.

func GetGlobalLogger

func GetGlobalLogger() Logger

GetGlobalLogger returns the current global logger instance. Used by package-level logging functions and dependency injection to access the configured logger implementation.

type MetricsCollector

type MetricsCollector interface {
	RecordAPICall(operation string, duration time.Duration, statusCode int)
	RecordError(operation string, errorType string)
	RecordRateLimit(remaining, limit int)
	RecordSessionActivity(sessionID string, requestCount, errorCount int64)
}

MetricsCollector defines the interface for collecting operational metrics from GitHub API operations. Supports recording API call performance, error rates, rate limit usage, and session activity for monitoring and observability.

type NoOpMetricsCollector

type NoOpMetricsCollector struct{}

NoOpMetricsCollector is a metrics collector implementation that performs no operations. Useful for environments where metrics collection is disabled or not required, providing a safe default that satisfies the MetricsCollector interface.

func NewNoOpMetricsCollector

func NewNoOpMetricsCollector() *NoOpMetricsCollector

NewNoOpMetricsCollector creates a metrics collector that discards all metrics. Suitable for development environments or deployments where metrics collection is not needed but the interface must be satisfied.

func (*NoOpMetricsCollector) RecordAPICall

func (m *NoOpMetricsCollector) RecordAPICall(operation string, duration time.Duration, statusCode int)

RecordAPICall records API call metrics (no-op implementation). In a real metrics collector, this would record operation duration, status codes, and other performance metrics.

func (*NoOpMetricsCollector) RecordError

func (m *NoOpMetricsCollector) RecordError(operation string, errorType string)

RecordError records error metrics (no-op implementation). In a real metrics collector, this would record error types, frequencies, and operation context for monitoring.

func (*NoOpMetricsCollector) RecordRateLimit

func (m *NoOpMetricsCollector) RecordRateLimit(remaining, limit int)

RecordRateLimit records rate limit metrics (no-op implementation). In a real metrics collector, this would track rate limit usage and remaining quota for capacity planning.

func (*NoOpMetricsCollector) RecordSessionActivity

func (m *NoOpMetricsCollector) RecordSessionActivity(sessionID string, requestCount, errorCount int64)

RecordSessionActivity records session usage metrics (no-op implementation). In a real metrics collector, this would track session duration, request counts, and error rates for user activity monitoring.

type Organization

type Organization struct {
	ID          int64     `json:"id"`
	Login       string    `json:"login"`
	Name        string    `json:"name,omitempty"`
	Description string    `json:"description,omitempty"`
	URL         string    `json:"html_url"`
	AvatarURL   string    `json:"avatar_url"`
	Type        string    `json:"type"`
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
}

Organization represents a GitHub organization with basic profile information and timestamps for creation and last update.

type OrganizationService

type OrganizationService interface {
	GetUserOrganizations(ctx context.Context, session *GitHubSession) ([]Organization, error)
	GetOrganizationRepositories(ctx context.Context, session *GitHubSession, org string) ([]Repository, error)
}

OrganizationService defines organization operations

type PaginationConfig

type PaginationConfig struct {
	PerPage    int
	Page       int
	MaxResults int // Maximum total results to fetch (0 = no limit)
}

PaginationConfig defines pagination parameters with built-in validation and safety limits. Prevents unbounded memory allocation by enforcing maximum result limits. Used by FetchPaginated to control memory usage and API request patterns.

func DefaultPaginationConfig

func DefaultPaginationConfig() *PaginationConfig

DefaultPaginationConfig returns production-ready pagination defaults. Uses 100 items per page with no maximum result limit, suitable for most GitHub API operations without memory constraints.

func (*PaginationConfig) Validate

func (pc *PaginationConfig) Validate() error

Validate ensures pagination configuration is safe and within acceptable limits. Sets defaults for invalid values and enforces maximum limits to prevent memory exhaustion and excessive API usage.

type ProductionLogger

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

ProductionLogger is a production-ready structured logger implementation with configurable log levels, contextual enrichment, and timestamp support. Designed for high-performance logging in concurrent environments.

func NewProductionLogger

func NewProductionLogger(level LogLevel) *ProductionLogger

NewProductionLogger creates a production-ready logger with the specified minimum log level. Uses Go's standard log package with microsecond timestamps for precise timing information in production environments.

func (*ProductionLogger) Critical

func (l *ProductionLogger) Critical(msg string, fields ...LogField)

Critical logs a critical message with optional structured fields. Used for severe error conditions that may require immediate attention or could lead to application failure.

func (*ProductionLogger) Debug

func (l *ProductionLogger) Debug(msg string, fields ...LogField)

Debug logs a debug-level message with optional structured fields. Only outputs if the logger's level is set to debug or lower. Useful for detailed troubleshooting and development information.

func (*ProductionLogger) Error

func (l *ProductionLogger) Error(msg string, fields ...LogField)

Error logs an error message with optional structured fields. Used for error conditions that affect operation but allow the application to continue running.

func (*ProductionLogger) Info

func (l *ProductionLogger) Info(msg string, fields ...LogField)

Info logs an informational message with optional structured fields. Used for normal operational messages and important state changes that should be visible in production logs.

func (*ProductionLogger) Warn

func (l *ProductionLogger) Warn(msg string, fields ...LogField)

Warn logs a warning message with optional structured fields. Used for potentially problematic situations that don't prevent operation continuation but should be monitored.

func (*ProductionLogger) WithContext

func (l *ProductionLogger) WithContext(ctx context.Context) Logger

WithContext creates a new logger instance enriched with request context. Returns a new logger that includes context information in all log entries for distributed tracing and request correlation.

func (*ProductionLogger) WithOperation

func (l *ProductionLogger) WithOperation(operationID string) Logger

WithOperation creates a new logger instance enriched with operation ID. Returns a new logger that includes the operation ID in all log entries for tracking specific API operations and their lifecycle.

func (*ProductionLogger) WithSession

func (l *ProductionLogger) WithSession(sessionID string) Logger

WithSession creates a new logger instance enriched with session ID. Returns a new logger that includes the session ID in all log entries for tracking user sessions and API usage patterns.

type ProgressInfo

type ProgressInfo struct {
	Current int `json:"current"`
	Total   int `json:"total"`
	Percent int `json:"percent"`
}

ProgressInfo represents progress information for long-running operations

type PullRequest

type PullRequest struct {
	ID        int64      `json:"id"`
	Number    int        `json:"number"`
	Title     string     `json:"title"`
	Body      string     `json:"body,omitempty"`
	State     string     `json:"state"`
	Draft     bool       `json:"draft"`
	Merged    bool       `json:"merged"`
	Mergeable bool       `json:"mergeable"`
	URL       string     `json:"html_url"`
	DiffURL   string     `json:"diff_url"`
	PatchURL  string     `json:"patch_url"`
	Head      Branch     `json:"head"`
	Base      Branch     `json:"base"`
	User      User       `json:"user"`
	Assignees []User     `json:"assignees"`
	Labels    []Label    `json:"labels"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	MergedAt  *time.Time `json:"merged_at,omitempty"`
	ClosedAt  *time.Time `json:"closed_at,omitempty"`
}

PullRequest represents a GitHub pull request with complete metadata including branch information, review state, labels, and timestamps. MergedAt and ClosedAt are pointers to support nil values for open pull requests.

type PullRequestComment

type PullRequestComment struct {
	Comment
	PullRequestURL   string `json:"pull_request_url"`
	DiffHunk         string `json:"diff_hunk,omitempty"`
	Path             string `json:"path,omitempty"`
	Position         int    `json:"position,omitempty"`
	OriginalPosition int    `json:"original_position,omitempty"`
	CommitID         string `json:"commit_id,omitempty"`
	OriginalCommitID string `json:"original_commit_id,omitempty"`
}

PullRequestComment represents a code review comment on a specific line in a pull request. Extends Comment with diff context, file path, and line position information.

type PullRequestListOptions

type PullRequestListOptions struct {
	ListOptions
	State     string `json:"state,omitempty"`
	Head      string `json:"head,omitempty"`
	Base      string `json:"base,omitempty"`
	Sort      string `json:"sort,omitempty"`
	Direction string `json:"direction,omitempty"`
}

PullRequestListOptions extends ListOptions with pull request specific filtering. Supports filtering by state, branch references, and sorting options.

type PullRequestService

type PullRequestService interface {
	CreatePullRequest(ctx context.Context, session *GitHubSession, owner, repo string, request *CreatePullRequestRequest) (*PullRequest, error)
	GetPullRequest(ctx context.Context, session *GitHubSession, owner, repo string, number int) (*PullRequest, error)
	GetPullRequestsWithTag(ctx context.Context, session *GitHubSession, owner, repo, tag string) ([]PullRequest, error)
	ListPullRequests(ctx context.Context, session *GitHubSession, owner, repo string, options *PullRequestListOptions) ([]PullRequest, error)
	MergePullRequest(ctx context.Context, session *GitHubSession, owner, repo string, number int, commitMessage string) (*PullRequest, error)
}

PullRequestService defines comprehensive GitHub pull request operations including creation, retrieval, listing with filters, tag-based searching, and merging. All methods require an authenticated session and return structured error information.

type RateLimitInfo

type RateLimitInfo struct {
	Limit     int       `json:"limit"`
	Remaining int       `json:"remaining"`
	Reset     time.Time `json:"reset"`
}

RateLimitInfo represents GitHub API rate limit information

type Repository

type Repository struct {
	ID            int64     `json:"id"`
	Name          string    `json:"name"`
	FullName      string    `json:"full_name"`
	Description   string    `json:"description,omitempty"`
	Private       bool      `json:"private"`
	Fork          bool      `json:"fork"`
	URL           string    `json:"html_url"`
	CloneURL      string    `json:"clone_url"`
	SSHURL        string    `json:"ssh_url"`
	DefaultBranch string    `json:"default_branch"`
	Language      string    `json:"language,omitempty"`
	StarCount     int       `json:"stargazers_count"`
	ForkCount     int       `json:"forks_count"`
	Owner         User      `json:"owner"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	PushedAt      time.Time `json:"pushed_at"`
}

Repository represents a GitHub repository containing metadata, ownership details, and repository statistics. All time fields use Go's time.Time for consistency.

type RepositoryService

type RepositoryService interface {
	GetAllUserRepositories(ctx context.Context, session *GitHubSession) ([]Repository, error)
	GetRepository(ctx context.Context, session *GitHubSession, owner, repo string) (*Repository, error)
}

RepositoryService defines GitHub repository operations including retrieval of user repositories and specific repository details. Provides comprehensive repository metadata with owner information and statistics.

type RequestHandler

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

RequestHandler provides production-ready handling of GitHub API requests with comprehensive logging, progress tracking, event reporting, and error handling. Supports intelligent progress throttling and backpressure management for events.

func NewRequestHandler

func NewRequestHandler(session *GitHubSession, operation string, eventType EventType) *RequestHandler

NewRequestHandler creates a new request handler with security validation and logging. Validates operation names for security (prevents injection), sets up structured logging with correlation IDs, and initializes progress tracking. Returns nil for invalid inputs.

func (*RequestHandler) HandleResponse

func (rh *RequestHandler) HandleResponse(resp *github.Response, err error, operation string) error

HandleResponse processes GitHub API responses with comprehensive error handling, rate limit tracking, and event reporting. Updates session metrics, logs structured error information, and emits rate limit warnings when thresholds are reached.

func (*RequestHandler) SendCompleteEvent

func (rh *RequestHandler) SendCompleteEvent(message string)

SendCompleteEvent sends an operation completion event with timing and usage metrics. Includes operation duration, session request count, and error count for monitoring. Uses backpressure handling and retry logic similar to start events.

func (*RequestHandler) SendProgressEvent

func (rh *RequestHandler) SendProgressEvent(message string, current, total int)

SendProgressEvent sends progress updates with intelligent throttling to prevent event spam. Only sends events when progress crosses meaningful thresholds (10%) or when the operation completes. Uses shorter timeouts for less critical progress events.

func (*RequestHandler) SendStartEvent

func (rh *RequestHandler) SendStartEvent(message string)

SendStartEvent sends an operation start event with correlation and operation IDs. Uses backpressure handling to prevent blocking on full event channels. Logs the operation start and retries event sending once in a goroutine if needed.

func (*RequestHandler) WithRepository

func (rh *RequestHandler) WithRepository(owner, repo string) *RequestHandler

WithRepository adds repository context (owner/repo) to the request handler's event builder. Returns the same handler for method chaining. Safe to call on nil handlers.

type RequestHandlerInterface

type RequestHandlerInterface interface {
	SendStartEvent(message string)
	SendProgressEvent(message string, current, total int)
	SendCompleteEvent(message string)
	HandleResponse(resp *github.Response, err error, operation string) error
	WithRepository(owner, repo string) RequestHandlerInterface
}

RequestHandlerInterface defines the interface for handling GitHub API requests with event reporting, progress tracking, and repository context management. Provides abstraction for different request handling implementations.

type ResourceConverter

type ResourceConverter[T any, R any] func(T) R

ResourceConverter is a generic function type for converting GitHub API types to internal model types. Enables type-safe conversion while maintaining clean separation between GitHub API structures and internal representations.

type ResourceFetcher

type ResourceFetcher[T any] func(opts *github.ListOptions) ([]T, *github.Response, error)

ResourceFetcher is a generic function type for fetching paginated GitHub API data. Takes GitHub list options and returns a slice of items, response metadata, and any error. Used by FetchPaginated to abstract different GitHub API list operations.

type ResourceSingleFetcher

type ResourceSingleFetcher[T any] func() (T, *github.Response, error)

ResourceSingleFetcher is a generic function type for fetching single GitHub API items. Returns the item, response metadata, and any error. Used by FetchSingle and FetchCreate to abstract different GitHub API single-item operations.

type SessionConfig

type SessionConfig struct {
	EventChannels    *EventChannels         `json:"-"`
	EnableRateLimit  bool                   `json:"enable_rate_limit"`
	EnableMetrics    bool                   `json:"enable_metrics"`
	Timeout          time.Duration          `json:"timeout"`
	MaxRetries       int                    `json:"max_retries"`
	RetryDelay       time.Duration          `json:"retry_delay"`
	CustomHTTPClient *http.Client           `json:"-"`
	Custom           map[string]interface{} `json:"custom,omitempty"`
}

SessionConfig defines the configuration options for creating a GitHub session. Includes event handling, timeouts, retry behavior, and custom HTTP client support. Event channels are optional and can be nil to disable event reporting.

func DefaultSessionConfig

func DefaultSessionConfig() *SessionConfig

DefaultSessionConfig returns a sensible default configuration for GitHub sessions. Enables rate limiting and metrics, sets 30-second timeout, and creates event channels with a 100-item buffer. Suitable for most production use cases.

type SessionManager

type SessionManager interface {
	CreateSession(token string, config *SessionConfig) GitHubSessionInterface
	ValidateSession(session GitHubSessionInterface) error
}

SessionManager defines the interface for creating and validating GitHub sessions. Provides abstraction for session lifecycle management with pluggable validation and HTTP client configuration for different deployment environments.

type SessionMetadata

type SessionMetadata struct {
	UserID       int64                  `json:"user_id"`
	UserLogin    string                 `json:"user_login"`
	UserName     string                 `json:"user_name"`
	UserEmail    string                 `json:"user_email"`
	Scopes       []string               `json:"scopes"`
	RateLimit    *RateLimitInfo         `json:"rate_limit,omitempty"`
	CreatedAt    time.Time              `json:"created_at"`
	LastActivity time.Time              `json:"last_activity"`
	RequestCount int64                  `json:"request_count"`
	ErrorCount   int64                  `json:"error_count"`
	Custom       map[string]interface{} `json:"custom,omitempty"`
}

SessionMetadata contains comprehensive metadata about a GitHub session including user information, API usage statistics, rate limiting data, and custom fields. All counters are goroutine-safe when accessed through GitHubSession methods.

type Tag

type Tag struct {
	Name       string    `json:"name"`
	ZipballURL string    `json:"zipball_url"`
	TarballURL string    `json:"tarball_url"`
	Commit     CommitRef `json:"commit"`
}

Tag represents a Git tag in a GitHub repository. Provides access to tagged commit and downloadable archives.

type TagService

type TagService interface {
	CreateTag(ctx context.Context, session *GitHubSession, owner, repo string, request *CreateTagRequest) (*Tag, error)
	ListTags(ctx context.Context, session *GitHubSession, owner, repo string) ([]Tag, error)
}

TagService defines GitHub tag operations for Git tag management. Supports creating both lightweight and annotated tags, and listing existing tags with complete metadata and download URLs.

type User

type User struct {
	ID        int64     `json:"id"`
	Login     string    `json:"login"`
	Name      string    `json:"name,omitempty"`
	Email     string    `json:"email,omitempty"`
	AvatarURL string    `json:"avatar_url"`
	URL       string    `json:"html_url"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"created_at"`
	UpdatedAt time.Time `json:"updated_at"`
}

User represents a GitHub user account with profile information. This structure is used for repository owners, pull request authors, assignees, and commenters.

type ValidationService

type ValidationService interface {
	ValidateGitHubIdentifier(identifier, fieldName string) error
	ValidateRepositoryPath(owner, repo string) error
	ValidateToken(token string) error
	ValidateOperation(operation string) error
}

ValidationService defines the interface for validating GitHub-related inputs. Provides comprehensive validation for tokens, identifiers, repository paths, and operation names to ensure security and API compatibility.

Jump to

Keyboard shortcuts

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