LexicalRelativePath computes a relative path between the current working directory and modPath without relying on runtime.GOOS to estimate OS-specific separators. This is necessary as the code runs inside a Linux container, but the user might have specified a Windows-style modPath.
(cwdPath, modPath string)
| 13 | // and modPath without relying on runtime.GOOS to estimate OS-specific separators. This is necessary as the code |
| 14 | // runs inside a Linux container, but the user might have specified a Windows-style modPath. |
| 15 | func LexicalRelativePath(cwdPath, modPath string) (string, error) { |
| 16 | cwdPath = normalizePath(cwdPath) |
| 17 | modPath = normalizePath(modPath) |
| 18 | |
| 19 | cwdDrive := GetDrive(cwdPath) |
| 20 | modDrive := GetDrive(modPath) |
| 21 | if cwdDrive != modDrive { |
| 22 | return "", fmt.Errorf("cannot make paths on different drives relative: %s and %s", cwdDrive, modDrive) |
| 23 | } |
| 24 | |
| 25 | // Remove drive letter for relative path calculation |
| 26 | cwdPath = strings.TrimPrefix(cwdPath, cwdDrive) |
| 27 | modPath = strings.TrimPrefix(modPath, modDrive) |
| 28 | |
| 29 | relPath, err := filepath.Rel(cwdPath, modPath) |
| 30 | if err != nil { |
| 31 | return "", fmt.Errorf("failed to make path relative: %w", err) |
| 32 | } |
| 33 | |
| 34 | return relPath, nil |
| 35 | } |
| 36 | |
| 37 | // normalizePath converts all backslashes to forward slashes and removes trailing slashes. |
| 38 | // We can't use filepath.ToSlash() as this code always runs inside a Linux container. |