### Query: Example Usage Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Example of using Query to list git branches and print the output. ```go out, err := git.Query("branch", "--list") if err != nil { return err } fmt.Println(out) ``` -------------------------------- ### picker.Item Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/types.md Demonstrates how to create a picker.Item. This item can be used in picker configurations. ```go item := picker.Item{ Label: "main", Value: "/repo/main", Desc: "default branch", } ``` -------------------------------- ### QueryRun: Example Usage Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Example of using QueryRun to list git worktrees, passing the command directly to the terminal. ```go // Pass-through for git worktree list git.QueryRun("worktree", "list") ``` -------------------------------- ### picker.Config Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/types.md Demonstrates configuring the picker with multiple options, a custom prompt, and a preview command. Used to run the picker interface. ```go cfg := picker.Config{ Items: items, Multi: true, Prompt: "Select worktrees: ", PreviewCmd: "git log --oneline -5 {1}", } result, _ := picker.Run(cfg) ``` -------------------------------- ### Install Shell Completions for Manual Installation Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Manually install shell completions for Bash, Zsh, and Fish after a manual git-wt installation. Zsh requires two files for full functionality. ```bash # Bash cp completions/git-wt.bash ~/.local/share/bash-completion/completions/git-wt # Zsh cp completions/_git-wt ~/.local/share/zsh/site-functions/_git-wt cp completions/_git_wt ~/.local/share/zsh/site-functions/_git_wt # enables `git wt` completion # Fish cp completions/git-wt.fish ~/.config/fish/completions/git-wt.fish ``` -------------------------------- ### RunTo: Example Usage Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Example of using RunTo to stream the last 10 log entries to standard output. ```go err := git.RunTo(os.Stdout, "log", "--oneline", "-10") ``` -------------------------------- ### Development Setup Commands Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Commands for entering the development shell, formatting code, and running all checks using Nix. ```bash # Enter development shell nix develop # Format code nix fmt # Run all checks nix flake check ``` -------------------------------- ### Install git-wt with Nix Flakes Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/index.md Install and run git-wt using Nix Flakes for declarative package management. ```bash nix run github:ahmedelgabri/git-wt ``` -------------------------------- ### Manual Installation of git-wt Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Download and install git-wt manually by extracting a release archive. Ensure you replace VERSION and OS-ARCH with your specific details. ```bash curl -sL https://github.com/ahmedelgabri/git-wt/releases/latest/download/git-wt-VERSION-OS-ARCH.tar.gz | tar xz cp git-wt-VERSION-OS-ARCH/git-wt ~/.local/bin/ ``` -------------------------------- ### Example Usage of ui.Step Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/types.md Illustrates how to create a `ui.Step` for cloning a repository. It sets a message, enables output streaming, and provides a function to execute the git clone command. ```go step := ui.Step{ Message: "Cloning repository", ShowOutput: true, Run: func(ctx context.Context, w io.Writer) error { return git.RunToContext(ctx, w, "clone", url) }, } ``` -------------------------------- ### Example Usage of QueryLines Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Demonstrates how to use the QueryLines function to fetch and print git branches. Ensure error handling is in place. ```go lines, err := git.QueryLines("branch", "--list") if err != nil { return err } for _, branch := range lines { fmt.Println(branch) } ``` -------------------------------- ### Install git-wt using Homebrew Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/homebrew-support.md Tap the git-wt Homebrew repository and install the git-wt package. This command also installs automatic shell completion support for bash, zsh, and fish. ```bash brew tap ahmedelgabri/git-wt brew install git-wt ``` -------------------------------- ### Install lefthook Hooks Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/ci-cd-setup.md Hooks are automatically installed when entering the Nix development environment. Run this command to enter the environment and trigger the automatic installation. ```bash nix develop # lefthook install runs automatically via shellHook ``` -------------------------------- ### Example Project Structure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Illustrates the directory structure of a project managed by git-wt after a clone operation, highlighting the bare repository and individual worktree directories. ```text my-project/ ├── .bare/ # Git database ├── .git # File: gitdir: ./.bare └── main/ # Worktree for main branch ``` -------------------------------- ### Interactive Selection Examples Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Demonstrates how git-wt utilizes an interactive fuzzy picker (fzf) for commands when no arguments are provided on a TTY. ```bash git wt add # Interactive picker to select branch git wt switch # Interactive picker to select worktree git wt remove # Interactive picker with cleanup filters ``` -------------------------------- ### picker.Result Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/types.md Shows how to handle the result of a picker interaction. Checks for cancellation or empty selections. ```go result, err := picker.Run(cfg) if result.Canceled || len(result.Items) == 0 { return nil } selected := result.Items[0] ``` -------------------------------- ### Clone with Bare Structure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Example of cloning a Git repository using git-wt, which sets up the bare repository structure. ```bash # Clone with bare structure git wt clone https://github.com/user/repo.git ``` -------------------------------- ### Basic git-wt Usage Examples Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/index.md Demonstrates common git-wt commands for cloning, migrating, adding, switching, checking health, viewing status, and performing safe cleanup operations. ```bash # Clone with the bare worktree layout git wt clone https://github.com/user/repo.git ``` ```bash # Migrate an existing repo git wt migrate ``` ```bash # Create a worktree interactively git wt add ``` ```bash # Switch between worktrees cd "$(git wt switch)" ``` ```bash # Show repository health git wt doctor ``` ```bash # Show status for all worktrees git wt status ``` ```bash # Sweep safe cleanup candidates git wt remove --sweep --dry-run ``` -------------------------------- ### Switch Worktrees Interactively Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Example of switching between worktrees using the 'switch' command, which returns the path of the selected worktree. ```bash # Switch worktrees interactively cd $(git wt switch) ``` -------------------------------- ### Install Jekyll Dependencies Locally Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/github-pages-setup.md Installs the necessary Ruby gems for Jekyll. Run this command once when setting up the project locally. ```bash bundle install # First time only ``` -------------------------------- ### Debug Mode Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Shows how setting the DEBUG environment variable affects mutation commands by printing the command instead of executing it. Read-only commands are unaffected. ```bash DEBUG=1 git wt add feature # Output: [in /repo] git worktree add -b feature feature ``` -------------------------------- ### Git WT Error Propagation Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Demonstrates how errors are propagated upwards through command functions and handled by the Cobra CLI framework, including UI formatting. ```mermaid graph TD runAdd() ├─→ worktree.List() [returns error if git fails] ├─→ worktree.BareRoot() [returns error if not in repo] └─→ Any operation failure → return error ↓ Cobra catches error ↓ Error formatted by ui.Error() or printed by root.Execute() ↓ Exit code 1 ``` -------------------------------- ### Picker Package: Preview System Configuration Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Shows how to configure the preview command in the picker, using a shell command template with item value substitution. ```go // PreviewCmd: Shell command template (e.g., "git log --oneline {1}") // {1} replaced with selected Item.Value // Preview runs as subprocess, output shown in sidebar ``` -------------------------------- ### Running a Picker UI Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Use `picker.Run()` to display an interactive picker interface to the user. Configure the picker using `picker.Config`. ```go // Show picker result, err := picker.Run(picker.Config{...}) ``` -------------------------------- ### Build with Nix Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Builds the project using Nix, suitable for reproducible builds. ```bash nix build ``` -------------------------------- ### Configure Git Bare Repository with core.logallrefupdates Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/configuration.md When creating a bare repository, git-wt sets core.logallrefupdates to true to enable recording of all reference updates. ```go git config core.logallrefupdates true ``` -------------------------------- ### Inspect repository health Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Run diagnostics on the repository to identify and report potential health issues or inconsistencies within the worktree setup. ```bash git wt doctor ``` -------------------------------- ### Git WT Ambiguous Worktree Error Example Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Shows how the custom 'ambiguousWorktreeError' is returned by 'worktree.Resolve()' and how its message automatically formats candidate worktrees. ```mermaid graph TD worktree.Resolve() returns custom error type ↓ Contains list of matching worktrees ↓ Error message automatically formats candidates ``` -------------------------------- ### Create Worktree Interactively Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Demonstrates how to create a new worktree using the 'add' command, which will prompt for selection if no arguments are given. ```bash # Create worktree interactively git wt add ``` -------------------------------- ### Git WT Resolution Pattern Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Describes the common pattern for resolving worktree arguments, starting from user input to performing an operation on the resolved path. ```mermaid graph TD User Input (name, path, relative path) ↓ worktree.List() [get current worktrees] ↓ worktree.Resolve(entries, input) [multi-strategy resolution] ↓ Full Absolute Path ↓ Perform Operation (git command) ``` -------------------------------- ### Configure Preview Command Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/picker.md Configures the picker to display a preview pane using a shell command. The {1} placeholder in the command is replaced with the Value of the highlighted item. ```go cfg := picker.Config{ Items: items, PreviewCmd: "git log --oneline {1}..HEAD", } // When user highlights an item, runs: git log --oneline ..HEAD ``` -------------------------------- ### View All Worktrees Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Demonstrates how to use the 'status' command to display a dashboard of all managed worktrees. ```bash # See all worktrees git wt status ``` -------------------------------- ### Format All Files with nix fmt Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/ci-cd-setup.md Use this command to format all files according to the project's configured formatters. This ensures consistent code style across the project. ```bash nix fmt ``` -------------------------------- ### Repair Broken Worktree Files Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/commands.md Use this command to fix corrupted administrative files within a worktree. No specific setup is required beyond having a broken worktree. ```bash git wt repair ``` -------------------------------- ### Add a worktree and create a new branch Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Create a new worktree and simultaneously create a new local branch for it. This is useful for starting new development tasks. ```bash git wt add -b new-feature new-feature ``` -------------------------------- ### Enter Nix Development Shell Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Use this command to enter the development environment for the project, which requires Nix. ```bash nix develop ``` -------------------------------- ### Handle Invalid Worktree Error Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/errors.md This error occurs when the provided input does not match any existing worktree. The error message helpfully lists all available worktrees to guide the user. ```Go err := worktree.Validate(entries, "nonexistent") if err != nil { // err message lists all available worktrees fmt.Println(err) } ``` -------------------------------- ### List worktrees with different output formats Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md List all worktrees in the repository. Supports plain text, JSON, and porcelain (machine-readable) output formats for different use cases. ```bash git wt list git wt list --json git wt list --porcelain ``` -------------------------------- ### Get Branch Name for Worktree Path Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/worktree.md Returns the branch name associated with a given worktree path. If the path is not found or has no associated branch, an empty string is returned. ```go func BranchFor(entries []Entry, path string) string ``` ```go entries, _ := worktree.List() branch := worktree.BranchFor(entries, "feature") ``` -------------------------------- ### Bubble Tea Program and Style Utilities Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/ui.md Utilities for creating Bubble Tea programs and defining foreground styles using lipgloss. ```Go func NewProgram(model tea.Model, output *os.File, opts ...tea.ProgramOption) *tea.Program func ForegroundStyle(color lipgloss.TerminalColor) lipgloss.Style ``` -------------------------------- ### Get Default Branch for Remote Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/worktree.md Fetches the default branch name for a specified remote. It prioritizes local symbolic-ref lookup over network calls to `git remote show`. Returns an empty string if the default branch cannot be determined. ```go func DefaultBranch(remote string) string ``` ```go branch := worktree.DefaultBranch("origin") if branch != "" { fmt.Println("Default branch:", branch) } ``` -------------------------------- ### Get Bare Repository Root Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/worktree.md Retrieves the root directory of the bare Git repository structure. This function uses `git rev-parse --git-common-dir` and resolves symlinks. It returns an error if the current directory is not part of a Git repository. ```go func BareRoot() (string, error) ``` ```go root, err := worktree.BareRoot() if err != nil { fmt.Println("Not in a git repo:", err) return } fmt.Println("Bare root:", root) ``` -------------------------------- ### Build Binary Locally Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Builds the git-wt binary locally, specifying the output file name and path. ```bash go build -o git-wt ./cmd/git-wt/ ``` -------------------------------- ### Get Default Remote Name Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/worktree.md Determines the most suitable remote name for the current repository. It prioritizes a single remote, then the current branch's remote, then 'origin', and finally the alphabetically first remote. Returns an empty string if no remotes are found. ```go func DefaultRemote() string ``` ```go remote := worktree.DefaultRemote() if remote != "" { fmt.Println("Default remote:", remote) } ``` -------------------------------- ### Programmatic Git-WT Operations Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Demonstrates common programmatic operations using the git-wt library, such as listing worktrees, finding them by branch, resolving paths, executing git commands, and running the interactive picker. ```go import ( "github.com/ahmedelgabri/git-wt/internal/worktree" "github.com/ahmedelgabri/git-wt/internal/git" "github.com/ahmedelgabri/git-wt/internal/picker" ) // Get all worktrees entries, _ := worktree.List() // Find worktree by branch entry := worktree.FindByBranch(entries, "main") // Resolve user input to path path, _ := worktree.Resolve(entries, userInput) // Execute git command out, _ := git.Query("log", "--oneline", "-5") // Show interactive picker result, _ := picker.Run(picker.Config{Items: items}) ``` -------------------------------- ### Switch to a worktree Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Navigate to the directory of the currently active worktree. This command helps in quickly switching context to the desired worktree. ```bash cd "$(git wt switch)" ``` -------------------------------- ### Pure Go Directory Copy Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Highlights the use of `internal/fsutil` for directory copying, serving as a replacement for rsync. ```go // Pure Go copy: `internal/fsutil` provides directory copy, replacing rsync. ``` -------------------------------- ### List Supported Git WT Commands Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/types.md An array of strings listing commands natively implemented by git-wt. These are the primary commands you can use with the `git wt` CLI. ```go var supportedCommandNames = []string{ "add", // Create a new worktree "clone", // Clone with bare structure "doctor", // Run diagnostics "migrate", // Convert existing repo "remove", // Remove worktrees "status", // Show worktree status "switch", // Interactively select worktree "update", // Fetch and update default branch } ``` -------------------------------- ### Worktree Package: Data Flow for Listing Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Shows the sequence of operations for listing worktrees, from calling List() to parsing the output. ```go worktree.List() ↓ git.Query("worktree", "list", "--porcelain") ↓ ParsePorcelain(output) ↓ []Entry {Path, Branch, Head, Locked, Prunable, ...} ``` -------------------------------- ### RunIn Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in the specified directory. Returns an error if the command fails. ```APIDOC ## RunIn ### Description Executes a git mutation command in the specified directory. ### Method `RunIn` ### Parameters #### Path Parameters - **dir** (string) - Required - Working directory for git command - **args** (...string) - Required - Git command arguments ### Returns - **error** - Error if command fails ### Example ```go err := git.RunIn("/path/to/worktree", "pull") ``` ``` -------------------------------- ### Git-WT Project Structure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Illustrates the directory layout and key files within the git-wt project. ```tree git-wt/ ├── cmd/ │ └── git-wt/ │ └── main.go # Entry point ├── internal/ │ ├── cmd/ # Cobra command implementations │ │ ├── root.go # Root command, help, version │ │ ├── add.go # Create worktree │ │ ├── clone.go # Clone with bare structure │ │ ├── doctor.go # Repository diagnostics │ │ ├── migrate.go # Convert existing repo │ │ ├── remove.go # Remove worktrees │ │ ├── status.go # Worktree dashboard │ │ ├── switch.go # Interactive selection │ │ ├── update.go # Fetch and pull default │ │ ├── preview.go # Hidden preview command │ │ ├── helpers.go # Shared utilities │ │ ├── render.go # Output formatting │ │ └── ... # Other helpers │ ├── git/ │ │ └── git.go # Git command runner │ ├── worktree/ │ │ ├── cache.go # Entry type, List(), Parse │ │ └── resolve.go # Path resolution, Bare root │ ├── picker/ │ │ ├── picker.go # FZF interface │ │ └── item.go # Item, Config, Result │ ├── ui/ │ │ ├── ui.go # Color, formatting, prompts │ │ ├── confirm.go # Y/N prompt UI │ │ ├── input.go # Text input UI │ │ ├── spinner.go # Loading spinner │ │ ├── task.go # Task runner with output │ │ ├── runtime.go # TTY detection, Bubble Tea │ │ ├── steps.go # Sequential step runner │ │ └── async.go # AsyncPhase enum │ └── fsutil/ │ └── copy.go # Directory copy with excludes └── tests/ └── *.bats # E2E tests ``` -------------------------------- ### Importing Git-WT Modules Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Shows the standard import paths for core git-wt modules. These imports are necessary to use the library's functionalities. ```go import ( "github.com/ahmedelgabri/git-wt/internal/git" "github.com/ahmedelgabri/git-wt/internal/worktree" "github.com/ahmedelgabri/git-wt/internal/picker" "github.com/ahmedelgabri/git-wt/internal/ui" "github.com/ahmedelgabri/git-wt/internal/fsutil" ) ``` -------------------------------- ### Clone a repository with bare worktree layout Source: https://github.com/ahmedelgabri/git-wt/blob/main/README.md Use git-wt to clone a repository, setting up a bare repository structure with a dedicated worktree for the default branch. ```bash git wt clone https://github.com/user/repo.git ``` -------------------------------- ### Run Picker Function Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/picker.md Displays the interactive picker interface and returns the user's selection. It can bypass the TUI if the GIT_WT_SELECT environment variable is set. ```go func Run(cfg Config) (Result, error) ``` ```go items := []picker.Item{ {Label: "main", Value: "/repo/main", Desc: "default branch"}, {Label: "feature", Value: "/repo/feature", Desc: "feature branch"}, } result, err := picker.Run(picker.Config{ Items: items, Prompt: "Select worktree: ", }) if err != nil { return err } if !result.Canceled && len(result.Items) > 0 { fmt.Println("Selected:", result.Items[0].Label) } ``` -------------------------------- ### Git WT Add Command Flow Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Illustrates the interactive flow for the 'git wt add' command, from fetching branches to creating a new worktree and streaming its output. ```mermaid graph TD add command → no args ↓ loadInteractiveAddItems() ├─→ fetchInteractiveBranches() [git fetch --all --prune] └─→ builds Item[] from remote branches ↓ picker.Run({Items: branches, ...}) ↓ User selects or creates new branch ↓ createNewBranch() or splitRemoteBranchRef() ↓ promptWorktreePath() [ui.PromptInput] ↓ git.RunToContext("worktree", "add", ...) [streams output] ↓ git.RunToContext("branch", "--set-upstream-to", ...) ↓ printCreatedWorktreePath(path) ``` -------------------------------- ### UI Task Configuration Structure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Configuration for executing a UI task, including its message and output display options. ```go type TaskConfig struct { Message string ShowOutput, RawOutput bool } ``` -------------------------------- ### Serve Jekyll Site Locally Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/github-pages-setup.md Builds and serves the Jekyll site locally for preview. Access the site at http://localhost:4000. ```bash bundle exec jekyll serve ``` -------------------------------- ### QueryIn: Execute Read-Only Git Command in Directory Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a read-only git command in a specified directory and returns its trimmed output. ```go func QueryIn(dir string, args ...string) (string, error) ``` -------------------------------- ### Picker Package: Interactive Selection Flow Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Describes the process of using the picker package, from initiating a selection to receiving the result. ```go picker.Run(Config{Items: [], ...}) ↓ Builds fzf options from Config ↓ fzf.Run() with input/output channels ↓ Format items as tab-delimited: value\tlabel[ · desc] ↓ fzf displays and filters (Value hidden by --with-nth) ↓ User selects, fzf returns selected items ↓ Parse output back to Item values ↓ Result{Items: [], Canceled: bool} ``` -------------------------------- ### Interactive Picker with fzf Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Explains how the `internal/picker` package embeds fzf using Input/Output channels for interactive fuzzy selection. Items are formatted for fzf, and a hidden `_preview` command is used for preview content. ```go // Interactive picker: `internal/picker` embeds fzf as a Go library via `Input`/`Output` channels. // Items are formatted as `value\tlabel[ · desc]` with `--with-nth=2..` to hide the value from display while exposing it as `{1}` in `--preview`. // Preview content is generated by a hidden `_preview` cobra subcommand that fzf invokes as a subprocess. ``` -------------------------------- ### Go Function to List All Worktrees Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/worktree.md Retrieves a list of all Git worktrees (excluding the bare repository itself) by executing `git worktree list --porcelain`. Ensure the `worktree` package is imported. ```go func List() ([]Entry, error) ``` ```go entries, err := worktree.List() if err != nil { return err } for _, entry := range entries { fmt.Printf("Branch: %s at %s\n", entry.Branch, entry.Path) } ``` -------------------------------- ### NO_COLOR Environment Variable Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Demonstrates that color output via lipgloss respects the `NO_COLOR` environment variable. ```go // NO_COLOR: Color output via lipgloss respects the `NO_COLOR` environment variable. ``` -------------------------------- ### Git-WT Entry Point Execution Flow Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Details the execution path from the main entry point to the Cobra command execution. ```go cmd/git-wt/main.go ↓ cmd.Execute() [internal/cmd/root.go:101] ↓ rootCmd.Execute() [Cobra] ├─→ Matches command name to registered subcommand ├─→ Runs subcommand's RunE function └─→ On error: formats and prints error message ``` -------------------------------- ### RunInToContext: Execute Git Mutation in Directory with Context and Stream Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in a specified directory with context, streaming the output to a writer. ```go func RunInToContext(ctx context.Context, dir string, w io.Writer, args ...string) error ``` -------------------------------- ### picker.Run Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/picker.md Displays the picker interface and returns the selected items. It can bypass the TUI if the GIT_WT_SELECT environment variable is set. ```APIDOC ## Run ### Description Displays the picker interface and returns the selected items. If GIT_WT_SELECT env var is set, bypasses the TUI and selects matching items directly. ### Function Signature ```go func Run(cfg Config) (Result, error) ``` ### Parameters #### Path Parameters * **cfg** (Config) - Required - Picker configuration ### Returns * **Result** - Selected items or canceled state * **error** - Error if picker fails ### Example ```go items := []picker.Item{ {Label: "main", Value: "/repo/main", Desc: "default branch"}, {Label: "feature", Value: "/repo/feature", Desc: "feature branch"}, } result, err := picker.Run(picker.Config{ Items: items, Prompt: "Select worktree: ", }) if err != nil { return err } if !result.Canceled && len(result.Items) > 0 { fmt.Println("Selected:", result.Items[0].Label) } ``` ``` -------------------------------- ### Listing Worktrees Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Use the `worktree.List()` function to retrieve all worktree entries. This is a common first step when interacting with worktrees. ```go // Get all worktrees entries, err := worktree.List() ``` -------------------------------- ### Configure Git Bare Repository with worktree.useRelativePaths Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/configuration.md git-wt configures worktree.useRelativePaths to true for bare repositories, enabling the use of relative paths for worktrees (requires Git 2.48.0+). ```go git config worktree.useRelativePaths true ``` -------------------------------- ### Run All Checks Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Performs all project checks, including building the binary and verifying formatting. ```bash nix flake check ``` -------------------------------- ### Configure Git Bare Repository with remote.origin.fetch Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/configuration.md For bare repositories, git-wt sets the remote.origin.fetch refspec to "+refs/heads/*:refs/remotes/origin/*" to configure fetch behavior for the origin remote. ```go git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*" ``` -------------------------------- ### Apply Color and Formatting to Strings Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/ui.md Applies color and formatting to strings using predefined functions. These functions respect the NO_COLOR environment variable. ```go fmt.Println(ui.Green("Success!")) fmt.Println(ui.Bold("Important")) fmt.Println(ui.Red("Error")) ``` -------------------------------- ### RunInWithOutputContext: Execute Git Mutation with Context Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in a specified directory with context. Returns the combined output of the command. ```go func RunInWithOutputContext(ctx context.Context, dir string, args ...string) (string, error) ``` -------------------------------- ### Picker Configuration Structure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Defines the configuration for the picker, including items, multi-select option, prompt, and header. ```go type Config struct { Items []Item Multi bool Prompt, Header, PreviewCmd string } ``` -------------------------------- ### Git Package: Read-Only Operations Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Demonstrates how to capture stdout from git commands using Query functions. ```go // Read-Only (always execute, even in DEBUG mode): // - Query() / QueryContext() - Capture stdout // - QueryLines() - Split output into lines // - QueryRun() - Stream directly to terminal // - QueryCombined() - Capture stdout + stderr ``` -------------------------------- ### Format Code with Nix Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Formats Go, Markdown, YAML, JSON, SVG, and Nix files using gofumpt, prettier, and alejandra. ```bash nix fmt ``` -------------------------------- ### Manually Run Pre-push Hooks Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/ci-cd-setup.md Execute the pre-push hooks manually to verify the flake builds before pushing to the remote repository. This ensures the project is in a buildable state. ```bash lefthook run pre-push ``` -------------------------------- ### Run Go Unit Tests Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Executes all Go unit tests within the project. ```bash go test ./... ``` -------------------------------- ### Run All E2E Tests Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Executes all end-to-end tests. This command will auto-build the binary if needed. ```bash bats tests/ ``` -------------------------------- ### Git Package: Mutation Operations Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Illustrates executing git commands that modify the repository, with optional echoing in DEBUG mode. ```go // Mutations (echo in DEBUG mode): // - Run() / RunContext() - Execute in current dir // - RunIn() / RunInContext() - Execute in specific dir // - RunWithOutput() / RunInWithOutput() - Capture output // - RunTo() / RunInTo() - Stream to writer ``` -------------------------------- ### Git WT Migrate Command Flow Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Details the steps involved in the 'git wt migrate' command, including building a migration plan, user confirmation, and executing migration steps. ```mermaid graph TD migrate command ↓ buildMigratePlan() ├─→ Detect changes (git status --porcelain) ├─→ Get current branch ├─→ Get default remote/branch ├─→ Get stash count ├─→ Enumerate remotes and selected config └─→ detectBareRepo() [check if already bare] ↓ renderMigratePlan() [display plan to user] ↓ ui.Confirm() [ask for permission] ↓ executeMigrationSteps() ├─→ Create .bare directory ├─→ Move .git to .bare ├─→ Create .git file (gitdir pointer) ├─→ configureBareRepo() [set config keys] ├─→ Copy worktrees ├─→ Restore stashes ├─→ Set up branches └─→ Restore current branch ``` -------------------------------- ### git-wt Command Pattern Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/README.md Shows the general syntax for invoking git-wt commands, including the base command, sub-command, and optional arguments. ```bash git wt [options] [arguments] ``` -------------------------------- ### RunInTo: Execute Git Mutation in Directory and Stream Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command within a specified directory, streaming the output to a writer. ```go func RunInTo(dir string, w io.Writer, args ...string) error ``` -------------------------------- ### Run Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command. In DEBUG mode, prints the command instead of executing it. Returns an error if the command fails. ```APIDOC ## Run ### Description Executes a git mutation command. In DEBUG mode (when DEBUG env var is set), prints the command instead of executing it. ### Method `Run` ### Parameters #### Arguments - **args** (...string) - Required - Git command arguments (e.g., "clone", "--progress", "repo.git") ### Returns - **error** - Error if command fails (or nil in DEBUG mode) ### Example ```go if err := git.Run("worktree", "add", "-b", "feature", "feature"); err != nil { fmt.Println("Failed:", err) } ``` ``` -------------------------------- ### RunToContext: Execute Git Mutation with Context and Stream Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command with context, streaming its output to a writer. ```go func RunToContext(ctx context.Context, w io.Writer, args ...string) error ``` -------------------------------- ### Run Git Mutation Command with Context and Capture Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command with context and returns its combined output. Use when you need to capture output from a potentially long-running, interruptible command. ```go func RunWithOutputContext(ctx context.Context, args ...string) (string, error) ``` -------------------------------- ### Git WT Task Execution Pattern Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Illustrates the pattern for executing tasks that display progress or output, handling both TTY and non-TTY environments. ```mermaid graph TD ui.SpinWithOutputContext(message, fn) ↓ Show spinner on TTY / Status on non-TTY ↓ fn(ctx, w) executes, writes to w ↓ Output streamed to viewport/stderr ↓ Spinner shows success/error result ``` -------------------------------- ### Handle Git Mutation Command Failure Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/errors.md This snippet demonstrates how to handle failures in git mutation commands like 'fetch'. It includes specific handling for DEBUG mode where the command is printed but not executed. ```Go // When a git mutation command fails if err := git.Run("fetch", remote); err != nil { // In DEBUG mode, this is nil (command was printed, not executed) // In normal mode, contains git's error output ui.Errorf("Fetch failed: %v", err) return err } ``` -------------------------------- ### Mock Git Failures for Testing Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/errors.md In test environments, you can override specific functions like `git.QueryLines` to simulate Git command failures. This allows for thorough testing of error handling logic within the application without relying on actual Git command failures. ```go // In tests, can override git.QueryLines to return error // when testing error handling ``` -------------------------------- ### RunInTo Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in the specified directory, streaming output to a writer. ```APIDOC ## RunInTo ### Description Executes a git mutation command in the specified directory, streaming output to a writer. ### Method Not applicable (Go function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **dir** (string) - Required - Working directory - **w** (io.Writer) - Required - Writer for output - **args** (...string) - Required - Git command arguments ### Returns - **error**: Error if command fails ``` -------------------------------- ### Run BATS tests with custom binary Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Execute the test suite while overriding the default binary path using the GIT_WT environment variable. ```bash GIT_WT=/path/to/binary bats tests/ ``` -------------------------------- ### Run Git Mutation Command in Directory and Capture Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in a specified directory and returns its combined output. Useful for capturing output from commands in non-current directories. ```go func RunInWithOutput(dir string, args ...string) (string, error) ``` -------------------------------- ### RunWithOutputContext Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command with context and returns its combined output. Returns the output string and an error if the command fails. ```APIDOC ## RunWithOutputContext ### Description Executes a git mutation command with context and returns its combined output. ### Method `RunWithOutputContext` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for cancellation - **args** (...string) - Required - Git command arguments ### Returns - **string** - Combined output - **error** - Error if fails ``` -------------------------------- ### Run Git Mutation Command in Directory with Context Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in a specified directory with context for cancellation. Combines directory specificity with interruptibility. ```go func RunInContext(ctx context.Context, dir string, args ...string) error ``` -------------------------------- ### Run a Single E2E Test File Source: https://github.com/ahmedelgabri/git-wt/blob/main/AGENTS.md Executes end-to-end tests from a specific file. ```bash bats tests/add.bats ``` -------------------------------- ### RunTo: Execute Git Mutation and Stream Output Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command, streaming its standard output and standard error to a provided writer. ```go func RunTo(w io.Writer, args ...string) error ``` -------------------------------- ### Format Specific Files with nix fmt Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/ci-cd-setup.md Use this command to format only specific files or directories. Provide the path to the file or directory you want to format. ```bash nix fmt -- path/to/file ``` -------------------------------- ### RunInToContext Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command in the specified directory with context, streaming to a writer. ```APIDOC ## RunInToContext ### Description Executes a git mutation command in the specified directory with context, streaming to a writer. ### Method Not applicable (Go function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (context.Context) - Required - Context for cancellation - **dir** (string) - Required - Working directory - **w** (io.Writer) - Required - Writer for output - **args** (...string) - Required - Git command arguments ### Returns - **error**: Error if command fails ``` -------------------------------- ### QueryContext: Execute Read-Only Git Command with Context Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a read-only git command with optional context and returns its trimmed output. ```go func QueryContext(ctx context.Context, args ...string) (string, error) ``` -------------------------------- ### Symlink Handling in CopyDir Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/fsutil.md Illustrates how CopyDir handles symbolic links. Symlinks are copied as symlinks, preserving the original link target. ```go // If src contains: /src/link -> /src/target // Result: /dst/link -> /src/target (same link target) ``` -------------------------------- ### Serve Jekyll Site Locally with Docker Source: https://github.com/ahmedelgabri/git-wt/blob/main/docs/github-pages-setup.md Runs the Jekyll serve command within a Docker container, mounting the local docs directory. This provides an isolated environment for local development. ```bash docker run --rm -v "$PWD/docs:/srv/jekyll" -p 4000:4000 jekyll/jekyll jekyll serve ``` -------------------------------- ### RunContext Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command with optional context for cancellation. Returns an error if the command fails. ```APIDOC ## RunContext ### Description Executes a git mutation command with optional context for cancellation. ### Method `RunContext` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for command cancellation - **args** (...string) - Required - Git command arguments ### Returns - **error** - Error if command fails ### Example ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() err := git.RunContext(ctx, "fetch", "origin") ``` ``` -------------------------------- ### RunToContext Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/api-reference/git.md Executes a git mutation command with context, streaming stdout and stderr to a writer. ```APIDOC ## RunToContext ### Description Executes a git mutation command with context, streaming stdout and stderr to a writer. ### Method Not applicable (Go function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **ctx** (context.Context) - Required - Context for cancellation - **w** (io.Writer) - Required - Writer for output - **args** (...string) - Required - Git command arguments ### Returns - **error**: Error if command fails ``` -------------------------------- ### Executing Git Commands Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md The `git.Query()` function allows executing arbitrary git commands and capturing their output. Use this for read-only git operations. ```go // Execute git command out, err := git.Query("log", "--oneline", "-5") ``` -------------------------------- ### picker.Run Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/REFERENCE_INDEX.md Initiates an interactive fuzzy selection process using fzf. ```APIDOC ## picker.Run ### Description Initiates an interactive fuzzy selection process using the fzf tool. It presents a list of items to the user and returns their selection. ### Method Run ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **config** (picker.Config) - Configuration for the picker, including items, prompt, and multi-select options. ### Request Example ```go config := picker.Config{ Items: []picker.Item{ {Label: "Worktree A", Value: "path/a"}, {Label: "Worktree B", Value: "path/b"}, }, Prompt: "Select a worktree:", } result, err := picker.Run(config) ``` ### Response #### Success Response (200) - **result** (picker.Result) - The result of the picker interaction, containing selected items and a cancellation status. - **error** (error) - An error if the picker failed to run. #### Response Example ```json { "result": { "Items": [ { "Label": "Worktree A", "Value": "path/a", "Desc": "" } ], "Canceled": false }, "error": null } ``` ``` -------------------------------- ### Worktree Package: Resolution Strategy Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/architecture.md Outlines the steps taken by the Resolve() function to find a worktree, including exact match, relative path, and realpath resolution. ```go // Resolution Strategy (in `Resolve()`): // 1. Exact path match against cached entries // 2. Relative-to-bare-root match (e.g., "feature" → "{bareRoot}/feature") // 3. Realpath resolution (follow symlinks, resolve relative paths) // 4. Basename matching (if unique, e.g., "feature" when only one "feature" worktree) // 5. Fails with list of candidates if ambiguous ``` -------------------------------- ### List Worktrees Source: https://github.com/ahmedelgabri/git-wt/blob/main/_autodocs/commands.md Use 'git wt list' to display all worktrees in the native git format. Supports all standard 'git worktree list' options, including '--porcelain' for machine-readable output and '-v' for verbose details. ```bash git wt list ``` ```bash git wt list --porcelain ``` ```bash git wt list -v ```