Skip to content

Conversation

@ocean
Copy link
Member

@ocean ocean commented Jul 21, 2025

This is done using the new ahoy config ... top level command, including the ahoy config validate command for the config file schema validation and system configuration report.

Summary by CodeRabbit

  • New Features

    • Added config init and config validate commands with detailed reports, recommendations and a backward-compatible notice when using the old init alias.
    • Improved path expansion so env/import file paths and home-directory (~) handling work across platforms and subdirectories.
  • Bug Fixes

    • Prevented crashes for missing imports and improved diagnostics for import-related errors.
  • Documentation

    • Updated CI badge to GitHub Actions, refreshed contributors list (now 14) including a new contributor, and updated sponsor image.
  • Tests

    • Added comprehensive tests for config init, validate, path handling and various config scenarios.
  • Chores

    • Updated an indirect dependency and added formatting/modernisation targets.

ocean added 2 commits July 21, 2025 13:05
…nd new `ahoy doctor` command

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
@ocean ocean mentioned this pull request Jul 21, 2025
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 22, 2025

Warning

Rate limit exceeded

@ocean has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 30 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 61d1ba9 and d0789d2.

📒 Files selected for processing (1)
  • v2/ahoy.go (14 hunks)

Walkthrough

Adds a contributor and README badge updates; introduces path expansion and a hidden simulate-version flag; changes getConfig signature; adds config init and config validate commands with comprehensive validation/reporting, tests, testdata, Makefile targets, and an indirect dependency bump.

Changes

