| 1 |
// Copyright 2024 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 helpers |
| 15 |
|
| 16 |
import ( |
| 17 |
"fmt" |
| 18 |
"io" |
| 19 |
"os" |
| 20 |
"path" |
| 21 |
"path/filepath" |
| 22 |
"regexp" |
| 23 |
"slices" |
| 24 |
"sort" |
| 25 |
"strings" |
| 26 |
|
| 27 |
"github.com/gohugoio/go-radix" |
| 28 |
"github.com/gohugoio/hugo/common/herrors" |
| 29 |
"github.com/gohugoio/hugo/common/text" |
| 30 |
"github.com/gohugoio/hugo/htesting" |
| 31 |
|
| 32 |
"github.com/gohugoio/hugo/common/paths" |
| 33 |
"github.com/gohugoio/hugo/hugofs" |
| 34 |
|
| 35 |
"github.com/gohugoio/hugo/common/hugio" |
| 36 |
"github.com/spf13/afero" |
| 37 |
) |
| 38 |
|
| 39 |
// MakePath takes a string with any characters and replace it |
| 40 |
// so the string could be used in a path. |
| 41 |
// It does so by creating a Unicode-sanitized string, with the spaces replaced, |
| 42 |
// whilst preserving the original casing of the string. |
| 43 |
// E.g. Social Media -> Social-Media |
| 44 |
func (p *PathSpec) MakePath(s string) string { |
| 45 |
s = paths.Sanitize(s) |
| 46 |
if p.Cfg.RemovePathAccents() { |
| 47 |
s = text.RemoveAccentsString(s) |
| 48 |
} |
| 49 |
return s |
| 50 |
} |
| 51 |
|
| 52 |
// MakePathsSanitized applies MakePathSanitized on every item in the slice |
| 53 |
func (p *PathSpec) MakePathsSanitized(paths []string) { |
| 54 |
for i, path := range paths { |
| 55 |
paths[i] = p.MakePathSanitized(path) |
| 56 |
} |
| 57 |
} |
| 58 |
|
| 59 |
// MakePathSanitized creates a Unicode-sanitized string, with the spaces replaced |
| 60 |
func (p *PathSpec) MakePathSanitized(s string) string { |
| 61 |
if p.Cfg.DisablePathToLower() { |
| 62 |
return p.MakePath(s) |
| 63 |
} |
| 64 |
return strings.ToLower(p.MakePath(s)) |
| 65 |
} |
| 66 |
|
| 67 |
// Should be good enough for Hugo. |
| 68 |
var isFileRe = regexp.MustCompile(`.*\..{1,6}$`) |
| 69 |
|
| 70 |
// GetDottedRelativePath expects a relative path starting after the content directory. |
| 71 |
// It returns a relative path with dots ("..") navigating up the path structure. |
| 72 |
func GetDottedRelativePath(inPath string) string { |
| 73 |
inPath = path.Clean(filepath.ToSlash(inPath)) |
| 74 |
|
| 75 |
if inPath == "." { |
| 76 |
return "./" |
| 77 |
} |
| 78 |
|
| 79 |
if !isFileRe.MatchString(inPath) && !strings.HasSuffix(inPath, "/") { |
| 80 |
inPath += "/" |
| 81 |
} |
| 82 |
|
| 83 |
if !strings.HasPrefix(inPath, "/") { |
| 84 |
inPath = "/" + inPath |
| 85 |
} |
| 86 |
|
| 87 |
dir, _ := path.Split(inPath) |
| 88 |
|
| 89 |
sectionCount := strings.Count(dir, "/") |
| 90 |
|
| 91 |
if sectionCount == 0 || dir == "/" { |
| 92 |
return "./" |
| 93 |
} |
| 94 |
|
| 95 |
var dottedPath strings.Builder |
| 96 |
|
| 97 |
for i := 1; i < sectionCount; i++ { |
| 98 |
dottedPath.WriteString("../") |
| 99 |
} |
| 100 |
|
| 101 |
return dottedPath.String() |
| 102 |
} |
| 103 |
|
| 104 |
type NamedSlice struct { |
| 105 |
Name string |
| 106 |
Slice []string |
| 107 |
} |
| 108 |
|
| 109 |
func (n NamedSlice) String() string { |
| 110 |
if len(n.Slice) == 0 { |
| 111 |
return n.Name |
| 112 |
} |
| 113 |
return fmt.Sprintf("%s%s{%s}", n.Name, FilePathSeparator, strings.Join(n.Slice, ",")) |
| 114 |
} |
| 115 |
|
| 116 |
// ExtractAndGroupRootPaths extracts and groups root paths from the supplied list of paths. |
| 117 |
// Note that the in slice will be sorted in place. |
| 118 |
func ExtractAndGroupRootPaths(in []string) []string { |
| 119 |
if len(in) == 0 { |
| 120 |
return nil |
| 121 |
} |
| 122 |
const maxGroups = 5 |
| 123 |
const maxRootGroups = 10 |
| 124 |
sort.Strings(in) |
| 125 |
var groups []string |
| 126 |
tree := radix.New[[]string]() |
| 127 |
|
| 128 |
LOOP: |
| 129 |
for _, s := range in { |
| 130 |
s = filepath.ToSlash(s) |
| 131 |
if ss, g, found := tree.LongestPrefix(s); found { |
| 132 |
if len(g) > maxGroups { |
| 133 |
continue LOOP |
| 134 |
} |
| 135 |
parts := strings.Split(strings.TrimPrefix(strings.TrimPrefix(s, ss), "/"), "/") |
| 136 |
if len(parts) > 0 && parts[0] != "" && !slices.Contains(g, parts[0]) { |
| 137 |
g = append(g, parts[0]) |
| 138 |
tree.Insert(ss, g) |
| 139 |
} |
| 140 |
|
| 141 |
} else { |
| 142 |
tree.Insert(s, []string{}) |
| 143 |
} |
| 144 |
} |
| 145 |
|
| 146 |
var collect radix.WalkFn[[]string] = func(s string, g []string) (radix.WalkFlag, []string, error) { |
| 147 |
if len(g) == 0 { |
| 148 |
groups = append(groups, s) |
| 149 |
return radix.WalkContinue, nil, nil |
| 150 |
} |
| 151 |
if len(g) == 1 { |
| 152 |
groups = append(groups, path.Join(s, g[0])) |
| 153 |
return radix.WalkContinue, nil, nil |
| 154 |
} |
| 155 |
var sb strings.Builder |
| 156 |
sb.WriteString(s) |
| 157 |
// This is used to print "Watching for changes in /Users/bep/dev/sites/hugotestsites/60k/content/{section0,section1,section10..." |
| 158 |
// Having too many groups here is not helpful. |
| 159 |
if len(g) > maxGroups { |
| 160 |
// This will modify the slice in the tree, but that is OK since we are done with it. |
| 161 |
g = g[:maxGroups] |
| 162 |
g = append(g, "...") |
| 163 |
} |
| 164 |
sb.WriteString("/{") |
| 165 |
sb.WriteString(strings.Join(g, ",")) |
| 166 |
sb.WriteString("}") |
| 167 |
groups = append(groups, sb.String()) |
| 168 |
return radix.WalkContinue, nil, nil |
| 169 |
} |
| 170 |
|
| 171 |
tree.Walk(collect) |
| 172 |
|
| 173 |
// Limit the total number of root groups to keep output manageable |
| 174 |
if len(groups) > maxRootGroups { |
| 175 |
remaining := len(groups) - maxRootGroups |
| 176 |
groups = groups[:maxRootGroups] |
| 177 |
groups = append(groups, fmt.Sprintf("... and %d more", remaining)) |
| 178 |
} |
| 179 |
|
| 180 |
return groups |
| 181 |
} |
| 182 |
|
| 183 |
// Walk walks the file tree rooted at root, calling walkFn for each file or |
| 184 |
// directory in the tree, including root. |
| 185 |
func Walk(fs afero.Fs, root string, walker hugofs.WalkFunc) error { |
| 186 |
if _, isOs := fs.(*afero.OsFs); isOs { |
| 187 |
fs = hugofs.NewBaseFileDecorator(fs) |
| 188 |
} |
| 189 |
w := hugofs.NewWalkway(hugofs.WalkwayConfig{ |
| 190 |
Fs: fs, |
| 191 |
Root: root, |
| 192 |
WalkFn: walker, |
| 193 |
}) |
| 194 |
|
| 195 |
return w.Walk() |
| 196 |
} |
| 197 |
|
| 198 |
// WriteToDisk writes content to disk. |
| 199 |
func WriteToDisk(inpath string, r io.Reader, fs afero.Fs) (err error) { |
| 200 |
return afero.WriteReader(fs, inpath, r) |
| 201 |
} |
| 202 |
|
| 203 |
// OpenFilesForWriting opens all the given filenames for writing. |
| 204 |
func OpenFilesForWriting(fs afero.Fs, filenames ...string) (io.WriteCloser, error) { |
| 205 |
var writeClosers []io.WriteCloser |
| 206 |
for _, filename := range filenames { |
| 207 |
f, err := OpenFileForWriting(fs, filename) |
| 208 |
if err != nil { |
| 209 |
for _, wc := range writeClosers { |
| 210 |
wc.Close() |
| 211 |
} |
| 212 |
return nil, err |
| 213 |
} |
| 214 |
writeClosers = append(writeClosers, f) |
| 215 |
} |
| 216 |
|
| 217 |
return hugio.NewMultiWriteCloser(writeClosers...), nil |
| 218 |
} |
| 219 |
|
| 220 |
// OpenFileForWriting opens or creates the given file. If the target directory |
| 221 |
// does not exist, it gets created. |
| 222 |
func OpenFileForWriting(fs afero.Fs, filename string) (afero.File, error) { |
| 223 |
filename = filepath.Clean(filename) |
| 224 |
// Create will truncate if file already exists. |
| 225 |
// os.Create will create any new files with mode 0666 (before umask). |
| 226 |
f, err := fs.Create(filename) |
| 227 |
if err != nil { |
| 228 |
if !herrors.IsNotExist(err) { |
| 229 |
return nil, err |
| 230 |
} |
| 231 |
if err = fs.MkdirAll(filepath.Dir(filename), 0o777); err != nil { // before umask |
| 232 |
return nil, err |
| 233 |
} |
| 234 |
f, err = fs.Create(filename) |
| 235 |
} |
| 236 |
|
| 237 |
return f, err |
| 238 |
} |
| 239 |
|
| 240 |
// GetCacheDir returns a cache dir from the given filesystem and config. |
| 241 |
// The dir will be created if it does not exist. |
| 242 |
func GetCacheDir(fs afero.Fs, cacheDir string) (string, error) { |
| 243 |
cacheDir = cacheDirDefault(cacheDir) |
| 244 |
|
| 245 |
if cacheDir != "" { |
| 246 |
exists, err := DirExists(cacheDir, fs) |
| 247 |
if err != nil { |
| 248 |
return "", err |
| 249 |
} |
| 250 |
if !exists { |
| 251 |
err := fs.MkdirAll(cacheDir, 0o777) // Before umask |
| 252 |
if err != nil { |
| 253 |
return "", fmt.Errorf("failed to create cache dir: %w", err) |
| 254 |
} |
| 255 |
} |
| 256 |
return cacheDir, nil |
| 257 |
} |
| 258 |
|
| 259 |
const hugoCacheBase = "hugo_cache" |
| 260 |
|
| 261 |
// Avoid filling up the home dir with Hugo cache dirs from development. |
| 262 |
if !htesting.IsTest { |
| 263 |
userCacheDir, err := os.UserCacheDir() |
| 264 |
if err == nil { |
| 265 |
cacheDir := filepath.Join(userCacheDir, hugoCacheBase) |
| 266 |
if err := fs.Mkdir(cacheDir, 0o777); err == nil || os.IsExist(err) { |
| 267 |
return cacheDir, nil |
| 268 |
} |
| 269 |
} |
| 270 |
} |
| 271 |
|
| 272 |
// Fall back to a cache in /tmp. |
| 273 |
userName := os.Getenv("USER") |
| 274 |
if userName != "" { |
| 275 |
return GetTempDir(hugoCacheBase+"_"+userName, fs), nil |
| 276 |
} else { |
| 277 |
return GetTempDir(hugoCacheBase, fs), nil |
| 278 |
} |
| 279 |
} |
| 280 |
|
| 281 |
func cacheDirDefault(cacheDir string) string { |
| 282 |
// Always use the cacheDir config if set. |
| 283 |
if len(cacheDir) > 1 { |
| 284 |
return addTrailingFileSeparator(cacheDir) |
| 285 |
} |
| 286 |
|
| 287 |
// See Issue #8714. |
| 288 |
// Turns out that Cloudflare also sets NETLIFY=true in its build environment, |
| 289 |
// but all of these 3 should not give any false positives. |
| 290 |
if os.Getenv("NETLIFY") == "true" && os.Getenv("PULL_REQUEST") != "" && os.Getenv("DEPLOY_PRIME_URL") != "" { |
| 291 |
// Netlify's cache behavior is not documented, the currently best example |
| 292 |
// is this project: |
| 293 |
// https://github.com/philhawksworth/content-shards/blob/master/gulpfile.js |
| 294 |
return "/opt/build/cache/hugo_cache/" |
| 295 |
} |
| 296 |
|
| 297 |
// This will fall back to an hugo_cache folder in either os.UserCacheDir or the tmp dir, which should work fine for most CI |
| 298 |
// providers. See this for a working CircleCI setup: |
| 299 |
// https://github.com/bep/hugo-sass-test/blob/6c3960a8f4b90e8938228688bc49bdcdd6b2d99e/.circleci/config.yml |
| 300 |
// If not, they can set the HUGO_CACHEDIR environment variable or cacheDir config key. |
| 301 |
return "" |
| 302 |
} |
| 303 |
|
| 304 |
func addTrailingFileSeparator(s string) string { |
| 305 |
if !strings.HasSuffix(s, FilePathSeparator) { |
| 306 |
s = s + FilePathSeparator |
| 307 |
} |
| 308 |
return s |
| 309 |
} |
| 310 |
|
| 311 |
// GetTempDir returns a temporary directory with the given sub path. |
| 312 |
func GetTempDir(subPath string, fs afero.Fs) string { |
| 313 |
return afero.GetTempDir(fs, subPath) |
| 314 |
} |
| 315 |
|
| 316 |
// DirExists checks if a path exists and is a directory. |
| 317 |
func DirExists(path string, fs afero.Fs) (bool, error) { |
| 318 |
return afero.DirExists(fs, path) |
| 319 |
} |
| 320 |
|
| 321 |
// IsDir checks if a given path is a directory. |
| 322 |
func IsDir(path string, fs afero.Fs) (bool, error) { |
| 323 |
return afero.IsDir(fs, path) |
| 324 |
} |
| 325 |
|
| 326 |
// IsEmpty checks if a given path is empty, meaning it doesn't contain any regular files. |
| 327 |
func IsEmpty(path string, fs afero.Fs) (bool, error) { |
| 328 |
var hasFile bool |
| 329 |
err := afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error { |
| 330 |
if info.IsDir() { |
| 331 |
return nil |
| 332 |
} |
| 333 |
hasFile = true |
| 334 |
return filepath.SkipDir |
| 335 |
}) |
| 336 |
return !hasFile, err |
| 337 |
} |
| 338 |
|
| 339 |
// Exists checks if a file or directory exists. |
| 340 |
func Exists(path string, fs afero.Fs) (bool, error) { |
| 341 |
return afero.Exists(fs, path) |
| 342 |
} |