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 new file mode 100644 index 00000000..017115a0 --- /dev/null +++ b/.github/workflows/gitbash-mintty.yml @@ -0,0 +1,28 @@ +name: Git Bash in mintty + +on: + push: + pull_request: + workflow_dispatch: + +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 + 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: 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-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/.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: diff --git a/cmd/commands/choose_line_test.go b/cmd/commands/choose_line_test.go new file mode 100644 index 00000000..f643cfe1 --- /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" + "strings" + "testing" + + "github.com/version-fox/vfox/internal/shared/printer" +) + +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) + } +} + +// 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.Fatalf("selectVersionWith() error: %v", err) + } + if version != "20.19.0" { + t.Errorf("selectVersionWith() = %q, want %q", version, "20.19.0") + } +} + +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("selectVersionWith() error: %v", err) + } + if 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 new file mode 100644 index 00000000..24f91801 --- /dev/null +++ b/cmd/commands/gitbash_mintty_windows_test.go @@ -0,0 +1,117 @@ +/* + * 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 +// 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, 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 == "" { + 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, "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() + 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") + 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) + + 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) + } + if !ok { + t.Errorf("Git Bash in mintty, %s:\n%s", stdio, report.String()) + } +} + +// 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 { + t.Fatal(err) + } +} + +// 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) + 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/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..77cbcd0e 100644 --- a/cmd/commands/search.go +++ b/cmd/commands/search.go @@ -94,6 +94,10 @@ func RunSearch(sdkName string, availableArgs []string) error { return nil } + 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{ TopText: "Please select a version of " + sdkName + " to install", @@ -126,6 +130,24 @@ 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 +} + +// 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) + } + 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..5ac2362b --- /dev/null +++ b/cmd/commands/search_line_test.go @@ -0,0 +1,124 @@ +/* + * 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 TestInstallChosenInstallsTheChosenVersion(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + 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("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) + } + 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 TestInstallChosenWithRawKeys(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + 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 TestInstallChosenRefusesAnInstalledVersion(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + installed := util.NewSet[string]() + installed.Add("20.19.0") + 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("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) + } + 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 TestInstallChosenReportsReadError(t *testing.T) { + var installer recordingInstaller + var out bytes.Buffer + 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("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/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/cmd/commands/use.go b/cmd/commands/use.go index 8915abdf..c120e156 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" ) @@ -175,8 +177,14 @@ 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) { + prompt := printer.StdinPrompt() + if prompt.Input != printer.Keyboard { + return selectVersionWith(prompt, options, sdkName) + } selectPrinter := pterm.InteractiveSelectPrinter{ TextStyle: &pterm.ThemeDefault.DefaultText, OptionStyle: &pterm.ThemeDefault.DefaultText, @@ -199,3 +207,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 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 := prompt.Choose(fmt.Sprintf("Please select a version of %s", sdkName), entries, nil) + 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 9473500a..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) -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: -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 4d59b52f..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运行`vfox`会出现无法进行选择的问题, 临时解决办法: -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 | ✅ | | diff --git a/internal/manager.go b/internal/manager.go index cbe82abc..50007d22 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..2a9c55b0 --- /dev/null +++ b/internal/shared/printer/confirm.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 printer + +import ( + "bufio" + "fmt" + "io" + "strings" + + "github.com/pterm/pterm" +) + +// 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 StdinPrompt().Confirm(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..d9239eed --- /dev/null +++ b/internal/shared/printer/confirm_test.go @@ -0,0 +1,153 @@ +/* + * 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 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 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()) + } +} + +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/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/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 new file mode 100644 index 00000000..b567ec7d --- /dev/null +++ b/internal/shared/printer/select_line.go @@ -0,0 +1,149 @@ +/* + * 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 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 a pipe. +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. 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) { + 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 isDisabledIn(s.DisabledOptions, chosen.Key) { + fmt.Fprintf(s.Out, "%s is already installed, choose another version.\n", chosen.Key) + continue + } + return chosen, nil + } +} + +// 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 options { + if fuzzy.MatchFold(filter, option.Value) { + found = append(found, option) + } + } + 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 +// listed entries. +func (s *LineSelect) choose(line string, listed []*KV) *KV { + 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 +} + +// 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 isDisabledIn(s.DisabledOptions, 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..4e31c898 --- /dev/null +++ b/internal/shared/printer/select_line_test.go @@ -0,0 +1,196 @@ +/* + * 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 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") +} + +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) + } +} + +// 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 { + 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..51ee056d 100644 --- a/internal/shared/util/tty.go +++ b/internal/shared/util/tty.go @@ -22,7 +22,23 @@ 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, and isCygwinTerminal reports that pipe as a terminal. 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()) +} + +// 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/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_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") + } +} diff --git a/internal/shared/util/tty_windows.go b/internal/shared/util/tty_windows.go new file mode 100644 index 00000000..e6cb6130 --- /dev/null +++ b/internal/shared/util/tty_windows.go @@ -0,0 +1,74 @@ +/* + * 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" + "regexp" + "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 +} + +// 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 { + return cygwinPipeName.MatchString(name) +} diff --git a/internal/shared/util/tty_windows_test.go b/internal/shared/util/tty_windows_test.go new file mode 100644 index 00000000..3d737997 --- /dev/null +++ b/internal/shared/util/tty_windows_test.go @@ -0,0 +1,120 @@ +/* + * 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") + } +} + +// 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{ + // 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, + `\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) + } + } +} diff --git a/scripts/gitbash-mintty-test.ps1 b/scripts/gitbash-mintty-test.ps1 new file mode 100644 index 00000000..13afc83d --- /dev/null +++ b/scripts/gitbash-mintty-test.ps1 @@ -0,0 +1,238 @@ +<# +.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: "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. +#> +[CmdletBinding()] +param( + [Parameter(Mandatory)] + [string] $TestBinary, + + [Parameter(Mandatory)] + [string] $WorkDir, + + [Parameter(Mandatory)] + [ValidateSet('pipe', 'console')] + [string] $Stdio, + + [string] $MsysOptions = '', + + [string] $TestRun = 'TestGitBashMinttySelection', + + [ValidateSet('selection', 'probe')] + [string] $Script = 'selection', + + [ValidateRange(10, 1800)] + [int] $TimeoutSeconds = 180 +) + +$ErrorActionPreference = 'Stop' + +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 +$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 +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 +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") + +if ($MsysOptions) { $env:MSYS = $MsysOptions } +Write-Host "MSYS for mintty: '$($env:MSYS)' (stdio: $Stdio)" + +# 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()) { + if ([VfoxWindow]::ClassOf($candidate) -eq 'mintty') { return $candidate } + } + return [IntPtr]::Zero +} + +# 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 + } + $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" + } + 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' +} + +$handle = Start-MinttyWindow + +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) + Start-Sleep -Milliseconds 100 + } + [void][VfoxWindow]::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 + # 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 { + # 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' + Get-Content -LiteralPath (Join-Path $WorkDir 'result.txt') -ErrorAction SilentlyContinue | Write-Host +} + +$exitCode = (Get-Content -LiteralPath (Join-Path $WorkDir 'exit.txt') -Raw).Trim() +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."