github.com/anakojm/hugo-katex@v0.0.0-20231023141351-42d6f5de9c0b/config/testconfig/testconfig.go (about) 1 // Copyright 2023 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 // This package should only be used for testing. 15 package testconfig 16 17 import ( 18 _ "unsafe" 19 20 "github.com/gohugoio/hugo/common/maps" 21 "github.com/gohugoio/hugo/config" 22 "github.com/gohugoio/hugo/config/allconfig" 23 "github.com/gohugoio/hugo/deps" 24 "github.com/gohugoio/hugo/hugofs" 25 toml "github.com/pelletier/go-toml/v2" 26 "github.com/spf13/afero" 27 ) 28 29 func GetTestConfigs(fs afero.Fs, cfg config.Provider) *allconfig.Configs { 30 if fs == nil { 31 fs = afero.NewMemMapFs() 32 } 33 if cfg == nil { 34 cfg = config.New() 35 } 36 // Make sure that the workingDir exists. 37 workingDir := cfg.GetString("workingDir") 38 if workingDir != "" { 39 if err := fs.MkdirAll(workingDir, 0777); err != nil { 40 panic(err) 41 } 42 } 43 44 configs, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs, Flags: cfg, Environ: []string{"EMPTY_TEST_ENVIRONMENT"}}) 45 if err != nil { 46 panic(err) 47 } 48 return configs 49 50 } 51 52 func GetTestConfig(fs afero.Fs, cfg config.Provider) config.AllProvider { 53 return GetTestConfigs(fs, cfg).GetFirstLanguageConfig() 54 } 55 56 func GetTestDeps(fs afero.Fs, cfg config.Provider, beforeInit ...func(*deps.Deps)) *deps.Deps { 57 if fs == nil { 58 fs = afero.NewMemMapFs() 59 } 60 conf := GetTestConfig(fs, cfg) 61 d := &deps.Deps{ 62 Conf: conf, 63 Fs: hugofs.NewFrom(fs, conf.BaseConfig()), 64 } 65 for _, f := range beforeInit { 66 f(d) 67 } 68 if err := d.Init(); err != nil { 69 panic(err) 70 } 71 return d 72 } 73 74 func GetTestConfigSectionFromStruct(section string, v any) config.AllProvider { 75 data, err := toml.Marshal(v) 76 if err != nil { 77 panic(err) 78 } 79 p := maps.Params{ 80 section: config.FromTOMLConfigString(string(data)).Get(""), 81 } 82 cfg := config.NewFrom(p) 83 return GetTestConfig(nil, cfg) 84 }