| 1 |
// Copyright 2021 The Hugo Authors. All rights reserved. |
| 2 |
// |
| 3 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 |
// you may not use this file except in compliance with the License. |
| 5 |
// You may obtain a copy of the License at |
| 6 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 7 |
// |
| 8 |
// Unless required by applicable law or agreed to in writing, software |
| 9 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 10 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 11 |
// See the License for the specific language governing permissions and |
| 12 |
// limitations under the License. |
| 13 |
|
| 14 |
package paths |
| 15 |
|
| 16 |
import ( |
| 17 |
"errors" |
| 18 |
"fmt" |
| 19 |
"net/url" |
| 20 |
"path" |
| 21 |
"path/filepath" |
| 22 |
"strings" |
| 23 |
"unicode" |
| 24 |
) |
| 25 |
|
| 26 |
// FilePathSeparator as defined by os.Separator. |
| 27 |
const ( |
| 28 |
FilePathSeparator = string(filepath.Separator) |
| 29 |
slash = "/" |
| 30 |
) |
| 31 |
|
| 32 |
// filepathPathBridge is a bridge for common functionality in filepath vs path |
| 33 |
type filepathPathBridge interface { |
| 34 |
Base(in string) string |
| 35 |
Clean(in string) string |
| 36 |
Dir(in string) string |
| 37 |
Ext(in string) string |
| 38 |
Join(elem ...string) string |
| 39 |
Separator() string |
| 40 |
} |
| 41 |
|
| 42 |
type filepathBridge struct{} |
| 43 |
|
| 44 |
func (filepathBridge) Base(in string) string { |
| 45 |
return filepath.Base(in) |
| 46 |
} |
| 47 |
|
| 48 |
func (filepathBridge) Clean(in string) string { |
| 49 |
return filepath.Clean(in) |
| 50 |
} |
| 51 |
|
| 52 |
func (filepathBridge) Dir(in string) string { |
| 53 |
return filepath.Dir(in) |
| 54 |
} |
| 55 |
|
| 56 |
func (filepathBridge) Ext(in string) string { |
| 57 |
return filepath.Ext(in) |
| 58 |
} |
| 59 |
|
| 60 |
func (filepathBridge) Join(elem ...string) string { |
| 61 |
return filepath.Join(elem...) |
| 62 |
} |
| 63 |
|
| 64 |
func (filepathBridge) Separator() string { |
| 65 |
return FilePathSeparator |
| 66 |
} |
| 67 |
|
| 68 |
var fpb filepathBridge |
| 69 |
|
| 70 |
// AbsPathify creates an absolute path if given a working dir and a relative path. |
| 71 |
// If already absolute, the path is just cleaned. |
| 72 |
func AbsPathify(workingDir, inPath string) string { |
| 73 |
if filepath.IsAbs(inPath) { |
| 74 |
return filepath.Clean(inPath) |
| 75 |
} |
| 76 |
return filepath.Join(workingDir, inPath) |
| 77 |
} |
| 78 |
|
| 79 |
// AddTrailingSlash adds a trailing Unix styled slash (/) if not already |
| 80 |
// there. |
| 81 |
func AddTrailingSlash(path string) string { |
| 82 |
if !strings.HasSuffix(path, "/") { |
| 83 |
path += "/" |
| 84 |
} |
| 85 |
return path |
| 86 |
} |
| 87 |
|
| 88 |
// AddLeadingSlash adds a leading Unix styled slash (/) if not already |
| 89 |
// there. |
| 90 |
func AddLeadingSlash(path string) string { |
| 91 |
if !strings.HasPrefix(path, "/") { |
| 92 |
path = "/" + path |
| 93 |
} |
| 94 |
return path |
| 95 |
} |
| 96 |
|
| 97 |
// AddTrailingAndLeadingSlash adds a leading and trailing Unix styled slash (/) if not already |
| 98 |
// there. |
| 99 |
func AddLeadingAndTrailingSlash(path string) string { |
| 100 |
return AddTrailingSlash(AddLeadingSlash(path)) |
| 101 |
} |
| 102 |
|
| 103 |
func makePathRelative(inPath string, possibleDirectories ...string) (string, error) { |
| 104 |
for _, currentPath := range possibleDirectories { |
| 105 |
if after, ok := strings.CutPrefix(inPath, currentPath); ok { |
| 106 |
return after, nil |
| 107 |
} |
| 108 |
} |
| 109 |
return inPath, errors.New("can't extract relative path, unknown prefix") |
| 110 |
} |
| 111 |
|
| 112 |
// ExtNoDelimiter takes a path and returns the extension, excluding the delimiter, i.e. "md". |
| 113 |
func ExtNoDelimiter(in string) string { |
| 114 |
return strings.TrimPrefix(Ext(in), ".") |
| 115 |
} |
| 116 |
|
| 117 |
// Ext takes a path and returns the extension, including the delimiter, i.e. ".md". |
| 118 |
func Ext(in string) string { |
| 119 |
_, ext := fileAndExt(in, fpb) |
| 120 |
return ext |
| 121 |
} |
| 122 |
|
| 123 |
// PathAndExt is the same as FileAndExt, but it uses the path package. |
| 124 |
func PathAndExt(in string) (string, string) { |
| 125 |
return fileAndExt(in, pb) |
| 126 |
} |
| 127 |
|
| 128 |
// FileAndExt takes a path and returns the file and extension separated, |
| 129 |
// the extension including the delimiter, i.e. ".md". |
| 130 |
func FileAndExt(in string) (string, string) { |
| 131 |
return fileAndExt(in, fpb) |
| 132 |
} |
| 133 |
|
| 134 |
// FileAndExtNoDelimiter takes a path and returns the file and extension separated, |
| 135 |
// the extension excluding the delimiter, e.g "md". |
| 136 |
func FileAndExtNoDelimiter(in string) (string, string) { |
| 137 |
file, ext := fileAndExt(in, fpb) |
| 138 |
return file, strings.TrimPrefix(ext, ".") |
| 139 |
} |
| 140 |
|
| 141 |
// Filename takes a file path, strips out the extension, |
| 142 |
// and returns the name of the file. |
| 143 |
func Filename(in string) (name string) { |
| 144 |
name, _ = fileAndExt(in, fpb) |
| 145 |
return |
| 146 |
} |
| 147 |
|
| 148 |
// FileAndExt returns the filename and any extension of a file path as |
| 149 |
// two separate strings. |
| 150 |
// |
| 151 |
// If the path, in, contains a directory name ending in a slash, |
| 152 |
// then both name and ext will be empty strings. |
| 153 |
// |
| 154 |
// If the path, in, is either the current directory, the parent |
| 155 |
// directory or the root directory, or an empty string, |
| 156 |
// then both name and ext will be empty strings. |
| 157 |
// |
| 158 |
// If the path, in, represents the path of a file without an extension, |
| 159 |
// then name will be the name of the file and ext will be an empty string. |
| 160 |
// |
| 161 |
// If the path, in, represents a filename with an extension, |
| 162 |
// then name will be the filename minus any extension - including the dot |
| 163 |
// and ext will contain the extension - minus the dot. |
| 164 |
func fileAndExt(in string, b filepathPathBridge) (name string, ext string) { |
| 165 |
ext = b.Ext(in) |
| 166 |
base := b.Base(in) |
| 167 |
|
| 168 |
return extractFilename(in, ext, base, b.Separator()), ext |
| 169 |
} |
| 170 |
|
| 171 |
func extractFilename(in, ext, base, pathSeparator string) (name string) { |
| 172 |
// No file name cases. These are defined as: |
| 173 |
// 1. any "in" path that ends in a pathSeparator |
| 174 |
// 2. any "base" consisting of just an pathSeparator |
| 175 |
// 3. any "base" consisting of just an empty string |
| 176 |
// 4. any "base" consisting of just the current directory i.e. "." |
| 177 |
// 5. any "base" consisting of just the parent directory i.e. ".." |
| 178 |
if (strings.LastIndex(in, pathSeparator) == len(in)-1) || base == "" || base == "." || base == ".." || base == pathSeparator { |
| 179 |
name = "" // there is NO filename |
| 180 |
} else if ext != "" { // there was an Extension |
| 181 |
// return the filename minus the extension (and the ".") |
| 182 |
name = base[:strings.LastIndex(base, ".")] |
| 183 |
} else { |
| 184 |
// no extension case so just return base, which will |
| 185 |
// be the filename |
| 186 |
name = base |
| 187 |
} |
| 188 |
return |
| 189 |
} |
| 190 |
|
| 191 |
// Sanitize sanitizes string to be used in Hugo's file paths and URLs, allowing only |
| 192 |
// a predefined set of special Unicode characters. |
| 193 |
// |
| 194 |
// Spaces will be replaced with a single hyphen. |
| 195 |
// |
| 196 |
// This function is the core function used to normalize paths in Hugo. |
| 197 |
// |
| 198 |
// Note that this is the first common step for URL/path sanitation, |
| 199 |
// the final URL/path may end up looking differently if the user has stricter rules defined (e.g. removePathAccents=true). |
| 200 |
func Sanitize(s string) string { |
| 201 |
var willChange bool |
| 202 |
for i, r := range s { |
| 203 |
willChange = !isAllowedPathCharacter(s, i, r) |
| 204 |
if willChange { |
| 205 |
break |
| 206 |
} |
| 207 |
} |
| 208 |
|
| 209 |
if !willChange { |
| 210 |
// Prevent allocation when nothing changes. |
| 211 |
return s |
| 212 |
} |
| 213 |
|
| 214 |
target := make([]rune, 0, len(s)) |
| 215 |
var ( |
| 216 |
prependHyphen bool |
| 217 |
wasHyphen bool |
| 218 |
) |
| 219 |
|
| 220 |
for i, r := range s { |
| 221 |
isAllowed := isAllowedPathCharacter(s, i, r) |
| 222 |
|
| 223 |
if isAllowed { |
| 224 |
// track explicit hyphen in input; no need to add a new hyphen if |
| 225 |
// we just saw one. |
| 226 |
wasHyphen = r == '-' |
| 227 |
|
| 228 |
if prependHyphen { |
| 229 |
// if currently have a hyphen, don't prepend an extra one |
| 230 |
if !wasHyphen { |
| 231 |
target = append(target, '-') |
| 232 |
} |
| 233 |
prependHyphen = false |
| 234 |
} |
| 235 |
target = append(target, r) |
| 236 |
} else if len(target) > 0 && !wasHyphen && unicode.IsSpace(r) { |
| 237 |
prependHyphen = true |
| 238 |
} |
| 239 |
} |
| 240 |
|
| 241 |
return string(target) |
| 242 |
} |
| 243 |
|
| 244 |
func isAllowedPathCharacter(s string, i int, r rune) bool { |
| 245 |
if r == ' ' { |
| 246 |
return false |
| 247 |
} |
| 248 |
// Check for the most likely first (faster). |
| 249 |
isAllowed := unicode.IsLetter(r) || unicode.IsDigit(r) |
| 250 |
isAllowed = isAllowed || r == '.' || r == '/' || r == '\\' || r == '_' || r == '#' || r == '+' || r == '~' || r == '-' || r == '@' |
| 251 |
isAllowed = isAllowed || unicode.IsMark(r) |
| 252 |
isAllowed = isAllowed || (r == '%' && i+2 < len(s) && ishex(s[i+1]) && ishex(s[i+2])) |
| 253 |
return isAllowed |
| 254 |
} |
| 255 |
|
| 256 |
// From https://golang.org/src/net/url/url.go |
| 257 |
func ishex(c byte) bool { |
| 258 |
switch { |
| 259 |
case '0' <= c && c <= '9': |
| 260 |
return true |
| 261 |
case 'a' <= c && c <= 'f': |
| 262 |
return true |
| 263 |
case 'A' <= c && c <= 'F': |
| 264 |
return true |
| 265 |
} |
| 266 |
return false |
| 267 |
} |
| 268 |
|
| 269 |
var slashFunc = func(r rune) bool { |
| 270 |
return r == '/' |
| 271 |
} |
| 272 |
|
| 273 |
// Dir behaves like path.Dir without the path.Clean step. |
| 274 |
// |
| 275 |
// The returned path ends in a slash only if it is the root "/". |
| 276 |
func Dir(s string) string { |
| 277 |
dir, _ := path.Split(s) |
| 278 |
if len(dir) > 1 && dir[len(dir)-1] == '/' { |
| 279 |
return dir[:len(dir)-1] |
| 280 |
} |
| 281 |
return dir |
| 282 |
} |
| 283 |
|
| 284 |
// FieldsSlash cuts s into fields separated with '/'. |
| 285 |
func FieldsSlash(s string) []string { |
| 286 |
f := strings.FieldsFunc(s, slashFunc) |
| 287 |
return f |
| 288 |
} |
| 289 |
|
| 290 |
// DirFile holds the result from path.Split. |
| 291 |
type DirFile struct { |
| 292 |
Dir string |
| 293 |
File string |
| 294 |
} |
| 295 |
|
| 296 |
// Used in test. |
| 297 |
func (df DirFile) String() string { |
| 298 |
return fmt.Sprintf("%s|%s", df.Dir, df.File) |
| 299 |
} |
| 300 |
|
| 301 |
// PathEscape escapes unicode letters in pth. |
| 302 |
// Use URLEscape to escape full URLs including scheme, query etc. |
| 303 |
// This is slightly faster for the common case. |
| 304 |
// Note, there is a url.PathEscape function, but that also |
| 305 |
// escapes /. |
| 306 |
func PathEscape(pth string) string { |
| 307 |
u, err := url.Parse(pth) |
| 308 |
if err != nil { |
| 309 |
panic(err) |
| 310 |
} |
| 311 |
return u.EscapedPath() |
| 312 |
} |
| 313 |
|
| 314 |
// ToSlashTrimLeading is just a filepath.ToSlash with an added / prefix trimmer. |
| 315 |
func ToSlashTrimLeading(s string) string { |
| 316 |
return TrimLeading(filepath.ToSlash(s)) |
| 317 |
} |
| 318 |
|
| 319 |
// TrimLeading trims the leading slash from the given string. |
| 320 |
func TrimLeading(s string) string { |
| 321 |
return strings.TrimPrefix(s, "/") |
| 322 |
} |
| 323 |
|
| 324 |
// ToSlashTrimTrailing is just a filepath.ToSlash with an added / suffix trimmer. |
| 325 |
func ToSlashTrimTrailing(s string) string { |
| 326 |
return TrimTrailing(filepath.ToSlash(s)) |
| 327 |
} |
| 328 |
|
| 329 |
// TrimTrailing trims the trailing slash from the given string. |
| 330 |
func TrimTrailing(s string) string { |
| 331 |
return strings.TrimSuffix(s, "/") |
| 332 |
} |
| 333 |
|
| 334 |
// ToSlashTrim trims any leading and trailing slashes from the given string and converts it to a forward slash separated path. |
| 335 |
func ToSlashTrim(s string) string { |
| 336 |
return strings.Trim(filepath.ToSlash(s), "/") |
| 337 |
} |
| 338 |
|
| 339 |
// ToSlashPreserveLeading converts the path given to a forward slash separated path |
| 340 |
// and preserves the leading slash if present trimming any trailing slash. |
| 341 |
func ToSlashPreserveLeading(s string) string { |
| 342 |
return "/" + strings.Trim(filepath.ToSlash(s), "/") |
| 343 |
} |
| 344 |
|
| 345 |
// IsSameFilePath checks if s1 and s2 are the same file path. |
| 346 |
func IsSameFilePath(s1, s2 string) bool { |
| 347 |
return path.Clean(ToSlashTrim(s1)) == path.Clean(ToSlashTrim(s2)) |
| 348 |
} |