Skip to content

Fork go-homedir into Atmos#1139

Merged
osterman merged 7 commits intomainfrom
fork-go-homedir
Mar 12, 2025
Merged

Fork go-homedir into Atmos#1139
osterman merged 7 commits intomainfrom
fork-go-homedir

Conversation

@haitham911
Copy link
Collaborator

@haitham911 haitham911 commented Mar 12, 2025

what

  • Forked mitchellh/go-homedir into the Atmos organization.
  • Added a LICENSE file to ensure compliance with the original repository's licensing terms.
  • Created an ATTRIBUTIONS.md file to credit the original author.
  • Updated references in Atmos to use the new forked repository instead of the original

why

references

Summary by CodeRabbit

  • New Features

    • Enhanced home directory functionality now reliably retrieves and expands user paths, ensuring seamless cross-platform support.
    • Updated dependency management improves overall module handling.
  • Documentation

    • Added comprehensive usage guidance, attributions, and licensing details for the new home directory library.

@haitham911 haitham911 requested review from a team as code owners March 12, 2025 20:09
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 12, 2025

📝 Walkthrough

Walkthrough

This pull request updates the dependency management and import paths for the go-homedir package. The direct dependency in the go.mod file was changed to an indirect dependency, and the import path in pkg/config/config.go was updated. Additionally, a new fork of the go-homedir library has been introduced under pkg/config/go-homedir with supporting documentation, licensing, implementation (home directory retrieval functions), and comprehensive tests.

Changes

File(s) Change Summary
go.mod Moved dependency github.com/mitchellh/go-homedir v1.1.0 from direct to indirect requirements.
pkg/config/config.go Updated import path for go-homedir from github.com/mitchellh/go-homedir to github.com/cloudposse/atmos/pkg/config/go-homedir.
pkg/config/go-homedir/ATTRIBUTIONS.md, pkg/config/go-homedir/LICENSE, pkg/config/go-homedir/README.md Added new files providing attribution, licensing (MIT License), and usage documentation for the forked go-homedir library.
pkg/config/go-homedir/homedir.go, pkg/config/go-homedir/homedir_test.go Introduced a new library with functions (Dir, Expand, etc.) for cross-platform home directory management along with tests and benchmarks for the new functionality.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Homedir as homedir package
    participant Env as OS/Environment Helpers

    Client->>Homedir: Call Dir()
    Homedir->>Homedir: Check cache status
    alt Cached value exists
        Homedir-->>Client: Return cached home directory
    else
        Homedir->>Env: Determine OS (Unix/Windows)
        alt Unix
            Env-->>Homedir: Return directory via Unix helper
        else Windows
            Env-->>Homedir: Return directory via Windows helper
        end
        Homedir->>Homedir: Cache the result
        Homedir-->>Client: Return determined home directory
    end
Loading
sequenceDiagram
    participant Client
    participant Homedir as homedir package

    Client->>Homedir: Call Expand(path)
    alt Path begins with '~'
        Homedir->>Homedir: Invoke Dir() to fetch home directory
        Homedir-->>Client: Return expanded path with home directory
    else
        Homedir-->>Client: Return path unchanged
    end
Loading

Suggested labels

minor, no-release

Warning

There were issues while running some tools. Please review the errors and either fix the tool’s configuration or disable the tool if it’s a critical failure.

🔧 golangci-lint (1.62.2)

Error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)
Failed executing command with error: can't load config: the Go language version (go1.23) used to build golangci-lint is lower than the targeted Go version (1.24.0)

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 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 1a08453 and e1d774d.

📒 Files selected for processing (1)
  • pkg/config/go-homedir/homedir.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
pkg/config/go-homedir/homedir.go (1)
Learnt from: osterman
PR: cloudposse/atmos#1139
File: pkg/config/go-homedir/homedir.go:183-196
Timestamp: 2025-03-12T21:38:42.699Z
Learning: The code in pkg/config/go-homedir is a direct fork of the mitchellh/go-homedir package and was intentionally imported as-is without modifications to maintain consistency with the original source. Security concerns or other improvements may be addressed in future PRs.
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: Analyze (go)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (4)
pkg/config/go-homedir/homedir.go (4)

22-24: Reaffirming static error usage complaint previously noted.
These dynamic errors declared with errors.New(...) were flagged in prior reviews for not using wrapped static errors. However, since this code is a direct fork meant to preserve the original form, the existing approach is currently acceptable.


100-119: Note on cyclomatic complexity.
Prior reviews flagged dirUnix() for exceeding recommended complexity levels. For now, preserving the original logic makes sense to maintain consistency. Consider refactoring in a future update if complexity becomes a hindrance.


166-166: Known potential security issue with subprocess execution.
These lines rely on system executables (exec.Command(...)) without strictly validating environment or command parameters. A previous review cited G204 warnings. Retaining as-is is justified at this time; consider hardening if a future revision expands this code’s scope.

Also applies to: 190-190


20-25: Commendation on concurrency control.
You handle shared state safely with a sync.RWMutex, preventing data races around homedirCache.

✨ 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 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 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

🧹 Nitpick comments (1)
pkg/config/go-homedir/homedir.go (1)

91-148: Comprehensive Unix home directory detection with fallbacks.

The dirUnix() function implements a thorough approach with multiple fallback mechanisms:

  1. HOME environment variable
  2. OS-specific commands (dscl for macOS, getent for other Unix systems)
  3. Shell command fallback

Consider breaking this function into smaller helper functions to improve readability and maintainability.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between acf4e0a and 5d4bfca.

📒 Files selected for processing (7)
  • go.mod (1 hunks)
  • pkg/config/config.go (1 hunks)
  • pkg/config/go-homedir/ATTRIBUTIONS.md (1 hunks)
  • pkg/config/go-homedir/LICENSE (1 hunks)
  • pkg/config/go-homedir/README.md (1 hunks)
  • pkg/config/go-homedir/homedir.go (1 hunks)
  • pkg/config/go-homedir/homedir_test.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (21)
pkg/config/go-homedir/ATTRIBUTIONS.md (3)

1-2: Clear and Concise Header
The header sets the tone perfectly with a clear title for attributions.


3-3: Accurate Attribution
The attribution correctly references the original repository and author. It’s clear and informative.


5-6: Explicit License Reference
The file clearly notes the MIT License and provides an accessible link to the LICENSE file. This meets the compliance requirements.

pkg/config/config.go (1)

11-11: Import path updated correctly.

The import path has been updated to use the forked version of go-homedir within the Atmos organization. This matches the PR objective of forking the package to ensure maintainability and control.

pkg/config/go-homedir/README.md (1)

1-14: Clear documentation for the forked package.

This README properly explains the purpose of the go-homedir package and the rationale for forking it. The documentation clearly states the two main functions (Dir() and Expand()) and explains why this approach is better than using the built-in os/user package for cross-compilation scenarios.

go.mod (1)

223-223: Correctly marked as indirect dependency.

The original go-homedir package is now properly marked as an indirect dependency since the project is using its own forked version. This ensures clarity in dependency management and prevents direct usage of the external package.

pkg/config/go-homedir/homedir_test.go (3)

1-36: Well-structured test setup and benchmark.

The test file starts with a good helper function for environment variable manipulation and includes proper benchmarking of the Dir() function. The benchmark includes a warm-up phase which is a good practice for accurate testing.


37-63: Thorough testing of the Dir() function.

The test validates the Dir() function against the actual user's home directory and tests behavior with and without caching. This ensures the function works correctly in different scenarios.


65-129: Comprehensive test cases for Expand() function.

The test includes multiple scenarios for the Expand() function, including absolute paths, paths with ~, empty strings, and error conditions. It also tests the function's behavior when the HOME environment variable is set to a custom path.

pkg/config/go-homedir/homedir.go (6)

1-13: Clean package declaration and imports.

The package declaration and imports are clear and appropriate for the functionality provided.


15-22: Effective caching mechanism with thread safety.

The global variables establish a simple but effective caching system with proper synchronization through RWMutex. The DisableCache option provides flexibility for testing scenarios.


24-55: Well-implemented home directory detection with OS-specific handling.

The Dir() function properly implements:

  • Thread-safe caching with read locks for performance
  • OS detection for platform-specific implementations
  • Clear error handling

The implementation follows best practices for cross-platform compatibility.


57-79: Robust path expansion implementation.

The Expand() function correctly handles:

  • Empty paths
  • Non-tilde paths
  • Home directory expansion
  • Error propagation

Good attention to edge cases while maintaining clean code.


81-89: Clear cache reset functionality.

The Reset() function provides a simple way to clear the cache with proper documentation of its purpose and use cases.


150-169: Appropriate Windows home directory detection.

