core

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 36 Imported by: 0

Documentation

Overview

Package core provides the business logic layer for Clonr.

This package contains all core functionality separated from UI concerns. Functions in this package handle validation, data transformation, and orchestration of operations across multiple subsystems.

Design Principles

  • Functions return errors instead of printing to stdout/stderr
  • All database operations go through grpc.GetClient()
  • UI-specific logic belongs in the cli package, not here

Clone Operations

Clone operations are split into two phases:

  1. PrepareClonePath - Validates URL and determines the local path
  2. SaveClonedRepo - Persists the repository to the database after git clone

This split allows the Bubbletea UI to handle the git clone progress display while core handles the validation and persistence logic.

Organization Operations

The package provides functions for managing GitHub organization repositories:

  • Fetching organization repository lists
  • Mirroring repositories locally
  • Tracking cloned organization repositories

Index

Constants

View Source
const (
	TimeoutShort  = 30 * time.Second // For quick API calls
	TimeoutMedium = 2 * time.Minute  // For standard operations
	TimeoutLong   = 5 * time.Minute  // For longer operations like uploads
	TimeoutXLong  = 10 * time.Minute // For very long operations like downloads
)

Common timeout durations used throughout the codebase

View Source
const (
	ZenHubTokenURL = "https://app.zenhub.com/settings/tokens"
	GitHubTokenURL = "https://github.com/settings/tokens"
	JiraTokenURL   = "https://id.atlassian.com/manage-profile/security/api-tokens"
)

Token page URLs

View Source
const DefaultClientID = ""

DefaultClientID is the OAuth client ID for clonr This uses the gh CLI's OAuth App credentials since cli/oauth expects them The cli/oauth package handles the client ID internally when using its default flow

View Source
const SnapshotVersion = "1.0"

SnapshotVersion is the current snapshot format version

Variables

View Source
var (
	// ErrOAuthCanceled is returned when the OAuth flow is canceled
	ErrOAuthCanceled = errors.New("OAuth flow canceled")

	// ErrOAuthExpired is returned when the device code expires
	ErrOAuthExpired = errors.New("device code expired")

	// ErrOAuthDenied is returned when the user denies authorization
	ErrOAuthDenied = errors.New("authorization denied by user")
)
View Source
var (
	// ErrProfileNotFound is returned when a profile doesn't exist
	ErrProfileNotFound = errors.New("profile not found")

	// ErrProfileExists is returned when trying to create a profile that already exists
	ErrProfileExists = errors.New("profile already exists")

	// ErrNoActiveProfile is returned when no profile is active
	ErrNoActiveProfile = errors.New("no active profile")

	// ErrTokenNotFound is returned when the token cannot be retrieved
	ErrTokenNotFound = errors.New("token not found")
)
View Source
var DefaultEditors = []EditorInfo{
	{Name: "VS Code", Command: "code", Icon: "󰨞"},
	{Name: "Cursor", Command: "cursor", Icon: "󰨞"},
	{Name: "Vim", Command: "vim", Icon: ""},
	{Name: "Neovim", Command: "nvim", Icon: ""},
	{Name: "GoLand", Command: "goland", Icon: ""},
	{Name: "IntelliJ IDEA", Command: "idea", Icon: ""},
	{Name: "WebStorm", Command: "webstorm", Icon: ""},
	{Name: "PyCharm", Command: "pycharm", Icon: ""},
	{Name: "Sublime Text", Command: "subl", Icon: ""},
	{Name: "Atom", Command: "atom", Icon: ""},
	{Name: "Nano", Command: "nano", Icon: ""},
	{Name: "Emacs", Command: "emacs", Icon: ""},
	{Name: "Helix", Command: "hx", Icon: ""},
	{Name: "Zed", Command: "zed", Icon: ""},
}

DefaultEditors is a list of common editors to check for.

View Source
var DefaultExcludeDirs = []string{
	"node_modules",
	"vendor",
	".cache",
	".npm",
	".yarn",
	"__pycache__",
	".venv",
	"venv",
	".tox",
	"target",
	"build",
	"dist",
	".gradle",
	".m2",
	"Pods",
	".pub-cache",
	".cargo",
	".rustup",
	"Library",
	"Applications",
}

DefaultExcludeDirs are directories commonly excluded from scanning

Functions

func AddCustomEditor

func AddCustomEditor(editor model.Editor) error

AddCustomEditor adds a custom editor to the configuration.

func AddRepo

func AddRepo(path string, _ AddOptions) (string, error)

AddRepo validates the path is a git repo and registers it in the DB if not present.

func CheckoutBranch

func CheckoutBranch(repoPath, branchName string) error

CheckoutBranch switches to the specified branch

func CloneRepo

func CloneRepo(args []string) error

CloneRepo is the legacy function that clones and saves in one operation

func CloneRepoWithOptions added in v0.3.0

func CloneRepoWithOptions(args []string, opts CloneOptions) error

CloneRepoWithOptions clones a repository with the specified options (non-TUI mode)

func CountCommitsByEmail

func CountCommitsByEmail(repoPath, email string) (int, error)

CountCommitsByEmail counts commits by a specific email address.

func CreateBranch

func CreateBranch(repoPath, branchName string, checkout bool) error

CreateBranch creates a new branch and optionally switches to it

func DeleteBranch

func DeleteBranch(repoPath, branchName string, force bool) error

DeleteBranch deletes a branch

func DetectJiraProject

func DetectJiraProject(arg, projectFlag string) (projectKey string, err error)

DetectJiraProject attempts to determine the Jira project key. Priority:

  1. Explicit argument (PROJ or PROJ-123)
  2. --project flag value
  3. Config file default project
  4. Error with guidance

func DetectRepository

func DetectRepository(arg, repoFlag string) (owner, repo string, err error)

DetectRepository detects the GitHub owner/repo from various sources. Priority:

  1. Explicit argument (owner/repo format)
  2. --repo flag value
  3. The current directory's git config (remote origin)

Returns owner, repo, and any error encountered.

func DetectZenHubRepo

func DetectZenHubRepo(arg, repoFlag string) (owner, repo string, err error)

DetectZenHubRepo attempts to determine the GitHub repository for ZenHub. Priority:

  1. Explicit argument (owner/repo)
  2. --repo flag value
  3. Current directory's git config
  4. Error with guidance

func ExtractJiraIssueKey

func ExtractJiraIssueKey(s string) (string, error)

ExtractJiraIssueKey extracts a full issue key (PROJ-123) from input

func FetchAndSaveGitStats

func FetchAndSaveGitStats(repoURL, repoPath string, opts FetchGitStatsOptions) error

FetchAndSaveGitStats gathers repository statistics using git-nerds and saves them

func FetchAndSaveIssues

func FetchAndSaveIssues(repoURL, repoPath string, opts FetchIssuesOptions) error

FetchAndSaveIssues fetches issues from a GitHub repository and saves them

