Help us shape the future of Go! Take the 2026 Go Developer Survey

diff

package
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Apr 24, 2026 License: MIT Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrOperationCancelled indicates user cancelled the operation
	ErrOperationCancelled = errors.New("operation cancelled by user")

	// ErrStaleRemote indicates user declined to continue with stale remote
	ErrStaleRemote = errors.New("operation declined due to stale remote")

	// ErrAutoBranchCheckoutFailed indicates auto-branch checkout failed (non-fatal)
	// This is wrapped with AutoBranchCheckoutError to provide details
	ErrAutoBranchCheckoutFailed = errors.New("auto-branch checkout failed")
)

Sentinel errors for error type checking with errors.Is()

Functions

func FormatAutoBranchSuccess

func FormatAutoBranchSuccess(branchName string, checkoutFailed bool, style *OutputStyle) string

FormatAutoBranchSuccess formats the success message for auto-branch creation

func FormatAutoBranchWarning

func FormatAutoBranchWarning(commitsAhead int, defaultBranch string, branchName string, style *OutputStyle) string

FormatAutoBranchWarning formats the warning when commits are detected on main

func FormatBaseChanged

func FormatBaseChanged(oldBase, newBase string, style *OutputStyle) string

FormatBaseChanged formats the message when PR base branch changed

func FormatDependentPRList

func FormatDependentPRList(dependentPRs []*github.PullRequest) string

FormatDependentPRList formats dependent PRs with more details for verbose output Includes PR number, title, and author

func FormatDependentPRWarning

func FormatDependentPRWarning(dependentPRs []*github.PullRequest) string

FormatDependentPRWarning generates a user-friendly warning message about dependent PRs that target the current branch as their base

func FormatDiffResult

func FormatDiffResult(result *DiffResult, style *OutputStyle) string

FormatDiffResult formats the complete diff workflow result

func FormatDryRunOutput

func FormatDryRunOutput(currentBranch, detectedBase string, parentPR *github.PullRequest, dependentPRs []*github.PullRequest, analysis *template.CommitAnalysis, style *OutputStyle) string

FormatDryRunOutput formats the output for --dry-run mode

func FormatErrorWithContext

func FormatErrorWithContext(err error, style *OutputStyle) string

FormatErrorWithContext formats an error with stacking context

func FormatFastPathOutput

func FormatFastPathOutput(pr *github.PullRequest, messages []string, style *OutputStyle) string

FormatFastPathOutput formats the output for fast path (existing PR, no edit)

func FormatNoNewCommits

func FormatNoNewCommits(style *OutputStyle) string

FormatNoNewCommits formats the message when there are no new commits to push

func FormatPRCreated

func FormatPRCreated(pr *github.PullRequest, parentPR *github.PullRequest, style *OutputStyle) string

FormatPRCreated formats the success message for PR creation with stacking info

func FormatPRUpdated

func FormatPRUpdated(pr *github.PullRequest, baseChanged bool, oldBase, newBase string, style *OutputStyle) string

FormatPRUpdated formats the success message for PR update with stacking info

func FormatProgressIndicator

func FormatProgressIndicator(operation string, style *OutputStyle) string

FormatProgressIndicator formats a progress indicator for operations

func FormatPushedSuccessfully

func FormatPushedSuccessfully(style *OutputStyle) string

FormatPushedSuccessfully formats the success message after pushing

func FormatPushingBranch

func FormatPushingBranch(branchName string, style *OutputStyle) string

FormatPushingBranch formats the message for pushing a branch

func FormatReviewersAssigned

func FormatReviewersAssigned(reviewers []string, style *OutputStyle) string

FormatReviewersAssigned formats the message for assigned reviewers

func FormatStackConfirmation

func FormatStackConfirmation(operation, currentBranch, baseBranch string, parentPR *github.PullRequest, style *OutputStyle) string

FormatStackConfirmation formats a confirmation prompt for stack operations

