Path: blob/main/components/local-app/pkg/config/config.go
2500 views
// Copyright (c) 2023 Gitpod GmbH. All rights reserved.1// Licensed under the GNU Affero General Public License (AGPL).2// See License.AGPL.txt in the project root for license information.34package config56import (7"context"8"fmt"9"os"10"path/filepath"11"strings"1213"github.com/gitpod-io/local-app/pkg/telemetry"14"gopkg.in/yaml.v3"15)1617const DEFAULT_LOCATION = "~/.gitpod/config.yaml"1819type Config struct {20Filename string `yaml:"-"`2122ActiveContext string `yaml:"activeContext,omitempty"`23Contexts map[string]*ConnectionContext24Telemetry Telemetry `yaml:"telemetry"`25Autoupdate bool `yaml:"autoupdate"`26}2728type Telemetry struct {29Enabled bool `yaml:"enabled"`30Identity string `yaml:"identity,omitempty"`31}3233func FromBool(v *bool) bool {34if v == nil {35return false36}37return *v38}3940func Bool(v bool) *bool {41return &v42}4344func SaveConfig(fn string, cfg *Config) error {45fc, err := yaml.Marshal(cfg)46if err != nil {47return err48}49_ = os.MkdirAll(filepath.Dir(fn), 0755)5051err = os.WriteFile(fn, fc, 0644)52if err != nil {53return err54}55return nil56}5758func DefaultConfig() *Config {59return &Config{60Filename: DEFAULT_LOCATION,61Contexts: make(map[string]*ConnectionContext),62}63}6465// LoadConfig loads the configuration from a file. If the file does not exist, it returns a default configuration.66// This function never returns nil, even in case of an error. If an error is returned, this function also returns the default configuration.67func LoadConfig(fn string) (res *Config, err error) {68defer func() {69if err != nil {70err = fmt.Errorf("failed to load config from %s: %w", fn, err)71}72}()7374if strings.HasPrefix(fn, "~/") {75homeDir, err := os.UserHomeDir()76if err != nil {77return nil, err78}79fn = filepath.Join(homeDir, fn[2:])80}8182cfg := &Config{83Filename: fn,84Contexts: make(map[string]*ConnectionContext),85Telemetry: Telemetry{86Enabled: !telemetry.DoNotTrack(),87Identity: telemetry.GenerateIdentity(),88},89Autoupdate: true,90}91fc, err := os.ReadFile(fn)92if err != nil {93return cfg, err94}95err = yaml.Unmarshal(fc, &cfg)96if err != nil {97return cfg, err98}99100return cfg, nil101}102103type configContextKeyTpe struct{}104105var configContextKey = configContextKeyTpe{}106107func ToContext(ctx context.Context, cfg *Config) context.Context {108return context.WithValue(ctx, configContextKey, cfg)109}110111func FromContext(ctx context.Context) *Config {112cfg, _ := ctx.Value(configContextKey).(*Config)113return cfg114}115116117