Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

restore hooks functionality #1010

Merged
merged 7 commits into from
Feb 4, 2025
Merged

restore hooks functionality #1010

merged 7 commits into from
Feb 4, 2025

Conversation

mcalhoun
Copy link
Member

@mcalhoun mcalhoun commented Feb 3, 2025

what

  • Restore the hooks functionality to atmos, since it was accidentally removed in a previous PR
  • Implemented a new hooks system for Terraform commands
  • Added support for after.terraform.apply events
  • Created a Redis-based store command for persisting Terraform outputs
  • Added integration tests for hooks and store functionality

why

  • Enables automation of post-deployment tasks through hooks
  • Provides a mechanism to share Terraform outputs between different components
  • Allows for more flexible and maintainable infrastructure deployment workflows
  • Ensures reliable state management across component deployments

references

  • Related to terraform hooks and event handling
  • Implements Redis-based state storage for cross-component communication

Summary by CodeRabbit

  • New Features

    • Enhanced the Terraform commands to support pre- and post-execution hooks that enable custom actions during deployments.
    • Improved the mechanism for managing and storing outputs, facilitating cross-component integrations.
    • Introduced new hooks and configuration structures to streamline output management between components.
    • Added a new YAML configuration file with detailed project settings, including Redis store and Terraform configurations.
    • Introduced a new StoreCommand structure for handling outputs within hooks.
  • Bug Fixes

    • Removed deprecated functions and streamlined command execution flow for improved reliability.
  • Documentation

    • Expanded configuration examples and messaging for better handling of deployment settings, including environment variable management.

This was referenced Feb 3, 2025
Copy link
Member Author

mcalhoun commented Feb 3, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@mergify mergify bot added the triage Needs triage label Feb 3, 2025
Copy link

mergify bot commented Feb 3, 2025

💥 This pull request now has conflicts. Could you fix it @mcalhoun? 🙏

@mergify mergify bot added the conflict This PR has conflicts label Feb 3, 2025
@mcalhoun mcalhoun added the no-release Do not create a new release (wait for additional code changes) label Feb 3, 2025 — with Graphite App
@mcalhoun mcalhoun marked this pull request as ready for review February 3, 2025 20:21
@mcalhoun mcalhoun requested review from a team as code owners February 3, 2025 20:21
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from a3110ed to bf1232e Compare February 3, 2025 20:56
@mcalhoun mcalhoun force-pushed the aws-ssm-param-store-get-key branch from 2ad5ece to 5a28ac1 Compare February 3, 2025 20:56
@mergify mergify bot removed the conflict This PR has conflicts label Feb 3, 2025
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from 748b99d to 1e175cb Compare February 3, 2025 21:21
@mcalhoun mcalhoun force-pushed the aws-ssm-param-store-get-key branch 2 times, most recently from 8563f33 to 13ffe7f Compare February 3, 2025 21:33
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from 1e175cb to 1501ce7 Compare February 3, 2025 21:33
Copy link

mergify bot commented Feb 3, 2025

💥 This pull request now has conflicts. Could you fix it @mcalhoun? 🙏

@mergify mergify bot added the conflict This PR has conflicts label Feb 3, 2025
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from 1e6a304 to ca0306b Compare February 3, 2025 21:57
@mcalhoun mcalhoun force-pushed the aws-ssm-param-store-get-key branch from f94f4cd to b4816f7 Compare February 3, 2025 21:57
@mergify mergify bot removed the conflict This PR has conflicts label Feb 3, 2025
@mcalhoun mcalhoun changed the base branch from aws-ssm-param-store-get-key to graphite-base/1010 February 4, 2025 01:16
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from ca0306b to da33ee9 Compare February 4, 2025 01:49
@mcalhoun mcalhoun changed the base branch from graphite-base/1010 to main February 4, 2025 01:50
@mcalhoun mcalhoun force-pushed the restore-hooks-functionality branch from da33ee9 to 7211dae Compare February 4, 2025 01:50
Copy link
Contributor

