helpers.go (2040B)
1 // Copyright 2020 The Hugo Authors. All rights reserved. 2 // 3 // Portions Copyright The Go Authors. 4 5 // Licensed under the Apache License, Version 2.0 (the "License"); 6 // you may not use this file except in compliance with the License. 7 // You may obtain a copy of the License at 8 // http://www.apache.org/licenses/LICENSE-2.0 9 // 10 // Unless required by applicable law or agreed to in writing, software 11 // distributed under the License is distributed on an "AS IS" BASIS, 12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 // See the License for the specific language governing permissions and 14 // limitations under the License. 15 16 package resourcehelpers 17 18 import ( 19 "errors" 20 "fmt" 21 22 "github.com/gohugoio/hugo/common/maps" 23 "github.com/gohugoio/hugo/resources" 24 ) 25 26 // We allow string or a map as the first argument in some cases. 27 func ResolveIfFirstArgIsString(args []any) (resources.ResourceTransformer, string, bool) { 28 if len(args) != 2 { 29 return nil, "", false 30 } 31 32 v1, ok1 := args[0].(string) 33 if !ok1 { 34 return nil, "", false 35 } 36 v2, ok2 := args[1].(resources.ResourceTransformer) 37 38 return v2, v1, ok2 39 } 40 41 // This roundabout way of doing it is needed to get both pipeline behaviour and options as arguments. 42 func ResolveArgs(args []any) (resources.ResourceTransformer, map[string]any, error) { 43 if len(args) == 0 { 44 return nil, nil, errors.New("no Resource provided in transformation") 45 } 46 47 if len(args) == 1 { 48 r, ok := args[0].(resources.ResourceTransformer) 49 if !ok { 50 return nil, nil, fmt.Errorf("type %T not supported in Resource transformations", args[0]) 51 } 52 return r, nil, nil 53 } 54 55 r, ok := args[1].(resources.ResourceTransformer) 56 if !ok { 57 if _, ok := args[1].(map[string]any); !ok { 58 return nil, nil, fmt.Errorf("no Resource provided in transformation") 59 } 60 return nil, nil, fmt.Errorf("type %T not supported in Resource transformations", args[0]) 61 } 62 63 m, err := maps.ToStringMapE(args[0]) 64 if err != nil { 65 return nil, nil, fmt.Errorf("invalid options type: %w", err) 66 } 67 68 return r, m, nil 69 }