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

[v3] Added AppDataDirectory path #3823

Merged

Conversation

ansxuman
Copy link

@ansxuman ansxuman commented Oct 13, 2024

Description

Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.

Fixes #3811

Type of change

Please delete options that are not relevant.

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • This change requires a documentation update

How Has This Been Tested?

Please describe the tests that you ran to verify your changes. Provide instructions so we can reproduce. Please also list any relevant details for your test configuration using wails doctor.

  • Windows
  • macOS
  • Linux

Test Configuration

Please paste the output of wails doctor. If you are unable to run this command, please describe your environment in as much detail as possible.

Checklist:

  • I have updated website/src/pages/changelog.mdx with details of this PR
  • My code follows the general coding style of this project
  • I have performed a self-review of my own code
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Summary by CodeRabbit

  • New Features

    • Introduced new methods for retrieving user-specific paths for application data, cache, and configuration across macOS, Linux, and Windows.
    • Added a new Path method in the application package for enhanced path management.
    • Included templates for sveltekit and sveltekit-ts configured for non-SSR development.
    • Added file association support and a new command wails3 update build-assets.
    • Introduced a new InitialPosition option for window positioning.
  • Bug Fixes

    • Fixed AlwaysOnTop functionality on macOS.
    • Resolved issues related to drag-and-drop functionality, compile errors on Linux, and system tray startup panics on Windows.
  • Documentation

    • Updated changelog to reflect notable changes and new features in the application API, including examples for new methods.

Copy link
Contributor

coderabbitai bot commented Oct 13, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

The pull request introduces several updates to the Wails framework, including new features, modifications, and bug fixes. Key additions include methods for path management in the application package, a new command for updating build assets, and enhancements to the documentation. Dependency management in the go.mod file has also been updated, along with a refactor of the Taskfile. The changelog has been expanded to reflect these changes, including significant updates for high DPI monitor support and bug resolutions for macOS functionality.

Changes

File Path Change Summary
mkdocs-website/docs/en/changelog.md Updated changelog with new features, modifications, and bug fixes, including events documentation.
v3/go.mod Added indirect dependency github.com/adrg/xdg v0.5.0 and upgraded golang.org/x/sys to v0.22.0.
v3/pkg/application/application.go Added methods Path(selector Path) string and Paths(selector Paths) []string to App struct.
mkdocs-website/docs/en/API/application.md Documented new methods Path and Paths with examples for path retrieval.
v3/pkg/application/path.go Introduced Path and Paths types with constants for user directory paths based on XDG spec.

Possibly related PRs

🐰 In the garden of code, we hop and play,
New paths and features brighten the day.
With updates and fixes, our work's never done,
A wail of delight, oh what fun!
So gather 'round, friends, let's cheer and rejoice,
For every new change, we celebrate with voice! 🎉

Warning

Rate limit exceeded

@leaanthony has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 18 minutes and 27 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 129592d and 6c3f442.


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

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.

@ansxuman
Copy link
Author

#3811

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

🧹 Outside diff range and nitpick comments (10)
mkdocs-website/docs/en/API/application.md (1)

136-156: Enhance the Path method documentation for clarity and completeness.

The documentation for the new Path method is clear and provides good examples. However, consider the following improvements to make it more comprehensive:

  1. Expand on the cross-platform nature of the method. For example: "This method provides a consistent way to access these directories across different operating systems, abstracting away OS-specific path structures."

  2. Add information about error handling. For instance: "If an invalid path type is provided, the method will return an empty string and log an error."

  3. Provide more context on when and why a developer might use these paths. For example: "The AppData directory is useful for storing application-specific data that should persist between sessions. The UserCache directory is ideal for temporary files that can be regenerated, while the UserConfig directory is suitable for user-specific configuration files."

  4. Consider adding a note about permissions or any potential issues that developers should be aware of when using these paths.

Would you like me to draft an expanded version of this documentation section?

v3/pkg/application/application_darwin.go (4)

369-372: LGTM with a minor suggestion for error handling

The getAppDataPath method correctly retrieves the Application Support directory path for macOS. However, consider handling potential errors from os.UserHomeDir().

You might want to handle the error from os.UserHomeDir(). Here's a suggestion:

func (a *macosApp) getAppDataPath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", fmt.Errorf("failed to get user home directory: %w", err)
    }
    return filepath.Join(home, "Library", "Application Support"), nil
}

