Skip to content

fix(dev): execute dev command with shell operators (&&, ||, etc.)#8234

Open
puneetdixit200 wants to merge 3 commits into
netlify:mainfrom
puneetdixit200:fix-dev-command-shell-operators-8228
Open

fix(dev): execute dev command with shell operators (&&, ||, etc.)#8234
puneetdixit200 wants to merge 3 commits into
netlify:mainfrom
puneetdixit200:fix-dev-command-shell-operators-8228

Conversation

@puneetdixit200
Copy link
Copy Markdown

Summary

Fixes #8228 by running dev.command through a shell so command strings with shell operators (like &&) are interpreted correctly in netlify dev.

Changes

  • Updated runCommand to call execa.command(..., { shell: true }).
  • Added integration regression test: should support shell operators in \command`intests/integration/framework-detection.test.ts`.

Why

execa.command() does not interpret shell operators by default. Without shell: true, a command like:

[dev]
command = "bundle install && bundle exec jekyll serve --port 4002 --incremental --future"

is parsed as a single command with literal && args, causing the observed failure.

Validation

  • npm run build
  • npx vitest run tests/integration/framework-detection.test.ts -t 'should support shell operators in \command`'`
  • npx vitest run tests/integration/framework-detection.test.ts -t "should print specific error when command doesn't exist"
  • npx vitest run tests/integration/framework-detection.test.ts -t 'should run \command` when both `command` and `targetPort` are configured'`

Copilot AI review requested due to automatic review settings May 6, 2026 05:53
@puneetdixit200 puneetdixit200 requested a review from a team as a code owner May 6, 2026 05:53
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 6, 2026

Review Change Stack

📝 Walkthrough

Summary by CodeRabbit

  • New Features

    • Support for shell operators (e.g., &&) in dev commands, enabling composite command sequences.
  • Bug Fixes

    • More reliable detection and clearer reporting when a command is missing or fails to start a server.
  • Tests

    • Added an integration test to verify shell operator behavior and that separate command outputs are captured correctly.

Walkthrough

runCommand now runs commands through a shell (execa.command with shell: true). Helpers were added: CommandResult shape, isCommandResult type guard, and getCommandName to correctly extract possibly quoted command names. Non-existent-command detection was rewritten to use the result shape and check exitCode === 127 or platform “not recognized” messages instead of relying on Error.message. An integration test verifies commands with shell operators (e.g., "echo first && echo second") produce separate stdout lines and are not passed as literal arguments.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(dev): execute dev command with shell operators' clearly and concisely summarizes the main change - enabling shell operators in dev commands.
Description check ✅ Passed The description is directly related to the changeset, explaining why the fix was needed, what was changed, and how validation was performed.
Linked Issues check ✅ Passed The PR addresses issue #8228 by modifying runCommand to use execa.command with shell: true, enabling shell operators like && to be interpreted correctly rather than treated as literal arguments.
Out of Scope Changes check ✅ Passed All changes are directly in scope: the shell.ts modification implements the required fix, and the integration test validates the new functionality without introducing unrelated modifications.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR fixes netlify dev execution of dev.command values that include shell operators (e.g., &&, ||) by running the configured command through a shell, matching the behavior users expect from netlify.toml command strings.

Changes:

  • Updated runCommand to execute via execa.command(..., { shell: true }) so shell operators are interpreted.
  • Added an integration regression test verifying dev.command supports && and does not treat it as a literal argument.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
