SanitizePath takes a string that might contain all kinds of special characters and makes a valid, similar, path name out of it. Spans of invalid characters, whitespace and/or non-UTF-8 sequences are replaced by a single space. The result is always UTF-8 and contains only printable characters, as de
(path string)
| 100 | // |
| 101 | // If the result is a name disallowed on windows, a hyphen is prepended. |
| 102 | func SanitizePath(path string) string { |
| 103 | var b strings.Builder |
| 104 | |
| 105 | const disallowed = `'/\[]{};:!@$%&^#` + windowsDisallowedCharacters |
| 106 | prev := ' ' |
| 107 | for _, c := range path { |
| 108 | if !unicode.IsPrint(c) || c == unicode.ReplacementChar || |
| 109 | strings.ContainsRune(disallowed, c) { |
| 110 | c = ' ' |
| 111 | } |
| 112 | |
| 113 | if !(c == ' ' && prev == ' ') { |
| 114 | b.WriteRune(c) |
| 115 | } |
| 116 | prev = c |
| 117 | } |
| 118 | |
| 119 | path = strings.TrimSpace(b.String()) |
| 120 | if reserved := windowsReservedNamePart(path); reserved != "" { |
| 121 | path = "-" + path |
| 122 | } |
| 123 | return path |
| 124 | } |
| 125 | |
| 126 | func windowsReservedNamePart(part string) string { |
| 127 | // nul.txt.jpg is also disallowed. |