This change would allow callers to handle potential errors when retrieving the path.


374-377: LGTM with a minor suggestion for error handling

The getUserCachePath method correctly retrieves the Caches directory path for macOS. As with the previous method, consider handling potential errors from os.UserHomeDir().

Similar to the previous suggestion, you might want to handle the error from os.UserHomeDir():

func (a *macosApp) getUserCachePath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", fmt.Errorf("failed to get user home directory: %w", err)
    }
    return filepath.Join(home, "Library", "Caches"), nil
}

This change would allow callers to handle potential errors when retrieving the path.


379-382: LGTM with a minor suggestion for error handling

The getUserConfigPath method correctly retrieves the Preferences directory path for macOS. As with the previous methods, consider handling potential errors from os.UserHomeDir().

Consistent with the previous suggestions, you might want to handle the error from os.UserHomeDir():

func (a *macosApp) getUserConfigPath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", fmt.Errorf("failed to get user home directory: %w", err)
    }
    return filepath.Join(home, "Library", "Preferences"), nil
}

This change would allow callers to handle potential errors when retrieving the path.


369-382: Overall, good addition of macOS-specific user directory paths

The addition of these three methods (getAppDataPath, getUserCachePath, and getUserConfigPath) enhances the functionality of the macosApp struct by providing access to common user directory paths specific to macOS. The implementations are correct and consistent.

To improve cross-platform consistency and make it easier to use these methods throughout the application, consider the following suggestions:

  1. Implement similar methods for other platforms (Windows, Linux) if not already done.
  2. Create a common interface in the application package that defines these methods, which each platform-specific implementation can satisfy.
  3. Consider adding a method to retrieve all paths at once, returning a struct with the various directories. This could be useful for initializing the application and would reduce the number of potential error checks needed when using these paths.

Example interface:

type PlatformPaths interface {
    GetAppDataPath() (string, error)
    GetUserCachePath() (string, error)
    GetUserConfigPath() (string, error)
    GetAllPaths() (Paths, error)
}

type Paths struct {
    AppData string
    UserCache string
    UserConfig string
}

This approach would make it easier to use these paths consistently across different parts of the application, regardless of the underlying OS.

v3/pkg/application/application_windows.go (3)

355-358: LGTM with a suggestion for error handling

The getAppDataPath method correctly retrieves the APPDATA environment variable. However, consider adding error handling in case the environment variable is not set.

You could improve the robustness of this method by checking if the environment variable exists:

func (a *windowsApp) getAppDataPath() (string, error) {
    path, exists := os.LookupEnv("APPDATA")
    if !exists {
        return "", fmt.Errorf("APPDATA environment variable not set")
    }
    return path, nil
}

360-363: LGTM with suggestions for improvement

The getUserCachePath method correctly constructs the user cache path. However, consider the following improvements:

  1. Add error handling in case the LOCALAPPDATA environment variable is not set.
  2. Ensure the directory exists or create it if it doesn't.

Here's an improved version of the method:

func (a *windowsApp) getUserCachePath() (string, error) {
    localAppData, exists := os.LookupEnv("LOCALAPPDATA")
    if !exists {
        return "", fmt.Errorf("LOCALAPPDATA environment variable not set")
    }
    path := filepath.Join(localAppData, "Temp")
    err := os.MkdirAll(path, 0755)
    if err != nil {
        return "", fmt.Errorf("failed to create cache directory: %w", err)
    }
    return path, nil
}

365-368: LGTM with a suggestion for error handling

The getUserConfigPath method correctly retrieves the LOCALAPPDATA environment variable. However, consider adding error handling in case the environment variable is not set.

You could improve the robustness of this method by checking if the environment variable exists:

func (a *windowsApp) getUserConfigPath() (string, error) {
    path, exists := os.LookupEnv("LOCALAPPDATA")
    if !exists {
        return "", fmt.Errorf("LOCALAPPDATA environment variable not set")
    }
    return path, nil
}
mkdocs-website/docs/en/changelog.md (1)

24-24: LGTM! Consider adding more details about the Path method.

The addition to the changelog is correctly placed and follows the established format. It accurately reflects the changes mentioned in the PR objectives.

To provide more context for users, consider expanding the description slightly. For example:

-- Add `Path` method to `application` package by [ansxuman](https://github.com/ansxuman) in [#3823](https://github.com/wailsapp/wails/pull/3823)
+- Add `Path` method to `application` package for retrieving AppDataDirectory path by [ansxuman](https://github.com/ansxuman) in [#3823](https://github.com/wailsapp/wails/pull/3823)

This additional detail helps users understand the purpose of the new method without needing to refer to the PR directly.

v3/pkg/application/application.go (1)

36-43: Consider adding comments for the new Path type and constants

To enhance code readability and maintainability, please add comments or documentation for the new Path type and its constants (AppData, UserCache, UserConfig). This will help other developers understand their purpose and usage within the application.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 94e8f8b and e6bf6d8.

📒 Files selected for processing (6)
  • mkdocs-website/docs/en/API/application.md (1 hunks)
  • mkdocs-website/docs/en/changelog.md (1 hunks)
  • v3/pkg/application/application.go (3 hunks)
  • v3/pkg/application/application_darwin.go (2 hunks)
  • v3/pkg/application/application_linux.go (2 hunks)
  • v3/pkg/application/application_windows.go (2 hunks)
🧰 Additional context used
🔇 Additional comments (3)
v3/pkg/application/application_linux.go (1)

265-278: Overall assessment of the changes

The introduction of methods to retrieve user-specific directory paths (getAppDataPath, getUserCachePath, and getUserConfigPath) is a valuable addition to the Linux application implementation. These methods align with the XDG Base Directory Specification, which is a standard practice in Linux environments.

However, there are opportunities for improvement:

  1. Error handling: Currently, potential errors from os.UserHomeDir() are ignored, which could lead to unexpected behavior.
  2. Robustness: The implementation could be more robust by checking for XDG environment variables before falling back to default paths.
  3. Code organization: There's some duplication in the implementation of these methods that could be reduced through refactoring.

Addressing these points would enhance the reliability and maintainability of the code. Consider implementing the suggested refactoring to create a more robust and DRY (Don't Repeat Yourself) solution.

To ensure that the XDG Base Directory Specification is correctly implemented, please run the following verification script:

This script will help verify that the implementation correctly uses XDG environment variables, has proper fallback paths, and handles potential errors from os.UserHomeDir().

v3/pkg/application/application_windows.go (1)

354-368: Overall assessment: Good addition with room for improvement

The new methods getAppDataPath, getUserCachePath, and getUserConfigPath are valuable additions to the windowsApp struct, providing functionality to retrieve application-specific directory paths. These changes align well with the PR objectives of adding AppDataDirectory path functionality.

Positive aspects:

  1. Consistent implementation across the three methods.
  2. Use of standard Windows environment variables.
  3. Use of filepath.Join for path construction in getUserCachePath.

Areas for improvement:

  1. Add error handling for cases where environment variables are not set.
  2. Include documentation for each method.
  3. Consider creating directories if they don't exist, especially for the cache path.
  4. Implement consistent return signatures (string vs string, error) across all methods.

Overall, these changes enhance the functionality of the application for Windows users. With the suggested improvements, the code will be more robust and maintainable.

v3/pkg/application/application.go (1)

203-205: Verify implementation of new interface methods across platforms

The platformApp interface now includes getAppDataPath(), getUserCachePath(), and getUserConfigPath(). Please ensure that all platform-specific implementations of this interface (e.g., Windows, macOS, Linux) have these methods implemented to prevent compile-time errors.

Run the following script to check for implementations of the new methods:

v3/pkg/application/application_linux.go Outdated Show resolved Hide resolved
v3/pkg/application/application_linux.go Outdated Show resolved Hide resolved
v3/pkg/application/application_linux.go Outdated Show resolved Hide resolved
v3/pkg/application/application_linux.go Outdated Show resolved Hide resolved
v3/pkg/application/application_windows.go Outdated Show resolved Hide resolved
v3/pkg/application/application.go Outdated Show resolved Hide resolved
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 (1)
v3/pkg/application/application.go (1)

1028-1041: LGTM: Path method is well-implemented, with a minor suggestion.

The Path method provides a clean API for retrieving platform-specific paths. It correctly handles all defined Path constants and includes proper error handling for unknown selectors.

Consider using a more descriptive error message in the default case:

-		return "", fmt.Errorf("unknown path selector: %v", selector)
+		return "", fmt.Errorf("invalid path selector: %v", selector)

This change makes it clearer that the selector is invalid, not just unknown.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between e6bf6d8 and 9e12aac.

⛔ Files ignored due to path filters (1)
  • v3/go.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • mkdocs-website/docs/en/API/application.md (1 hunks)
  • v3/go.mod (2 hunks)
  • v3/pkg/application/application.go (3 hunks)
  • v3/pkg/application/application_darwin.go (2 hunks)
  • v3/pkg/application/application_linux.go (2 hunks)
  • v3/pkg/application/application_windows.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • mkdocs-website/docs/en/API/application.md
  • v3/pkg/application/application_linux.go
  • v3/pkg/application/application_windows.go
🧰 Additional context used
🔇 Additional comments (11)
v3/go.mod (3)

Line range hint 1-108: Summary of changes in go.mod

The changes in this file are minimal and focused on the PR objective of adding AppDataDirectory path functionality:

  1. Upgrade of golang.org/x/sys from v0.20.0 to v0.22.0
  2. Addition of github.com/adrg/xdg v0.5.0 as an indirect dependency

These changes appear to be in line with the PR objectives and don't introduce any obvious conflicts. However, it's important to:

  1. Verify that the golang.org/x/sys upgrade doesn't introduce any breaking changes.
  2. Clarify how the github.com/adrg/xdg package is being used in the codebase.

Please ensure that these changes are reflected in the changelog and that any necessary documentation updates are made.

To ensure these changes don't have any unintended consequences, please run the project's test suite and perform a thorough manual testing of the new AppDataDirectory functionality on all supported platforms (Windows, macOS, and Linux).


49-49: Approve the addition of github.com/adrg/xdg, but clarify its usage.

The addition of github.com/adrg/xdg v0.5.0 as an indirect dependency aligns with the PR objective of adding AppDataDirectory path functionality. This package is commonly used for handling XDG Base Directory Specification in Go applications.

To ensure proper integration and usage, please run the following script:

#!/bin/bash
# Description: Verify the usage of github.com/adrg/xdg in the codebase

# Test: Search for direct imports of github.com/adrg/xdg
rg --type go 'import.*"github.com/adrg/xdg"'

# Test: Search for usage of xdg package functions
rg --type go 'xdg\.'

# Test: Check if any existing code for handling app data directories has been modified
rg --type go 'AppData|UserConfigDir|UserDataDir'

Could you please clarify which component is using this package and how it's being integrated into the existing codebase?


34-34: Approve the upgrade of golang.org/x/sys, but verify compatibility.

The upgrade of golang.org/x/sys from v0.20.0 to v0.22.0 is a good practice to keep dependencies up-to-date. However, it's important to ensure that this upgrade doesn't introduce any breaking changes to the project.

Please run the following script to check for any potential breaking changes or deprecations:

v3/pkg/application/application.go (4)

36-42: LGTM: New Path type and constants are well-defined.

The introduction of the Path type and associated constants (AppData, UserCache, UserConfig) is a good addition. The use of iota for defining the constants is idiomatic Go and provides a clear enumeration of path types.


203-205: LGTM: New methods in platformApp interface are well-defined.

The addition of getAppDataPath, getUserCachePath, and getUserConfigPath methods to the platformApp interface is consistent with the new Path type. The method signatures returning (string, error) follow Go conventions for operations that might fail.


1028-1041: Past review comment addressed.

The current implementation of the Path method addresses the concern raised in the past review comment. The default case in the switch statement now handles invalid Path selectors by returning an error, preventing silent failures.


Line range hint 36-1041: Overall changes: New path management feature well-integrated.

The introduction of the Path type, constants, and associated methods provides a robust and consistent way to handle application-specific paths across different platforms. The changes are well-integrated into the existing codebase and enhance the application's functionality without introducing conflicts or inconsistencies.

The new feature allows for more flexible and platform-independent path management, which should improve the application's portability and ease of use across different operating systems.

v3/pkg/application/application_darwin.go (4)

163-165: Appropriate addition of necessary imports

The imports os, path/filepath, and strings are required for file path manipulation and string operations in the new methods. They are correctly included.


168-169: Addition of external packages for directory handling

Including github.com/adrg/xdg and github.com/wailsapp/wails/v3/internal/operatingsystem is appropriate for accessing standard directories and operating system information, enhancing cross-platform compatibility.


371-382: ⚠️ Potential issue

Ensure macOS-specific application data path is used

The getAppDataPath function uses xdg.DataHome, which follows the XDG Base Directory specification common on Linux systems. On macOS, the standard location for application data is ~/Library/Application Support. Relying on xdg.DataHome may not return the expected directory on macOS and could lead to inconsistency.

Consider modifying the function to directly return the standard macOS application data path. Here's a suggested change:

func (a *macosApp) getAppDataPath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", err
    }
    return filepath.Join(home, "Library", "Application Support"), nil
}

If cross-platform consistency is a goal, ensure that the xdg package appropriately handles macOS paths or implement conditional logic based on the operating system.


384-394: ⚠️ Potential issue

Adjust cache directory retrieval to macOS standards

In getUserCachePath, using xdg.CacheHome may not align with macOS conventions, as macOS typically uses ~/Library/Caches for cache files. Depending on xdg.CacheHome could result in an incorrect path on macOS.

It's advisable to modify the function to return the standard macOS cache directory directly:

func (a *macosApp) getUserCachePath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", err
    }
    return filepath.Join(home, "Library", "Caches"), nil
}

Ensure that the application uses the appropriate cache directory consistent with macOS guidelines.

Comment on lines 396 to 415
func (a *macosApp) getUserConfigPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}

userPrefDir := filepath.Join(home, "Library", "Preferences")

for _, dir := range xdg.ConfigDirs {
if dir == userPrefDir {
return dir, nil
}
if strings.HasSuffix(dir, "Library/Preferences") {
if strings.HasPrefix(dir, home) {
return dir, nil
}
}
}
return userPrefDir, 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

Simplify and correct user configuration path retrieval

The getUserConfigPath function includes complex logic involving xdg.ConfigDirs to determine the user configuration directory. On macOS, configuration files are typically stored in ~/Library/Preferences. The usage of xdg.ConfigDirs may not be necessary and could introduce unexpected behavior.

Consider simplifying the function to directly return the macOS preferences directory:

func (a *macosApp) getUserConfigPath() (string, error) {
    home, err := os.UserHomeDir()
    if err != nil {
        return "", err
    }
    return filepath.Join(home, "Library", "Preferences"), nil
}

If there's a need to handle user-defined configuration directories, ensure that the logic accurately reflects macOS directory structures and standards.

📝 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 (a *macosApp) getUserConfigPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
userPrefDir := filepath.Join(home, "Library", "Preferences")
for _, dir := range xdg.ConfigDirs {
if dir == userPrefDir {
return dir, nil
}
if strings.HasSuffix(dir, "Library/Preferences") {
if strings.HasPrefix(dir, home) {
return dir, nil
}
}
}
return userPrefDir, nil
}
func (a *macosApp) getUserConfigPath() (string, error) {
home, err := os.UserHomeDir()
if err != nil {
return "", err
}
return filepath.Join(home, "Library", "Preferences"), nil
}

@leaanthony
Copy link
Member

Hi @ansxuman - I think we should simply expose the XDG methods and exports via app.Path rather than wrapping the functionality and providing defaults if paths don't exist. I think we should leave that for the developer to decide. Thoughts?

@ansxuman
Copy link
Author

ansxuman commented Oct 20, 2024

Hi @ansxuman - I think we should simply expose the XDG methods and exports via app.Path rather than wrapping the functionality and providing defaults if paths don't exist. I think we should leave that for the developer to decide. Thoughts?

Thats a good point, devs will have more control, i have made the changes.

P.S - Should i raise PR for v2 also ?

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 (2)
v3/pkg/application/application_darwin.go (1)

368-384: Summary of changes and recommendations

The additions to the macosApp struct enhance its functionality by providing methods to retrieve user-specific paths. While getAppDataPath and getUserCachePath are well-implemented and adhere to XDG specifications, getUserConfigPath needs refinement to better align with macOS conventions.

Consider implementing the suggested changes for getUserConfigPath to ensure consistency with macOS standards and improve reliability. Once these changes are made, the overall implementation will provide a robust solution for managing application-specific directories on macOS.

v3/pkg/application/application.go (1)

1027-1044: LGTM! Well-implemented Path method with a suggestion.

The Path method is well-structured and properly handles different cases, including uninitialized application and unknown selectors. It effectively abstracts the platform-specific implementations.

Consider using a custom error type or error variables for better error handling and consistency. For example:

var ErrAppNotInitialized = errors.New("application not initialized")
var ErrUnknownPathSelector = errors.New("unknown path selector")

