Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
gitpod-io
GitHub Repository: gitpod-io/gitpod
Path: blob/main/components/local-app/pkg/config/config.go
2500 views
1
// Copyright (c) 2023 Gitpod GmbH. All rights reserved.
2
// Licensed under the GNU Affero General Public License (AGPL).
3
// See License.AGPL.txt in the project root for license information.
4
5
package config
6
7
import (
8
"context"
9
"fmt"
10
"os"
11
"path/filepath"
12
"strings"
13
14
"github.com/gitpod-io/local-app/pkg/telemetry"
15
"gopkg.in/yaml.v3"
16
)
17
18
const DEFAULT_LOCATION = "~/.gitpod/config.yaml"
19
20
type Config struct {
21
Filename string `yaml:"-"`
22
23
ActiveContext string `yaml:"activeContext,omitempty"`
24
Contexts map[string]*ConnectionContext
25
Telemetry Telemetry `yaml:"telemetry"`
26
Autoupdate bool `yaml:"autoupdate"`
27
}
28
29
type Telemetry struct {
30
Enabled bool `yaml:"enabled"`
31
Identity string `yaml:"identity,omitempty"`
32
}
33
34
func FromBool(v *bool) bool {
35
if v == nil {
36
return false
37
}
38
return *v
39
}
40
41
func Bool(v bool) *bool {
42
return &v
43
}
44
45
func SaveConfig(fn string, cfg *Config) error {
46
fc, err := yaml.Marshal(cfg)
47
if err != nil {
48
return err
49
}
50
_ = os.MkdirAll(filepath.Dir(fn), 0755)
51
52
err = os.WriteFile(fn, fc, 0644)
53
if err != nil {
54
return err
55
}
56
return nil
57
}
58
59
func DefaultConfig() *Config {
60
return &Config{
61
Filename: DEFAULT_LOCATION,
62
Contexts: make(map[string]*ConnectionContext),
63
}
64
}
65
66
// LoadConfig loads the configuration from a file. If the file does not exist, it returns a default configuration.
67
// This function never returns nil, even in case of an error. If an error is returned, this function also returns the default configuration.
68
func LoadConfig(fn string) (res *Config, err error) {
69
defer func() {
70
if err != nil {
71
err = fmt.Errorf("failed to load config from %s: %w", fn, err)
72
}
73
}()
74
75
if strings.HasPrefix(fn, "~/") {
76
homeDir, err := os.UserHomeDir()
77
if err != nil {
78
return nil, err
79
}
80
fn = filepath.Join(homeDir, fn[2:])
81
}
82
83
cfg := &Config{
84
Filename: fn,
85
Contexts: make(map[string]*ConnectionContext),
86
Telemetry: Telemetry{
87
Enabled: !telemetry.DoNotTrack(),
88
Identity: telemetry.GenerateIdentity(),
89
},
90
Autoupdate: true,
91
}
92
fc, err := os.ReadFile(fn)
93
if err != nil {
94
return cfg, err
95
}
96
err = yaml.Unmarshal(fc, &cfg)
97
if err != nil {
98
return cfg, err
99
}
100
101
return cfg, nil
102
}
103
104
type configContextKeyTpe struct{}
105
106
var configContextKey = configContextKeyTpe{}
107
108
func ToContext(ctx context.Context, cfg *Config) context.Context {
109
return context.WithValue(ctx, configContextKey, cfg)
110
}
111
112
func FromContext(ctx context.Context) *Config {
113
cfg, _ := ctx.Value(configContextKey).(*Config)
114
return cfg
115
}
116
117