github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/supervisor/config/config.go (about) 1 /* 2 * Copyright (C) 2020 The "MysteriumNetwork/node" Authors. 3 * 4 * This program is free software: you can redistribute it and/or modify 5 * it under the terms of the GNU General Public License as published by 6 * the Free Software Foundation, either version 3 of the License, or 7 * (at your option) any later version. 8 * 9 * This program is distributed in the hope that it will be useful, 10 * but WITHOUT ANY WARRANTY; without even the implied warranty of 11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 * GNU General Public License for more details. 13 * 14 * You should have received a copy of the GNU General Public License 15 * along with this program. If not, see <http://www.gnu.org/licenses/>. 16 */ 17 18 package config 19 20 import ( 21 "errors" 22 "fmt" 23 "os" 24 "path/filepath" 25 "strings" 26 27 "github.com/BurntSushi/toml" 28 ) 29 30 const configFile = "myst_supervisor.conf" 31 32 // Config for supervisor, created during -install. 33 type Config struct { 34 Uid string 35 } 36 37 func (c Config) valid() bool { 38 return c.Uid != "" 39 } 40 41 // Write config file. 42 func (c Config) Write() error { 43 if !c.valid() { 44 return errors.New("configuration is not valid") 45 } 46 confPath, err := configPath() 47 if err != nil { 48 return err 49 } 50 51 var out strings.Builder 52 err = toml.NewEncoder(&out).Encode(c) 53 if err != nil { 54 return fmt.Errorf("could not encode configuration: %w", err) 55 } 56 if err := os.WriteFile(confPath, []byte(out.String()), 0700); err != nil { 57 return fmt.Errorf("could not write %q: %w", confPath, err) 58 } 59 return nil 60 } 61 62 // Read config file. 63 func Read() (*Config, error) { 64 confPath, err := configPath() 65 if err != nil { 66 return nil, err 67 } 68 69 c := Config{} 70 _, err = toml.DecodeFile(confPath, &c) 71 if err != nil { 72 return nil, fmt.Errorf("could not read %q: %w", confPath, err) 73 } 74 if !c.valid() { 75 return nil, fmt.Errorf("invalid configuration file %q, please re-install the supervisor (-install)", confPath) 76 } 77 return &c, nil 78 } 79 80 func configPath() (string, error) { 81 dir, err := configDir() 82 if err != nil { 83 return "", fmt.Errorf("could not determine config dir: %w", err) 84 } 85 return filepath.Join(dir, configFile), nil 86 }