func FormatAge

func FormatAge(t time.Time) string

FormatAge formats a time as a human-readable age string

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a duration in a human-readable way

func FormatRepoStats

func FormatRepoStats(stats *RepoStats) string

FormatRepoStats returns a formatted string of repo stats

func GetCurrentBranch

func GetCurrentBranch(repoPath string) (string, error)

GetCurrentBranch returns the current branch name for a repository

func GetCurrentGitBranch

func GetCurrentGitBranch() (string, error)

GetCurrentGitBranch returns the current git branch name

func GetCurrentWorkingDirectory

func GetCurrentWorkingDirectory() (string, error)

GetCurrentWorkingDirectory returns the current working directory

func GetCustomEditors

func GetCustomEditors() ([]model.Editor, error)

GetCustomEditors returns the list of custom editors from configuration.

func GetDiffFiles

func GetDiffFiles(repoPath string, staged bool) ([]string, error)

GetDiffFiles returns a list of changed files.

func GetDiffSummary

func GetDiffSummary(repoPath string, staged bool) (string, error)

GetDiffSummary returns a quick summary of changes.

func GetGitHubToken

func GetGitHubToken() string

GetGitHubToken retrieves GitHub token from environment or gh CLI config

func GetGitStatsSummary

func GetGitStatsSummary(repoPath string) (string, error)

GetGitStatsSummary returns a brief summary of the git statistics

func GetRepoFullName

func GetRepoFullName(owner, repo string) string

GetRepoFullName returns the full "owner/repo" name

func GitStatsExists

func GitStatsExists(repoPath string) bool

GitStatsExists checks if git stats have been gathered for a repository

func IsEditorInstalled

func IsEditorInstalled(editor string) bool

IsEditorInstalled checks if the given editor command is available in PATH.

func IsJiraIssueKey

func IsJiraIssueKey(s string) bool

IsJiraIssueKey checks if a string is a valid Jira issue key

func IsJiraProjectKey

func IsJiraProjectKey(s string) bool

IsJiraProjectKey checks if a string is a valid Jira project key

func IsNetworkError

func IsNetworkError(err error) bool

IsNetworkError checks if an error is a transient network error

func ListAuthors

func ListAuthors(repoPath string) ([]string, error)

ListAuthors returns a list of unique author emails in the repository.

func ListRepos

func ListRepos() ([]model.Repository, error)

ListRepos returns all repositories.

func ListReposFiltered

func ListReposFiltered(favoritesOnly bool) ([]model.Repository, error)

ListReposFiltered returns repos optionally filtered by favoritesOnly.

func ListReposFilteredByWorkspace added in v0.3.0

func ListReposFilteredByWorkspace(workspace string, favoritesOnly bool) ([]model.Repository, error)

ListReposFilteredByWorkspace returns repos filtered by workspace. Server-side filtering is used for efficiency.

func LogDryRunPlan

func LogDryRunPlan(plan *MirrorPlan, logger *slog.Logger)

LogDryRunPlan logs what would be done without executing

func LogMirrorSummary

func LogMirrorSummary(results []MirrorResult, logger *slog.Logger)

LogMirrorSummary logs the final summary after mirroring

func MapRepos

func MapRepos(args []string) error

MapRepos scans a directory for Git repositories and registers them

func MapReposWithOptions

func MapReposWithOptions(args []string, opts MapOptions) error

MapReposWithOptions scans a directory with custom options

func MirrorCloneRepo

func MirrorCloneRepo(repoURL, path string, shallow bool) error

MirrorCloneRepo clones a single repository for mirroring

func MirrorUpdateRepo

func MirrorUpdateRepo(repoURL, path string, strategy DirtyRepoStrategy, logger *slog.Logger) error

MirrorUpdateRepo pulls the latest changes for mirroring with dirty repo strategy support

func NewGitHubClient added in v0.3.0

func NewGitHubClient(ctx context.Context, token string) *github.Client

NewGitHubClient creates a new authenticated GitHub client using the provided token. This is the standard way to create GitHub API clients throughout the codebase.

func NewGitHubClientWithContext added in v0.3.0

func NewGitHubClientWithContext(token string) *github.Client

NewGitHubClientWithContext creates a new authenticated GitHub client using background context. This is a convenience function for cases where a fresh context is preferred.

func NewOAuth2HTTPClient added in v0.3.0

func NewOAuth2HTTPClient(ctx context.Context, token string) *http.Client

NewOAuth2HTTPClient creates an authenticated HTTP client for direct HTTP requests. Use this when you need to make authenticated requests outside of the GitHub API, such as downloading release assets directly.

func OpenBrowser

func OpenBrowser(url string) error

OpenBrowser opens a URL in the default browser (cross-platform)

func OpenGitHubTokenPage

func OpenGitHubTokenPage() error

OpenGitHubTokenPage opens the GitHub token settings page in the browser

func OpenInEditor

func OpenInEditor(editor, path string) error

OpenInEditor opens the given path in the specified editor.

func OpenInFileManager

func OpenInFileManager(path string) error

OpenInFileManager opens the given path in the system's default file manager.

func OpenJiraTokenPage

func OpenJiraTokenPage() error

OpenJiraTokenPage opens the Jira/Atlassian token settings page in the browser

func OpenZenHubTokenPage

func OpenZenHubTokenPage() error

OpenZenHubTokenPage opens the ZenHub token settings page in the browser

func PrepareClonePath deprecated

func PrepareClonePath(args []string, opts CloneOptions) (*url.URL, string, error)

PrepareClonePath validates the URL and determines the target path for cloning.

Deprecated: Use PrepareClone instead.

func PrintBatchSummary

func PrintBatchSummary(result *MirrorBatchResult)

PrintBatchSummary prints a summary of the batch mirror results

func PrintDryRunPlan

func PrintDryRunPlan(plan *MirrorPlan)

PrintDryRunPlan prints what would be done without executing (for TUI display)

func PrintMirrorSummary

func PrintMirrorSummary(results []MirrorResult)

PrintMirrorSummary prints the final summary after mirroring (for TUI display)

func PullRepo

func PullRepo(path string) error

func RefreshGitStats

func RefreshGitStats(repoURL, repoPath string, opts FetchGitStatsOptions) error

RefreshGitStats updates the git statistics for a repository

func RemoveCustomEditor

func RemoveCustomEditor(name string) error

RemoveCustomEditor removes a custom editor from the configuration.

func RemoveRepo

func RemoveRepo(urlStr string) error

func ResetConfig

func ResetConfig() error

ResetConfig resets the configuration to default values

func SaveClonedRepo

func SaveClonedRepo(uri *url.URL, savePath string) error

SaveClonedRepo saves the successfully cloned repository to the database

func SaveClonedRepoFromResult added in v0.3.0

func SaveClonedRepoFromResult(result *CloneResult) error

SaveClonedRepoFromResult saves the repository using CloneResult