coderabbitai bot commented Feb 4, 2025

📝 Walkthrough

Walkthrough

This pull request refactors hook handling within the Terraform commands. A new runHooks function is introduced in cmd/terraform.go, and the old PostRunE hook logic is adjusted. The cmd/terraform_commands.go file now uses post-run hooks for the apply and deploy commands. In addition, new dependencies are added in go.mod, and integration tests using a mock Redis server are implemented in main_test.go. The hooks package has been restructured with new interfaces, types, and methods, while obsolete hook functions are removed. Test configurations for hooks are also provided in the fixtures.

Changes

File(s) Change Summary
cmd/terraform.go
cmd/terraform_commands.go
Added new function runHooks in terraform.go; removed old PostRunE from terraform.go; added PostRunE functions for apply and deploy commands in terraform_commands.go; updated import statements and documentation for hook execution flow.
go.mod Added direct dependency github.com/alicebob/miniredis/v2 v2.34.0 and indirect dependency github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302.
main_test.go Introduced new test function TestMainHooksAndStoreIntegration that uses a mock Redis server (miniredis) to simulate hook interactions during a two-step deployment process.
pkg/hooks/cmd.go Removed several functions related to processing hooks, including functions for checking Terraform apply and store commands, retrieving outputs, and processing/store commands.
pkg/hooks/command.go
pkg/hooks/event.go
pkg/hooks/hook.go
Introduced new hooks package: defined a Command interface, new HookEvent type with constants, and a Hook structure to store event, command, name, and outputs information.
pkg/hooks/hooks.go Introduced a new Hooks struct that encapsulates hook configurations; added methods GetHooks and RunAll for fetching and executing hooks; updated ConvertToHooks while retaining its interface.
pkg/hooks/store_cmd.go Added new StoreCommand struct with methods for processing store commands, retrieving output values, and logging/storing Terraform outputs as part of hook execution.
pkg/hooks/store.go Removed the old hooks store package and its associated logic for processing and storing outputs.
testdata/fixtures/hooks-test/atmos.yaml
testdata/fixtures/hooks-test/components/terraform/random/main.tf
testdata/fixtures/hooks-test/stacks/stack.yaml
Added new configuration files for integration tests; updated the Atmos YAML to include Redis store settings, Terraform component configurations, and stack definitions that include hook specifications for inter-component output storage and referencing.

Sequence Diagram(s)

sequenceDiagram
    participant CLI as CLI
    participant TC as Terraform Command
    participant RH as runHooks Function
    participant H as Hooks Manager
    participant SC as StoreCommand

    CLI->>TC: Execute Terraform command
    TC->>RH: Invoke runHooks(event, cmd, args)
    RH->>H: Fetch hooks configuration (GetHooks)
    H-->>RH: Return hooks configuration
    RH->>H: Execute hooks (RunAll)
    alt Hook requires store command
        H->>SC: Instantiate StoreCommand and call RunE
        SC-->>H: Return stored output result
    end
    H-->>RH: Completed hook execution
    RH-->>TC: Return result
    TC-->>CLI: Final command output
Loading

Possibly related PRs

Suggested labels

minor

Suggested reviewers

  • aknysh
  • osterman
✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • 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. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary or @auto-summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai or @auto-title 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.

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 (11)
pkg/hooks/hooks.go (3)

20-23: Consider defensive checks for the 'hooks' key before casting.

If “hooks” is missing, sections["hooks"].(map[string]any) could panic. Returning nil instead of &Hooks{} on errors is also more idiomatic.

 if val, ok := sections["hooks"].(map[string]any); ok {
     hooksSection := val
     ...
 } else {
-    return &Hooks{}, fmt.Errorf("no hooks section found")
+    return nil, fmt.Errorf("no hooks section found")
 }

Also applies to: 26-37, 39-46


48-66: Handle unknown commands or provide feedback.

