Skip to content

Conversation

@ascandone
Copy link
Contributor

@ascandone ascandone commented Jul 18, 2025

This PR updates and simplify the CLI args, so that the usage is simplified and more consistent with the playground.
Docs preview: https://formance-d105fefb-add-cli-docs.mintlify.app/modules/numscript/cli

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 18, 2025

"""

Walkthrough

The command-line interface for running a numscript file was refactored to consolidate all input sources into a single JSON inputs file, replacing multiple input flags and stdin handling. The LSP command handler was modified to retain the RunE signature but now explicitly silences usage and error messages on failure before returning the error.

Changes

File(s) Change Summary
internal/cmd/lsp.go Modified LSP command handler to explicitly silence usage and error messages on lsp.RunServer() failure before returning error.
internal/cmd/run.go Refactored CLI to use a single --inputs JSON file for all inputs; removed multiple input flags including variables, balances, metadata, raw JSON, and stdin; updated types (runArgsRunArgs, added InputsFile); enhanced error handling and updated command usage.

Poem

Oh, what a hop in the code today,
Inputs now gathered in one tidy way!
No more flags to juggle or parse,
Just one JSON file—so simple, so sparse.
Errors now shout, not sneak out the door,
This bunny approves—let’s code some more!
🐇✨
"""

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2cc29f4 and 32d8914.

📒 Files selected for processing (2)
  • internal/cmd/lsp.go (1 hunks)
  • internal/cmd/run.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • internal/cmd/lsp.go
  • internal/cmd/run.go
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Dirty
  • GitHub Check: Tests
  • GitHub Check: Cursor Bugbot
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cli/change-run-args

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@ascandone ascandone requested a review from flemzord July 18, 2025 13:18
@ascandone ascandone force-pushed the cli/change-run-args branch from 2b822c6 to b6e1e2b Compare July 18, 2025 13:19
@codecov
Copy link

codecov bot commented Jul 18, 2025

Codecov Report

Attention: Patch coverage is 0% with 50 lines in your changes missing coverage. Please review.

Project coverage is 71.32%. Comparing base (7f13174) to head (32d8914).
Report is 4 commits behind head on main.

Files with missing lines Patch % Lines
internal/cmd/run.go 0.00% 43 Missing ⚠️
internal/cmd/lsp.go 0.00% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main      #84      +/-   ##
==========================================
+ Coverage   71.06%   71.32%   +0.25%     
==========================================
  Files          41       41              
  Lines        4676     4631      -45     
==========================================
- Hits         3323     3303      -20     
+ Misses       1212     1176      -36     
- Partials      141      152      +11     

☔ 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.

@ascandone ascandone marked this pull request as ready for review July 18, 2025 13:23
cursor[bot]

This comment was marked as outdated.

Copy link
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: 2

🧹 Nitpick comments (2)
internal/cmd/run.go (2)

39-43: Consider returning the actual parsing errors.

The function prints parsing errors to stderr but returns a generic "parsing failed" error. Consider including more context in the returned error.

 	parseResult := parser.Parse(string(numscriptContent))
 	if len(parseResult.Errors) != 0 {
 		fmt.Fprint(os.Stderr, parser.ParseErrorsToString(parseResult.Errors, string(numscriptContent)))
-		return fmt.Errorf("parsing failed")
+		return fmt.Errorf("parsing failed with %d errors", len(parseResult.Errors))
 	}

132-132: Fix grammatical error in command description.

There's a grammatical error in the help text.

-You can use explicitly specify where the inputs file should be using the optional --inputs argument.
+You can explicitly specify where the inputs file should be using the optional --inputs argument.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 328edee and b6e1e2b.

📒 Files selected for processing (2)
  • internal/cmd/lsp.go (2 hunks)
  • internal/cmd/run.go (2 hunks)
🧰 Additional context used
🧠 Learnings (1)
📓 Common learnings
Learnt from: ascandone
PR: formancehq/numscript#70
File: internal/utils/pretty_csv.go:12-16
Timestamp: 2025-07-16T14:49:54.326Z
Learning: ascandone prefers documenting function preconditions in comments rather than adding defensive validation code when the precondition violation would cause a panic. This is a valid design choice for utility functions.
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cursor BugBot
🔇 Additional comments (1)
internal/cmd/run.go (1)

