Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ predict: A copy of {{.commit}} is added on top of {{.branch}}.
when `ACCESSIBLE=1`.
- **Steps** are git argument lists. Arguments are Go templates over the answers; an argument that
is just `{{.x}}` expands a list answer into several arguments, so values never go through a
shell. A step can have `when`, `ask` (ask a question mid-recipe), `fail` (stop before running),
shell. A `text` answer used that way before `--`, and not as an option's value (`-m`), is
refused if it starts with `-`, because git would read it as an option. A step can have `when`, `ask` (ask a question mid-recipe), `fail` (stop before running),
`warn`, `env`, `todo` (edit a rebase todo list) and `always` (run even after an earlier step
failed, to clean up, such as ending a bisect). `fail` and `warn` are decided before anything
runs, so loading a recipe fails if they use an answer that a later `ask` step collects.
Expand Down
5 changes: 4 additions & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,10 @@ A recipe is one YAML file in `recipes/`. Copy a similar one (`recipes/copy-commi
and follow the model in `internal/recipe/recipe.go`. Rules:

- Pass user answers as **separate arguments** (`git: [cherry-pick, "{{.commit}}"]`), never glued
into a string, and put `--` before file or branch names that could start with a dash.
into a string, and put `--` before file names. A `text` answer passed alone as an argument
before `--` must not start with a dash, or git would read it as an option, so the wizard refuses
one, unless it follows an option that takes a value (`valueFlags` in `internal/recipe`, such as
`-m`). Add an option there if a new recipe passes a typed value after it.
- Write a `predict` line that says what really happens. If a step cannot be undone, say so.
- `go test ./internal/recipe/` loads every recipe, and the end-to-end tests in
`cmd/gitwhy/e2e_test.go` run many of them against a real repository. Add an end-to-end test for
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ No AI, no account, no network: one binary that runs the real `git`.
- **Learn as you go.** Every command it runs is shown and broken down part by part.
- **Undo anything it ran.** Before running, gitwhy saves branches, staged and unstaged changes, untracked files, stashes, and merge/rebase state. `gitwhy undo` puts it all back, even after `reset --hard` or `clean -fdx`.
- **Recover from plain git too.** `gitwhy recover` reads git's history of your branch ("2h ago: pulled 14 commits from origin/master") and takes you back to before any of it. It also finds lost commits and staged files git still has.
- **Every git command and flag.** `gitwhy build` walks you through any command with every flag explained in a few words, from [the docs in this repo](docs/README.md) (181 commands, ~3,500 flags, git 2.56).
- **Every git command and flag.** `gitwhy build` walks you through any command with every flag explained in a few words, from [the docs in this repo](docs/README.md) (181 commands, ~2,700 flags, git 2.56).

## Quickstart

Expand Down
10 changes: 10 additions & 0 deletions cmd/gitwhy/recipes_e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -218,3 +218,13 @@ func TestTagRecipesPushToTheChosenRemote(t *testing.T) {
t.Fatalf("v1.0.0 still on backup:\n%s", out)
}
}

// TestRenameBranchRefusesOptionName proves a typed branch name that starts with "-" is refused
// and asked again. It used to reach git as an option: "git branch -m main --force" ran with
// --force as a flag instead of a name.
func TestRenameBranchRefusesOptionName(t *testing.T) {
r := newRepo(t)
out := r.do("rename-branch", pick("main"), text("--force"), text("feature"), yes)
mustSay(t, out, []string{`"--force" can't start with "-"`}, nil)
expect(t, "branches", r.git("branch", "--format=%(refname:short)"), "feature", out)
}
28 changes: 28 additions & 0 deletions internal/recipe/recipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,9 @@ type Question struct {
Multi bool `yaml:"multi"` // pickers: allow several picks; the answer is a []string
Partial bool `yaml:"partial"` // files: must leave at least one file unpicked
Actions []string `yaml:"actions"` // todo: allowed actions besides reorder (drop, squash, fixup, reword)
// NoLeadingDash is set at load time on a text question that a step passes as a whole
// argument, not as an option's value: git would read an answer like "--force" as an option.
NoLeadingDash bool `yaml:"-"`
}