Currently, only “store” is handled. A default case or a way to notify users about unrecognized commands might be helpful.

         switch hook.Command {
         case "store":
             ...
         default:
+            log.Warn("Unsupported hook command", "command", hook.Command)
         }

68-69: Implement or remove this placeholder.

Returning an empty Hooks without converting could lead to confusion.

Would you like me to propose an implementation or remove it if unused?

pkg/hooks/hook.go (1)

3-14: LGTM! Consider enhancing documentation.

The Hook struct is well-designed with clear YAML tags and good separation of concerns. The documentation is clear, but could be enhanced with examples.

Consider adding usage examples in the documentation:

 // Hook is the structure for a hook and is using in the stack config to define
 // a command that should be run when a specific event occurs.
+//
+// Example:
+//   hooks:
+//     - events: ["after.terraform.apply"]
+//       command: "store"
+//       name: "testredis"
+//       outputs:
+//         random_string: ".random_string"
 type Hook struct {
main_test.go (1)

33-42: Consider enhancing test assertions.

The test successfully validates the integration flow but could benefit from explicit assertions on the Redis state.

Consider adding assertions to verify the Redis state after each deployment:

 os.Args = []string{"atmos", "terraform", "deploy", "random1", "-s", "test"}
 main()
+// Verify Redis state after random1 deployment
+if got := s.Get("test/random1/random_string"); got == "" {
+    t.Error("expected Redis to contain output from random1")
+}

 os.Args = []string{"atmos", "terraform", "deploy", "random2", "-s", "test"}
 main()
+// Verify Redis state after random2 deployment
+if got := s.Get("test/random2/random_string"); got == "" {
+    t.Error("expected Redis to contain output from random2")
+}
cmd/terraform.go (1)

45-60: LGTM! Consider adding debug logging.

The runHooks function is well-structured with proper error handling. Consider adding debug logging for better observability.

 func runHooks(event h.HookEvent, cmd *cobra.Command, args []string) error {
+    log.Debug("running hooks", "event", event, "command", cmd.Name())
     info := getConfigAndStacksInfo("terraform", cmd, append([]string{cmd.Name()}, args...))

     // Initialize the CLI config
     atmosConfig, err := cfg.InitCliConfig(info, true)
     if err != nil {
+        log.Debug("failed to initialize CLI config", "error", err)
         return fmt.Errorf("error initializing CLI config: %w", err)
     }
pkg/hooks/store_cmd.go (2)

57-61: Optimize string comparison.

The string index check could be replaced with a more idiomatic Go approach.

-if strings.Index(value, ".") == 0 {
+if strings.HasPrefix(value, ".") {
     outputValue = e.GetTerraformOutput(c.atmosConfig, c.info.Stack, c.info.ComponentFromArg, outputKey, true)
 } else {
     outputValue = value
 }

65-77: LGTM! Consider adding validation.

The store output function is well-implemented with proper error handling and logging.

Consider adding validation for the output value:

 func (c *StoreCommand) storeOutput(hook *Hook, key string, outputKey string, outputValue any) error {
+    if outputValue == nil {
+        return fmt.Errorf("output value for key %q cannot be nil", key)
+    }
+
     log.Debug("checking if the store exists", "store", hook.Name)
     store := c.atmosConfig.Stores[hook.Name]
testdata/fixtures/hooks-test/components/terraform/random/main.tf (1)

1-20: Well-structured test configuration!

The configuration properly defines variables, uses triggers for updates, and exposes the required output for hook testing.

Consider adding validation for the stage variable to ensure it matches expected values.

 variable "stage" {
   description = "Stage where it will be deployed"
   type        = string
+  validation {
+    condition     = contains(["test", "dev", "prod"], var.stage)
+    error_message = "Stage must be one of: test, dev, prod"
+  }
 }
testdata/fixtures/hooks-test/atmos.yaml (1)

1-25: Solid configuration for hook testing!

The configuration properly sets up all required components: Redis store, Terraform settings, stack configuration, and logging.

Consider adding Redis connection settings for production use.

 stores:
   testredis:
     type: redis
+    host: ${REDIS_HOST:-localhost}
+    port: ${REDIS_PORT:-6379}
+    db: ${REDIS_DB:-0}
+    username: ${REDIS_USERNAME:-""}
+    password: ${REDIS_PASSWORD:-""}
testdata/fixtures/hooks-test/stacks/stack.yaml (1)

1-23: Excellent hook and store integration setup!

The configuration demonstrates proper hook usage and store value sharing between components.

Consider adding a description to the hook for better maintainability.

   hooks:
     store-outputs:
+      description: "Stores the random value for use by random2 component"
       events:
         - after-terraform-apply
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 2a38feb and 7211dae.

⛔ Files ignored due to path filters (1)
  • go.sum is excluded by !**/*.sum
📒 Files selected for processing (14)
  • cmd/terraform.go (2 hunks)
  • cmd/terraform_commands.go (4 hunks)
  • go.mod (2 hunks)
  • main_test.go (1 hunks)
  • pkg/hooks/cmd.go (0 hunks)
  • pkg/hooks/command.go (1 hunks)
  • pkg/hooks/event.go (1 hunks)
  • pkg/hooks/hook.go (1 hunks)
  • pkg/hooks/hooks.go (1 hunks)
  • pkg/hooks/store.go (0 hunks)
  • pkg/hooks/store_cmd.go (1 hunks)
  • testdata/fixtures/hooks-test/atmos.yaml (1 hunks)
  • testdata/fixtures/hooks-test/components/terraform/random/main.tf (1 hunks)
  • testdata/fixtures/hooks-test/stacks/stack.yaml (1 hunks)
💤 Files with no reviewable changes (2)
  • pkg/hooks/store.go
  • pkg/hooks/cmd.go
🧰 Additional context used
🪛 golangci-lint (1.62.2)
main_test.go

25-25: Error return value of os.Chdir is not checked

(errcheck)


27-27: Error return value of os.Chdir is not checked

(errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (9)
pkg/hooks/hooks.go (2)

6-10: Imports look appropriate.

They are used consistently in the file. No issues here.


14-18: Struct composition is clear.

These fields provide a good container for config, stack info, and hook items.

pkg/hooks/command.go (1)

1-9: Interface design looks good.

This is straightforward for hooking different commands.

pkg/hooks/event.go (1)

1-10: Event constants enable clean comparisons.

Nicely keeps Terraform event strings in one place.

cmd/terraform_commands.go (3)

6-7: LGTM! Hook execution properly integrated into apply command.

The implementation correctly logs hook execution and triggers the AfterTerraformApply event.

Also applies to: 32-35


164-172: Documentation improvements enhance clarity!

The updated documentation clearly explains the region variable handling and command arguments.


66-69: LGTM! Consistent hook handling in deploy command.

The deploy command correctly uses the same hook event as apply, maintaining consistency.

go.mod (2)

9-9: Miniredis Dependency Addition

The inclusion of github.com/alicebob/miniredis/v2 v2.34.0 directly supports your integration tests for the new Redis-based store functionality. Please confirm that this version meshes well with your test scenarios and overall environment.


85-85: Gopher-JSON Indirect Dependency Check

The dependency github.com/alicebob/gopher-json v0.0.0-20230218143504-906a9b012302 is added as an indirect requirement. Please verify that it is indeed required by one of your direct dependencies and that the pinned version meets your compatibility expectations.

main_test.go Outdated Show resolved Hide resolved
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 4, 2025
@mergify mergify bot removed the triage Needs triage label Feb 4, 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)
main_test.go (1)

25-25: ⚠️ Potential issue

Add error handling for directory restoration.

The deferred directory restoration should check for errors.

-defer os.Chdir(origDir)
+defer func() {
+    if err := os.Chdir(origDir); err != nil {
+        // In deferred functions, we can't return an error or fail the test directly
+        // Best practice is to log the error or panic
+        panic(fmt.Sprintf("failed to restore original directory: %v", err))
+    }
+}()
🧰 Tools
🪛 golangci-lint (1.62.2)

25-25: Error return value of os.Chdir is not checked

(errcheck)

🧹 Nitpick comments (1)
main_test.go (1)

35-44: Consider enhancing test robustness.

The test execution could be improved in several ways:

  1. Add assertions to verify the Redis store contains expected values after each main() call
  2. Consider capturing and validating main()'s output
  3. Add error handling for main() execution

Here's an example enhancement:

 os.Args = []string{"atmos", "terraform", "deploy", "random1", "-s", "test"}
-main()
+// Capture stdout for verification
+oldStdout := os.Stdout
+r, w, _ := os.Pipe()
+os.Stdout = w
+
+main()
+
+w.Close()
+os.Stdout = oldStdout
+
+// Verify Redis store
+val, err := s.Get("your_expected_key")
+if err != nil {
+    t.Fatalf("failed to get value from Redis: %v", err)
+}
+if val != "expected_value" {
+    t.Errorf("expected value %q, got %q", "expected_value", val)
+}
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7211dae and 136c025.

📒 Files selected for processing (1)
  • main_test.go (1 hunks)
🧰 Additional context used
🪛 golangci-lint (1.62.2)
main_test.go

25-25: Error return value of os.Chdir is not checked

(errcheck)

⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (2)
main_test.go (2)

12-19: LGTM! Clean Redis test setup.

The Redis mock setup is well-structured with proper cleanup using defer.


31-34: LGTM! Clean arguments management.

The original arguments are properly captured and restored.

coderabbitai[bot]
coderabbitai bot previously approved these changes Feb 4, 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: 2

🧹 Nitpick comments (2)
cmd/terraform.go (1)

47-67: Enhance logging for better observability

The function has good error handling, but could benefit from additional debug logs to help troubleshoot hook execution issues.

 func runHooks(event h.HookEvent, cmd *cobra.Command, args []string) error {
+    l.Debug("starting hook execution", "event", event, "command", cmd.Name())
     info := getConfigAndStacksInfo("terraform", cmd, append([]string{cmd.Name()}, args...))
cmd/terraform_commands.go (1)

31-33: Consider adding validation for args

The PostRunE hooks could benefit from validating that required arguments are present before executing the hooks.

 PostRunE: func(cmd *cobra.Command, args []string) error {
+    if len(args) == 0 {
+        return fmt.Errorf("component argument is required")
+    }
     return runHooks(h.AfterTerraformApply, cmd, args)
 },

Also applies to: 64-66

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 136c025 and ae4cf54.

📒 Files selected for processing (3)
  • cmd/terraform.go (2 hunks)
  • cmd/terraform_commands.go (4 hunks)
  • pkg/hooks/hooks.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Acceptance Tests (macos-latest, macos)
  • GitHub Check: Acceptance Tests (windows-latest, windows)
  • GitHub Check: Acceptance Tests (ubuntu-latest, linux)
  • GitHub Check: [localstack] demo-localstack
  • GitHub Check: Summary
🔇 Additional comments (2)
pkg/hooks/hooks.go (1)

14-18: Well-structured Hooks type!

The Hooks struct provides a clean encapsulation of configuration, info, and hook items. This design promotes better organization and maintainability.

cmd/terraform_commands.go (1)

160-169: Excellent documentation update!

The import command documentation is clear, comprehensive, and well-structured. It effectively explains the region handling and required arguments.

Comment on lines +24 to +50
func GetHooks(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (*Hooks, error) {
sections, err := e.ExecuteDescribeComponent(info.ComponentFromArg, info.Stack, true, true, []string{})
if err != nil {
return &Hooks{}, fmt.Errorf("failed to execute describe component: %w", err)
}

func (h Hooks) ConvertToHooks(input map[string]any) (Hooks, error) {
yamlData, err := yaml.Marshal(input)
hooksSection := sections["hooks"].(map[string]any)

yamlData, err := yaml.Marshal(hooksSection)
if err != nil {
return nil, fmt.Errorf("failed to marshal input: %w", err)
return &Hooks{}, fmt.Errorf("failed to marshal hooksSection: %w", err)
}

var hooks Hooks
err = yaml.Unmarshal(yamlData, &hooks)
var items map[string]Hook
err = yaml.Unmarshal(yamlData, &items)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal to Hooks: %w", err)
}

return hooks, nil
hooks := Hooks{
config: atmosConfig,
info: info,
items: items,
}

return &hooks, nil
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add nil check for hooksSection

The type assertion on line 30 could panic if the "hooks" section is nil. Add a safety check.

-  hooksSection := sections["hooks"].(map[string]any)
+  hooksSection, ok := sections["hooks"].(map[string]any)
+  if !ok {
+    return &Hooks{}, fmt.Errorf("hooks section is missing or invalid")
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func GetHooks(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (*Hooks, error) {
sections, err := e.ExecuteDescribeComponent(info.ComponentFromArg, info.Stack, true, true, []string{})
if err != nil {
return &Hooks{}, fmt.Errorf("failed to execute describe component: %w", err)
}
func (h Hooks) ConvertToHooks(input map[string]any) (Hooks, error) {
yamlData, err := yaml.Marshal(input)
hooksSection := sections["hooks"].(map[string]any)
yamlData, err := yaml.Marshal(hooksSection)
if err != nil {
return nil, fmt.Errorf("failed to marshal input: %w", err)
return &Hooks{}, fmt.Errorf("failed to marshal hooksSection: %w", err)
}
var hooks Hooks
err = yaml.Unmarshal(yamlData, &hooks)
var items map[string]Hook
err = yaml.Unmarshal(yamlData, &items)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal to Hooks: %w", err)
}
return hooks, nil
hooks := Hooks{
config: atmosConfig,
info: info,
items: items,
}
return &hooks, nil
}
func GetHooks(atmosConfig *schema.AtmosConfiguration, info *schema.ConfigAndStacksInfo) (*Hooks, error) {
sections, err := e.ExecuteDescribeComponent(info.ComponentFromArg, info.Stack, true, true, []string{})
if err != nil {
return &Hooks{}, fmt.Errorf("failed to execute describe component: %w", err)
}
// Safely assert hooksSection to avoid nil pointer dereference
hooksSection, ok := sections["hooks"].(map[string]any)
if !ok {
return &Hooks{}, fmt.Errorf("hooks section is missing or invalid")
}
yamlData, err := yaml.Marshal(hooksSection)
if err != nil {
return &Hooks{}, fmt.Errorf("failed to marshal hooksSection: %w", err)
}
var items map[string]Hook
err = yaml.Unmarshal(yamlData, &items)
if err != nil {
return nil, fmt.Errorf("failed to unmarshal to Hooks: %w", err)
}
hooks := Hooks{
config: atmosConfig,
info: info,
items: items,
}
return &hooks, nil
}

pkg/hooks/hooks.go Show resolved Hide resolved
@mcalhoun mcalhoun merged commit b8fd5dc into main Feb 4, 2025
45 checks passed
@mcalhoun mcalhoun deleted the restore-hooks-functionality branch February 4, 2025 03:48
Copy link

github-actions bot commented Feb 5, 2025

These changes were released in v1.159.0.

Cerebrovinny pushed a commit that referenced this pull request Feb 9, 2025
* restore hooks functionality
* [autofix.ci] apply automated fixes

* Update main_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* [autofix.ci] apply automated fixes

* [autofix.ci] apply automated fixes

---------

Co-authored-by: autofix-ci[bot] <114827586+autofix-ci[bot]@users.noreply.github.com>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-release Do not create a new release (wait for additional code changes)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant