Skip to content

test: add unit tests for shell-substitution helpers - #2478

Closed
MrChees8157 wants to merge 2 commits into
affaan-m:mainfrom
MrChees8157:test/shell-substitution-coverage
Closed

MrChees8157 wants to merge 2 commits into
affaan-m:mainfrom
MrChees8157:test/shell-substitution-coverage

Conversation

@MrChees8157

Copy link
Copy Markdown

What

Adds tests/lib/shell-substitution.test.js, covering the three parsers exported from scripts/lib/shell-substitution.js:

  • extractCommandSubstitutions
  • extractSubshellGroups
  • extractBraceGroups

This module previously had no matching test in tests/lib/, whereas the project convention (.claude/rules/node.md) is that new scripts/lib/ modules require a matching test.

Coverage

19 assertions verifying the documented quoting semantics, including:

  • Substitutions are scanned inside double quotes but ignored inside single quotes.
  • Plain (...) subshell groups and { ...; } brace groups are distinguished from $(...) command substitutions.
  • Nested groups are extracted recursively.
  • Edge cases: empty string, null/undefined, and inputs with no substitution.

Testing

  • node tests/lib/shell-substitution.test.js → 19 passed, 0 failed.
  • Test file follows the existing tests/lib/shell-split.test.js style and is auto-discovered by tests/run-all.js.
  • No production code changed.

🤖 Generated with Claude Code

Cover the three parsers exported from scripts/lib/shell-substitution.js
(extractCommandSubstitutions, extractSubshellGroups, extractBraceGroups)
which previously had no matching test in tests/lib/.

Cases assert the documented quoting semantics: substitutions are scanned
inside double quotes but ignored inside single quotes, plain (...) and
{ ...; } groups are distinguished from $(...), and nested groups are
extracted recursively.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
@MrChees8157
MrChees8157 requested a review from affaan-m as a code owner July 8, 2026 18:34
@coderabbitai

coderabbitai Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 47cbcf2d-d6b6-4ada-b735-06312e61dc0a

📥 Commits

Reviewing files that changed from the base of the PR and between 3e6ec37 and a459507.

📒 Files selected for processing (1)
  • tests/lib/shell-substitution.test.js
📜 Recent review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/lib/shell-substitution.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/lib/shell-substitution.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/lib/shell-substitution.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/lib/shell-substitution.test.js
🔇 Additional comments (1)
tests/lib/shell-substitution.test.js (1)

76-79: LGTM!

Also applies to: 98-101


📝 Walkthrough

Summary by CodeRabbit

  • Tests
    • Added new test coverage for shell parsing behavior, including nested command substitutions and correct handling of quoted strings.
    • Added validation for subshell group extraction and brace group detection, including edge cases for empty, null, or unsupported patterns.

Walkthrough

This PR adds a Node.js test file for shell-substitution helpers. It covers command substitutions, subshell groups, and brace groups, plus runner output and exit handling.

Changes

Shell substitution tests

Layer / File(s) Summary
Test harness setup
tests/lib/shell-substitution.test.js
Requires assert and the three helper functions, and defines a test() wrapper that tracks pass/fail counts.
Command substitution extraction tests
tests/lib/shell-substitution.test.js
Verifies $(...) and backtick extraction, nesting, quote handling, and empty/null input behavior.
Subshell group extraction tests
tests/lib/shell-substitution.test.js
Verifies ( ... ) extraction, skipping of $(...) spans, nested detection, and quote-aware parsing.
Brace group extraction tests
tests/lib/shell-substitution.test.js
Verifies { ...; } extraction with spacing rules, skipping subshell content, nested groups, empty/null behavior, and final results output with non-zero exit on failure.

Estimated code review effort: 2 (Simple) | ~10 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly states the change is adding unit tests for shell-substitution helpers.
Description check ✅ Passed The description matches the change set and summarizes the new test coverage accurately.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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.

@greptile-apps

greptile-apps Bot commented Jul 8, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

Adds tests/lib/shell-substitution.test.js, a new test file covering all three public exports of scripts/lib/shell-substitution.js, which previously had no matching test. No production code is changed.

  • 21 test() cases span extractCommandSubstitutions, extractSubshellGroups, and extractBraceGroups, verifying quoting semantics (single vs. double quotes), $(…)/backtick skipping, recursive nesting, and null/undefined coercion.
  • The file follows the shell-split.test.js style exactly and is auto-discovered by tests/run-all.js via the tests/**/*.test.js glob.

Confidence Score: 5/5