The dirWindows() function properly checks multiple environment variables in the right order:

  1. HOME
  2. USERPROFILE
  3. HOMEDRIVE + HOMEPATH

The implementation is concise and handles error cases appropriately.

pkg/config/go-homedir/LICENSE (6)

1-2: License Header Looks Good

The file begins by clearly stating the MIT License with its proper identifier. Everything here is clearly laid out.


3-4: Accurate Copyright Information

The copyright information properly credits Mitchell Hashimoto as per the original repository. This is correct for maintaining proper attribution.


5-11: Permission Section is Correct

The permissions granted under the MIT License are detailed clearly and completely, allowing free use and distribution. No issues here.


12-14: Attribution Clause is Present

The clause requiring inclusion of the copyright and permission notice in all copies is present and follows the standard wording.


15-22: Standard Warranty Disclaimer

The warranty disclaimer is implemented as expected, reinforcing the "AS IS" nature of the license without offering any warranties.


1-22: Overall, the LICENSE file is spot on!

The entire file adheres to the standard MIT License text and ensures compliance with licensing requirements, fitting perfectly into the new fork requirements in Atmos.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 12, 2025
@codecov
Copy link

codecov bot commented Mar 12, 2025

Codecov Report

Attention: Patch coverage is 42.50000% with 69 lines in your changes missing coverage. Please review.

Project coverage is 19.49%. Comparing base (acf4e0a) to head (e1d774d).
Report is 1 commits behind head on main.

Files with missing lines Patch % Lines
pkg/config/go-homedir/homedir.go 42.50% 61 Missing and 8 partials ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main    #1139      +/-   ##
==========================================
+ Coverage   19.34%   19.49%   +0.14%     
==========================================
  Files         170      171       +1     
  Lines       18789    18909     +120     
==========================================
+ Hits         3635     3686      +51     
- Misses      14437    14498      +61     
- Partials      717      725       +8     
Flag Coverage Δ
unittests 19.49% <42.50%> (+0.14%) ⬆️

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.

Actionable comments posted: 0

🧹 Nitpick comments (1)
pkg/config/go-homedir/homedir.go (1)

72-73: Support ~someuser expansion
If you need to expand paths like ~username/dir, consider enhancing this function to handle those cases.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5d4bfca and 7e460fb.

📒 Files selected for processing (2)
  • pkg/config/go-homedir/homedir.go (1 hunks)
  • pkg/config/go-homedir/homedir_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • pkg/config/go-homedir/homedir_test.go
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Build (macos-latest, macos)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Analyze (go)
  • GitHub Check: Summary
🔇 Additional comments (6)
pkg/config/go-homedir/homedir.go (6)

19-25: Use wrapped static errors
This is a repeat of a previously flagged comment: instead of plain errors.New(...), consider using wrapped static errors if you need to attach context or wrap underlying errors.


31-42: Good concurrency approach
Locking and caching logic look correct. Using separate read and write locks is straightforward and efficient.


94-151: Function dirUnix flagged for high cyclomatic complexity
This has been noted in previous reviews. Consider splitting up OS-specific logic or extracting helper methods.


109-118: Nested blocks add to complexity
Simplify conditionals or extract smaller functions to reduce block complexity inside this if branch.


129-131: Replace magic numbers with named constants
Using numeric literals 7 and 5 here hurts readability. This was flagged previously.


137-143:

Details

✅ Verification successful

Confirm shell command safety
No user input is passed in, but some scanners may flag subprocess calls as potential security risks. Please verify.


🏁 Script executed:

#!/bin/bash
# Verify no user-supplied args are passed to Expand() or Dir() that might lead to injection.
rg -A 3 "Expand\(|Dir\("

Length of output: 20988


Shell Command Safety Confirmed
The verification output shows no sign of user-supplied input being passed to either Expand() or Dir(). The shell command "sh", "-c", "cd && pwd" is hardcoded and doesn’t incorporate external input, mitigating injection concerns.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 12, 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: 1

♻️ Duplicate comments (2)
pkg/config/go-homedir/homedir.go (2)

95-114: ⚠️ Potential issue

Function has high cyclomatic complexity.

The dirUnix function has a cyclomatic complexity of 12, which exceeds the maximum allowed complexity of 10 as flagged in previous analysis.

Consider refactoring this function to reduce complexity, such as extracting the OS-specific checks into separate helper functions.


102-110: ⚠️ Potential issue

Complex nested conditional blocks.

