| 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 source contains the types and functions related to source files. |
| 15 |
package source |
| 16 |
|
| 17 |
import ( |
| 18 |
"path/filepath" |
| 19 |
"runtime" |
| 20 |
|
| 21 |
"github.com/spf13/afero" |
| 22 |
|
| 23 |
"github.com/gohugoio/hugo/helpers" |
| 24 |
"github.com/gohugoio/hugo/hugofs/hglob" |
| 25 |
) |
| 26 |
|
| 27 |
// SourceSpec abstracts language-specific file creation. |
| 28 |
// TODO(bep) rename to Spec |
| 29 |
type SourceSpec struct { |
| 30 |
*helpers.PathSpec |
| 31 |
|
| 32 |
SourceFs afero.Fs |
| 33 |
|
| 34 |
shouldInclude func(filename string) bool |
| 35 |
} |
| 36 |
|
| 37 |
// NewSourceSpec initializes SourceSpec using languages the given filesystem and PathSpec. |
| 38 |
func NewSourceSpec(ps *helpers.PathSpec, inclusionFilter *hglob.FilenameFilter, fs afero.Fs) *SourceSpec { |
| 39 |
shouldInclude := func(filename string) bool { |
| 40 |
if !inclusionFilter.Match(filename, false) { |
| 41 |
return false |
| 42 |
} |
| 43 |
if ps.Cfg.IgnoreFile(filename) { |
| 44 |
return false |
| 45 |
} |
| 46 |
|
| 47 |
return true |
| 48 |
} |
| 49 |
|
| 50 |
return &SourceSpec{shouldInclude: shouldInclude, PathSpec: ps, SourceFs: fs} |
| 51 |
} |
| 52 |
|
| 53 |
// IgnoreFile returns whether a given file should be ignored. |
| 54 |
func (s *SourceSpec) IgnoreFile(filename string) bool { |
| 55 |
if filename == "" { |
| 56 |
if _, ok := s.SourceFs.(*afero.OsFs); ok { |
| 57 |
return true |
| 58 |
} |
| 59 |
return false |
| 60 |
} |
| 61 |
|
| 62 |
base := filepath.Base(filename) |
| 63 |
|
| 64 |
if len(base) > 0 { |
| 65 |
first := base[0] |
| 66 |
last := base[len(base)-1] |
| 67 |
if first == '.' || |
| 68 |
first == '#' || |
| 69 |
last == '~' { |
| 70 |
return true |
| 71 |
} |
| 72 |
} |
| 73 |
|
| 74 |
if !s.shouldInclude(filename) { |
| 75 |
return true |
| 76 |
} |
| 77 |
|
| 78 |
if runtime.GOOS == "windows" { |
| 79 |
// Also check the forward slash variant if different. |
| 80 |
unixFilename := filepath.ToSlash(filename) |
| 81 |
if unixFilename != filename { |
| 82 |
if !s.shouldInclude(unixFilename) { |
| 83 |
return true |
| 84 |
} |
| 85 |
} |
| 86 |
} |
| 87 |
|
| 88 |
return false |
| 89 |
} |