Debian Codegraph @

config/testconfig/testconfig.go

raw
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 // This package should only be used for testing.
15 package testconfig
16
17 import (
18 _ "unsafe"
19
20 "github.com/gohugoio/hugo/common/hmaps"
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 "github.com/gohugoio/hugo/internal/warpc"
26 toml "github.com/pelletier/go-toml/v2"
27 "github.com/spf13/afero"
28 )
29
30 func GetTestConfigs(fs afero.Fs, cfg config.Provider) *allconfig.Configs {
31 if fs == nil {
32 fs = afero.NewMemMapFs()
33 }
34 if cfg == nil {
35 cfg = config.New()
36 }
37 // Make sure that the workingDir exists.
38 workingDir := cfg.GetString("workingDir")
39 if workingDir != "" {
40 if err := fs.MkdirAll(workingDir, 0o777); err != nil {
41 panic(err)
42 }
43 }
44
45 configs, err := allconfig.LoadConfig(allconfig.ConfigSourceDescriptor{Fs: fs, Flags: cfg, Environ: []string{"EMPTY_TEST_ENVIRONMENT"}})
46 if err != nil {
47 panic(err)
48 }
49 return configs
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 WasmDispatchers: warpc.AllDispatchers(
65 warpc.Options{
66 PoolSize: 1,
67 },
68 warpc.Options{
69 PoolSize: 1,
70 },
71 warpc.Options{
72 PoolSize: 1,
73 },
74 ),
75 }
76 for _, f := range beforeInit {
77 f(d)
78 }
79 if err := d.Init(); err != nil {
80 panic(err)
81 }
82 return d
83 }
84
85 func GetTestConfigSectionFromStruct(section string, v any) config.AllProvider {
86 data, err := toml.Marshal(v)
87 if err != nil {
88 panic(err)
89 }
90 p := hmaps.Params{
91 section: config.FromTOMLConfigString(string(data)).Get(""),
92 }
93 cfg := config.NewFrom(p)
94 return GetTestConfig(nil, cfg)
95 }