| 1 |
// Copyright 2019 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 hugofs |
| 15 |
|
| 16 |
import ( |
| 17 |
"context" |
| 18 |
"errors" |
| 19 |
"path/filepath" |
| 20 |
"strings" |
| 21 |
|
| 22 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 23 |
"github.com/spf13/afero" |
| 24 |
) |
| 25 |
|
| 26 |
// Glob walks the fs and passes all matches to the handle func. |
| 27 |
// The handle func can return true to signal a stop. |
| 28 |
func Glob(fs afero.Fs, pattern string, handle func(fi FileMetaInfo) (bool, error)) error { |
| 29 |
pattern = hglob.NormalizePathNoLower(pattern) |
| 30 |
if pattern == "" { |
| 31 |
return nil |
| 32 |
} |
| 33 |
root := hglob.ResolveRootDir(pattern) |
| 34 |
if !strings.HasPrefix(root, "/") { |
| 35 |
root = "/" + root |
| 36 |
} |
| 37 |
pattern = strings.ToLower(pattern) |
| 38 |
|
| 39 |
g, err := hglob.GetGlob(pattern) |
| 40 |
if err != nil { |
| 41 |
return err |
| 42 |
} |
| 43 |
|
| 44 |
hasSuperAsterisk := strings.Contains(pattern, "**") |
| 45 |
levels := strings.Count(pattern, "/") |
| 46 |
|
| 47 |
// Signals that we're done. |
| 48 |
done := errors.New("done") |
| 49 |
|
| 50 |
wfn := func(ctx context.Context, p string, info FileMetaInfo) error { |
| 51 |
p = hglob.NormalizePath(p) |
| 52 |
if info.IsDir() { |
| 53 |
if !hasSuperAsterisk { |
| 54 |
// Avoid walking to the bottom if we can avoid it. |
| 55 |
if p != "" && strings.Count(p, "/") >= levels { |
| 56 |
return filepath.SkipDir |
| 57 |
} |
| 58 |
} |
| 59 |
return nil |
| 60 |
} |
| 61 |
|
| 62 |
if g.Match(p) { |
| 63 |
d, err := handle(info) |
| 64 |
if err != nil { |
| 65 |
return err |
| 66 |
} |
| 67 |
if d { |
| 68 |
return done |
| 69 |
} |
| 70 |
} |
| 71 |
|
| 72 |
return nil |
| 73 |
} |
| 74 |
|
| 75 |
w := NewWalkway( |
| 76 |
WalkwayConfig{ |
| 77 |
Root: root, |
| 78 |
Fs: fs, |
| 79 |
WalkFn: wfn, |
| 80 |
FailOnNotExist: true, |
| 81 |
}) |
| 82 |
|
| 83 |
err = w.Walk() |
| 84 |
|
| 85 |
if err != done { |
| 86 |
return err |
| 87 |
} |
| 88 |
|
| 89 |
return nil |
| 90 |
} |