func SaveClonedRepoWithWorkspace added in v0.3.0

func SaveClonedRepoWithWorkspace(uri *url.URL, savePath string, workspace string) error

SaveClonedRepoWithWorkspace saves the cloned repository with workspace

func SaveMirroredRepo

func SaveMirroredRepo(repoURL, path string) error

SaveMirroredRepo saves the repo to a database and gathers statistics

func SetFavoriteByURL

func SetFavoriteByURL(url string, fav bool) error

func ShowConfig

func ShowConfig() error

ShowConfig displays the current configuration

func TruncateString

func TruncateString(s string, maxLen int) string

TruncateString truncates a string to a maximum length with ellipsis

func UpdateAllRepos

func UpdateAllRepos()

UpdateAllRepos pulls the latest changes for all repositories in the clonr database.

func UpdateRepo

func UpdateRepo(url, path string) error

func ValidateOrgName

func ValidateOrgName(orgName string) error

ValidateOrgName validates the organization name

func ValidateToken

func ValidateToken(ctx context.Context, token, host string) (bool, string, error)

ValidateToken checks if a token is still valid by making an API call

func WithLongTimeout added in v0.3.0

func WithLongTimeout() (context.Context, context.CancelFunc)

WithLongTimeout creates a context with a 5-minute timeout. Use for longer operations like file uploads.

func WithMediumTimeout added in v0.3.0

func WithMediumTimeout() (context.Context, context.CancelFunc)

WithMediumTimeout creates a context with a 2-minute timeout. Use for standard operations like listing resources.

func WithShortTimeout added in v0.3.0

func WithShortTimeout() (context.Context, context.CancelFunc)

WithShortTimeout creates a context with a 30-second timeout. Use for quick API calls like fetching single resources.

func WithTimeout added in v0.3.0

func WithTimeout(d time.Duration) (context.Context, context.CancelFunc)

WithTimeout creates a context with a custom timeout duration. Prefer the predefined timeout functions when applicable.

func WithTimeoutFrom added in v0.3.0

func WithTimeoutFrom(parent context.Context, d time.Duration) (context.Context, context.CancelFunc)

WithTimeoutFrom creates a context with timeout derived from parent context. Use when you need to inherit cancellation from a parent context.

func WithXLongTimeout added in v0.3.0

func WithXLongTimeout() (context.Context, context.CancelFunc)

WithXLongTimeout creates a context with a 10-minute timeout. Use for very long operations like large file downloads.

func WriteSnapshot

func WriteSnapshot(w io.Writer, snapshot *Snapshot, pretty bool) error

WriteSnapshot writes a snapshot to a writer as JSON

func WriteSnapshotToFile

func WriteSnapshotToFile(path string, snapshot *Snapshot, pretty bool) error

WriteSnapshotToFile writes a snapshot to a file

Types

type AddOptions

type AddOptions struct {
	Yes  bool   // skip confirmation (handled at CLI level)
	Name string // reserved for future use
}

AddOptions holds optional parameters for adding a repo.

type AuthorStats

type AuthorStats struct {
	Name         string    `json:"name"`
	Email        string    `json:"email"`
	Commits      int       `json:"commits"`
	LinesAdded   int       `json:"lines_added"`
	LinesDeleted int       `json:"lines_deleted"`
	LinesChanged int       `json:"lines_changed"`
	FilesChanged int       `json:"files_changed"`
	FirstCommit  time.Time `json:"first_commit"`
	LastCommit   time.Time `json:"last_commit"`
	ActiveDays   int       `json:"active_days"`
}

AuthorStats contains statistics for a single author

type Branch

type Branch struct {
	Name      string `json:"name"`
	IsCurrent bool   `json:"is_current"`
	IsRemote  bool   `json:"is_remote"`
}

Branch represents a git branch

func ListBranches

func ListBranches(repoPath string, opts BranchListOptions) ([]Branch, error)

ListBranches returns all branches for a repository at the given path

type BranchListOptions

type BranchListOptions struct {
	IncludeRemote bool // Include remote branches
	All           bool // Show all branches (local + remote)
}

BranchListOptions configures branch listing

type BranchSection

type BranchSection struct {
	Remote string `ini:"remote"`
	Merge  string `ini:"merge"`
}

type BranchStats

type BranchStats struct {
	Name      string        `json:"name"`
	Hash      string        `json:"hash"`
	UpdatedAt time.Time     `json:"updated_at"`
	Age       time.Duration `json:"age"`
	IsActive  bool          `json:"is_active"`
}

BranchStats contains branch information

type CheckRun