This section has complex nested blocks with a complexity of 13, making it harder to read and maintain.

Consider simplifying this logic by extracting the OS-specific parts into separate functions with clearer control flow.

🧹 Nitpick comments (2)
pkg/config/go-homedir/homedir.go (2)

159-181: getUnixHomeDir implementation has hardcoded indices.

The function uses magic numbers (5, 7) without named constants for the passwd file format fields.

Consider defining constants for these indices to improve code readability:

+const (
+    passwdFieldsCount = 7
+    passwdHomeIndex = 5
+)

 func getUnixHomeDir() (string, error) {
     // ...
-    passwdParts := strings.SplitN(passwd, ":", 7)
+    passwdParts := strings.SplitN(passwd, ":", passwdFieldsCount)
-    if len(passwdParts) > 5 {
-        return passwdParts[5], nil
+    if len(passwdParts) > passwdHomeIndex {
+        return passwdParts[passwdHomeIndex], nil
     }
     // ...
 }

1-196: Overall, this is a solid implementation of a home directory finder.

The code successfully forks the go-homedir package with some improvements like static error definitions. There are a few complexity and security concerns that should be addressed, but the core functionality seems solid and well-tested.

Given this is a fork of an existing package, consider maintaining a changelog of the differences between your version and the original to make future updates easier.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7e460fb and 1a08453.

📒 Files selected for processing (2)
  • .golangci.yml (1 hunks)
  • pkg/config/go-homedir/homedir.go (1 hunks)
⏰ Context from checks skipped due to timeout of 90000ms (6)
  • GitHub Check: Analyze (javascript-typescript)
  • GitHub Check: Build (windows-latest, windows)
  • GitHub Check: Build (ubuntu-latest, linux)
  • GitHub Check: Analyze (go)
  • GitHub Check: Lint (golangci)
  • GitHub Check: Summary
🔇 Additional comments (9)
.golangci.yml (1)

111-111: Linter configuration updated for integer literals.

The change expands the allowed integer literals from "0,1,2,3,4" to "0,1,2,3,4,5,6,7". This appears to accommodate the newly forked go-homedir implementation which uses these values.

pkg/config/go-homedir/homedir.go (8)

1-13: The package definition and imports look good.

The imported packages are appropriate for the functionality being implemented. The code properly imports necessary standard libraries for file operations, error handling, and cross-platform support.


15-25: Well-defined error variables.

Good job defining static error variables instead of creating dynamic errors. This is consistent with Go best practices and addresses previous static analysis warnings.


27-58: The Dir function implementation is solid.

The function properly implements caching with thread safety using read/write locks. The platform detection for Windows vs Unix-like systems follows standard Go practices.


60-82: Expand function looks correct.

The implementation properly handles path expansion for paths starting with tilde (~). The early returns for edge cases are a good practice.


84-93: Reset function implementation is appropriate.

The function correctly implements cache clearing with proper locking.


116-122: getHomeFromEnv function is clean and focused.

This helper function has a single responsibility and handles the Plan 9 edge case appropriately.


124-143: dirWindows function looks good.

The function has a clear priority order for checking different environment variables and properly handles error cases.


145-157:

Details

✅ Verification successful

Potential security issue in command execution.

The command execution in getDarwinHomeDir uses shell commands with no validation of inputs.

While this is part of the original implementation, it's worth noting that executing shell commands can introduce security vulnerabilities. Consider using safer alternatives if possible.


🏁 Script executed:

#!/bin/bash
# Check if the command contains any user-controlled input
grep -r "getDarwinHomeDir" --include="*.go" .

Length of output: 222


Clarification on Shell Command Execution in getDarwinHomeDir

After running the grep check, it's clear that the function and its usage are confined to the pkg/config/go-homedir/homedir.go file. Since the shell command uses $(whoami), which is determined by the system, there's no evidence of user-supplied input being incorporated into the command. While caution is always encouraged with shell executions, in this context the risks are minimal.

For future maintainability and clarity, consider adding a comment in the code that explains the assumptions behind using the shell command here and exploring dedicated OS APIs if deemed more secure.

coderabbitai[bot]
coderabbitai bot previously approved these changes Mar 12, 2025
@osterman osterman added the patch A minor, backward compatible change label Mar 12, 2025
@osterman osterman merged commit 062d337 into main Mar 12, 2025
50 checks passed
@osterman osterman deleted the fork-go-homedir branch March 12, 2025 22:26
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.

2 participants