### Example: Using GitHubClient to comment, add reviewers, and get assignable users Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/githubclient.md Shows how to create a GitHub client with default config, set repo owner/name, and use it to comment on conflicting PRs, get assignable users, and add reviewers. Requires GITHUB_TOKEN or gh/hub CLI configs. ```go import ( "context" "github.com/ejoffe/spr/config" "github.com/ejoffe/spr/github/githubclient" ) ctx := context.Background() cfg := config.DefaultConfig() cfg.Repo.GitHubRepoOwner = "ejoffe" cfg.Repo.GitHubRepoName = "spr" // GITHUB_TOKEN must be set (or gh/hub CLI configs present) client := githubclient.NewGitHubClient(ctx, cfg) info := client.GetInfo(ctx, gitcmd) for _, pr := range info.PullRequests { if !pr.MergeStatus.NoConflicts { client.CommentPullRequest(ctx, pr, "please rebase") } } users := client.GetAssignableUsers(ctx) for _, u := range users { if u.Login == "alice" { client.AddReviewers(ctx, info.PullRequests[0], []string{u.ID}) } } ``` -------------------------------- ### Example usage of config_parser Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config-parser.md Shows how to parse configuration, check for errors, and get config file paths. Auto-creates .spr.yml and ~/.spr.yml if missing. ```go import ( "github.com/ejoffe/spr/config" "github.com/ejoffe/spr/config/config_parser" "github.com/ejoffe/spr/git/realgit" ) gitcmd := realgit.NewGitCmd(config.DefaultConfig()) cfg := config_parser.ParseConfig(gitcmd) // auto-creates .spr.yml / ~/.spr.yml if missing if err := config_parser.CheckConfig(cfg); err != nil { fmt.Println(err) // e.g. branch name containing '/' os.Exit(2) } repoPath := config_parser.RepoConfigFilePath(gitcmd) // /.spr.yml statePath := config_parser.InternalConfigFilePath() // ~/.spr.state ``` -------------------------------- ### Example usage of realgit Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Shows how to create a gitcmd, run git commands, delete a remote branch, and get the root directory. Includes error handling and panics on failure. ```go import ( "github.com/ejoffe/spr/config" "github.com/ejoffe/spr/git/realgit" ) gitcmd := realgit.NewGitCmd(config.DefaultConfig()) var output string err := gitcmd.Git("status --porcelain", &output) if err != nil { fmt.Println(output) os.Exit(2) } gitcmd.MustGit("fetch", nil) // panics on failure gitcmd.MustGit("rebase origin/main --autostash", nil) err = gitcmd.DeleteRemoteBranch(context.Background(), "spr/main/3f2a9c1b") if err != nil { log.Printf("failed to delete branch: %v", err) } root := gitcmd.RootDir() // e.g. /workspace/repo ``` -------------------------------- ### Install git-spr Source: https://github.com/ejoffe/spr/blob/master/readme.md Installation commands for macOS/Linux using Homebrew or Nix. ```shell brew install ejoffe/tap/spr # macOS/Linux nix profile install github:ejoffe/spr # Nix ``` -------------------------------- ### Install spr with apt Source: https://github.com/ejoffe/spr/blob/master/readme.md Install spr via apt from the inigolabs repository. Adds the repository to apt sources, updates, and installs. ```shell echo "deb [trusted=yes] https://apt.fury.io/inigolabs/ /" | sudo tee /etc/apt/sources.list.d/inigolabs.list sudo apt update sudo apt install spr ``` -------------------------------- ### Example .spr.yml repository configuration Source: https://github.com/ejoffe/spr/blob/master/readme.md Example repository configuration file. Sets required checks, approval, merge method, and default reviewers. ```yaml requireChecks: true requiredChecks: - "ci/test" - "ci/build" requireApproval: true mergeMethod: squash defaultReviewers: - teammate ``` -------------------------------- ### Example usage Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/genclient.md Example of using the generated client to query pull requests and create a pull request. ```APIDOC ## Example usage ### Description Example of using the generated client to query pull requests and create a pull request. ### Code ```go import ( "context" "net/http" "github.com/ejoffe/spr/github/githubclient/gen/genclient" "golang.org/x/oauth2" ) ts := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: os.Getenv("GITHUB_TOKEN")}) hc := oauth2.NewClient(context.Background(), ts) api := genclient.NewClient("https://api.github.com/graphql", hc) resp, err := api.PullRequests(ctx, "ejoffe", "spr") if err != nil { log.Fatal(err) } fmt.Println("viewer:", resp.Viewer.Login) pr, err := api.CreatePullRequest(ctx, genclient.CreatePullRequestInput{ RepositoryId: resp.Repository.Id, BaseRefName: "main", HeadRefName: "spr/main/3f2a9c1b", Title: "Add feature", Draft: boolPtr(false), }) if err != nil { log.Fatal(err) } fmt.Println(pr.CreatePullRequest.PullRequest.Number) ``` ``` -------------------------------- ### pretty package example: PrettyPrint, PrettyWriter, PrefixPretty, PrettyString Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Shows usage of the `pretty` package functions: `PrettyPrint` prints a JSON-marshaled object to stdout with 2-space indent, `PrettyWriter` writes to an `io.Writer`, `PrefixPretty` prints with a prefix, and `PrettyString` returns the output as a string. The example defines a `stackStatus` struct and demonstrates each function. ```go import ( "bytes" "fmt" "github.com/ejoffe/spr/pretty" ) type stackStatus struct { Branch string PRs int } pretty.PrettyPrint(stackStatus{Branch: "main", PRs: 3}) // { // "Branch": "main", // "PRs": 3 // } var buf bytes.Buffer pretty.PrettyWriter(stackStatus{Branch: "main", PRs: 3}, &buf) pretty.PrefixPretty("stack", stackStatus{Branch: "main", PRs: 3}) // "stack: {...}" s := pretty.PrettyString(stackStatus{Branch: "main", PRs: 3}) fmt.Println(s) ``` -------------------------------- ### Install spr with Nix profile Source: https://github.com/ejoffe/spr/blob/master/readme.md Install spr as a Nix profile package. ```shell nix profile install github:ejoffe/spr ``` -------------------------------- ### terminal package example: using Width with fallback Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Example of calling `terminal.Width` and handling the error by falling back to a width of 1000 (no truncation) when the terminal size cannot be determined. Prints the resulting width. ```go import "github.com/ejoffe/spr/terminal" width, err := terminal.Width() if err != nil { width = 1000 // fallback: do not truncate } fmt.Printf("terminal width: %d\n", width) ``` -------------------------------- ### Basic construction (as done by cmd/spr/main.go) Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/spr.md Example of constructing the stackediff type and calling UpdatePullRequests with nil reviewers and count. ```APIDOC ## Basic construction (as done by cmd/spr/main.go) ### Description Example of constructing the stackediff type and calling UpdatePullRequests with nil reviewers and count. ### Code ```go import ( "github.com/ejoffe/spr/config/config_parser" "github.com/ejoffe/spr/git/realgit" "github.com/ejoffe/spr/github/githubclient" "github.com/ejoffe/spr/spr" ) gitcmd := realgit.NewGitCmd(config.DefaultConfig()) cfg := config_parser.ParseConfig(gitcmd) gitcmd = realgit.NewGitCmd(cfg) client := githubclient.NewGitHubClient(ctx, cfg) sd := spr.NewStackedPR(cfg, client, gitcmd) sd.UpdatePullRequests(ctx, nil, nil) ``` ``` -------------------------------- ### Install spr with Homebrew Source: https://github.com/ejoffe/spr/blob/master/readme.md Install spr via Homebrew. Requires the ejoffe/homebrew-tap tap. ```shell brew tap ejoffe/homebrew-tap brew install ejoffe/tap/spr ``` -------------------------------- ### Start a new stack with git checkout -b Source: https://github.com/ejoffe/spr/blob/master/readme.md Create a new branch from the latest pushed state to start a new stack. ```shell git checkout -b new_stack @{push} ``` -------------------------------- ### Go: Stack Summary Example Using spr Git API Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/git.md This example shows how to use the spr Git API to get the local commit stack, top commit, and branch name. It iterates over commits, skipping WIP commits, and checks if the current branch is spr-managed using a regex pattern from the config. The code is intended for use in a Go program that imports the spr config and git packages. ```go import ( "github.com/ejoffe/spr/config" "github.com/ejoffe/spr/git" ) func stackSummary(cfg *config.Config, g git.GitInterface) { commits := git.GetLocalCommitStack(cfg, g) top := git.GetLocalTopCommit(cfg, g) branch := git.GetLocalBranchName(g) for _, c := range commits { if c.WIP { continue } remoteBranch := git.BranchNameFromCommit(cfg, c) _ = remoteBranch } _ = top _ = branch re := git.BranchNameRegex(cfg.User.BranchPrefix) if re.FindString(branch) != "" { // we are on a spr-managed branch } } ``` -------------------------------- ### Run spr without installing via Nix Source: https://github.com/ejoffe/spr/blob/master/readme.md Run spr without installing it, using nix run. ```shell nix run github:ejoffe/spr ``` -------------------------------- ### File path helpers Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config-parser.md Provides functions to get the file paths for repository, user, and internal configuration files. ```APIDOC ## File path helpers ### Description Provides functions to get the file paths for repository, user, and internal configuration files. ### Functions #### RepoConfigFilePath func RepoConfigFilePath(gitcmd git.GitInterface) string Returns `/.spr.yml` (via `gitcmd.RootDir()`). #### UserConfigFilePath func UserConfigFilePath() string Returns `~/.spr.yml` (via `os.UserHomeDir()`). #### InternalConfigFilePath func InternalConfigFilePath() string Returns `~/.spr.state`. All three use `filepath.Clean(path.Join(...))`. ``` -------------------------------- ### Edit session lifecycle Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/spr.md Example of managing an edit session: picking a commit, amending and restoring the stack, or aborting. ```APIDOC ## Edit session lifecycle ### Description Example of managing an edit session: picking a commit, amending and restoring the stack, or aborting. ### Code ```go sd.EditCommit(ctx) // pick a commit; rebase stops at an 'edit' point // ... make changes ... sd.EditCommitDone(ctx, true) // amend, restore stack, then run spr update // or cancel: sd.EditCommitAbort(ctx) ``` ``` -------------------------------- ### terminal.Width implementation for non-Windows (terminal_other.go) Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Implementation of `Width` for non-Windows builds. It uses `unix.IoctlGetWinsize` with `TIOCGWINSZ` on stdin to get the terminal column count. Returns an error if the terminal size cannot be determined. ```go // Width returns the current character width of the terminal func Width() (int, error) { terminalMaxSize, err := unix.IoctlGetWinsize(int(os.Stdin.Fd()), unix.TIOCGWINSZ) if err != nil { return 0, err } return int(terminalMaxSize.Col), nil } ``` -------------------------------- ### git spr update output example Source: https://github.com/ejoffe/spr/blob/master/readme.md Example output of git spr update showing status bits for each PR. New commits get new PRs; amended commits update existing PRs automatically. ```shell > git spr update [⌛❌✅❌] 60: Feature 3 [✅✅✅✅] 59: Feature 2 [✅✅✅✅] 58: Feature 1 ``` -------------------------------- ### Basic construction of stacked PR client Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/spr.md Shows how to construct the stacked PR client as done by cmd/spr/main.go. It imports the necessary packages, creates a git command, parses config, creates a GitHub client, and then calls UpdatePullRequests with nil arguments. ```go import ( "github.com/ejoffe/spr/config/config_parser" "github.com/ejoffe/spr/git/realgit" "github.com/ejoffe/spr/github/githubclient" "github.com/ejoffe/spr/spr" ) gitcmd := realgit.NewGitCmd(config.DefaultConfig()) cfg := config_parser.ParseConfig(gitcmd) gitcmd = realgit.NewGitCmd(cfg) client := githubclient.NewGitHubClient(ctx, cfg) sd := spr.NewStackedPR(cfg, client, gitcmd) sd.UpdatePullRequests(ctx, nil, nil) ``` -------------------------------- ### Build spr from source with make bin Source: https://github.com/ejoffe/spr/blob/master/readme.md Build spr from source. Requires goreleaser; binaries are output to dist/. ```shell make bin # requires goreleaser; binaries output to dist/ ``` -------------------------------- ### File path helper function signatures Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config-parser.md Returns the paths for the repository config file, user config file, and internal state file. All use filepath.Clean(path.Join(...)). ```go func RepoConfigFilePath(gitcmd git.GitInterface) string func UserConfigFilePath() string func InternalConfigFilePath() string ``` -------------------------------- ### git spr merge output example Source: https://github.com/ejoffe/spr/blob/master/readme.md Example output of git spr merge. It finds the top mergeable PR, combines all commits up to it into a single PR, merges it, and closes intermediate PRs to avoid redundant CI runs. ```shell > git spr merge MERGED #58 Feature 1 MERGED #59 Feature 2 MERGED #60 Feature 3 [✅❌✅✅] 61: Feature 4 ``` -------------------------------- ### NewGitCmd constructor Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Creates a new gitcmd instance. It runs git rev-parse --show-toplevel to find the repo root, converts Cygwin paths with cygpath -w, and opens the repository with gogit.PlainOpen. On errors it prints and exits with os.Exit(-1). ```go func NewGitCmd(cfg *config.Config) *gitcmd ``` -------------------------------- ### NewGitHubClient Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/githubclient.md Creates a new GitHub GraphQL client. It resolves an OAuth token from the environment or existing CLI configs, builds an authenticated HTTP client, and selects the appropriate GraphQL endpoint based on the configured GitHub host. If no token is found, it prints help text and exits. ```APIDOC ## NewGitHubClient ### Description Creates a new GitHub GraphQL client. It resolves an OAuth token from the environment or existing CLI configs, builds an authenticated HTTP client, and selects the appropriate GraphQL endpoint based on the configured GitHub host. If no token is found, it prints help text and exits. ### Function Signature ```go func NewGitHubClient(ctx context.Context, config *config.Config) *client ``` ### Parameters - **ctx** (`context.Context`) - Required - Used to build the OAuth HTTP client. - **config** (`*config.Config`) - Required - Provides `Repo.GitHubHost`, `Repo.GitHubRepoOwner`, `Repo.GitHubRepoName`, `Repo.MergeQueue`, `User.*`. ### Returns - **`*client`** - The unexported concrete type; its methods are exported. ### Behavior 1. Resolves a token via `findToken(config.Repo.GitHubHost)`. If none is found, prints `tokenHelpText` (instructions for creating a token, using `gh auth login --insecure-storage`, or configuring `~/.config/hub`) and calls `os.Exit(3)`. 2. Builds an `oauth2.StaticTokenSource` client. 3. Picks the GraphQL endpoint: - `https://api.github.com/graphql` when `Repo.GitHubHost` ends with `github.com` - otherwise parses `Repo.GitHubHost` as a URL: scheme defaults to `https`, and builds `https:///api/graphql` (or `:///api/graphql` for a full URL) 4. Wraps it in `genclient.NewClient(endpoint, tc)`. ``` -------------------------------- ### RootDir method Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Returns the resolved working-tree root. ```go func (c *gitcmd) RootDir() string ``` -------------------------------- ### GitWithEditor method Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Runs git with the given arguments and editor command. Sets core.editor, commit.verbose=false, rebase.abbreviateCommands=false, and sequence.editor. Skips fetch/rebase commands if NoFetch/NoRebase config is set. Strips EDITOR env var from child environment. ```go func (c *gitcmd) GitWithEditor(argStr string, output *string, editorCmd string) error ``` -------------------------------- ### EditCommit Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/spr.md Starts an interactive edit session on a chosen commit using git rebase with the spr binary as the sequence editor. ```APIDOC ## EditCommit ### Description Starts an interactive edit session on a chosen commit. Writes a state file at `/.git/spr_edit_state` containing `commit_id=\ncommit_subject=\n`, then runs `git rebase -i --autostash /` using the running spr binary itself as the git sequence editor (` _edit-sequence `). On failure the state file is removed. ### Method Go function ### Signature `func (sd *stackediff) EditCommit(ctx context.Context)` ### Parameters - **ctx** (`context.Context`) - Required - Cancellation context ### Behavior - If a session is already in progress, prints `Already editing a commit.` plus instructions and returns without action. - An empty stack prints `No commits to edit`. ``` -------------------------------- ### unimplemented error (terminal.Width on Windows) Source: https://github.com/ejoffe/spr/blob/master/_autodocs/errors.md Error returned by terminal.Width() on Windows. Callers must handle it; for example, PullRequest.String falls back to width 1000. ```go errors.New("unimplemented") ``` -------------------------------- ### genclient.Client and genclient.SubscriptionClient Source: https://github.com/ejoffe/spr/blob/master/_autodocs/types.md Documentation for the genclient.Client and genclient.SubscriptionClient interfaces, including all methods and constructors. ```APIDOC ## PullRequests ### Description Retrieves pull requests for a given repository. ### Method PullRequests ### Endpoint PullRequests(ctx context.Context, repoOwner string, repoName string) (*PullRequestsResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **repoOwner** (string) - Required - The owner of the repository. - **repoName** (string) - Required - The name of the repository. ### Response - **PullRequestsResponse** - The response containing pull requests. - **error** - An error if the request fails. ``` ```APIDOC ## PullRequestsWithMergeQueue ### Description Retrieves pull requests with merge queue information for a given repository. ### Method PullRequestsWithMergeQueue ### Endpoint PullRequestsWithMergeQueue(ctx context.Context, repoOwner string, repoName string) (*PullRequestsWithMergeQueueResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **repoOwner** (string) - Required - The owner of the repository. - **repoName** (string) - Required - The name of the repository. ### Response - **PullRequestsWithMergeQueueResponse** - The response containing pull requests with merge queue information. - **error** - An error if the request fails. ``` ```APIDOC ## AssignableUsers ### Description Retrieves assignable users for a repository. ### Method AssignableUsers ### Endpoint AssignableUsers(ctx context.Context, repoOwner string, repoName string, endCursor *string) (*AssignableUsersResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **repoOwner** (string) - Required - The owner of the repository. - **repoName** (string) - Required - The name of the repository. - **endCursor** (*string) - Optional - The cursor for pagination. ### Response - **AssignableUsersResponse** - The response containing assignable users. - **error** - An error if the request fails. ``` ```APIDOC ## CreatePullRequest ### Description Creates a new pull request. ### Method CreatePullRequest ### Endpoint CreatePullRequest(ctx context.Context, input CreatePullRequestInput) (*CreatePullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (CreatePullRequestInput) - Required - The input for creating a pull request. ### Response - **CreatePullRequestResponse** - The response containing the created pull request. - **error** - An error if the request fails. ``` ```APIDOC ## UpdatePullRequest ### Description Updates an existing pull request. ### Method UpdatePullRequest ### Endpoint UpdatePullRequest(ctx context.Context, input UpdatePullRequestInput) (*UpdatePullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (UpdatePullRequestInput) - Required - The input for updating a pull request. ### Response - **UpdatePullRequestResponse** - The response containing the updated pull request. - **error** - An error if the request fails. ``` ```APIDOC ## AddReviewers ### Description Adds reviewers to a pull request. ### Method AddReviewers ### Endpoint AddReviewers(ctx context.Context, input RequestReviewsInput) (*AddReviewersResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (RequestReviewsInput) - Required - The input for adding reviewers. ### Response - **AddReviewersResponse** - The response containing the result of adding reviewers. - **error** - An error if the request fails. ``` ```APIDOC ## CommentPullRequest ### Description Adds a comment to a pull request. ### Method CommentPullRequest ### Endpoint CommentPullRequest(ctx context.Context, input AddCommentInput) (*CommentPullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (AddCommentInput) - Required - The input for adding a comment. ### Response - **CommentPullRequestResponse** - The response containing the result of adding a comment. - **error** - An error if the request fails. ``` ```APIDOC ## MergePullRequest ### Description Merges a pull request. ### Method MergePullRequest ### Endpoint MergePullRequest(ctx context.Context, input MergePullRequestInput) (*MergePullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (MergePullRequestInput) - Required - The input for merging a pull request. ### Response - **MergePullRequestResponse** - The response containing the result of merging. - **error** - An error if the request fails. ``` ```APIDOC ## AutoMergePullRequest ### Description Enables auto-merge for a pull request. ### Method AutoMergePullRequest ### Endpoint AutoMergePullRequest(ctx context.Context, input EnablePullRequestAutoMergeInput) (*AutoMergePullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (EnablePullRequestAutoMergeInput) - Required - The input for enabling auto-merge. ### Response - **AutoMergePullRequestResponse** - The response containing the result of enabling auto-merge. - **error** - An error if the request fails. ``` ```APIDOC ## ClosePullRequest ### Description Closes a pull request. ### Method ClosePullRequest ### Endpoint ClosePullRequest(ctx context.Context, input ClosePullRequestInput) (*ClosePullRequestResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (ClosePullRequestInput) - Required - The input for closing a pull request. ### Response - **ClosePullRequestResponse** - The response containing the result of closing. - **error** - An error if the request fails. ``` ```APIDOC ## StarCheck ### Description Checks if the authenticated user has starred a repository. ### Method StarCheck ### Endpoint StarCheck(ctx context.Context, after *string) (*StarCheckResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **after** (*string) - Optional - The cursor for pagination. ### Response - **StarCheckResponse** - The response containing the star check result. - **error** - An error if the request fails. ``` ```APIDOC ## StarGetRepo ### Description Gets repository information for starring. ### Method StarGetRepo ### Endpoint StarGetRepo(ctx context.Context, owner string, name string) (*StarGetRepoResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **owner** (string) - Required - The owner of the repository. - **name** (string) - Required - The name of the repository. ### Response - **StarGetRepoResponse** - The response containing repository information. - **error** - An error if the request fails. ``` ```APIDOC ## StarAdd ### Description Adds a star to a repository. ### Method StarAdd ### Endpoint StarAdd(ctx context.Context, input AddStarInput) (*AddStarResponse, error) ### Parameters - **ctx** (context.Context) - Required - The context for the request. - **input** (AddStarInput) - Required - The input for adding a star. ### Response - **AddStarResponse** - The response containing the result of adding a star. - **error** - An error if the request fails. ``` ```APIDOC ## SubscriptionClient.Close ### Description Closes the subscription client. ### Method Close ### Endpoint Close() (err error) ### Parameters None. ### Response - **err** (error) - An error if closing fails. ``` -------------------------------- ### terminal.Width implementation for Windows (terminal_windows.go) Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Windows build of `Width` always returns an error with message "unimplemented". This is a placeholder that does not support terminal width detection on Windows. ```go func Width() (int, error) { return 0, errors.New("unimplemented") } ``` -------------------------------- ### NewSubscriptionClient Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/genclient.md Creates a new subscription client that starts a background websocket subscription with the given connection parameters. Not used by spr's own code, but generated for completeness. ```APIDOC ## NewSubscriptionClient ### Description Starts a background websocket subscription client with the given connection params. Not referenced by spr's own code; generated for completeness. ### Function `func NewSubscriptionClient(url string, params map[string]interface{}) SubscriptionClient` ### Parameters - **url** (string) - Required - The websocket URL to connect to. - **params** (map[string]interface{}) - Required - Connection parameters for the subscription. ### Returns - **SubscriptionClient** - An interface with a `Close() (err error)` method. ``` -------------------------------- ### pretty.PrefixPretty Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Prints a prefix and pretty-printed JSON to stdout. Equivalent to `PrefixPrettyWriter(os.Stdout, prefix, object)`. ```APIDOC ## pretty.PrefixPretty ### Description Prints a prefix and pretty-printed JSON to stdout. Equivalent to `PrefixPrettyWriter(os.Stdout, prefix, object)`. ### Function Signature ```go func PrefixPretty(prefix string, object interface{}) ``` ### Parameters - **prefix** (`string`) - Required - Prefix string; if empty, the `: ` suffix is omitted - **object** (`interface{}`) - Required - Value to marshal (must be JSON-serializable) ### Behavior - Calls `PrefixPrettyWriter(os.Stdout, prefix, object)`. ### Example ```go pretty.PrefixPretty("stack", stackStatus{Branch: "main", PRs: 3}) // "stack: {...}" ``` ``` -------------------------------- ### git.GitInterface interface definition Source: https://github.com/ejoffe/spr/blob/master/_autodocs/types.md Defines the GitInterface interface with methods for running git commands, getting root directory, and deleting remote branches. Implemented by realgit.gitcmd and mockgit.Mock. ```go type GitInterface interface { GitWithEditor(args string, output *string, editorCmd string) error Git(args string, output *string) error MustGit(args string, output *string) RootDir() string DeleteRemoteBranch(ctx context.Context, branch string) error } ``` -------------------------------- ### NewGitCmd Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Creates a new gitcmd instance by locating the repository root, adjusting paths for Cygwin, and opening the repository with go-git. Exits the process on errors. ```APIDOC ## NewGitCmd ### Description Creates a new gitcmd instance. It runs `git rev-parse --show-toplevel` to find the repo root, adjusts Cygwin paths, opens the repository with go-git, and returns a *gitcmd with config, repo, and rootdir fields set. ### Signature ```go func NewGitCmd(cfg *config.Config) *gitcmd ``` ### Parameters - **cfg** (*config.Config) - Required - Configuration; User.NoFetch/User.NoRebase gate commands at execution time. ### Behavior 1. Runs `git rev-parse --show-toplevel` to find the repo root. On error prints the error and calls `os.Exit(-1)`. 2. On Cygwin-style paths (`/cygdrive/...`), converts with `cygpath -w` (see `maybeAdjustPathPerPlatform`, `realcmd.go:43`; panics if `cygpath` fails). 3. Opens the repository with `gogit.PlainOpen(rootdir)`; on error prints and `os.Exit(-1)`. 4. Returns `*gitcmd` with `config`, `repo`, and `rootdir` fields set. ### Returns - *gitcmd - The new gitcmd instance. ``` -------------------------------- ### Updating a bounded number of PRs with reviewers and error handling Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/spr.md Example of updating a bounded number of PRs with reviewers and merging only mergeable PRs, with error handling via check(). ```APIDOC ## Updating a bounded number of PRs with reviewers and error handling ### Description Example of updating a bounded number of PRs with reviewers and merging only mergeable PRs, with error handling via check(). ### Code ```go count := uint(3) sd.UpdatePullRequests(ctx, []string{"alice"}, &count) // Merge only what is mergeable; failures are reported via check() which // prints "error: " and exits 1 (or panics when SPR_DEBUG=1). sd.MergePullRequests(ctx, nil) ``` ``` -------------------------------- ### GitInterface Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/git.md The GitInterface defines the methods for interacting with git in the spr commit stack. It includes methods for running git commands, getting the root directory, and deleting remote branches. ```APIDOC ## GitInterface ### Description The GitInterface is an abstraction layer over git, providing methods to run git commands, get the repository root, and delete remote branches. ### Methods #### Git - **Signature**: `(args string, output *string) error` - **Description**: Runs `git `; when `output` is non-nil it receives the trimmed combined output; returns the command error. #### GitWithEditor - **Signature**: `(args string, output *string, editorCmd string) error` - **Description**: Like `Git`, but sets `core.editor`, `commit.verbose=false`, `rebase.abbreviateCommands=false`, and `sequence.editor` to `editorCmd`. #### MustGit - **Signature**: `(args string, output *string)` - **Description**: Calls `Git` and panics on error. #### RootDir - **Signature**: `() string` - **Description**: Returns the git working-tree root. #### DeleteRemoteBranch - **Signature**: `(ctx context.Context, branch string) error` - **Description**: Deletes a remote branch via a `:` push. ### Parameters #### Git - **args** (string) - Required - The git command arguments. - **output** (*string) - Optional - Pointer to receive the trimmed combined output. #### GitWithEditor - **args** (string) - Required - The git command arguments. - **output** (*string) - Optional - Pointer to receive the trimmed combined output. - **editorCmd** (string) - Required - The editor command to use. #### MustGit - **args** (string) - Required - The git command arguments. - **output** (*string) - Optional - Pointer to receive the trimmed combined output. #### DeleteRemoteBranch - **ctx** (context.Context) - Required - The context for the operation. - **branch** (string) - Required - The name of the remote branch to delete. ### Return Values - **Git**: Returns an error if the command fails. - **GitWithEditor**: Returns an error if the command fails. - **MustGit**: No return value; panics on error. - **RootDir**: Returns the git working-tree root as a string. - **DeleteRemoteBranch**: Returns an error if the deletion fails. ``` -------------------------------- ### pretty.PrettyString Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Like `PrefixPrettyWriter` but captures the output into a `bytes.Buffer` and returns it as a string. ```APIDOC ## pretty.PrettyString ### Description Like `PrefixPrettyWriter` but captures the output into a `bytes.Buffer` and returns it as a `string`. ### Function Signature ```go func PrettyString(object interface{}) string ``` ### Parameters - **object** (`interface{}`) - Required - Value to marshal (must be JSON-serializable) ### Returns - `string` - The pretty-printed JSON string. ### Example ```go s := pretty.PrettyString(stackStatus{Branch: "main", PRs: 3}) fmt.Println(s) ``` ``` -------------------------------- ### Git method Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Delegates to GitWithEditor with a no-op editor /usr/bin/true. On Windows this default path is not meaningful. ```go func (c *gitcmd) Git(argStr string, output *string) error ``` -------------------------------- ### GetInfo method signature Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/githubclient.md Fetches the viewer's open pull requests, computes the local commit stack, and matches it against remote PRs. Overrides checks pass status when required checks are configured. ```go func (c *client) GetInfo(ctx context.Context, gitcmd git.GitInterface) *github.GitHubInfo ``` -------------------------------- ### Edit a commit with git spr edit Source: https://github.com/ejoffe/spr/blob/master/readme.md Start an interactive rebase session on a specific commit with git spr edit. Finish with git spr edit --done (add -u to also update) or cancel with git spr edit --abort. ```shell > git spr edit 3 : 5cba235d : Feature 3 2 : 4dc2c5b2 : Feature 2 1 : 9d1b8193 : Feature 1 Commit to edit [1-3]: 2 ``` -------------------------------- ### ErrNoMatchesFound error value Source: https://github.com/ejoffe/spr/blob/master/_autodocs/errors.md Custom error value returned when getSectionOfPRTemplate finds zero occurrences of an anchor string. On the default start anchor, insertBodyIntoPRTemplate treats it as the append-mode signal and no error propagates; for other anchors it is wrapped and becomes fatal. Consumer code can match with errors.Is(err, template_custom.ErrNoMatchesFound). ```go ErrNoMatchesFound = fmt.Errorf("no matches found") ``` -------------------------------- ### Version metadata variables Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/cli.md Defines version, commit, and date variables in `cmd/spr/main.go` that are overridden at build time via goreleaser ldflags. ```go var ( version = "dev" commit = "dversion" date = "unknown" ) ``` -------------------------------- ### MustGit method Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/realgit.md Calls Git and panics on error. ```go func (c *gitcmd) MustGit(argStr string, output *string) ``` -------------------------------- ### pretty.PrefixPrettyWriter Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/utilities.md Compact-marshals an object, then writes `: \n` to the writer using colorized formatting. When prefix is empty, the `: ` suffix is omitted. ```APIDOC ## pretty.PrefixPrettyWriter ### Description Compact-marshals `object`, then writes `: \n` to `writer` using `pretty.Pretty` (colorized formatting). When `prefix` is empty the `": "` suffix is omitted. ### Function Signature ```go func PrefixPrettyWriter(writer io.Writer, prefix string, object interface{}) ``` ### Parameters - **writer** (`io.Writer`) - Required - Destination writer - **prefix** (`string`) - Required - Prefix string; if empty, the `: ` suffix is omitted - **object** (`interface{}`) - Required - Value to marshal (must be JSON-serializable) ### Behavior - Compact-marshals the object. - Writes `: \n` to the writer. - Uses colorized formatting via `pretty.Pretty`. ### Example ```go pretty.PrefixPrettyWriter(&buf, "stack", stackStatus{Branch: "main", PRs: 3}) ``` ``` -------------------------------- ### unable to add reviewer, user %q not found error Source: https://github.com/ejoffe/spr/blob/master/_autodocs/errors.md Error returned when a requested reviewer login is not in the GetAssignableUsers result (case-insensitive match on Login). Propagated through check, which exits with status 1. ```go fmt.Errorf("unable to add reviewer, user %q not found", r) ``` -------------------------------- ### NewGitHubClient function signature Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/githubclient.md Constructor for the githubclient package. Takes a context and config, returns an unexported *client. Resolves an OAuth token, exits with code 3 if none found, and builds a GraphQL client for the appropriate endpoint. ```go func NewGitHubClient(ctx context.Context, config *config.Config) *client ``` -------------------------------- ### Configure spr repository merge method and PR template Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config.md Imports the spr config package, creates a default configuration, sets the merge method to 'squash', retrieves the merge method, and normalizes the configuration. After normalization, setting the PR template path automatically updates the template type to 'custom'. ```go import "github.com/ejoffe/spr/config" cfg := config.DefaultConfig() cfg.Repo.MergeMethod = "squash" method, err := cfg.MergeMethod() if err != nil { log.Fatal(err) } _ = method // genclient.PullRequestMergeMethod_SQUASH cfg.Normalize() cfg.Repo.PRTemplatePath = ".spr/pr_template.md" // cfg.Repo.PRTemplateType is now "custom" ``` -------------------------------- ### EmptyConfig function signature Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config.md Returns a Config with empty Repo, User, and State sub-configs, with MergeCheckCommit initialized to an empty map. No defaults are applied. ```go func EmptyConfig() *Config ``` -------------------------------- ### Environment variables (GITHUB_TOKEN, SPR_NOREBASE) Source: https://github.com/ejoffe/spr/blob/master/_autodocs/configuration.md Environment variables for spr. GITHUB_TOKEN is required; SPR_NOREBASE disables rebasing, equivalent to git spr update --no-rebase. ```sh export GITHUB_TOKEN=ghp_xxx # required export SPR_NOREBASE=1 # equivalent to git spr update --no-rebase ``` -------------------------------- ### Normalize method signature Source: https://github.com/ejoffe/spr/blob/master/_autodocs/api-reference/config.md If Repo.PRTemplatePath is not empty, sets Repo.PRTemplateType to "custom". ```go func (c *Config) Normalize() ```