Cohort / File(s) Summary
Contributors & README
/.all-contributorsrc, README.md
Add contributor jnsalsa; update badges (CircleCI→GitHub Actions, contributors count/style); move badges; replace sponsor image; add contributor row in README.
Core CLI & path handling
v2/ahoy.go, v2/flag.go
Add expandPath(path, baseDir string) and var simulateVersion string; add hidden --simulate-version flag; change getConfig(file, skipValidation bool) signature and update callers; resolve import/env paths via expandPath; improve import error diagnostics; avoid duplicate default commands; update setupApp to call getConfig with skipValidation.
Config init feature
v2/config_init.go, v2/config_init_test.go, v2/tests/config-init.bats
Implement ahoy config init (download example, prompts, --force, custom URL); add InitArgs, RunConfigInit, CLI handler and unit + Bats tests; deprecation notice for legacy ahoy init.
Config validate & reporting
v2/config_validation.go, v2/config.go, v2/config_validation_test.go, v2/tests/config-validate.bats
Implement version-aware validation framework, issue types, semantic version checks, file existence validations, RunConfigValidate and PrintConfigReport; add CLI handler validateCommandAction; extensive Go + Bats tests.
Tests & small test fixes
v2/tests/missing-cmd.bats, v2/tests/no-ahoy-file.bats, v2/ahoy_test.go, v2/windows_test.go, v2/description_test.go
Update expected messages/lines in Bats tests; adapt tests to new getConfig signature; add TestExpandPath.
Testdata
v2/testdata/*.ahoy.yml, v2/testdata/.env.test
Add fixtures: invalid-yaml.ahoy.yml, missing-api-version.ahoy.yml, with-imports.ahoy.yml, wrong-api-version.ahoy.yml, and .env.test.
Bats test suites
v2/tests/config-init.bats, v2/tests/config-validate.bats
Add Bats suites exercising config init and config validate flows and edge cases.
Build tooling
v2/Makefile
Add fmt, modernize, modernize-check targets and update .PHONY.
Dependencies / vendor
v2/go.mod, v2/vendor/modules.txt
Bump github.com/cpuguy83/go-md2man/v2 v2.0.2 → v2.0.7; vendor metadata updated.
CI workflow
.github/workflows/release.yml
Pin goreleaser-action to ~> v2 instead of latest.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant CLI as Ahoy CLI
  participant FS as Filesystem
  participant Net as HTTP

  User->>CLI: ahoy config init [--force] [URL]
  CLI->>FS: Check for .ahoy.yml
  alt exists and not --force
    CLI->>User: Prompt overwrite?
    User-->>CLI: yes/no
    opt no
      CLI-->>User: Abort without changes
    end
  end
  CLI->>Net: GET example config (URL or default)
  Net-->>CLI: Response body / error
  CLI->>FS: Write .ahoy.yml
  CLI-->>User: Success or error message
Loading
sequenceDiagram
  participant User
  participant CLI as Ahoy CLI
  participant FS as Filesystem

  User->>CLI: ahoy config validate
  CLI->>FS: Locate .ahoy.yml
  alt not found
    CLI-->>User: Warn and exit
  else found
    CLI->>CLI: Load config (getConfig with skipValidation)
    CLI->>CLI: ValidateConfig (versions, imports, envs)
    CLI->>FS: Check import/env file existence (expandPath)
    CLI-->>User: PrintConfigReport with recommendations
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related issues

Possibly related PRs

Suggested labels

ready-for-merging

Poem

I’m a rabbit at keys with a keen little hop,
Paths expand neat as I nibble and crop.
Init fetches a file, validate gives a wink,
Badges refreshed—give the repo a blink.
Thump-thump, code checks—now off for a hop! 🐇

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch schema-validation

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

Support

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

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 4

🧹 Nitpick comments (4)
v2/flag.go (1)

9-30: Consider validating the simulated version format.

The implementation looks good for testing purposes. However, consider adding validation to ensure the simulated version follows a valid format (e.g., semantic versioning) to prevent potential issues in the validation logic.

You could add version format validation when this flag is used, similar to:

if simulateVersion != "" && !isValidVersion(simulateVersion) {
    logger("fatal", "Invalid version format for --simulate-version")
}
README.md (1)

226-226: Fix minor formatting issues in sponsor section.

The sponsor image update looks good, but there are a few formatting issues to address:

  • Add alt text to the image for accessibility
  • Consider using asterisk (*) instead of dash (-) for consistency with markdown list style
-- [<img src="https://avatars.githubusercontent.com/u/378794?s=160&v=4" width="160px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
+* [<img src="https://avatars.githubusercontent.com/u/378794?s=160&v=4" alt="Alex Skrypnyk - DrevOps" width="160px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
v2/ahoy.go (1)

47-47: Global state for validation control.

The skipValidation variable is used appropriately to prevent validation during the doctor command execution. However, using global state can be problematic in concurrent scenarios.

Consider passing validation control through function parameters or context instead of global state for better maintainability and thread safety.

v2/validation.go (1)

32-32: Clarify the comment about multiple_env_files support

The comment "Actually supported since the beginning via StringArray" might be confusing. Consider clarifying whether this is a legacy feature that always worked or if the version requirement is still relevant.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6521792 and e80f4d3.

📒 Files selected for processing (8)
  • .all-contributorsrc (1 hunks)
  • README.md (3 hunks)
  • v2/ahoy.go (5 hunks)
  • v2/doctor.go (1 hunks)
  • v2/doctor_test.go (1 hunks)
  • v2/flag.go (2 hunks)
  • v2/tests/missing-cmd.bats (1 hunks)
  • v2/validation.go (1 hunks)
🧬 Code Graph Analysis (3)
v2/flag.go (1)
v2/vendor/github.com/urfave/cli/flag_string.go (1)
  • StringFlag (6-16)
v2/validation.go (1)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
v2/doctor_test.go (3)
v2/doctor.go (4)
  • RunDoctor (38-78)
  • ImportFileStatus (30-35)
  • DoctorResult (10-20)
  • EnvFileStatus (23-27)
v2/validation.go (2)
  • ValidationResult (24-27)
  • ValidationIssue (11-21)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

🧰 Additional context used
🧬 Code Graph Analysis (3)
v2/flag.go (1)
v2/vendor/github.com/urfave/cli/flag_string.go (1)
  • StringFlag (6-16)
v2/validation.go (1)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
v2/doctor_test.go (3)
v2/doctor.go (4)
  • RunDoctor (38-78)
  • ImportFileStatus (30-35)
  • DoctorResult (10-20)
  • EnvFileStatus (23-27)
v2/validation.go (2)
  • ValidationResult (24-27)
  • ValidationIssue (11-21)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

⏰ 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). (2)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (27)
v2/tests/missing-cmd.bats (1)

24-24: LGTM! Error message update aligns with enhanced validation.

The updated error message is more specific and consistent with the improved error handling introduced in the validation framework.

README.md (2)

3-3: Contributor count correctly updated.

The badge update reflects the addition of Jonathan Nagy as a contributor.


8-8: CI badge updated to GitHub Actions.

Good to see the migration to GitHub Actions for CI/CD.

.all-contributorsrc (1)

162-171: New contributor entry properly added.

The addition of Jonathan Nagy follows the correct format and includes appropriate contribution types.

v2/ahoy.go (4)

180-184: Improved error visibility for import failures.

Good enhancement to log warnings when import files fail to load, making debugging easier while maintaining backward compatibility.


480-482: Doctor command properly added to defaults.

The command is correctly added only if it doesn't already exist, preventing duplicates.


142-156: Validation functions confirmed; validation logic approved.

Both ValidateConfig and PrintValidationIssues are implemented in v2/validation.go (lines 87–124 and 275–320), so the validation block in v2/ahoy.go operates correctly. No further changes needed.


341-380: Approved: Enhanced error messaging with version support verified

  • Confirmed GetAhoyVersion, VersionSupports, and the FeatureSupport map are implemented in v2/validation.go.
  • Missing-file detection and user guidance are clear and actionable.
  • Version checks correctly gate optional imports and point users to upgrade when needed.
  • “ahoy doctor” reference provides an easy troubleshooting path.

No further changes required.

v2/doctor_test.go (11)

9-36: Test implementation looks good!

The test properly covers the scenario when a config file doesn't exist, checking all relevant fields and the expected recommendation.


38-77: Good test coverage for invalid YAML scenario!

The test correctly simulates invalid YAML syntax and verifies the expected behavior.


79-115: Well-structured test for valid configuration!

The test properly validates all expected fields for a valid configuration file.


117-171: Excellent test coverage for environment file detection!

The test properly validates the detection of existing and missing environment files at both global and command levels.


173-230: Comprehensive test for import file handling!

The test effectively covers both required and optional import files, properly validating their existence and optional status.


232-258: Good unit test for version mismatch recommendations!

The test properly validates that version mismatch errors generate the appropriate upgrade recommendation.


260-287: Well-designed test for missing import file recommendations!

The test correctly validates that missing required import files trigger the appropriate recommendation.


289-315: Good coverage for missing environment file recommendations!

The test properly validates the recommendation generation for missing environment files.


317-343: Effective test for newer feature recommendations!

The test correctly handles warning-level version mismatches and generates appropriate upgrade suggestions.


345-367: Nice test for the happy path!

The test properly validates that a clean configuration generates an appropriate success message.


369-556: Thorough test coverage for helper functions and data structures!

The remaining tests effectively validate:

  • Environment and import file checking logic
  • All struct fields are properly accessible and functional
  • Helper functions work correctly with relative paths

Great job on comprehensive test coverage!

v2/doctor.go (5)

9-35: Well-structured data types for diagnostic results!

The structs provide a clean and comprehensive representation of the diagnostic information.


37-78: Clean implementation of the diagnostic workflow!

The function follows a logical progression through all diagnostic checks with proper early returns for error conditions.


80-108: Proper implementation of environment file checking!

The function correctly handles both global and command-specific environment files with appropriate path resolution.


134-195: Comprehensive recommendation generation logic!

The function effectively analyzes all diagnostic results and generates appropriate, actionable recommendations for each scenario.


197-321: Excellent user-friendly diagnostic report formatting!

The function provides clear, visually appealing output with appropriate emoji indicators and well-structured information. Great attention to user experience!

v2/validation.go (3)

37-47: Good version handling with testing support!

The function properly handles version simulation for testing and provides sensible defaults.


86-124: Well-structured configuration validation!

The function provides comprehensive validation with proper error tracking and clear separation of concerns.


274-320: Clear and informative validation issue reporting!

The function provides excellent user feedback with proper severity indication and helpful suggestions.

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: 0

🧹 Nitpick comments (2)
README.md (2)

3-4: Keep the contributors badge in sync with the table

The badge count was manually bumped to 14.
To avoid future drift, regenerate the badge with the all-contributors CLI (npx all-contributors-cli generate) instead of hand-editing, or add the new contributor through the CLI (add).
That will update both the badge and the list consistently.


226-226: Add missing alt text to comply with MD045

The sponsor image lacks alt text, triggering markdown-lint. Add an alt attribute so screen-readers and automated checks are happy.

- [<img src="https://avatars.githubusercontent.com/u/378794?s=100&v=4" width="100px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
+ [<img src="https://avatars.githubusercontent.com/u/378794?s=100&v=4" width="100px;" alt="Alex Skrypnyk avatar"><br />Alex Skrypnyk – DrevOps](https://drevops.com)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e80f4d3 and 7c27245.

📒 Files selected for processing (1)
  • README.md (3 hunks)
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

🔇 Additional comments (1)
README.md (1)

8-8: Confirm the workflow file path in the badge URL

The badge now points to
actions/workflows/build_and_test.yml.
If the workflow file is renamed or moved (common when cleaning up CI), the badge will silently break. Double-check that the file exists on the default branch and, if required, append ?branch=main so the badge always reflects the status of main.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 0

🧹 Nitpick comments (1)
README.md (1)

226-226: Missing alt attribute and inconsistent bullet marker.

markdownlint flags both issues. Fix with:

- - [<img src="https://avatars.githubusercontent.com/u/378794?s=100&v=4" width="100px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
+ * [<img src="https://avatars.githubusercontent.com/u/378794?s=100&v=4" width="100px;" alt="Alex Skrypnyk avatar"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c27245 and 9965dc0.

📒 Files selected for processing (1)
  • README.md (3 hunks)
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

6-6: Trailing punctuation in heading
Punctuation: '.'

(MD026, no-trailing-punctuation)


226-226: Unordered list style
Expected: asterisk; Actual: dash

(MD004, ul-style)


226-226: Images should have alternate text (alt text)

(MD045, no-alt-text)

⏰ 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). (2)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (3)
README.md (3)

3-3: Badge count/style change looks good.

The switch to flat and increment to 14 accurately reflect the new contributor.


8-8: Verify that the referenced workflow exists.

Please confirm that actions/workflows/build_and_test.yml is present on main (and in forks) so the badge doesn’t render as “no status”.


250-250: Table extension LGTM.

New contributor cell follows the established structure and keeps the 7-column layout intact.

ocean added 2 commits July 22, 2025 12:06
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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

🧹 Nitpick comments (1)
v2/doctor.go (1)

82-109: Consider handling tilde expansion for environment files

While import files support tilde expansion (lines 121-125), environment files don't have the same support. Consider adding consistent path expansion for environment files.

 // Check global environment files
 for _, envPath := range config.Env {
-  fullPath := filepath.Join(configDir, envPath)
+  fullPath := envPath
+  if !strings.HasPrefix(envPath, "/") && !strings.HasPrefix(envPath, "~") {
+    fullPath = filepath.Join(configDir, envPath)
+  } else if strings.HasPrefix(envPath, "~") {
+    if home, err := os.UserHomeDir(); err == nil {
+      fullPath = filepath.Join(home, envPath[2:])
+    }
+  }
   envFiles = append(envFiles, EnvFileStatus{
     Path:   envPath,
     Exists: fileExists(fullPath),
     Global: true,
   })
 }

Apply similar changes to the command-specific environment files loop.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 9965dc0 and bdceaf5.

📒 Files selected for processing (3)
  • README.md (3 hunks)
  • v2/doctor.go (1 hunks)
  • v2/validation.go (1 hunks)
🧬 Code Graph Analysis (2)
v2/doctor.go (3)
v2/validation.go (3)
  • ValidationResult (25-28)
  • GetAhoyVersion (39-48)
  • ValidateConfig (101-138)
v2/ahoy.go (2)
  • Command (31-40)
  • Config (21-27)
v2/vendor/github.com/urfave/cli/command.go (1)
  • Commands (97-97)
v2/validation.go (2)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
v2/vendor/github.com/urfave/cli/command.go (1)
  • Commands (97-97)
🚧 Files skipped from review as they are similar to previous changes (1)
  • README.md
🧰 Additional context used
🧬 Code Graph Analysis (2)
v2/doctor.go (3)
v2/validation.go (3)
  • ValidationResult (25-28)
  • GetAhoyVersion (39-48)
  • ValidateConfig (101-138)
v2/ahoy.go (2)
  • Command (31-40)
  • Config (21-27)
v2/vendor/github.com/urfave/cli/command.go (1)
  • Commands (97-97)
v2/validation.go (2)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
v2/vendor/github.com/urfave/cli/command.go (1)
  • Commands (97-97)
⏰ 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: build (ubuntu-latest)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
🔇 Additional comments (12)
v2/doctor.go (5)

10-36: Well-structured diagnostic types

The struct definitions are clear and comprehensive, providing all necessary fields for diagnostic reporting.


39-79: Solid diagnostic flow implementation

The function properly handles all diagnostic steps with appropriate early returns for error cases.


111-137: Proper import path handling with tilde expansion

The function correctly handles various path types including tilde expansion, addressing the previous review comments.


139-200: Comprehensive recommendation generation

The function provides helpful, actionable recommendations for various configuration issues.


202-326: Excellent user-friendly diagnostic output

The report format is clear, visually appealing, and provides comprehensive diagnostic information with appropriate visual indicators.

v2/validation.go (7)

11-36: Well-designed validation structures and feature mapping

The validation structures provide comprehensive fields for detailed issue reporting, and the feature support map clearly defines version requirements.


73-98: Proper semantic version comparison implemented

The version comparison correctly handles semantic versioning by parsing components as integers, properly addressing the previous review comment about string comparison issues.


100-138: Clear validation orchestration

The main validation function properly orchestrates various validation checks with appropriate error handling.


140-162: Appropriate feature validation

The feature validation correctly checks version compatibility and provides helpful warnings.


164-213: Comprehensive command validation

The function thoroughly validates all aspects of command configuration with appropriate version checks.


215-268: Proper import validation with path expansion

The function correctly handles import validation with proper path expansion including tilde support, addressing the previous review comment.


292-338: Clear validation issue reporting

The function provides well-formatted, user-friendly output with appropriate severity indicators and helpful suggestions.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
@AlexSkrypnyk
Copy link
Collaborator

@ocean
Currently, the only reserved command is init. This PR adds a second command doctor. It may already be used by consumer projects for their own functionality.

Can doctor be renamed to config validate to avoid clashes? config would be a high-level reserved word and validate would be a sub-command. This will future-proof the implementation to support additional actions like config process (to compile a full config from all included files - what Docker Compose does) or config migrate (to migrate from Ahoy 2 to Ahoy 3) etc.

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)
v2/ahoy.go (1)

47-47: Global state mutation creates race condition risk.

The global skipValidation flag can cause race conditions when multiple Ahoy instances run concurrently. This issue was previously identified but remains unaddressed.

Consider using a context-based approach instead:

-skipValidation bool
+type ConfigOptions struct {
+    SkipValidation bool
+}

// In doctor command:
-skipValidation = true
-result := RunDoctor(configFile)
-skipValidation = false
+opts := ConfigOptions{SkipValidation: true}
+result := RunDoctorWithOptions(configFile, opts)

Also applies to: 490-493

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between bdceaf5 and 041aacb.

📒 Files selected for processing (4)
  • v2/ahoy.go (6 hunks)
  • v2/ahoy_test.go (1 hunks)
  • v2/doctor.go (1 hunks)
  • v2/validation.go (1 hunks)
🧬 Code Graph Analysis (1)
v2/validation.go (1)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
🚧 Files skipped from review as they are similar to previous changes (1)
  • v2/doctor.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
v2/validation.go (1)
v2/ahoy.go (2)
  • Config (21-27)
  • Command (31-40)
⏰ 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: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (7)
v2/ahoy_test.go (1)

238-286: Well-structured and comprehensive path expansion tests.

The test coverage for expandPath is thorough, covering all major scenarios including absolute paths, relative paths, tilde expansion (both Unix and Windows styles), and edge cases. The error handling for home directory lookup failures is appropriately considered.

v2/ahoy.go (3)

82-106: Excellent path expansion implementation.

The expandPath function properly handles all path types (absolute, tilde, relative) with appropriate error handling for cases where the home directory cannot be determined. This provides consistent path resolution throughout the codebase.


197-208: Good error handling improvements.

The addition of warning logs for failed import file loads improves debugging capabilities whilst maintaining backwards compatibility by continuing execution. The consistent use of expandPath ensures uniform path handling.


365-401: Excellent user experience improvements for error diagnostics.

The enhanced error messages provide clear, actionable guidance including:

  • Identification of missing files
  • Multiple solution options
  • Version compatibility checks
  • Reference to the diagnostic tool

This significantly improves troubleshooting capabilities.

v2/validation.go (3)

73-98: Proper semantic version comparison implemented.

The version comparison function correctly handles semantic versioning by:

  • Stripping the 'v' prefix
  • Splitting version strings into components
  • Comparing each numeric part in order

This addresses the previous review comment about string comparison issues.


220-221: Path expansion properly implemented.

Both validateImport and validateEnvFile now use the expandPath function, ensuring consistent path handling including tilde expansion. This addresses the previous review comments about inconsistent path handling.

Also applies to: 268-269


100-138: Excellent validation framework implementation.

The validation system provides:

  • Clear issue categorisation with appropriate severity levels
  • Version-aware feature compatibility checking
  • Detailed, actionable error messages
  • User-friendly output formatting
  • Backwards compatibility through appropriate use of warnings

The framework significantly enhances configuration troubleshooting capabilities.

Also applies to: 285-331

@ocean
Copy link
Member Author

ocean commented Jul 22, 2025

@AlexSkrypnyk Yep cool, good idea. I didn't want to add a new top level command at all, but that is a good suggestion to use "config" as a reserved word and then we can have sub-commands under it in future.

@ocean
Copy link
Member Author

ocean commented Jul 22, 2025

Also given this a new top level command, it's probably a breaking change that we should release as Ahoy v3 rather than another v2 release 🤔

ocean added 2 commits July 23, 2025 11:48
… cross platform compatibility

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
…tructure of "ahoy config ..." as "ahoy config validate"

Updated lots of tests, divided commands into separate files.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 6

🧹 Nitpick comments (12)
v2/testdata/.env.test (1)

1-2: Add missing newline at end of file.

The file lacks a newline character at the end, which can cause issues with some tools and violates POSIX standards for text files.

 TEST=value
-ANOTHER_VAR=another_value
+ANOTHER_VAR=another_value
+
v2/testdata/missing-api-version.ahoy.yml (1)

1-4: Add missing newline at end of file.

The file lacks a newline character at the end, which violates YAML formatting standards and can cause issues with some parsers.

 commands:
   test:
     description: Test command
-    cmd: echo "test"
+    cmd: echo "test"
+
v2/testdata/wrong-api-version.ahoy.yml (1)

1-5: Add missing newline at end of file.

The file lacks a newline character at the end, which violates YAML formatting standards.

 ahoyapi: v1
 commands:
   test:
     description: Test command
-    cmd: echo "test"
+    cmd: echo "test"
+
v2/testdata/with-env-files.ahoy.yml (1)

1-10: Fix formatting: Add newline at end of file.

The YAML file is missing a newline character at the end, which violates standard formatting conventions.

     env:
       - .env.command
+
v2/testdata/with-imports.ahoy.yml (1)

1-12: Fix formatting: Add newline at end of file.

The YAML file is missing a newline character at the end, which violates standard formatting conventions.

     - another-missing.ahoy.yml
   optional: true
+
v2/testdata/newer-features.ahoy.yml (1)

1-13: Fix formatting: Add newline at end of file.

The YAML file is missing a newline character at the end, which violates standard formatting conventions.

     - optional-import.ahoy.yml
   optional: true
+
v2/config_init_test.go (2)

9-26: Consider removing or implementing skipped network tests.

This test sets up the environment but then skips execution due to network dependencies. Consider either implementing the test with mocked network calls or removing it entirely if the integration tests provide sufficient coverage.


28-52: Consider removing or implementing skipped network tests.

Similar to the previous test, this sets up the environment but skips execution. The setup code provides some value for testing directory handling, but the overall test doesn't contribute to coverage.

v2/config_init.go (1)

72-85: Good error handling pattern but consider graceful degradation.

The CLI action function properly constructs the arguments and handles errors by printing to stderr and exiting. However, the direct os.Exit(1) call makes the function difficult to test.

Consider returning the error instead of calling os.Exit(1) directly:

 func initCommandAction(c *cli.Context) {
+	if err := initCommandActionImpl(c); err != nil {
+		fmt.Fprintln(os.Stderr, "Error:", err)
+		os.Exit(1)
+	}
+}
+
+func initCommandActionImpl(c *cli.Context) error {
 	args := InitArgs{
 		Force: c.Bool("force"),
 	}
 	
 	if len(c.Args()) > 0 {
 		args.URL = c.Args()[0]
 	}

-	if err := RunConfigInit(args); err != nil {
-		fmt.Fprintln(os.Stderr, "Error:", err)
-		os.Exit(1)
-	}
+	return RunConfigInit(args)
 }

This would make the function more testable while maintaining the same CLI behaviour.

v2/config_validation.go (3)

11-22: Consider using constants for Type and Severity values

To improve type safety and prevent typos, consider defining constants for the Type and Severity field values instead of using raw strings.

+// ValidationIssueType constants
+const (
+    IssueTypeVersionMismatch = "version_mismatch"
+    IssueTypeUnknownField    = "unknown_field"
+    IssueTypeMissingFile     = "missing_file"
+    IssueTypeSyntaxError     = "syntax_error"
+)
+
+// ValidationSeverity constants
+const (
+    SeverityError   = "error"
+    SeverityWarning = "warning"
+    SeverityInfo    = "info"
+)
+
 // ValidationIssue represents a configuration validation problem
 type ValidationIssue struct {
-	Type            string // "version_mismatch", "unknown_field", "missing_file", "syntax_error"
-	Severity        string // "error", "warning", "info"
+	Type            string
+	Severity        string
 	Message         string

35-35: Update version comment when releasing

The comment "This version we're implementing" should be updated or removed when v2.6.0 is actually released.


129-135: Optimise error checking by setting HasError immediately

Instead of looping through all issues at the end, set HasError when adding error-level issues.

Consider setting result.HasError = true immediately when adding error-level issues in lines 117 and within the validation functions, then remove this loop.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 379550a and a99c473.

📒 Files selected for processing (17)
  • v2/ahoy.go (8 hunks)
  • v2/ahoy_test.go (2 hunks)
  • v2/config.go (1 hunks)
  • v2/config_init.go (1 hunks)
  • v2/config_init_test.go (1 hunks)
  • v2/config_validation.go (1 hunks)
  • v2/config_validation_test.go (1 hunks)
  • v2/testdata/.env.test (1 hunks)
  • v2/testdata/invalid-yaml.ahoy.yml (1 hunks)
  • v2/testdata/missing-api-version.ahoy.yml (1 hunks)
  • v2/testdata/newer-features.ahoy.yml (1 hunks)
  • v2/testdata/with-env-files.ahoy.yml (1 hunks)
  • v2/testdata/with-imports.ahoy.yml (1 hunks)
  • v2/testdata/wrong-api-version.ahoy.yml (1 hunks)
  • v2/tests/config-init.bats (1 hunks)
  • v2/tests/config-validate.bats (1 hunks)
  • v2/windows_test.go (1 hunks)
🧬 Code Graph Analysis (2)
v2/config_init_test.go (1)
v2/config_init.go (1)
  • InitArgs (14-17)
v2/config_validation.go (1)
v2/ahoy.go (2)
  • Config (20-26)
  • Command (30-39)
🪛 GitHub Actions: Build and test
v2/config_init_test.go

[error] 9-92: gofmt formatting check failed. There are whitespace differences and missing newline at end of file. Run 'gofmt -w' to fix code style issues.

🪛 dotenv-linter (3.3.0)
v2/testdata/.env.test

[warning] 2-2: [EndingBlankLine] No blank line at the end of the file


[warning] 2-2: [UnorderedKey] The ANOTHER_VAR key should go before the TEST key

🪛 YAMLlint (1.37.1)
v2/testdata/invalid-yaml.ahoy.yml

[error] 5-5: syntax error: expected ',' or ']', but got ''

(syntax)

v2/testdata/missing-api-version.ahoy.yml

[error] 4-4: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/newer-features.ahoy.yml

[error] 13-13: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/with-env-files.ahoy.yml

[error] 10-10: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/with-imports.ahoy.yml

[error] 12-12: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/wrong-api-version.ahoy.yml

[error] 5-5: no new line character at the end of file

(new-line-at-end-of-file)

🚧 Files skipped from review as they are similar to previous changes (1)
  • v2/ahoy_test.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
v2/config_init_test.go (1)
v2/config_init.go (1)
  • InitArgs (14-17)
v2/config_validation.go (1)
v2/ahoy.go (2)
  • Config (20-26)
  • Command (30-39)
🪛 GitHub Actions: Build and test
v2/config_init_test.go

[error] 9-92: gofmt formatting check failed. There are whitespace differences and missing newline at end of file. Run 'gofmt -w' to fix code style issues.

🪛 dotenv-linter (3.3.0)
v2/testdata/.env.test

[warning] 2-2: [EndingBlankLine] No blank line at the end of the file


[warning] 2-2: [UnorderedKey] The ANOTHER_VAR key should go before the TEST key

🪛 YAMLlint (1.37.1)
v2/testdata/invalid-yaml.ahoy.yml

[error] 5-5: syntax error: expected ',' or ']', but got ''

(syntax)

v2/testdata/missing-api-version.ahoy.yml

[error] 4-4: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/newer-features.ahoy.yml

[error] 13-13: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/with-env-files.ahoy.yml

[error] 10-10: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/with-imports.ahoy.yml

[error] 12-12: no new line character at the end of file

(new-line-at-end-of-file)

v2/testdata/wrong-api-version.ahoy.yml

[error] 5-5: no new line character at the end of file

(new-line-at-end-of-file)

🔇 Additional comments (61)
v2/testdata/invalid-yaml.ahoy.yml (1)

1-5: LGTM - intentionally invalid YAML for testing.

The invalid YAML syntax with the unclosed array is correctly designed to test YAML parsing error handling in the validation system.

v2/windows_test.go (1)

17-17: LGTM - correctly updated function signature.

The getConfig call has been properly updated to include the new skipValidation parameter, maintaining the existing test behaviour whilst adapting to the enhanced configuration loading functionality.

v2/config.go (1)

9-27: Well-structured validation command implementation.

The function properly handles config file discovery, provides helpful user guidance for missing files, and cleanly separates validation execution from reporting. The use of ValidateOptions{SkipValidation: true} is appropriate for the validate command.

v2/config_init_test.go (2)

54-68: Good structural validation of InitArgs.

The test effectively validates that the InitArgs struct fields work as expected, providing good coverage of the basic struct functionality.


70-95: Comprehensive testing of fileExists helper.

The test covers all relevant scenarios: non-existent files, existing files, and directories. This provides good confidence in the helper function's behaviour.

v2/config_init.go (4)

1-11: Imports look appropriate for the functionality.

The imports cover all necessary functionality: file operations, command execution, path handling, and CLI framework integration.


13-17: Well-structured configuration struct.

The InitArgs struct provides a clean interface for the init command parameters with appropriate field names and types.


19-44: Proper file existence checking and user interaction.

The function correctly checks for existing .ahoy.yml files and provides appropriate user prompts. The logic for handling force mode versus interactive confirmation is well-implemented.


62-69: Clear success messaging.

The conditional messaging based on whether a custom URL was provided gives users appropriate feedback about what was downloaded.

v2/config_validation_test.go (19)

1-6: Standard test file structure.

Proper package declaration and testing import for a Go test file.


7-34: Well-structured test for non-existent config files.

The test properly validates the expected behaviour when a config file doesn't exist, checking both the boolean flags and the presence of appropriate recommendations.


36-61: Good test coverage for invalid YAML handling.

The test uses a static test file from testdata/ which is a good practice for reproducible tests. The assertions cover both the existence check and validation results.


63-84: Comprehensive validation of successful config parsing.

The test checks multiple aspects of a valid configuration: existence, validity, API version, and that the Ahoy version is populated.


86-122: Thorough testing of environment file detection.

The test validates that environment files are properly detected and their status is correctly reported. The approach of building maps to verify expected paths is solid.


124-152: Good coverage of import file functionality.

The test properly validates import file detection, including checking the optional flag and existence status. The verification that simple.ahoy.yml exists in testdata shows good test data management.


154-180: Effective testing of recommendation generation.

The test creates a minimal ConfigReport with specific validation issues and verifies that appropriate recommendations are generated. This is a good unit test approach.


182-209: Good test for missing import file scenarios.

The test constructs a realistic scenario with missing import files and validates that the correct recommendations are generated.


211-237: Appropriate test for missing environment files.

Similar to the import file test, this properly validates environment file recommendation generation.


239-265: Good coverage of version mismatch scenarios.

The test validates that newer feature warnings generate appropriate upgrade recommendations.


267-289: Important test for the happy path.

Testing the "no issues" scenario ensures that the system provides positive feedback when everything is correct.


291-335: Comprehensive environment file checking test.

The test uses a realistic configuration structure and validates both the detection logic and the global/command-specific environment file categorisation.


337-382: Thorough import file checking validation.

The test covers both regular and optional import files, ensuring that the optional flag is properly detected and reported.


384-417: Good structural validation of ConfigReport.

This test ensures that all expected fields are present and working correctly in the ConfigReport struct.


419-438: Proper field validation for EnvFileStatus.

The test validates the structure and field accessibility of the EnvFileStatus struct.


440-464: Complete field validation for ImportFileStatus.

The test ensures all fields of the ImportFileStatus struct are accessible and working correctly.


466-484: Important edge case testing.

Testing wrong API version scenarios ensures that the validation correctly handles version mismatches and provides appropriate error responses.


486-503: Good coverage of missing API version scenario.

This test ensures that configurations without API version specifications are properly detected and handled.


505-525: Validates newer features handling.

The test ensures that configurations with newer features are properly parsed and validated, which is important for backwards compatibility.

v2/tests/config-validate.bats (11)

1-15: Proper Bats test setup with good isolation.

The setup and teardown functions provide proper test isolation by creating temporary directories and cleaning up afterwards. This prevents tests from interfering with each other.


17-24: Good help output validation.

The test properly validates that the help command works and contains expected content. The regex patterns ensure key information is present.


26-32: Appropriate handling of missing config files.

The test validates that the command provides helpful guidance when no configuration file exists, including the suggestion to use ahoy config init.


34-58: Comprehensive validation of successful config processing.

The test creates a valid configuration and validates multiple aspects of the output including file detection, API version validation, YAML syntax checking, and overall health assessment.


60-75: Good error detection for invalid YAML.

The test creates a configuration with intentionally broken YAML syntax and validates that the error is properly detected and reported.


77-91: Proper API version validation testing.

The test validates that missing API version fields are detected and result in appropriate error messages.


93-108: Good coverage of wrong API version scenario.

The test ensures that incorrect API versions (like v1) are properly rejected with clear error messages.


110-135: Thorough environment file validation testing.

The test creates a realistic scenario with missing environment files and validates that the validation command properly detects and reports on them.


137-170: Comprehensive import file testing.

The test covers both existing and missing import files, including optional imports, and validates that the validation output properly reports their status.


172-190: Good complex error scenario testing.

The test creates a configuration with multiple issues and validates that the most critical error (API version) is properly reported first.


192-211: Important subdirectory execution test.

This test ensures that the validation command works correctly when run from a subdirectory, which is a common real-world scenario.

v2/tests/config-init.bats (8)

1-15: Consistent test infrastructure.

The setup and teardown follow the same pattern as the validation tests, providing good consistency and proper isolation.


17-27: Good test of basic init functionality.

The test validates that the init command successfully downloads and creates a configuration file with expected content.


29-42: Important backwards compatibility testing.

The test ensures that the legacy ahoy init command still works and properly displays the deprecation notice, which is crucial for user migration.


44-60: Realistic user interaction testing.

The test simulates user input ('n') to decline overwriting and validates that the original file remains unchanged. This is important for data safety.


62-79: Good validation of overwrite acceptance.

The test simulates user agreement ('y') and validates that the file is properly replaced with new content.


81-98: Important force flag testing.

The test validates that the --force flag bypasses user prompts and overwrites files directly, which is crucial for automation scenarios.


100-107: Pragmatic handling of network-dependent testing.

The test acknowledges the challenge of testing network operations in CI environments and focuses on validating the command structure instead.


109-117: Proper help output validation.

The test ensures that the help command provides complete information about the init command and its options.

v2/ahoy.go (8)

80-104: Well-implemented path expansion utility.

The expandPath function properly handles different path types (absolute, tilde, relative) with appropriate OS compatibility considerations. The logic is clear and the error handling for home directory expansion is appropriate.


126-126: Good simplification of loop condition.

Removing the redundant err == nil check makes the loop condition clearer and more focused on the actual termination condition.


141-182: Improved configuration loading with validation control.

The addition of the skipValidation parameter provides better control over when validation occurs. The conditional validation logic and improved error handling (returning errors instead of calling os.Exit) address the previous review comment about error handling patterns.


195-206: Enhanced path handling and error logging.

The use of expandPath for consistent path resolution and the addition of error logging for failed imports improve the robustness and debuggability of the import system.


363-387: Significantly improved error diagnostics.

The enhanced error message for commands with imports provides much more helpful information, including:

  • Context about missing import files
  • Specific suggestions for resolution
  • Version-aware upgrade recommendations
  • Reference to the validation command for additional help

This is a substantial improvement in user experience.


388-401: Good version compatibility checking.

The validation of optional import support based on the current Ahoy version prevents runtime errors and provides clear upgrade guidance when newer features are used with older versions.


416-468: Well-structured command hierarchy reorganisation.

The restructuring introduces a clean config command with init and validate subcommands while maintaining backwards compatibility with the legacy init command. The deprecation notice helps users migrate to the new structure.


564-564: Consistent parameter passing.

The update to pass false for skipValidation in the main setup ensures that normal operations include validation while allowing commands like validate to skip it when needed.

v2/config_validation.go (6)

164-213: Well-structured command validation

The command validation logic is comprehensive and properly handles all command features with appropriate version checks.


215-261: Comprehensive import validation logic

The import validation correctly handles all scenarios with appropriate severity levels and helpful error messages.


460-521: Excellent recommendation generation logic

The function provides comprehensive, actionable recommendations covering all issue types with a positive message when no issues are found.


523-647: Excellent diagnostic report formatting

The report uses clear visual indicators (emojis) and well-structured sections to present comprehensive diagnostic information in a user-friendly format.


384-384: Verified getConfig definition

  • The getConfig(file string, skipValidation bool) (Config, error) function is implemented in v2/ahoy.go (at lines 141–182).
  • No further changes needed.

329-329: Ignore circular suggestion concern

The PrintValidationIssues function (v2/config_validation.go) is never invoked by the validate subcommand—instead, validateCommandAction calls PrintConfigReport. Therefore the advice to run ahoy config validate only appears during other commands and isn’t redundant. You can safely disregard this comment.

Likely an incorrect or invalid review comment.

Comment on lines 38 to 56
// GetAhoyVersion returns the current Ahoy version
func GetAhoyVersion() string {
// Allow simulation of older versions for testing
if simulateVersion != "" {
return simulateVersion
}
if version == "" {
return "development"
}
return version
}

// GetAhoyVersionForTesting allows overriding version for testing
func GetAhoyVersionForTesting(testVersion string) string {
if testVersion != "" {
return testVersion
}
return GetAhoyVersion()
}
Copy link
Contributor

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify global variable definitions and consider simplifying test function

The functions reference simulateVersion and version variables that aren't defined in this file. Additionally, GetAhoyVersionForTesting seems redundant.

Consider removing GetAhoyVersionForTesting as GetAhoyVersion already handles test scenarios via simulateVersion.


🏁 Script executed:

#!/bin/bash
# Search for the definition of simulateVersion and version variables
rg -A 2 'var\s+(simulateVersion|version)\s+'

Length of output: 137


Define missing simulateVersion and simplify test override

The reference to simulateVersion in GetAhoyVersion will fail to compile—only version is declared in v2/ahoy.go. You should:

• Add a declaration for simulateVersion in v2/ahoy.go, for example:

// ahoy.go
var (
    version         string
    simulateVersion string
)

Or remove the simulateVersion branch from GetAhoyVersion if you don’t need runtime simulation.
• Reevaluate GetAhoyVersionForTesting: it merely wraps GetAhoyVersion. If you introduce a setter for simulateVersion, you can remove this function and call GetAhoyVersion directly in tests after setting the global, or vice versa.

Locations to update:

  • v2/ahoy.go: declare simulateVersion (or strip out simulation logic)
  • v2/config_validation.go (lines 38–56): remove or merge GetAhoyVersionForTesting
🤖 Prompt for AI Agents
In v2/ahoy.go, add a declaration for the variable simulateVersion alongside
version to avoid compilation errors due to its use in v2/config_validation.go.
Then, in v2/config_validation.go lines 38 to 56, either remove the
simulateVersion logic from GetAhoyVersion if runtime simulation is not needed,
or keep it and simplify by removing GetAhoyVersionForTesting entirely, using a
setter function to assign simulateVersion in tests and calling GetAhoyVersion
directly instead.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 0

🧹 Nitpick comments (1)
v2/ahoy.go (1)

85-87: Simplify absolute path detection logic.

The condition checks both filepath.IsAbs(path) and strings.HasPrefix(path, "/"), which is redundant. On Windows, filepath.IsAbs() correctly identifies C:\path as absolute, but strings.HasPrefix(path, "/") would be false. The Unix-style prefix check is unnecessary since filepath.IsAbs() handles cross-platform absolute path detection.

-	if filepath.IsAbs(path) || strings.HasPrefix(path, "/") {
-		// Absolute path (either OS-native or Unix-style), return as-is
+	if filepath.IsAbs(path) {
+		// Absolute path, return as-is
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a99c473 and 17146a9.

📒 Files selected for processing (4)
  • v2/ahoy.go (8 hunks)
  • v2/config.go (1 hunks)
  • v2/config_init.go (1 hunks)
  • v2/config_init_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • v2/config_init_test.go
  • v2/config.go
  • v2/config_init.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: build (ubuntu-latest)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (windows-latest)
🔇 Additional comments (6)
v2/ahoy.go (6)

126-126: Good simplification of loop termination logic.

Removing the redundant err == nil check makes the loop condition clearer and more focused on the actual termination condition (reaching the root directory).


166-180: Excellent improvement to error handling and validation control.

The conditional validation logic and proper error return (instead of os.Exit(1)) addresses previous feedback about inconsistent error handling patterns. This makes the function more testable and follows Go conventions.


195-206: Improved path handling and error resilience.

The use of expandPath ensures consistent path resolution, and the enhanced error handling allows graceful degradation when import files fail to load while providing useful diagnostic information.


363-399: Excellent enhancement to import error diagnostics.

The detailed error messages with specific solutions and version compatibility checks significantly improve the user experience. The multi-step guidance (create files, use optional imports, upgrade Ahoy) provides clear paths forward when imports fail.


562-562: Consistent with new function signature.

Correctly updates the call to match the new getConfig signature while maintaining existing validation behavior.


414-466: Verified: initCommandAction and validateCommandAction are present

Both action handlers are defined in the expected files:

  • initCommandAction in v2/config_init.go (lines 72–85)
  • validateCommandAction in v2/config.go (lines 10–27)

No further changes needed.

ocean added 3 commits July 23, 2025 13:38
…gh the code

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
…o built-in HTTP client

This means it's now OS-independent and also more secure.

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 0

♻️ Duplicate comments (3)
v2/config_validation.go (3)

41-41: ** Variable simulateVersion is not declared**

The reference to simulateVersion will cause a compilation error as only version is declared in v2/ahoy.go. This issue was previously identified and needs to be resolved.


201-201: ** Warning message remains unclear**

The suggestion "This should work but consider upgrading for better support" is still confusing for users. The previous feedback to clarify this message has not been addressed.


461-461: ** Inconsistent path resolution in environment file checking**

These functions use filepath.Join while validateEnvFile uses expandPath. This inconsistency was previously identified and should be fixed for uniform path handling.

Also applies to: 472-472

🧹 Nitpick comments (1)
v2/config_validation.go (1)

330-376: ** Consider using consistent output stream for validation messages**

The function outputs to os.Stderr but the main config report uses os.Stdout. Consider using a consistent approach or making the output stream configurable.

-func PrintValidationIssues(result ValidationResult) {
+func PrintValidationIssues(result ValidationResult, writer io.Writer) {
     if len(result.Issues) == 0 {
         return
     }
 
-    fmt.Fprintf(os.Stderr, "\nConfiguration Validation Issues:\n")
+    fmt.Fprintf(writer, "\nConfiguration Validation Issues:\n")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 225645a and d596d00.

📒 Files selected for processing (1)
  • v2/config_validation.go (1 hunks)
🧬 Code Graph Analysis (1)
v2/config_validation.go (1)
v2/ahoy.go (2)
  • Config (20-26)
  • Command (30-39)
🧰 Additional context used
🧬 Code Graph Analysis (1)
v2/config_validation.go (1)
v2/ahoy.go (2)
  • Config (20-26)
  • Command (30-39)
⏰ 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). (2)
  • GitHub Check: build (ubuntu-latest)
  • GitHub Check: build (macos-latest)
🔇 Additional comments (7)
v2/config_validation.go (7)

67-143: ** Excellent improvement to version comparison logic**

The version comparison function now properly handles pre-release versions and error cases from strconv.Atoi, addressing the previous review feedback. The implementation correctly follows semantic versioning rules for pre-release precedence.


266-266: ** Correct use of expandPath for consistent path resolution**

Good use of expandPath here for handling tilde expansion and relative paths consistently with the validation approach.


145-183: ** Well-structured main validation function**

The ValidateConfig function provides a comprehensive validation framework that properly orchestrates different validation checks and aggregates results effectively.

@AlexSkrypnyk
Copy link
Collaborator

Also given this a new top level command, it's probably a breaking change that we should release as Ahoy v3 rather than another v2 release 🤔

I think adding a new reserved word is not changing API much to have it as a new major version. But leaving this with you to decide.

Thank you for working on this

Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
@ocean ocean added the go Pull requests that update Go code label Jul 26, 2025
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: 0

♻️ Duplicate comments (1)
v2/config_validation.go (1)

201-201: Update suggestion text as per previous review

The suggestion text could be clearer about why upgrading is recommended.

🧹 Nitpick comments (1)
v2/config_validation.go (1)

35-35: Clarify the comment about schema validation version

The comment "This version we're implementing" is ambiguous. Consider clarifying it to indicate whether this is the version that introduces schema validation support.

-	"schema_validation":  "v2.6.0", // This version we're implementing
+	"schema_validation":  "v2.6.0", // Version that introduces schema validation
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between d77c5a5 and d435e34.

📒 Files selected for processing (3)
  • v2/ahoy.go (11 hunks)
  • v2/config_validation.go (1 hunks)
  • v2/tests/no-ahoy-file.bats (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (2)
v2/ahoy.go (1)
v2/config_validation.go (5)
  • ValidateConfig (146-183)
  • PrintValidationIssues (331-376)
  • GetAhoyVersion (39-48)
  • VersionSupports (51-63)
  • FeatureSupport (31-36)
v2/config_validation.go (1)
v2/ahoy.go (2)
  • Config (20-26)
  • Command (30-39)
⏰ 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). (2)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (15)
v2/tests/no-ahoy-file.bats (2)

27-28: Tests correctly updated for new command structure

The test assertions properly validate the new deprecation notice for ahoy init, which aligns with the PR's objective to move this functionality under ahoy config init.


35-36: Consistent test updates for --force flag

The test for ahoy init --force is consistently updated to check for the same deprecation notice.

v2/ahoy.go (7)

81-105: Well-implemented path expansion utility

The expandPath function correctly handles all path types (absolute, tilde, relative) with proper cross-platform support. The fallback behaviour for failed home directory retrieval is appropriate.


142-182: Improved error handling and validation control

The refactored getConfig function correctly implements conditional validation and returns errors instead of calling os.Exit(1) directly, addressing the previous review feedback. The verbose mode check appropriately reduces noise for non-error warnings.


196-207: Enhanced error handling for import file loading

Good improvement to log warnings when import files fail to load and continue processing other imports. Using expandPath ensures consistent path resolution across the codebase.


259-260: Consistent path expansion for environment files

Good use of expandPath for environment file paths, maintaining consistency with import file handling.


364-400: Excellent error diagnostics for import issues

The enhanced error messages provide clear, actionable guidance for users encountering import-related issues. The version-aware suggestions and detailed diagnostics significantly improve the user experience.


414-467: Well-structured command refactoring with backward compatibility

The refactoring successfully implements the new ahoy config command structure with init and validate subcommands while maintaining backward compatibility through the legacy init command. The deprecation notice appropriately guides users to the new command structure.


51-51: simulateVersion flag integration confirmed

The --simulate-version flag is defined in v2/flag.go (Destination: &simulateVersion), so the variable is correctly wired to the CLI. No further changes required here.

v2/config_validation.go (6)

38-63: Well-implemented version checking with test support

The version handling functions correctly support version simulation for testing and handle development versions appropriately.


67-143: Comprehensive semantic version comparison

The compareVersions function correctly implements semantic versioning comparison, including proper handling of pre-release versions and parsing errors, addressing the previous review feedback.


145-183: Comprehensive configuration validation logic

The ValidateConfig function provides thorough validation coverage with appropriate error tracking.


411-452: Well-structured validation orchestration

The RunConfigValidate function effectively orchestrates the validation process with proper error handling and recommendation generation.


454-503: Consistent path expansion in file checking functions

Good to see expandPath being used consistently in checkEnvironmentFiles and checkImportFiles, addressing the previous review comment about path handling consistency.


568-692: Excellent user-friendly diagnostic output

The PrintConfigReport function provides clear, visually appealing output with emoji indicators that make it easy to understand the configuration status at a glance. The structured format with sections for issues, files, and recommendations is very helpful.

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: 0

🧹 Nitpick comments (2)
README.md (2)

5-8: Keep badge alt-text consistent with other images

The new “Build and test” badge lacks a descriptive alt-text (Build and test is OK, but consider adding “GitHub Actions” for clarity and screen-reader users).
Example:

[![GitHub Actions – Build and test](...)](...)

Small accessibility win, zero functional impact.


252-253: Unordered-list style breaks project markdownlint rule

Line 252 begins with *, whereas the rest of the repo (and markdownlint rule MD004) expects -.
Replace the asterisk with a dash to silence the linter and keep style uniform.

-* [<img src="https://avatars.githubusercontent.com/u/378794?s=160&v=4" alt="Alex Skrypnyk - DrevOps" width="160px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
+- [<img src="https://avatars.githubusercontent.com/u/378794?s=160&v=4" alt="Alex Skrypnyk - DrevOps" width="160px;"><br />Alex Skrypnyk - DrevOps](https://drevops.com)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7c3efa6 and e907a5b.

📒 Files selected for processing (1)
  • README.md (3 hunks)
🧰 Additional context used
🪛 markdownlint-cli2 (0.17.2)
README.md

252-252: Unordered list style
Expected: dash; Actual: asterisk

(MD004, ul-style)

⏰ 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). (2)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (1)
README.md (1)

276-276: Contributor row added – looks good

Avatar URL, alt-text, and contribution icons are all correct; no action needed.

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

🔭 Outside diff range comments (2)
v2/ahoy.go (2)

344-366: Avoid env var leakage across command runs (use a local copy per invocation)

envVars is captured by the Action closure and appended to; this can accumulate per-command env vars across runs within the same process. Use a per-execution copy.

 				var cmdArgs []string
 				var cmdEntrypoint []string
+				// Start with a fresh copy of global env vars per execution.
+				cmdEnvVars := append([]string{}, envVars...)
@@
 				if len(cmd.Env) > 0 {
 					for _, envPath := range cmd.Env {
-						cmdEnvFile := expandPath(envPath, AhoyConf.srcDir)
-						vars := getEnvironmentVars(cmdEnvFile)
-						if vars != nil {
-							envVars = append(envVars, vars...)
-						}
+						cmdEnvFile := expandPath(envPath, AhoyConf.srcDir)
+						vars := getEnvironmentVars(cmdEnvFile)
+						if vars != nil {
+							cmdEnvVars = append(cmdEnvVars, vars...)
+						}
 					}
 				}
@@
-				command.Env = append(command.Environ(), envVars...)
+				command.Env = append(command.Environ(), cmdEnvVars...)

54-62: Ensure hidden simulate-version flag is fully wired and isolated in tests

We’ve confirmed:

  • v2/flag.go defines the hidden “simulate-version” CLI flag, binding to the global simulateVersion.
  • v2/config_validation.go’s GetAhoyVersion() honours simulateVersion when set.

Next steps:

  • Add or update tests for GetAhoyVersion() to cover both simulated and real-version paths.
  • In each test case, explicitly reset the global simulateVersion (for example in setup/teardown) to prevent cross-test state leakage.
♻️ Duplicate comments (1)
v2/ahoy.go (1)

151-191: Fix wrong filename in API version error; include filename in validation error; consider removing duplicate API check

  • Bug: Line 168 references global sourcefile instead of the provided file.
  • Suggestion: Include the filename in the returned validation error to aid debugging.
  • Optional: The API version check duplicates ValidateConfig; consider relying solely on validation for consistency.
 	if config.AhoyAPI != "v2" {
-		err = errors.New("Ahoy only supports API version 'v2', but '" + config.AhoyAPI + "' given in " + sourcefile)
+		err = errors.New("Ahoy only supports API version 'v2', but '" + config.AhoyAPI + "' given in " + file)
 		return config, err
 	}
@@
-			if validationResult.HasError {
-				return config, errors.New("configuration validation failed")
-			}
+			if validationResult.HasError {
+				return config, fmt.Errorf("configuration validation failed for %s", file)
+			}

Note: Great improvement over previous behaviour (no more os.Exit within getConfig); this addresses earlier feedback regarding error handling.

🧹 Nitpick comments (4)
v2/ahoy.go (4)

54-54: Document test-only simulateVersion to prevent misuse

Add a brief comment clarifying this is set via a hidden flag for tests and not for production use.

 var version string
-var simulateVersion string
+// Used by tests via a hidden CLI flag to emulate older Ahoy versions.
+// Not intended for production use; leave unset by default.
+var simulateVersion string

84-115: Normalise paths with filepath.Clean (minor hardening)

Function is correct; normalise outputs to avoid redundant separators and up-levels. Optional: the explicit "/" check is likely redundant on Windows as filepath.IsAbs handles rooted paths.

 	if filepath.IsAbs(path) {
-		// OS-native absolute path
-		return path
+		// OS-native absolute path
+		return filepath.Clean(path)
 	}
 	// On Windows, also treat Unix-style paths as absolute for cross-platform compatibility
 	if strings.HasPrefix(path, "/") {
 		// Unix-style absolute path
-		return path
+		return filepath.Clean(path)
 	} else if strings.HasPrefix(path, "~") {
 		// Tilde path, expand to home directory
 		if home, err := os.UserHomeDir(); err == nil {
 			// Handle both ~/path and ~\path (Windows)
 			remainder := path[1:]
 			if len(remainder) > 0 && (remainder[0] == '/' || remainder[0] == '\\') {
 				remainder = remainder[1:]
 			}
-			return filepath.Join(home, remainder)
+			return filepath.Clean(filepath.Join(home, remainder))
 		}
 		// If we can't get home dir, return original path
-		return path
+		return filepath.Clean(path)
 	} else {
 		// Relative path, join with base directory
-		return filepath.Join(baseDir, path)
+		return filepath.Clean(filepath.Join(baseDir, path))
 	}

428-476: Enforce the “config” reserved top-level command to avoid consumer clashes

You currently only add the default config command if not already present. This doesn’t “reserve” the name—consumer configs defining “config” will silently shadow these tools. Recommend one of:

  • Detect and warn/fail on user-defined “config” to preserve the reserved namespace.
  • Always register the built-in “config” command first and prevent overrides.
  • Document and enforce a set of reserved names at load time (e.g., {"config", "init"}).

This aligns with the PR goal to future-proof and avoid clashes.


468-470: Consider gating the deprecation note behind verbose or send to stderr

Printing a note to stdout can interfere with scripts parsing stdout from init. Consider printing to stderr or only when verbose is enabled.

-			fmt.Println("Note: 'ahoy init' is now available as 'ahoy config init'")
+			fmt.Fprintln(os.Stderr, "Note: 'ahoy init' is now available as 'ahoy config init'")
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between e907a5b and 535750b.

📒 Files selected for processing (2)
  • v2/ahoy.go (11 hunks)
  • v2/go.mod (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • v2/go.mod
🧰 Additional context used
🧬 Code Graph Analysis (1)
v2/ahoy.go (1)
v2/config_validation.go (5)
  • ValidateConfig (146-183)
  • PrintValidationIssues (331-376)
  • GetAhoyVersion (39-48)
  • VersionSupports (51-63)
  • FeatureSupport (31-36)
⏰ 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: build (macos-latest)
  • GitHub Check: build (windows-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (5)
v2/ahoy.go (5)

136-146: LGTM: Robust root detection in traversal

Using prevDir to terminate at filesystem root is correct and avoids relying on error state.


205-216: Good: Expand include paths and validate imported configs with graceful degradation

Imports now use expandPath and run validation; failures are logged as warnings and skipped. This makes imports safer without hard-failing the whole app.

Also applies to: 212-216


268-269: Global env path expansion is correct

Using expandPath against AhoyConf.srcDir improves portability for env files.


377-414: Clear, actionable diagnostics for missing imports and version support

Helpful guidance and version gating for optional_imports. This should reduce user friction when imports are missing or the Ahoy version is outdated.


576-576: LGTM: setupApp now opts into validation during initial config load

Updated call site matches new signature and intended flow.

ocean added 3 commits August 11, 2025 15:01
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
Signed-off-by: Drew Robinson <drew.robinson@gmail.com>
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: 0

🧹 Nitpick comments (1)
v2/Makefile (1)

76-76: Consider adding the conventional "all" target.

The static analysis tool correctly identifies that most Makefiles include an "all" target as a convention. While not required for functionality, it improves consistency with standard Makefile patterns.

Consider adding an "all" target:

+all: build
+
 .PHONY: clean test fmt fmtcheck staticcheck vet gocyclo modernize modernize-check version testdeps cross build_dir default install all
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 535750b and f7698a0.

📒 Files selected for processing (5)
  • v2/Makefile (2 hunks)
  • v2/ahoy.go (13 hunks)
  • v2/config_validation.go (1 hunks)
  • v2/config_validation_test.go (1 hunks)
  • v2/description_test.go (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • v2/config_validation_test.go
  • v2/config_validation.go
🧰 Additional context used
🧬 Code Graph Analysis (2)
v2/description_test.go (2)
v2/windows_test.go (2)
  • TestWindowsPathHandling (11-25)
  • TestWindowsConfigPathResolution (27-73)
v2/ahoy_test.go (1)
  • TestGetConfig (163-208)
v2/ahoy.go (1)
v2/config_validation.go (5)
  • ValidateConfig (146-183)
  • PrintValidationIssues (331-376)
  • GetAhoyVersion (39-48)
  • VersionSupports (51-63)
  • FeatureSupport (31-36)
🪛 checkmake (0.2.2)
v2/Makefile

[warning] 76-76: Missing required phony target "all"

(minphony)

⏰ 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). (2)
  • GitHub Check: build (macos-latest)
  • GitHub Check: build (ubuntu-latest)
🔇 Additional comments (16)
v2/Makefile (2)

45-47: Well-implemented formatting target.

The fmt target correctly applies gofmt -w to all Go source files. The implementation using $(foreach ...) is appropriate for this use case.


62-69: Excellent addition of modernization targets.

The modernize and modernize-check targets provide valuable tooling for maintaining modern Go code patterns. The separation between applying fixes (-fix) and preview mode (-test) follows best practices.

v2/description_test.go (1)

12-12: Correctly addressed the missing skipValidation parameter.

All getConfig calls have been properly updated to include the new skipValidation parameter with the appropriate false value for test scenarios. This resolves the past review comment about missing function arguments.

Also applies to: 69-69, 157-157, 202-202

v2/ahoy.go (13)

9-9: Appropriate addition of maps import.

The maps package import is correctly added to support the maps.Copy functionality used in the custom help printer.


55-55: Well-designed simulation variable for testing.

The simulateVersion variable provides a clean mechanism for testing version-specific behaviour without requiring actual version changes. This supports the version simulation functionality referenced in the related code snippets.


85-115: Robust path expansion implementation.

The expandPath function handles multiple path types correctly:

  • Absolute paths (both OS-native and Unix-style for cross-platform compatibility)
  • Tilde expansion with proper home directory resolution
  • Relative paths joined with base directory
  • Graceful fallback for home directory resolution failures

The Windows compatibility considerations are particularly well thought out.


137-137: Simplified loop condition improves readability.

The removal of && err == nil from the loop condition simplifies the logic whilst maintaining the same functional behaviour. The error handling is properly managed elsewhere in the function.


152-152: Function signature update addresses past review.

The addition of the skipValidation parameter to getConfig correctly addresses the past review comment about missing arguments in test files.


177-191: Excellent validation integration with proper error handling.

The validation logic correctly:

  • Skips validation when requested (for diagnostic commands)
  • Shows issues only in verbose mode or when errors exist
  • Returns an error instead of calling os.Exit(1) directly

This addresses the past review comment about inconsistent error handling patterns.


206-217: Improved import handling with proper error management.

The enhanced import loading logic:

  • Uses the new expandPath function for consistent path resolution
  • Provides informative warnings for failed imports instead of silent failures
  • Continues processing other imports when one fails

This is a significant improvement in robustness.


269-269: Consistent path expansion for environment files.

The use of expandPath for both global and command-level environment files ensures consistent path resolution across all configuration contexts.

Also applies to: 350-350


377-402: Enhanced error reporting for missing imports.

The improved error handling for imports provides:

  • Detailed context about missing files
  • Actionable solutions for users
  • Version-aware guidance for feature availability
  • Reference to the new ahoy config validate command

This significantly improves the user experience when configuration issues occur.


404-414: Proper version compatibility checking for optional imports.

The validation logic correctly checks if the current version supports optional imports and provides clear upgrade guidance when the feature is not available. This prevents silent failures and guides users toward appropriate solutions.


429-481: Well-structured config command implementation.

The new command structure:

  • Introduces the reserved config top-level command as agreed in PR discussions
  • Maintains backwards compatibility with the existing init command
  • Provides clear usage descriptions for all subcommands
  • Follows proper CLI command organisation patterns

The backwards compatibility notice is a nice touch for user guidance.


577-577: Correct usage of updated getConfig signature.

The call to getConfig(AhoyConf.srcFile, false) correctly uses the new signature with validation enabled for normal application startup.


594-594: Safe map copying implementation.

The use of maps.Copy to merge template functions is a clean and safe approach that avoids potential issues with manual map merging.

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

Labels

enhancement go Pull requests that update Go code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants