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

feat: support XDG standards on new installs #230

Merged
merged 4 commits into from
Oct 12, 2024

Conversation

hay-kot
Copy link
Owner

@hay-kot hay-kot commented Oct 12, 2024

Summary by CodeRabbit

  • New Features

    • Introduced a new package for managing application-specific directories, supporting both legacy and modern directory specifications.
    • Added a migration command to transition legacy paths to the new structure.
  • Bug Fixes

    • Improved error handling and logging for directory management functions.

Copy link

coderabbitai bot commented Oct 12, 2024

Walkthrough

The changes introduce a new package, appdirs, which provides cross-platform access to application-specific directories for configuration and cache management. This package includes functions for handling legacy paths and transitioning to the XDG Base Directory Specification. Additionally, the main.go file is updated to utilize the appdirs package, replacing the existing HomeDir function and adding a migrate command to facilitate the migration of legacy paths.

Changes

File Change Summary
internal/appdirs/appdirs.go Introduced a new package with functions for managing application directories, including legacy and XDG paths. Functions added: RCFilepath, RCFilepathLegacy, RCFilepathXDG, CacheDir, CacheDirLegacy, CacheDirXDG, homeDir, MigrateLegacyPaths, migrateRCFile, migrateCacheDir.
main.go Integrated the appdirs package, removed HomeDir, and added migrate command for legacy path migration using appdirs.MigrateLegacyPaths().

Poem

In the burrow where paths intertwine,
A new way to find is simply divine.
With appdirs to guide, both old and new,
Our caches and configs, all fresh like the dew.
Hop along, dear friends, to the XDG way,
Migration is here, let’s frolic and play! 🐇✨


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:

‼️ IMPORTANT
Auto-reply has been disabled for this repository in the CodeRabbit settings. The CodeRabbit bot will not respond to your replies unless it is explicitly tagged.

  • 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 to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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

@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: 5

🧹 Outside diff range and nitpick comments (2)
main.go (1)

381-392: LGTM: Added migrate command for legacy path migration.

The addition of the migrate command under the dev subcommands is a good approach for handling the transition to XDG-compliant paths. This aligns well with the PR objective and provides a way for users or developers to migrate existing installations.

However, consider the following suggestion:

The successful migration message is logged at the Info level, which might not be visible with the default warn log level. Consider either:

  1. Logging this message at a higher level (e.g., Warn) to ensure visibility.
  2. Adding a console output to inform the user of successful migration.

Example:

- log.Info().Msg("migrated legacy paths")
+ log.Warn().Msg("Successfully migrated legacy paths")
+ fmt.Println("Legacy paths have been successfully migrated to XDG-compliant locations.")
internal/appdirs/appdirs.go (1)

148-152: Ensure parent directories exist in migrateCacheDir

In migrateCacheDir, there is no check to create the parent directories of the XDG path before renaming, which could cause the os.Rename operation to fail if the parent directories do not exist.

Add a call to os.MkdirAll to ensure the parent directories exist:

 func migrateCacheDir(legacyDir string) error {
 	xdgDir := CacheDirXDG()
+	// Ensure the destination parent directory exists
+	err := os.MkdirAll(filepath.Dir(xdgDir), os.ModePerm)
+	if err != nil {
+		return err
+	}

-	err = os.Rename(legacyDir, xdgDir)
+	err = os.Rename(legacyDir, xdgDir)
 	if err != nil {
 		log.Error().Err(err).Msg("failed to migrate legacy cache directory")
 		return err
 	}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between cf05d80 and c868393.

📒 Files selected for processing (2)
  • internal/appdirs/appdirs.go (1 hunks)
  • main.go (4 hunks)
🧰 Additional context used
🔇 Additional comments (4)
main.go (4)

14-14: LGTM: Import of appdirs package.

The addition of the appdirs package import is correct and necessary for the subsequent usage of its functions in the code.


56-56: LGTM: Updated default scaffoldrc path to use XDG standards.

The change to use appdirs.RCFilepath() as the default value for the scaffoldrc flag aligns well with the PR objective of supporting XDG standards on new installs. This ensures that the configuration file is stored in a standardized location across different platforms.


68-68: LGTM: Updated default cache directory to use XDG standards.

The change to use appdirs.CacheDir() as the default value for the cache flag is in line with the PR objective of supporting XDG standards on new installs. This ensures that the cache directory is stored in a standardized location across different platforms, improving consistency and adhering to best practices.


Line range hint 1-418: LGTM: Successfully implemented XDG standards support.

The changes in this file consistently implement support for XDG standards, which aligns perfectly with the PR objectives. Key points:

  1. The appdirs package is properly imported and utilized.
  2. Default paths for configuration and cache now use XDG-compliant locations.
  3. A migrate command has been added to facilitate the transition for existing installations.

These changes improve the application's adherence to cross-platform standards and should enhance user experience across different environments. The implementation is clean and well-integrated into the existing codebase.

Comment on lines +45 to +57
func RCFilepathXDG() string {
configDir := os.Getenv("XDG_CONFIG_HOME")
if configDir == "" {
home, err := os.UserHomeDir()
if err != nil {
log.Fatal().Err(err).Msg("failed to get home directory")
}

configDir = filepath.Join(home, ".config")
}

return filepath.Join(configDir, "scaffold", RCFilename)
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Avoid using log.Fatal() in library functions

The functions RCFilepathXDG, CacheDirXDG, and homeDir call log.Fatal() when encountering errors. Using log.Fatal() causes the application to exit, which might not be appropriate in a library package, as it prevents the caller from handling errors gracefully.

Consider returning errors instead of exiting, allowing the calling code to decide how to handle them. For example, modify RCFilepathXDG:

-func RCFilepathXDG() string {
+func RCFilepathXDG() (string, error) {
 	configDir := os.Getenv("XDG_CONFIG_HOME")
 	if configDir == "" {
 		home, err := os.UserHomeDir()
 		if err != nil {
-			log.Fatal().Err(err).Msg("failed to get home directory")
+			return "", err
 		}

 		configDir = filepath.Join(home, ".config")
 	}

-	return filepath.Join(configDir, "scaffold", RCFilename)
+	return filepath.Join(configDir, "scaffold", RCFilename), nil
 }

You would need to adjust the calling functions to handle the returned errors appropriately.

Also applies to: 84-95, 97-104

Comment on lines +135 to +139
err = os.Rename(legacyFilepath, xdgFilepath)
if err != nil {
log.Error().Err(err).Msg("failed to migrate legacy configuration file")
return err
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Check for existing destination before renaming

In migrateRCFile and migrateCacheDir, the code attempts to rename the legacy file or directory to the new XDG location without checking if the destination already exists. This can result in an error if the destination file or directory is already present.

Consider checking if the destination exists before attempting to rename:

 func migrateRCFile(legacyFilepath string) error {
 	xdgFilepath := RCFilepathXDG()
+	// Check if the destination file already exists
+	_, err := os.Stat(xdgFilepath)
+	if err == nil {
+		log.Info().Str("file", xdgFilepath).Msg("configuration file already migrated")
+		return nil
+	} else if !os.IsNotExist(err) {
+		return err
+	}

 	err = os.MkdirAll(filepath.Dir(xdgFilepath), os.ModePerm)
 	if err != nil {
 		return err
 	}

 	err = os.Rename(legacyFilepath, xdgFilepath)

Apply similar checks in migrateCacheDir:

 func migrateCacheDir(legacyDir string) error {
 	xdgDir := CacheDirXDG()
+	// Check if the destination directory already exists
+	_, err := os.Stat(xdgDir)
+	if err == nil {
+		log.Info().Str("directory", xdgDir).Msg("cache directory already migrated")
+		return nil
+	} else if !os.IsNotExist(err) {
+		return err
+	}

+	// Ensure the parent directory exists
+	err = os.MkdirAll(filepath.Dir(xdgDir), os.ModePerm)
+	if err != nil {
+		return err
+	}

 	err = os.Rename(legacyDir, xdgDir)

This ensures that existing files or directories are handled gracefully.

Also applies to: 148-152

Comment on lines 117 to 123
legacyFilepath, exists = CacheDirLegacy()
if exists {
err := migrateCacheDir(legacyFilepath)
if err != nil {
return err
}
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Use consistent variable naming in MigrateLegacyPaths

In the MigrateLegacyPaths function, the variable legacyFilepath is reused when handling the cache directory, which can be confusing since it's actually a directory path.

Consider renaming the variable to legacyDir when working with directories:

-	legacyFilepath, exists = CacheDirLegacy()
+	legacyDir, exists := CacheDirLegacy()
 	if exists {
-		err := migrateCacheDir(legacyFilepath)
+		err := migrateCacheDir(legacyDir)
 		if err != nil {
 			return err
 		}
 	}

This change improves readability and reduces potential confusion.

📝 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
legacyFilepath, exists = CacheDirLegacy()
if exists {
err := migrateCacheDir(legacyFilepath)
if err != nil {
return err
}
}
legacyDir, exists := CacheDirLegacy()
if exists {
err := migrateCacheDir(legacyDir)
if err != nil {
return err
}
}

Comment on lines +73 to +81
func CacheDirLegacy() (path string, exists bool) {
dir := homeDir(".scaffold/cache")
_, err := os.Stat(dir)
if err != nil {
return "", false
}

return dir, true
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors precisely in CacheDirLegacy

Similarly, in CacheDirLegacy, all errors from os.Stat are considered as the directory not existing. Important errors might be overlooked.

Apply this diff to improve error handling:

 func CacheDirLegacy() (path string, exists bool) {
 	dir := homeDir(".scaffold/cache")
 	_, err := os.Stat(dir)
-	if err != nil {
+	if err != nil {
+		if os.IsNotExist(err) {
+			return "", false
+		}
+		// Log unexpected errors
+		log.Error().Err(err).Msg("failed to access legacy cache directory")
+		return "", false
 	}

 	return dir, true
 }
📝 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 CacheDirLegacy() (path string, exists bool) {
dir := homeDir(".scaffold/cache")
_, err := os.Stat(dir)
if err != nil {
return "", false
}
return dir, true
}
func CacheDirLegacy() (path string, exists bool) {
dir := homeDir(".scaffold/cache")
_, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
return "", false
}
// Log unexpected errors
log.Error().Err(err).Msg("failed to access legacy cache directory")
return "", false
}
return dir, true
}

Comment on lines +35 to +43
func RCFilepathLegacy() (path string, exists bool) {
fp := homeDir(".scaffold", RCFilename)
_, err := os.Stat(fp)
if err != nil {
return "", false
}

return fp, true
}
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle errors precisely in RCFilepathLegacy

In the RCFilepathLegacy function, all errors from os.Stat are treated as the file not existing. This approach may overlook other potential errors (e.g., permission issues) that should be handled differently.

Consider modifying the error handling to specifically check if the error indicates that the file does not exist:

 func RCFilepathLegacy() (path string, exists bool) {
 	fp := homeDir(".scaffold", RCFilename)
 	_, err := os.Stat(fp)
-	if err != nil {
+	if err != nil {
+		if os.IsNotExist(err) {
+			return "", false
+		}
+		// Log unexpected errors
+		log.Error().Err(err).Msg("failed to access legacy configuration file")
+		return "", false
 	}

 	return fp, true
 }
📝 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 RCFilepathLegacy() (path string, exists bool) {
fp := homeDir(".scaffold", RCFilename)
_, err := os.Stat(fp)
if err != nil {
return "", false
}
return fp, true
}
func RCFilepathLegacy() (path string, exists bool) {
fp := homeDir(".scaffold", RCFilename)
_, err := os.Stat(fp)
if err != nil {
if os.IsNotExist(err) {
return "", false
}
// Log unexpected errors
log.Error().Err(err).Msg("failed to access legacy configuration file")
return "", false
}
return fp, true
}

@hay-kot hay-kot merged commit d1d2f8c into main Oct 12, 2024
2 checks passed
@hay-kot hay-kot deleted the fix/use-xdg-standard-directories branch October 12, 2024 02:28
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.

1 participant