GetAbsolutePath resolves a given path to its absolute form, handling ~, ./, ../, UNC paths, and symlinks.
(path string)
| 13 | |
| 14 | // GetAbsolutePath resolves a given path to its absolute form, handling ~, ./, ../, UNC paths, and symlinks. |
| 15 | func GetAbsolutePath(path string) (string, error) { |
| 16 | if path == "" { |
| 17 | return "", errors.New(i18n.T("util_error_path_is_empty")) |
| 18 | } |
| 19 | |
| 20 | // Handle UNC paths on Windows |
| 21 | if runtime.GOOS == "windows" && strings.HasPrefix(path, `\\`) { |
| 22 | return path, nil |
| 23 | } |
| 24 | |
| 25 | // Handle ~ for home directory expansion |
| 26 | if strings.HasPrefix(path, "~") { |
| 27 | home, err := os.UserHomeDir() |
| 28 | if err != nil { |
| 29 | return "", errors.New(i18n.T("util_error_resolve_home_directory")) |
| 30 | } |
| 31 | path = filepath.Join(home, path[1:]) |
| 32 | } |
| 33 | |
| 34 | // Convert to absolute path |
| 35 | absPath, err := filepath.Abs(path) |
| 36 | if err != nil { |
| 37 | return "", errors.New(i18n.T("util_error_get_absolute_path")) |
| 38 | } |
| 39 | |
| 40 | // Resolve symlinks, but allow non-existent paths |
| 41 | resolvedPath, err := filepath.EvalSymlinks(absPath) |
| 42 | if err == nil { |
| 43 | return resolvedPath, nil |
| 44 | } |
| 45 | if os.IsNotExist(err) { |
| 46 | // Return the absolute path for non-existent paths |
| 47 | return absPath, nil |
| 48 | } |
| 49 | |
| 50 | return "", fmt.Errorf(i18n.T("util_error_resolve_symlinks"), err) |
| 51 | } |
| 52 | |
| 53 | // Helper function to check if a symlink points to a directory |
| 54 | func IsSymlinkToDir(path string) bool { |
no test coverage detected