Test-only addition with no production code changes; all assertions were verified correct against the source implementation.

Every test case was traced against the actual source logic and produces the expected output. The file follows established project conventions, is auto-discovered by the test runner, and exits non-zero on failure so CI will catch regressions.

No files require special attention.

Important Files Changed

Filename Overview
tests/lib/shell-substitution.test.js New test file; all 21 assertions verified correct against the source implementation. PR description says "19 passed" but the actual count is 21 (null/undefined tests for extractSubshellGroups and extractBraceGroups appear to have been added after the description was written).

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A[tests/run-all.js\nauto-discovers *.test.js] --> B[shell-substitution.test.js]
    B --> C[extractCommandSubstitutions\n8 test cases]
    B --> D[extractSubshellGroups\n7 test cases]
    B --> E[extractBraceGroups\n6 test cases]
    C --> F["plain $(…), backtick, nested,\nsingle/double quote, empty, null/undefined"]
    D --> G["plain (…), skip $(…),\nnested, quotes, null/undefined"]
    E --> H["{ …; }, no-space {token},\nskip (…), nested, null/undefined"]
    F --> I[scripts/lib/shell-substitution.js]
    G --> I
    H --> I
Loading
%%{init: {'theme': 'base', 'themeVariables': {"darkMode": true, "background": "#0d1117", "primaryColor": "#21262d", "primaryTextColor": "#e6edf3", "primaryBorderColor": "#8b949e", "lineColor": "#8b949e", "textColor": "#e6edf3", "edgeLabelBackground": "#161b22", "actorBkg": "#21262d", "actorBorder": "#8b949e", "actorTextColor": "#e6edf3", "actorLineColor": "#8b949e", "signalColor": "#8b949e", "signalTextColor": "#e6edf3", "noteBkgColor": "#373320", "noteBorderColor": "#d4a72c", "noteTextColor": "#f0e6c0", "labelBoxBkgColor": "#21262d", "labelBoxBorderColor": "#8b949e", "labelTextColor": "#e6edf3", "loopTextColor": "#e6edf3", "activationBkgColor": "#30363d", "activationBorderColor": "#8b949e"}}}%%
flowchart TD
    A[tests/run-all.js\nauto-discovers *.test.js] --> B[shell-substitution.test.js]
    B --> C[extractCommandSubstitutions\n8 test cases]
    B --> D[extractSubshellGroups\n7 test cases]
    B --> E[extractBraceGroups\n6 test cases]
    C --> F["plain $(…), backtick, nested,\nsingle/double quote, empty, null/undefined"]
    D --> G["plain (…), skip $(…),\nnested, quotes, null/undefined"]
    E --> H["{ …; }, no-space {token},\nskip (…), nested, null/undefined"]
    F --> I[scripts/lib/shell-substitution.js]
    G --> I
    H --> I
Loading

Reviews (2): Last reviewed commit: "test: cover null/undefined input for sub..." | Re-trigger Greptile

Comment thread tests/lib/shell-substitution.test.js Resolved
Comment thread tests/lib/shell-substitution.test.js Resolved
Address Greptile review feedback on #2478: extractSubshellGroups and
extractBraceGroups share the same String(input || '') coercion as
extractCommandSubstitutions, so assert the same null/undefined guard
for them too.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 2

🤖 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 `@tests/lib/shell-substitution.test.js`:
- Around line 56-75: Add a focused test in extractSubshellGroups coverage for
backtick span skipping: verify that a command containing backticks (for example
via the existing extractSubshellGroups test block) returns an empty array and
does not treat any parenthesized content inside the backtick span as a subshell.
Use the existing extractSubshellGroups test suite in shell-substitution.test.js
to exercise the backtick-ignoring branch in the implementation.
- Around line 77-93: Add coverage in extractBraceGroups tests for the skip logic
that handles $(...) and backtick spans inside brace group bodies. Update the
test block in shell-substitution.test.js to include cases where a closing brace
appears inside a command substitution or backtick expression and confirm
extractBraceGroups still returns the enclosing brace group unchanged. Use the
existing extractBraceGroups test suite and its helper expectations to locate the
right area and verify both nested and non-nested behavior.
🪄 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: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: 38fb0b35-ab00-4819-b9f3-aaa8eb0ca7ca

📥 Commits

Reviewing files that changed from the base of the PR and between 4130457 and 3e6ec37.

📒 Files selected for processing (1)
  • tests/lib/shell-substitution.test.js
📜 Review details
⏰ Context from checks skipped due to timeout. (1)
  • GitHub Check: Greptile Review
