From 1b9d9c10ce2239a649efa4d254ef88dfdc945b4a Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 19:07:27 +0800 Subject: [PATCH 01/15] test: reproduce the GitBash selection failure on Windows (#98) Git Bash in mintty gives native programs a pipe, not a console. Two Windows tests pin the failure: IsTTY does not recognize a mintty pty (an msys-named pipe), and selectFromOptions never reads the choice typed into a pipe because the key reader cannot read from one. --- cmd/commands/select_windows_test.go | 63 ++++++++++++++++++++ internal/shared/util/tty_windows_test.go | 73 ++++++++++++++++++++++++ 2 files changed, 136 insertions(+) create mode 100644 cmd/commands/select_windows_test.go create mode 100644 internal/shared/util/tty_windows_test.go diff --git a/cmd/commands/select_windows_test.go b/cmd/commands/select_windows_test.go new file mode 100644 index 00000000..75c831c8 --- /dev/null +++ b/cmd/commands/select_windows_test.go @@ -0,0 +1,63 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "os" + "testing" + "time" +) + +// Git Bash in mintty gives vfox a pipe for stdin, not a console. The key reader +// cannot read from such a pipe, so the choice typed into it must still be read. +func TestSelectFromOptionsReadsChoiceFromPipe(t *testing.T) { + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + reader.Close() + writer.Close() + }) + if _, err := writer.WriteString("2\r\n"); err != nil { + t.Fatal(err) + } + previous := os.Stdin + os.Stdin = reader + t.Cleanup(func() { os.Stdin = previous }) + + type outcome struct { + version string + err error + } + done := make(chan outcome, 1) + go func() { + version, err := selectFromOptions([]string{"18.20.8", "20.19.0"}, "nodejs") + done <- outcome{version, err} + }() + select { + case got := <-done: + if got.err != nil { + t.Fatalf("selectFromOptions() error: %v", got.err) + } + if got.version != "20.19.0" { + t.Errorf("selectFromOptions() = %q, want %q", got.version, "20.19.0") + } + case <-time.After(15 * time.Second): + t.Fatal("selectFromOptions() did not return: the key reader never reads from a pipe") + } +} diff --git a/internal/shared/util/tty_windows_test.go b/internal/shared/util/tty_windows_test.go new file mode 100644 index 00000000..f22cf5da --- /dev/null +++ b/internal/shared/util/tty_windows_test.go @@ -0,0 +1,73 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package util + +import ( + "os" + "testing" + + "golang.org/x/sys/windows" +) + +// createNamedPipe returns the server end of a named pipe called name. The name +// is what tells a pty apart from an ordinary pipe. +func createNamedPipe(t *testing.T, name string) *os.File { + t.Helper() + path, err := windows.UTF16PtrFromString(`\\.\pipe\` + name) + if err != nil { + t.Fatal(err) + } + handle, err := windows.CreateNamedPipe(path, windows.PIPE_ACCESS_DUPLEX, windows.PIPE_TYPE_BYTE, 1, 4096, 4096, 0, nil) + if err != nil { + t.Fatalf("CreateNamedPipe(%s): %v", name, err) + } + file := os.NewFile(uintptr(handle), name) + t.Cleanup(func() { file.Close() }) + return file +} + +// replaceStdout points os.Stdout at file until the test ends. +func replaceStdout(t *testing.T, file *os.File) { + t.Helper() + previous := os.Stdout + os.Stdout = file + t.Cleanup(func() { os.Stdout = previous }) +} + +// Git Bash in mintty gives native programs a pipe named \msys--pty-to-master +// instead of a console. The person at mintty is at a terminal, so IsTTY must say so. +func TestIsTTYRecognizesMinttyPty(t *testing.T) { + replaceStdout(t, createNamedPipe(t, "msys-1888ae32e00d56aa-pty0-to-master")) + if !IsTTY() { + t.Error("IsTTY() = false for a mintty pty, want true") + } +} + +func TestIsTTYRejectsOrdinaryPipe(t *testing.T) { + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + reader.Close() + writer.Close() + }) + replaceStdout(t, writer) + if IsTTY() { + t.Error("IsTTY() = true for an ordinary pipe, want false") + } +} From a392bf2007b7949e0b65b950c29059f2ac86ce6f Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 19:22:28 +0800 Subject: [PATCH 02/15] fix: select and confirm by line in GitBash mintty (#98) Git Bash in mintty gives vfox a pty that reaches it as a pipe. IsTTY therefore said no, so use, search and the prompts were skipped as non-interactive. Where the prompts did run, the key reader (atomicgo.dev/keyboard) cannot read a Windows pipe and spins on it. - IsTTY also accepts a Cygwin or MSYS2 pty, recognized by its pipe name the way go-isatty does. - CanReadKeys reports whether stdin is a console on Windows. Off Windows it stays true, as the key reader falls back to /dev/tty. - Without key input, use and search pick a version with printer.LineSelect (a number, a version, or text to filter), and the y/n prompts go through printer.Confirm, which reads a line. Consoles keep the arrow-key selection and single-key prompts. - The FAQ describes how native GitBash behaves now. --- cmd/commands/install.go | 8 +- cmd/commands/link.go | 6 +- cmd/commands/remove.go | 6 +- cmd/commands/search.go | 16 ++ cmd/commands/use.go | 29 ++++ cmd/commands/use_line_select_test.go | 45 ++++++ docs/guides/faq.md | 2 +- docs/zh-hans/guides/faq.md | 2 +- internal/manager.go | 6 +- internal/shared/printer/confirm.go | 87 +++++++++++ internal/shared/printer/confirm_test.go | 94 +++++++++++ internal/shared/printer/select_line.go | 143 +++++++++++++++++ internal/shared/printer/select_line_test.go | 164 ++++++++++++++++++++ internal/shared/util/tty.go | 13 +- internal/shared/util/tty_notwindows.go | 28 ++++ internal/shared/util/tty_windows.go | 82 ++++++++++ internal/shared/util/tty_windows_test.go | 38 +++++ 17 files changed, 752 insertions(+), 17 deletions(-) create mode 100644 cmd/commands/use_line_select_test.go create mode 100644 internal/shared/printer/confirm.go create mode 100644 internal/shared/printer/confirm_test.go create mode 100644 internal/shared/printer/select_line.go create mode 100644 internal/shared/printer/select_line_test.go create mode 100644 internal/shared/util/tty_notwindows.go create mode 100644 internal/shared/util/tty_windows.go diff --git a/cmd/commands/install.go b/cmd/commands/install.go index 0ac2e92b..fd4831ed 100644 --- a/cmd/commands/install.go +++ b/cmd/commands/install.go @@ -29,6 +29,7 @@ import ( "github.com/version-fox/vfox/internal/env" "github.com/version-fox/vfox/internal/sdk" "github.com/version-fox/vfox/internal/shared/logger" + "github.com/version-fox/vfox/internal/shared/printer" "github.com/version-fox/vfox/internal/shared/util" ) @@ -156,7 +157,7 @@ func installCmd(ctx context.Context, cmd *cli.Command) error { if util.IsNonInteractiveTerminal() { return cli.Exit(fmt.Sprintf("install requires specifying a version for %s", name), 1) } - showAvailable, _ := pterm.DefaultInteractiveConfirm.Show(fmt.Sprintf("No %s version provided, do you want to select a version to install?", pterm.Red(name))) + showAvailable, _ := printer.Confirm(&pterm.DefaultInteractiveConfirm, fmt.Sprintf("No %s version provided, do you want to select a version to install?", pterm.Red(name))) if showAvailable { err := RunSearch(name, []string{}) if err != nil { @@ -218,9 +219,8 @@ func installAll(autoConfirm bool) error { if util.IsNonInteractiveTerminal() { return cli.Exit("Use the -y flag to automatically confirm installation in non-interactive environments", 1) } - result, _ := pterm.DefaultInteractiveConfirm. - WithDefaultValue(true). - Show("Do you want to install these plugins and SDKs?") + result, _ := printer.Confirm(pterm.DefaultInteractiveConfirm. + WithDefaultValue(true), "Do you want to install these plugins and SDKs?") if !result { return nil } diff --git a/cmd/commands/link.go b/cmd/commands/link.go index 105cdfea..b9672a9d 100644 --- a/cmd/commands/link.go +++ b/cmd/commands/link.go @@ -28,6 +28,7 @@ import ( "github.com/version-fox/vfox/internal" "github.com/version-fox/vfox/internal/sdk" + "github.com/version-fox/vfox/internal/shared/printer" "github.com/version-fox/vfox/internal/shared/util" ) @@ -134,9 +135,8 @@ func linkDetected(cmd *cli.Command) error { if util.IsNonInteractiveTerminal() { return cli.Exit("Use the -y flag to link what was found in non-interactive environments", 1) } - confirmed, _ := pterm.DefaultInteractiveConfirm. - WithDefaultValue(true). - Show(fmt.Sprintf("Link %d %s installation(s)?", len(candidates), name)) + confirmed, _ := printer.Confirm(pterm.DefaultInteractiveConfirm. + WithDefaultValue(true), fmt.Sprintf("Link %d %s installation(s)?", len(candidates), name)) if !confirmed { return nil } diff --git a/cmd/commands/remove.go b/cmd/commands/remove.go index 66fd1be2..37569993 100644 --- a/cmd/commands/remove.go +++ b/cmd/commands/remove.go @@ -22,6 +22,7 @@ import ( "github.com/pterm/pterm" "github.com/urfave/cli/v3" "github.com/version-fox/vfox/internal" + "github.com/version-fox/vfox/internal/shared/printer" "github.com/version-fox/vfox/internal/shared/util" ) @@ -58,12 +59,11 @@ func removeCmd(ctx context.Context, cmd *cli.Command) error { if util.IsNonInteractiveTerminal() { return cli.Exit("Use the -y flag to skip confirmation in non-interactive environments", 1) } - result, _ := pterm.DefaultInteractiveConfirm. + result, _ := printer.Confirm(pterm.DefaultInteractiveConfirm. WithTextStyle(&pterm.ThemeDefault.DefaultText). WithConfirmStyle(&pterm.ThemeDefault.DefaultText). WithRejectStyle(&pterm.ThemeDefault.DefaultText). - WithDefaultText("Please confirm"). - Show() + WithDefaultText("Please confirm"), "") if !result { return cli.Exit("remove canceled", 1) } diff --git a/cmd/commands/search.go b/cmd/commands/search.go index 89da1131..1e6e7246 100644 --- a/cmd/commands/search.go +++ b/cmd/commands/search.go @@ -94,6 +94,22 @@ func RunSearch(sdkName string, availableArgs []string) error { return nil } + if !util.CanReadKeys() { + selected, err := (&printer.LineSelect{ + TopText: "Please select a version of " + sdkName + " to install", + Options: options, + DisabledOptions: installedVersions, + In: os.Stdin, + Out: os.Stdout, + }).Show() + if err != nil { + return fmt.Errorf("select version error: %w", err) + } + if selected == nil { + return nil + } + return source.Install(sdk.Version(selected.Key)) + } _, height, _ := terminal.GetSize(int(os.Stdout.Fd())) kvSelect := printer.PageKVSelect{ TopText: "Please select a version of " + sdkName + " to install", diff --git a/cmd/commands/use.go b/cmd/commands/use.go index 8915abdf..34c309fe 100644 --- a/cmd/commands/use.go +++ b/cmd/commands/use.go @@ -19,6 +19,7 @@ package commands import ( "context" "fmt" + "io" "os" "strings" @@ -29,6 +30,7 @@ import ( "github.com/pterm/pterm" "github.com/version-fox/vfox/internal" "github.com/version-fox/vfox/internal/shared/logger" + "github.com/version-fox/vfox/internal/shared/printer" "github.com/urfave/cli/v3" ) @@ -177,6 +179,9 @@ func resolveVersion(sdkSource sdk.Sdk, manager *internal.Manager, version sdk.Ve // selectFromOptions displays an interactive selection prompt func selectFromOptions(options []string, sdkName string) (string, error) { + if !util.CanReadKeys() { + return selectVersionByLine(os.Stdin, os.Stdout, options, sdkName) + } selectPrinter := pterm.InteractiveSelectPrinter{ TextStyle: &pterm.ThemeDefault.DefaultText, OptionStyle: &pterm.ThemeDefault.DefaultText, @@ -199,3 +204,27 @@ func selectFromOptions(options []string, sdkName string) (string, error) { logger.Debugf("Selected version: %s for SDK: %s\n", result, sdkName) return result, nil } + +// selectVersionByLine chooses a version by reading lines, for a terminal that +// cannot deliver single key presses (Git Bash in mintty). A cancelled selection +// is an error, since there is then no version to use. +func selectVersionByLine(in io.Reader, out io.Writer, options []string, sdkName string) (string, error) { + entries := make([]*printer.KV, len(options)) + for i, option := range options { + entries[i] = &printer.KV{Key: option, Value: option} + } + selected, err := (&printer.LineSelect{ + TopText: fmt.Sprintf("Please select a version of %s", sdkName), + Options: entries, + In: in, + Out: out, + }).Show() + if err != nil { + return "", fmt.Errorf("version selection failed: %w", err) + } + if selected == nil { + return "", cli.Exit(fmt.Sprintf("No version of %s selected", sdkName), 1) + } + logger.Debugf("Selected version: %s for SDK: %s\n", selected.Key, sdkName) + return selected.Key, nil +} diff --git a/cmd/commands/use_line_select_test.go b/cmd/commands/use_line_select_test.go new file mode 100644 index 00000000..5ccf9048 --- /dev/null +++ b/cmd/commands/use_line_select_test.go @@ -0,0 +1,45 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "bytes" + "strings" + "testing" +) + +func TestSelectVersionByLine(t *testing.T) { + var out bytes.Buffer + version, err := selectVersionByLine(strings.NewReader("2\r\n"), &out, []string{"18.20.8", "20.19.0"}, "nodejs") + if err != nil { + t.Fatalf("selectVersionByLine() error: %v", err) + } + if version != "20.19.0" { + t.Errorf("selectVersionByLine() = %q, want %q", version, "20.19.0") + } + if !strings.Contains(out.String(), "Please select a version of nodejs") { + t.Errorf("prompt does not name the SDK:\n%s", out.String()) + } +} + +func TestSelectVersionByLineCancelIsAnError(t *testing.T) { + var out bytes.Buffer + version, err := selectVersionByLine(strings.NewReader("\n"), &out, []string{"18.20.8"}, "nodejs") + if err == nil { + t.Fatalf("selectVersionByLine() = %q, want an error for a cancelled selection", version) + } +} diff --git a/docs/guides/faq.md b/docs/guides/faq.md index 848e07cf..4ca4d835 100644 --- a/docs/guides/faq.md +++ b/docs/guides/faq.md @@ -59,6 +59,6 @@ with `vfox` instead. Related ISSUE: [Unable to select in GitBash](https://github.com/version-fox/vfox/issues/98) -The problem of not being able to select in GitBash only occurs when you directly open the native GitBash to run `vfox`. A temporary solution is: +In the native GitBash (MinTTY), vfox cannot read single key presses, so `use`, `search` and the other prompts read a line instead: type a number from the list or a version and press Enter. Typing text narrows the list, and an empty line cancels. For arrow-key selection, run GitBash in one of these: 1. Run `GitBash` through `Windows Terminal` 2. Run `GitBash` in `VS Code` diff --git a/docs/zh-hans/guides/faq.md b/docs/zh-hans/guides/faq.md index aafbd3e8..8c5908a8 100644 --- a/docs/zh-hans/guides/faq.md +++ b/docs/zh-hans/guides/faq.md @@ -52,6 +52,6 @@ vfox use java@17-system 相关ISSUE: [GitBash下无法进行选择](https://github.com/version-fox/vfox/issues/98) -仅限直接打开原生GitBash运行`vfox`会出现无法进行选择的问题, 临时解决办法: +原生GitBash(MinTTY)无法读取单个按键, 因此`use`、`search`等命令改为按行读取输入: 输入列表中的序号或版本号后回车即可, 输入文字可以过滤列表, 空行则取消。如需使用方向键选择, 可以: 1. 通过`Windows Terminal`运行`GitBash` 2. 在`VS Code`中运行`GitBash` diff --git a/internal/manager.go b/internal/manager.go index e664559b..6f48c23c 100644 --- a/internal/manager.go +++ b/internal/manager.go @@ -41,6 +41,7 @@ import ( "github.com/version-fox/vfox/internal/plugin" "github.com/version-fox/vfox/internal/sdk" "github.com/version-fox/vfox/internal/shared/logger" + "github.com/version-fox/vfox/internal/shared/printer" "github.com/version-fox/vfox/internal/shared/util" ) @@ -145,12 +146,11 @@ func (m *Manager) LookupSdkWithInstall(name string, autoConfirm bool) (sdk.Sdk, return nil, cli.Exit(fmt.Sprintf("Plugin %s is not installed. Use the -y flag to automatically install plugins in non-interactive environments", name), 1) } else { fmt.Printf("[%s] not added yet, confirm that you want to use [%s]? \n", pterm.LightBlue(name), pterm.LightRed(name)) - result, _ := pterm.DefaultInteractiveConfirm. + result, _ := printer.Confirm(pterm.DefaultInteractiveConfirm. WithTextStyle(&pterm.ThemeDefault.DefaultText). WithConfirmStyle(&pterm.ThemeDefault.DefaultText). WithRejectStyle(&pterm.ThemeDefault.DefaultText). - WithDefaultText("Please confirm"). - Show() + WithDefaultText("Please confirm"), "") if !result { return nil, cli.Exit(fmt.Sprintf("Plugin %s is not installed. Installation cancelled by user", name), 1) } diff --git a/internal/shared/printer/confirm.go b/internal/shared/printer/confirm.go new file mode 100644 index 00000000..093b7a4e --- /dev/null +++ b/internal/shared/printer/confirm.go @@ -0,0 +1,87 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" + + "github.com/pterm/pterm" + "github.com/version-fox/vfox/internal/shared/util" +) + +// Confirm asks a yes-or-no question with p. Where key presses can be read it +// behaves as p.Show; elsewhere the answer is a line (see util.CanReadKeys). +func Confirm(p *pterm.InteractiveConfirmPrinter, text string) (bool, error) { + if util.CanReadKeys() { + return p.Show(text) + } + return lineConfirm(os.Stdin, os.Stdout, *p, text) +} + +// lineConfirm asks text and reads an answer line. The confirm or reject text, or +// its first letter, settles it; an empty line gives the default; an input that +// ends gives no. +func lineConfirm(in io.Reader, out io.Writer, p pterm.InteractiveConfirmPrinter, text string) (bool, error) { + if text == "" { + text = p.DefaultText + } + yes, no := shortAnswer(p.ConfirmText, "y"), shortAnswer(p.RejectText, "n") + shownYes, shownNo := yes, no + if p.DefaultValue { + shownYes = strings.ToUpper(yes) + } else { + shownNo = strings.ToUpper(no) + } + + input := bufio.NewReader(in) + for { + fmt.Fprintf(out, "%s [%s/%s]%s", text, shownYes, shownNo, p.Delimiter) + line, readErr := input.ReadString('\n') + if readErr != nil && readErr != io.EOF { + return false, fmt.Errorf("read answer: %w", readErr) + } + answer := strings.ToLower(strings.TrimSpace(line)) + switch answer { + case "": + if readErr == io.EOF { + fmt.Fprintln(out) + return false, nil + } + return p.DefaultValue, nil + case yes, strings.ToLower(p.ConfirmText): + return true, nil + case no, strings.ToLower(p.RejectText): + return false, nil + } + if readErr == io.EOF { + return false, nil + } + } +} + +// shortAnswer returns the lower-case first letter of text, or fallback when text is empty. +func shortAnswer(text, fallback string) string { + runes := []rune(strings.ToLower(text)) + if len(runes) == 0 { + return fallback + } + return string(runes[0]) +} diff --git a/internal/shared/printer/confirm_test.go b/internal/shared/printer/confirm_test.go new file mode 100644 index 00000000..95ecd3d9 --- /dev/null +++ b/internal/shared/printer/confirm_test.go @@ -0,0 +1,94 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bytes" + "strings" + "testing" + + "github.com/pterm/pterm" +) + +func TestLineConfirmAnswers(t *testing.T) { + cases := []struct { + name string + input string + defaultValue bool + want bool + }{ + {"y", "y\n", false, true}, + {"yes word", "Yes\n", false, true}, + {"n", "n\n", true, false}, + {"no word", "NO\n", true, false}, + {"enter takes default yes", "\n", true, true}, + {"enter takes default no", "\n", false, false}, + {"invalid answer asks again", "maybe\ny\n", false, true}, + {"end of input is no", "", true, false}, + {"invalid answer then end of input is no", "maybe", true, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{ + DefaultValue: tc.defaultValue, + DefaultText: "Please confirm", + ConfirmText: "Yes", + RejectText: "No", + Delimiter: ": ", + } + var out bytes.Buffer + got, err := lineConfirm(strings.NewReader(tc.input), &out, p, "Install nodejs?") + if err != nil { + t.Fatalf("lineConfirm() error: %v", err) + } + if got != tc.want { + t.Errorf("lineConfirm() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestLineConfirmShowsDefaultInUpperCase(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + if _, err := lineConfirm(strings.NewReader("\n"), &out, p, "Install nodejs?"); err != nil { + t.Fatal(err) + } + if want := "Install nodejs? [y/N]: "; out.String() != want { + t.Errorf("prompt = %q, want %q", out.String(), want) + } + + p.DefaultValue = true + out.Reset() + if _, err := lineConfirm(strings.NewReader("\n"), &out, p, "Install nodejs?"); err != nil { + t.Fatal(err) + } + if want := "Install nodejs? [Y/n]: "; out.String() != want { + t.Errorf("prompt = %q, want %q", out.String(), want) + } +} + +func TestLineConfirmUsesDefaultTextWhenNoQuestion(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{DefaultText: "Please confirm", ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + if _, err := lineConfirm(strings.NewReader("y\n"), &out, p, ""); err != nil { + t.Fatal(err) + } + if !strings.HasPrefix(out.String(), "Please confirm ") { + t.Errorf("prompt = %q, want the default text", out.String()) + } +} diff --git a/internal/shared/printer/select_line.go b/internal/shared/printer/select_line.go new file mode 100644 index 00000000..d9ebc4e1 --- /dev/null +++ b/internal/shared/printer/select_line.go @@ -0,0 +1,143 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bufio" + "fmt" + "io" + "strconv" + "strings" + + "github.com/lithammer/fuzzysearch/fuzzy" + "github.com/version-fox/vfox/internal/shared/util" +) + +// lineSelectLimit is how many matches LineSelect lists at a time. +const lineSelectLimit = 20 + +// LineSelect chooses one of Options by reading lines. It serves terminals that +// cannot deliver single key presses (see util.CanReadKeys), such as Git Bash in +// mintty. +type LineSelect struct { + TopText string + Options []*KV + // DisabledOptions are listed as installed and cannot be chosen. It may be nil. + DisabledOptions util.Set[string] + In io.Reader + Out io.Writer +} + +// Show lists the options and reads lines until one is chosen. A number chooses +// the entry at that position in the list, the key of an option chooses that +// option, and other text filters the list. An empty line clears the filter, or +// cancels when there is none. Show returns nil when the selection is cancelled +// or the input ends. +func (s *LineSelect) Show() (*KV, error) { + input := bufio.NewReader(s.In) + filter := "" + for { + matches := s.matches(filter) + listed := matches + if len(listed) > lineSelectLimit { + listed = listed[:lineSelectLimit] + } + s.render(filter, matches, listed) + + line, readErr := input.ReadString('\n') + if readErr != nil && readErr != io.EOF { + return nil, fmt.Errorf("read selection: %w", readErr) + } + line = strings.TrimSpace(line) + if line == "" { + if readErr == io.EOF || filter == "" { + fmt.Fprintln(s.Out) + return nil, nil + } + filter = "" + continue + } + + chosen := s.choose(line, listed) + if chosen == nil { + filter = line + continue + } + if s.isDisabled(chosen.Key) { + fmt.Fprintf(s.Out, "%s is already installed, choose another version.\n", chosen.Key) + continue + } + return chosen, nil + } +} + +// matches returns the options whose value fuzzily contains filter, in the order +// the plugin gave them. An empty filter matches every option. +func (s *LineSelect) matches(filter string) []*KV { + var found []*KV + for _, option := range s.Options { + if fuzzy.MatchFold(filter, option.Value) { + found = append(found, option) + } + } + return found +} + +// choose returns the option that line picks, or nil when line is a filter. A +// number picks from the listed entries; a key picks from all options. +func (s *LineSelect) choose(line string, listed []*KV) *KV { + if n, err := strconv.Atoi(line); err == nil && n >= 1 && n <= len(listed) { + return listed[n-1] + } + for _, option := range s.Options { + if option.Key == line { + return option + } + } + return nil +} + +func (s *LineSelect) isDisabled(key string) bool { + return s.DisabledOptions != nil && s.DisabledOptions.Contains(key) +} + +// render writes the title, the listed matches numbered, and the prompt. +func (s *LineSelect) render(filter string, matches, listed []*KV) { + if filter == "" { + fmt.Fprintf(s.Out, "%s:\n", s.TopText) + } else { + fmt.Fprintf(s.Out, "%s [filter: %s]:\n", s.TopText, filter) + } + if len(matches) == 0 { + fmt.Fprintln(s.Out, " No version matches the filter.") + } + for i, option := range listed { + label := option.Value + if s.isDisabled(option.Key) { + label += " (installed)" + } + fmt.Fprintf(s.Out, " %d) %s\n", i+1, label) + } + if more := len(matches) - len(listed); more > 0 { + fmt.Fprintf(s.Out, " ... %d more, type part of a version to narrow the list\n", more) + } + action := "cancel" + if filter != "" { + action = "clear the filter" + } + fmt.Fprintf(s.Out, "Type a number or a version to choose it, or text to filter the list (Enter to %s): ", action) +} diff --git a/internal/shared/printer/select_line_test.go b/internal/shared/printer/select_line_test.go new file mode 100644 index 00000000..38290a17 --- /dev/null +++ b/internal/shared/printer/select_line_test.go @@ -0,0 +1,164 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "github.com/version-fox/vfox/internal/shared/util" +) + +func lineSelectOptions() []*KV { + return []*KV{ + {Key: "24.1.0", Value: "24.1.0 (Current)"}, + {Key: "22.15.0", Value: "22.15.0 (LTS Jod)"}, + {Key: "20.19.0", Value: "20.19.0 (LTS Iron)"}, + {Key: "18.20.8", Value: "18.20.8 (LTS Hydrogen)"}, + } +} + +// runLineSelect shows a LineSelect fed with input and returns its choice and output. +func runLineSelect(t *testing.T, input string, options []*KV, disabled util.Set[string]) (*KV, string, error) { + t.Helper() + var out bytes.Buffer + s := &LineSelect{ + TopText: "Please select a version of nodejs", + Options: options, + DisabledOptions: disabled, + In: strings.NewReader(input), + Out: &out, + } + chosen, err := s.Show() + return chosen, out.String(), err +} + +func assertChosen(t *testing.T, chosen *KV, err error, wantKey string) { + t.Helper() + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if chosen == nil { + t.Fatalf("Show() = nil, want %q", wantKey) + } + if chosen.Key != wantKey { + t.Errorf("Show() chose %q, want %q", chosen.Key, wantKey) + } +} + +func TestLineSelectChoosesByNumber(t *testing.T) { + chosen, _, err := runLineSelect(t, "2\n", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "22.15.0") +} + +func TestLineSelectAcceptsCarriageReturnLineEnding(t *testing.T) { + chosen, _, err := runLineSelect(t, "3\r\n", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "20.19.0") +} + +func TestLineSelectChoosesByKey(t *testing.T) { + chosen, _, err := runLineSelect(t, "18.20.8\n", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "18.20.8") +} + +func TestLineSelectNumberWithoutNewlineAtEndOfInput(t *testing.T) { + chosen, _, err := runLineSelect(t, "2", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "22.15.0") +} + +func TestLineSelectFilterThenNumberChoosesFromFilteredList(t *testing.T) { + // "lts" leaves three matches, so 2 is 20.19.0 in the filtered list. + chosen, out, err := runLineSelect(t, "lts\n2\n", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "20.19.0") + filtered := " 1) 22.15.0 (LTS Jod)\n 2) 20.19.0 (LTS Iron)\n 3) 18.20.8 (LTS Hydrogen)\n" + if !strings.Contains(out, "[filter: lts]") || !strings.Contains(out, filtered) { + t.Errorf("filter lts did not list the three LTS versions:\n%s", out) + } +} + +func TestLineSelectEmptyLineClearsFilterThenCancels(t *testing.T) { + chosen, out, err := runLineSelect(t, "lts\n\n\n", lineSelectOptions(), nil) + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if chosen != nil { + t.Errorf("Show() chose %q, want cancel", chosen.Key) + } + // The full list is drawn at the start and again after the filter is cleared. + if got := strings.Count(out, "24.1.0 (Current)"); got != 2 { + t.Errorf("full list drawn %d times, want 2:\n%s", got, out) + } +} + +func TestLineSelectCancelsOnEndOfInput(t *testing.T) { + chosen, _, err := runLineSelect(t, "", lineSelectOptions(), nil) + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if chosen != nil { + t.Errorf("Show() chose %q at end of input, want nil", chosen.Key) + } +} + +func TestLineSelectRefusesDisabledOption(t *testing.T) { + disabled := util.NewSet[string]() + disabled.Add("22.15.0") + chosen, out, err := runLineSelect(t, "2\n3\n", lineSelectOptions(), disabled) + assertChosen(t, chosen, err, "20.19.0") + if !strings.Contains(out, "22.15.0 is already installed") { + t.Errorf("output does not refuse the installed version:\n%s", out) + } + if !strings.Contains(out, "22.15.0 (LTS Jod) (installed)") { + t.Errorf("output does not mark the installed version:\n%s", out) + } +} + +func TestLineSelectReportsEmptyFilter(t *testing.T) { + chosen, out, err := runLineSelect(t, "zz\n", lineSelectOptions(), nil) + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if chosen != nil { + t.Errorf("Show() chose %q, want cancel", chosen.Key) + } + if !strings.Contains(out, "No version matches the filter.") { + t.Errorf("output does not report the empty filter:\n%s", out) + } +} + +func TestLineSelectListsAtMostLimitAndSaysHowMany(t *testing.T) { + var options []*KV + for i := 0; i < lineSelectLimit+5; i++ { + version := fmt.Sprintf("1.%d.0", i) + options = append(options, &KV{Key: version, Value: version}) + } + chosen, out, err := runLineSelect(t, "\n", options, nil) + if err != nil || chosen != nil { + t.Fatalf("Show() = %v, %v, want cancel", chosen, err) + } + if !strings.Contains(out, fmt.Sprintf(" %d) 1.%d.0\n", lineSelectLimit, lineSelectLimit-1)) { + t.Errorf("last listed entry missing:\n%s", out) + } + if strings.Contains(out, fmt.Sprintf(" %d) ", lineSelectLimit+1)) { + t.Errorf("more than %d entries listed:\n%s", lineSelectLimit, out) + } + if !strings.Contains(out, "... 5 more") { + t.Errorf("output does not say how many are left:\n%s", out) + } +} diff --git a/internal/shared/util/tty.go b/internal/shared/util/tty.go index 8d74beb0..a0f8703a 100644 --- a/internal/shared/util/tty.go +++ b/internal/shared/util/tty.go @@ -22,7 +22,16 @@ import ( "golang.org/x/term" ) -// IsTTY checks if the process is running in a TTY (interactive terminal) +// IsTTY checks if the process is running in a TTY (interactive terminal). On +// Windows, Git Bash in mintty counts as one: its pty reaches native programs as +// a pipe, which isCygwinTerminal recognizes. func IsTTY() bool { - return term.IsTerminal(int(os.Stdout.Fd())) + return term.IsTerminal(int(os.Stdout.Fd())) || isCygwinTerminal(os.Stdout.Fd()) +} + +// CanReadKeys reports whether single key presses can be read from stdin, as +// arrow-key selection and y/n prompts need. On Windows the key reader needs a +// console, so a stdin that is a pipe (Git Bash in mintty) gets line input instead. +func CanReadKeys() bool { + return canReadKeysFrom(os.Stdin.Fd()) } diff --git a/internal/shared/util/tty_notwindows.go b/internal/shared/util/tty_notwindows.go new file mode 100644 index 00000000..d3c08415 --- /dev/null +++ b/internal/shared/util/tty_notwindows.go @@ -0,0 +1,28 @@ +//go:build !windows + +// Copyright 2026 vfox project contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package util + +// canReadKeysFrom reports true: off Windows the key reader reads /dev/tty, so a +// redirected stdin does not stop it. +func canReadKeysFrom(uintptr) bool { + return true +} + +// isCygwinTerminal reports false: only Windows runs Cygwin and MSYS2 ptys as pipes. +func isCygwinTerminal(uintptr) bool { + return false +} diff --git a/internal/shared/util/tty_windows.go b/internal/shared/util/tty_windows.go new file mode 100644 index 00000000..2a6794c9 --- /dev/null +++ b/internal/shared/util/tty_windows.go @@ -0,0 +1,82 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package util + +import ( + "encoding/binary" + "strings" + "unicode/utf16" + + "golang.org/x/sys/windows" +) + +// maxPathUnits is the length of a file name buffer in UTF-16 units, MAX_PATH. +const maxPathUnits = 260 + +// canReadKeysFrom reports whether the key reader can read fd, which needs a console. +func canReadKeysFrom(fd uintptr) bool { + var mode uint32 + return windows.GetConsoleMode(windows.Handle(fd), &mode) == nil +} + +// isCygwinTerminal reports whether fd is a pty of Cygwin or MSYS2, such as the +// one Git Bash in mintty runs in. Native programs get that pty as a named pipe +// called \msys--pty-to-master (or -from-master), not as a console. +func isCygwinTerminal(fd uintptr) bool { + handle := windows.Handle(fd) + if fileType, err := windows.GetFileType(handle); err != nil || fileType != windows.FILE_TYPE_PIPE { + return false + } + name, err := pipeName(handle) + return err == nil && isCygwinPipeName(name) +} + +// pipeName returns the name of a pipe handle as FileNameInfo reports it: a byte +// count, then the name in UTF-16. +func pipeName(handle windows.Handle) (string, error) { + buf := make([]byte, 4+2*maxPathUnits) + if err := windows.GetFileInformationByHandleEx(handle, windows.FileNameInfo, &buf[0], uint32(len(buf))); err != nil { + return "", err + } + size := int(binary.LittleEndian.Uint32(buf[:4])) + if size > len(buf)-4 { + size = len(buf) - 4 + } + units := make([]uint16, size/2) + for i := range units { + units[i] = binary.LittleEndian.Uint16(buf[4+2*i:]) + } + return string(utf16.Decode(units)), nil +} + +// isCygwinPipeName matches the names of Cygwin and MSYS2 ptys, the way go-isatty +// does: \msys--pty-(from|to)-master, or the same with cygwin for msys. +func isCygwinPipeName(name string) bool { + token := strings.Split(name, "-") + if len(token) < 5 { + return false + } + switch token[0] { + case `\msys`, `\cygwin`, `\Device\NamedPipe\msys`, `\Device\NamedPipe\cygwin`: + default: + return false + } + return token[1] != "" && + strings.HasPrefix(token[2], "pty") && + (token[3] == "from" || token[3] == "to") && + token[4] == "master" +} diff --git a/internal/shared/util/tty_windows_test.go b/internal/shared/util/tty_windows_test.go index f22cf5da..848cccae 100644 --- a/internal/shared/util/tty_windows_test.go +++ b/internal/shared/util/tty_windows_test.go @@ -71,3 +71,41 @@ func TestIsTTYRejectsOrdinaryPipe(t *testing.T) { t.Error("IsTTY() = true for an ordinary pipe, want false") } } + +// Git Bash's stdin is a pipe too, which the key reader cannot read. +func TestCanReadKeysRejectsPipe(t *testing.T) { + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + reader.Close() + writer.Close() + }) + previous := os.Stdin + os.Stdin = reader + t.Cleanup(func() { os.Stdin = previous }) + if CanReadKeys() { + t.Error("CanReadKeys() = true for a pipe, want false") + } +} + +func TestIsCygwinPipeName(t *testing.T) { + cases := map[string]bool{ + `\msys-1888ae32e00d56aa-pty0-to-master`: true, + `\msys-1888ae32e00d56aa-pty1-from-master`: true, + `\cygwin-ab12cd34-pty2-to-master`: true, + `\Device\NamedPipe\msys-1888ae32e00d56aa-pty0-to-master`: true, + `\msys-1888ae32e00d56aa-pty0-to-slave`: false, + `\msys--pty0-to-master`: false, + `\msys-1888ae32e00d56aa-tty0-to-master`: false, + `\other-1888ae32e00d56aa-pty0-to-master`: false, + `\Win32Pipes.1234.5678`: false, + ``: false, + } + for name, want := range cases { + if got := isCygwinPipeName(name); got != want { + t.Errorf("isCygwinPipeName(%q) = %v, want %v", name, got, want) + } + } +} From 2f39e7ec4fff7d3432b39f9de6cbabf5af1904d7 Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 19:36:10 +0800 Subject: [PATCH 03/15] fix: a typed version wins over a list position in line selection (#98) A version whose name is a number, such as "2", must choose that version and not the second entry of the list, so keys are matched before positions. --- internal/shared/printer/select_line.go | 16 +++++++++------- internal/shared/printer/select_line_test.go | 11 +++++++++++ 2 files changed, 20 insertions(+), 7 deletions(-) diff --git a/internal/shared/printer/select_line.go b/internal/shared/printer/select_line.go index d9ebc4e1..491e5c2b 100644 --- a/internal/shared/printer/select_line.go +++ b/internal/shared/printer/select_line.go @@ -42,9 +42,9 @@ type LineSelect struct { Out io.Writer } -// Show lists the options and reads lines until one is chosen. A number chooses -// the entry at that position in the list, the key of an option chooses that -// option, and other text filters the list. An empty line clears the filter, or +// Show lists the options and reads lines until one is chosen. The key of an +// option chooses that option, a number chooses the entry at that position in the +// list, and other text filters the list. An empty line clears the filter, or // cancels when there is none. Show returns nil when the selection is cancelled // or the input ends. func (s *LineSelect) Show() (*KV, error) { @@ -98,16 +98,18 @@ func (s *LineSelect) matches(filter string) []*KV { } // choose returns the option that line picks, or nil when line is a filter. A -// number picks from the listed entries; a key picks from all options. +// key picks from all options and wins over a number, so that a version such as +// "17" is never mistaken for the seventeenth entry; a number picks from the +// listed entries. func (s *LineSelect) choose(line string, listed []*KV) *KV { - if n, err := strconv.Atoi(line); err == nil && n >= 1 && n <= len(listed) { - return listed[n-1] - } for _, option := range s.Options { if option.Key == line { return option } } + if n, err := strconv.Atoi(line); err == nil && n >= 1 && n <= len(listed) { + return listed[n-1] + } return nil } diff --git a/internal/shared/printer/select_line_test.go b/internal/shared/printer/select_line_test.go index 38290a17..f0c44ddf 100644 --- a/internal/shared/printer/select_line_test.go +++ b/internal/shared/printer/select_line_test.go @@ -77,6 +77,17 @@ func TestLineSelectChoosesByKey(t *testing.T) { assertChosen(t, chosen, err, "18.20.8") } +func TestLineSelectVersionWinsOverPosition(t *testing.T) { + // "2" is the version of the first entry, so it chooses that entry and not + // the second one. + options := []*KV{ + {Key: "2", Value: "2"}, + {Key: "1.0.0", Value: "1.0.0"}, + } + chosen, _, err := runLineSelect(t, "2\n", options, nil) + assertChosen(t, chosen, err, "2") +} + func TestLineSelectNumberWithoutNewlineAtEndOfInput(t *testing.T) { chosen, _, err := runLineSelect(t, "2", lineSelectOptions(), nil) assertChosen(t, chosen, err, "22.15.0") From bdef9d4cd85a7a79fceb3d692ddd4a0a1a3c389a Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:01:23 +0800 Subject: [PATCH 04/15] test: accept the -nat pipe names a real MSYS2 pty gives native programs (#98) Seen on windows-latest under script(1): a native program on an MSYS2 pty gets \msys--pty0-to-master-nat for stdout and ...-from-master-nat for stdin. The name check already accepts them; these cases pin it. --- internal/shared/util/tty_windows_test.go | 3 +++ 1 file changed, 3 insertions(+) diff --git a/internal/shared/util/tty_windows_test.go b/internal/shared/util/tty_windows_test.go index 848cccae..80328aef 100644 --- a/internal/shared/util/tty_windows_test.go +++ b/internal/shared/util/tty_windows_test.go @@ -92,6 +92,9 @@ func TestCanReadKeysRejectsPipe(t *testing.T) { func TestIsCygwinPipeName(t *testing.T) { cases := map[string]bool{ + // The names a real MSYS2 pty gives a native program, seen under script(1). + `\msys-a64f078b8998658e-pty0-from-master-nat`: true, + `\msys-a64f078b8998658e-pty0-to-master-nat`: true, `\msys-1888ae32e00d56aa-pty0-to-master`: true, `\msys-1888ae32e00d56aa-pty1-from-master`: true, `\cygwin-ab12cd34-pty2-to-master`: true, From 4138deb9952746695ead2baa93884a6f084342de Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:11:00 +0800 Subject: [PATCH 05/15] test: type the answers into Git Bash in a mintty window on Windows (#98) scripts/gitbash-mintty-test.ps1 starts Git for Windows' mintty.exe running Git for Windows' bash.exe, which runs TestGitBashMinttySelection. The test checks IsTTY and CanReadKeys in that window, then the script types "2" for the selection and "y" for the confirmation with WM_CHAR messages. --- .github/workflows/gitbash-mintty.yml | 23 ++++ cmd/commands/gitbash_mintty_windows_test.go | 89 +++++++++++++++ scripts/gitbash-mintty-test.ps1 | 113 ++++++++++++++++++++ 3 files changed, 225 insertions(+) create mode 100644 .github/workflows/gitbash-mintty.yml create mode 100644 cmd/commands/gitbash_mintty_windows_test.go create mode 100644 scripts/gitbash-mintty-test.ps1 diff --git a/.github/workflows/gitbash-mintty.yml b/.github/workflows/gitbash-mintty.yml new file mode 100644 index 00000000..f8ccf101 --- /dev/null +++ b/.github/workflows/gitbash-mintty.yml @@ -0,0 +1,23 @@ +name: Git Bash in mintty + +on: + push: + pull_request: + workflow_dispatch: + +jobs: + mintty: + name: Select and confirm in a Git Bash mintty window + runs-on: windows-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v7 + - uses: actions/setup-go@v7 + with: + go-version-file: go.mod + - name: Build the test binary + shell: pwsh + run: go test -c -o "$env:RUNNER_TEMP\commands.test.exe" ./cmd/commands + - name: Type the answers into Git Bash in mintty + shell: pwsh + run: ./scripts/gitbash-mintty-test.ps1 -TestBinary "$env:RUNNER_TEMP\commands.test.exe" -WorkDir "$env:RUNNER_TEMP\gitbash-mintty" diff --git a/cmd/commands/gitbash_mintty_windows_test.go b/cmd/commands/gitbash_mintty_windows_test.go new file mode 100644 index 00000000..b5450372 --- /dev/null +++ b/cmd/commands/gitbash_mintty_windows_test.go @@ -0,0 +1,89 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "encoding/binary" + "fmt" + "os" + "path/filepath" + "strings" + "testing" + "unicode/utf16" + + "github.com/pterm/pterm" + "github.com/version-fox/vfox/internal/shared/printer" + "github.com/version-fox/vfox/internal/shared/util" + "golang.org/x/sys/windows" +) + +// TestGitBashMinttySelection runs the terminal code in a Git Bash window: the +// test binary runs under Git for Windows' bash.exe in a mintty window, as it +// does for a person at mintty. scripts/gitbash-mintty-test.ps1 starts it and +// types the answers. When the test waits for one it creates a marker file in +// VFOX_TEST_GITBASH_MINTTY_DIR, and it writes its result there too. +func TestGitBashMinttySelection(t *testing.T) { + dir := os.Getenv("VFOX_TEST_GITBASH_MINTTY_DIR") + if dir == "" { + t.Skip("only runs in a Git Bash mintty window, started by scripts/gitbash-mintty-test.ps1") + } + var report strings.Builder + fmt.Fprintf(&report, "stdin pipe name: %s\n", gitBashPipeName(os.Stdin.Fd())) + fmt.Fprintf(&report, "stdout pipe name: %s\n", gitBashPipeName(os.Stdout.Fd())) + isTTY, canReadKeys := util.IsTTY(), util.CanReadKeys() + fmt.Fprintf(&report, "IsTTY: %v\nCanReadKeys: %v\n", isTTY, canReadKeys) + + markWaiting(t, dir, "select") + version, selectErr := selectFromOptions([]string{"18.20.8", "20.19.0"}, "nodejs") + fmt.Fprintf(&report, "selected: %q, error: %v\n", version, selectErr) + + markWaiting(t, dir, "confirm") + confirmed, confirmErr := printer.Confirm(&pterm.DefaultInteractiveConfirm, "Proceed with the check?") + fmt.Fprintf(&report, "confirmed: %v, error: %v\n", confirmed, confirmErr) + + if err := os.WriteFile(filepath.Join(dir, "result.txt"), []byte(report.String()), 0o644); err != nil { + t.Fatal(err) + } + if !isTTY || canReadKeys || selectErr != nil || version != "20.19.0" || confirmErr != nil || !confirmed { + t.Errorf("Git Bash in mintty:\n%s", report.String()) + } +} + +// markWaiting tells the driver that the test is about to wait for the input of step. +func markWaiting(t *testing.T, dir, step string) { + t.Helper() + if err := os.WriteFile(filepath.Join(dir, step+".ready"), nil, 0o644); err != nil { + t.Fatal(err) + } +} + +// gitBashPipeName returns the name of a pipe as FileNameInfo reports it. +func gitBashPipeName(fd uintptr) string { + buf := make([]byte, 4+2*260) + if err := windows.GetFileInformationByHandleEx(windows.Handle(fd), windows.FileNameInfo, &buf[0], uint32(len(buf))); err != nil { + return "error: " + err.Error() + } + size := int(binary.LittleEndian.Uint32(buf[:4])) + if size > len(buf)-4 { + size = len(buf) - 4 + } + units := make([]uint16, size/2) + for i := range units { + units[i] = binary.LittleEndian.Uint16(buf[4+2*i:]) + } + return string(utf16.Decode(units)) +} diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 new file mode 100644 index 00000000..7e932e77 --- /dev/null +++ b/scripts/gitbash-mintty-test.ps1 @@ -0,0 +1,113 @@ +<# +.SYNOPSIS + Runs the terminal code in a real mintty window and types the answers into it. + +.DESCRIPTION + Starts Git for Windows' mintty.exe running Git for Windows' bash.exe, and in + that bash the test binary built from cmd/commands: TestGitBashMinttySelection. + The test creates a marker file in -WorkDir when it waits for a choice. This + script then types the choice into the window with WM_CHAR messages, each + followed by Enter: "2" for the selection, then "y" for the confirmation. It + fails unless the test passes. + + It needs a desktop session, which GitHub-hosted Windows runners have, and it + types into a terminal window. Run it on a disposable runner or VM only. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string] $TestBinary, + + [Parameter(Mandatory)] + [string] $WorkDir, + + [ValidateRange(10, 1800)] + [int] $TimeoutSeconds = 180 +) + +$ErrorActionPreference = 'Stop' + +Add-Type -Namespace Vfox -Name Win32 -MemberDefinition @' +[DllImport("user32.dll", CharSet = CharSet.Auto)] +public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); +'@ + +$WM_CHAR = 0x0102 +$git = 'C:\Program Files\Git' +$bash = Join-Path $git 'bin\bash.exe' +$mintty = Join-Path $git 'usr\bin\mintty.exe' +foreach ($tool in $bash, $mintty, $TestBinary) { + if (-not (Test-Path -LiteralPath $tool -PathType Leaf)) { throw "missing $tool" } +} + +New-Item -ItemType Directory -Force -Path $WorkDir | Out-Null +$WorkDir = (Resolve-Path -LiteralPath $WorkDir).Path +Get-ChildItem -LiteralPath $WorkDir | Remove-Item -Force +$unixWork = (& $bash --noprofile --norc -c "cygpath -u '$WorkDir'").Trim() +$unixTest = (& $bash --noprofile --norc -c "cygpath -u '$TestBinary'").Trim() +$unixScript = "$unixWork/run.sh" + +# The script runs in Git Bash inside mintty. Its exit status goes to a file, and +# the window closes when the script ends. +$runScript = @' +#!/usr/bin/env bash +export VFOX_TEST_GITBASH_MINTTY_DIR='__WORK__' +'__TEST__' -test.run '^TestGitBashMinttySelection$' -test.v +echo $? > '__UNIXWORK__/exit.txt' +'@ +$runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork) +[System.IO.File]::WriteAllText((Join-Path $WorkDir 'run.sh'), $runScript.Replace("`r`n", "`n") + "`n") + +$window = Start-Process -FilePath $mintty -ArgumentList "-e `"$bash`" --noprofile --norc `"$unixScript`"" -PassThru + +$deadline = (Get-Date).AddSeconds($TimeoutSeconds) +while ($window.MainWindowHandle -eq [IntPtr]::Zero) { + if ((Get-Date) -gt $deadline) { + Write-Host "UserInteractive: $([Environment]::UserInteractive)" + throw 'mintty opened no window: is there a desktop session?' + } + Start-Sleep -Milliseconds 300 + $window.Refresh() +} +$handle = $window.MainWindowHandle +Write-Host "mintty window $handle, process $($window.Id)" + +function Send-Line([IntPtr] $target, [string] $text) { + foreach ($char in $text.ToCharArray()) { + [void][Vfox.Win32]::PostMessage($target, $WM_CHAR, [IntPtr][int][char]$char, [IntPtr]1) + Start-Sleep -Milliseconds 100 + } + [void][Vfox.Win32]::PostMessage($target, $WM_CHAR, [IntPtr]13, [IntPtr]1) +} + +function Wait-Marker([string] $name) { + $path = Join-Path $WorkDir $name + $deadline = (Get-Date).AddSeconds($TimeoutSeconds) + while (-not (Test-Path -LiteralPath $path)) { + if ((Get-Date) -gt $deadline) { throw "timed out waiting for $name" } + Start-Sleep -Milliseconds 200 + } +} + +try { + Wait-Marker 'select.ready' + Start-Sleep -Seconds 1 + Send-Line $handle '2' + Wait-Marker 'confirm.ready' + Start-Sleep -Seconds 1 + Send-Line $handle 'y' + Wait-Marker 'exit.txt' +} +finally { + if (-not $window.HasExited -and -not $window.WaitForExit(10000)) { + Stop-Process -Id $window.Id -Force + } + Write-Host "files in ${WorkDir}:" + Get-ChildItem -LiteralPath $WorkDir | ForEach-Object { Write-Host " $($_.Name)" } +} + +$exitCode = (Get-Content -LiteralPath (Join-Path $WorkDir 'exit.txt') -Raw).Trim() +Write-Host '--- result.txt' +Get-Content -LiteralPath (Join-Path $WorkDir 'result.txt') -ErrorAction SilentlyContinue | Write-Host +if ($exitCode -ne '0') { throw "the test failed in mintty with exit code $exitCode" } +Write-Host 'Git Bash in mintty: selection and confirmation passed.' From 0b38e376cf22683f3e4ad4c9d69a261d3faaa26d Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:15:52 +0800 Subject: [PATCH 06/15] test: find the mintty window by its class in the Git Bash driver (#98) MainWindowHandle stayed zero on windows-latest although the session was interactive, so the driver now enumerates the top-level windows and takes the one of class "mintty". On a timeout it prints the windows and the mintty command lines, and it fails at once when mintty has exited. --- scripts/gitbash-mintty-test.ps1 | 86 +++++++++++++++++++++++++++++---- 1 file changed, 76 insertions(+), 10 deletions(-) diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 index 7e932e77..a0a85119 100644 --- a/scripts/gitbash-mintty-test.ps1 +++ b/scripts/gitbash-mintty-test.ps1 @@ -27,9 +27,59 @@ param( $ErrorActionPreference = 'Stop' -Add-Type -Namespace Vfox -Name Win32 -MemberDefinition @' -[DllImport("user32.dll", CharSet = CharSet.Auto)] -public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); +Add-Type -TypeDefinition @' +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; +using System.Text; + +public static class VfoxWindow +{ + public delegate bool EnumProc(IntPtr hWnd, IntPtr lParam); + + [DllImport("user32.dll")] + public static extern bool EnumWindows(EnumProc callback, IntPtr lParam); + + [DllImport("user32.dll")] + public static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint processId); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern int GetClassName(IntPtr hWnd, StringBuilder className, int maxCount); + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int maxCount); + + [DllImport("user32.dll")] + public static extern bool PostMessage(IntPtr hWnd, uint msg, IntPtr wParam, IntPtr lParam); + + public static List TopLevel() + { + List found = new List(); + EnumWindows(delegate (IntPtr hWnd, IntPtr lParam) { found.Add(hWnd); return true; }, IntPtr.Zero); + return found; + } + + public static string ClassOf(IntPtr hWnd) + { + StringBuilder text = new StringBuilder(256); + GetClassName(hWnd, text, text.Capacity); + return text.ToString(); + } + + public static string TitleOf(IntPtr hWnd) + { + StringBuilder text = new StringBuilder(512); + GetWindowText(hWnd, text, text.Capacity); + return text.ToString(); + } + + public static uint ProcessOf(IntPtr hWnd) + { + uint processId; + GetWindowThreadProcessId(hWnd, out processId); + return processId; + } +} '@ $WM_CHAR = 0x0102 @@ -59,25 +109,41 @@ $runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__TEST__', $unixT [System.IO.File]::WriteAllText((Join-Path $WorkDir 'run.sh'), $runScript.Replace("`r`n", "`n") + "`n") $window = Start-Process -FilePath $mintty -ArgumentList "-e `"$bash`" --noprofile --norc `"$unixScript`"" -PassThru +Write-Host "started $mintty as process $($window.Id)" + +function Find-MinttyWindow { + foreach ($candidate in [VfoxWindow]::TopLevel()) { + if ([VfoxWindow]::ClassOf($candidate) -eq 'mintty') { return $candidate } + } + return [IntPtr]::Zero +} $deadline = (Get-Date).AddSeconds($TimeoutSeconds) -while ($window.MainWindowHandle -eq [IntPtr]::Zero) { +$handle = Find-MinttyWindow +while ($handle -eq [IntPtr]::Zero) { + if ($window.HasExited) { throw "mintty exited with code $($window.ExitCode) before it showed a window" } if ((Get-Date) -gt $deadline) { Write-Host "UserInteractive: $([Environment]::UserInteractive)" - throw 'mintty opened no window: is there a desktop session?' + foreach ($candidate in [VfoxWindow]::TopLevel()) { + $title = [VfoxWindow]::TitleOf($candidate) + if ($title) { + Write-Host ("window {0} class '{1}' title '{2}' process {3}" -f $candidate, [VfoxWindow]::ClassOf($candidate), $title, [VfoxWindow]::ProcessOf($candidate)) + } + } + Get-CimInstance Win32_Process -Filter "Name = 'mintty.exe'" | ForEach-Object { Write-Host "mintty.exe $($_.ProcessId): $($_.CommandLine)" } + throw 'no mintty window appeared' } Start-Sleep -Milliseconds 300 - $window.Refresh() + $handle = Find-MinttyWindow } -$handle = $window.MainWindowHandle -Write-Host "mintty window $handle, process $($window.Id)" +Write-Host "mintty window $handle, process $([VfoxWindow]::ProcessOf($handle))" function Send-Line([IntPtr] $target, [string] $text) { foreach ($char in $text.ToCharArray()) { - [void][Vfox.Win32]::PostMessage($target, $WM_CHAR, [IntPtr][int][char]$char, [IntPtr]1) + [void][VfoxWindow]::PostMessage($target, $WM_CHAR, [IntPtr][int][char]$char, [IntPtr]1) Start-Sleep -Milliseconds 100 } - [void][Vfox.Win32]::PostMessage($target, $WM_CHAR, [IntPtr]13, [IntPtr]1) + [void][VfoxWindow]::PostMessage($target, $WM_CHAR, [IntPtr]13, [IntPtr]1) } function Wait-Marker([string] $name) { From 2ee2b455d9718f6198e0492be1165f21b390450a Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:18:42 +0800 Subject: [PATCH 07/15] test: run the mintty check in both pipe and console modes (#98) The first run showed that the mintty window's default gives vfox a pseudo console, where the arrow-key selection already works, so the check did not reach the pipe case of the issue. The workflow now runs the window twice: once with MSYS=disable_pcon, the classic pseudo terminal that reaches the program as a pipe, and once with the default. The test checks which one it got, and the driver types the full version, which both selectors accept. --- .github/workflows/gitbash-mintty.yml | 10 ++++-- cmd/commands/gitbash_mintty_windows_test.go | 35 ++++++++++++++++++--- scripts/gitbash-mintty-test.ps1 | 30 +++++++++++++----- 3 files changed, 61 insertions(+), 14 deletions(-) diff --git a/.github/workflows/gitbash-mintty.yml b/.github/workflows/gitbash-mintty.yml index f8ccf101..e18a9a35 100644 --- a/.github/workflows/gitbash-mintty.yml +++ b/.github/workflows/gitbash-mintty.yml @@ -9,7 +9,7 @@ jobs: mintty: name: Select and confirm in a Git Bash mintty window runs-on: windows-latest - timeout-minutes: 15 + timeout-minutes: 20 steps: - uses: actions/checkout@v7 - uses: actions/setup-go@v7 @@ -18,6 +18,10 @@ jobs: - name: Build the test binary shell: pwsh run: go test -c -o "$env:RUNNER_TEMP\commands.test.exe" ./cmd/commands - - name: Type the answers into Git Bash in mintty + - name: Classic pseudo terminal, which reaches the program as a pipe shell: pwsh - run: ./scripts/gitbash-mintty-test.ps1 -TestBinary "$env:RUNNER_TEMP\commands.test.exe" -WorkDir "$env:RUNNER_TEMP\gitbash-mintty" + run: ./scripts/gitbash-mintty-test.ps1 -TestBinary "$env:RUNNER_TEMP\commands.test.exe" -WorkDir "$env:RUNNER_TEMP\gitbash-mintty-pipe" -Stdio pipe -MsysOptions disable_pcon + - name: Pseudo console, the default of the MSYS2 runtime here + if: always() + shell: pwsh + run: ./scripts/gitbash-mintty-test.ps1 -TestBinary "$env:RUNNER_TEMP\commands.test.exe" -WorkDir "$env:RUNNER_TEMP\gitbash-mintty-console" -Stdio console diff --git a/cmd/commands/gitbash_mintty_windows_test.go b/cmd/commands/gitbash_mintty_windows_test.go index b5450372..6d0e4ad1 100644 --- a/cmd/commands/gitbash_mintty_windows_test.go +++ b/cmd/commands/gitbash_mintty_windows_test.go @@ -36,14 +36,23 @@ import ( // does for a person at mintty. scripts/gitbash-mintty-test.ps1 starts it and // types the answers. When the test waits for one it creates a marker file in // VFOX_TEST_GITBASH_MINTTY_DIR, and it writes its result there too. +// +// VFOX_TEST_GITBASH_MINTTY_STDIO says what the window gives the program: "pipe" +// for a pseudo terminal that reaches it as a pipe (the line input of the fix), +// or "console" for a pseudo console (the arrow-key selection). func TestGitBashMinttySelection(t *testing.T) { dir := os.Getenv("VFOX_TEST_GITBASH_MINTTY_DIR") if dir == "" { t.Skip("only runs in a Git Bash mintty window, started by scripts/gitbash-mintty-test.ps1") } + stdio := os.Getenv("VFOX_TEST_GITBASH_MINTTY_STDIO") + if stdio != "pipe" && stdio != "console" { + t.Fatalf("VFOX_TEST_GITBASH_MINTTY_STDIO = %q, want pipe or console", stdio) + } var report strings.Builder - fmt.Fprintf(&report, "stdin pipe name: %s\n", gitBashPipeName(os.Stdin.Fd())) - fmt.Fprintf(&report, "stdout pipe name: %s\n", gitBashPipeName(os.Stdout.Fd())) + fmt.Fprintf(&report, "MSYS: %q\n", os.Getenv("MSYS")) + fmt.Fprintf(&report, "stdin: %s\n", gitBashHandleKind(os.Stdin.Fd())) + fmt.Fprintf(&report, "stdout: %s\n", gitBashHandleKind(os.Stdout.Fd())) isTTY, canReadKeys := util.IsTTY(), util.CanReadKeys() fmt.Fprintf(&report, "IsTTY: %v\nCanReadKeys: %v\n", isTTY, canReadKeys) @@ -55,11 +64,17 @@ func TestGitBashMinttySelection(t *testing.T) { confirmed, confirmErr := printer.Confirm(&pterm.DefaultInteractiveConfirm, "Proceed with the check?") fmt.Fprintf(&report, "confirmed: %v, error: %v\n", confirmed, confirmErr) + ok := isTTY && selectErr == nil && version == "20.19.0" && confirmErr == nil && confirmed + if stdio == "pipe" { + ok = ok && !canReadKeys + } else { + ok = ok && canReadKeys + } if err := os.WriteFile(filepath.Join(dir, "result.txt"), []byte(report.String()), 0o644); err != nil { t.Fatal(err) } - if !isTTY || canReadKeys || selectErr != nil || version != "20.19.0" || confirmErr != nil || !confirmed { - t.Errorf("Git Bash in mintty:\n%s", report.String()) + if !ok { + t.Errorf("Git Bash in mintty, %s:\n%s", stdio, report.String()) } } @@ -71,6 +86,18 @@ func markWaiting(t *testing.T, dir, step string) { } } +// gitBashHandleKind describes a standard handle: the name of a pipe, or the file type. +func gitBashHandleKind(fd uintptr) string { + fileType, err := windows.GetFileType(windows.Handle(fd)) + if err != nil { + return "error: " + err.Error() + } + if fileType != windows.FILE_TYPE_PIPE { + return fmt.Sprintf("file type %d", fileType) + } + return "pipe " + gitBashPipeName(fd) +} + // gitBashPipeName returns the name of a pipe as FileNameInfo reports it. func gitBashPipeName(fd uintptr) string { buf := make([]byte, 4+2*260) diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 index a0a85119..0c109b80 100644 --- a/scripts/gitbash-mintty-test.ps1 +++ b/scripts/gitbash-mintty-test.ps1 @@ -7,8 +7,13 @@ that bash the test binary built from cmd/commands: TestGitBashMinttySelection. The test creates a marker file in -WorkDir when it waits for a choice. This script then types the choice into the window with WM_CHAR messages, each - followed by Enter: "2" for the selection, then "y" for the confirmation. It - fails unless the test passes. + followed by Enter: "20.19.0" for the selection, then "y" for the confirmation. + It fails unless the test passes. + + -Stdio says what the window gives the program: "pipe" for a pseudo terminal + that reaches it as a pipe, which is how mintty's classic terminal works; the + MSYS option disable_pcon asks the MSYS2 runtime for that. "console" leaves the + runtime's default, which may be a pseudo console. It needs a desktop session, which GitHub-hosted Windows runners have, and it types into a terminal window. Run it on a disposable runner or VM only. @@ -21,6 +26,12 @@ param( [Parameter(Mandatory)] [string] $WorkDir, + [Parameter(Mandatory)] + [ValidateSet('pipe', 'console')] + [string] $Stdio, + + [string] $MsysOptions = '', + [ValidateRange(10, 1800)] [int] $TimeoutSeconds = 180 ) @@ -102,12 +113,18 @@ $unixScript = "$unixWork/run.sh" $runScript = @' #!/usr/bin/env bash export VFOX_TEST_GITBASH_MINTTY_DIR='__WORK__' +export VFOX_TEST_GITBASH_MINTTY_STDIO='__STDIO__' '__TEST__' -test.run '^TestGitBashMinttySelection$' -test.v echo $? > '__UNIXWORK__/exit.txt' '@ -$runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork) +$runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__STDIO__', $Stdio).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork) [System.IO.File]::WriteAllText((Join-Path $WorkDir 'run.sh'), $runScript.Replace("`r`n", "`n") + "`n") +# A window left over from an earlier run would be taken for this one. +Get-Process -Name mintty -ErrorAction SilentlyContinue | Stop-Process -Force +if ($MsysOptions) { $env:MSYS = $MsysOptions } +Write-Host "MSYS for mintty: '$($env:MSYS)' (stdio: $Stdio)" + $window = Start-Process -FilePath $mintty -ArgumentList "-e `"$bash`" --noprofile --norc `"$unixScript`"" -PassThru Write-Host "started $mintty as process $($window.Id)" @@ -130,7 +147,6 @@ while ($handle -eq [IntPtr]::Zero) { Write-Host ("window {0} class '{1}' title '{2}' process {3}" -f $candidate, [VfoxWindow]::ClassOf($candidate), $title, [VfoxWindow]::ProcessOf($candidate)) } } - Get-CimInstance Win32_Process -Filter "Name = 'mintty.exe'" | ForEach-Object { Write-Host "mintty.exe $($_.ProcessId): $($_.CommandLine)" } throw 'no mintty window appeared' } Start-Sleep -Milliseconds 300 @@ -158,7 +174,7 @@ function Wait-Marker([string] $name) { try { Wait-Marker 'select.ready' Start-Sleep -Seconds 1 - Send-Line $handle '2' + Send-Line $handle '20.19.0' Wait-Marker 'confirm.ready' Start-Sleep -Seconds 1 Send-Line $handle 'y' @@ -175,5 +191,5 @@ finally { $exitCode = (Get-Content -LiteralPath (Join-Path $WorkDir 'exit.txt') -Raw).Trim() Write-Host '--- result.txt' Get-Content -LiteralPath (Join-Path $WorkDir 'result.txt') -ErrorAction SilentlyContinue | Write-Host -if ($exitCode -ne '0') { throw "the test failed in mintty with exit code $exitCode" } -Write-Host 'Git Bash in mintty: selection and confirmation passed.' +if ($exitCode -ne '0') { throw "the test failed in mintty ($Stdio) with exit code $exitCode" } +Write-Host "Git Bash in mintty ($Stdio): selection and confirmation passed." From 04ebbc1ec6d568755524a85425eedc08a670cffe Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:20:39 +0800 Subject: [PATCH 08/15] test: print the mintty result when the check fails (#98) --- scripts/gitbash-mintty-test.ps1 | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 index 0c109b80..ccf897ca 100644 --- a/scripts/gitbash-mintty-test.ps1 +++ b/scripts/gitbash-mintty-test.ps1 @@ -186,10 +186,10 @@ finally { } Write-Host "files in ${WorkDir}:" Get-ChildItem -LiteralPath $WorkDir | ForEach-Object { Write-Host " $($_.Name)" } + Write-Host '--- result.txt' + Get-Content -LiteralPath (Join-Path $WorkDir 'result.txt') -ErrorAction SilentlyContinue | Write-Host } $exitCode = (Get-Content -LiteralPath (Join-Path $WorkDir 'exit.txt') -Raw).Trim() -Write-Host '--- result.txt' -Get-Content -LiteralPath (Join-Path $WorkDir 'result.txt') -ErrorAction SilentlyContinue | Write-Host if ($exitCode -ne '0') { throw "the test failed in mintty ($Stdio) with exit code $exitCode" } Write-Host "Git Bash in mintty ($Stdio): selection and confirmation passed." From 1986ebdefe723df41cad759fce960861b9cff5b4 Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:33:44 +0800 Subject: [PATCH 09/15] test: cover the line selection, confirm and tty helpers the Codecov note lists (#98) - search: the line selection of RunSearch moves into installByLine, which takes the installer as an interface, so the cancel, refusal, install and read-error paths run in unit tests. - use, confirm: the choice between keys and a line is a parameter of chooseVersion and confirm, so the line paths run in unit tests on every platform; the wrappers that read util.CanReadKeys stay one line each. - Read errors of LineSelect, lineConfirm and selectVersionByLine, shortAnswer, and the tty helpers off Windows are covered. - On Windows, Confirm reads a line from a pipe. What remains uncovered is interactive only: the confirmation calls in install, link, remove and manager, and the key paths of RunSearch and confirm. Those run only when stdout is a terminal. --- cmd/commands/choose_line_test.go | 58 ++++++++++ cmd/commands/search.go | 41 ++++--- cmd/commands/search_line_test.go | 107 ++++++++++++++++++ cmd/commands/use.go | 8 +- internal/shared/printer/confirm.go | 9 +- internal/shared/printer/confirm_test.go | 29 +++++ .../shared/printer/confirm_windows_test.go | 51 +++++++++ internal/shared/printer/select_line_test.go | 21 ++++ internal/shared/util/tty_notwindows_test.go | 35 ++++++ 9 files changed, 342 insertions(+), 17 deletions(-) create mode 100644 cmd/commands/choose_line_test.go create mode 100644 cmd/commands/search_line_test.go create mode 100644 internal/shared/printer/confirm_windows_test.go create mode 100644 internal/shared/util/tty_notwindows_test.go diff --git a/cmd/commands/choose_line_test.go b/cmd/commands/choose_line_test.go new file mode 100644 index 00000000..53fb4ca3 --- /dev/null +++ b/cmd/commands/choose_line_test.go @@ -0,0 +1,58 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "bytes" + "os" + "testing" +) + +func TestSelectVersionByLineReportsReadError(t *testing.T) { + var out bytes.Buffer + version, err := selectVersionByLine(failingReader{}, &out, []string{"18.20.8"}, "nodejs") + if err == nil { + t.Fatalf("selectVersionByLine() = %q, want an error for a failing read", version) + } +} + +// Without key presses chooseVersion reads the choice from stdin, so the test +// gives stdin a pipe that holds the choice. +func TestChooseVersionWithoutKeysReadsALine(t *testing.T) { + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + reader.Close() + writer.Close() + }) + if _, err := writer.WriteString("20.19.0\n"); err != nil { + t.Fatal(err) + } + previous := os.Stdin + os.Stdin = reader + t.Cleanup(func() { os.Stdin = previous }) + + version, err := chooseVersion(false, []string{"18.20.8", "20.19.0"}, "nodejs") + if err != nil { + t.Fatalf("chooseVersion() error: %v", err) + } + if version != "20.19.0" { + t.Errorf("chooseVersion() = %q, want %q", version, "20.19.0") + } +} diff --git a/cmd/commands/search.go b/cmd/commands/search.go index 1e6e7246..d40fec56 100644 --- a/cmd/commands/search.go +++ b/cmd/commands/search.go @@ -19,6 +19,7 @@ package commands import ( "context" "fmt" + "io" "math" "os" "strings" @@ -95,20 +96,7 @@ func RunSearch(sdkName string, availableArgs []string) error { } if !util.CanReadKeys() { - selected, err := (&printer.LineSelect{ - TopText: "Please select a version of " + sdkName + " to install", - Options: options, - DisabledOptions: installedVersions, - In: os.Stdin, - Out: os.Stdout, - }).Show() - if err != nil { - return fmt.Errorf("select version error: %w", err) - } - if selected == nil { - return nil - } - return source.Install(sdk.Version(selected.Key)) + return installByLine(source, os.Stdin, os.Stdout, options, installedVersions, sdkName) } _, height, _ := terminal.GetSize(int(os.Stdout.Fd())) kvSelect := printer.PageKVSelect{ @@ -142,6 +130,31 @@ func RunSearch(sdkName string, availableArgs []string) error { return source.Install(sdk.Version(version.Key)) } +// versionInstaller is what installing a chosen version needs from sdk.Sdk. +type versionInstaller interface { + Install(version sdk.Version) error +} + +// installByLine lets the person choose a version by reading a line, and installs +// it, for a terminal that cannot deliver single key presses. Cancelling installs +// nothing. +func installByLine(installer versionInstaller, in io.Reader, out io.Writer, options []*printer.KV, installed util.Set[string], sdkName string) error { + selected, err := (&printer.LineSelect{ + TopText: "Please select a version of " + sdkName + " to install", + Options: options, + DisabledOptions: installed, + In: in, + Out: out, + }).Show() + if err != nil { + return fmt.Errorf("select version error: %w", err) + } + if selected == nil { + return nil + } + return installer.Install(sdk.Version(selected.Key)) +} + func searchCmd(ctx context.Context, cmd *cli.Command) error { sdkName := cmd.Args().First() if sdkName == "" { diff --git a/cmd/commands/search_line_test.go b/cmd/commands/search_line_test.go new file mode 100644 index 00000000..c6451c25 --- /dev/null +++ b/cmd/commands/search_line_test.go @@ -0,0 +1,107 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package commands + +import ( + "bytes" + "errors" + "strings" + "testing" + + "github.com/version-fox/vfox/internal/sdk" + "github.com/version-fox/vfox/internal/shared/printer" + "github.com/version-fox/vfox/internal/shared/util" +) + +// recordingInstaller records the versions it is asked to install. +type recordingInstaller struct { + installed []sdk.Version +} + +func (r *recordingInstaller) Install(version sdk.Version) error { + r.installed = append(r.installed, version) + return nil +} + +// failingReader fails every read, as a terminal that went away does. +type failingReader struct{} + +func (failingReader) Read([]byte) (int, error) { + return 0, errors.New("terminal gone") +} + +func searchOptions() []*printer.KV { + return []*printer.KV{ + {Key: "18.20.8", Value: "18.20.8 (LTS Hydrogen)"}, + {Key: "20.19.0", Value: "20.19.0 (LTS Iron)"}, + } +} + +func TestInstallByLineInstallsTheChosenVersion(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + err := installByLine(&installer, strings.NewReader("2\n"), &out, searchOptions(), util.NewSet[string](), "nodejs") + if err != nil { + t.Fatalf("installByLine() error: %v", err) + } + if len(installer.installed) != 1 || installer.installed[0] != "20.19.0" { + t.Errorf("installed %v, want [20.19.0]", installer.installed) + } + if !strings.Contains(out.String(), "Please select a version of nodejs to install") { + t.Errorf("prompt does not name the SDK:\n%s", out.String()) + } +} + +func TestInstallByLineCancelInstallsNothing(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + if err := installByLine(&installer, strings.NewReader("\n"), &out, searchOptions(), util.NewSet[string](), "nodejs"); err != nil { + t.Fatalf("installByLine() error: %v", err) + } + if len(installer.installed) != 0 { + t.Errorf("installed %v after a cancelled selection, want nothing", installer.installed) + } +} + +func TestInstallByLineRefusesAnInstalledVersion(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + installed := util.NewSet[string]() + installed.Add("20.19.0") + err := installByLine(&installer, strings.NewReader("2\n1\n"), &out, searchOptions(), installed, "nodejs") + if err != nil { + t.Fatalf("installByLine() error: %v", err) + } + if len(installer.installed) != 1 || installer.installed[0] != "18.20.8" { + t.Errorf("installed %v, want [18.20.8] after the installed version was refused", installer.installed) + } + if !strings.Contains(out.String(), "20.19.0 is already installed") { + t.Errorf("output does not refuse the installed version:\n%s", out.String()) + } +} + +func TestInstallByLineReportsReadError(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + err := installByLine(&installer, failingReader{}, &out, searchOptions(), util.NewSet[string](), "nodejs") + if err == nil || !strings.Contains(err.Error(), "select version error") { + t.Fatalf("installByLine() error = %v, want a select version error", err) + } + if len(installer.installed) != 0 { + t.Errorf("installed %v after a failed read, want nothing", installer.installed) + } +} diff --git a/cmd/commands/use.go b/cmd/commands/use.go index 34c309fe..99a6c5e5 100644 --- a/cmd/commands/use.go +++ b/cmd/commands/use.go @@ -179,7 +179,13 @@ func resolveVersion(sdkSource sdk.Sdk, manager *internal.Manager, version sdk.Ve // selectFromOptions displays an interactive selection prompt func selectFromOptions(options []string, sdkName string) (string, error) { - if !util.CanReadKeys() { + return chooseVersion(util.CanReadKeys(), options, sdkName) +} + +// chooseVersion shows the selection and takes the arrow keys when keys is true. +// Without key presses it reads the choice as a line. +func chooseVersion(keys bool, options []string, sdkName string) (string, error) { + if !keys { return selectVersionByLine(os.Stdin, os.Stdout, options, sdkName) } selectPrinter := pterm.InteractiveSelectPrinter{ diff --git a/internal/shared/printer/confirm.go b/internal/shared/printer/confirm.go index 093b7a4e..d6485808 100644 --- a/internal/shared/printer/confirm.go +++ b/internal/shared/printer/confirm.go @@ -30,10 +30,15 @@ import ( // Confirm asks a yes-or-no question with p. Where key presses can be read it // behaves as p.Show; elsewhere the answer is a line (see util.CanReadKeys). func Confirm(p *pterm.InteractiveConfirmPrinter, text string) (bool, error) { - if util.CanReadKeys() { + return confirm(util.CanReadKeys(), p, text, os.Stdin, os.Stdout) +} + +// confirm asks with p when keys is true, and otherwise reads the answer as a line from in. +func confirm(keys bool, p *pterm.InteractiveConfirmPrinter, text string, in io.Reader, out io.Writer) (bool, error) { + if keys { return p.Show(text) } - return lineConfirm(os.Stdin, os.Stdout, *p, text) + return lineConfirm(in, out, *p, text) } // lineConfirm asks text and reads an answer line. The confirm or reject text, or diff --git a/internal/shared/printer/confirm_test.go b/internal/shared/printer/confirm_test.go index 95ecd3d9..0489fb46 100644 --- a/internal/shared/printer/confirm_test.go +++ b/internal/shared/printer/confirm_test.go @@ -62,6 +62,35 @@ func TestLineConfirmAnswers(t *testing.T) { } } +func TestLineConfirmReportsReadError(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + if _, err := lineConfirm(brokenReader{}, &out, p, "Install?"); err == nil { + t.Fatal("lineConfirm() error = nil for a failing read, want an error") + } +} + +func TestConfirmWithoutKeysReadsALine(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + got, err := confirm(false, &p, "Install?", strings.NewReader("y\n"), &out) + if err != nil || !got { + t.Fatalf("confirm(false) = %v, %v, want true", got, err) + } +} + +func TestShortAnswer(t *testing.T) { + for _, tc := range []struct{ text, fallback, want string }{ + {"", "y", "y"}, + {"Yes", "n", "y"}, + {"No", "y", "n"}, + } { + if got := shortAnswer(tc.text, tc.fallback); got != tc.want { + t.Errorf("shortAnswer(%q, %q) = %q, want %q", tc.text, tc.fallback, got, tc.want) + } + } +} + func TestLineConfirmShowsDefaultInUpperCase(t *testing.T) { p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} var out bytes.Buffer diff --git a/internal/shared/printer/confirm_windows_test.go b/internal/shared/printer/confirm_windows_test.go new file mode 100644 index 00000000..872b8f3b --- /dev/null +++ b/internal/shared/printer/confirm_windows_test.go @@ -0,0 +1,51 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "os" + "testing" + + "github.com/pterm/pterm" +) + +// Git Bash in mintty gives vfox a pipe for stdin, so Confirm reads the answer as a line. +func TestConfirmReadsLineFromPipe(t *testing.T) { + reader, writer, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + reader.Close() + writer.Close() + }) + if _, err := writer.WriteString("y\r\n"); err != nil { + t.Fatal(err) + } + previous := os.Stdin + os.Stdin = reader + t.Cleanup(func() { os.Stdin = previous }) + + p := pterm.DefaultInteractiveConfirm + confirmed, err := Confirm(&p, "Proceed?") + if err != nil { + t.Fatalf("Confirm() error: %v", err) + } + if !confirmed { + t.Error("Confirm() = false for y, want true") + } +} diff --git a/internal/shared/printer/select_line_test.go b/internal/shared/printer/select_line_test.go index f0c44ddf..4e31c898 100644 --- a/internal/shared/printer/select_line_test.go +++ b/internal/shared/printer/select_line_test.go @@ -117,6 +117,27 @@ func TestLineSelectEmptyLineClearsFilterThenCancels(t *testing.T) { } } +// brokenReader fails every read, as a terminal that went away does. +type brokenReader struct{} + +func (brokenReader) Read([]byte) (int, error) { + return 0, fmt.Errorf("terminal gone") +} + +func TestLineSelectReportsReadError(t *testing.T) { + var out bytes.Buffer + s := &LineSelect{ + TopText: "Please select a version of nodejs", + Options: lineSelectOptions(), + In: brokenReader{}, + Out: &out, + } + chosen, err := s.Show() + if err == nil || chosen != nil { + t.Fatalf("Show() = %v, %v, want an error for a failing read", chosen, err) + } +} + func TestLineSelectCancelsOnEndOfInput(t *testing.T) { chosen, _, err := runLineSelect(t, "", lineSelectOptions(), nil) if err != nil { diff --git a/internal/shared/util/tty_notwindows_test.go b/internal/shared/util/tty_notwindows_test.go new file mode 100644 index 00000000..c73385bf --- /dev/null +++ b/internal/shared/util/tty_notwindows_test.go @@ -0,0 +1,35 @@ +//go:build !windows + +// Copyright 2026 vfox project contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package util + +import ( + "os" + "testing" +) + +// Off Windows the key reader reads /dev/tty, and no pipe is a pseudo terminal. +func TestKeysAndPtysOffWindows(t *testing.T) { + if !CanReadKeys() { + t.Error("CanReadKeys() = false off Windows, want true") + } + if !canReadKeysFrom(os.Stdin.Fd()) { + t.Error("canReadKeysFrom() = false off Windows, want true") + } + if isCygwinTerminal(os.Stdout.Fd()) { + t.Error("isCygwinTerminal() = true off Windows, want false") + } +} From 19d983c8e8ca59181ce0f28f2928a1baf74687f7 Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:41:19 +0800 Subject: [PATCH 10/15] fix: accept only the documented pty pipe names (#98) Copilot review on #763: the matcher checked only the first five parts of a pipe name, so \msys--pty0-to-master-not-a-pty counted as a terminal and could switch a command into interactive mode. The name is now matched as a whole: the documented forms, with -nat as the only suffix, and digits after pty. The table adds names with anything else after the name. --- internal/shared/util/tty_windows.go | 22 +++++++--------------- internal/shared/util/tty_windows_test.go | 6 ++++++ 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/internal/shared/util/tty_windows.go b/internal/shared/util/tty_windows.go index 2a6794c9..e6cb6130 100644 --- a/internal/shared/util/tty_windows.go +++ b/internal/shared/util/tty_windows.go @@ -18,7 +18,7 @@ package util import ( "encoding/binary" - "strings" + "regexp" "unicode/utf16" "golang.org/x/sys/windows" @@ -63,20 +63,12 @@ func pipeName(handle windows.Handle) (string, error) { return string(utf16.Decode(units)), nil } -// isCygwinPipeName matches the names of Cygwin and MSYS2 ptys, the way go-isatty +// cygwinPipeName matches the names of Cygwin and MSYS2 ptys, the way go-isatty // does: \msys--pty-(from|to)-master, or the same with cygwin for msys. +// Native programs get the -nat suffix, and nothing else may follow the name. +var cygwinPipeName = regexp.MustCompile(`^\\(?:Device\\NamedPipe\\)?(?:msys|cygwin)-[0-9A-Za-z]+-pty[0-9]+-(?:from|to)-master(?:-nat)?$`) + +// isCygwinPipeName reports whether name is the name of a Cygwin or MSYS2 pty. func isCygwinPipeName(name string) bool { - token := strings.Split(name, "-") - if len(token) < 5 { - return false - } - switch token[0] { - case `\msys`, `\cygwin`, `\Device\NamedPipe\msys`, `\Device\NamedPipe\cygwin`: - default: - return false - } - return token[1] != "" && - strings.HasPrefix(token[2], "pty") && - (token[3] == "from" || token[3] == "to") && - token[4] == "master" + return cygwinPipeName.MatchString(name) } diff --git a/internal/shared/util/tty_windows_test.go b/internal/shared/util/tty_windows_test.go index 80328aef..3d737997 100644 --- a/internal/shared/util/tty_windows_test.go +++ b/internal/shared/util/tty_windows_test.go @@ -92,6 +92,12 @@ func TestCanReadKeysRejectsPipe(t *testing.T) { func TestIsCygwinPipeName(t *testing.T) { cases := map[string]bool{ + // Anything after the documented forms makes a name something else. + `\msys-1888ae32e00d56aa-pty0-to-master-not-a-pty`: false, + `\msys-1888ae32e00d56aa-pty0-to-master-nat-extra`: false, + `\msys-1888ae32e00d56aa-pty0-to-master-`: false, + `\msys-1888ae32e00d56aa-pty0-to-masterx`: false, + `\msys-1888ae32e00d56aa-ptyx-to-master`: false, // The names a real MSYS2 pty gives a native program, seen under script(1). `\msys-a64f078b8998658e-pty0-from-master-nat`: true, `\msys-a64f078b8998658e-pty0-to-master-nat`: true, From 177c7ab616eeaf19fd11bd5a17a7a08f24ee017c Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:41:19 +0800 Subject: [PATCH 11/15] docs: say that isCygwinTerminal reports the pipe as a terminal (#98) The comment read ambiguously ("a pipe, which isCygwinTerminal recognizes"). --- internal/shared/util/tty.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/shared/util/tty.go b/internal/shared/util/tty.go index a0f8703a..5a99088a 100644 --- a/internal/shared/util/tty.go +++ b/internal/shared/util/tty.go @@ -24,7 +24,7 @@ import ( // IsTTY checks if the process is running in a TTY (interactive terminal). On // Windows, Git Bash in mintty counts as one: its pty reaches native programs as -// a pipe, which isCygwinTerminal recognizes. +// a pipe, and isCygwinTerminal reports that pipe as a terminal. func IsTTY() bool { return term.IsTerminal(int(os.Stdout.Fd())) || isCygwinTerminal(os.Stdout.Fd()) } From 2aa04e1063f84cda7b1eeb2202e37d7b259ba4f8 Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:55:08 +0800 Subject: [PATCH 12/15] feat: arrow keys in a classic Git Bash pty, through stty raw mode (#98) In Git Bash in mintty, with the pseudo console off, the program gets its terminal as a pipe, and the keyboard library cannot read it. The arrow keys then arrived only with the line, so the selection fell back to typed lines. Now such a terminal is switched with stty to raw mode (no line buffering, no echo, no signals from Ctrl-C), which stty from Git for Windows does on the pipe. The prompts read the keys themselves: the arrow keys move the highlight in the version list, typed text filters it, Enter chooses, Ctrl-C cancels, and y and n answer a confirmation. The mode is restored afterwards. - printer.InputFor says how the prompts take their answers: the keyboard library where it can read keys, raw keys on a pty pipe where stty works, and a line otherwise. printer.Prompt takes it for choosing and confirming, and the existing call sites of the keyboard library are unchanged. - printer.KeySelect is the key-driven selection; readKey decodes the keys, including the arrow sequences of both cursor modes. - The version selection of use and search and the confirmations use the prompt; the line input stays the fallback. - The mintty check drives the down arrow in both modes and checks that the pipe mode reads the keys raw. --- cmd/commands/choose_line_test.go | 36 ++-- cmd/commands/gitbash_mintty_windows_test.go | 21 +- cmd/commands/search.go | 21 +- cmd/commands/search_line_test.go | 41 ++-- cmd/commands/use.go | 33 ++- internal/shared/printer/confirm.go | 16 +- internal/shared/printer/confirm_test.go | 72 +++++-- internal/shared/printer/input.go | 102 ++++++++++ internal/shared/printer/keys.go | 97 +++++++++ internal/shared/printer/keys_test.go | 77 +++++++ internal/shared/printer/keyselect.go | 215 ++++++++++++++++++++ internal/shared/printer/keyselect_test.go | 126 ++++++++++++ internal/shared/printer/rawtty_other.go | 36 ++++ internal/shared/printer/rawtty_windows.go | 77 +++++++ internal/shared/printer/select_line.go | 30 +-- internal/shared/util/tty.go | 7 + scripts/gitbash-mintty-test.ps1 | 36 +++- 17 files changed, 918 insertions(+), 125 deletions(-) create mode 100644 internal/shared/printer/input.go create mode 100644 internal/shared/printer/keys.go create mode 100644 internal/shared/printer/keys_test.go create mode 100644 internal/shared/printer/keyselect.go create mode 100644 internal/shared/printer/keyselect_test.go create mode 100644 internal/shared/printer/rawtty_other.go create mode 100644 internal/shared/printer/rawtty_windows.go diff --git a/cmd/commands/choose_line_test.go b/cmd/commands/choose_line_test.go index 53fb4ca3..f643cfe1 100644 --- a/cmd/commands/choose_line_test.go +++ b/cmd/commands/choose_line_test.go @@ -18,8 +18,10 @@ package commands import ( "bytes" - "os" + "strings" "testing" + + "github.com/version-fox/vfox/internal/shared/printer" ) func TestSelectVersionByLineReportsReadError(t *testing.T) { @@ -30,29 +32,27 @@ func TestSelectVersionByLineReportsReadError(t *testing.T) { } } -// Without key presses chooseVersion reads the choice from stdin, so the test -// gives stdin a pipe that holds the choice. -func TestChooseVersionWithoutKeysReadsALine(t *testing.T) { - reader, writer, err := os.Pipe() +// The down arrow in raw mode, then Enter, chooses the second version. +func TestSelectVersionWithRawKeys(t *testing.T) { + var out bytes.Buffer + prompt := printer.Prompt{Input: printer.RawKeys, In: strings.NewReader("\x1b[B\r"), Out: &out} + version, err := selectVersionWith(prompt, []string{"18.20.8", "20.19.0"}, "nodejs") if err != nil { - t.Fatal(err) + t.Fatalf("selectVersionWith() error: %v", err) } - t.Cleanup(func() { - reader.Close() - writer.Close() - }) - if _, err := writer.WriteString("20.19.0\n"); err != nil { - t.Fatal(err) + if version != "20.19.0" { + t.Errorf("selectVersionWith() = %q, want %q", version, "20.19.0") } - previous := os.Stdin - os.Stdin = reader - t.Cleanup(func() { os.Stdin = previous }) +} - version, err := chooseVersion(false, []string{"18.20.8", "20.19.0"}, "nodejs") +func TestSelectVersionWithLineReadsTheChoice(t *testing.T) { + var out bytes.Buffer + prompt := printer.Prompt{Input: printer.Line, In: strings.NewReader("2\n"), Out: &out} + version, err := selectVersionWith(prompt, []string{"18.20.8", "20.19.0"}, "nodejs") if err != nil { - t.Fatalf("chooseVersion() error: %v", err) + t.Fatalf("selectVersionWith() error: %v", err) } if version != "20.19.0" { - t.Errorf("chooseVersion() = %q, want %q", version, "20.19.0") + t.Errorf("selectVersionWith() = %q, want %q", version, "20.19.0") } } diff --git a/cmd/commands/gitbash_mintty_windows_test.go b/cmd/commands/gitbash_mintty_windows_test.go index 6d0e4ad1..24f91801 100644 --- a/cmd/commands/gitbash_mintty_windows_test.go +++ b/cmd/commands/gitbash_mintty_windows_test.go @@ -34,12 +34,13 @@ import ( // TestGitBashMinttySelection runs the terminal code in a Git Bash window: the // test binary runs under Git for Windows' bash.exe in a mintty window, as it // does for a person at mintty. scripts/gitbash-mintty-test.ps1 starts it and -// types the answers. When the test waits for one it creates a marker file in +// presses the keys. When the test waits for an answer it creates a marker file in // VFOX_TEST_GITBASH_MINTTY_DIR, and it writes its result there too. // // VFOX_TEST_GITBASH_MINTTY_STDIO says what the window gives the program: "pipe" -// for a pseudo terminal that reaches it as a pipe (the line input of the fix), -// or "console" for a pseudo console (the arrow-key selection). +// for a pseudo terminal that reaches it as a pipe, where the arrow keys work in +// raw mode, or "console" for a pseudo console, where the keyboard library reads +// them. func TestGitBashMinttySelection(t *testing.T) { dir := os.Getenv("VFOX_TEST_GITBASH_MINTTY_DIR") if dir == "" { @@ -54,7 +55,8 @@ func TestGitBashMinttySelection(t *testing.T) { fmt.Fprintf(&report, "stdin: %s\n", gitBashHandleKind(os.Stdin.Fd())) fmt.Fprintf(&report, "stdout: %s\n", gitBashHandleKind(os.Stdout.Fd())) isTTY, canReadKeys := util.IsTTY(), util.CanReadKeys() - fmt.Fprintf(&report, "IsTTY: %v\nCanReadKeys: %v\n", isTTY, canReadKeys) + input := printer.InputFor() + fmt.Fprintf(&report, "IsTTY: %v\nCanReadKeys: %v\ninput: %v\n", isTTY, canReadKeys, input) markWaiting(t, dir, "select") version, selectErr := selectFromOptions([]string{"18.20.8", "20.19.0"}, "nodejs") @@ -64,12 +66,11 @@ func TestGitBashMinttySelection(t *testing.T) { confirmed, confirmErr := printer.Confirm(&pterm.DefaultInteractiveConfirm, "Proceed with the check?") fmt.Fprintf(&report, "confirmed: %v, error: %v\n", confirmed, confirmErr) - ok := isTTY && selectErr == nil && version == "20.19.0" && confirmErr == nil && confirmed - if stdio == "pipe" { - ok = ok && !canReadKeys - } else { - ok = ok && canReadKeys + want := printer.RawKeys + if stdio == "console" { + want = printer.Keyboard } + ok := isTTY && input == want && selectErr == nil && version == "20.19.0" && confirmErr == nil && confirmed if err := os.WriteFile(filepath.Join(dir, "result.txt"), []byte(report.String()), 0o644); err != nil { t.Fatal(err) } @@ -78,7 +79,7 @@ func TestGitBashMinttySelection(t *testing.T) { } } -// markWaiting tells the driver that the test is about to wait for the input of step. +// markWaiting tells the driver that the test is about to wait for the answer to step. func markWaiting(t *testing.T, dir, step string) { t.Helper() if err := os.WriteFile(filepath.Join(dir, step+".ready"), nil, 0o644); err != nil { diff --git a/cmd/commands/search.go b/cmd/commands/search.go index d40fec56..77cbcd0e 100644 --- a/cmd/commands/search.go +++ b/cmd/commands/search.go @@ -19,7 +19,6 @@ package commands import ( "context" "fmt" - "io" "math" "os" "strings" @@ -95,8 +94,9 @@ func RunSearch(sdkName string, availableArgs []string) error { return nil } - if !util.CanReadKeys() { - return installByLine(source, os.Stdin, os.Stdout, options, installedVersions, sdkName) + prompt := printer.StdinPrompt() + if prompt.Input != printer.Keyboard { + return installChosen(source, prompt, options, installedVersions, sdkName) } _, height, _ := terminal.GetSize(int(os.Stdout.Fd())) kvSelect := printer.PageKVSelect{ @@ -135,17 +135,10 @@ type versionInstaller interface { Install(version sdk.Version) error } -// installByLine lets the person choose a version by reading a line, and installs -// it, for a terminal that cannot deliver single key presses. Cancelling installs -// nothing. -func installByLine(installer versionInstaller, in io.Reader, out io.Writer, options []*printer.KV, installed util.Set[string], sdkName string) error { - selected, err := (&printer.LineSelect{ - TopText: "Please select a version of " + sdkName + " to install", - Options: options, - DisabledOptions: installed, - In: in, - Out: out, - }).Show() +// installChosen lets the person choose a version with prompt, which is not the +// keyboard, and installs it. Cancelling installs nothing. +func installChosen(installer versionInstaller, prompt printer.Prompt, options []*printer.KV, installed util.Set[string], sdkName string) error { + selected, err := prompt.Choose("Please select a version of "+sdkName+" to install", options, installed) if err != nil { return fmt.Errorf("select version error: %w", err) } diff --git a/cmd/commands/search_line_test.go b/cmd/commands/search_line_test.go index c6451c25..5ac2362b 100644 --- a/cmd/commands/search_line_test.go +++ b/cmd/commands/search_line_test.go @@ -51,12 +51,13 @@ func searchOptions() []*printer.KV { } } -func TestInstallByLineInstallsTheChosenVersion(t *testing.T) { +func TestInstallChosenInstallsTheChosenVersion(t *testing.T) { var installer recordingInstaller var out bytes.Buffer - err := installByLine(&installer, strings.NewReader("2\n"), &out, searchOptions(), util.NewSet[string](), "nodejs") + prompt := printer.Prompt{Input: printer.Line, In: strings.NewReader("2\n"), Out: &out} + err := installChosen(&installer, prompt, searchOptions(), util.NewSet[string](), "nodejs") if err != nil { - t.Fatalf("installByLine() error: %v", err) + t.Fatalf("installChosen() error: %v", err) } if len(installer.installed) != 1 || installer.installed[0] != "20.19.0" { t.Errorf("installed %v, want [20.19.0]", installer.installed) @@ -66,25 +67,40 @@ func TestInstallByLineInstallsTheChosenVersion(t *testing.T) { } } -func TestInstallByLineCancelInstallsNothing(t *testing.T) { +func TestInstallChosenWithRawKeys(t *testing.T) { var installer recordingInstaller var out bytes.Buffer - if err := installByLine(&installer, strings.NewReader("\n"), &out, searchOptions(), util.NewSet[string](), "nodejs"); err != nil { - t.Fatalf("installByLine() error: %v", err) + prompt := printer.Prompt{Input: printer.RawKeys, In: strings.NewReader("\x1b[B\r"), Out: &out} + err := installChosen(&installer, prompt, searchOptions(), util.NewSet[string](), "nodejs") + if err != nil { + t.Fatalf("installChosen() error: %v", err) + } + if len(installer.installed) != 1 || installer.installed[0] != "20.19.0" { + t.Errorf("installed %v, want [20.19.0]", installer.installed) + } +} + +func TestInstallChosenCancelInstallsNothing(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + prompt := printer.Prompt{Input: printer.Line, In: strings.NewReader("\n"), Out: &out} + if err := installChosen(&installer, prompt, searchOptions(), util.NewSet[string](), "nodejs"); err != nil { + t.Fatalf("installChosen() error: %v", err) } if len(installer.installed) != 0 { t.Errorf("installed %v after a cancelled selection, want nothing", installer.installed) } } -func TestInstallByLineRefusesAnInstalledVersion(t *testing.T) { +func TestInstallChosenRefusesAnInstalledVersion(t *testing.T) { var installer recordingInstaller var out bytes.Buffer installed := util.NewSet[string]() installed.Add("20.19.0") - err := installByLine(&installer, strings.NewReader("2\n1\n"), &out, searchOptions(), installed, "nodejs") + prompt := printer.Prompt{Input: printer.Line, In: strings.NewReader("2\n1\n"), Out: &out} + err := installChosen(&installer, prompt, searchOptions(), installed, "nodejs") if err != nil { - t.Fatalf("installByLine() error: %v", err) + t.Fatalf("installChosen() error: %v", err) } if len(installer.installed) != 1 || installer.installed[0] != "18.20.8" { t.Errorf("installed %v, want [18.20.8] after the installed version was refused", installer.installed) @@ -94,12 +110,13 @@ func TestInstallByLineRefusesAnInstalledVersion(t *testing.T) { } } -func TestInstallByLineReportsReadError(t *testing.T) { +func TestInstallChosenReportsReadError(t *testing.T) { var installer recordingInstaller var out bytes.Buffer - err := installByLine(&installer, failingReader{}, &out, searchOptions(), util.NewSet[string](), "nodejs") + prompt := printer.Prompt{Input: printer.Line, In: failingReader{}, Out: &out} + err := installChosen(&installer, prompt, searchOptions(), util.NewSet[string](), "nodejs") if err == nil || !strings.Contains(err.Error(), "select version error") { - t.Fatalf("installByLine() error = %v, want a select version error", err) + t.Fatalf("installChosen() error = %v, want a select version error", err) } if len(installer.installed) != 0 { t.Errorf("installed %v after a failed read, want nothing", installer.installed) diff --git a/cmd/commands/use.go b/cmd/commands/use.go index 99a6c5e5..c120e156 100644 --- a/cmd/commands/use.go +++ b/cmd/commands/use.go @@ -177,16 +177,13 @@ func resolveVersion(sdkSource sdk.Sdk, manager *internal.Manager, version sdk.Ve return sdk.Version(selectedVersion), nil } -// selectFromOptions displays an interactive selection prompt +// selectFromOptions displays an interactive selection prompt. Where the keys of +// the terminal cannot be read by the keyboard library, the choice is made with +// the arrow keys in raw mode, or else as a line (see printer.Prompt). func selectFromOptions(options []string, sdkName string) (string, error) { - return chooseVersion(util.CanReadKeys(), options, sdkName) -} - -// chooseVersion shows the selection and takes the arrow keys when keys is true. -// Without key presses it reads the choice as a line. -func chooseVersion(keys bool, options []string, sdkName string) (string, error) { - if !keys { - return selectVersionByLine(os.Stdin, os.Stdout, options, sdkName) + prompt := printer.StdinPrompt() + if prompt.Input != printer.Keyboard { + return selectVersionWith(prompt, options, sdkName) } selectPrinter := pterm.InteractiveSelectPrinter{ TextStyle: &pterm.ThemeDefault.DefaultText, @@ -211,20 +208,20 @@ func chooseVersion(keys bool, options []string, sdkName string) (string, error) return result, nil } -// selectVersionByLine chooses a version by reading lines, for a terminal that -// cannot deliver single key presses (Git Bash in mintty). A cancelled selection -// is an error, since there is then no version to use. +// selectVersionByLine chooses a version by reading a line from in, for a terminal +// that cannot deliver single key presses. func selectVersionByLine(in io.Reader, out io.Writer, options []string, sdkName string) (string, error) { + return selectVersionWith(printer.Prompt{Input: printer.Line, In: in, Out: out}, options, sdkName) +} + +// selectVersionWith chooses a version with prompt, which is not the keyboard. A +// cancelled selection is an error, since there is then no version to use. +func selectVersionWith(prompt printer.Prompt, options []string, sdkName string) (string, error) { entries := make([]*printer.KV, len(options)) for i, option := range options { entries[i] = &printer.KV{Key: option, Value: option} } - selected, err := (&printer.LineSelect{ - TopText: fmt.Sprintf("Please select a version of %s", sdkName), - Options: entries, - In: in, - Out: out, - }).Show() + selected, err := prompt.Choose(fmt.Sprintf("Please select a version of %s", sdkName), entries, nil) if err != nil { return "", fmt.Errorf("version selection failed: %w", err) } diff --git a/internal/shared/printer/confirm.go b/internal/shared/printer/confirm.go index d6485808..2a9c55b0 100644 --- a/internal/shared/printer/confirm.go +++ b/internal/shared/printer/confirm.go @@ -20,25 +20,15 @@ import ( "bufio" "fmt" "io" - "os" "strings" "github.com/pterm/pterm" - "github.com/version-fox/vfox/internal/shared/util" ) -// Confirm asks a yes-or-no question with p. Where key presses can be read it -// behaves as p.Show; elsewhere the answer is a line (see util.CanReadKeys). +// Confirm asks a yes-or-no question with p, on the terminal of the process: see +// StdinPrompt. func Confirm(p *pterm.InteractiveConfirmPrinter, text string) (bool, error) { - return confirm(util.CanReadKeys(), p, text, os.Stdin, os.Stdout) -} - -// confirm asks with p when keys is true, and otherwise reads the answer as a line from in. -func confirm(keys bool, p *pterm.InteractiveConfirmPrinter, text string, in io.Reader, out io.Writer) (bool, error) { - if keys { - return p.Show(text) - } - return lineConfirm(in, out, *p, text) + return StdinPrompt().Confirm(p, text) } // lineConfirm asks text and reads an answer line. The confirm or reject text, or diff --git a/internal/shared/printer/confirm_test.go b/internal/shared/printer/confirm_test.go index 0489fb46..d9239eed 100644 --- a/internal/shared/printer/confirm_test.go +++ b/internal/shared/printer/confirm_test.go @@ -70,27 +70,6 @@ func TestLineConfirmReportsReadError(t *testing.T) { } } -func TestConfirmWithoutKeysReadsALine(t *testing.T) { - p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} - var out bytes.Buffer - got, err := confirm(false, &p, "Install?", strings.NewReader("y\n"), &out) - if err != nil || !got { - t.Fatalf("confirm(false) = %v, %v, want true", got, err) - } -} - -func TestShortAnswer(t *testing.T) { - for _, tc := range []struct{ text, fallback, want string }{ - {"", "y", "y"}, - {"Yes", "n", "y"}, - {"No", "y", "n"}, - } { - if got := shortAnswer(tc.text, tc.fallback); got != tc.want { - t.Errorf("shortAnswer(%q, %q) = %q, want %q", tc.text, tc.fallback, got, tc.want) - } - } -} - func TestLineConfirmShowsDefaultInUpperCase(t *testing.T) { p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} var out bytes.Buffer @@ -121,3 +100,54 @@ func TestLineConfirmUsesDefaultTextWhenNoQuestion(t *testing.T) { t.Errorf("prompt = %q, want the default text", out.String()) } } + +func TestPromptConfirmOnALine(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + got, err := Prompt{Input: Line, In: strings.NewReader("y\n"), Out: &out}.Confirm(&p, "Install?") + if err != nil || !got { + t.Fatalf("Confirm() = %v, %v, want true", got, err) + } +} + +func TestPromptConfirmWithKeys(t *testing.T) { + cases := []struct { + name string + input string + defaultValue bool + want bool + }{ + {"y", "y", false, true}, + {"Y", "Y", false, true}, + {"n after a stray key", "xn", true, false}, + {"enter takes the default", "\r", true, true}, + {"enter takes the default no", "\r", false, false}, + {"ctrl-c refuses", "\x03", true, false}, + {"end of input refuses", "", true, false}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + p := pterm.InteractiveConfirmPrinter{DefaultValue: tc.defaultValue, ConfirmText: "Yes", RejectText: "No", Delimiter: ": "} + var out bytes.Buffer + got, err := Prompt{Input: RawKeys, In: strings.NewReader(tc.input), Out: &out}.Confirm(&p, "Install?") + if err != nil { + t.Fatalf("Confirm() error: %v", err) + } + if got != tc.want { + t.Errorf("Confirm() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestShortAnswer(t *testing.T) { + for _, tc := range []struct{ text, fallback, want string }{ + {"", "y", "y"}, + {"Yes", "n", "y"}, + {"No", "y", "n"}, + } { + if got := shortAnswer(tc.text, tc.fallback); got != tc.want { + t.Errorf("shortAnswer(%q, %q) = %q, want %q", tc.text, tc.fallback, got, tc.want) + } + } +} diff --git a/internal/shared/printer/input.go b/internal/shared/printer/input.go new file mode 100644 index 00000000..d42165d9 --- /dev/null +++ b/internal/shared/printer/input.go @@ -0,0 +1,102 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "io" + "os" + + "github.com/pterm/pterm" + "github.com/version-fox/vfox/internal/shared/util" +) + +// Input says how a prompt takes its answer. +type Input int + +const ( + // Keyboard reads key presses with the keyboard library: a console, or a Unix + // terminal. The prompts of pterm do that. + Keyboard Input = iota + // RawKeys reads key presses from a pty that reaches the program as a pipe, such + // as Git Bash in mintty. stty puts that terminal in raw mode for the prompt. + RawKeys + // Line reads a line: a pipe, a file, or a terminal that cannot be put in raw + // mode. + Line +) + +// InputFor says how the prompts of the process take their answers. +func InputFor() Input { + if util.CanReadKeys() { + return Keyboard + } + if util.IsPtyInput() && rawModeAvailable() { + return RawKeys + } + return Line +} + +// Prompt says how a prompt takes its answer: from key presses or from a line, and +// from where. +type Prompt struct { + Input Input + // Terminal is the terminal that RawKeys puts in raw mode. It may be nil. + Terminal *os.File + In io.Reader + Out io.Writer +} + +// StdinPrompt is the prompt of the process: its answer comes from stdin, and its +// text goes to stdout. +func StdinPrompt() Prompt { + return Prompt{Input: InputFor(), Terminal: os.Stdin, In: os.Stdin, Out: os.Stdout} +} + +// Choose lets the person pick one of options. It handles RawKeys and Line; the +// Keyboard selection is the select printer of pterm, which the caller uses. +func (p Prompt) Choose(topText string, options []*KV, disabled util.Set[string]) (*KV, error) { + if p.Input == RawKeys { + return (&KeySelect{ + TopText: topText, + Options: options, + DisabledOptions: disabled, + Terminal: p.Terminal, + In: p.In, + Out: p.Out, + }).Show() + } + return (&LineSelect{ + TopText: topText, + Options: options, + DisabledOptions: disabled, + In: p.In, + Out: p.Out, + }).Show() +} + +// Confirm asks a yes-or-no question. The Keyboard answer is q's own Show, which +// reads stdin itself. +func (p Prompt) Confirm(q *pterm.InteractiveConfirmPrinter, text string) (bool, error) { + switch p.Input { + case RawKeys: + return confirmKeys(p.Terminal, p.In, p.Out, *q, text) + case Line: + return lineConfirm(p.In, p.Out, *q, text) + default: + return q.Show(text) + } +} diff --git a/internal/shared/printer/keys.go b/internal/shared/printer/keys.go new file mode 100644 index 00000000..a5bf740c --- /dev/null +++ b/internal/shared/printer/keys.go @@ -0,0 +1,97 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import "bufio" + +// keyKind says what a key press asks for. +type keyKind int + +const ( + keyOther keyKind = iota // a key the prompts do not use + keyRune // a printable character, which filters the list + keyUp // the up arrow + keyDown // the down arrow + keyEnter // Enter + keyBackspace // Backspace or Delete + keyCancel // Ctrl-C or Ctrl-D +) + +// keyPress is one key press, read from a terminal in raw mode. +type keyPress struct { + kind keyKind + r rune // the character, for keyRune +} + +// readKey reads one key press from in. An arrow key arrives as an escape +// sequence: ESC [ A to ESC [ D, or ESC O A to ESC O D. +func readKey(in *bufio.Reader) (keyPress, error) { + b, err := in.ReadByte() + if err != nil { + return keyPress{}, err + } + switch b { + case 0x1b: + return readEscape(in), nil + case '\r', '\n': + return keyPress{kind: keyEnter}, nil + case 0x7f, 0x08: + return keyPress{kind: keyBackspace}, nil + case 0x03, 0x04: + return keyPress{kind: keyCancel}, nil + } + if b < 0x20 { + return keyPress{kind: keyOther}, nil + } + if err := in.UnreadByte(); err != nil { + return keyPress{}, err + } + r, _, err := in.ReadRune() + if err != nil { + return keyPress{}, err + } + return keyPress{kind: keyRune, r: r}, nil +} + +// readEscape reads what follows an escape. A sequence that is not an arrow key, +// or an escape with nothing after it, is a key the prompts do not use. +func readEscape(in *bufio.Reader) keyPress { + next, err := in.ReadByte() + if err != nil { + return keyPress{kind: keyOther} + } + if next != '[' && next != 'O' { + _ = in.UnreadByte() + return keyPress{kind: keyOther} + } + // Parameters, such as the 1;5 of ESC [ 1 ; 5 A, come before the final byte. + for { + c, err := in.ReadByte() + if err != nil { + return keyPress{kind: keyOther} + } + if c >= 0x40 && c <= 0x7e { + switch c { + case 'A': + return keyPress{kind: keyUp} + case 'B': + return keyPress{kind: keyDown} + } + return keyPress{kind: keyOther} + } + } +} diff --git a/internal/shared/printer/keys_test.go b/internal/shared/printer/keys_test.go new file mode 100644 index 00000000..3665c9d7 --- /dev/null +++ b/internal/shared/printer/keys_test.go @@ -0,0 +1,77 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bufio" + "io" + "strings" + "testing" +) + +func TestReadKey(t *testing.T) { + cases := []struct { + name string + input string + want keyPress + }{ + {"up", "\x1b[A", keyPress{kind: keyUp}}, + {"down", "\x1b[B", keyPress{kind: keyDown}}, + {"application cursor up", "\x1bOA", keyPress{kind: keyUp}}, + {"application cursor down", "\x1bOB", keyPress{kind: keyDown}}, + {"modified down", "\x1b[1;5B", keyPress{kind: keyDown}}, + {"carriage return", "\r", keyPress{kind: keyEnter}}, + {"line feed", "\n", keyPress{kind: keyEnter}}, + {"delete", "\x7f", keyPress{kind: keyBackspace}}, + {"backspace", "\x08", keyPress{kind: keyBackspace}}, + {"ctrl-c", "\x03", keyPress{kind: keyCancel}}, + {"ctrl-d", "\x04", keyPress{kind: keyCancel}}, + {"letter", "a", keyPress{kind: keyRune, r: 'a'}}, + {"multi-byte character", "é", keyPress{kind: keyRune, r: 'é'}}, + {"other control", "\x01", keyPress{kind: keyOther}}, + {"escape before a letter", "\x1ba", keyPress{kind: keyOther}}, + {"unknown sequence", "\x1b[2~", keyPress{kind: keyOther}}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + got, err := readKey(bufio.NewReader(strings.NewReader(tc.input))) + if err != nil { + t.Fatalf("readKey() error: %v", err) + } + if got != tc.want { + t.Errorf("readKey(%q) = %+v, want %+v", tc.input, got, tc.want) + } + }) + } +} + +func TestReadKeyLeavesTheNextKey(t *testing.T) { + // The escape that is not an arrow key leaves its following letter for the next read. + in := bufio.NewReader(strings.NewReader("\x1ba")) + if got, err := readKey(in); err != nil || got.kind != keyOther { + t.Fatalf("first readKey() = %+v, %v, want an unused key", got, err) + } + if got, err := readKey(in); err != nil || got != (keyPress{kind: keyRune, r: 'a'}) { + t.Errorf("second readKey() = %+v, %v, want the letter a", got, err) + } +} + +func TestReadKeyEndOfInput(t *testing.T) { + if _, err := readKey(bufio.NewReader(strings.NewReader(""))); err != io.EOF { + t.Errorf("readKey() error = %v, want io.EOF", err) + } +} diff --git a/internal/shared/printer/keyselect.go b/internal/shared/printer/keyselect.go new file mode 100644 index 00000000..4a14377f --- /dev/null +++ b/internal/shared/printer/keyselect.go @@ -0,0 +1,215 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bufio" + "fmt" + "io" + "os" + "strings" + + "github.com/pterm/pterm" + "github.com/version-fox/vfox/internal/shared/util" +) + +// keyHint says what the keys do, under the list. +const keyHint = "Up and Down move, typing filters the list, Enter chooses, Ctrl-C cancels" + +// KeySelect chooses one of Options by key presses. The arrow keys move the +// highlight, typed text filters the list, Enter chooses, and Ctrl-C cancels. It +// serves a terminal that delivers key presses in raw mode (see Prompt.Choose). +type KeySelect struct { + TopText string + Options []*KV + // DisabledOptions are listed as installed and cannot be chosen. It may be nil. + DisabledOptions util.Set[string] + // Terminal, when set, is put in raw mode for the selection and restored after it. + Terminal *os.File + In io.Reader + Out io.Writer +} + +// Show lists the options and reads key presses until one is chosen. It returns +// nil when the selection is cancelled or the input ends. +func (s *KeySelect) Show() (*KV, error) { + if s.Terminal != nil { + restore, err := enterRawMode(s.Terminal) + if err != nil { + return nil, fmt.Errorf("raw mode: %w", err) + } + defer restore() + } + input := bufio.NewReader(s.In) + filter, notice := "", "" + highlight, drawn := 0, 0 + for { + matches := fuzzyMatches(s.Options, filter) + if highlight >= len(matches) { + highlight = 0 + } + drawn = s.draw(drawn, filter, matches, highlight, notice) + notice = "" + + press, err := readKey(input) + if err == io.EOF { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("read selection: %w", err) + } + switch press.kind { + case keyUp: + if n := len(matches); n > 0 { + highlight = (highlight + n - 1) % n + } + case keyDown: + if n := len(matches); n > 0 { + highlight = (highlight + 1) % n + } + case keyRune: + filter += string(press.r) + highlight = 0 + case keyBackspace: + if runes := []rune(filter); len(runes) > 0 { + filter = string(runes[:len(runes)-1]) + } + highlight = 0 + case keyEnter: + if len(matches) == 0 { + continue + } + chosen := matches[highlight] + if isDisabledIn(s.DisabledOptions, chosen.Key) { + notice = chosen.Key + " is already installed, choose another version." + continue + } + return chosen, nil + case keyCancel: + return nil, nil + } + } +} + +// draw writes the title, the matches around the highlight, the notice and the +// hint. It starts over the block drawn last time, which is drawn lines long, and +// it returns the length of the block it wrote. +func (s *KeySelect) draw(drawn int, filter string, matches []*KV, highlight int, notice string) int { + var b strings.Builder + if drawn > 0 { + fmt.Fprintf(&b, "\x1b[%dA", drawn) + } + b.WriteString("\r\x1b[J") + + var lines []string + if filter == "" { + lines = append(lines, s.TopText+":") + } else { + lines = append(lines, fmt.Sprintf("%s [filter: %s]:", s.TopText, filter)) + } + if len(matches) == 0 { + lines = append(lines, " No version matches the filter.") + } + start := 0 + if highlight >= lineSelectLimit { + start = highlight - lineSelectLimit + 1 + } + end := min(start+lineSelectLimit, len(matches)) + for i := start; i < end; i++ { + marker := " " + if i == highlight { + marker = "-> " + } + label := matches[i].Value + if isDisabledIn(s.DisabledOptions, matches[i].Key) { + label += " (installed)" + } + lines = append(lines, marker+label) + } + if more := len(matches) - end; more > 0 { + lines = append(lines, fmt.Sprintf(" ... %d more, type part of a version to narrow the list", more)) + } + if notice != "" { + lines = append(lines, notice) + } + lines = append(lines, keyHint) + for _, line := range lines { + b.WriteString(line) + b.WriteString("\n") + } + fmt.Fprint(s.Out, b.String()) + return len(lines) +} + +// confirmKeys asks a yes-or-no question with key presses, on a terminal in raw +// mode when terminal is set: y or n settles it, Enter gives the default, and +// Ctrl-C refuses. +func confirmKeys(terminal *os.File, in io.Reader, out io.Writer, p pterm.InteractiveConfirmPrinter, text string) (bool, error) { + if terminal != nil { + restore, err := enterRawMode(terminal) + if err != nil { + return false, fmt.Errorf("raw mode: %w", err) + } + defer restore() + } + if text == "" { + text = p.DefaultText + } + yes, no := shortAnswer(p.ConfirmText, "y"), shortAnswer(p.RejectText, "n") + shownYes, shownNo := yes, no + if p.DefaultValue { + shownYes = strings.ToUpper(yes) + } else { + shownNo = strings.ToUpper(no) + } + fmt.Fprintf(out, "%s [%s/%s]%s", text, shownYes, shownNo, p.Delimiter) + + input := bufio.NewReader(in) + for { + press, err := readKey(input) + if err == io.EOF { + fmt.Fprintln(out) + return false, nil + } + if err != nil { + return false, fmt.Errorf("read answer: %w", err) + } + switch press.kind { + case keyEnter: + return p.DefaultValue, answered(out, p, p.DefaultValue) + case keyCancel: + return false, answered(out, p, false) + case keyRune: + switch strings.ToLower(string(press.r)) { + case yes: + return true, answered(out, p, true) + case no: + return false, answered(out, p, false) + } + } + } +} + +// answered shows the answer that was given, and returns the error of writing it. +func answered(out io.Writer, p pterm.InteractiveConfirmPrinter, value bool) error { + text := p.RejectText + if value { + text = p.ConfirmText + } + _, err := fmt.Fprintln(out, text) + return err +} diff --git a/internal/shared/printer/keyselect_test.go b/internal/shared/printer/keyselect_test.go new file mode 100644 index 00000000..66c70d9e --- /dev/null +++ b/internal/shared/printer/keyselect_test.go @@ -0,0 +1,126 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bytes" + "strings" + "testing" + + "github.com/version-fox/vfox/internal/shared/util" +) + +// runKeySelect shows a KeySelect fed with the key presses in input. +func runKeySelect(t *testing.T, input string, options []*KV, disabled util.Set[string]) (*KV, string, error) { + t.Helper() + var out bytes.Buffer + s := &KeySelect{ + TopText: "Please select a version of nodejs", + Options: options, + DisabledOptions: disabled, + In: strings.NewReader(input), + Out: &out, + } + chosen, err := s.Show() + return chosen, out.String(), err +} + +func TestKeySelectDownArrowChoosesTheNextEntry(t *testing.T) { + chosen, _, err := runKeySelect(t, "\x1b[B\r", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "22.15.0") +} + +func TestKeySelectUpArrowWrapsToTheLastEntry(t *testing.T) { + chosen, _, err := runKeySelect(t, "\x1b[A\r", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "18.20.8") +} + +func TestKeySelectApplicationCursorKeys(t *testing.T) { + chosen, _, err := runKeySelect(t, "\x1bOB\x1bOB\r", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "20.19.0") +} + +func TestKeySelectTypedTextFiltersThenTheArrowChooses(t *testing.T) { + chosen, out, err := runKeySelect(t, "lts\x1b[B\r", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "20.19.0") + if !strings.Contains(out, "[filter: lts]") { + t.Errorf("output does not show the filter:\n%s", out) + } +} + +func TestKeySelectBackspaceRemovesTheLastCharacter(t *testing.T) { + chosen, _, err := runKeySelect(t, "ltz\x7f\r", lineSelectOptions(), nil) + assertChosen(t, chosen, err, "22.15.0") +} + +func TestKeySelectCtrlCCancels(t *testing.T) { + chosen, _, err := runKeySelect(t, "\x1b[B\x03", lineSelectOptions(), nil) + if err != nil || chosen != nil { + t.Fatalf("Show() = %v, %v, want a cancelled selection", chosen, err) + } +} + +func TestKeySelectEndOfInputCancels(t *testing.T) { + chosen, _, err := runKeySelect(t, "", lineSelectOptions(), nil) + if err != nil || chosen != nil { + t.Fatalf("Show() = %v, %v, want a cancelled selection", chosen, err) + } +} + +func TestKeySelectRefusesAnInstalledVersion(t *testing.T) { + disabled := util.NewSet[string]() + disabled.Add("22.15.0") + chosen, out, err := runKeySelect(t, "\x1b[B\r\x1b[B\r", lineSelectOptions(), disabled) + assertChosen(t, chosen, err, "20.19.0") + if !strings.Contains(out, "22.15.0 is already installed") { + t.Errorf("output does not refuse the installed version:\n%s", out) + } + if !strings.Contains(out, "22.15.0 (LTS Jod) (installed)") { + t.Errorf("output does not mark the installed version:\n%s", out) + } +} + +func TestKeySelectDrawsTheHighlight(t *testing.T) { + _, out, err := runKeySelect(t, "\x1b[B\x03", lineSelectOptions(), nil) + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if !strings.Contains(out, "-> 22.15.0 (LTS Jod)") { + t.Errorf("the highlight does not move with the down arrow:\n%s", out) + } +} + +func TestKeySelectRedrawsOverTheBlock(t *testing.T) { + // Each key press redraws the block: the cursor goes back over the lines of + // the block drawn last time. + _, out, err := runKeySelect(t, "\x1b[B\x03", lineSelectOptions(), nil) + if err != nil { + t.Fatalf("Show() error: %v", err) + } + if !strings.Contains(out, "\x1b[") || !strings.Contains(out, "A\r\x1b[J") { + t.Errorf("the second draw does not go back over the first:\n%q", out) + } +} + +func TestKeySelectReportsReadError(t *testing.T) { + var out bytes.Buffer + s := &KeySelect{TopText: "Please select a version of nodejs", Options: lineSelectOptions(), In: brokenReader{}, Out: &out} + chosen, err := s.Show() + if err == nil || chosen != nil { + t.Fatalf("Show() = %v, %v, want an error for a failing read", chosen, err) + } +} diff --git a/internal/shared/printer/rawtty_other.go b/internal/shared/printer/rawtty_other.go new file mode 100644 index 00000000..f55361e3 --- /dev/null +++ b/internal/shared/printer/rawtty_other.go @@ -0,0 +1,36 @@ +//go:build !windows + +// Copyright 2026 vfox project contributors +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package printer + +import ( + "errors" + "os" +) + +var errNoRawMode = errors.New("the raw mode is switched with stty, on Windows only") + +// rawModeAvailable reports false: off Windows the keyboard library reads the +// terminal, so no pipe needs raw mode. +func rawModeAvailable() bool { + return false +} + +// enterRawMode is not reached off Windows, where the keyboard library reads key +// presses itself. +func enterRawMode(*os.File) (func(), error) { + return nil, errNoRawMode +} diff --git a/internal/shared/printer/rawtty_windows.go b/internal/shared/printer/rawtty_windows.go new file mode 100644 index 00000000..64b2ed01 --- /dev/null +++ b/internal/shared/printer/rawtty_windows.go @@ -0,0 +1,77 @@ +/* + * Copyright 2026 Han Li and contributors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package printer + +import ( + "bytes" + "errors" + "fmt" + "io" + "os" + "os/exec" + "strings" +) + +// A pty that reaches a native program as a pipe, as Git Bash in mintty gives it, +// cannot be read a key at a time by the keyboard library. stty puts it in raw +// mode instead: no line buffering, no echo, and no signals from Ctrl-C, which then +// arrive as a key. stty comes with Git for Windows, next to bash. + +// runStty runs stty on terminal with args, and writes its output to out, which may +// be nil. +func runStty(terminal *os.File, out io.Writer, args ...string) error { + path, err := exec.LookPath("stty") + if err != nil { + return err + } + var stderr bytes.Buffer + cmd := exec.Command(path, args...) + cmd.Stdin = terminal + cmd.Stdout = out + cmd.Stderr = &stderr + if err := cmd.Run(); err != nil { + return fmt.Errorf("stty %s: %w: %s", strings.Join(args, " "), err, strings.TrimSpace(stderr.String())) + } + return nil +} + +// rawModeAvailable reports whether stdin can be switched with stty. +func rawModeAvailable() bool { + var mode bytes.Buffer + return runStty(os.Stdin, &mode, "-g") == nil +} + +// enterRawMode puts terminal in raw mode, and returns the function that restores +// the mode it had. +func enterRawMode(terminal *os.File) (func(), error) { + var saved bytes.Buffer + if err := runStty(terminal, &saved, "-g"); err != nil { + return nil, err + } + state := strings.TrimSpace(saved.String()) + if state == "" { + return nil, errors.New("stty printed no terminal mode") + } + if err := runStty(terminal, nil, "-icanon", "-echo", "-isig", "min", "1", "time", "0"); err != nil { + return nil, err + } + return func() { + if err := runStty(terminal, nil, state); err != nil { + fmt.Fprintf(os.Stderr, "could not restore the terminal mode: %v\n", err) + } + }, nil +} diff --git a/internal/shared/printer/select_line.go b/internal/shared/printer/select_line.go index 491e5c2b..b567ec7d 100644 --- a/internal/shared/printer/select_line.go +++ b/internal/shared/printer/select_line.go @@ -27,12 +27,11 @@ import ( "github.com/version-fox/vfox/internal/shared/util" ) -// lineSelectLimit is how many matches LineSelect lists at a time. +// lineSelectLimit is how many matches a selection lists at a time. const lineSelectLimit = 20 // LineSelect chooses one of Options by reading lines. It serves terminals that -// cannot deliver single key presses (see util.CanReadKeys), such as Git Bash in -// mintty. +// cannot deliver single key presses (see util.CanReadKeys), such as a pipe. type LineSelect struct { TopText string Options []*KV @@ -77,7 +76,7 @@ func (s *LineSelect) Show() (*KV, error) { filter = line continue } - if s.isDisabled(chosen.Key) { + if isDisabledIn(s.DisabledOptions, chosen.Key) { fmt.Fprintf(s.Out, "%s is already installed, choose another version.\n", chosen.Key) continue } @@ -85,11 +84,11 @@ func (s *LineSelect) Show() (*KV, error) { } } -// matches returns the options whose value fuzzily contains filter, in the order -// the plugin gave them. An empty filter matches every option. -func (s *LineSelect) matches(filter string) []*KV { +// fuzzyMatches returns the options whose value fuzzily contains filter, in the +// order the plugin gave them. An empty filter matches every option. +func fuzzyMatches(options []*KV, filter string) []*KV { var found []*KV - for _, option := range s.Options { + for _, option := range options { if fuzzy.MatchFold(filter, option.Value) { found = append(found, option) } @@ -97,6 +96,15 @@ func (s *LineSelect) matches(filter string) []*KV { return found } +// isDisabledIn reports whether key is among disabled, which may be nil. +func isDisabledIn(disabled util.Set[string], key string) bool { + return disabled != nil && disabled.Contains(key) +} + +func (s *LineSelect) matches(filter string) []*KV { + return fuzzyMatches(s.Options, filter) +} + // choose returns the option that line picks, or nil when line is a filter. A // key picks from all options and wins over a number, so that a version such as // "17" is never mistaken for the seventeenth entry; a number picks from the @@ -113,10 +121,6 @@ func (s *LineSelect) choose(line string, listed []*KV) *KV { return nil } -func (s *LineSelect) isDisabled(key string) bool { - return s.DisabledOptions != nil && s.DisabledOptions.Contains(key) -} - // render writes the title, the listed matches numbered, and the prompt. func (s *LineSelect) render(filter string, matches, listed []*KV) { if filter == "" { @@ -129,7 +133,7 @@ func (s *LineSelect) render(filter string, matches, listed []*KV) { } for i, option := range listed { label := option.Value - if s.isDisabled(option.Key) { + if isDisabledIn(s.DisabledOptions, option.Key) { label += " (installed)" } fmt.Fprintf(s.Out, " %d) %s\n", i+1, label) diff --git a/internal/shared/util/tty.go b/internal/shared/util/tty.go index 5a99088a..51ee056d 100644 --- a/internal/shared/util/tty.go +++ b/internal/shared/util/tty.go @@ -35,3 +35,10 @@ func IsTTY() bool { func CanReadKeys() bool { return canReadKeysFrom(os.Stdin.Fd()) } + +// IsPtyInput reports whether stdin is a Cygwin or MSYS2 pty, such as Git Bash in +// mintty. Its input reaches the program as a pipe, and stty can switch it to raw +// mode. +func IsPtyInput() bool { + return isCygwinTerminal(os.Stdin.Fd()) +} diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 index ccf897ca..715e63e9 100644 --- a/scripts/gitbash-mintty-test.ps1 +++ b/scripts/gitbash-mintty-test.ps1 @@ -32,6 +32,11 @@ param( [string] $MsysOptions = '', + [string] $TestRun = 'TestGitBashMinttySelection', + + [ValidateSet('selection', 'probe')] + [string] $Script = 'selection', + [ValidateRange(10, 1800)] [int] $TimeoutSeconds = 180 ) @@ -114,10 +119,10 @@ $runScript = @' #!/usr/bin/env bash export VFOX_TEST_GITBASH_MINTTY_DIR='__WORK__' export VFOX_TEST_GITBASH_MINTTY_STDIO='__STDIO__' -'__TEST__' -test.run '^TestGitBashMinttySelection$' -test.v +'__TEST__' -test.run '^__RUN__$' -test.v echo $? > '__UNIXWORK__/exit.txt' '@ -$runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__STDIO__', $Stdio).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork) +$runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__STDIO__', $Stdio).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork).Replace('__RUN__', $TestRun) [System.IO.File]::WriteAllText((Join-Path $WorkDir 'run.sh'), $runScript.Replace("`r`n", "`n") + "`n") # A window left over from an earlier run would be taken for this one. @@ -154,6 +159,20 @@ while ($handle -eq [IntPtr]::Zero) { } Write-Host "mintty window $handle, process $([VfoxWindow]::ProcessOf($handle))" +function Send-Char([IntPtr] $target, [int] $char) { + [void][VfoxWindow]::PostMessage($target, $WM_CHAR, [IntPtr]$char, [IntPtr]1) +} + +# A key press as the window sees it: WM_KEYDOWN and WM_KEYUP with the scan code. +function Send-VirtualKey([IntPtr] $target, [int] $key, [int] $scanCode, [bool] $extended) { + $extendedBit = if ($extended) { [long]1 -shl 24 } else { [long]0 } + $down = [long]1 -bor ([long]$scanCode -shl 16) -bor $extendedBit + $up = $down -bor ([long]3 -shl 30) + [void][VfoxWindow]::PostMessage($target, 0x0100, [IntPtr]$key, [IntPtr]$down) + Start-Sleep -Milliseconds 50 + [void][VfoxWindow]::PostMessage($target, 0x0101, [IntPtr]$key, [IntPtr]$up) +} + function Send-Line([IntPtr] $target, [string] $text) { foreach ($char in $text.ToCharArray()) { [void][VfoxWindow]::PostMessage($target, $WM_CHAR, [IntPtr][int][char]$char, [IntPtr]1) @@ -174,10 +193,15 @@ function Wait-Marker([string] $name) { try { Wait-Marker 'select.ready' Start-Sleep -Seconds 1 - Send-Line $handle '20.19.0' - Wait-Marker 'confirm.ready' - Start-Sleep -Seconds 1 - Send-Line $handle 'y' + # The down arrow: virtual key 0x28, scan code 0x50, an extended key. + Send-VirtualKey $handle 0x28 0x50 $true + if ($Script -eq 'selection') { + Start-Sleep -Milliseconds 300 + Send-Char $handle 13 + Wait-Marker 'confirm.ready' + Start-Sleep -Seconds 1 + Send-Char $handle 0x79 + } Wait-Marker 'exit.txt' } finally { From a71499f20b151699b1933faf33567698a1595a1d Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 20:57:47 +0800 Subject: [PATCH 13/15] docs: the arrow keys select a version in native Git Bash (#98) The FAQ said the arrow keys did not work in native Git Bash (MinTTY). They do now, through stty raw mode on the classic pty, and the line input is the fallback. The heading becomes a question about how to select, and the links to it follow. --- docs/guides/faq.md | 6 ++---- docs/guides/intro.md | 2 +- docs/zh-hans/guides/faq.md | 6 ++---- docs/zh-hans/guides/intro.md | 2 +- 4 files changed, 6 insertions(+), 10 deletions(-) diff --git a/docs/guides/faq.md b/docs/guides/faq.md index 95dc9e11..3c86f55a 100644 --- a/docs/guides/faq.md +++ b/docs/guides/faq.md @@ -60,10 +60,8 @@ On a CI runner, `vfox link --detect java -y` links the JDKs the plugin can find. Put it back with `vfox install --reinstall @`, and move to a newer version by installing that version with `vfox` instead. -## Why can't I select when use `use` and `search` commands in GitBash? +## How do I select a version with `use` and `search` in GitBash? Related ISSUE: [Unable to select in GitBash](https://github.com/version-fox/vfox/issues/98) -In the native GitBash (MinTTY), vfox cannot read single key presses, so `use`, `search` and the other prompts read a line instead: type a number from the list or a version and press Enter. Typing text narrows the list, and an empty line cancels. For arrow-key selection, run GitBash in one of these: -1. Run `GitBash` through `Windows Terminal` -2. Run `GitBash` in `VS Code` +In the native GitBash (MinTTY), the arrow keys select a version in `use`, `search` and the other prompts. The up and down arrows move the highlight, typing filters the list, Enter chooses, Ctrl-C cancels, and a confirmation takes `y` or `n` without Enter. To read single keys, vfox switches the terminal to raw mode with `stty`, which comes with Git for Windows, and restores it afterwards. Without `stty`, the prompts read a line instead: type a number from the list or a version and press Enter, and an empty line cancels. diff --git a/docs/guides/intro.md b/docs/guides/intro.md index 5f725b5e..f900da8a 100644 --- a/docs/guides/intro.md +++ b/docs/guides/intro.md @@ -22,7 +22,7 @@ Traditional solutions require installing multiple version managers (such as `nvm | Shell | Support | Note | |------------|---------|----------------------------------------------------------------------------------| | PowerShell | ✅ | | -| Git Bash | ✅ | [FAQ](./faq.md#why-can-t-i-select-when-use-use-and-search-commands-in-gitbash) | +| Git Bash | ✅ | [FAQ](./faq.md#how-do-i-select-a-version-with-use-and-search-in-gitbash) | | Bash | ✅ | | | ZSH | ✅ | | | Fish | ✅ | | diff --git a/docs/zh-hans/guides/faq.md b/docs/zh-hans/guides/faq.md index 3ace4c8d..a04ee10b 100644 --- a/docs/zh-hans/guides/faq.md +++ b/docs/zh-hans/guides/faq.md @@ -50,10 +50,8 @@ vfox use java@17-system `vfox` 按目录管理版本,没办法阻止 SDK 自己在原地更新。不过它能发现:当插件报告某个已安装的版本和安装时不一样了,`vfox use` 和 `vfox doctor` 会给出警告。用 `vfox install --reinstall @` 把它恢复原样;想换到更新的版本,请用 `vfox` 安装那个版本,而不是在原地更新。 -## GitBash下`use`和`search`命令无法进行选择? +## GitBash下如何用`use`和`search`命令选择版本? 相关ISSUE: [GitBash下无法进行选择](https://github.com/version-fox/vfox/issues/98) -原生GitBash(MinTTY)无法读取单个按键, 因此`use`、`search`等命令改为按行读取输入: 输入列表中的序号或版本号后回车即可, 输入文字可以过滤列表, 空行则取消。如需使用方向键选择, 可以: -1. 通过`Windows Terminal`运行`GitBash` -2. 在`VS Code`中运行`GitBash` +原生GitBash(MinTTY)中, `use`、`search`等命令可以用方向键选择版本: 上下键移动高亮, 输入文字过滤列表, 回车选择, Ctrl+C取消; 确认提示直接按`y`或`n`即可。vfox读取单个按键时, 会用随Git for Windows提供的`stty`把终端切换到单键模式, 结束后再恢复。如果找不到`stty`, 则改为按行读取输入: 输入列表中的序号或版本号后回车, 空行则取消。 diff --git a/docs/zh-hans/guides/intro.md b/docs/zh-hans/guides/intro.md index 73c2a60d..c4db88bc 100644 --- a/docs/zh-hans/guides/intro.md +++ b/docs/zh-hans/guides/intro.md @@ -22,7 +22,7 @@ | Shell | 支持 | 说明 | |------------|------|---------------------------------------------------------------------------------| | PowerShell | ✅ | | -| Git Bash | ✅ | [常见问题](./faq.md#why-can-t-i-select-when-use-use-and-search-commands-in-gitbash) | +| Git Bash | ✅ | [常见问题](./faq.md#how-do-i-select-a-version-with-use-and-search-in-gitbash) | | Bash | ✅ | | | ZSH | ✅ | | | Fish | ✅ | | From 1bdc01cf9c6e2f15943c2eb11fb1d374d1dcfb4e Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 21:09:36 +0800 Subject: [PATCH 14/15] ci: run every workflow job only in version-fox/vfox (#98) Every job of the workflows now carries if: github.repository == 'version-fox/vfox', so a push to a fork runs no job. The test summary keeps its always() and joins the gate with &&. Pull requests from forks still run the jobs, because a pull_request workflow runs in the base repository. --- .github/workflows/ci.yml | 4 ++++ .github/workflows/compile-inno-setup.yml | 1 + .github/workflows/compile-msix.yml | 1 + .github/workflows/documentation.yml | 2 ++ .github/workflows/e2e-tests.yml | 5 ++++- .github/workflows/gitbash-mintty.yml | 1 + .github/workflows/go-releaser.yml | 1 + .github/workflows/release.yml | 1 + 8 files changed, 15 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 09320651..f04924cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -8,6 +8,7 @@ concurrency: jobs: build: + if: github.repository == 'version-fox/vfox' runs-on: ${{ matrix.os }} strategy: matrix: @@ -37,6 +38,7 @@ jobs: uses: codecov/codecov-action@v7 windows-regressions: + if: github.repository == 'version-fox/vfox' name: Windows shell and interrupted installation regressions runs-on: windows-latest timeout-minutes: 15 @@ -65,6 +67,7 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } nushell: + if: github.repository == 'version-fox/vfox' name: Nushell integration runs-on: ubuntu-latest timeout-minutes: 10 @@ -98,6 +101,7 @@ jobs: go test ./cmd/commands -run '^TestNushell' -count=1 -v fish-completion: + if: github.repository == 'version-fox/vfox' name: Fish completion integration runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.github/workflows/compile-inno-setup.yml b/.github/workflows/compile-inno-setup.yml index 460b43dc..9b5c230d 100644 --- a/.github/workflows/compile-inno-setup.yml +++ b/.github/workflows/compile-inno-setup.yml @@ -11,6 +11,7 @@ permissions: jobs: compile-inno-setup: + if: github.repository == 'version-fox/vfox' name: Compile setup and publish runs-on: windows-latest defaults: diff --git a/.github/workflows/compile-msix.yml b/.github/workflows/compile-msix.yml index 25475084..38e38373 100644 --- a/.github/workflows/compile-msix.yml +++ b/.github/workflows/compile-msix.yml @@ -11,6 +11,7 @@ permissions: jobs: compile-msix: + if: github.repository == 'version-fox/vfox' name: Build MSIX bundle and publish runs-on: windows-latest defaults: diff --git a/.github/workflows/documentation.yml b/.github/workflows/documentation.yml index 2dcf2492..120ba642 100644 --- a/.github/workflows/documentation.yml +++ b/.github/workflows/documentation.yml @@ -17,6 +17,7 @@ permissions: jobs: build: + if: github.repository == 'version-fox/vfox' runs-on: ubuntu-latest defaults: run: @@ -60,6 +61,7 @@ jobs: path: docs/.vitepress/dist # Deployment job deploy: + if: github.repository == 'version-fox/vfox' environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index 93f4f2be..65e6f1f4 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -15,6 +15,7 @@ on: jobs: test-windows: + if: github.repository == 'version-fox/vfox' name: Test on Windows runs-on: windows-latest @@ -59,6 +60,7 @@ jobs: path: ${{ runner.temp }}\.vfox test-msix-windows: + if: github.repository == 'version-fox/vfox' name: Test MSIX packaging on Windows runs-on: windows-latest timeout-minutes: 20 @@ -90,6 +92,7 @@ jobs: path: msix-e2e-out test-unix: + if: github.repository == 'version-fox/vfox' name: Test on Unix runs-on: ${{ matrix.os }} @@ -132,7 +135,7 @@ jobs: name: Test Summary runs-on: ubuntu-latest needs: [test-windows, test-unix, test-msix-windows] - if: always() + if: always() && github.repository == 'version-fox/vfox' steps: - name: Download all artifacts diff --git a/.github/workflows/gitbash-mintty.yml b/.github/workflows/gitbash-mintty.yml index e18a9a35..017115a0 100644 --- a/.github/workflows/gitbash-mintty.yml +++ b/.github/workflows/gitbash-mintty.yml @@ -7,6 +7,7 @@ on: jobs: mintty: + if: github.repository == 'version-fox/vfox' name: Select and confirm in a Git Bash mintty window runs-on: windows-latest timeout-minutes: 20 diff --git a/.github/workflows/go-releaser.yml b/.github/workflows/go-releaser.yml index 389269e7..fd6e49bb 100644 --- a/.github/workflows/go-releaser.yml +++ b/.github/workflows/go-releaser.yml @@ -11,6 +11,7 @@ permissions: jobs: release: + if: github.repository == 'version-fox/vfox' runs-on: ubuntu-latest env: flags: "" diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 7d25a832..e684cb2d 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,7 @@ permissions: jobs: create-release: + if: github.repository == 'version-fox/vfox' runs-on: ubuntu-latest environment: production steps: From 718941873a86912a7afa16e398a93e7733346885 Mon Sep 17 00:00:00 2001 From: Qiheng He Date: Sat, 14 Nov 2026 21:19:15 +0800 Subject: [PATCH 15/15] test: give the mintty window 30 seconds, and try the launch once more (#98) mintty.exe does not always keep its window in the process it starts. The driver treated that process exiting before the window showed as a failure, so a launch that was still starting failed the step: the classic-pty run of a71499f on the fork exited with code 0 at 0.7 seconds, while the same commit passed upstream. In every run that found a window, the window belonged to a different process than the one started. The window is now looked for by its class for 30 seconds, whatever became of the process started. A launch that shows no window is tried once more, after the mintty, bash and test processes of the first are stopped and its leftover files are removed. A bash that starts writes started.txt, which the message for a failed launch reports. The test and its assertions are unchanged. --- scripts/gitbash-mintty-test.ps1 | 63 +++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 index 715e63e9..13afc83d 100644 --- a/scripts/gitbash-mintty-test.ps1 +++ b/scripts/gitbash-mintty-test.ps1 @@ -117,6 +117,7 @@ $unixScript = "$unixWork/run.sh" # the window closes when the script ends. $runScript = @' #!/usr/bin/env bash +echo started > '__UNIXWORK__/started.txt' export VFOX_TEST_GITBASH_MINTTY_DIR='__WORK__' export VFOX_TEST_GITBASH_MINTTY_STDIO='__STDIO__' '__TEST__' -test.run '^__RUN__$' -test.v @@ -125,13 +126,15 @@ echo $? > '__UNIXWORK__/exit.txt' $runScript = $runScript.Replace('__WORK__', $WorkDir).Replace('__STDIO__', $Stdio).Replace('__TEST__', $unixTest).Replace('__UNIXWORK__', $unixWork).Replace('__RUN__', $TestRun) [System.IO.File]::WriteAllText((Join-Path $WorkDir 'run.sh'), $runScript.Replace("`r`n", "`n") + "`n") -# A window left over from an earlier run would be taken for this one. -Get-Process -Name mintty -ErrorAction SilentlyContinue | Stop-Process -Force if ($MsysOptions) { $env:MSYS = $MsysOptions } Write-Host "MSYS for mintty: '$($env:MSYS)' (stdio: $Stdio)" -$window = Start-Process -FilePath $mintty -ArgumentList "-e `"$bash`" --noprofile --norc `"$unixScript`"" -PassThru -Write-Host "started $mintty as process $($window.Id)" +# Ends what an earlier launch left running: the windows, the shell and the test. A +# window left over would be taken for the new one. +function Stop-MinttyRun { + $test = [IO.Path]::GetFileNameWithoutExtension($TestBinary) + Get-Process -Name mintty, bash, $test -ErrorAction SilentlyContinue | Stop-Process -Force -ErrorAction SilentlyContinue +} function Find-MinttyWindow { foreach ($candidate in [VfoxWindow]::TopLevel()) { @@ -140,24 +143,39 @@ function Find-MinttyWindow { return [IntPtr]::Zero } -$deadline = (Get-Date).AddSeconds($TimeoutSeconds) -$handle = Find-MinttyWindow -while ($handle -eq [IntPtr]::Zero) { - if ($window.HasExited) { throw "mintty exited with code $($window.ExitCode) before it showed a window" } - if ((Get-Date) -gt $deadline) { - Write-Host "UserInteractive: $([Environment]::UserInteractive)" - foreach ($candidate in [VfoxWindow]::TopLevel()) { - $title = [VfoxWindow]::TitleOf($candidate) - if ($title) { - Write-Host ("window {0} class '{1}' title '{2}' process {3}" -f $candidate, [VfoxWindow]::ClassOf($candidate), $title, [VfoxWindow]::ProcessOf($candidate)) - } +# mintty.exe may hand its window to a process of its own and exit once it has, so the +# process started here is never a failure by itself: the window is looked for by its +# class until 30 seconds have passed. A launch that shows no window is tried once more. +function Start-MinttyWindow { + for ($attempt = 1; $attempt -le 2; $attempt++) { + Stop-MinttyRun + Get-ChildItem -LiteralPath $WorkDir -Exclude run.sh | Remove-Item -Force + $launcher = Start-Process -FilePath $mintty -ArgumentList "-e `"$bash`" --noprofile --norc `"$unixScript`"" -PassThru + Write-Host "attempt ${attempt}: started $mintty as process $($launcher.Id)" + $deadline = (Get-Date).AddSeconds(30) + $handle = Find-MinttyWindow + while ($handle -eq [IntPtr]::Zero -and (Get-Date) -lt $deadline) { + Start-Sleep -Milliseconds 300 + $handle = Find-MinttyWindow + } + if ($handle -ne [IntPtr]::Zero) { + Write-Host "mintty window $handle, process $([VfoxWindow]::ProcessOf($handle))" + return $handle } - throw 'no mintty window appeared' + $state = if ($launcher.HasExited) { "exited with code $($launcher.ExitCode)" } else { 'still running' } + $started = Test-Path -LiteralPath (Join-Path $WorkDir 'started.txt') + Write-Host "attempt ${attempt}: no mintty window within 30 seconds; the process started here $state; bash started: $started" } - Start-Sleep -Milliseconds 300 - $handle = Find-MinttyWindow + foreach ($candidate in [VfoxWindow]::TopLevel()) { + $title = [VfoxWindow]::TitleOf($candidate) + if ($title) { + Write-Host ("window {0} class '{1}' title '{2}' process {3}" -f $candidate, [VfoxWindow]::ClassOf($candidate), $title, [VfoxWindow]::ProcessOf($candidate)) + } + } + throw 'no mintty window appeared' } -Write-Host "mintty window $handle, process $([VfoxWindow]::ProcessOf($handle))" + +$handle = Start-MinttyWindow function Send-Char([IntPtr] $target, [int] $char) { [void][VfoxWindow]::PostMessage($target, $WM_CHAR, [IntPtr]$char, [IntPtr]1) @@ -205,9 +223,10 @@ try { Wait-Marker 'exit.txt' } finally { - if (-not $window.HasExited -and -not $window.WaitForExit(10000)) { - Stop-Process -Id $window.Id -Force - } + # The window closes once the script has ended, after it wrote exit.txt. A window + # that stays open is stopped, so that exit.txt is read after the shell is done. + Get-Process -Name mintty -ErrorAction SilentlyContinue | Wait-Process -Timeout 10 -ErrorAction SilentlyContinue + Stop-MinttyRun Write-Host "files in ${WorkDir}:" Get-ChildItem -LiteralPath $WorkDir | ForEach-Object { Write-Host " $($_.Name)" } Write-Host '--- result.txt'