Skip to content

feat(parse): add usage__varargs_idx env var#573

Open
JanPokorny wants to merge 1 commit intojdx:mainfrom
JanPokorny:claude/add-varargs-index-SFw6S
Open

feat(parse): add usage__varargs_idx env var#573
JanPokorny wants to merge 1 commit intojdx:mainfrom
JanPokorny:claude/add-varargs-index-SFw6S

Conversation

@JanPokorny
Copy link
Copy Markdown

Add special env var for usage scripts containing number of parsed args before trailing varargs.

Intended use -- pass on varargs without needing to use eval. Despite being safe, it raises eyebrows and this change is IMO simple and unobtrusive. It can exist alongside, being just another option.

Example of a script that has args and flags followed by varargs:

shift $usage__varargs_idx  # removes parsed args from $@
eslint "$@"

It's not the most elegant solution in the world but it might be less inelegant than eval.

Code is by Claude with significant handholding by me.

@codecov
Copy link
Copy Markdown

codecov Bot commented Apr 5, 2026

Codecov Report

❌ Patch coverage is 90.52632% with 18 lines in your changes missing coverage. Please review.
✅ Project coverage is 79.15%. Comparing base (63172cb) to head (a72e971).
⚠️ Report is 2 commits behind head on main.

Files with missing lines Patch % Lines
lib/src/parse.rs 94.38% 3 Missing and 7 partials ⚠️
cli/src/cli/exec.rs 33.33% 0 Missing and 4 partials ⚠️
cli/src/cli/shell.rs 33.33% 0 Missing and 4 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #573      +/-   ##
==========================================
+ Coverage   79.04%   79.15%   +0.11%     
==========================================
  Files          48       48              
  Lines        7235     7437     +202     
  Branches     7235     7437     +202     
==========================================
+ Hits         5719     5887     +168     
- Misses       1141     1153      +12     
- Partials      375      397      +22     

☔ View full report in Codecov by Sentry.
📢 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.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented Apr 5, 2026

Greptile Summary

This PR adds a usage__varargs_idx environment variable that is set on the subprocess when running scripts via usage exec or usage bash/fish/etc. The value represents the count of positional args in $@ that precede any trailing varargs, letting scripts call shift "$usage__varargs_idx" to strip the parsed args and leave only the raw varargs in $@ — a clean alternative to eval.

Key implementation decisions:

  • trailing_varargs_count() on ParseOutput — iterates args in reverse with take_while(a.var) to find consecutive trailing vararg groups, counting only MultiString values; returns None when self.errors is non-empty (addressing a prior review concern).
  • saturating_sub — used in both exec.rs and shell.rs to compute the index, preventing any possible underflow (addressing a prior review concern).
  • Six unit tests — cover basic varargs, no-varargs, -- double-dash, subcommands, multiple consecutive vararg groups, and the non-MultiString edge case.

Both prior review threads (bare usize subtraction and guarding on parse errors) have been properly addressed. The implementation is logically sound.

Confidence Score: 5/5

Safe to merge — both prior P1 concerns are resolved, no new logic or security issues found.

Both review-thread concerns (bare usize subtraction → saturating_sub; emitting on parse errors → None guard) are properly addressed. The index arithmetic in exec.rs and shell.rs is correct relative to what the subprocess sees as $@. Six unit tests cover the meaningful edge cases. The only remaining finding is a P2 documentation wording suggestion.

No files require special attention; docs/cli/scripts.md has one minor wording/quoting suggestion.

Important Files Changed

Filename Overview
lib/src/parse.rs Adds trailing_varargs_count() to ParseOutput, correctly guarding on empty errors, iterating args in reverse with take_while, and summing MultiString lengths; 6 thorough unit tests covering key edge cases.
cli/src/cli/exec.rs Sets usage__varargs_idx env var using self.args.len().saturating_sub(trailing) — index arithmetic is correct relative to the subprocess's $@.
cli/src/cli/shell.rs Same usage__varargs_idx injection as exec.rs; parallel implementation is correct and consistent.
docs/cli/scripts.md New 'Trailing Varargs' section documents the feature with a clear bash example; one minor wording and quoting suggestion.

Sequence Diagram

sequenceDiagram
    participant User as User Shell
    participant CLI as usage CLI (exec/shell)
    participant Lib as usage-lib parse()
    participant Script as Subprocess Script

    User->>CLI: usage bash script.sh --verbose file.txt extra1 extra2
    CLI->>Lib: parse(spec, ["bin", "--verbose", "file.txt", "extra1", "extra2"])
    Lib-->>CLI: ParseOutput { args: {file→"file.txt", extra→["extra1","extra2"]}, errors: [] }
    CLI->>CLI: trailing_varargs_count() → Some(2)
    CLI->>CLI: usage__varargs_idx = self.args.len() - 2 = 2
    CLI->>Script: spawn(env: {usage_file="file.txt", usage_extra="extra1 extra2", usage__varargs_idx="2"})
    Script->>Script: shift "$usage__varargs_idx"  # shift 2
    Script->>Script: $@ = ["extra1", "extra2"]
Loading

Reviews (7): Last reviewed commit: "feat(parse): add usage__varargs_idx env ..." | Re-trigger Greptile

Comment thread lib/src/parse.rs Outdated
Comment thread lib/src/parse.rs Outdated
Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request introduces a new environment variable, usage__varargs_idx, which identifies the starting index of trailing variadic arguments within the original CLI input. This is implemented by tracking the total input argument count in the ParseOutput struct and calculating the offset during environment variable generation. While the logic is supported by new unit tests, feedback indicates a high-risk issue where the calculation could cause a subtraction overflow panic if variadic arguments are populated by default values rather than CLI input. Additionally, it is recommended to add documentation comments to the new public struct field for better maintainability.

Comment thread lib/src/parse.rs Outdated
Comment thread lib/src/parse.rs Outdated
@JanPokorny JanPokorny force-pushed the claude/add-varargs-index-SFw6S branch 6 times, most recently from 3185992 to c976318 Compare April 5, 2026 12:56
…args

Add `trailing_varargs_count()` to `ParseOutput`, returning the number
of values captured by trailing contiguous vararg groups (or `None` when
the spec has no trailing varargs).

The CLI shell/exec runners use this to set `usage__varargs_idx` on the
subprocess, equal to `args.len() - trailing_varargs_count`. Scripts can
`shift $usage__varargs_idx` to remove parsed args and keep only the
trailing varargs in `$@`.

https://claude.ai/code/session_01CwiKAozb4jeH6soFJrNxPk
@JanPokorny JanPokorny force-pushed the claude/add-varargs-index-SFw6S branch from c976318 to a72e971 Compare April 6, 2026 08:55
@JanPokorny
Copy link
Copy Markdown
Author

I'd like to hear your thoughts here, @jdx
(pinging in case this got lost, I get it if you are busy)

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