func (a *App) Path(selector Path) (string, error) {
	if a.impl == nil {
		return "", ErrAppNotInitialized
	}
	switch selector {
	case AppData:
		return a.impl.getAppDataPath()
	case UserCache:
		return a.impl.getUserCachePath()
	case UserConfig:
		return a.impl.getUserConfigPath()
	default:
		return "", fmt.Errorf("%w: %v", ErrUnknownPathSelector, selector)
	}
}

This approach allows for easier error checking and provides more context in the error messages.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 9e12aac and 5a0b492.

📒 Files selected for processing (3)
  • v3/pkg/application/application.go (3 hunks)
  • v3/pkg/application/application_darwin.go (2 hunks)
  • v3/pkg/application/application_linux.go (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • v3/pkg/application/application_linux.go
🧰 Additional context used
🔇 Additional comments (5)
v3/pkg/application/application_darwin.go (3)

369-371: LGTM: Appropriate use of XDG specification for app data path

The getAppDataPath method correctly uses the xdg.DataHome to retrieve the application data directory. This adheres to the XDG Base Directory Specification, which is a good practice for cross-platform compatibility.


373-375: LGTM: Correct implementation for user cache path

The getUserCachePath method appropriately uses xdg.CacheHome to retrieve the user's cache directory. This is consistent with the XDG Base Directory Specification and provides a standard location for caching application data.


377-384: ⚠️ Potential issue

Simplify and correct user configuration path retrieval

The current implementation of getUserConfigPath has some issues:

  1. It iterates through xdg.ConfigDirs, which is not typically used on macOS.
  2. It returns an empty string if no suitable directory is found, which could lead to unexpected behavior.
  3. It doesn't align with macOS conventions for storing user preferences.

Consider simplifying the function to directly return the macOS preferences directory:

func (a *macosApp) getUserConfigPath() (string, error) {
-   for _, dir := range xdg.ConfigDirs {
-       if strings.HasSuffix(dir, "Library/Preferences") {
-           return dir, nil
-       }
-   }
-   return "", nil
+   home, err := os.UserHomeDir()
+   if err != nil {
+       return "", err
+   }
+   return filepath.Join(home, "Library", "Preferences"), nil
}

This implementation:

  1. Directly uses the standard macOS location for user preferences.
  2. Properly handles and returns any errors encountered.
  3. Aligns with macOS conventions and is more reliable.
v3/pkg/application/application.go (2)

36-42: LGTM! Well-structured path type and constants.

The introduction of the Path type and associated constants (AppData, UserCache, UserConfig) is a good approach for managing different application-specific paths. Using an integer type with iota ensures efficient comparisons and unique values.


203-205: LGTM! Consistent interface extension.

The addition of getAppDataPath(), getUserCachePath(), and getUserConfigPath() methods to the platformApp interface is well-aligned with the new Path type and constants. The consistent return types (string, error) allow for proper error handling.

Copy link

sonarcloud bot commented Oct 21, 2024

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)
mkdocs-website/docs/en/changelog.md (1)

27-27: Approved with a suggestion for clarity.

The new changelog entry correctly documents the addition of the Path method to the application package. This aligns with the PR objectives and follows the proper format for changelog entries.

Consider expanding the description slightly to provide more context about the purpose of the Path method. For example:

- Add `Path` method to `application` package by [ansxuman](https://github.com/ansxuman) in [#3823](https://github.com/wailsapp/wails/pull/3823)
+ Add `Path` method to `application` package for retrieving application-specific directory paths by [ansxuman](https://github.com/ansxuman) in [#3823](https://github.com/wailsapp/wails/pull/3823)

This additional context would help users understand the purpose and significance of the new method without needing to refer to the PR directly.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between afb8385 and 129592d.

📒 Files selected for processing (1)
  • mkdocs-website/docs/en/changelog.md (1 hunks)
🧰 Additional context used

@leaanthony leaanthony merged commit 331097f into wailsapp:v3-alpha Nov 16, 2024
4 of 5 checks passed
@leaanthony
Copy link
Member

Refactored the PR (I hope you don't mind!) to make it easier to maintain. Thanks for kicking this off @ansxuman 🙏

@coderabbitai coderabbitai bot mentioned this pull request Nov 16, 2024
15 tasks
@ansxuman
Copy link
Author

Refactored the PR (I hope you don't mind!) to make it easier to maintain. Thanks for kicking this off @ansxuman 🙏

My Pleasure

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.

2 participants