src/utils/shell.ts Enables shell mode for netlify dev command execution to support shell operators in command strings.
tests/integration/framework-detection.test.ts Adds an integration test to confirm dev.command supports && semantics.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread src/utils/shell.ts
Comment on lines 69 to +73
const commandProcess = execa.command(command, {
preferLocal: true,
// Command strings in netlify.toml may use shell operators like `&&`.
// execa.command() does not interpret these unless shell mode is enabled.
shell: true,
Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
src/utils/shell.ts (1)

115-134: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

isNonExistingCommandError is broken by shell: true — non-existing command errors now show the wrong message.

With shell: true, execa spawns the system shell (/bin/sh, cmd.exe) rather than the user command directly. The shell binary always starts successfully, so code: 'ENOENT' is never set on the result when the user's command doesn't exist on POSIX. On POSIX, the shell simply exits with code 127 instead.

Similarly on Windows, when cmd.exe reports "is not recognized..." it writes that to stdout/stderr — it does not appear in commandError.message, so the string-match branch also misses it.

The practical consequence: the user-friendly message "Failed running command: X. Please verify 'X' exists" (line 119) will never be shown for any non-existing command after this change. Instead, the generic shortMessage path (line 128) fires. The snapshot test at tests/integration/__snapshots__/framework-detection.test.ts.snap shows the friendly error message as expected output, but the current implementation cannot produce it.

To fix, check result.exitCode === 127 on POSIX (the shell's canonical "command not found" exit code) as a complement to the existing ENOENT check:

🐛 Proposed fix
 const isNonExistingCommandError = ({ command, error: commandError }: { command: string; error: unknown }) => {
   // `ENOENT` is only returned for non Windows systems
   // See https://github.com/sindresorhus/execa/pull/447
   if (isErrnoException(commandError) && commandError.code === 'ENOENT') {
     return true
   }

+  // When shell: true is used, the shell itself starts successfully.
+  // On POSIX, a missing command causes the shell to exit with code 127.
+  if (
+    commandError instanceof Error &&
+    'exitCode' in commandError &&
+    (commandError as { exitCode: unknown }).exitCode === 127
+  ) {
+    return true
+  }
+
   // if the command is a package manager we let it report the error
   if (['yarn', 'npm', 'pnpm'].includes(command)) {
     return false
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/shell.ts` around lines 115 - 134, The non-existing-command
detection (used where commandProcess resolves and isNonExistingCommandError is
called) fails when execa is run with shell: true because shells succeed but
return exit code 127 on POSIX or emit human text on Windows; update
isNonExistingCommandError (and the call-site logic around result in the
commandProcess.then block) to treat result.exitCode === 127 as a "command not
found" on POSIX and also inspect result.stderr/result.stdout for Windows phrases
like "is not recognized as an internal or external command" (or "is not
recognized") for cmd.exe, so that the friendly log path (the branch that logs
Failed running command: ... Please verify 'X' exists) is triggered when
shell-based command resolution fails.
🧹 Nitpick comments (2)
tests/integration/framework-detection.test.ts (1)

133-150: 💤 Low value

New integration test LGTM — one minor regex note.

The test structure correctly mirrors the existing "should run \command`..."pattern and validates both the positive (shell operators interpreted) and negative (literal&&` not echoed) cases.

One minor note on Line 146: \s* between the two capture groups includes \n, so the regex would match even if arbitrary blank lines appear between first and second. Using [^\S\r\n]* (horizontal whitespace only) is stricter:

🔧 Optional tightening
-        t.expect(output).toMatch(/\nfirst\s*\r?\n\s*second\r?\n/i)
+        t.expect(output).toMatch(/\nfirst[^\S\r\n]*\r?\n[^\S\r\n]*second\r?\n/i)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/integration/framework-detection.test.ts` around lines 133 - 150, The
regex in the test "should support shell operators in `command`" is too
permissive because the `\s*` between the capture groups can match newlines;
update the assertion that checks the output (the t.expect(output).toMatch(...)
call) to use horizontal-whitespace-only matching (e.g., replace `\s*` between
`first` and `second` with `[^\S\r\n]*`) so blank lines won't satisfy the test;
locate this in the test using withSiteBuilder/withNetlifyToml/withDevServer and
normalizeSnapshot to adjust the pattern accordingly.
src/utils/shell.ts (1)

71-73: 💤 Low value

Remove code-explaining comments.

The two comments describe what execa.command() does without shell: true, which is implementation documentation rather than essential context. The option name is self-explanatory and the PR description/commit message is the right place for this rationale.

♻️ Proposed change
-    // Command strings in netlify.toml may use shell operators like `&&`.
-    // execa.command() does not interpret these unless shell mode is enabled.
     shell: true,

As per coding guidelines: "Never write comments on what the code does; make the code clean and self-explanatory instead."

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/shell.ts` around lines 71 - 73, Remove the explanatory comment
lines above the shell option so the code only contains the self-explanatory
option "shell: true" in the execa command invocation; locate the object where
execa.command() is configured (the block that sets shell: true in
src/utils/shell.ts) and delete the two comment lines describing why shell mode
is needed, leaving the option as-is.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@src/utils/shell.ts`:
- Around line 115-134: The non-existing-command detection (used where
commandProcess resolves and isNonExistingCommandError is called) fails when
execa is run with shell: true because shells succeed but return exit code 127 on
POSIX or emit human text on Windows; update isNonExistingCommandError (and the
call-site logic around result in the commandProcess.then block) to treat
result.exitCode === 127 as a "command not found" on POSIX and also inspect
result.stderr/result.stdout for Windows phrases like "is not recognized as an
internal or external command" (or "is not recognized") for cmd.exe, so that the
friendly log path (the branch that logs Failed running command: ... Please
verify 'X' exists) is triggered when shell-based command resolution fails.

---

Nitpick comments:
In `@src/utils/shell.ts`:
- Around line 71-73: Remove the explanatory comment lines above the shell option
so the code only contains the self-explanatory option "shell: true" in the execa
command invocation; locate the object where execa.command() is configured (the
block that sets shell: true in src/utils/shell.ts) and delete the two comment
lines describing why shell mode is needed, leaving the option as-is.

In `@tests/integration/framework-detection.test.ts`:
- Around line 133-150: The regex in the test "should support shell operators in
`command`" is too permissive because the `\s*` between the capture groups can
match newlines; update the assertion that checks the output (the
t.expect(output).toMatch(...) call) to use horizontal-whitespace-only matching
(e.g., replace `\s*` between `first` and `second` with `[^\S\r\n]*`) so blank
lines won't satisfy the test; locate this in the test using
withSiteBuilder/withNetlifyToml/withDevServer and normalizeSnapshot to adjust
the pattern accordingly.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3f2281fc-868f-4dda-a909-89e6fc361732

📥 Commits

Reviewing files that changed from the base of the PR and between 30d4ef0 and 835fb0b.

📒 Files selected for processing (2)
  • src/utils/shell.ts
  • tests/integration/framework-detection.test.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
src/utils/shell.ts (1)

23-23: 💤 Low value

Type guard is overly permissive.

isCommandResult accepts any non-null object rather than verifying the expected shape. This works in practice because commandError is an execa result, but the guard doesn't actually narrow to CommandResult.

♻️ Optional: Strengthen the type guard
-const isCommandResult = (value: unknown): value is CommandResult => typeof value === 'object' && value !== null
+const isCommandResult = (value: unknown): value is CommandResult =>
+  typeof value === 'object' &&
+  value !== null &&
+  ('exitCode' in value || 'message' in value || 'shortMessage' in value || 'stderr' in value || 'stdout' in value)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/shell.ts` at line 23, The type guard isCommandResult is too
permissive (it only checks for a non-null object) and doesn't ensure the shape
of CommandResult; update isCommandResult to verify required properties from
CommandResult (e.g., check for string/number/boolean properties and fields you
rely on such as stderr, stdout, exitCode or signal as appropriate) so that
narrowing actually identifies an execa CommandResult used in commandError
handling; locate the function isCommandResult in src/utils/shell.ts and add
checks for those specific keys and types before returning true.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@src/utils/shell.ts`:
- Line 23: The type guard isCommandResult is too permissive (it only checks for
a non-null object) and doesn't ensure the shape of CommandResult; update
isCommandResult to verify required properties from CommandResult (e.g., check
for string/number/boolean properties and fields you rely on such as stderr,
stdout, exitCode or signal as appropriate) so that narrowing actually identifies
an execa CommandResult used in commandError handling; locate the function
isCommandResult in src/utils/shell.ts and add checks for those specific keys and
types before returning true.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dd9ef1f3-623b-434c-b741-c50daad944e0

📥 Commits

Reviewing files that changed from the base of the PR and between 835fb0b and d601605.

📒 Files selected for processing (2)
  • src/utils/shell.ts
  • tests/integration/framework-detection.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • tests/integration/framework-detection.test.ts

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/utils/shell.ts`:
- Around line 32-35: The current getCommandName logic and the 127-handling
branch should not always map exit code 127 to the first token; update the code
that emits the "Please verify ..." message (the branch handling exit code 127
around the existing message emission) to first detect shell operators and
leading env assignments and only emit the specialized message when safe: use a
shell-syntax check (/(?:&&|\|\||[|;<>])/) to skip compound commands and an
env-assignment check (/^\s*[\w.-]+=/) to skip commands with leading VAR=
assignments; keep getCommandName as-is for simple cases but do not rely on it
when either check matches (fall back to a generic error message), and add
regression tests that run a failing compound command (e.g., "echo ok &&
missing-cmd") and a failing env-assigned command (e.g., "FOO=1 missing-cmd") to
ensure the specialized message is not emitted incorrectly.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 3d0c695b-66d2-47ed-941a-4f28e27c6ac3

📥 Commits

Reviewing files that changed from the base of the PR and between d601605 and 5d256fc.

📒 Files selected for processing (1)
  • src/utils/shell.ts

Comment thread src/utils/shell.ts
Comment on lines +32 to +35
const getCommandName = (command: string) => {
const match = /^(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(command.trim())

return match?.[1] ?? match?.[2] ?? match?.[3] ?? command
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Don't map every shell 127 back to the first token.

When shell execution is enabled (shell: true), exit code 127 can result from any command in a compound command chain or from a missing executable preceded by environment variable assignments. For example:

  • echo ok && missing-cmd will currently ask users to verify 'echo' exists (incorrect)
  • FOO=1 missing-cmd will point at 'FOO=1' (not a valid executable)

The current implementation only extracts the first token via regex, missing the actual failing command. Only emit the specialized "Please verify ..." message when you can safely attribute the failure to the first executable. Skip it for:

  1. Compound commands containing shell operators (&&, ||, |, ;, <, >)
  2. Commands preceded by leading environment variable assignments

Consider applying checks at lines 138-143 (where the message is emitted):

Shell syntax check: /(?:&&|\|\||[|;<>])/
Env assignment check: /^\s*[\w.-]+=/ 

Also add regression tests covering a missing command after && and one with a leading environment assignment to prevent this issue from recurring.

🧰 Tools
🪛 OpenGrep (1.21.0)

[ERROR] 33-33: Dynamic command passed to child_process.exec/execSync. Use child_process.execFile or spawn with an argument array instead.

(coderabbit.command-injection.exec-js)

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@src/utils/shell.ts` around lines 32 - 35, The current getCommandName logic
and the 127-handling branch should not always map exit code 127 to the first
token; update the code that emits the "Please verify ..." message (the branch
handling exit code 127 around the existing message emission) to first detect
shell operators and leading env assignments and only emit the specialized
message when safe: use a shell-syntax check (/(?:&&|\|\||[|;<>])/) to skip
compound commands and an env-assignment check (/^\s*[\w.-]+=/) to skip commands
with leading VAR= assignments; keep getCommandName as-is for simple cases but do
not rely on it when either check matches (fall back to a generic error message),
and add regression tests that run a failing compound command (e.g., "echo ok &&
missing-cmd") and a failing env-assigned command (e.g., "FOO=1 missing-cmd") to
ensure the specialized message is not emitted incorrectly.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dev command with && incorrectly parsed

2 participants