type CheckRun struct {
	Name        string     `json:"name"`
	Status      string     `json:"status"`     // queued, in_progress, completed
	Conclusion  string     `json:"conclusion"` // success, failure, neutral, cancelled, skipped, timed_out, action_required
	URL         string     `json:"url,omitempty"`
	StartedAt   *time.Time `json:"started_at,omitempty"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

CheckRun represents a CI check run status

type CloneOptions

type CloneOptions struct {
	Force     bool     // Force clone even if the repo exists (removes existing)
	GitArgs   []string // Additional git clone arguments
	Protocol  string   // Preferred protocol (https or ssh), empty for auto-detect
	Workspace string   // Workspace to clone into (empty for active workspace or default)
}

CloneOptions configures the clone operation

type CloneResult added in v0.3.0

type CloneResult struct {
	Repository *giturl.Repository
	CloneURL   string
	TargetPath string
	GitArgs    []string
	Workspace  string // Workspace the repo was cloned into
}

CloneResult contains the result of a clone operation

func PrepareClone added in v0.3.0

func PrepareClone(args []string, opts CloneOptions) (*CloneResult, error)

PrepareClone parses clone arguments and prepares for cloning. Supports multiple input formats like gh repo clone:

Arguments format: <repository> [<directory>] [-- <gitflags>...] Note: Cobra strips the "--" separator, so args after repo that start with "-" are treated as git flags.

type CloseIssueOptions

type CloseIssueOptions struct {
	Comment string // Optional comment to add when closing
	Reason  string // Close reason: completed, not_planned (default: completed)
	Logger  *slog.Logger
}

CloseIssueOptions configures issue closing

type ClosedIssue

type ClosedIssue struct {
	Number   int       `json:"number"`
	Title    string    `json:"title"`
	URL      string    `json:"url"`
	State    string    `json:"state"`
	ClosedAt time.Time `json:"closed_at"`
}

ClosedIssue represents the result of closing an issue

func CloseIssue

func CloseIssue(token, owner, repo string, issueNumber int, opts CloseIssueOptions) (*ClosedIssue, error)

CloseIssue closes an issue in the specified repository

type Contributor

type Contributor struct {
	Login         string `json:"login"`
	Name          string `json:"name,omitempty"`
	AvatarURL     string `json:"avatar_url"`
	Contributions int    `json:"contributions"`
	URL           string `json:"url"`
}

Contributor represents a repository contributor

type ContributorCommit

type ContributorCommit struct {
	SHA       string    `json:"sha"`
	Message   string    `json:"message"`
	Date      time.Time `json:"date"`
	Additions int       `json:"additions"`
	Deletions int       `json:"deletions"`
	URL       string    `json:"url"`
}

ContributorCommit represents a commit by a contributor

type ContributorIssue

type ContributorIssue struct {
	Number    int       `json:"number"`
	Title     string    `json:"title"`
	State     string    `json:"state"`
	CreatedAt time.Time `json:"created_at"`
	URL       string    `json:"url"`
}

ContributorIssue represents an issue created by a contributor

type ContributorJourney

type ContributorJourney struct {
	Contributor   Contributor         `json:"contributor"`
	Commits       []ContributorCommit `json:"commits"`
	PullRequests  []ContributorPR     `json:"pull_requests"`
	Issues        []ContributorIssue  `json:"issues"`
	TotalCommits  int                 `json:"total_commits"`
	TotalPRs      int                 `json:"total_prs"`
	TotalIssues   int                 `json:"total_issues"`
	FirstActivity *time.Time          `json:"first_activity,omitempty"`
	LastActivity  *time.Time          `json:"last_activity,omitempty"`
}

ContributorJourney represents a contributor's activity in a repository

func GetContributorJourney

func GetContributorJourney(token, owner, repo, username string, opts GetContributorJourneyOptions) (*ContributorJourney, error)

GetContributorJourney returns the activity journey of a contributor

type ContributorPR

type ContributorPR struct {
	Number    int        `json:"number"`
	Title     string     `json:"title"`
	State     string     `json:"state"`
	Merged    bool       `json:"merged"`
	CreatedAt time.Time  `json:"created_at"`
	MergedAt  *time.Time `json:"merged_at,omitempty"`
	URL       string     `json:"url"`
}

ContributorPR represents a pull request by a contributor

type ContributorStats

type ContributorStats struct {
	Name    string    `json:"name"`
	Email   string    `json:"email"`
	Commits int       `json:"commits"`
	Since   time.Time `json:"since"`
}

ContributorStats contains simplified contributor information

type ContributorsResult

type ContributorsResult struct {
	Repository   string        `json:"repository"`
	Contributors []Contributor `json:"contributors"`
	TotalCount   int           `json:"total_count"`
}

ContributorsResult contains the list of contributors

func ListContributors

func ListContributors(token, owner, repo string, opts ListContributorsOptions) (*ContributorsResult, error)

ListContributors returns the list of contributors for a repository

type CoreSection

type CoreSection struct {
	RepositoryFormatVersion int  `ini:"repositoryformatversion"`
	FileMode                bool `ini:"filemode"`
	Bare                    bool `ini:"bare"`
}

type CreateIssueOptions

type CreateIssueOptions struct {
	Title     string
	Body      string
	Labels    []string
	Assignees []string
	Milestone int // Milestone number (0 = none)
	Logger    *slog.Logger
}

CreateIssueOptions configures issue creation

type CreateReleaseOptions

type CreateReleaseOptions struct {
	TagName         string   // Required: Tag name for the release
	TargetCommitish string   // Branch or commit SHA (default: default branch)
	Name            string   // Release name (default: tag name)
	Body            string   // Release notes
	Draft           bool     // Create as draft
	Prerelease      bool     // Mark as prerelease
	GenerateNotes   bool     // Auto-generate release notes
	Assets          []string // Local file paths to upload as assets
	Logger          *slog.Logger
}

CreateReleaseOptions configures release creation

type CreateSnapshotOptions

type CreateSnapshotOptions struct {
	IncludeBranches bool // Fetch current branch for each repo
	IncludeConfig   bool // Include configuration
}

CreateSnapshotOptions configures snapshot creation

func DefaultSnapshotOptions

func DefaultSnapshotOptions() CreateSnapshotOptions

DefaultSnapshotOptions returns sensible defaults for snapshot creation

type CreatedIssue

type CreatedIssue struct {
	Number    int       `json:"number"`
	Title     string    `json:"title"`
	URL       string    `json:"url"`
	State     string    `json:"state"`
	CreatedAt time.Time `json:"created_at"`
}

CreatedIssue represents the result of creating an issue

func CreateIssue

func CreateIssue(token, owner, repo string, opts CreateIssueOptions) (*CreatedIssue, error)

CreateIssue creates a new issue in the specified repository

type DeviceCode

type DeviceCode struct {
	UserCode        string
	VerificationURL string
}

DeviceCode represents the device code response from GitHub

type DiffOptions

type DiffOptions struct {
	Staged   bool // Show staged changes (--cached)
	Stat     bool // Show diffstat instead of full diff
	NameOnly bool // Show only file names
}

DiffOptions configures diff behavior.

type DiffResult

type DiffResult struct {
	RepoPath   string   `json:"repo_path"`
	RepoURL    string   `json:"repo_url,omitempty"`
	HasChanges bool     `json:"has_changes"`
	Files      []string `json:"files,omitempty"`
	Stats      string   `json:"stats,omitempty"`
	Diff       string   `json:"diff,omitempty"`
}

DiffResult holds parsed diff information.

func GetDiff

func GetDiff(repoPath string, opts DiffOptions) (*DiffResult, error)

GetDiff returns git diff for a repository.

type DirtyRepoError

type DirtyRepoError struct {
	Path string
}

DirtyRepoError indicates a repository has uncommitted changes

func (*DirtyRepoError) Error

func (e *DirtyRepoError) Error() string

type DirtyRepoStrategy

type DirtyRepoStrategy int

DirtyRepoStrategy defines how to handle repos with uncommitted changes

const (
	DirtyStrategySkip  DirtyRepoStrategy = iota // Skip with warning (default)
	DirtyStrategyStash                          // Stash changes, pull, unstash
	DirtyStrategyReset                          // Reset to a clean state (destructive)
)

func ParseDirtyStrategy

func ParseDirtyStrategy(s string) DirtyRepoStrategy

ParseDirtyStrategy converts a string to DirtyRepoStrategy

func (DirtyRepoStrategy) String

func (s DirtyRepoStrategy) String() string

type DotGit

type DotGit struct {
	*GitConfig

	Path string
	URL  *url.URL
}

type DownloadReleaseOptions

type DownloadReleaseOptions struct {
	Tag      string   // Specific tag or "latest" (default: latest)
	Patterns []string // Asset name patterns to download (glob-like)
	Dir      string   // Destination directory (default: current dir)
	Logger   *slog.Logger
}

DownloadReleaseOptions configures release download

type DownloadResult

type DownloadResult struct {
	Release Release          `json:"release"`
	Files   []DownloadedFile `json:"files"`
}

DownloadResult contains info about downloaded assets

func DownloadRelease

func DownloadRelease(token, owner, repo string, opts DownloadReleaseOptions) (*DownloadResult, error)

DownloadRelease downloads release assets

type DownloadedFile

type DownloadedFile struct {
	Name string `json:"name"`
	Path string `json:"path"`
	Size int64  `json:"size"`
}

DownloadedFile represents a downloaded asset

type EditorInfo

type EditorInfo struct {
	Name    string
	Command string
	Icon    string
}

EditorInfo represents editor information for display.

func GetAllEditors

func GetAllEditors() ([]EditorInfo, error)

GetAllEditors returns all editors (default + custom).

func GetInstalledEditors

func GetInstalledEditors() ([]EditorInfo, error)

GetInstalledEditors returns only installed editors (default + custom).

type FetchGitStatsOptions

type FetchGitStatsOptions struct {
	Logger          *slog.Logger
	IncludeTemporal bool // Include temporal analysis (commits by day/month/etc)
	IncludeBranches bool // Include branch information
	Since           time.Time
	Until           time.Time
}

FetchGitStatsOptions configures the git stats fetching behavior

type FetchIssuesOptions

type FetchIssuesOptions struct {
	Token      string
	Logger     *slog.Logger
	IncludePRs bool // Whether to include pull requests (default: false)
}

FetchIssuesOptions configures the issue fetching behavior

type GetContributorJourneyOptions

type GetContributorJourneyOptions struct {
	IncludeCommits bool
	IncludePRs     bool
	IncludeIssues  bool
	Limit          int // Limit per category
}

GetContributorJourneyOptions configures the journey retrieval

type GetWorkflowRunOptions

type GetWorkflowRunOptions struct {
	IncludeJobs bool // Include job details
	Logger      *slog.Logger
}

GetWorkflowRunOptions configures getting a specific workflow run

type GitConfig

type GitConfig struct {
	Core   CoreSection              `ini:"core"`
	Remote map[string]RemoteSection `ini:"remote"`
	Branch map[string]BranchSection `ini:"branch"`
}

type GitHubClientWrapper

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

GitHubClientWrapper wraps the GitHub client with rate limit awareness

func NewGitHubClientWrapper

func NewGitHubClientWrapper(token string, cfg RateLimitConfig, logger *slog.Logger) *GitHubClientWrapper

NewGitHubClientWrapper creates a rate-limit-aware GitHub client

type GitStats

type GitStats struct {
	Repository   string    `json:"repository"`
	Path         string    `json:"path"`
	FetchedAt    time.Time `json:"fetched_at"`
	TotalCommits int       `json:"total_commits"`
	TotalAuthors int       `json:"total_authors"`
	LinesAdded   int       `json:"lines_added"`
	LinesDeleted int       `json:"lines_deleted"`
	LinesChanged int       `json:"lines_changed"`

	// Temporal boundaries
	FirstCommitAt time.Time `json:"first_commit_at,omitzero"`
	LastCommitAt  time.Time `json:"last_commit_at,omitzero"`

	// Detailed statistics
	Authors      []AuthorStats      `json:"authors,omitempty"`
	Contributors []ContributorStats `json:"contributors,omitempty"`
	Branches     []BranchStats      `json:"branches,omitempty"`

	// Temporal analysis
	CommitsByDay      map[string]int `json:"commits_by_day,omitempty"`
	CommitsByMonth    map[string]int `json:"commits_by_month,omitempty"`
	CommitsByYear     map[string]int `json:"commits_by_year,omitempty"`
	CommitsByWeekday  map[string]int `json:"commits_by_weekday,omitempty"`
	CommitsByHour     map[int]int    `json:"commits_by_hour,omitempty"`
	CommitsByTimezone map[string]int `json:"commits_by_timezone,omitempty"`
}

GitStats contains comprehensive repository statistics from git-nerds

func LoadGitStats

func LoadGitStats(repoPath string) (*GitStats, error)

LoadGitStats loads previously saved git statistics from a repository

type Issue

type Issue struct {
	Number    int        `json:"number"`
	Title     string     `json:"title"`
	State     string     `json:"state"`
	Body      string     `json:"body,omitempty"`
	Labels    []string   `json:"labels,omitempty"`
	Assignees []string   `json:"assignees,omitempty"`
	Author    string     `json:"author"`
	CreatedAt time.Time  `json:"created_at"`
	UpdatedAt time.Time  `json:"updated_at"`
	ClosedAt  *time.Time `json:"closed_at,omitempty"`
	Comments  int        `json:"comments"`
	URL       string     `json:"url"`
	IsPR      bool       `json:"is_pull_request"`
}

Issue represents a GitHub issue with essential fields

type IssuesData

type IssuesData struct {
	Repository  string    `json:"repository"`
	FetchedAt   time.Time `json:"fetched_at"`
	TotalCount  int       `json:"total_count"`
	OpenCount   int       `json:"open_count"`
	ClosedCount int       `json:"closed_count"`
	Issues      []Issue   `json:"issues"`
}

IssuesData contains all issues for a repository

func ListIssuesFromAPI

func ListIssuesFromAPI(token, owner, repo string, opts ListIssuesOptions) (*IssuesData, error)

ListIssuesFromAPI fetches issues directly from GitHub API

type JobStep

type JobStep struct {
	Name        string     `json:"name"`
	Status      string     `json:"status"`
	Conclusion  string     `json:"conclusion"`
	Number      int64      `json:"number"`
	StartedAt   *time.Time `json:"started_at,omitempty"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
}