// Option is one choice of a "choice" question.
Expand Down Expand Up @@ -204,6 +207,7 @@ func Load(fsys fs.FS) ([]*Recipe, error) {
if err := r.validate(); err != nil {
return nil, fmt.Errorf("%s: %w", f, err)
}
r.markLeadingDash()
if seen[r.ID] {
return nil, fmt.Errorf("%s: duplicate recipe id %q", f, r.ID)
}
Expand All @@ -214,6 +218,30 @@ func Load(fsys fs.FS) ([]*Recipe, error) {
return rs, nil
}

// valueFlags are the step options whose next argument is their value (-m, -L, --path, and the
// -c of "switch -c" and "sh -c"), so a typed answer there may start with "-", like a message.
// An option missing here only makes its answer refuse a leading "-", the safe direction.
var valueFlags = map[string]bool{"-m": true, "-L": true, "--path": true, "-c": true}

// markLeadingDash sets NoLeadingDash on each text question that a step passes alone as one
// argument ("{{.x}}") before "--", other than right after an option in valueFlags.
func (r *Recipe) markLeadingDash() {
for _, s := range r.Steps {
for i, el := range s.Git {
if el == "--" {
break
}
m := soloVar.FindStringSubmatch(el)
if m == nil || (i > 0 && valueFlags[s.Git[i-1]]) {
continue
}
if q := r.Question(m[1]); q != nil && q.Type == "text" {
q.NoLeadingDash = true
}
}
}
}

// actionRe and fieldRe find the answers a template uses: each ".name" inside a {{ }} action.
var (
actionRe = regexp.MustCompile(`(?s){{.*?}}`) // an action may span lines
Expand Down
35 changes: 35 additions & 0 deletions internal/recipe/recipe_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -217,3 +217,38 @@ func TestAnswersUsedFindsMultiLineActions(t *testing.T) {
t.Fatalf("got %q", got)
}
}

// TestNoLeadingDash proves which typed answers may not start with "-": those a step passes as a
// whole argument before "--" that is not an option's value. git would read "--force" given as a
// new branch name as an option, while a commit message after -m or a path after "--" is safe.
func TestNoLeadingDash(t *testing.T) {
rs, err := Load(os.DirFS("../.."))
if err != nil {
t.Fatal(err)
}
want := map[string]bool{
"rename-branch/name": true, // branch -m <old> <name>
"move-commits-new-branch/name": true, // branch <name>
"create-tag/name": true, // after the boolean -a
"delete-tag/name": true, // after the boolean -d
"sparse-checkout/dirs": true, // a split answer, splatted
"worktree-add/dir": true, // worktree add <dir>
"add-remote/url": true, // remote add <name> <url>
"commit-staged/message": false, // the value of -m
"new-branch/name": false, // the value of switch -c
"who-changed-line/lines": false, // the value of -L
"find-commit/text": false, // inside "--grep=..."
"rename-file/to": false, // after "--"
}
got := map[string]bool{}
for _, r := range rs {
for _, q := range r.Questions {
got[r.ID+"/"+q.ID] = q.NoLeadingDash
}
}
for k, w := range want {
if g, ok := got[k]; !ok || g != w {
t.Errorf("%s: NoLeadingDash = %v (found %v), want %v", k, g, ok, w)
}
}
}
33 changes: 23 additions & 10 deletions internal/ui/wizard.go
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,27 @@ func (a *App) offer(id string) error {
return a.RunRecipe(s)
}

// checkText reports what is wrong with a typed answer: blank when one is required, or a word
// starting with "-" where git would read it as an option (see recipe.Question.NoLeadingDash).
func checkText(q *recipe.Question, s string) error {
if !q.Optional && strings.TrimSpace(s) == "" {
return fmt.Errorf("required")
}
if !q.NoLeadingDash {
return nil
}
words := []string{strings.TrimSpace(s)}
if q.Split {
words = strings.Fields(s)
}
for _, w := range words {
if strings.HasPrefix(w, "-") {
return fmt.Errorf("%q can't start with \"-\": git would read it as an option", w)
}
}
return nil
}

// ask asks one question and stores the answer (plus derived answers) in ans.
func (a *App) ask(q *recipe.Question, ans recipe.Answers) error {
// A question whose "when" is false is answered with "" so templates that use it still render.
Expand Down Expand Up @@ -179,16 +200,8 @@ func (a *App) ask(q *recipe.Question, ans recipe.Answers) error {
ans[q.ID] = strconv.FormatBool(v)
case "text":
v := def
in := huh.NewInput().Title(title).Description(q.Help).Value(&v)
if !q.Optional {
in = in.Validate(func(s string) error {
if strings.TrimSpace(s) == "" {
return fmt.Errorf("required")
}
return nil
})
}
err = prompt(in)
err = prompt(huh.NewInput().Title(title).Description(q.Help).Value(&v).
Validate(func(s string) error { return checkText(q, s) }))
if q.Split {
ans[q.ID] = strings.Fields(v)
} else {
Expand Down
30 changes: 30 additions & 0 deletions internal/ui/wizard_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,3 +102,33 @@ func TestRunRecipeWithRejectsAPresetOfTheWrongType(t *testing.T) {
t.Fatal("want an error for a non-text commit preset")
}
}

// TestCheckText proves the checks on a typed answer: a required answer can't be blank, and an
// answer git would read as an option ("--force" as a branch name) is refused, word by word for a
// split answer, while one used as an option's value, such as a commit message, may start with "-".
func TestCheckText(t *testing.T) {
positional := &recipe.Question{Type: "text", NoLeadingDash: true}
split := &recipe.Question{Type: "text", NoLeadingDash: true, Split: true}
message := &recipe.Question{Type: "text"}
optional := &recipe.Question{Type: "text", Optional: true, NoLeadingDash: true}
for _, c := range []struct {
q *recipe.Question
in string
fail bool
}{
{positional, "feature", false},
{positional, "--force", true},
{positional, " -d", true},
{positional, "a-b", false},
{split, "src docs", false},
{split, "src -x", true},
{message, "-fix the typo", false},
{message, " ", true},
{optional, "", false},
{optional, "-x", true},
} {
if err := checkText(c.q, c.in); (err != nil) != c.fail {
t.Errorf("checkText(%+v, %q) = %v, want fail %v", *c.q, c.in, err, c.fail)
}
}
}
Loading