🧰 Additional context used
📓 Path-based instructions (13)
**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}

📄 CodeRabbit inference engine (.cursor/rules/common-coding-style.md)

**/*.{js,ts,jsx,tsx,py,java,cs,go,rb,php,scala,kt}: Always create new objects, never mutate existing ones. Use immutable patterns to prevent hidden side effects and enable safe concurrency
Organize code into many small files (200-400 lines typical, 800 lines max) organized by feature/domain rather than by type
Always handle errors explicitly at every level and never silently swallow errors
Always validate all user input before processing at system boundaries
Use schema-based validation where available
Fail fast with clear error messages when validation fails
Never trust external data (API responses, user input, file content)
Ensure code is readable and well-named
Keep functions small (less than 50 lines)
Keep files focused (less than 800 lines)
Avoid deep nesting (more than 4 levels)
Do not use hardcoded values; use constants or configuration instead

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

No hardcoded secrets (API keys, passwords, tokens) - validate before any commit

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php}: All user inputs must be validated
Enable CSRF protection on all state-changing endpoints
Verify authentication and authorization for all protected endpoints
Implement rate limiting on all endpoints to prevent abuse
Ensure error messages do not leak sensitive data in responses

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,sql}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Use parameterized queries to prevent SQL injection

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,html,php,java,cs,rb,go}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

Implement XSS prevention by sanitizing HTML output

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,py,java,cs,rb,go,php,swift,kt,rs,c,cpp,h,hpp,properties,yml,yaml,json,env,config}

📄 CodeRabbit inference engine (.cursor/rules/common-security.md)

NEVER hardcode secrets in source code - ALWAYS use environment variables or a secret manager

Files:

  • tests/lib/shell-substitution.test.js
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/typescript-coding-style.md)

**/*.{ts,tsx,js,jsx}: Use spread operator for immutable updates in TypeScript/JavaScript instead of direct mutation
Use async/await with try-catch for error handling in TypeScript/JavaScript
Use Zod for schema-based input validation in TypeScript/JavaScript
No console.log statements in production code; use proper logging libraries instead

**/*.{ts,tsx,js,jsx}: Auto-format JavaScript/TypeScript files using Prettier after edit
Warn about console.log statements in edited files
Check all modified files for console.log statements before session ends

**/*.{ts,tsx,js,jsx}: Use the ApiResponse interface pattern with generic type parameter: interface ApiResponse<T> { success: boolean; data?: T; error?: string; meta?: { total: number; page: number; limit: number; } }
Implement custom React hooks following the pattern: export a named function with use prefix, generic type parameters, and proper useEffect cleanup for side effects

**/*.{ts,tsx,js,jsx}: Never hardcode secrets; always use environment variables for sensitive credentials like API keys
Throw an error when required environment variables are not configured to fail fast and ensure security prerequisites are met

Use Playwright as the E2E testing framework for critical user flows in TypeScript/JavaScript

Files:

  • tests/lib/shell-substitution.test.js
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{test,spec}.{js,ts,jsx,tsx}: Write tests before implementation (test-driven development); target 80%+ coverage
Achieve minimum 80% test coverage across all three layers: Unit, Integration, and E2E
Use AAA structure (Arrange / Act / Assert) in tests with descriptive test names that explain behavior under test

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts,jsx,tsx}: Always create new objects and never mutate in place; return new copies instead
Keep files between 200–400 lines typical, with a maximum of 800 lines
Extract helpers when a file exceeds 200 lines
Handle errors explicitly at every level; never swallow errors silently
Validate all user input before processing; use schema-based validation where available
Never trust external data (API responses, file content, query params); always validate
All user inputs must be validated and sanitized
Error messages must be scrubbed of sensitive internals
Use readable, well-named identifiers in all code
Keep functions under 50 lines
Keep files under 800 lines
Avoid nesting deeper than 4 levels
Implement comprehensive error handling in all code
Do not hardcode values; use constants or environment configuration instead
Do not use in-place mutation; always return new objects or state

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,jsx,tsx,json,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Do not hardcode secrets, API keys, passwords, or tokens

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use parameterized queries for all database writes (no string interpolation)
Auth/authz must be checked server-side for every sensitive path
Rate limiting must be applied to all public endpoints

Files:

  • tests/lib/shell-substitution.test.js
**/*.{jsx,tsx,js,ts}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

HTML output must be sanitized where applicable

Files:

  • tests/lib/shell-substitution.test.js
**/*.{js,ts,env*}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Required environment variables must be validated at startup

Files:

  • tests/lib/shell-substitution.test.js
🔇 Additional comments (2)
tests/lib/shell-substitution.test.js (2)

1-23: LGTM!


25-54: LGTM!

Comment on lines +56 to +75
// extractSubshellGroups
console.log('\nextractSubshellGroups:');
test('extracts a plain (...) subshell body', () => {
assert.deepStrictEqual(extractSubshellGroups('(npm run dev)'), ['npm run dev']);
});
test('skips $(...) command substitutions', () => {
assert.deepStrictEqual(extractSubshellGroups('echo $(whoami)'), []);
});
test('extracts nested (...) recursively', () => {
assert.deepStrictEqual(extractSubshellGroups('(a && (b))'), ['a && (b)', 'b']);
});
test('ignores parens inside single quotes', () => {
assert.deepStrictEqual(extractSubshellGroups("echo '(not a subshell)'"), []);
});
test('ignores parens inside double quotes', () => {
assert.deepStrictEqual(extractSubshellGroups('echo "(not a subshell)"'), []);
});
test('returns [] when there is no subshell', () => {
assert.deepStrictEqual(extractSubshellGroups('echo hello'), []);
});

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.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test for backtick span skipping in extractSubshellGroups.

The implementation explicitly skips backtick spans (lines ~189-196 in scripts/lib/shell-substitution.js), but no test exercises this path. A command like echo \id`should return[]` since the parens inside backticks (if any) should be ignored. Adding this test would cover an important branch of the skip logic.

🧪 Suggested additional test
 test('returns [] when there is no subshell', () => {
   assert.deepStrictEqual(extractSubshellGroups('echo hello'), []);
 });
+test('skips backtick command substitutions', () => {
+  assert.deepStrictEqual(extractSubshellGroups('echo `id`'), []);
+});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// extractSubshellGroups
console.log('\nextractSubshellGroups:');
test('extracts a plain (...) subshell body', () => {
assert.deepStrictEqual(extractSubshellGroups('(npm run dev)'), ['npm run dev']);
});
test('skips $(...) command substitutions', () => {
assert.deepStrictEqual(extractSubshellGroups('echo $(whoami)'), []);
});
test('extracts nested (...) recursively', () => {
assert.deepStrictEqual(extractSubshellGroups('(a && (b))'), ['a && (b)', 'b']);
});
test('ignores parens inside single quotes', () => {
assert.deepStrictEqual(extractSubshellGroups("echo '(not a subshell)'"), []);
});
test('ignores parens inside double quotes', () => {
assert.deepStrictEqual(extractSubshellGroups('echo "(not a subshell)"'), []);
});
test('returns [] when there is no subshell', () => {
assert.deepStrictEqual(extractSubshellGroups('echo hello'), []);
});
// extractSubshellGroups
console.log('\nextractSubshellGroups:');
test('extracts a plain (...) subshell body', () => {
assert.deepStrictEqual(extractSubshellGroups('(npm run dev)'), ['npm run dev']);
});
test('skips $(...) command substitutions', () => {
assert.deepStrictEqual(extractSubshellGroups('echo $(whoami)'), []);
});
test('extracts nested (...) recursively', () => {
assert.deepStrictEqual(extractSubshellGroups('(a && (b))'), ['a && (b)', 'b']);
});
test('ignores parens inside single quotes', () => {
assert.deepStrictEqual(extractSubshellGroups("echo '(not a subshell)'"), []);
});
test('ignores parens inside double quotes', () => {
assert.deepStrictEqual(extractSubshellGroups('echo "(not a subshell)"'), []);
});
test('returns [] when there is no subshell', () => {
assert.deepStrictEqual(extractSubshellGroups('echo hello'), []);
});
test('skips backtick command substitutions', () => {
assert.deepStrictEqual(extractSubshellGroups('echo `id`'), []);
});
🤖 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/lib/shell-substitution.test.js` around lines 56 - 75, Add a focused
test in extractSubshellGroups coverage for backtick span skipping: verify that a
command containing backticks (for example via the existing extractSubshellGroups
test block) returns an empty array and does not treat any parenthesized content
inside the backtick span as a subshell. Use the existing extractSubshellGroups
test suite in shell-substitution.test.js to exercise the backtick-ignoring
branch in the implementation.

Comment on lines +77 to +93
// extractBraceGroups
console.log('\nextractBraceGroups:');
test('extracts a { ...; } brace group body', () => {
assert.deepStrictEqual(extractBraceGroups('{ npm run dev; }'), [' npm run dev; ']);
});
test('does not treat {token} (no space) as a group', () => {
assert.deepStrictEqual(extractBraceGroups('{npm run dev}'), []);
});
test('skips (...) subshell spans', () => {
assert.deepStrictEqual(extractBraceGroups('(npm run dev)'), []);
});
test('extracts nested brace groups recursively', () => {
assert.deepStrictEqual(extractBraceGroups('{ a; { b; }; }'), [' a; { b; }; ', ' b; ']);
});
test('returns [] when there is no brace group', () => {
assert.deepStrictEqual(extractBraceGroups('echo hello'), []);
});

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.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add tests for $(...) and backtick span skipping inside brace groups.

The extractBraceGroups implementation has explicit skip logic for $(...) spans (lines ~393-418) and backtick spans (lines ~420+) inside brace group bodies, but neither path is tested. These are important branches — a } inside a command substitution or backtick body must not close the enclosing brace group. Consider adding:

🧪 Suggested additional tests
 test('returns [] when there is no brace group', () => {
   assert.deepStrictEqual(extractBraceGroups('echo hello'), []);
 });
+test('skips $(...) spans inside brace groups', () => {
+  assert.deepStrictEqual(extractBraceGroups('{ echo $(whoami); }'), [' echo $(whoami); ']);
+});
+test('skips backtick spans inside brace groups', () => {
+  assert.deepStrictEqual(extractBraceGroups('{ echo `id`; }'), [' echo `id`; ']);
+});
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// extractBraceGroups
console.log('\nextractBraceGroups:');
test('extracts a { ...; } brace group body', () => {
assert.deepStrictEqual(extractBraceGroups('{ npm run dev; }'), [' npm run dev; ']);
});
test('does not treat {token} (no space) as a group', () => {
assert.deepStrictEqual(extractBraceGroups('{npm run dev}'), []);
});
test('skips (...) subshell spans', () => {
assert.deepStrictEqual(extractBraceGroups('(npm run dev)'), []);
});
test('extracts nested brace groups recursively', () => {
assert.deepStrictEqual(extractBraceGroups('{ a; { b; }; }'), [' a; { b; }; ', ' b; ']);
});
test('returns [] when there is no brace group', () => {
assert.deepStrictEqual(extractBraceGroups('echo hello'), []);
});
// extractBraceGroups
console.log('\nextractBraceGroups:');
test('extracts a { ...; } brace group body', () => {
assert.deepStrictEqual(extractBraceGroups('{ npm run dev; }'), [' npm run dev; ']);
});
test('does not treat {token} (no space) as a group', () => {
assert.deepStrictEqual(extractBraceGroups('{npm run dev}'), []);
});
test('skips (...) subshell spans', () => {
assert.deepStrictEqual(extractBraceGroups('(npm run dev)'), []);
});
test('extracts nested brace groups recursively', () => {
assert.deepStrictEqual(extractBraceGroups('{ a; { b; }; }'), [' a; { b; }; ', ' b; ']);
});
test('returns [] when there is no brace group', () => {
assert.deepStrictEqual(extractBraceGroups('echo hello'), []);
});
test('skips $(...) spans inside brace groups', () => {
assert.deepStrictEqual(extractBraceGroups('{ echo $(whoami); }'), [' echo $(whoami); ']);
});
test('skips backtick spans inside brace groups', () => {
assert.deepStrictEqual(extractBraceGroups('{ echo `id`; }'), [' echo `id`; ']);
});
🤖 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/lib/shell-substitution.test.js` around lines 77 - 93, Add coverage in
extractBraceGroups tests for the skip logic that handles $(...) and backtick
spans inside brace group bodies. Update the test block in
shell-substitution.test.js to include cases where a closing brace appears inside
a command substitution or backtick expression and confirm extractBraceGroups
still returns the enclosing brace group unchanged. Use the existing
extractBraceGroups test suite and its helper expectations to locate the right
area and verify both nested and non-nested behavior.

@affaan-m

Copy link
Copy Markdown
Owner

Closing as superseded by #2495, now merged in 19df41d. Both PRs add the same test file, but #2495 provides 46 cases (including the escaped substitution/backtick gaps called out in review) and uses the result format consumed by the current run-all harness. Thank you for covering this area.

@affaan-m affaan-m closed this Jul 26, 2026
@MrChees8157
MrChees8157 deleted the test/shell-substitution-coverage branch August 22, 2026 17:07
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.

2 participants