Skip to content

feat: Inject AHOY_CMD and AHOY_COMMAND_NAME environment variables into subprocesses#170

Open
ocean wants to merge 7 commits into
ahoy-cli:v3-candidatefrom
ocean:master
Open

feat: Inject AHOY_CMD and AHOY_COMMAND_NAME environment variables into subprocesses#170
ocean wants to merge 7 commits into
ahoy-cli:v3-candidatefrom
ocean:master

Conversation

@ocean
Copy link
Copy Markdown
Member

@ocean ocean commented May 12, 2026

Sets AHOY_CMD to the resolved path of the running ahoy binary and AHOY_COMMAND_NAME to the name of the invoked command, making both available to every subprocess ahoy runs.

Adds a testdata fixture and BATS integration tests to verify the behaviour.

This is a fix for #165

Summary by CodeRabbit

Release Notes

  • New Features

    • Commands now have access to Ahoy-specific environment variables containing the command name and binary path during execution.
  • Bug Fixes

    • Command execution now properly returns errors instead of directly terminating the process.
  • Tests

    • Added comprehensive test coverage verifying environment variables are correctly injected into executed commands.

Review Change Stack

…o subprocesses

Sets AHOY_CMD to the resolved path of the running ahoy binary and
AHOY_COMMAND_NAME to the name of the invoked command, making both
available to every subprocess ahoy runs.

Adds a testdata fixture and BATS integration tests to verify the
behaviour.
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 690b8c6e-53c8-4c02-ad3e-b7d3535e64c5

📥 Commits

Reviewing files that changed from the base of the PR and between 1f78216 and b13edf2.

📒 Files selected for processing (3)
  • ahoy.go
  • testdata/ahoy-self-env.ahoy.yml
  • tests/environment-variables.bats

Walkthrough

The PR adds environment variable injection to ahoy command execution. Config and Command structs now declare explicit YAML tags for schema alignment. Command handlers switch from Run to RunE for error propagation. The ahoy binary path is captured at startup via os.Executable() and injected as AHOY_CMD alongside AHOY_COMMAND_NAME into every executed command's environment. Bash completion logic is simplified, and test configuration and Bats tests validate the new variables' presence and executability.

Changes

Environment variable injection feature

Layer / File(s) Summary
Config schema and error-returning execution
ahoy.go
Config and Command struct fields declare yaml:"..." tags for all config-mapped fields. Command execution switches from Run (void) to RunE (returning error) to propagate subprocess failures.
Executable path initialisation
ahoy.go
main() captures the ahoy binary's executable path via os.Executable() and stores it in ahoyExecutable for later environment injection.
Environment variable injection and error handling
ahoy.go
Command execution injects AHOY_COMMAND_NAME and AHOY_CMD into subprocess environment. Errors from exec.Command(...).Run() are returned via the RunE handler instead of calling os.Exit().
Bash completion logic simplification
ahoy.go
Early conditional exit based on sourcefile is removed, making completion generation unconditional.
Test configuration and validation
testdata/ahoy-self-env.ahoy.yml, tests/environment-variables.bats
YAML test configuration defines commands that echo and validate AHOY_CMD and AHOY_COMMAND_NAME. Bats tests verify both variables are set correctly, point to an executable file, and are accessible within subprocesses across multiple command invocations.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Possibly related PRs

  • ahoy-cli/ahoy#157: Both PRs touch command metadata for the description field—this PR adds YAML struct tags so Command.Description is parsed, whilst the related PR adds logic, tests, and help formatting to propagate and display description in v2 command parsing.

Suggested labels

ready-for-merging


🐰 Aha! Environment variables leap through the air,
AHOY_CMD and AHOY_COMMAND_NAME declare their flair,
The binary path captured, injected with care,
Subprocess execution floats, light as a hare! 🌟

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarises the main change: injecting AHOY_CMD and AHOY_COMMAND_NAME environment variables into subprocesses, which is the primary focus of the pull request.
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.

✏️ 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.

@ocean
Copy link
Copy Markdown
Member Author

ocean commented May 12, 2026

@coderabbitai There should be a configuration change to include you doing code reviews on the v3-candidate branch, please check your configuration

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 12, 2026

Tip

For best results, initiate chat on the files or code changes.

🧩 Analysis chain

@ocean, let me check the current CodeRabbit configuration for this repository to verify the branch settings.


🛠 Debug Information Gathered


@ocean — I've found the issue. The current configuration has base_branches set to an empty array, which means CodeRabbit only automatically reviews PRs targeting the default branch. The v3-candidate branch is not included.

To fix this, add v3-candidate to the base_branches list in your .coderabbit.yaml file:

