Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
lima-vm
GitHub Repository: lima-vm/lima
Path: blob/master/pkg/limayaml/load.go
2601 views
1
// SPDX-FileCopyrightText: Copyright The Lima Authors
2
// SPDX-License-Identifier: Apache-2.0
3
4
package limayaml
5
6
import (
7
"context"
8
"errors"
9
"fmt"
10
"os"
11
"path/filepath"
12
13
"github.com/sirupsen/logrus"
14
15
"github.com/lima-vm/lima/v2/pkg/limatype"
16
"github.com/lima-vm/lima/v2/pkg/limatype/dirnames"
17
"github.com/lima-vm/lima/v2/pkg/limatype/filenames"
18
)
19
20
// Load loads the yaml and fulfills unspecified fields with the default values.
21
//
22
// Load does not validate. Use Validate for validation.
23
func Load(ctx context.Context, b []byte, filePath string) (*limatype.LimaYAML, error) {
24
return load(ctx, b, filePath, false)
25
}
26
27
// LoadWithWarnings will call FillDefaults with warnings enabled (e.g. when
28
// the username is not valid on Linux and must be replaced by "Lima").
29
// It is called when creating or editing an instance.
30
func LoadWithWarnings(ctx context.Context, b []byte, filePath string) (*limatype.LimaYAML, error) {
31
return load(ctx, b, filePath, true)
32
}
33
34
func load(ctx context.Context, b []byte, filePath string, warn bool) (*limatype.LimaYAML, error) {
35
var y, d, o limatype.LimaYAML
36
37
if err := Unmarshal(b, &y, fmt.Sprintf("main file %q", filePath)); err != nil {
38
return nil, err
39
}
40
configDir, err := dirnames.LimaConfigDir()
41
if err != nil {
42
return nil, err
43
}
44
45
defaultPath := filepath.Join(configDir, filenames.Default)
46
bytes, err := os.ReadFile(defaultPath)
47
if err == nil {
48
logrus.Debugf("Mixing %q into %q", defaultPath, filePath)
49
if err := Unmarshal(bytes, &d, fmt.Sprintf("default file %q", defaultPath)); err != nil {
50
return nil, err
51
}
52
} else if !errors.Is(err, os.ErrNotExist) {
53
return nil, err
54
}
55
56
overridePath := filepath.Join(configDir, filenames.Override)
57
bytes, err = os.ReadFile(overridePath)
58
if err == nil {
59
logrus.Debugf("Mixing %q into %q", overridePath, filePath)
60
if err := Unmarshal(bytes, &o, fmt.Sprintf("override file %q", overridePath)); err != nil {
61
return nil, err
62
}
63
} else if !errors.Is(err, os.ErrNotExist) {
64
return nil, err
65
}
66
67
// It should be called before the `y` parameter is passed to FillDefault() that execute template.
68
if err := validateParamIsUsed(&y); err != nil {
69
return nil, err
70
}
71
72
FillDefault(ctx, &y, &d, &o, filePath, warn)
73
74
return &y, nil
75
}
76
77