JobStep represents a step within a workflow job

type ListContributorsOptions

type ListContributorsOptions struct {
	Limit int // Maximum number of contributors to return
}

ListContributorsOptions configures the contributor listing

type ListIssuesOptions

type ListIssuesOptions struct {
	State    string   // open, closed, all (default: open)
	Labels   []string // Filter by labels
	Assignee string   // Filter by assignee
	Creator  string   // Filter by creator
	Sort     string   // created, updated, comments (default: created)
	Order    string   // asc, desc (default: desc)
	Limit    int      // Max issues to return (0 = unlimited)
	Logger   *slog.Logger
}

ListIssuesOptions configures the issue listing behavior

type ListOrganizationsOptions

type ListOrganizationsOptions struct {
	IncludeUser bool // Include user's personal repos as pseudo-org
}

ListOrganizationsOptions configures the organization listing

type ListPRsOptions

type ListPRsOptions struct {
	State  string // open, closed, all (default: open)
	Sort   string // created, updated, popularity, long-running (default: created)
	Order  string // asc, desc (default: desc)
	Base   string // Filter by base branch
	Head   string // Filter by head branch (user:branch or org:branch)
	Limit  int    // Max PRs to return (0 = unlimited)
	Logger *slog.Logger
}

ListPRsOptions configures PR listing

type ListReleasesOptions

type ListReleasesOptions struct {
	Limit  int // Max releases to return (0 = unlimited)
	Logger *slog.Logger
}

ListReleasesOptions configures release listing

type ListWorkflowRunsOptions

type ListWorkflowRunsOptions struct {
	Branch     string // Filter by branch
	Event      string // Filter by event type (push, pull_request, etc.)
	Status     string // Filter by status (queued, in_progress, completed)
	Actor      string // Filter by actor (username)
	WorkflowID int64  // Filter by specific workflow ID
	Limit      int    // Max runs to return (0 = unlimited)
	Logger     *slog.Logger
}

ListWorkflowRunsOptions configures workflow run listing

type MapOptions

type MapOptions struct {
	DryRun    bool     // Don't actually add repos, just show what would be added
	MaxDepth  int      // Maximum directory depth to scan (0 = unlimited)
	Exclude   []string // Directory names to skip (e.g., node_modules, vendor)
	JSON      bool     // Output results as JSON
	Verbose   bool     // Show verbose output
	Workspace string   // Workspace to assign to found repos (empty = no workspace)
}

MapOptions configures the repository mapping operation

type MapResult

type MapResult struct {
	ScannedDir   string          `json:"scanned_dir"`
	Found        []MappedRepo    `json:"found"`
	AlreadyAdded []MappedRepo    `json:"already_added"`
	Errors       []MappedRepoErr `json:"errors,omitempty"`
	TotalFound   int             `json:"total_found"`
	TotalAdded   int             `json:"total_added"`
	TotalSkipped int             `json:"total_skipped"`
	TotalErrors  int             `json:"total_errors"`
}

MapResult contains the result of a mapping operation

type MappedRepo

type MappedRepo struct {
	Path string `json:"path"`
	URL  string `json:"url"`
}

MappedRepo represents a discovered repository

type MappedRepoErr

type MappedRepoErr struct {
	Path  string `json:"path"`
	Error string `json:"error"`
}

MappedRepoErr represents an error during mapping

type MirrorBatchOptions

type MirrorBatchOptions struct {
	Plan   *MirrorPlan
	Logger *slog.Logger
}

MirrorBatchOptions configures batch (non-TUI) mirror execution

type MirrorBatchResult

type MirrorBatchResult struct {
	Results  []MirrorResult
	Cloned   int
	Updated  int
	Skipped  int
	Failed   int
	Duration time.Duration
}

MirrorBatchResult contains the results of a batch mirror operation

func ExecuteMirrorBatch

func ExecuteMirrorBatch(opts MirrorBatchOptions) (*MirrorBatchResult, error)

ExecuteMirrorBatch runs the mirror operation without TUI

type MirrorOptions

type MirrorOptions struct {
	SkipArchived    bool
	PublicOnly      bool
	Filter          *regexp.Regexp
	Parallel        int
	DirtyStrategy   DirtyRepoStrategy
	RateLimitConfig RateLimitConfig
	NetworkRetries  int // default: 3
	Shallow         bool
	Logger          *slog.Logger
}

MirrorOptions contains configuration for mirror operations

type MirrorPlan

type MirrorPlan struct {
	OrgName        string
	Repos          []MirrorRepo
	BaseDir        string
	Token          string
	Parallel       int
	SkipArchived   bool
	Filter         *regexp.Regexp
	DirtyStrategy  DirtyRepoStrategy
	NetworkRetries int
	Shallow        bool
	Logger         *slog.Logger
}

MirrorPlan represents the prepared mirror operation

func PrepareMirror

func PrepareMirror(orgName, token string, opts MirrorOptions) (*MirrorPlan, error)

PrepareMirror fetches repos from GitHub and determines actions

type MirrorRepo

type MirrorRepo struct {
	Name       string
	URL        string
	Path       string
	Action     string // "clone", "update", or "skip"
	Reason     string // reason for skip
	SkipReason SkipReason
	IsArchived bool
	IsFork     bool
	Size       int64
}

MirrorRepo represents a single repository to mirror

type MirrorResult

type MirrorResult struct {
	Repo       MirrorRepo
	Success    bool
	Error      error
	Duration   int64 // duration in milliseconds
	RetryCount int   // number of retries performed
}

MirrorResult captures the result of mirroring one repo

type NetworkError

type NetworkError struct {
	Operation string
	Err       error
	Attempts  int
}

NetworkError wraps transient network failures

func (*NetworkError) Error

func (e *NetworkError) Error() string

func (*NetworkError) Unwrap

func (e *NetworkError) Unwrap() error

type OAuthConfig

type OAuthConfig struct {
	Host     string
	Scopes   []string
	ClientID string
}

OAuthConfig holds OAuth configuration

type OAuthFlow

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

OAuthFlow handles the OAuth device flow

func NewOAuthFlow

func NewOAuthFlow(host string, scopes []string) *OAuthFlow

NewOAuthFlow creates a new OAuth flow

func (*OAuthFlow) OnDeviceCode

func (f *OAuthFlow) OnDeviceCode(callback func(code, verificationURL string))

OnDeviceCode sets the callback for when a device code is received

func (*OAuthFlow) Run

func (f *OAuthFlow) Run(ctx context.Context) (*OAuthResult, error)

Run executes the OAuth device flow and returns the result

type OAuthResult

type OAuthResult struct {
	Token    string
	Username string
	Scopes   []string
}

OAuthResult contains the result of an OAuth flow

type Organization

type Organization struct {
	Login       string
	Name        string
	Description string
	URL         string
	RepoCount   int
	IsMirrored  bool
	MirrorPath  string
	LocalRepos  int
}

Organization represents a GitHub organization with local mirror status

func ListOrganizations

func ListOrganizations(token string, opts ListOrganizationsOptions) ([]Organization, error)

ListOrganizations fetches the user's GitHub organizations and checks mirror status

type PRStatus

type PRStatus struct {
	Number       int        `json:"number"`
	Title        string     `json:"title"`
	State        string     `json:"state"` // open, closed
	Merged       bool       `json:"merged"`
	Draft        bool       `json:"draft"`
	Mergeable    *bool      `json:"mergeable,omitempty"` // nil if unknown
	Author       string     `json:"author"`
	Branch       string     `json:"head_branch"`
	BaseBranch   string     `json:"base_branch"`
	ReviewState  string     `json:"review_state"` // approved, changes_requested, pending, commented
	Checks       []CheckRun `json:"checks,omitempty"`
	ChecksStatus string     `json:"checks_status"` // success, failure, pending, none
	Additions    int        `json:"additions"`
	Deletions    int        `json:"deletions"`
	ChangedFiles int        `json:"changed_files"`
	Comments     int        `json:"comments"`
	ReviewCount  int        `json:"review_count"`
	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"`
	URL          string     `json:"url"`
	Labels       []string   `json:"labels,omitempty"`
	Assignees    []string   `json:"assignees,omitempty"`
	Reviewers    []string   `json:"reviewers,omitempty"`
}

PRStatus represents the status of a pull request

func GetPRStatus

func GetPRStatus(token, owner, repo string, prNumber int, opts PRStatusOptions) (*PRStatus, error)

