gitee.com/mirrors/Hugo-Go@v0.47.1/helpers/pathspec.go (about) 1 // Copyright 2016-present 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 "strings" 18 19 "github.com/gohugoio/hugo/config" 20 "github.com/gohugoio/hugo/hugofs" 21 "github.com/gohugoio/hugo/hugolib/filesystems" 22 "github.com/gohugoio/hugo/hugolib/paths" 23 ) 24 25 // PathSpec holds methods that decides how paths in URLs and files in Hugo should look like. 26 type PathSpec struct { 27 *paths.Paths 28 *filesystems.BaseFs 29 30 ProcessingStats *ProcessingStats 31 32 // The file systems to use 33 Fs *hugofs.Fs 34 35 // The config provider to use 36 Cfg config.Provider 37 } 38 39 // NewPathSpec creats a new PathSpec from the given filesystems and language. 40 func NewPathSpec(fs *hugofs.Fs, cfg config.Provider) (*PathSpec, error) { 41 return NewPathSpecWithBaseBaseFsProvided(fs, cfg, nil) 42 } 43 44 // NewPathSpecWithBaseBaseFsProvided creats a new PathSpec from the given filesystems and language. 45 // If an existing BaseFs is provided, parts of that is reused. 46 func NewPathSpecWithBaseBaseFsProvided(fs *hugofs.Fs, cfg config.Provider, baseBaseFs *filesystems.BaseFs) (*PathSpec, error) { 47 48 p, err := paths.New(fs, cfg) 49 if err != nil { 50 return nil, err 51 } 52 53 var options []func(*filesystems.BaseFs) error 54 if baseBaseFs != nil { 55 options = []func(*filesystems.BaseFs) error{ 56 filesystems.WithBaseFs(baseBaseFs), 57 } 58 } 59 bfs, err := filesystems.NewBase(p, options...) 60 if err != nil { 61 return nil, err 62 } 63 64 ps := &PathSpec{ 65 Paths: p, 66 BaseFs: bfs, 67 Fs: fs, 68 Cfg: cfg, 69 ProcessingStats: NewProcessingStats(p.Lang()), 70 } 71 72 if !ps.CanonifyURLs { 73 basePath := ps.BaseURL.Path() 74 if basePath != "" && basePath != "/" { 75 ps.BasePath = basePath 76 } 77 } 78 79 return ps, nil 80 } 81 82 // PermalinkForBaseURL creates a permalink from the given link and baseURL. 83 func (p *PathSpec) PermalinkForBaseURL(link, baseURL string) string { 84 link = strings.TrimPrefix(link, "/") 85 if !strings.HasSuffix(baseURL, "/") { 86 baseURL += "/" 87 } 88 return baseURL + link 89 90 }