fmt.go (2639B)
1 // Copyright 2017 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 fmt provides template functions for formatting strings. 15 package fmt 16 17 import ( 18 _fmt "fmt" 19 20 "github.com/gohugoio/hugo/common/loggers" 21 22 "github.com/gohugoio/hugo/deps" 23 "github.com/gohugoio/hugo/helpers" 24 ) 25 26 // New returns a new instance of the fmt-namespaced template functions. 27 func New(d *deps.Deps) *Namespace { 28 ignorableLogger, ok := d.Log.(loggers.IgnorableLogger) 29 if !ok { 30 ignorableLogger = loggers.NewIgnorableLogger(d.Log) 31 } 32 33 distinctLogger := helpers.NewDistinctLogger(d.Log) 34 ns := &Namespace{ 35 distinctLogger: ignorableLogger.Apply(distinctLogger), 36 } 37 38 d.BuildStartListeners.Add(func() { 39 ns.distinctLogger.Reset() 40 }) 41 42 return ns 43 } 44 45 // Namespace provides template functions for the "fmt" namespace. 46 type Namespace struct { 47 distinctLogger loggers.IgnorableLogger 48 } 49 50 // Print returns a string representation args. 51 func (ns *Namespace) Print(args ...any) string { 52 return _fmt.Sprint(args...) 53 } 54 55 // Printf returns a formatted string representation of args. 56 func (ns *Namespace) Printf(format string, args ...any) string { 57 return _fmt.Sprintf(format, args...) 58 } 59 60 // Println returns string representation of args ending with a newline. 61 func (ns *Namespace) Println(args ...any) string { 62 return _fmt.Sprintln(args...) 63 } 64 65 // Errorf formats args according to a format specifier and logs an ERROR. 66 // It returns an empty string. 67 func (ns *Namespace) Errorf(format string, args ...any) string { 68 ns.distinctLogger.Errorf(format, args...) 69 return "" 70 } 71 72 // Erroridf formats args according to a format specifier and logs an ERROR and 73 // an information text that the error with the given ID can be suppressed in config. 74 // It returns an empty string. 75 func (ns *Namespace) Erroridf(id, format string, args ...any) string { 76 ns.distinctLogger.Errorsf(id, format, args...) 77 return "" 78 } 79 80 // Warnf formats args according to a format specifier and logs a WARNING. 81 // It returns an empty string. 82 func (ns *Namespace) Warnf(format string, args ...any) string { 83 ns.distinctLogger.Warnf(format, args...) 84 return "" 85 }