GetPRStatus retrieves the status of a specific pull request

type PRStatusOptions

type PRStatusOptions struct {
	Logger *slog.Logger
}

PRStatusOptions configures PR status retrieval

type PRsData

type PRsData struct {
	Repository  string     `json:"repository"`
	FetchedAt   time.Time  `json:"fetched_at"`
	TotalCount  int        `json:"total_count"`
	OpenCount   int        `json:"open_count"`
	ClosedCount int        `json:"closed_count"`
	MergedCount int        `json:"merged_count"`
	PRs         []PRStatus `json:"pull_requests"`
}

PRsData contains all PRs for a repository

func ListOpenPRs

func ListOpenPRs(token, owner, repo string, opts ListPRsOptions) (*PRsData, error)

ListOpenPRs lists open pull requests for a repository

type PathCollisionError

type PathCollisionError struct {
	Path        string
	ExpectedURL string
	ActualURL   string
}

PathCollisionError indicates the path exists with different content

func (*PathCollisionError) Error

func (e *PathCollisionError) Error() string

type ProfileManager

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

ProfileManager handles profile operations

func NewProfileManager

func NewProfileManager() (*ProfileManager, error)

NewProfileManager creates a new ProfileManager

func (*ProfileManager) CreateProfile

func (pm *ProfileManager) CreateProfile(ctx context.Context, name, host string, scopes []string) (*model.Profile, string, error)

CreateProfile creates a new profile with OAuth authentication

func (*ProfileManager) DeleteProfile

func (pm *ProfileManager) DeleteProfile(name string) error

DeleteProfile removes a profile and its stored token

func (*ProfileManager) GetActiveProfile

func (pm *ProfileManager) GetActiveProfile() (*model.Profile, error)

GetActiveProfile retrieves the currently active profile

func (*ProfileManager) GetActiveProfileToken

func (pm *ProfileManager) GetActiveProfileToken() (string, error)

GetActiveProfileToken retrieves the token for the active profile

func (*ProfileManager) GetProfile

func (pm *ProfileManager) GetProfile(name string) (*model.Profile, error)

GetProfile retrieves a profile by name

func (*ProfileManager) GetProfileToken

func (pm *ProfileManager) GetProfileToken(name string) (string, error)

GetProfileToken retrieves the token for a profile

func (*ProfileManager) ListProfiles

func (pm *ProfileManager) ListProfiles() ([]model.Profile, error)

ListProfiles returns all profiles

func (*ProfileManager) RefreshProfile

func (pm *ProfileManager) RefreshProfile(ctx context.Context, name string) error

RefreshProfile refreshes a profile's OAuth token

func (*ProfileManager) SetActiveProfile

func (pm *ProfileManager) SetActiveProfile(name string) error

SetActiveProfile sets the active profile

func (*ProfileManager) UpdateProfile added in v0.3.0

func (pm *ProfileManager) UpdateProfile(profile *model.Profile) error

UpdateProfile updates an existing profile

func (*ProfileManager) ValidateProfileToken

func (pm *ProfileManager) ValidateProfileToken(ctx context.Context, name string) (bool, error)

ValidateProfileToken checks if a profile's token is still valid

type RateLimitConfig

type RateLimitConfig struct {
	MaxRetries        int           // Maximum retry attempts (default: 5)
	InitialBackoff    time.Duration // Initial backoff duration (default: 1s)
	MaxBackoff        time.Duration // Maximum backoff duration (default: 2min)
	BackoffMultiplier float64       // Multiplier for exponential backoff (default: 2.0)
}

RateLimitConfig contains settings for GitHub API rate limiting

func DefaultRateLimitConfig

func DefaultRateLimitConfig() RateLimitConfig

DefaultRateLimitConfig returns sensible defaults

type ReauthorOptions

type ReauthorOptions struct {
	// OldEmail is the email address to replace
	OldEmail string
	// NewEmail is the new email address
	NewEmail string
	// NewName is the new author/committer name (optional, keeps existing if empty)
	NewName string
	// RepoPath is the path to the repository (uses current directory if empty)
	RepoPath string
	// AllRefs rewrites all branches and tags when true
	AllRefs bool
}

ReauthorOptions contains options for rewriting git author history.

type ReauthorResult

type ReauthorResult struct {
	// CommitsRewritten is the number of commits that were rewritten
	CommitsRewritten int
	// TagsRewritten is the list of tags that were rewritten
	TagsRewritten []string
	// BranchesRewritten is the list of branches that were rewritten
	BranchesRewritten []string
}

ReauthorResult contains the result of a reauthor operation.

func Reauthor

func Reauthor(opts ReauthorOptions) (*ReauthorResult, error)

Reauthor rewrites git history to change author/committer email and name. This delegates to git-nerds library for the actual implementation.

type Release

type Release struct {
	ID          int64          `json:"id"`
	TagName     string         `json:"tag_name"`
	Name        string         `json:"name"`
	Body        string         `json:"body,omitempty"`
	Draft       bool           `json:"draft"`
	Prerelease  bool           `json:"prerelease"`
	CreatedAt   time.Time      `json:"created_at"`
	PublishedAt *time.Time     `json:"published_at,omitempty"`
	Author      string         `json:"author"`
	URL         string         `json:"url"`
	TarballURL  string         `json:"tarball_url,omitempty"`
	ZipballURL  string         `json:"zipball_url,omitempty"`
	Assets      []ReleaseAsset `json:"assets,omitempty"`
}

Release represents a GitHub release

func CreateRelease

func CreateRelease(token, owner, repo string, opts CreateReleaseOptions) (*Release, error)

CreateRelease creates a new release

func GetRelease

func GetRelease(token, owner, repo, tag string) (*Release, error)

GetRelease gets a specific release by tag

type ReleaseAsset

type ReleaseAsset struct {
	ID            int64     `json:"id"`
	Name          string    `json:"name"`
	Label         string    `json:"label,omitempty"`
	ContentType   string    `json:"content_type"`
	Size          int       `json:"size"`
	DownloadCount int       `json:"download_count"`
	CreatedAt     time.Time `json:"created_at"`
	UpdatedAt     time.Time `json:"updated_at"`
	DownloadURL   string    `json:"download_url"`
}

ReleaseAsset represents a release asset

type ReleasesData

type ReleasesData struct {
	Repository string    `json:"repository"`
	FetchedAt  time.Time `json:"fetched_at"`
	TotalCount int       `json:"total_count"`
	Releases   []Release `json:"releases"`
}

ReleasesData contains releases for a repository

func ListReleases

func ListReleases(token, owner, repo string, opts ListReleasesOptions) (*ReleasesData, error)

ListReleases lists releases for a repository

type RemoteSection

type RemoteSection struct {
	URL   string `ini:"url"`
	Fetch string `ini:"fetch"`
}

type RepoStats