func FormatStackWarning

func FormatStackWarning(message string, details []string, style *OutputStyle) string

FormatStackWarning formats a warning about stack operations

func FormatStackingOutput

func FormatStackingOutput(currentBranch string, baseBranch string, parentPR *github.PullRequest, dependentPRs []*github.PullRequest, style *OutputStyle) string

FormatStackingOutput formats the stacking hierarchy for display Shows the relationship between current PR and parent/dependent PRs

func FormatValidationErrors

func FormatValidationErrors(errors []string, templatePath string, style *OutputStyle) string

FormatValidationErrors formats template validation errors

func IsParentBranch

func IsParentBranch(dependentPRs []*github.PullRequest) bool

IsParentBranch checks if the given branch has any dependent PRs Returns true if there are PRs targeting this branch as their base

func ShowStackingStatus

func ShowStackingStatus(parentBranch string, parentPR *github.PullRequest) string

ShowStackingStatus displays information about stacking relationships Shows which parent PR the current branch is stacking on

Types

type AutoBranchCheckoutError

type AutoBranchCheckoutError struct {
	BranchName string
	Err        error
}

AutoBranchCheckoutError is returned when auto-branch checkout fails (non-fatal)

func (*AutoBranchCheckoutError) Error

func (e *AutoBranchCheckoutError) Error() string

func (*AutoBranchCheckoutError) Is

func (e *AutoBranchCheckoutError) Is(target error) bool

func (*AutoBranchCheckoutError) Unwrap

func (e *AutoBranchCheckoutError) Unwrap() error

type AutoBranchContext

type AutoBranchContext struct {
	BranchName    string // Generated branch name for the auto-branch
	ShouldProceed bool   // Whether the operation should proceed
}

AutoBranchContext holds state for the auto-branch operation. This context is passed through the diff command flow to coordinate the push-before-PR and checkout-after-PR operations.

type AutoBranchDetector

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

AutoBranchDetector is the main detector and orchestrator for auto-branch operations. It handles detection of commits on main and orchestrates the auto-branch creation flow.

func NewAutoBranchDetector

func NewAutoBranchDetector(repo *git.Repository, cfg *config.DiffConfig) *AutoBranchDetector

NewAutoBranchDetector creates a new AutoBranchDetector with the given repository and configuration.

func (*AutoBranchDetector) CheckStaleRemote

func (d *AutoBranchDetector) CheckStaleRemote(ctx context.Context, defaultBranch string) (bool, error)

CheckStaleRemote checks if the remote tracking branch is stale (not updated recently). Returns (shouldContinue, error). If shouldContinue is false, the operation should be aborted (user declined or error).

func (*AutoBranchDetector) DetectCommitsOnMain

func (d *AutoBranchDetector) DetectCommitsOnMain(ctx context.Context) (*DetectionResult, error)

DetectCommitsOnMain detects if the user is on main/master with unpushed commits. It returns a DetectionResult with the current state, or an error if detection fails.

func (*AutoBranchDetector) EnsureUniqueBranchName

func (d *AutoBranchDetector) EnsureUniqueBranchName(baseName string) (string, error)

EnsureUniqueBranchName checks if a branch name exists and appends a counter if needed. Returns a unique branch name or an error if unable to generate one.

func (*AutoBranchDetector) ExecuteAutoBranch

func (d *AutoBranchDetector) ExecuteAutoBranch(ctx context.Context, context *AutoBranchContext) (string, error)

ExecuteAutoBranch executes the full auto-branch flow: 1. Pushes the branch to remote (with collision retry) 2. Checks out the tracking branch locally Returns the final branch name used (may differ from context.BranchName if collision occurred). Checkout failures are non-fatal and return an error that should be displayed as a warning.

func (*AutoBranchDetector) GenerateBranchName

func (d *AutoBranchDetector) GenerateBranchName() (string, bool, error)

GenerateBranchName generates a branch name based on the configured pattern. Returns (generated name, shouldPrompt, error). If shouldPrompt is true, the caller should prompt the user for a branch name.

func (*AutoBranchDetector) PrepareAutoBranch

func (d *AutoBranchDetector) PrepareAutoBranch(ctx context.Context, detection *DetectionResult) (*AutoBranchContext, error)

PrepareAutoBranch prepares the auto-branch operation by checking for stale remote, prompting user if needed, generating branch name, and returning the context for execution. Returns AutoBranchContext with branch name and proceed flag, or error if preparation fails.

func (*AutoBranchDetector) PushWithRetry

func (d *AutoBranchDetector) PushWithRetry(ctx context.Context, context *AutoBranchContext, maxAttempts int) (string, error)

PushWithRetry pushes the auto-created branch to remote with collision retry logic. If a branch name collision is detected, it regenerates a unique name and retries. Returns the final branch name used (which may differ from context.BranchName if collision occurred).

func (*AutoBranchDetector) ShouldAutoBranch

func (d *AutoBranchDetector) ShouldAutoBranch(result *DetectionResult) bool

ShouldAutoBranch determines if the auto-branch flow should be activated. Returns true if the user is on main/master with unpushed commits.

type BaseBranchDetector

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

BaseBranchDetector handles intelligent base branch detection for stacking

func NewBaseBranchDetector

func NewBaseBranchDetector(
	repo GitRepository,
	gitHubClient GitHubClient,
	cfg *config.DiffConfig,
	owner string,
	repoName string,
) *BaseBranchDetector

NewBaseBranchDetector creates a new base branch detector

func (*BaseBranchDetector) DetectBaseBranch

func (d *BaseBranchDetector) DetectBaseBranch(
	ctx context.Context,
	currentBranch string,
	baseFlagValue string,
) (*BaseBranchResult, error)

DetectBaseBranch intelligently detects the base branch for a PR, considering stacking scenarios

type BaseBranchResult

type BaseBranchResult struct {
	Base       string              // The detected base branch name
	IsStacking bool                // Whether this is a stacked PR
	ParentPR   *github.PullRequest // The parent PR if stacking
	Method     string              // How the base was determined
}

BaseBranchResult contains the result of base branch detection

func (*BaseBranchResult) FormatStackingMessage

func (r *BaseBranchResult) FormatStackingMessage() string

FormatStackingMessage returns a user-friendly message about the stacking result

type ContinueModeExecutor

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

ContinueModeExecutor handles the --continue workflow for diff command. This workflow loads a previously saved template, allows editing to fix validation errors, and then creates or updates the PR.

func NewContinueModeExecutor

func NewContinueModeExecutor(repo *git.Repository, client *github.Client, cfg *config.DiffConfig, owner, name string) *ContinueModeExecutor

NewContinueModeExecutor creates a new continue mode executor

func (*ContinueModeExecutor) Execute

Execute runs the complete continue mode workflow: 1. Load saved template 2. Open editor (unless --no-edit) 3. Parse and validate template 4. Create or update PR 5. Assign reviewers

type ContinueModeOptions

type ContinueModeOptions struct {
	CurrentBranch   string
	NoEdit          bool
	RequireTestPlan bool
	Draft           bool // Override draft status from template
	Ready           bool // Override ready status from template
}

ContinueModeOptions contains options for continue mode execution

type ContinueModeResult

type ContinueModeResult struct {
	PR           *github.PullRequest
	WasCreated   bool
	HeadBranch   string
	BaseBranch   string
	ParsedFields *template.TemplateFields
	Messages     []string
}

ContinueModeResult contains the results of continue mode execution

type DependentPRDetector

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

DependentPRDetector handles detection of PRs that stack on top of the current branch

func NewDependentPRDetector

func NewDependentPRDetector(
	gitHubClient GitHubClient,
	cfg *config.DiffConfig,
	owner string,
	repoName string,
) *DependentPRDetector

