LexicallyCleanPath makes a path safe for use with filepath.Join. This is done by not only cleaning the path, but also (if the path is relative) adding a leading '/' and cleaning it (then removing the leading '/'). This ensures that a path resulting from prepending another path will always resolve to
(path string)
| 45 | // done lexically, so paths that include symlinks won't be safe as a result of |
| 46 | // using CleanPath. |
| 47 | func LexicallyCleanPath(path string) string { |
| 48 | // Deal with empty strings nicely. |
| 49 | if path == "" { |
| 50 | return "" |
| 51 | } |
| 52 | |
| 53 | // Ensure that all paths are cleaned (especially problematic ones like |
| 54 | // "/../../../../../" which can cause lots of issues). |
| 55 | |
| 56 | if filepath.IsAbs(path) { |
| 57 | return filepath.Clean(path) |
| 58 | } |
| 59 | |
| 60 | // If the path isn't absolute, we need to do more processing to fix paths |
| 61 | // such as "../../../../<etc>/some/path". We also shouldn't convert absolute |
| 62 | // paths to relative ones. |
| 63 | path = filepath.Clean(string(os.PathSeparator) + path) |
| 64 | // This can't fail, as (by definition) all paths are relative to root. |
| 65 | path, _ = filepath.Rel(string(os.PathSeparator), path) |
| 66 | |
| 67 | return path |
| 68 | } |
| 69 | |
| 70 | // LexicallyStripRoot returns the passed path, stripping the root path if it |
| 71 | // was (lexicially) inside it. Note that both passed paths will always be |
no outgoing calls
searching dependent graphs…