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

Fix vendor pull directory creation issue #782

Open
wants to merge 12 commits into
base: main
Choose a base branch
from
Open

Conversation

Cerebrovinny
Copy link
Collaborator

@Cerebrovinny Cerebrovinny commented Nov 14, 2024

what

Fixed the regression where the vendor command would error if the vendor manifests file path did not exist.

why

Previously, the atmos vendor pull command would fail with a “no such file or directory” error when the vendor manifests file path was missing.

references

Closes #780

Logic design

@aknysh following test cases

When vendor.yaml exists and using -c flag:
Correctly checks if the component exists in vendor.yaml
Error if component not found in vendor.yaml

When no vendor.yaml but component.yaml exists:
Proceeds without vendor configurations
Pulls from component.yaml configuration
Shows a Warning about vendor.yaml not existing

When component specified but no vendor.yaml or component.yaml:
System correct shows vendor.yaml doesn't exist
Properly errors that component.yaml doesn't exist in the component folder

When no component specified:
a. With vendor.yaml:
System attempts to process vendor.yaml
Shows appropriate error for invalid configuration

b. Without vendor.yaml:
System shows vendor.yaml doesn't exist
Provides an error message about needing to specify --component flag

CleanShot 2024-11-28 at 18 22 36
CleanShot 2024-11-28 at 18 29 14
CleanShot 2024-11-28 at 18 30 06
CleanShot 2024-11-28 at 18 30 25
CleanShot 2024-11-28 at 18 31 38

I also added tests integrating these criteria's

This is before the fix so the tests fail

Screenshot 2024-11-28 at 22 33 43

This is after the fix all tests are passing

Screenshot 2024-11-28 at 22 37 08

Summary by CodeRabbit

  • New Features

    • Enhanced error handling for vendor configuration file checks, ensuring smoother operations when files are missing.
    • Introduced a new test suite for vendor configuration functionality, covering various scenarios to ensure reliability.
  • Bug Fixes

    • Improved clarity in error reporting related to vendor configuration file existence.
  • Tests

    • Added comprehensive unit tests to validate the behavior of vendor configuration handling under different conditions.

Copy link
Contributor

coderabbitai bot commented Nov 14, 2024

📝 Walkthrough

Walkthrough

The changes in this pull request enhance the ReadAndProcessVendorConfigFile function in internal/exec/vendor_utils.go by improving error handling related to vendor configuration files. A boolean flag is introduced to indicate the existence of the vendor configuration file, and the function now logs a warning instead of returning an error when the file is not found. Additionally, a new file vendor_config_test.go is added, containing unit tests for various scenarios involving vendor configuration files.

Changes

File Change Summary
internal/exec/vendor_utils.go Enhanced ReadAndProcessVendorConfigFile function with improved error handling and new flags.
pkg/vender/vendor_config_test.go Introduced unit tests for vendor configuration handling, covering multiple scenarios.

Assessment against linked issues

Objective Addressed Explanation
Running atmos vendor pull using component.yaml should succeed (#780)

Possibly related PRs

Suggested reviewers

  • osterman
  • aknysh
  • nitrocode

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

🧹 Outside diff range and nitpick comments (1)
internal/exec/vendor_utils.go (1)

554-557: LGTM! This is a solid fix for the directory creation issue.

The addition of os.MkdirAll before the copy operation is exactly what was needed to resolve the "no such file or directory" error. The error handling is well-structured and provides clear feedback.

A small suggestion to make the code even more robust:

 targetDir := filepath.Dir(targetPath)
-if err := os.MkdirAll(targetDir, 0755); err != nil {
+if err := os.MkdirAll(targetDir, 0o755); err != nil {
   return fmt.Errorf("failed to create target directory '%s': %w", targetDir, err)
 }

Using 0o755 instead of 0755 makes the octal permission more explicit and follows modern Go conventions.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 9acca77 and cf24006.

📒 Files selected for processing (1)
  • internal/exec/vendor_utils.go (1 hunks)

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 14, 2024
@osterman
Copy link
Member

osterman commented Nov 14, 2024

@Cerebrovinny I do not think this is the fix based on the description of the problem. Bear in mind we have two types of vendor manifests.

https://atmos.tools/core-concepts/vendor/

The bug report concerns the component manifest file. That means that any logic relating to the vendor manifests file should not inhibit the component manifest from functioning.

To me, it sounds like the regression is that when vendoring a component manifest, it is erroring if the vendor manifests file path does not exist. However, that should not be required. We should instead log to warning that the path does not exist and continue processing.

We should not create the vendor configuration path if it does not exist.

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 15, 2024
@Cerebrovinny
Copy link
Collaborator Author

Cerebrovinny commented Nov 15, 2024

@osterman @aknysh another idea would be start integrating something like this in documentation so the users can consult

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 15, 2024
@osterman osterman added the patch A minor, backward compatible change label Nov 15, 2024
aknysh and others added 3 commits November 19, 2024 00:02
* fix: handle empty stack YAML configuration and adjust file content retrieval

* fix: return existing content from GetFileContent instead of an empty string

* fix: remove unnecessary blank lines in ProcessYAMLConfigFile and GetFileContent functions
* feat: set default Atmos manifest URL if not specified in configuration

* feat: log trace message when using default Atmos JSON Schema file

* fix: improve error message for missing Atmos JSON Schema file

* Update internal/exec/validate_stacks.go

* fix: change log level from trace to info for default Atmos JSON Schema message

* fix: change log level from info to trace for default Atmos JSON Schema message

---------

Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
Co-authored-by: Andriy Knysh <[email protected]>
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

🧹 Outside diff range and nitpick comments (1)
internal/exec/validate_stacks.go (1)

105-110: Consider improving error message readability.

While the error message is informative, we can make it more readable.

Consider this format:

-		return fmt.Errorf("Schema file '%s' not found. Configure via:\n"+
-			"1. 'schemas.atmos.manifest' in atmos.yaml\n"+
-			"2. ATMOS_SCHEMAS_ATMOS_MANIFEST env var\n"+
-			"3. --schemas-atmos-manifest flag\n\n"+
-			"Accepts: absolute path, paths relative to base_path, or URL",
-			cliConfig.Schemas.Atmos.Manifest)
+		return fmt.Errorf("Schema file '%s' not found.\n\n"+
+			"Configure using any of these methods:\n"+
+			"  1. 'schemas.atmos.manifest' in atmos.yaml\n"+
+			"  2. ATMOS_SCHEMAS_ATMOS_MANIFEST env var\n"+
+			"  3. --schemas-atmos-manifest flag\n\n"+
+			"Accepts:\n"+
+			"  • absolute path\n"+
+			"  • paths relative to base_path\n"+
+			"  • URL",
+			cliConfig.Schemas.Atmos.Manifest)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 59a9602 and 50ff73e.

📒 Files selected for processing (2)
  • internal/exec/stack_processor_utils.go (1 hunks)
  • internal/exec/validate_stacks.go (2 hunks)
🧰 Additional context used
📓 Learnings (1)
internal/exec/validate_stacks.go (1)
Learnt from: haitham911
PR: cloudposse/atmos#731
File: internal/exec/validate_stacks.go:0-0
Timestamp: 2024-11-12T05:52:05.088Z
Learning: In `internal/exec/validate_stacks.go`, when downloading the Atmos JSON Schema file to the temp directory, the temporary file is overwritten each time, so explicit removal is not necessary.
🔇 Additional comments (4)
internal/exec/validate_stacks.go (2)

22-23: LGTM! Good addition of default schema URL.

Adding a default schema URL constant improves the robustness of the validation process. This ensures we always have a fallback schema location.


89-92: LGTM! Robust default schema handling.

The logic for handling empty schema configuration is solid. Using trace logging to inform about default schema usage is a good practice for debugging.

internal/exec/stack_processor_utils.go (2)

202-204: LGTM! The empty config handling looks good.

The addition of this early return for empty YAML configurations is a solid defensive programming practice. It gracefully handles the case where a file exists but is empty, returning empty maps which is consistent with the error handling pattern used when files don't exist.


202-204: Verify the impact on vendor pull operations.

While the empty config handling looks correct, let's verify that this change properly fixes the vendor pull directory creation issue.

#!/bin/bash
# Description: Check for any other instances where empty YAML configs might be handled differently

# Test: Search for similar empty YAML handling patterns
rg -A 5 "stackYamlConfig\s*==" 

# Test: Look for vendor-related file operations
rg -A 5 "vendor.*pull"

coderabbitai[bot]
coderabbitai bot previously approved these changes Nov 19, 2024
@aknysh
Copy link
Member

aknysh commented Nov 26, 2024

@Cerebrovinny thanks for the PR.
Did you test these use cases:

  • vendor.yaml exists and the user uses -c flag to vendor a component, and the component is defined in vendor.yaml - in this case Atmos needs to vendor the component from vendor.yaml

  • vendor.yaml does not exist and the user uses -c flag to vendor a component. There is a component.yaml file in the component directory. In this case Atmos needs to vendor the component from component.yaml

  • If the suer specifies a component -c <component>, and it's not defined in vendor.yaml and there is no component.yaml files in the component folder, throw an error

  • If the user does not specify a component, then:

    • If vendor.yaml exists, use it to vendor all components
    • If vendor.yaml does not exist, print an error

vendor.yaml takes precedence over component.yaml if the same component is defined in both.

Copy link
Member

@aknysh aknysh left a comment

Choose a reason for hiding this comment

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

please see comments

@Cerebrovinny
Copy link
Collaborator Author

@aknysh following test cases

When vendor.yaml exists and using -c flag:
Correctly checks if the component exists in vendor.yaml
Error if component not found in vendor.yaml

When no vendor.yaml but component.yaml exists:
Proceeds without vendor configurations
Pulls from component.yaml configuration
Shows a Warning about vendor.yaml not existing

When component specified but no vendor.yaml or component.yaml:
System correct shows vendor.yaml doesn't exist
Properly errors that component.yaml doesn't exist in the component folder

When no component specified:
a. With vendor.yaml:
System attempts to process vendor.yaml
Shows appropriate error for invalid configuration

b. Without vendor.yaml:
System shows vendor.yaml doesn't exist
Provides an error message about needing to specify --component flag

CleanShot 2024-11-28 at 18 22 36
CleanShot 2024-11-28 at 18 29 14
CleanShot 2024-11-28 at 18 30 06
CleanShot 2024-11-28 at 18 30 25
CleanShot 2024-11-28 at 18 31 38

I also added tests integrating these criteria's

This is before the fix so the tests fail

Screenshot 2024-11-28 at 22 33 43

This is after the fix all tests are passing

Screenshot 2024-11-28 at 22 37 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: 1

🧹 Outside diff range and nitpick comments (2)
pkg/vender/vendor_config_test.go (2)

14-27: Consider test setup improvements

A few suggestions to enhance the test setup:

  1. Consider using a less verbose log level for tests unless debugging
  2. Extract magic strings like "components/terraform" into constants for better maintainability
+const (
+    defaultComponentPath = "components/terraform"
+    defaultLogLevel     = "Info"  // or "Error" for less verbose output
+)

 cliConfig := schema.CliConfiguration{
     BasePath: testDir,
     Components: schema.Components{
         Terraform: schema.Terraform{
-            BasePath: "components/terraform",
+            BasePath: defaultComponentPath,
         },
     },
 }
-cliConfig.Logs.Level = "Trace"
+cliConfig.Logs.Level = defaultLogLevel

28-32: Extract directory permissions to a constant

Consider extracting the directory permissions to a named constant for better maintainability and clarity.

+const defaultDirPerms = 0755

 componentPath := path.Join(testDir, "components", "terraform", "myapp")
-err := os.MkdirAll(componentPath, 0755)
+err := os.MkdirAll(componentPath, defaultDirPerms)
📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Reviewing files that changed from the base of the PR and between 0f9cead and aa87519.

📒 Files selected for processing (1)
  • pkg/vender/vendor_config_test.go (1 hunks)
🔇 Additional comments (1)
pkg/vender/vendor_config_test.go (1)

33-142: 🛠️ Refactor suggestion

Consider enhancing test coverage and structure

The test cases are comprehensive but could be improved:

  1. Consider using table-driven tests for YAML content variations
  2. Extract common setup/cleanup into helper functions
  3. Add edge cases mentioned in PR comments by osterman regarding component manifest handling

Here's a suggested refactor for the YAML content:

+var testCases = []struct {
+    name       string
+    vendorYaml string
+    wantErr    bool
+}{
+    {
+        name: "valid vendor config",
+        vendorYaml: `apiVersion: atmos/v1
+kind: AtmosVendorConfig
+metadata:
+  name: test-vendor-config
+spec:
+  sources:
+    - component: myapp
+      source: github.com/cloudposse/terraform-null-label.git//exports?ref={{.Version}}
+      version: 0.25.0`,
+        wantErr: false,
+    },
+    // Add more test cases
+}

Also, consider adding these helper functions:

func setupVendorYaml(t *testing.T, dir, content string) string {
    path := path.Join(dir, "vendor.yaml")
    err := os.WriteFile(path, []byte(content), 0644)
    assert.Nil(t, err)
    return path
}

func cleanup(t *testing.T, paths ...string) {
    for _, p := range paths {
        err := os.Remove(p)
        assert.Nil(t, err)
    }
}

Let's verify the test coverage aligns with PR objectives:

Comment on lines +1 to +12
package vender

import (
"os"
"path"
"testing"

"github.com/stretchr/testify/assert"

e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/pkg/schema"
)
Copy link
Contributor

@coderabbitai coderabbitai bot Nov 28, 2024

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix package name typo: 'vender' should be 'vendor'

The package name contains a typo that should be corrected for consistency.

-package vender
+package vendor
📝 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
package vender
import (
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/pkg/schema"
)
package vendor
import (
"os"
"path"
"testing"
"github.com/stretchr/testify/assert"
e "github.com/cloudposse/atmos/internal/exec"
"github.com/cloudposse/atmos/pkg/schema"
)

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

I also noticed that but I think its made by purpose right @aknysh ?

Copy link
Contributor

Choose a reason for hiding this comment

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

Seems like the humans are having a chat. I'll hop back into my burrow for now. If you need me again, just tag @coderabbitai in a new comment, and I'll come hopping out!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
patch A minor, backward compatible change
Projects
None yet
Development

Successfully merging this pull request may close these issues.

Running atmos vendor pull using component.yaml failing
4 participants