NewDependentPRDetector creates a new dependent PR detector

func (*DependentPRDetector) DetectDependentPRs

func (d *DependentPRDetector) DetectDependentPRs(
	ctx context.Context,
	branchName string,
) (*DependentPRInfo, error)

DetectDependentPRs finds all PRs that target the given branch as their base

func (*DependentPRDetector) ShouldShowWarning

func (d *DependentPRDetector) ShouldShowWarning() bool

ShouldShowWarning determines if the warning should be shown based on configuration

type DependentPRInfo

type DependentPRInfo struct {
	DependentPRs  []*github.PullRequest // PRs that target this branch
	HasDependents bool                  // Whether there are any dependent PRs
}

DependentPRInfo contains information about PRs that depend on the current branch

func (*DependentPRInfo) FormatDependentPRsInfo

func (info *DependentPRInfo) FormatDependentPRsInfo() string

FormatDependentPRsInfo returns a user-friendly informational message about dependent PRs

func (*DependentPRInfo) FormatDependentPRsWarning

func (info *DependentPRInfo) FormatDependentPRsWarning() string

FormatDependentPRsWarning returns a user-friendly warning message about dependent PRs

type DetectionResult

type DetectionResult struct {
	OnMainBranch  bool   // Whether the current branch is main/master
	CommitsAhead  int    // Number of commits ahead of origin/main
	DefaultBranch string // The default branch name (main or master)
}

DetectionResult represents the result of detecting commits on main.

type DiffOptions

type DiffOptions struct {
	Draft    bool
	Ready    bool
	Edit     bool
	NoEdit   bool
	Continue bool
	Base     string
}

DiffOptions contains all options for the diff command

type DiffResult

type DiffResult struct {
	PR                       *github.PullRequest
	WasCreated               bool
	DraftChanged             bool
	AutoBranchUsed           bool
	AutoBranchName           string
	AutoBranchCheckoutFailed bool
	IsStacking               bool
	BaseBranch               string
	ParentPR                 *github.PullRequest
	ReviewersAdded           []string
	Messages                 []string
}

DiffResult contains the complete results of the diff workflow

type DiffWorkflow

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

DiffWorkflow orchestrates the entire diff command workflow. It coordinates between auto-branch detection, base branch detection, template generation/editing, and PR creation/updates.

func NewDiffWorkflow

func NewDiffWorkflow(repo *git.Repository, client *github.Client, cfg *config.Config, owner, name string) *DiffWorkflow

NewDiffWorkflow creates a new diff workflow orchestrator

func (*DiffWorkflow) Execute

func (w *DiffWorkflow) Execute(ctx context.Context, opts *DiffOptions) (*DiffResult, error)

Execute runs the diff workflow based on the provided options. This is the main entry point that routes to the appropriate sub-workflow:

1. Continue Mode (--continue flag):

  • Loads saved template from previous validation failure
  • Allows user to fix errors and retry
  • See: executeContinueMode()

2. Fast Path (existing PR, no --edit flag):

  • Pushes new commits if any
  • Updates draft status if flags provided
  • Updates base branch if changed
  • See: executeFastPath()

3. Normal Mode (new PR or --edit flag):

  • Full template generation and editing flow
  • Handles auto-branch creation if on main
  • Creates or updates PR with full metadata
  • See: executeWithTemplateEditing()

type GitHubClient

type GitHubClient interface {
	GetPullRequests(ctx context.Context, owner, repo string, opts *github.PullRequestListOptions) ([]*github.PullRequest, error)
}

GitHubClient defines the interface for GitHub operations needed by base detection

type GitRepository

type GitRepository interface {
	Path() string
	GetDefaultBranch() (string, error)
	ListBranches(includeRemote bool) ([]git.BranchInfo, error)
	GetMergeBase(ref1, ref2 string) (string, error)
	GetCommitRange(from, to string) ([]git.CommitInfo, error)
	GetCommitsBetween(base, head string) ([]git.CommitInfo, error)
	IsAncestor(ancestorRef, descendantRef string) (bool, error)
}

