Skip to content

Conversation

yhakbar
Copy link
Collaborator

@yhakbar yhakbar commented Mar 28, 2025

Description

Adds error handling for discovery.

This is important, as it allows the list and find commands to operate without failure when running against directories of configurations with requirements like authentication, etc. that aren't relevant to the discovery process.

TODOs

Read the Gruntwork contribution guidelines.

  • Update the docs.
  • Run the relevant tests successfully, including pre-commit checks.
  • Ensure any 3rd party code adheres with our license policy or delete this line if its not applicable.
  • Include release notes. If this PR is backward incompatible, include a migration guide.

Release Notes (draft)

Updated discovery to handle errors gracefully.

Summary by CodeRabbit

  • New Features

    • CLI commands now handle minor configuration issues more gracefully by logging warnings instead of abruptly terminating, ensuring smoother operation.
    • Enhanced discovery process with improved error handling and suppression of parse errors.
  • Documentation

    • Updated reference materials now reflect the finalized experimental tasks related to improved command processing, including completed integration tests for CLI commands.
  • Tests

    • Expanded test coverage for Terragrunt command functionalities with new test cases and improved memory management in the test suite.

Copy link

vercel bot commented Mar 28, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
terragrunt-docs ✅ Ready (Inspect) Visit Preview 💬 Add feedback Mar 31, 2025 3:00pm

Copy link
Contributor

coderabbitai bot commented Mar 28, 2025

📝 Walkthrough

Walkthrough

This PR updates the error handling and initialization of the discovery process used by the CLI commands. Both the find and list commands now configure their discovery objects with a chainable method to suppress parse errors. In addition, internal discovery logic has been enhanced with new fields and methods to manage parse errors and cycle detection, along with corresponding test suite updates and documentation task status revisions.

Changes

File(s) Change Summary
cli/commands/find/find.go
cli/commands/list/list.go
Updated discovery initialization by chaining WithSuppressParseErrors(). In the find command, error handling now logs warnings instead of returning errors.
internal/discovery/discovery.go Added a new suppressParseErrors flag and corresponding WithSuppressParseErrors() methods. Modified Discover, CycleCheck, and introduced RemoveCycles to manage parse errors and dependency cycles.
internal/discovery/discovery_test.go Adjusted tests for CycleCheck to capture and assert on both the returned configuration and error, ensuring proper behavior based on cycle detection outcomes.
docs/_docs/04_reference/06-experiments.md Updated task statuses for the cli-redesign feature, marking previously pending tasks (handling of broken configurations, integration tests for find and list commands with --sort=dag) as completed.
test/integration_parse_test.go Improved memory management by invoking runtime.GC() during configuration parsing, extracted knownBadFiles variable, and added three new integration test functions to test command outputs and dependency ordering.

Sequence Diagram(s)

sequenceDiagram
    participant Command
    participant Discovery
    participant DepDiscovery
    participant Logger

    Command->>Discovery: NewDiscovery(WorkingDir)
    Discovery->>Discovery: WithSuppressParseErrors()
    Discovery->>DepDiscovery: Create dependency discovery instance
    DepDiscovery-->>Discovery: Return discovery results or parse errors
    alt Parse error occurs and suppression enabled
        Discovery->>Logger: Log warning with error details
        Discovery-->>Command: Continue execution without error propagation
    else Valid results or unsuppressed error
        Discovery-->>Command: Return result or error normally
    end
Loading

Possibly related PRs

Suggested reviewers

  • denis256
  • levkohimins

📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 017e172 and f1ffde8.

📒 Files selected for processing (1)
  • internal/discovery/discovery.go (13 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • internal/discovery/discovery.go
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Pull Request has non-contributor approval
  • GitHub Check: build-and-test
  • GitHub Check: unessential
  • GitHub Check: Pull Request has non-contributor approval

🪧 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.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

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

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

Documentation and Community

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

@yhakbar yhakbar marked this pull request as ready for review March 28, 2025 21:08
@yhakbar yhakbar requested review from denis256 and lev-ok as code owners March 28, 2025 21:08
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)
internal/discovery/discovery.go (1)

546-565: Multi-iteration cycle removal strategy.

This works well but might remove many configs in complex cycles. Consider logging each removal for clarity:

 for range maxCycleChecks {
   if cfg, err = c.CycleCheck(); err == nil {
     break
   }
+  opts.Logger.Debugf("Removing discovered config at path due to cycle: %s", cfg.Path)
   c = c.RemoveByPath(cfg.Path)
 }

This helps diagnose multi-cycle removal scenarios.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 2df2cda and 017e172.

📒 Files selected for processing (6)
  • cli/commands/find/find.go (2 hunks)
  • cli/commands/list/list.go (1 hunks)
  • docs/_docs/04_reference/06-experiments.md (2 hunks)
  • internal/discovery/discovery.go (13 hunks)
  • internal/discovery/discovery_test.go (1 hunks)
  • test/integration_parse_test.go (3 hunks)
🧰 Additional context used
📓 Path-based instructions (2)
`**/*.go`: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

**/*.go: Review the Go code for quality and correctness. Make sure that the Go code follows best practices, is performant, and is easy to understand and maintain.

  • cli/commands/list/list.go
  • cli/commands/find/find.go
  • internal/discovery/discovery_test.go
  • test/integration_parse_test.go
  • internal/discovery/discovery.go
`docs/**/*.md`: Review the documentation for clarity, grammar, and spelling. Make sure that the documentation is easy to understand and follow. There is currently a migration under...

docs/**/*.md: Review the documentation for clarity, grammar, and spelling. Make sure that the documentation is easy to understand and follow. There is currently a migration underway from the Jekyll based documentation in docs to the Starlight + Astro based documentation in docs-starlight. Whenever changes are made to the docs directory, ensure that an equivalent change is made in the docs-starlight directory to keep the docs-starlight documentation accurate.

  • docs/_docs/04_reference/06-experiments.md
🧬 Code Definitions (3)
cli/commands/list/list.go (1)
internal/discovery/discovery.go (1)
  • NewDiscovery (85-96)
cli/commands/find/find.go (1)
internal/discovery/discovery.go (1)
  • NewDiscovery (85-96)
test/integration_parse_test.go (1)
test/helpers/package.go (1)
  • RunTerragruntCommandWithOutput (827-831)
⏰ Context from checks skipped due to timeout of 90000ms (1)
  • GitHub Check: Pull Request has non-contributor approval
🔇 Additional comments (34)
internal/discovery/discovery.go (20)

6-6: Imports look good.

The new io import is used for discarding output when suppressParseErrors is set, which helps reduce noise.


16-17: Logging dependency addition.

The introduction of github.com/gruntwork-io/terragrunt/pkg/log and its formatter is consistent with the new suppress-logging approach.


77-78: New suppressParseErrors field.

This boolean flag cleanly aligns with the overarching design to optionally ignore parse errors during discovery.


137-142: Chainable method to toggle parse error suppression.

This is consistent with the existing style of With* methods, enabling selective error handling when discovering modules.


226-235: Conditional enabling of parse error suppression in dependency discovery.

This implementation follows the new WithSuppressParseErrors approach. It correctly ensures downstream dependency discovery inherits the same flag.


241-244: Warn-level logging for suppressed parse errors.

Converting parse errors to warnings is aligned with the PR objective. No issues detected, and debug logs are used to capture full details.


248-257: Cycle detection and removal flow.

Good approach to detect and remove cycles before finalizing discovered configs. The warning plus debug statements effectively communicate the issue and resolution steps.


267-273: Extended DependencyDiscovery with suppressParseErrors.

Mirroring the pattern established in Discovery ensures consistent error-suppression handling across both code paths.


275-281: Constructor signature for NewDependencyDiscovery.

The initialization combines default values with the given config references. The pattern remains clear and maintains backward compatibility in other calls.


285-290: Chainable WithSuppressParseErrors for DependencyDiscovery.

Matches the style in the Discovery struct. Straightforward, no additional concerns noted.


292-297: Chainable WithDiscoverExternalDependencies.

Again, follows the pattern of toggling features with a fluent API. Nicely done.


325-329: Early return for stack configs.

This is consistent with current design assumptions that stacks do not hold direct dependencies. No concerns unless future requirements change.


331-341: Discarding output for parse operations.

Excellent approach to prevent irrelevant parse logs from surfacing when suppressParseErrors is in effect.


354-363: Partial parse error handling.

Ensure config.PartialParseConfigFile will always yield a non-nil cfg on partial parses. Otherwise, ignoring parse errors might mask deeper issues. If you’d like, I can generate a script to verify if partial parse commonly produces a nil config upon error.


375-375: Path resolution logic for dependencies.

Using filepath.Join(parseOpts.WorkingDir, depPath) keeps path references consistent and reduces relative path pitfalls.


384-384: Absolute path logic for dependency references.

Similarly ensures paths remain consistent when building the dependency graph.


395-397: Early return for empty dependency sets.

Saves time and avoids unnecessary processing when no dependencies are present.


448-450: Constructing external config stubs.

Correctly sets up a minimal DiscoveredConfig for external references, ensuring they can still be tracked if needed.


480-491: RemoveByPath for DiscoveredConfigs.

This helper is straightforward and will be especially useful for removing problematic entries encountered in cycle detection or error scenarios.


503-544: Revised CycleCheck to return the first config in a cycle.

Clear logic for cycle detection. The approach to return the offending config (*DiscoveredConfig) alongside the error helps identify the cycle origin.

cli/commands/list/list.go (1)

21-23: Suppressing parse errors during list discovery.

Chaining WithSuppressParseErrors() follows the new standard for graceful error handling without interrupting user workflows.

cli/commands/find/find.go (2)

17-19: New chaining of suppression for the discovery object.

This mirrors the list command’s pattern, promoting uniform error-handling across CLI commands.


35-36: Warn instead of fail on discovery errors.

Shifting from returning the error to issuing a warning aligns with the PR objective of allowing partial or best-effort results when parse errors occur.

internal/discovery/discovery_test.go (3)

380-381: Method signature update looks good.

The test now properly captures both the configuration and error return values from the CycleCheck method, aligning with the updated method signature.


384-384: Good assert addition for cycle detection.

This assertion correctly verifies that when a cycle is detected, the configuration where the cycle was found is returned (not nil) alongside the error, which provides better debugging information.


387-387: Good assert addition for no cycle scenario.

This assertion correctly verifies that when no cycle is detected, no configuration is returned (nil), which complements the error check on the previous line.

docs/_docs/04_reference/06-experiments.md (2)

169-170: Documentation update reflects completed features.

The checkmarks now correctly indicate that error handling for broken configurations and integration tests for the find command have been implemented, which aligns with the PR objective of enhancing error handling.


184-185: Documentation update reflects completed features.

The checkmarks now correctly indicate that error handling for broken configurations and integration tests for the list command have been implemented, which aligns with the PR objective of enhancing error handling.

test/integration_parse_test.go (6)

3-6: Improved comment clarity about memory issues.

The updated comments clearly explain the memory consumption problem and the need to run these tests in isolation, which is helpful for future developers who may encounter or need to address these issues.


25-31: Good addition of centralized problematic files list.

Centralizing the list of known problematic files makes it easier to maintain and understand which files are expected to fail parsing, improving code maintainability.


66-69: Good memory management improvement.

Explicitly triggering garbage collection after parsing each configuration file is a smart approach to reduce memory pressure, especially for these memory-intensive tests.


74-116: Well-implemented test for basic command functionality.

This new test properly validates that both find and list commands work correctly without additional flags. It also verifies that the dependency order is as expected (a-dependent comes before b-dependency in the output).


118-160: Well-implemented test for DAG sorting functionality.

This test correctly validates that when using the --dag flag, the dependency order is reversed compared to the default alphabetical sorting (b-dependency now comes before a-dependent in the output), which is the expected behavior for DAG-based sorting.


162-204: Well-implemented test for DAG with external dependencies.

This test properly validates the combined functionality of --dag and --external flags, ensuring that dependency order is maintained correctly even when external dependencies are included.

denis256
denis256 previously approved these changes Mar 31, 2025
break
}

c = c.RemoveByPath(cfg.Path)
Copy link
Member

Choose a reason for hiding this comment

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

cfg might have 'nil'?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

It shouldn't ever have nil, but I can add a check.

@yhakbar yhakbar merged commit 2b5bb16 into main Mar 31, 2025
8 of 9 checks passed
@yhakbar yhakbar deleted the feat/adding-error-handling-for-discovery branch March 31, 2025 15:43
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants