8000 Fix Version Check & Add Tests by samtholiya · Pull Request #1120 · cloudposse/atmos · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Fix Version Check & Add Tests #1120

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

Conversation

samtholiya
Copy link
Collaborator
@samtholiya samtholiya commented Mar 6, 2025

what

  • We have to make version cmd more testable
  • Understand the reason behind release tags not being able to be downloaded and compared when using --check flag

why

  • We want to make sure that the customer knows the latest version of the atmos.
  • We should test the feature thoroughly to avoid regressions.

references

Summary by CodeRabbit

  • New Features

    • The Atmos version command now presents a streamlined display of your current version, operating system, and architecture, along with clear update notifications for new releases.
    • Introduced a mock implementation for unit testing of version execution operations.
  • Bug Fixes

    • Improved error handling for fetching the latest GitHub release.
  • Chores

    • Added a new dependency for mocking in unit tests.

@github-actions github-actions bot added the size/m label Mar 6, 2025
@samtholiya samtholiya force-pushed the feature/dev-3081-fix-atmos-version-command-not-able-to-check-for-latest branch from ff56dd2 to 488afbd Compare March 6, 2025 23:46
@samtholiya samtholiya marked this pull request as ready for review March 6, 2025 23:53
@samtholiya samtholiya requested a review from a team as a code owner March 6, 2025 23:53
Copy link
Contributor
coderabbitai bot commented Mar 6, 2025
📝 Walkthrough

Walkthrough

This pull request refactors the version command in Atmos by delegating its execution logic to a new executor in the internal/exec package. The refactoring in cmd/version.go replaces direct output and update-check logic with a call to exec.NewVersionExec().Execute(). Additionally, a new executor structure, its tests, and mocks have been added, along with a dependency update in go.mod for mocking support. The logic to fetch the latest GitHub release has been simplified within the GitHub utility.

Changes

File(s) Change Summary
cmd/version.go Refactored the Run function to instantiate and delegate to exec.NewVersionExec() instead of handling output and update checks directly
go.mod Added a new dependency: github.com/golang/mock v1.6.0
internal/exec/{version.go, version_test.go, mock_version_test.go} Introduced a new executor (versionExec) with methods Execute and checkRelease; added accompanying unit tests and generated mocks for the interface
pkg/utils/github_utils.go Simplified GetLatestGitHubRepoRelease to directly call GetLatestRelease with enhanced logging and error handling

Sequence Diagram(s)

sequenceDiagram
    participant User as User/CLI
    participant Cmd as cmd/version.go
    participant Exec as versionExec (internal/exec/version.go)
    participant GitHub as GitHub API (pkg/utils/github_utils.go)

    User->>Cmd: Invoke version command
    Cmd->>Exec: Execute(checkFlag)
    Exec->>Exec: Print logo & version info
    alt checkFlag is true
      Exec->>Exec: checkRelease()
      Exec->>GitHub: GetLatestRelease(owner, repo)
      GitHub-->>Exec: Return latest release tag
      Exec->>Exec: Compare versions and log update message
    end
Loading

Possibly related PRs

  • Add custom help message and upgrade notification #809: The changes in the main PR, which refactor the version command execution logic, are related to the retrieved PR as both involve enhancements to version checking and user notifications regarding updates, specifically through the VersionExecutor interface and its methods.
  • Update Atmos YAML functions #1038: The changes in the main PR, particularly the refactoring of the Run function in cmd/version.go to utilize the new exec.NewVersionExec() structure, are related to modifications in the retrieved PR that enhance the handling of environment variables and improve logging and spinner functionality.
  • fix check the version if config broken #735: The changes in the main PR, which refactor the Run function to delegate version execution to a new structure, are related to modifications in the retrieved PR that enhance error handling for the version command.

Suggested labels

minor

Suggested reviewers

  • mcalhoun
  • aknysh
  • osterman

📜 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 c8961bb and 30ce5f3.

📒 Files selected for processing (1)
  • internal/exec/version.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (2)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Summary
🔇 Additional comments (3)
internal/exec/version.go (3)

15-20: Great use of function pointers in the struct.
This design nicely aids testability by allowing easy mocking of external dependencies.


22-29: Constructor pattern looks clean.
Returning a fully initialized struct with function pointers ensures predictable behavior across multiple callers.


60-61: Past feedback from osterman is implemented.
We see you adopted the suggestion to log an info-level message when already on the latest version.

✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 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 tas 8000 ks 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 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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (1)
internal/exec/version.go (1)

31-48: Consider more graceful error handling in Execute

The log.Fatal call will terminate the program if printStyledText fails, which seems too extreme for a UI rendering error.

- if err != nil {
-   //nolint:revive
-   log.Fatal(err)
- }
+ if err != nil {
+   log.Error("Failed to print styled text", "err", err)
+ }
🛑 Comments failed to post (1)
internal/exec/version.go (1)

50-64: 🛠️ Refactor suggestion

Improve error handling for release check failures

The current code continues execution after logging an error at debug level, which could lead to misleading output if the GitHub API call fails (empty latest release tag).

if err != nil || latestReleaseTag == "" {
    log.Debug("Did not get release tag", "err", err, "latestReleaseTag", latestReleaseTag)
+   log.Warn("Unable to check for the latest version of Atmos")
+   return
}
📝 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.

func (v versionExec) checkRelease() {
	// Check for the latest Atmos release on GitHub
	latestReleaseTag, err := v.getLatestGitHubRepoRelease("cloudposse", "atmos")
	if err != nil || latestReleaseTag == "" {
		log.Debug("Did not get release tag", "err", err, "latestReleaseTag", latestReleaseTag)
		log.Warn("Unable to check for the latest version of Atmos")
		return
	}
	latestRelease := strings.TrimPrefix(latestReleaseTag, "v")
	currentRelease := strings.TrimPrefix(version.Version, "v")

	if latestRelease == currentRelease {
		log.Warn("You are running the latest version of Atmos", "version", latestRelease)
	} else {
		v.printMessageToUpgradeToAtmosLatestRelease(latestRelease)
	}
}

@samtholiya samtholiya force-pushed the feature/dev-3081-fix-atmos-version-command-not-able-to-check-for-latest branch from 488afbd to c8961bb Compare March 7, 2025 00:11
coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 7, 2025
Copy link
codecov bot commented Mar 7, 2025

Codecov Report

Attention: Patch coverage is 57.44681% with 20 lines in your changes missing coverage. Please review.

Project coverage is 17.43%. Comparing base (5bc5b69) to head (30ce5f3).
Report is 3 commits behind head on main.

Files with missing lines Patch % Lines
internal/exec/version.go 71.05% 10 Missing and 1 partial ⚠️
pkg/utils/github_utils.go 0.00% 8 Missing ⚠️
cmd/version.go 0.00% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1120      +/-   ##
==========================================
+ Coverage   17.29%   17.43%   +0.13%     
==========================================
  Files         169      170       +1     
  Lines       18747    18754       +7     
==========================================
+ Hits         3242     3269      +27     
+ Misses      14908    14887      -21     
- Partials      597      598       +1     
Flag Coverage Δ
unittests 17.43% <57.44%> (+0.13%) ⬆️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🧹 Nitpick comments (2)
internal/exec/version.go (2)

40-41: Inline the atmosIcon variable for brevity.
Since it's used only once, consider referencing the icon inline, reducing unnecessary variables.

-atmosIcon := "\U0001F47D"
-v.printMessage(fmt.Sprintf("%s Atmos %s on %s/%s", atmosIcon, version.Version, runtime.GOOS, runtime.GOARCH))
+v.printMessage(fmt.Sprintf("\U0001F47D Atmos %s on %s/%s", version.Version, runtime.GOOS, runtime.GOARCH))

50-56: Show a brief user message on release check failure.
Currently, the user receives no feedback if there’s an error fetching the release. A short info-level message can enhance user awareness.

	if err != nil || latestReleaseTag == "" {
		log.Debug("Did not get release tag", "err", err, "latestReleaseTag", latestReleaseTag)
+		v.printMessage("Could not determine the latest available Atmos version.")
		return
	}
🛑 Comments failed to post (1)
internal/exec/version.go (1)

31-38: 🛠️ Refactor suggestion

Consider avoiding log.Fatal for better control flow.
Instead of exiting the program outright, gracefully return an error or propagate it to the caller. This helps in scenarios where the calling context prefers handling errors differently.

- log.Fatal(err)
+ // Optionally return an error or handle it at a higher level
+ log.Error("Failed to print styled text", "error", err)
+ // return fmt.Errorf("failed to print styled text: %w", err)
📝 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.

func (v versionExec) Execute(checkFlag bool) {
	// Print a styled Atmos logo to the terminal
	v.printMessage("")
	err := v.printStyledText("ATMOS")
	if err != nil {
		//nolint:revive
		// Optionally return an error or handle it at a higher level
		log.Error("Failed to print styled text", "error", err)
		// return fmt.Errorf("failed to print styled text: %w", err)
	}
}

@osterman
Copy link
Member
osterman commented Mar 7, 2025

What’s not clear to me from the PR description is what the actual fix was, in other words why was it failing and why does it work now?

@osterman osterman changed the title update version command Fix Version Check & Add Tests Mar 7, 2025
@osterman osterman merged commit 6902770 into main Mar 7, 2025
49 checks passed
@osterman osterman deleted the feature/dev-3081-fix-atmos-version-command-not-able-to-check-for-latest branch March 7, 2025 15:11
Copy link
github-actions bot commented Mar 7, 2025

These changes were released in v1.165.2.

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.

3 participants
0