21-31: Well-structured input definitions.

The consolidation of inputs into a single InputsFile struct provides a clean and organized approach to handling all input types. The JSON tags are properly defined.

cursor[bot]

This comment was marked as outdated.

@ascandone ascandone force-pushed the cli/change-run-args branch from 1a04fe9 to ab32999 Compare July 18, 2025 14:10
cursor[bot]

This comment was marked as outdated.

@ascandone ascandone force-pushed the cli/change-run-args branch 2 times, most recently from f3f1c6f to 91a284f Compare July 23, 2025 09:45
@ascandone ascandone force-pushed the cli/change-run-args branch from 91a284f to 2cc29f4 Compare July 23, 2025 09:47
Copy link
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

♻️ Duplicate comments (1)
internal/cmd/run.go (1)

49-52: Add helpful error message when inputs file is not found.

When the inputs file doesn't exist, the error message might not be clear to users. Consider wrapping the error with more context.

 	inputsContent, err := os.ReadFile(inputsPath)
 	if err != nil {
-		return err
+		return fmt.Errorf("failed to read inputs file '%s': %w", inputsPath, err)
 	}
🧹 Nitpick comments (1)
internal/cmd/run.go (1)

124-124: Fix typo in help text.

There's a grammatical error in the help text.

-You can use explicitly specify where the inputs file should be using the optional --inputs argument.
+You can explicitly specify where the inputs file should be using the optional --inputs argument.
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between ab32999 and 2cc29f4.

⛔ Files ignored due to path filters (1)
  • inputs.schema.json is excluded by !**/*.json
📒 Files selected for processing (2)
  • internal/cmd/lsp.go (2 hunks)
  • internal/cmd/run.go (2 hunks)
🧠 Learnings (2)
📓 Common learnings
Learnt from: ascandone
PR: formancehq/numscript#70
File: internal/utils/pretty_csv.go:12-16
Timestamp: 2025-07-16T14:49:54.326Z
Learning: ascandone prefers documenting function preconditions in comments rather than adding defensive validation code when the precondition violation would cause a panic. This is a valid design choice for utility functions.
internal/cmd/run.go (2)

Learnt from: ascandone
PR: #31
File: internal/parser/parser_test.go:115-126
Timestamp: 2025-02-06T17:48:48.962Z
Learning: The numscript parser's fault tolerance is built into the infrastructure and handles errors gracefully for all clause types. Tests in parser_fault_tolerance_test.go cover both inorder and oneof constructs as they share the same parsing infrastructure.

Learnt from: ascandone
PR: #27
File: internal/interpreter/interpreter.go:667-668
Timestamp: 2024-12-05T11:42:58.472Z
Learning: In Go test files within the internal/interpreter package (e.g., reconciler_test.go and interpreter_test.go), it's acceptable to use hardcoded "<kept>" strings in test data and comments, and they do not need to be replaced with the KEPT_ADDR constant.

🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/cmd/lsp.go
🧰 Additional context used
🧠 Learnings (2)
📓 Common learnings
Learnt from: ascandone
PR: formancehq/numscript#70
File: internal/utils/pretty_csv.go:12-16
Timestamp: 2025-07-16T14:49:54.326Z
Learning: ascandone prefers documenting function preconditions in comments rather than adding defensive validation code when the precondition violation would cause a panic. This is a valid design choice for utility functions.
internal/cmd/run.go (2)

Learnt from: ascandone
PR: #31
File: internal/parser/parser_test.go:115-126
Timestamp: 2025-02-06T17:48:48.962Z
Learning: The numscript parser's fault tolerance is built into the infrastructure and handles errors gracefully for all clause types. Tests in parser_fault_tolerance_test.go cover both inorder and oneof constructs as they share the same parsing infrastructure.

Learnt from: ascandone
PR: #27
File: internal/interpreter/interpreter.go:667-668
Timestamp: 2024-12-05T11:42:58.472Z
Learning: In Go test files within the internal/interpreter package (e.g., reconciler_test.go and interpreter_test.go), it's acceptable to use hardcoded "<kept>" strings in test data and comments, and they do not need to be replaced with the KEPT_ADDR constant.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Cursor Bugbot
🔇 Additional comments (6)
internal/cmd/run.go (6)

20-25: Well-structured inputs consolidation.

The InputsFile struct provides a clean way to consolidate all input sources into a single JSON structure. The field types and JSON tags are appropriate for the use case.


27-30: Good simplification of command arguments.

The simplified RunArgs struct reduces complexity by consolidating multiple input flags into a single inputs file path, while maintaining the essential output format option.


32-42: Good error handling for parsing errors.

The parsing error handling properly writes to stderr and includes source information, providing helpful feedback to users when numscript parsing fails.


65-78: Excellent execution error handling with source ranges.

The execution error handling provides comprehensive feedback by showing both the error message and the source range where the error occurred, making debugging much easier for users.


118-126: Clear documentation of new inputs file convention.

The updated help text clearly explains the new inputs file naming convention and usage, making it easy for users to understand how to structure their inputs.


138-139: Good flag simplification.

The simplified flag structure reduces complexity while maintaining essential functionality. The inputs flag provides flexibility when the default naming convention doesn't fit.

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Nil Maps in Struct Fields Cause Runtime Issues

The InputsFile struct's Variables, Meta, and Balances map fields are now nil if not present in the JSON input, instead of being initialized as empty maps. This can cause runtime panics or unexpected behavior when passed to interpreter.RunProgram, which expects non-nil maps.

internal/cmd/run.go#L53-L68

var inputs InputsFile
err = json.Unmarshal(inputsContent, &inputs)
if err != nil {
return fmt.Errorf("failed to parse inputs file '%s' as JSON: %w", inputsPath, err)
}
featureFlags := map[string]struct{}{}
for _, flag := range inputs.FeatureFlags {
featureFlags[flag] = struct{}{}
}
result, iErr := interpreter.RunProgram(context.Background(), parseResult.Value, inputs.Variables, interpreter.StaticStore{
Balances: inputs.Balances,
Meta: inputs.Meta,
}, featureFlags)

Fix in CursorFix in Web


Bug: Error Messages Concatenate with Shell Prompt

Error messages printed to os.Stderr in run.go lack a newline character, as fmt.Fprint is used instead of fmt.Fprintln. This causes messages to concatenate with the shell prompt, hindering readability and creating an inconsistency with lsp.go.

internal/cmd/run.go#L131-L132

if err != nil {
fmt.Fprint(os.Stderr, err)

Fix in CursorFix in Web


Was this report helpful? Give feedback by reacting with 👍 or 👎

@ascandone ascandone requested a review from a team July 23, 2025 10:56
@fguery fguery changed the title cli: change run args feat: cli, change run args Jul 24, 2025
@ascandone ascandone force-pushed the cli/change-run-args branch from 2e6b73a to 32d8914 Compare July 24, 2025 12:41
Meta: opt.Meta,
result, iErr := interpreter.RunProgram(context.Background(), parseResult.Value, inputs.Variables, interpreter.StaticStore{
Balances: inputs.Balances,
Meta: inputs.Meta,
Copy link

Choose a reason for hiding this comment

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

Bug: JSON Parsing Initializes Maps Incorrectly

The InputsFile struct's Variables, Meta, and Balances map fields are no longer explicitly initialized. Unlike the previous implementation, these fields are now nil if missing from the JSON input file. This can lead to nil pointer dereferences or unexpected behavior when passed to interpreter.RunProgram(), which likely expects non-nil maps.

Locations (1)

Fix in CursorFix in Web

return lsp.RunServer()
err := lsp.RunServer()
if err != nil {
cmd.SilenceErrors = true
Copy link

Choose a reason for hiding this comment

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

Discussion on the merit of Run vs RunE and Cobra error handling: https://numary.slack.com/archives/C096FH98AKC/p1753358540338769

@ascandone ascandone merged commit 559426b into main Jul 24, 2025
8 of 9 checks passed
@ascandone ascandone deleted the cli/change-run-args branch July 24, 2025 12:59
ascandone added a commit that referenced this pull request Aug 26, 2025
* feat: change cli command args

* feat: better docs and improve err handling

* fix: fix error handling

* feat: added schema for inputs file

* feat: improve error output

* feat: more reliable exit from cli (no explicit exit() call)
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.

3 participants