GitRepository defines the interface for git operations needed by base detection

type OutputStyle

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

OutputStyle defines the styling configuration for terminal output

func NewOutputStyle

func NewOutputStyle(useColor bool) *OutputStyle

NewOutputStyle creates a new OutputStyle with appropriate color profile

func (*OutputStyle) Dim

func (s *OutputStyle) Dim(text string) string

Dim dims text

func (*OutputStyle) Error

func (s *OutputStyle) Error(message string) string

Error formats an error message with styling

func (*OutputStyle) Highlight

func (s *OutputStyle) Highlight(text string) string

Highlight highlights text

func (*OutputStyle) Info

func (s *OutputStyle) Info(message string) string

Info formats an info message with styling

func (*OutputStyle) Stack

func (s *OutputStyle) Stack(message string) string

Stack formats a stacking indicator

func (*OutputStyle) Success

func (s *OutputStyle) Success(message string) string

Success formats a success message with styling

func (*OutputStyle) Warning

func (s *OutputStyle) Warning(message string) string

Warning formats a warning message with styling

type PRExecutor

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

func NewPRExecutor

func NewPRExecutor(client PRGitHubClient, repo PRGitRepository, owner, name string) *PRExecutor

NewPRExecutor creates a new PR executor

func (*PRExecutor) CreateOrUpdatePR

func (e *PRExecutor) CreateOrUpdatePR(ctx context.Context, req *PRRequest) (*PRResult, error)

CreateOrUpdatePR handles the full PR creation/update flow including: - Pushing commits to remote - Creating new PR or updating existing PR - Handling draft ↔ ready transitions - Assigning reviewers

func (*PRExecutor) UpdateDraftStatus

func (e *PRExecutor) UpdateDraftStatus(ctx context.Context, pr *github.PullRequest, wantDraft bool) (*github.PullRequest, error)

UpdateDraftStatus updates only the draft status of an existing PR. This is a convenience method for the fast path when only draft status needs to change.

type PRGitHubClient

type PRGitHubClient interface {
	CreatePullRequest(ctx context.Context, owner, name, title, head, base, body string, draft bool, parentPR *github.PullRequest) (*github.PullRequest, error)
	UpdatePullRequest(ctx context.Context, owner, name string, number int, title, body string, draft *bool, parentPR *github.PullRequest) (*github.PullRequest, error)
	MarkPRReadyForReview(ctx context.Context, owner, name string, pr *github.PullRequest) (*github.PullRequest, error)
	ConvertPRToDraft(ctx context.Context, owner, name string, pr *github.PullRequest) (*github.PullRequest, error)
	AssignReviewers(ctx context.Context, owner, name string, number int, users, teams []string) error
}

PRGitHubClient defines the GitHub operations needed for PR execution

type PRGitRepository

type PRGitRepository interface {
	Push(ctx context.Context, branch string) error
	HasUnpushedCommits(branch string) (bool, error)
}

PRExecutor handles Pull Request creation, updates, and related operations. It consolidates PR workflow logic that was previously duplicated across continue mode, fast path, and normal mode in cmd/diff.go. PRGitRepository defines the git operations needed for PR execution

type PRRequest

type PRRequest struct {
	Title       string
	HeadBranch  string
	BaseBranch  string
	Body        string
	Draft       bool
	Reviewers   []string
	ExistingPR  *github.PullRequest
	ParentPR    *github.PullRequest
	CurrentUser string
}

PRRequest contains all information needed to create or update a PR

type PRResult

type PRResult struct {
	PR             *github.PullRequest
	WasCreated     bool
	DraftChanged   bool
	ReviewersAdded []string
	Pushed         bool
	Messages       []string
}

PRResult contains the results of a PR create/update operation

Jump to

Keyboard shortcuts

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