type RepoStats struct {
	TotalCommits   int       `json:"total_commits"`
	RecentCommits  int       `json:"recent_commits"` // Last 30 days
	LastCommitDate time.Time `json:"last_commit_date"`
	LastCommitMsg  string    `json:"last_commit_msg"`
	Additions      int       `json:"additions"`
	Deletions      int       `json:"deletions"`
}

RepoStats contains commit statistics for a repository

func GetRepoStats

func GetRepoStats(repoPath string) (*RepoStats, error)

GetRepoStats returns commit statistics for a repository

type RepoWithStats

type RepoWithStats struct {
	model.Repository

	Stats *RepoStats `json:"stats,omitempty"`
}

RepoWithStats combines a repository with its stats

func ListReposWithStats

func ListReposWithStats(favoritesOnly bool, sortBy SortBy, withStats bool) ([]RepoWithStats, error)

ListReposWithStats returns repos with optional stats and sorting

func ListReposWithStatsAndWorkspace added in v0.3.0

func ListReposWithStatsAndWorkspace(favoritesOnly bool, workspace string, sortBy SortBy, withStats bool) ([]RepoWithStats, error)

ListReposWithStatsAndWorkspace returns repos filtered by workspace with optional stats and sorting

type RepositorySnapshot

type RepositorySnapshot struct {
	model.Repository

	CurrentBranch string `json:"current_branch,omitempty"`
	BranchError   string `json:"branch_error,omitempty"`
}

RepositorySnapshot extends Repository with branch info

type SkipReason

type SkipReason int

SkipReason categorizes why a repo was skipped

const (
	SkipReasonNone SkipReason = iota
	SkipReasonDirty
	SkipReasonPathCollision
	SkipReasonArchived
	SkipReasonFiltered
	SkipReasonNotGitRepo
)

func (SkipReason) String

func (r SkipReason) String() string

type Snapshot

type Snapshot struct {
	Version      string               `json:"version"`
	CreatedAt    time.Time            `json:"created_at"`
	Hostname     string               `json:"hostname,omitempty"`
	Repositories []RepositorySnapshot `json:"repositories"`
	Config       *model.Config        `json:"config,omitempty"`
}

Snapshot represents a complete database export

func CreateSnapshot

func CreateSnapshot(opts CreateSnapshotOptions) (*Snapshot, error)

CreateSnapshot creates a database snapshot with optional branch info

type SortBy

type SortBy string

SortBy defines how repositories should be sorted

const (
	SortByName          SortBy = "name"
	SortByClonedAt      SortBy = "cloned"
	SortByUpdatedAt     SortBy = "updated"
	SortByCommits       SortBy = "commits"
	SortByRecentCommits SortBy = "recent"
	SortByChanges       SortBy = "changes"
)

type TokenSource

type TokenSource string

TokenSource indicates where the token was found

const (
	TokenSourceFlag      TokenSource = "flag"
	TokenSourceProfile   TokenSource = "profile"
	TokenSourceEnvGitHub TokenSource = "GITHUB_TOKEN"
	TokenSourceEnvGH     TokenSource = "GH_TOKEN"
	TokenSourceGHCLI     TokenSource = "gh-cli"
	TokenSourceNone      TokenSource = "none"
)

func ResolveGitHubToken

func ResolveGitHubToken(flagToken, profileName string) (token string, source TokenSource, err error)

ResolveGitHubToken attempts to find a GitHub token from multiple sources. Priority order:

  1. flagToken (explicit --token flag)
  2. profileName (explicit --profile flag)
  3. GITHUB_TOKEN environment variable
  4. GH_TOKEN environment variable
  5. Active clonr profile token
  6. gh CLI auth (config file)

func ResolveGitHubTokenForHost

func ResolveGitHubTokenForHost(flagToken, profileName, host string) (token string, source TokenSource, err error)

ResolveGitHubTokenForHost resolves token for a specific host (enterprise support). Priority order:

  1. flagToken (explicit --token flag)
  2. profileName (explicit --profile flag)
  3. GITHUB_TOKEN environment variable
  4. GH_TOKEN environment variable
  5. Active clonr profile token
  6. gh CLI auth for the specific host

type WorkflowJob

type WorkflowJob struct {
	ID          int64      `json:"id"`
	Name        string     `json:"name"`
	Status      string     `json:"status"`
	Conclusion  string     `json:"conclusion"`
	StartedAt   *time.Time `json:"started_at,omitempty"`
	CompletedAt *time.Time `json:"completed_at,omitempty"`
	Steps       []JobStep  `json:"steps,omitempty"`
	RunnerName  string     `json:"runner_name,omitempty"`
	URL         string     `json:"url"`
}

WorkflowJob represents a job within a workflow run

type WorkflowRun

type WorkflowRun struct {
	ID           int64      `json:"id"`
	Name         string     `json:"name"`
	WorkflowName string     `json:"workflow_name"`
	Status       string     `json:"status"`     // queued, in_progress, completed, waiting
	Conclusion   string     `json:"conclusion"` // success, failure, neutral, cancelled, skipped, timed_out, action_required, stale
	Branch       string     `json:"branch"`
	Event        string     `json:"event"` // push, pull_request, schedule, workflow_dispatch, etc.
	HeadSHA      string     `json:"head_sha"`
	HeadCommit   string     `json:"head_commit,omitempty"`
	Actor        string     `json:"actor"`
	RunNumber    int        `json:"run_number"`
	RunAttempt   int        `json:"run_attempt"`
	CreatedAt    time.Time  `json:"created_at"`
	UpdatedAt    time.Time  `json:"updated_at"`
	StartedAt    *time.Time `json:"started_at,omitempty"`
	CompletedAt  *time.Time `json:"completed_at,omitempty"`
	URL          string     `json:"url"`
	Duration     string     `json:"duration,omitempty"`
}

WorkflowRun represents a GitHub Actions workflow run

type WorkflowRunDetail

type WorkflowRunDetail struct {
	Run  WorkflowRun   `json:"run"`
	Jobs []WorkflowJob `json:"jobs,omitempty"`
}

WorkflowRunDetail contains detailed information about a specific workflow run

func GetWorkflowRunStatus

func GetWorkflowRunStatus(token, owner, repo string, runID int64, opts GetWorkflowRunOptions) (*WorkflowRunDetail, error)

GetWorkflowRunStatus retrieves the status of a specific workflow run

type WorkflowRunsData

type WorkflowRunsData struct {
	Repository string        `json:"repository"`
	FetchedAt  time.Time     `json:"fetched_at"`
	TotalCount int           `json:"total_count"`
	Runs       []WorkflowRun `json:"workflow_runs"`
}

WorkflowRunsData contains workflow runs for a repository

func ListWorkflowRuns

func ListWorkflowRuns(token, owner, repo string, opts ListWorkflowRunsOptions) (*WorkflowRunsData, error)

ListWorkflowRuns lists workflow runs for a repository

Jump to

Keyboard shortcuts

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