Skip to content

fix(exec): skip CLI flag parsing so target command flags pass through without -- - #828

Merged
linghengqian merged 10 commits into
version-fox:mainfrom
aloneangel45:fix/824-exec-flag-parsing
Nov 24, 2026
Merged

linghengqian merged 10 commits into
version-fox:mainfrom
aloneangel45:fix/824-exec-flag-parsing

Conversation

@aloneangel45

@aloneangel45 aloneangel45 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #824.

Summary

  • exec leading-flag and pass-through parsing (cmd/cmd.go, cmd/commands/exec.go):
    • Set SkipFlagParsing: true on Exec and parse vfox exec's own leading flags (--help/-help/-h and --debug/-debug including =0/=false/=1/=true) before the SDK specs, forwarding all flags after <command> directly to the target executable without --.
    • Updated root --debug handling in cmd/cmd.go so --debug=false explicitly sets logger.InfoLevel instead of ignoring the false value.
    • Also accept --debug/-debug (=0/=false/=1/=true) positioned between the SDK specs and <command> (or --), matching main (vfox exec [email protected] --debug etcd put).
    • Reject -v, -V, and --version before the SDK with an error telling users to run vfox --version to print the vfox version.
  • Single-SDK shorthand vs separator rules (cmd/commands/exec.go):
    • Kept <sdk>[@<version>] <command> [args...] working without -- while treating the first -- as the separator between SDK specs and <command> (requiring -- for multiple SDKs or when <command> itself receives --).
    • Gate manager.LookupSdk(command) on isBareSDKName(command) and gate "treated as an SDK instead of the command" on sdkSpecs[len(sdkSpecs)-1].Version == "".
  • Unix . lookup, Windows PATHEXT + batch quoting/guard, and completion probes (cmd/commands/exec.go, cmd/commands/exec_windows.go, cmd/commands/exec_other.go):
    • Restored main's exact Unix PATH lookup branch (strings.Split and dir + string(os.PathSeparator) + command), preserving . PATH entries as ./<command>.
    • Kept Windows PATHEXT resolution (lookPathInEnvWithExt + joinRelativeExecutable preserving relative .\ entries), and added prepareExecCommand (cmd/commands/exec_windows.go): when the target is a .cmd or .bat shim, buildBatchCmdLine quotes both execPath (argv[0]) and metacharacter/whitespace arguments for cmd.exe via SysProcAttr.CmdLine (wrapping the full line in an outer quote pair because CreateProcessW launches cmd.exe /c, which strips one outer pair), allowing &, |, <, >, (, ), ^, and spaces (including & inside SDK directory paths) while validateWindowsBatchCommand refuses only characters that cmd.exe quoting cannot protect (%, !, ", CR, LF, NUL) in both execPath and args.
    • Intercept trailing --generate-shell-completion in both -- and non--- forms with empty output (ShellComplete offers --help only before an SDK spec, plus hasTrailingCompletionFlag).
  • Documentation (docs/usage/all-commands.md, docs/usage/core-commands.md, and docs/zh-hans/):
    • Documented the single-SDK shorthand, -- rules, leading-flag rule (--help/--debug before <sdk>, -v/-V/--version -> vfox --version), --generate-shell-completion behavior with the shell escape hatch (vfox exec <sdk> sh -c '<tool> --generate-shell-completion'), and Windows .cmd/.bat quoting, refused characters (%, !, ", CR, LF, NUL), and workarounds.

Testing

  • cmd/commands/exec_test.go, cmd/commands/exec_windows_test.go, and cmd/exec_test.go cover root --debug=false, leading and between-SDK --debug/-debug (=0/=false), -v/-V/--version vfox --version error hint, Unix . PATH resolution, Windows PATHEXT and relative .\etcd.exe lookup, Windows batch cmd.exe quoting for express@^4.18.0 / & / | / < / > / () / spaces / &-containing SDK directories + % ! " CR LF NUL refusal across both argv[0] and args, pass-through flags, separator hints, and completion probes.
  • Verified locally with go test -race -count=1 ./cmd ./cmd/commands, go vet ./... (windows/amd64, linux/amd64, darwin/amd64), and go test -c (linux/amd64, darwin/amd64).

@linghengqian linghengqian added this to the 1.1.1 milestone Nov 23, 2026
@codecov

codecov Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 52.21239% with 108 lines in your changes missing coverage. Please review.
✅ Project coverage is 59.93%. Comparing base (90a96e1) to head (a039a5a).

Files with missing lines Patch % Lines
cmd/commands/exec.go 49.76% 104 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #828      +/-   ##
==========================================
+ Coverage   59.57%   59.93%   +0.36%     
==========================================
  Files         124      125       +1     
  Lines        9061     9255     +194     
==========================================
+ Hits         5398     5547     +149     
- Misses       3181     3219      +38     
- Partials      482      489       +7     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes.

This fixes the cases from #824: vfox exec [email protected] etcd --version, --help, -h, -v and -V now reach etcd. It also breaks some existing invocations, and the -- case is still open. Reviewed at head a0a2e91.

I ran the same commands on the PR base (90a96e1) and on this head, using a fake etcd 3.5.12 SDK in an isolated VFOX_HOME. go vet ./..., gofmt -l on the three changed files, and go test ./... -count=1 all pass on Linux.

  1. Root flags between exec and the SDK name now fail.

vfox exec --debug [email protected] etcd put runs on main and exits 0. On this branch it exits 1 with "multiple SDKs require '--' before the command". vfox exec -v [email protected] etcd put fails the same way. The message is wrong, since only one SDK is named.

The cause is SkipFlagParsing. With it, urfave/cli does not apply the persistent root flags (--debug, --version) to exec, so --debug reaches parseExecInvocation as the first argument, and the @ check on the second argument fires. No test reaches that branch, so the wrong message is not caught.

Make --debug work in that position again, as it does on main. For -v and -V there, either keep main's behavior or reject them with an error that names the flag. Add a test for the choice. TestExecForwardsFlagsAfterCommandWithoutSeparator only covers --debug before exec.

  1. A -- after the command name is still the separator.

parseExecInvocation takes the first -- anywhere in the arguments as the separator, so a -- after the command never reaches the command:

  • vfox exec [email protected] etcd -- --version fails with "no version configured for etcd", because the second etcd is read as an SDK name.
  • vfox exec [email protected] etcd put -- key fails the same way.
  • vfox exec [email protected] npm run build -- --watch reads npm, run and build as SDK names and fails with "npm not supported".

Flags after the command name now reach it: vfox exec [email protected] etcd run build --watch works. A -- in the same position still does not. #824 expects the arguments after the command name to reach the command, as they do after --.

The words alone do not settle this. The usage line makes versions optional, so vfox exec nodejs golang -- npm install has the same shape as vfox exec [email protected] etcd -- --version. Keeping the first -- as the separator is the simplest rule, and it keeps the names-only form working. If you keep it, state the rule in the usage text and in docs/usage/core-commands.md, which only shows the -- form. Make the error name the word that was read as an SDK, and test the message. If you want -- after the command to pass through, define how that case is told apart from the names-only form, and test that too.

  1. vfox exec --help output changed.

On main, vfox exec --help prints USAGE: vfox exec [options] and lists --debug and --version under GLOBAL OPTIONS. This branch prints USAGE: vfox exec with no GLOBAL OPTIONS section, which is the same output vfox help exec already gives on main.

Without flag parsing, urfave never sees --help, so its own help handling does not run. The new branch in execCmd calls cli.ShowSubcommandHelp instead, and that template has no GLOBAL OPTIONS section. Either produce main's output again, or accept the change and say so in the PR.

  1. One subtest does not check what its name says.

In cmd/exec_test.go, "root --debug before exec still enables debug while preserving target flags" checks the exit code, the target output and that the vfox version is absent. It never checks that debug output appears. Assert it, or rename the subtest.

Checked and fine: the -- form (vfox exec [email protected] -- etcd --version and vfox exec [email protected] -- etcd put -- key), vfox exec clang --version (usage error, nothing installed), vfox exec --version (usage error, no version printed), the x alias, and [email protected] without --.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks for the thorough review, @linghengqian — addressed all four points in 8154e8a:

  1. Root flags between exec and the SDK name (--debug, -v, -V):

    • Added parseExecLeadingArgs in cmd/commands/exec.go to handle leading flags only before the first non-flag SDK/command argument (without intercepting flags after the command).
    • vfox exec --debug [email protected] etcd put now enables debug logging via logger.SetLevel(logger.DebugLevel) and runs cleanly again.
    • Leading -v, -V, --version, and any other unsupported leading flags before <sdk> are rejected with unexpected flag "<flag>" before SDK plus the usage block (naming the flag instead of hitting the multi-SDK @ error or printing the vfox version).
    • Covered in TestParseExecLeadingArgs (cmd/commands/exec_test.go) and TestExecForwardsFlagsAfterCommandWithoutSeparator (cmd/exec_test.go).
  2. -- after the command name & usage/docs:

    • Kept the first -- as the separator so the names-only multi-SDK form (vfox exec nodejs golang -- npm install) keeps working deterministically.
    • Documented both the single-SDK shorthand and the first--- rule in Exec.ArgsUsage, Exec.Description, execUsageLine(), docs/usage/core-commands.md, and docs/zh-hans/usage/core-commands.md (with vfox exec [email protected] -- npm run build -- --watch as example).
    • When multiple tokens appear before -- and one fails resolution (for example vfox exec [email protected] etcd -- --version -> no version configured for etcd... or vfox exec [email protected] npm run build -- --watch -> npm not supported...), the error keeps the exact SDK word named and adds a note explaining the first--- rule; tested both cases plus vfox exec [email protected] -- etcd put -- key in cmd/exec_test.go.
  3. vfox exec --help output:

    • Updated showExecHelp to render with cli.CommandHelpTemplate (instead of cli.ShowSubcommandHelp), restoring USAGE: vfox exec [options] ..., OPTIONS:, and GLOBAL OPTIONS: (--debug, --version, -v, -V). Verified for both --help and -h in cmd/exec_test.go.
  4. --debug test assertion:

    • Updated "root --debug before exec still enables debug while preserving target flags" (and the new exec --debug subtests) in cmd/exec_test.go to explicitly assert debug log output (Looking up SDK: etcd) in stdout.

Verified with gofmt -l, git diff --check, Windows + GOOS=linux GOARCH=amd64 go vet ./..., GOOS=linux GOARCH=amd64 go test -c on ./cmd and ./cmd/commands, and go test -count=1 ./cmd ./cmd/commands (all non-registry tests passing).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes.

The #824 cases work now: vfox exec [email protected] etcd --version, --help, -h, -v and -V reach etcd, and vfox exec --debug ... works again. I found one regression and some gaps at 8154e8a.

  1. Some --debug spellings that main accepts now fail.

On this head each of these exits 1 with unexpected flag "..." before SDK. On main, each one runs the command with debug output:

vfox exec -debug [email protected] etcd put
vfox exec -debug=true [email protected] etcd put
vfox exec --debug=1 [email protected] etcd put
vfox exec --debug=TRUE [email protected] etcd put
vfox exec --debug=0 [email protected] etcd put
vfox x -debug [email protected] etcd put

The root parser accepts --debug=1 (vfox --debug=1 exec ... works on both branches). parseExecLeadingArgs (cmd/commands/exec.go:100) only matches the literal strings. Please parse the value with strconv.ParseBool, accept the single-dash form, and add test cases for these spellings.

--debug=false now turns debug off, where main turned it on. That is a fix. Please mention it in the description.

  1. The note in executeInVfoxEnv is wrong for a correct command line.

vfox exec [email protected] nosuch@1 -- etcd put has the separator in the right place, but the error still ends with "pass '--' before the command when it also uses '--'" (cmd/commands/exec.go:194-195). The condition is only len(sdkSpecs) > 1 && i > 0, so it fires for any SDK after the first that fails to resolve. Please limit the hint to cases where it helps, or reword it as a plain statement of the rule.

  1. A misplaced or missing -- is not explained when the command lookup fails.

With etcd set in .vfox.toml, vfox exec etcd etcd -- --version resolves both names, so no SDK error is raised. The command becomes --version:

command not found: --version: exec: "--version": executable file not found in $PATH

There is no note. The same happens with no separator at all: vfox exec etcd nosuch put gives command not found: nosuch. The PR description says failures before -- are annotated, and the earlier review asked for the word read as an SDK to be named. Please add the note to command not found errors too.

  1. The tests do not show that the SDK environment is used.

runExecCLI puts tools/ first on the child PATH (cmd/exec_test.go:58, 64), and setupExecFakeSDK writes the same fake etcd into it (line 92). I pointed the fake plugin's PATH entry (line 89) at a directory that does not exist, and TestExecForwardsFlagsAfterCommandWithoutSeparator still passed. The forwarding assertions cannot tell the difference.

Please give the copy in tools/ different output from the SDK copy, assert on the SDK output, and then drop the tools/ copy on Unix.

If the Windows job needs the tools copy, the likely reason is lookPathInEnv (cmd/commands/exec.go:379): a bare etcd is stat'ed as-is in the SDK bin directory, so etcd.cmd is not matched there. That is a separate issue. I have not run the Windows job, so this comes from reading the code. Please do not let this test depend on it silently.

  1. Docs.

docs/usage/all-commands.md and docs/zh-hans/usage/all-commands.md (line 18) still show only the -- form. Please add the single-SDK form, as the core-commands pages now do.

Checked and fine: vfox exec [email protected] -- etcd --version, -- etcd put -- key, the x alias, vfox --debug exec ..., exec --help and -h (GLOBAL OPTIONS intact), leading -v/-V/--version rejected with the flag named, shell completion probes giving the same output on both branches, and go test ./... on Linux.

@aloneangel45

aloneangel45 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the thorough follow-up review! Addressed all five items in commit a694a54 (and updated the PR description to mention --debug=false / --debug=0):

  1. Accept all urfave/cli --debug / -debug boolean spellings (cmd/commands/exec.go, cmd/commands/exec_test.go, cmd/exec_test.go):
    • Added parseExecDebugFlag using strconv.ParseBool, supporting -debug, --debug, -debug=<bool>, and --debug=<bool> (1, 0, true, TRUE, false, etc.) across both vfox exec and vfox x.
    • Added unit + CLI end-to-end tests covering -debug, -debug=true, --debug=1, --debug=TRUE, --debug=0, --debug=false, -debug=false, and vfox x -debug, verifying --debug=0/--debug=false suppress debug logging.
  2. Limit the SDK-resolution separator note (cmd/commands/exec.go, cmd/exec_test.go):
    • Scoped the executeInVfoxEnvWithSeparator note to bare SDK tokens without @ (len(sdkSpecs) > 1 && i > 0 && sdkSpec.Version == ""), so valid multi-SDK -- commands whose explicit sdk@version fails (vfox exec [email protected] nosuch@1 -- etcd put) no longer receive a misplaced separator hint.
  3. Add separator context to command not found failures (cmd/commands/exec.go, cmd/exec_test.go):
    • Annotated command not found failures when a leading flag follows -- (vfox exec etcd etcd -- --version, naming the absorbed SDK before --) or when no -- separator was used (vfox exec etcd nosuch put, naming the single-SDK token and command), while keeping well-formed vfox exec [email protected] -- nosuchcmd free of extraneous separator hints.
  4. Prevent tools/ from masking the SDK bin directory (cmd/exec_test.go):
    • Differentiated fake binary output (sdk:args=... in the SDK bin/ directory vs windows-tools:args=... in tools/) and removed tools/etcd completely on Unix so Unix runs directly prove the SDK environment PATH is used (retained tools/etcd.cmd only on Windows with an explicit note on the pre-existing lookPathInEnv extensionless-lookup behavior).
  5. Docs (docs/usage/all-commands.md, docs/zh-hans/usage/all-commands.md):
    • Added the single-SDK vfox exec <sdk-name>[@<version>] <command> [args...] usage line to both all-commands.md pages.

Re-verified locally at a694a54:

  • gofmt -l and git diff --check: clean
  • go vet ./... on Windows host, GOOS=linux GOARCH=amd64, and GOOS=darwin GOARCH=arm64, plus GOOS=linux GOARCH=amd64 go test -c ./cmd ./cmd/commands: passed
  • go test -race -count=1 ./cmd ./cmd/commands: passed (cmd 36.067s, cmd/commands 1.305s; Windows registry PATH tests skipped as expected without VFOX_TEST_WINDOWS_REGISTRY=1)

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. This is not ready to merge.

I rebuilt a694a54 and 90a96e1 on Linux and ran the same exec invocations against both, with HOME and VFOX_HOME isolated and a fake etcd 3.5.12 SDK. go vet ./..., gofmt -l on the three changed files, and go test ./... pass.

Fixed since the last round: --version, --help, -h, -v, -V and --debug after the command reach the target. vfox exec --help keeps GLOBAL OPTIONS. The single-dash -debug spellings and --debug=0 / --debug=1 work. The x alias works. The all-commands docs are updated.

1. Regression: --generate-shell-completion is dropped in the -- form.

$ vfox exec [email protected] -- etcd put --generate-shell-completion
base: sdk:args=put --generate-shell-completion
PR:   sdk:args=put

Both exit 0. urfave/cli strips a trailing --generate-shell-completion before Run. The base -- branch read os.Args, so the target still got the flag. This PR reads only cmd.Args() in execCmd, so the target runs with different arguments and nothing reports it. No test covers this. Either read the raw argument list for the -- branch again, or put the stripped argument back. Add a test that the target receives it.

2. The separator hint is wrong on correct command lines.

executeInVfoxEnvWithSeparator adds hints in three places. In each case the hint does not apply to the line the user wrote:

$ vfox exec [email protected] -- --version
command not found: --version: ...
note: arguments before the first '--' (including "etcd") are parsed as SDKs; pass '--' before the command
  • -- --version and -- -x get the note. -- nosuchcmd does not. Whether the note appears depends on whether the command starts with -, not on where the separator is.
  • exec [email protected] nosuch -- etcd put and exec etcd nosuch -- etcd put get "pass '--' before the command when it also uses '--'". The command does not use --, and the separator is already in place.
  • exec [email protected] nosuchcmd (one SDK, no separator) says "pass '--' before the command to use multiple SDKs". Only one SDK was named.

Also, exec [email protected] - now reports unexpected flag "-". Base reports command not found: -. parseExecLeadingArgs treats - as a positional, and the shorthand branch does not.

Attach a hint only when a word before the first -- is the likely cause. Do not tell the user to add a -- that is already there. Add tests for the correct lines, where the expected result is no hint.

3. The Windows branch of TestExecForwardsFlagsAfterCommandWithoutSeparator runs the host copy.

On Windows, execExpectedLine expects windows-tools:. The SDK copy written to bin/etcd.cmd is never executed. lookPathInEnv only stats the bare name in each custom PATH entry, so etcd.cmd in the SDK bin is missed. It then calls exec.LookPath, which searches the process PATH with PATHEXT (os/exec/lp_windows.go). The test puts tools/ first on that PATH, so the test passes by running tools\etcd.cmd.

If lookPathInEnv learns PATHEXT, these subtests fail. Fix the lookup in this PR, change the Windows expectation to the SDK output, and let the windows-latest job cover it. The lookup gap predates this PR (it came in with 2468c92), but the new test depends on it and pins it.

4. --debug=false means different things before and after exec.

$ vfox --debug=false exec [email protected] etcd put   # debug lines printed, base and PR
$ vfox exec --debug=false [email protected] etcd put   # no debug lines, PR

The root flag's Action in cmd/cmd.go ignores its bool argument, so the root form still turns debug on. The PR description says --debug=false keeps debug off. That is only true when the flag follows exec. Make the root flag honor its value and add a test. Otherwise, narrow the description and explain why the two positions differ.

5. A single SDK cannot take a command path that contains @.

$ vfox exec [email protected] ./node_modules/@foo/bin/run arg
multiple SDKs require '--' before the command

Base prints the same thing. parseExecInvocation treats any @ in the command word as a second SDK. The -- form reaches the command correctly. Only treat the second word as an SDK when it has no path separator and its name part is a valid SDK name. This is pre-existing, but the shorthand is now documented, so it belongs to this change.

Not counted as bugs

  • The first -- is the separator. It is documented in the usage text and in the core-commands pages, and the earlier review said it is fine when documented. Keep the rule as written.
  • executeInVfoxEnv has no callers. Delete it. CI has no unused-code linter, so nothing else will catch it.
  • isExecCommandNotFound matches on an error string. A typed error would be safer.
  • runExecCLI still puts tools/ on PATH on Unix, where that directory no longer exists.

Status of earlier points: resolved are the --debug spellings, the bare-name hint limit, the exec help format, the debug subtest assertion, the all-commands doc, and Unix isolation of the fake SDK. Still open are the command-not-found hint (point 2) and the Windows expectation (point 3).

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all items and cleanups from your review in 174cd0d:

  1. --generate-shell-completion preservation after -- (cmd/cmd.go, cmd/commands/exec.go): Recorded rawArgs in cmd.app.Metadata["rawArgs"] and added restoreExecTrailingCompletionArg in execCmd so a trailing --generate-shell-completion stripped by urfave/cli's checkShellCompleteFlag is restored when -- and EnableShellCompletion are active; added cmd/exec_test.go verifying vfox exec [email protected] -- etcd --generate-shell-completion passes --generate-shell-completion to etcd.
  2. Separator notes and bare - command (cmd/commands/exec.go):
    • Gated the hasSeparator command not found note on len(sdkSpecs) > 1 && strings.HasPrefix(command, "-"), so [email protected] -- --version and [email protected] -- -x omit the note.
    • Gated the resolveExecSDKEnv misplaced-separator note on hasDoubleDashOptionAfterSeparator(command, cmdArgs) so [email protected] nosuch -- etcd put and etcd nosuch -- etcd put omit "pass '--' before the command when it also uses '--'".
    • Gated the !hasSeparator note on len(cmdArgs) > 0 && !strings.HasPrefix(cmdArgs[0], "-") so [email protected] nosuchcmd omits the "to use multiple SDKs" note.
    • Changed parseExecInvocation so bare - is treated as <command> rather than an unexpected flag (vfox exec [email protected] - now reports command not found: - with no note); added regression tests for every case in cmd/exec_test.go and cmd/commands/exec_test.go.
  3. Windows PATHEXT resolution (cmd/commands/exec.go, cmd/commands/exec_windows_test.go, cmd/exec_test.go): Added lookPathInEnvWithExt / windowsPathExts / findWindowsExecutable (plus filepath.FromSlash for path-containing commands on Windows), unified execExpectedLine to "sdk:args=" + args on all OSes, and placed decoy tools/etcd binaries on both Unix and Windows in setupExecFakeSDK so every OS verifies SDK bin/ shadows tools/ on PATH.
  4. Root --debug boolean handling (cmd/cmd.go, cmd/exec_test.go): Updated the root --debug flag Action to honor its boolean parameter (if b { logger.SetLevel(logger.DebugLevel) } else { logger.SetLevel(logger.InfoLevel) }) and added a test for vfox --debug=false exec [email protected] etcd put.
  5. Command paths containing @ (cmd/commands/exec.go, cmd/exec_test.go, cmd/commands/exec_test.go): Replaced strings.Contains(args[1], "@") with looksLikeExecSDKSpec(args[1]) (requiring no / or \ and non-empty SDK name before @), and tested ./node_modules/@foo/bin/run arg end-to-end plus \ and @scope/... unit cases.
  6. Cleanups (cmd/commands/exec.go): Removed unused executeInVfoxEnv and replaced isExecCommandNotFound string prefix matching with typed execCommandNotFoundError (errors.As).

Verified locally at 174cd0d with gofmt -s -l, git diff --check, cross-OS go vet ./cmd/... ./internal/... (windows/linux/darwin), go test -c (linux/darwin for ./cmd and ./cmd/commands), and go test -race -count=1 ./cmd ./cmd/commands.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes. I compared 174cd0d against its base 90a96e1. Linux tests and vet pass and CI is green, but the following behavior problems need fixing.

  1. vfox exec -help regressed. On the base it prints the exec help, because urfave accepts the single-dash long form. On this branch parseExecLeadingArgs only recognizes --help and -h, so -help fails with unexpected flag "-help" before SDK and exit status 1. No test covers it. Please accept -help the same way urfave does and add it to TestParseExecLeadingArgs and the CLI tests.

  2. --generate-shell-completion behaves differently with and without --, and the docs say it should not.

    • vfox exec [email protected] etcd --version forwards the flag. vfox exec [email protected] etcd --generate-shell-completion does not: urfave treats it as a completion request, prints help, and never starts etcd. The base does the same.
    • docs/usage/core-commands.md (line 362 and the zh-hans copy) says flags after <command> are passed directly to <command>. That is not true for this flag.
    • With --, restoreExecTrailingCompletionArg forwards it. With the bash script from vfox completion bash, TAB after vfox exec [email protected] -- etcd runs etcd --generate-shell-completion, and its stdout becomes the completion list. The base does the same, but this PR now owns and tests that path, so it needs an explicit decision.
      I would pick one contract and document it. One option: exec and x answer the trailing probe without running the target, in both forms, and the docs say the flag is not forwarded. That also keeps TAB from running programs.
  3. The separator hint is wrong for a pinned SDK. vfox exec [email protected] etcdx put prints without '--', "etcd" is parsed as a single SDK ... pass '--' ... to use multiple SDKs. The user named one SDK with a version, so the hint is false. The same typo without arguments gets no hint, which means the condition checks the argument count, not the intent. Show the hint only when the command word is a known SDK (LookupSdk succeeds), or drop it for pinned SDKs.

  4. Windows batch shims. findWindowsExecutable now resolves .CMD and .BAT in SDK bin/, and executeCommand starts them with exec.Command. Go builds the command line by escaping each argument with CommandLineToArgvW rules and does not special-case batch files (syscall/exec_windows.go: EscapeArg leaves & unquoted). An argument such as x&calc reaches cmd.exe unquoted and runs a second command. I have not run this on Windows, so please verify it there. Either reject cmd metacharacters for .cmd/.bat targets, or build the command line for cmd.exe through SysProcAttr.CmdLine, and add a test that checks a second command in an argument is not executed.

lookPathInEnv (exec.go:448) has no production caller now; only the Windows test uses it. Not a bug, but it can go.

I'll review again once 1 to 4 have tests.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed all review items at 62d7180:

  1. vfox exec -help: parseExecLeadingArgs (cmd/commands/exec.go) now accepts -help alongside --help and -h, covered in TestParseExecLeadingArgs (cmd/commands/exec_test.go) and cmd/exec_test.go (while -help after <command> still forwards to the target).
  2. Uniform --generate-shell-completion contract: exec and x now answer a trailing --generate-shell-completion probe via hasTrailingCompletionFlag (cmd.ShellComplete) without starting <command> in both forms (with or without --), removing restoreExecTrailingCompletionArg. Documented this exception explicitly in docs/usage/core-commands.md and docs/zh-hans/usage/core-commands.md, and updated cmd/exec_test.go to verify neither form runs the target script.
  3. Separator hint scoped to known SDKs: executeInVfoxEnvWithSeparator now emits the missing--- multi-SDK note only when manager.LookupSdk(command) succeeds, so typos like vfox exec [email protected] etcdx put or vfox exec etcd nosuch put omit it while known-SDK invocations like vfox exec etcd alpha put retain it (cmd/exec_test.go).
  4. Windows .cmd/.bat metacharacter guard: added validateWindowsBatchArgs (isWindowsBatchFile) in cmd/commands/exec.go rejecting cmd.exe metacharacters (&|<>()^%!\r\n\x00") in arguments targeting .cmd/.bat files before exec.Command runs, verified on Windows in both TestExecuteCommandRejectsWindowsBatchMetacharacters (cmd/commands/exec_windows_test.go) and cmd/exec_test.go (x&echo>... fails without creating the marker file).
  • Also removed unused lookPathInEnv and updated cmd/commands/exec_windows_test.go to call lookPathInEnvWithExt directly.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Requesting changes on 62d7180.

I built base (90a96e1) and head on Linux and ran about 70 invocations against each, with HOME and VFOX_HOME in a temp directory and a fake etcd 3.5.12 SDK. go vet passes for linux, windows and darwin. go test ./cmd ./cmd/commands passes. CI is green.

Most earlier points are fixed. --version, --help, -h, -v, -V and --debug after the command now reach the target. -help works. --debug=false behaves the same before and after exec. exec -h keeps GLOBAL OPTIONS. In the -- form, quoted arguments and exit codes match base.

Items 1 and 2 were open in earlier rounds. Items 3 and 4 are new in this round. Item 5 predates the PR, but the PR rewrote that function, so it counts here.

  1. A misplaced -- gives a misleading error.

    $ vfox exec [email protected] etcd put -- key
    no version configured for etcd. Please use 'vfox use' to set a version first

The version is pinned in the same command, and nothing points at the separator. The hint is only added when a token starting with -- comes after the separator (hasDoubleDashOptionAfterSeparator, cmd/commands/exec.go:249, checked at :269), so this line gets no hint. "vfox exec etcd etcd put -- key" with etcd configured fails with "put not supported" and no hint. This is the case from the first review.

  1. The hint appears on correct command lines.

    $ vfox exec [email protected] nosuch -- etcd put -- key
    nosuch not supported, error: nosuch not installed
    note: arguments before the first '--' (including "nosuch") are parsed as SDKs; pass '--' before the command when it also uses '--'

The -- is already in front of the command, so the note asks for a separator that is there. The same output appears for "vfox exec [email protected] nosuch -- npm install --save foo" and "vfox exec [email protected] alpha -- etcd put -- key". No test covers an error path where the command contains --.

Suggestion: state the rule instead of giving an instruction. For example: "arguments before the first '--' are read as SDK names, and 'put' is not an installed SDK." That is true for every line above. Add a test for each line.

  1. The completion probe prints "help" in the -- form.

    $ vfox exec [email protected] -- etcd put --generate-shell-completion
    help

On base this form passed the probe flag to the target, so a target that implements --generate-shell-completion could answer TAB. Now vfox answers, and the answer is "help", which the shell offers as a completion. The form without -- already printed "help" on base, so both forms now offer a candidate nobody asked for. If vfox answers the probe, the answer should be empty. cmd/exec_test.go:170 and :194 pin "help" as the expected output, so those assertions need to change. The PR description and the docs should say that the -- form no longer lets the target answer the probe.

  1. Windows batch shims refuse common arguments.

validateWindowsBatchArgs (cmd/commands/exec.go:459) refuses & | < > ( ) ^ % ! " and CR, LF and NUL for .cmd and .bat targets. "npm install express@^4.18.0" is refused. The docs and usage text do not mention this, and there is no way to pass the argument. Base never found npm.cmd in an SDK directory, so this guard is now reached for shims base could not find at all.

I could not run this on Windows. The reasoning comes from the code and from the os/exec documentation on cmd.exe. Quoting each argument for cmd.exe through SysProcAttr.CmdLine would keep ^ and & working. Refuse only the characters that quoting cannot protect (%, !, ", CR, LF, NUL), and add a Windows test with ^ and &. If you keep the wider refusal, document it together with a workaround.

Please also check whether the guard covers the batch file path (argv[0]). cmd.exe parses that too when the path has no spaces, so C:\R&D...\npm.cmd would be split.

  1. Unix lookup ignores the execute bit. This predates the PR.

With a non-executable file nonexec-tool in an SDK directory and an executable with the same name later in PATH:

$ vfox exec [email protected] nonexec-tool hello
fork/exec .../nonexec-tool: permission denied

lookPathInEnvWithExt (cmd/commands/exec.go:502) returns the first non-directory match without checking mode bits. Match exec.LookPath on Unix: a regular file with an execute bit. Add a Unix test.

Please request review again after 1 to 5 are fixed.

@aloneangel45

aloneangel45 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed all 5 points from the review in a507d6a:

  1. Misplaced -- without post--- options (cmd/commands/exec.go): Removed hasDoubleDashOptionAfterSeparator and now emit the rule note whenever hasSeparator && len(sdkSpecs) > 1 && i > 0 && sdkSpec.Version == "" fails in resolveExecSDKEnv, so both vfox exec [email protected] etcd put -- key and vfox exec etcd etcd put -- key explain that arguments before the first '--' are read as SDK names.
  2. Removed misleading "pass '--' before the command" instruction when -- is present (cmd/commands/exec.go, cmd/exec_test.go): Reworded both ---present notes (resolveExecSDKEnv and execCommandNotFoundError) to state the parsing rule without asking the user to add --, and added tests in cmd/exec_test.go for all five command lines ([email protected] etcd put -- key, etcd etcd put -- key, [email protected] nosuch -- etcd put -- key, [email protected] nosuch -- npm install --save foo, and [email protected] alpha -- etcd put -- key).
  3. Empty --generate-shell-completion output (cmd/cmd.go, cmd/commands/exec.go, cmd/exec_test.go, docs/*/usage/core-commands.md): Made Exec.ShellComplete a no-op (preserved by cmd/cmd.go) and returned nil directly from execCmd on hasTrailingCompletionFlag(cmd) so both -- and non--- forms emit empty stdout without running <command>. Updated cmd/exec_test.go to require stdout == "", and updated the PR body and English/Chinese docs to state that the -- form no longer lets <command> answer completion probes.
  4. Windows batch shim quoting and argv[0] check (cmd/commands/exec_windows.go, cmd/commands/exec_other.go, cmd/commands/exec_windows_test.go, cmd/exec_test.go): In buildCommandExec, .cmd/.bat shims now check both execPath and args only for characters cmd.exe quoting cannot protect (%, !, ", CR, LF, NUL) and run through util.ShellCommand with an outer quote pair around buildWindowsBatchCmdLine (execPath always quoted, args quoted when empty or containing spaces/&|<>()^,;=). Added tests covering express@^4.18.0, x&echo>... (without executing echo), & in argv[0] (R&D\shim.cmd), and refusal of %, !, ", \n, \r, \x00 in both args and execPath.
  5. Unix execute bit check in lookPathInEnvWithExt (cmd/commands/exec.go, cmd/commands/exec_unix_test.go): On runtime.GOOS != "windows", require info.Mode().IsRegular() && info.Mode()&0o111 != 0 so non-executable files do not shadow executables later in PATH, and added TestLookPathInEnvSkipsNonExecutableUnixFiles in cmd/commands/exec_unix_test.go (cross-compiled for linux and darwin).

Verified locally on Windows at a507d6a (gofmt -s -l, git diff --check, 3-OS go vet, linux/darwin go test -c ./cmd ./cmd/commands, and VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./cmd ./cmd/commands). Ready for re-review!

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #828 at a507d6a.

On Linux, the fix for #824 works. vfox exec [email protected] etcd --version reaches etcd, -h, -help and --debug after the command are passed through, and completion probes no longer run the target. go test ./... passes. I'm requesting changes before merge.

Decisions

  • Completion probes: keep the interception in both forms. Without it, urfave strips a trailing --generate-shell-completion when -- is present, so the target runs with no arguments during TAB completion. Main runs the target with the probe in that form, which is also wrong.
  • -v, -V and --version before the SDK: keep the error. Main prints the vfox version and then runs the target. The error should point to vfox --version.
  • Scope: split this PR. See items 1 and 3.

Required changes

  1. Narrow this PR to the #824 fix. Keep leading-flag parsing, shorthand parsing, completion-probe handling, --debug, help, docs, and their tests. Keep the Windows PATHEXT lookup here as well. The Windows fake SDK in cmd/exec_test.go only has etcd.cmd, so the Windows tests need PATHEXT to resolve the command.

  2. Revert the Unix execute-bit change in lookPathInEnvWithExt (cmd/commands/exec.go:478) and delete TestLookPathInEnvSkipsNonExecutableUnixFiles. #824 does not need it: with main's Unix lookup restored, the #824 tests pass on Linux. The change also causes two bugs. When the SDK's file is not executable, vfox runs a same-named binary from the parent PATH and exits 0. And the executability test accepts a file the current user cannot run. Any change to Unix lookup needs its own PR and tests.

  3. Move the Windows batch-shim work to a separate PR. That covers cmd/commands/exec_windows.go, cmd/commands/exec_other.go, isWindowsBatchFile, TestExecuteCommandWindowsBatchQuotingAndGuard, and the batch subtest in cmd/exec_test.go. It changes how arguments reach .cmd and .bat targets, so it needs its own review and a Windows CI run. Keep refusing %, !, ", CR, LF and NUL. % expands even inside quotes on a cmd /c line.

  4. Fix the separator hint for path-like command tokens. executeInVfoxEnvWithSeparator passes the raw token to manager.LookupSdk(command) (cmd/commands/exec.go:283). LookupSdk joins that token onto the plugin directory (internal/manager.go:94). With etcd installed and no ./etcd file, vfox exec [email protected] ./etcd arg prints "pass '--' before the command to use multiple SDKs". ../plugin/etcd does the same. Call LookupSdk only for a bare name: no path separator, and no . or ... Add tests for ./etcd and ../plugin/etcd.

  5. Apply the Version == "" condition to the command-not-found hint at exec.go:279, as the resolve-time hint at exec.go:258 already does. Otherwise vfox exec [email protected] [email protected] -- --version says the pinned etcd "was treated as an SDK instead of the command". Add a test for this input.

  6. Document the escape hatch. Say that a tool which itself needs the probe can be reached through a shell, for example vfox exec <sdk> sh -c '<tool> --generate-shell-completion'. I checked that this passes the flag through.

What I checked

  • go test -count=1 ./... on Linux at a507d6a: all packages pass.
  • go vet for linux, windows and darwin, and go test -c ./cmd/commands for windows: pass.
  • Shell runs against a fake etcd SDK, this PR and main side by side.
  • Lookup experiment: with main's Unix lookup restored and its test removed, go test ./cmd ./cmd/commands passes on Linux.
  • Not run: the Windows paths. I read the batch quoting code and found no injection path, but it needs a Windows run.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Thanks @linghengqian for the clear decisions! Addressed all six items in the new commit (and updated the PR description to match the narrowed scope):

  1. Narrowed to exec without -- takes --version and --help after the SDK name as vfox's own flags #824 (docs/, cmd/cmd.go, cmd/commands/exec.go, tests) while keeping Windows PATHEXT lookup in lookPathInEnvWithExt.
  2. Reverted the Unix execute-bit change in lookPathInEnvWithExt back to !info.IsDir() and removed cmd/commands/exec_unix_test.go.
  3. Removed the Windows batch-shim quoting/guard changes (cmd/commands/exec_windows.go, cmd/commands/exec_other.go, isWindowsBatchFile, TestExecuteCommandWindowsBatchQuotingAndGuard, and the batch subtest in cmd/exec_test.go) to handle separately in its own PR.
  4. Fixed path-like tokens in the separator hint (cmd/commands/exec.go): added isBareSDKName so manager.LookupSdk(command) is only called for bare names (no / or \, ., or ..), plus CLI tests for ./etcd and ../plugin/etcd.
  5. Applied Version == "" to the command-not-found note (cmd/commands/exec.go): checked sdkSpecs[len(sdkSpecs)-1].Version == "", plus a CLI test for vfox exec [email protected] [email protected] -- --version.
  6. Documented the completion-probe shell escape hatch (vfox exec <sdk> sh -c '<tool> --generate-shell-completion') in docs/usage/core-commands.md and docs/zh-hans/usage/core-commands.md.

Verified locally after the final edit: go test -race -count=1 ./cmd ./cmd/commands, go vet ./..., and go test -c ./cmd/commands pass for linux/amd64, windows/amd64, and darwin/arm64.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review of #828 at 1f9ce38: not ready to merge

The #824 case is fixed. --version, --help, -h and -help after the command now reach etcd, and the -- form behaves as on main. gofmt, go vet (linux, windows, darwin) and go test ./cmd ./cmd/commands pass. Five items block the merge. Items 1 to 3 repeat requests from the last review that are not complete on this head.

  1. -v, -V and --version before the SDK: the error does not point to vfox --version.

vfox exec -v [email protected] etcd put prints unexpected flag "-v" before SDK and the usage block. The message needs to say that vfox --version prints the vfox version. Add a test that checks it.

  1. Unix lookup still differs from main, and it breaks PATH entries of ..

lookPathInEnvWithExt builds candidates with filepath.Join(dir, command) and splits PATH with filepath.SplitList on every platform. filepath.Join drops the "./", so for a PATH entry of "." the function returns "etcd", and exec.Command then looks for it in vfox's own PATH.

Repro: a PATH entry of "." and an executable etcd in the current directory.

The last review said Unix lookup changes need their own PR. Restore main's Unix branch: strings.Split, and dir + string(os.PathSeparator) + command. I checked this on a copy: the tests pass and the repro works. Add a test with a "." entry.

  1. Windows: the refusal of unsafe characters for batch targets was removed.

The last review asked to keep refusing %, !, ", CR, LF and NUL for .cmd and .bat targets. This head has no such check and no test for it. Main's lookup matched only the exact name in each PATH entry, so it never picked npm.cmd from an SDK directory. The PATHEXT lookup in this PR does find .cmd and .bat files there, so their arguments go to exec.Command unescaped. The os/exec documentation says cmd.exe and batch files use a different unquoting rule and need SysProcAttr.CmdLine. Until the batch PR lands, & | ^ < > ( ) also reach cmd.exe unescaped. If that set cannot wait, refuse it here too. Add a Windows test that a .cmd target with these characters in an argument is refused and that no second command runs.

I have not run this on Windows.

  1. --debug between the SDK and the command is now rejected.

vfox exec [email protected] --debug etcd put works on main (debug output, exit 0). On this head it fails with unexpected flag "--debug" instead of command. Either accept --debug and -debug in that position, as the leading form does, or say in the usage text and in core-commands that vfox flags are not accepted there. Add a test for the choice.

  1. The PR description is out of date.

It does not mention that the root --debug=false now turns debug off (cmd/cmd.go), that --debug=0 and --debug=false after exec do the same, or that -v, -V and --version before the SDK are now errors. Update the description, and add the leading-flag rule to core-commands in both languages.

Please request review again after these are fixed.

@aloneangel45

aloneangel45 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor Author

Addressed all five items from your review in commit d7d3eea:

  1. -v, -V, --version hint before SDK (cmd/commands/exec.go): updated parseExecLeadingArgs so -v, -V, and --version before the SDK tell users use 'vfox --version' to print the vfox version; verified in TestParseExecLeadingArgs and TestExecCLI.
  2. Restored main's Unix PATH lookup (cmd/commands/exec.go): restored the exact Unix branch (strings.Split and dir + string(os.PathSeparator) + command) for non-Windows hosts so PATH=. resolves ./<command> intact. Added TestLookPathInEnvWithDotEntry (cmd/commands/exec_test.go) and the end-to-end PATH=. subtest in cmd/exec_test.go.
  3. Windows batch metacharacter guard restored (cmd/commands/exec.go, cmd/commands/exec_windows_test.go): added isWindowsBatchFile and validateWindowsBatchArgs refusing &, |, ^, <, >, (, ), %, !, ", \r, \n, \x00 for .cmd/.bat targets until batch quoting lands in its own PR, and added TestExecuteCommandRefusesUnsafeBatchArgs proving unsafe args return an error and do not execute any second command while safe args run normally.
  4. Accepted --debug / -debug between SDK and <command> (cmd/commands/exec.go): added parseExecArgs so vfox exec [email protected] --debug etcd put, -debug, --debug=false, and [email protected] [email protected] --debug -- etcd work identically to main, while flags after <command> continue passing through untouched; covered in TestParseExecArgsBetweenSDKAndCommand and cmd/exec_test.go.
  5. Updated PR description and core-commands docs: updated the PR summary to document root cmd/cmd.go --debug=false, --debug=0/--debug=false after exec, and -v/-V/--version errors, and documented the leading-flag rule in both docs/usage/core-commands.md and docs/zh-hans/usage/core-commands.md.

Verified locally on Windows with go test -race -count=1 ./cmd ./cmd/commands (passing including TestExecuteCommandRefusesUnsafeBatchArgs; Unix . lookup subtests skipped on Windows and will run on Linux/macOS CI), plus go vet and go test -c across linux/amd64, windows/amd64, and darwin/arm64.

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ran this on Linux: go test ./cmd ./cmd/commands passes, and go vet is clean for linux, windows/amd64 and darwin/arm64. Against main, the #824 cases behave as described: flags after the command reach the target, --debug works both before the SDK and between the SDK and the command, and -v before the SDK gets the hint. I found two regressions, so this needs changes.

  1. Relative PATH entries on Windows

findWindowsExecutable builds the candidate with filepath.Join(dir, name). For a relative entry such as ., Join drops the ./, so the function returns a bare name. exec.Command then resolves a bare name through the parent process's PATH, not the SDK PATH, and the launch fails. On main the lookup returned .\etcd.exe, which contains a separator and is used as is, so an explicit etcd.exe in a relative entry ran.

Same helper, run on Linux (it is not OS-gated; Windows error wording differs):

findWindowsExecutable(".", "etcd")   -> "etcd.EXE"
exec.Command("etcd.EXE").Err         -> executable file not found
exec.Command("./etcd.EXE").Err       -> nil

I have not run this on Windows. Keep the separator the way the Unix branch does, or put .\ back in front of relative directories, and add a Windows test that puts the fake binary in a relative entry (t.Chdir plus PATH=.) and runs the explicit etcd.exe.

  1. Completion of exec's own flags

Exec.ShellComplete is now a no-op. On main, vfox exec - --generate-shell-completion and vfox exec --he --generate-shell-completion print --help. On this branch they print nothing. --help and -h are still valid before the SDK spec, so the completion is lost with nothing to replace it. Please offer --help while no SDK spec has been given, and stay silent after the SDK spec, where --help goes to the target. The same applies to vfox x.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Addressed both items at 0bda1ec:

  1. Relative PATH entries on Windows (cmd/commands/exec.go, cmd/commands/exec_test.go):
    • Added joinRelativeExecutable and used it in findWindowsExecutable so relative directory candidates keep a separator prefix (e.g. .\etcd.exe / ./etcd.exe when dir is .), ensuring exec.Command runs the resolved executable instead of re-searching the parent process PATH.
    • Added TestFindWindowsExecutableRelativeDirPreservesSeparator (using t.Chdir + PATH=., checking both findWindowsExecutable output and executing an actual .exe on Windows via executeCommand("etcd.exe", ..., {"PATH": "."})).
  2. Completion of exec/x flags before the SDK spec (cmd/commands/exec.go, cmd/exec_test.go):
    • Replaced the no-op Exec.ShellComplete with completeExec (sharing execRawArgs with hasTrailingCompletionFlag). When no SDK spec has been given yet (vfox exec - --generate-shell-completion, vfox exec --he --generate-shell-completion, vfox exec --debug --he --generate-shell-completion, and vfox x ...), it delegates to cli.DefaultCompleteWithFlags and offers --help; once an SDK spec (or --) appears, it stays silent so target flags are not mixed with vfox completions.
    • Added subtests in TestExecCLI (cmd/exec_test.go) covering exec and x before and after the SDK spec.

Local Verification (0bda1ec, Windows host)

  • gofmt -s, git diff --check, 3-OS go vet ./..., and linux/darwin go test -c -o NUL ./cmd ./cmd/commands: passed
  • VFOX_TEST_WINDOWS_REGISTRY=1 go test -race -count=1 ./cmd ./cmd/commands and go test -v -run TestFindWindowsExecutableRelativeDirPreservesSeparator ./cmd/commands: passed (57.562s, 88.791s; Unix . entry tests skip on Windows).

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not ready to merge at 0bda1ec.

The Windows batch-shim path still has two problems that earlier reviews raised, and the docs do not describe the behavior. The Linux and macOS checks are green, and gofmt, go vet and go test ./... pass on Linux as a non-root user. I did not run anything on Windows, so items 1 and 2 come from reading the code.

  1. Arguments to .cmd and .bat targets are refused, including ^ and &

validateWindowsBatchArgs (cmd/commands/exec.go:538-549) refuses & | < > ( ) ^ % ! " and CR, LF and NUL in every argument of a .cmd or .bat target. The PATHEXT lookup now finds npm.CMD in an SDK bin directory, so

vfox exec nodejs@20 npm install express@^4.18.0

is refused on Windows, and there is no way to pass that argument. The earlier review (62d7180) asked for the arguments to be quoted for cmd.exe, with the refusal limited to the characters quoting cannot protect: % ! " CR LF NUL. This head does not do that. Quote the arguments, refuse only that smaller set, and update exec_windows_test.go and cmd/exec_test.go to match.

  1. argv[0] is not checked

The guard only looks at args. execPath is used to decide whether the target is a batch file, and nothing else. A path such as C:\R&D\vfox...\npm.CMD reaches cmd.exe unquoted when the shim starts, and cmd.exe splits the line at &. The earlier review asked for the path to be covered too. Quote it or refuse it, and add a Windows test whose SDK directory contains &.

  1. The refusal is not documented

Neither docs/usage/core-commands.md nor docs/zh-hans/usage/core-commands.md says which arguments are refused for batch targets, or how to work around it. Please add that to both pages.

What I ran on Linux: 17 exec invocations against main, with a fake etcd 3.5.12 SDK and an isolated HOME and VFOX_HOME. They cover the leading and trailing --debug forms, -h, --help, -v, --version, --generate-shell-completion, and the separator notes. The differences from main are the ones the description lists.

@aloneangel45

Copy link
Copy Markdown
Contributor Author

Updated a039a5a and refreshed the PR description to cover all 3 review items:

  1. cmd.exe quoting & narrower refusal (cmd/commands/exec_windows.go, cmd/commands/exec_other.go, cmd/commands/exec.go):
    • Added prepareExecCommand: for .cmd/.bat targets on Windows, buildBatchCmdLine quotes execPath and metacharacter/whitespace arguments for cmd.exe via SysProcAttr.CmdLine (doubling trailing backslashes before closing quotes and wrapping the command line in an outer quote pair so cmd.exe /c's quote-stripping preserves inner quotes), so arguments such as express@^4.18.0, &, |, <, >, (), and spaces pass safely without shell execution.
    • Limited validateWindowsBatchCommand refusal strictly to characters cmd.exe quoting cannot protect (%, !, ", CR, LF, NUL).
  2. argv[0] (execPath) coverage:
    • validateWindowsBatchCommand checks execPath for %, !, ", CR, LF, NUL, and buildBatchCmdLine always quotes execPath ("..."), so SDK paths containing & (e.g. R&D\bin\npm.CMD) run cleanly without splitting at &.
    • Updated cmd/commands/exec_windows_test.go (TestExecuteCommandRefusesUnsafeBatchArgs + TestExecuteCommandQuotesBatchArgsAndAmpersandPath) and added an end-to-end Windows CLI test in cmd/exec_test.go verifying vfox exec [email protected] npm install express@^4.18.0 "a&echo pwned" from an R&D SDK directory plus %PATH% refusal.
  3. Documentation (docs/usage/core-commands.md, docs/zh-hans/usage/core-commands.md):
    • Added a Windows Batch Shims (.cmd / .bat) warning block to both pages listing the refused characters (%, !, ", CR, LF, NUL) and workarounds (invoke the .exe binary directly, run the underlying script directly, or wrap via powershell/sh).

Verified locally on Windows: gofmt -l clean on changed Go files, 3-OS go vet ./... (windows/linux/darwin), linux/darwin go test -c cross-compile (./cmd, ./cmd/commands), go test -race -count=1 ./cmd (59.465s), and non-registry go test -race -count=1 ./cmd/commands (including the new Windows batch probe tests at 0.01s / 2.16s; registry-mutating tests skipped with VFOX_TEST_WINDOWS_REGISTRY unset).

@linghengqian linghengqian added bug Something isn't working and removed need-more-info labels Nov 24, 2026

@linghengqian linghengqian left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

exec without -- takes --version and --help after the SDK name as vfox's own flags

2 participants