Skip to content

Commit 9af8417

Browse files
committed
📝 Add prompts for GitHub Copilot (#4)
1 parent 987f3e7 commit 9af8417

File tree

7 files changed

+473
-0
lines changed

7 files changed

+473
-0
lines changed

.github/copilot-instructions.md

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
# Copilot Instructions
2+
3+
## Architecture & Flow
4+
5+
`bin/gtr` (961 lines) dispatches to `cmd_*` functions (case block lines 36‑77). Libraries sourced at startup:
6+
7+
- `lib/core.sh` - create/list/remove/resolve worktrees
8+
- `lib/config.sh` - git config wrapper with precedence
9+
- `lib/ui.sh` - log_error/log_info/prompts
10+
- `lib/copy.sh` - glob pattern file copying
11+
- `lib/hooks.sh` - postCreate/postRemove execution
12+
- `lib/platform.sh` - OS detection + GUI helpers
13+
14+
Adapters in `adapters/{editor,ai}` each implement two functions with strict contracts (see below).
15+
16+
## Key Concepts
17+
18+
- Special ID `1` = main repo (usable in `open`, `go`, `ai`).
19+
- Folder naming = sanitized branch (`feature/auth``feature-auth`).
20+
- Base dir resolution (`resolve_base_dir`): config `gtr.worktrees.dir` → env → default `<repo>-worktrees`; relative paths resolved from repo root; tilde expanded; warns if inside repo unignored.
21+
- Target resolution (`resolve_target`): ID `1` → current → sanitized path → scan directories; returns TSV: `is_main\tpath\tbranch`.
22+
- Config precedence (`cfg_default`): git config (local→global→system) → env → fallback. Multi-value keys merged & deduped (`cfg_get_all`).
23+
24+
## Adapter Contract
25+
26+
Editor: `editor_can_open`, `editor_open <path>`; AI: `ai_can_start`, `ai_start <path> [args...]`. Must check tool availability (`command -v`), emit errors via `log_error`, never silently fail, and avoid side effects outside the target directory (AI uses subshell `(cd ...)`). Update README, help (`cmd_help`), completions.
27+
28+
## Manual Testing (Essential Subset)
29+
30+
```bash
31+
./bin/gtr new feature/x # creates folder feature-x
32+
./bin/gtr open feature/x # loads configured editor
33+
./bin/gtr ai feature/x # starts configured AI tool
34+
./bin/gtr list # lists main + worktrees
35+
./bin/gtr rm feature/x # removes worktree
36+
./bin/gtr go feature/x # prints path (use in cd)
37+
```
38+
39+
Advanced: `--force --name backend` (same branch multi-worktree); `git config --add gtr.copy.include "**/.env.example"`; hooks: `git config --add gtr.hook.postCreate "npm install"`.
40+
Full matrix: see `.github/instructions/testing.instructions.md`.
41+
42+
## Common Changes
43+
44+
**Add command**: new `cmd_<name>()` function in `bin/gtr` + case entry (lines 36‑77) + help text in `cmd_help` + all three completions (bash/zsh/fish) + README docs.
45+
46+
**Add adapter**: two functions (see contract below), `log_error` with install instructions, quote all paths, check `command -v`. Update: README, help text (`cmd_help`), completions (all three).
47+
48+
**Modify core (`lib/*.sh`)**: keep backwards compatibility, always quote variables `"$var"`, support Git <2.22 fallback (`branch --show-current``rev-parse --abbrev-ref HEAD`), test manually across macOS/Linux.
49+
50+
## Patterns & Gotchas
51+
52+
- Always quote paths (spaces). Avoid unguarded globbing.
53+
- `set -e` active: ensure non-critical failures are guarded (`command || true`).
54+
- Multi-value config keys require `git config --add` (do not overwrite entire list unintentionally).
55+
- If placing worktrees inside repo (relative path), add directory to `.gitignore` to prevent accidental commits.
56+
57+
## Debugging
58+
59+
Trace: `bash -x ./bin/gtr new test`; scoped: `set -x` / `set +x`; list function: `declare -f resolve_target`; inspect var: `echo "DEBUG=$var" >&2`; adapter sourcing: `bash -c 'source adapters/ai/claude.sh && ai_can_start && echo OK'`.
60+
61+
## Troubleshooting Quick
62+
63+
Permission: `chmod +x bin/gtr`. Missing adapter: `gtr adapter`. Install check: `./bin/gtr doctor`. Config issues: `git config --list | grep gtr`. Worktree confusion: inspect `resolve_target` logic & naming. Symlink problems: ensure `/usr/local/bin` exists then `ln -s "$(pwd)/bin/gtr" /usr/local/bin/gtr`.
64+
65+
## Version
66+
67+
Update `GTR_VERSION` (line 8 `bin/gtr`) when releasing; affects `gtr version` / `--version`.
68+
69+
## Documentation Structure
70+
71+
- **`.github/copilot-instructions.md`** (this file) - High-level guide for AI agents
72+
- **`.github/instructions/*.instructions.md`** - Specific guidance by file pattern:
73+
- `testing.instructions.md` - Manual testing checklist (applies to: `bin/gtr`, `lib/**/*.sh`, `adapters/**/*.sh`)
74+
- `sh.instructions.md` - Shell scripting conventions (applies to: `**/*.sh`, `**/*.bash`, `**/*.fish`)
75+
- `lib.instructions.md` - Core library modification guidelines (applies to: `lib/**/*.sh`)
76+
- `editor.instructions.md` - Editor adapter contract (applies to: `adapters/editor/**/*.sh`)
77+
- `ai.instructions.md` - AI tool adapter contract (applies to: `adapters/ai/**/*.sh`)
78+
- `completions.instructions.md` - Shell completion updates (applies to: `completions/*`)
79+
- **`README.md`** - User-facing documentation
80+
- **`CONTRIBUTING.md`** - Contribution guidelines
81+
- **`CLAUDE.md`** - Extended development guide for Claude Code
82+
83+
Feedback: Ask if more detail needed on copy patterns, hooks, or multi-worktree `--force` safety.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
---
2+
applyTo: adapters/ai/**/*.sh
3+
---
4+
5+
# AI Instructions
6+
7+
## Adding Features
8+
9+
### New AI Tool Adapter (`adapters/ai/<name>.sh`)
10+
11+
```bash
12+
#!/usr/bin/env bash
13+
# ToolName adapter
14+
15+
ai_can_start() {
16+
command -v tool-cli >/dev/null 2>&1
17+
}
18+
19+
ai_start() {
20+
local path="$1"
21+
shift
22+
if ! ai_can_start; then
23+
log_error "ToolName not found. Install with: ..."
24+
return 1
25+
fi
26+
(cd "$path" && tool-cli "$@") # Note: subshell for directory change
27+
}
28+
```
29+
30+
**Also update**: Same as editor adapters (README, completions, help text)
31+
32+
## Contract & Guidelines
33+
34+
- Must define: `ai_can_start` (0 = available), `ai_start <path> [args...]` (runs in subshell `(cd ...)`).
35+
- Always quote: `"$path"` and arguments; never assume current working directory.
36+
- Use `log_error` + helpful install hint; never silent fail.
37+
- Keep side effects confined to worktree directory; do not modify repo root unintentionally.
38+
- Accept extra args after `--`: preserve ordering (`ai_start` receives already-shifted args).
39+
- Prefer fast startup; heavy initialization belongs in hooks (`postCreate`), not adapters.
40+
- When adding adapter: update `cmd_help`, README tool list, and completions (bash/zsh/fish).
41+
- Test manually: `bash -c 'source adapters/ai/<tool>.sh && ai_can_start && echo OK'`.
42+
- Inspect function definition if needed: `declare -f ai_start`.
Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
---
2+
applyTo: completions/gtr.bash, completions/_gtr, completions/gtr.fish
3+
---
4+
5+
# Completions Instructions
6+
7+
## Overview
8+
9+
Shell completions provide tab-completion for `gtr` commands, flags, branches, and adapter names across Bash, Zsh, and Fish shells.
10+
11+
## When to Update Completions
12+
13+
**Always update all three completion files** when:
14+
15+
- Adding new commands (e.g., `gtr new-command`)
16+
- Adding new flags to existing commands (e.g., `--new-flag`)
17+
- Adding editor or AI adapters (completion must list available adapters)
18+
- Changing command names or flag names
19+
20+
## File Responsibilities
21+
22+
- **`completions/gtr.bash`** - Bash completion (requires bash-completion v2+)
23+
- **`completions/_gtr`** - Zsh completion (uses Zsh completion system)
24+
- **`completions/gtr.fish`** - Fish shell completion
25+
26+
## Implementation Pattern
27+
28+
Each completion file implements:
29+
30+
1. **Command completion** - Top-level commands (`new`, `rm`, `open`, `ai`, `list`, etc.)
31+
2. **Flag completion** - Command-specific flags (e.g., `--from`, `--force`, `--editor`)
32+
3. **Branch completion** - Dynamic completion of existing worktree branches (via `gtr list --porcelain`)
33+
4. **Adapter completion** - Editor names (`cursor`, `vscode`, `zed`) and AI tool names (`aider`, `claude`, `codex`)
34+
35+
## Testing Completions
36+
37+
**Manual testing** (no automated tests):
38+
39+
```bash
40+
# Bash - source the completion file
41+
source completions/gtr.bash
42+
gtr <TAB> # Should show commands
43+
gtr new <TAB> # Should show flags
44+
gtr open <TAB> # Should show branches
45+
gtr open --editor <TAB> # Should show editor names
46+
47+
# Zsh - fpath must include completions directory
48+
fpath=(completions $fpath)
49+
autoload -U compinit && compinit
50+
gtr <TAB>
51+
52+
# Fish - symlink to ~/.config/fish/completions/
53+
ln -s "$(pwd)/completions/gtr.fish" ~/.config/fish/completions/
54+
gtr <TAB>
55+
```
56+
57+
## Branch Completion Logic
58+
59+
All three completions dynamically fetch current worktree branches:
60+
61+
- Parse output of `gtr list --porcelain` (tab-separated: `path\tbranch\tstatus`)
62+
- Extract branch column (second field)
63+
- Exclude the special ID `1` (main repo) if needed
64+
65+
## Adapter Name Updates
66+
67+
When adding an editor or AI adapter:
68+
69+
**Bash** (`completions/gtr.bash`):
70+
71+
- Update `_gtr_editors` array or case statement
72+
- Update flag completion for `--editor` in `open` command
73+
74+
**Zsh** (`completions/_gtr`):
75+
76+
- Update `_arguments` completion specs for `--editor` or `--ai`
77+
- Use `_values` or `_alternative` for adapter names
78+
79+
**Fish** (`completions/gtr.fish`):
80+
81+
- Update `complete -c gtr` lines for editor/AI flags
82+
- List adapter names explicitly or parse from `gtr adapter` output
83+
84+
## Keep in Sync
85+
86+
The three completion files must stay synchronized:
87+
88+
- Same commands supported
89+
- Same flags for each command
90+
- Same adapter names
91+
- Same branch completion behavior
92+
93+
## Examples
94+
95+
**Adding a new command `gtr status`**:
96+
97+
1. Add `status` to main command list in all three files
98+
2. Add flag completion if the command has flags
99+
3. Test tab completion works
100+
101+
**Adding a new editor `sublime`**:
102+
103+
1. Create `adapters/editor/sublime.sh` with contract functions
104+
2. Add `sublime` to editor list in all three completion files
105+
3. Update help text in `bin/gtr` (`cmd_help` function)
106+
4. Update README with installation instructions
107+
5. Test `gtr open --editor s<TAB>` completes to `sublime`
108+
109+
## Common Pitfalls
110+
111+
- **Forgetting to update all three files** - Always update Bash, Zsh, AND Fish
112+
- **Hardcoding adapter names** - Keep adapter lists in sync with actual files in `adapters/{editor,ai}/`
113+
- **Not testing** - Source/reload completions and test with `<TAB>` key
114+
- **Case sensitivity** - Command and flag names must match exactly (case-sensitive)
115+
116+
## Bash-Specific Notes
117+
118+
- Requires `bash-completion` v2+ package
119+
- Use `COMPREPLY` array to return completions
120+
- Use `compgen` to filter based on current word (`$cur`)
121+
- Check `$COMP_CWORD` for argument position
122+
123+
## Zsh-Specific Notes
124+
125+
- Uses `_arguments` completion framework
126+
- Supports more sophisticated completion logic (descriptions, grouping)
127+
- Use `_describe` for simple lists, `_arguments` for complex commands
128+
129+
## Fish-Specific Notes
130+
131+
- Uses declarative `complete -c gtr` syntax
132+
- Conditions can check previous arguments with `__fish_seen_subcommand_from`
133+
- Can call external commands for dynamic completion
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
---
2+
applyTo: adapters/editor/**/*.sh
3+
---
4+
5+
# Editor Instructions
6+
7+
## Adding Features
8+
9+
### New Editor Adapter (`adapters/editor/<name>.sh`)
10+
11+
```bash
12+
#!/usr/bin/env bash
13+
# EditorName adapter
14+
15+
editor_can_open() {
16+
command -v editor-cli >/dev/null 2>&1
17+
}
18+
19+
editor_open() {
20+
local path="$1"
21+
if ! editor_can_open; then
22+
log_error "EditorName not found. Install from https://..."
23+
return 1
24+
fi
25+
editor-cli "$path"
26+
}
27+
```
28+
29+
**Also update**:
30+
31+
- README.md (setup instructions)
32+
- All three completion files: `completions/gtr.bash`, `completions/_gtr`, `completions/gtr.fish`
33+
- Help text in `bin/gtr` (`cmd_help` function)
34+
35+
## Contract & Guidelines
36+
37+
- Required functions: `editor_can_open` (probe via `command -v`), `editor_open <path>`.
38+
- Quote all paths; support spaces. Avoid changing PWD globally—no subshell needed (editor opens path).
39+
- Use `log_error` with actionable install guidance if command missing.
40+
- Keep adapter lean: no project scans, no blocking prompts.
41+
- Naming: file name = tool name (`zed.sh``zed` flag). Avoid uppercase.
42+
- Update: README editor list, completions (bash/zsh/fish), help (`Available editors:`), optional screenshots.
43+
- Manual test: `bash -c 'source adapters/editor/<tool>.sh && editor_can_open && editor_open . || echo fail'`.
44+
- Fallback behavior: if editor absent, fail clearly; do NOT silently defer to file browser.
45+
- Inspect function definition if needed: `declare -f editor_open`.
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
---
2+
applyTo: lib/**/*.sh
3+
---
4+
5+
# Lib Instructions
6+
7+
## Modifying Core (`lib/*.sh`)
8+
9+
- **Maintain backwards compatibility** with existing configs
10+
- **Quote all paths**: Support spaces in directory names
11+
- **Use `log_error` / `log_info`** from `lib/ui.sh` for user messages
12+
- **Git version fallbacks**: Check `lib/core.sh:97-100` for example (Git 2.22+ `--show-current` vs older `rev-parse`)
13+
14+
## Key Functions & Responsibilities
15+
16+
- `resolve_base_dir`: config/env/default selection; warn if inside repo & not ignored.
17+
- `resolve_target`: ID `1` + branch/current + sanitized path scan; returns TSV.
18+
- `create_worktree`: decides remote/local/new; respects `--force` + `--name` safety.
19+
- `cfg_default`: precedence local→global→system→env→fallback (do not reorder).
20+
- `cfg_get_all`: merge multi-value keys; preserves order; deduplicates.
21+
22+
## Change Guidelines
23+
24+
- Preserve adapter contracts; do not rename exported functions used by `bin/gtr`.
25+
- Add new config keys with `gtr.<name>` prefix; avoid collisions.
26+
- For performance-sensitive loops (e.g. directory scans) prefer built-ins (`find`, `grep`) with minimal subshells.
27+
- Any new Git command: add fallback for older versions or guard with detection.
28+
- Manual test after changes (subset): `new`, `open`, `ai`, `rm`, `list --porcelain`, `config set/get/unset`, `go 1`, hooks run once.
Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
---
2+
applyTo: **/*.bash, **/*.fish, **/*.sh
3+
---
4+
5+
# Shell Instructions
6+
7+
## Architecture
8+
9+
**Key Pattern**: Everything is sourced at startup (`set -e` enabled). Functions call each other directly. No subshells except for hooks and AI tools.
10+
11+
## Code Conventions
12+
13+
### Shell Script Style
14+
15+
- **Bash 3.2+ compatible** (macOS default), but 4.0+ features allowed where appropriate
16+
- **Always quote variables**: `"$var"` not `$var`
17+
- **Function-scoped vars**: Use `local var="value"`
18+
- **Error handling**: Check return codes; functions return 1 on failure
19+
- **Naming**: `snake_case` for functions/vars, `UPPER_CASE` for constants
20+
21+
### Strict Mode & Safety
22+
23+
- Global `set -e` in `bin/gtr`: guard non-critical commands with `|| true`.
24+
- Prefer `[ ]` over `[[ ]]` for POSIX portability (use `[[` only when needed).
25+
- Always quote glob inputs; disable unintended globbing (`set -f` temporarily if required).
26+
27+
### Portability
28+
29+
- Target Bash 3.2+: avoid associative arrays; use simple string/loop constructs.
30+
- Avoid `readarray` and process substitution unsupported in older Bash.
31+
32+
### Debugging
33+
34+
- Quick trace: `bash -x ./bin/gtr <cmd>`.
35+
- Inline: wrap suspicious block with `set -x` / `set +x`.
36+
- Function presence: `declare -f create_worktree` or `declare -f resolve_target`.
37+
- Variable inspection: `echo "DEBUG var=$var" >&2` (stderr keeps stdout clean for command substitution).
38+
39+
### External Commands
40+
41+
- Keep dependencies minimal: only `git`, `sed`, `awk`, `find`, `grep` (avoid jq/curl unless justified).
42+
- Check availability before use if adding new tools.
43+
44+
### Quoting & Paths
45+
46+
- Use `"${var}"`; for loop over lines: `while IFS= read -r line; do ... done` to preserve spaces.
47+
- Sanitize branch names via `sanitize_branch_name` (do NOT duplicate logic elsewhere).

0 commit comments

Comments
 (0)