reviews:
  auto_review:
    base_branches:
      - v3-candidate

This field accepts regex patterns too, so if you want to cover all non-default branches you could use .*, but scoping it to v3-candidate specifically is the more targeted approach.

Once that change is merged into the default branch, CodeRabbit will automatically review PRs that target v3-candidate as well.

@ocean
Copy link
Copy Markdown
Member Author

ocean commented May 13, 2026

@coderabbitai help

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 13, 2026

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

CodeRabbit commands

These commands are invoked using PR/Issue 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 rate limit to show your current review rate limit status.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai evaluate custom pre-merge check --instructions <custom-checks-instructions> --name <custom-checks-title> [--mode <error|warning>] to validate the custom pre-merge checks instructions. Defaults to error when --mode is omitted.
  • @coderabbitai ignore pre-merge checks to override pre-merge checks and get an approval on PR.
  • @coderabbitai run pre-merge checks to run pre-merge checks on the pull request.
  • @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 merge conflict to automatically resolve merge conflicts.
  • @coderabbitai autofix to automatically fix issues identified in unresolved review comments.
  • @coderabbitai resolve to resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai generate configuration to create a PR that adds the current resolved configuration as .coderabbit.yaml (or show it if already present).
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore or @coderabbit 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.
  • You can also validate your configuration using the online YAML validator.
  • 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

Status, support, documentation and community

  • Visit our status page to check the current availability of CodeRabbit.
  • Create a ticket on our support page for assistance with any issues or questions.
  • Visit our documentation site for detailed information on how to use CodeRabbit.
  • Join our Discord community to connect with other users and get help from the community.
  • Follow us on X/Twitter for updates and announcements.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

Note

Unit test generation is a public access feature. Expect some limitations and changes as we gather feedback and continue to improve it.


Generating unit tests... This may take up to 20 minutes.

@ocean
Copy link
Copy Markdown
Member Author

ocean commented May 14, 2026

@coderabbitai review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@ocean
Copy link
Copy Markdown
Member Author

ocean commented May 14, 2026

@coderabbitai full review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

✅ Actions performed

Full review triggered.

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 `@v2/ahoy.go`:
- Line 321: The current assignment to command.Env appends ahoyEnvVars before
envVars so user-provided environment entries can override injected values;
change the append order so envVars are appended first and ahoyEnvVars are
appended last (so injected AHOY_CMD / AHOY_COMMAND_NAME override any
duplicates), i.e., update the expression that builds command.Env which uses
command.Environ(), ahoyEnvVars and envVars to append envVars then ahoyEnvVars.
🪄 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: 850910d1-4739-42ea-8472-a116e8914154

📥 Commits

Reviewing files that changed from the base of the PR and between aa7f6e7 and 1f78216.

📒 Files selected for processing (3)
  • v2/ahoy.go
  • v2/testdata/ahoy-self-env.ahoy.yml
  • v2/tests/environment-variables.bats

Comment thread v2/ahoy.go Outdated
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 14, 2026

❌ Failed to create PR with unit tests: AGENT_CHAT: Failed to open pull request

ocean added 6 commits May 17, 2026 13:40
- $AHOY_CMD contains a path to the actual ahoy executable
so it can be used for substitution for running ahoy-driven
subcommands with the exact same binary.
- $AHOY_COMMAND_NAME contains the name of the ahoy command (within
the .ahoy.yml file) that is being run, and therefore allows the
subprocess to know it is being run by an ahoy parent process.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
… files...

... don't override the injected runtime values. In Go's os/exec, the
last occurrence of a duplicate environment variable key
takes precedence, and we want that to be the ones set by ahoy
itself.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
yaml.v2 uses case-insensitive field matching as a fallback when no tags
are present, but yaml.v3 (the current maintained version) requires exact
matches. Without tags, migrating to yaml.v3 would silently leave AhoyAPI
empty on every config file, causing spurious "unsupported API version"
errors for all users. Add explicit yaml:"..." tags to every field on both
Config and Command to make the structs safe for a future yaml.v3 migration.
…os.Exit

os.Exit inside rootCmd.Execute() bypasses the pipe-drain cleanup in main(),
which can cause in-flight subprocess stderr output to be silently truncated.
Switching the command closure from Run to RunE and returning the subprocess
error lets main() close the write-end of the pipe and wait for the drain
goroutine to flush before exiting.
The block logged the sourcefile path and called os.Exit(0) whenever
sourcefile was set, which in normal usage is always. This meant shell
completion was printing the config file path instead of command names
and exiting without running the pipe-drain cleanup in main(). Removing
it lets the correct completion logic below run and avoids the os.Exit
inside Execute().
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.

1 participant