github.com/mysteriumnetwork/node@v0.0.0-20240516044423-365054f76801/mobile/mysterium/config.go (about)

     1  /*
     2   * Copyright (C) 2021 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 mysterium
    19  
    20  import (
    21  	"fmt"
    22  	"os"
    23  
    24  	"github.com/rs/zerolog/log"
    25  
    26  	"github.com/mysteriumnetwork/node/config"
    27  )
    28  
    29  const userConfigFilename = "user-config.toml"
    30  
    31  func loadUserConfig(dataDir string) error {
    32  	if err := createDirIfNotExists(dataDir); err != nil {
    33  		return err
    34  	}
    35  
    36  	userConfigPath := dataDir + "/" + userConfigFilename
    37  	if err := createFileIfNotExists(userConfigPath); err != nil {
    38  		return err
    39  	}
    40  	if err := config.Current.LoadUserConfig(userConfigPath); err != nil {
    41  		return err
    42  	}
    43  
    44  	return nil
    45  }
    46  
    47  func createDirIfNotExists(dir string) error {
    48  	err := dirExists(dir)
    49  	if os.IsNotExist(err) {
    50  		log.Info().Msg("Directory does not exist, creating a new one: " + dir)
    51  		return os.MkdirAll(dir, 0700)
    52  	}
    53  	return err
    54  }
    55  
    56  func createFileIfNotExists(filePath string) error {
    57  	if _, err := os.Stat(filePath); os.IsNotExist(err) {
    58  		log.Info().Msg("Config file does not exist, attempting to create: " + filePath)
    59  		_, err := os.Create(filePath)
    60  		if err != nil {
    61  			return fmt.Errorf("failed to create config file %w", err)
    62  		}
    63  	}
    64  	return nil
    65  }
    66  
    67  func dirExists(dir string) error {
    68  	fileStat, err := os.Stat(dir)
    69  	if err != nil {
    70  		return err
    71  	}
    72  	if isDir := fileStat.IsDir(); !isDir {
    73  		return fmt.Errorf("directory expected: %s", dir)
    74  	}
    75  	return nil
    76  }
    77  
    78  func setUserConfig(key, value string) error {
    79  	config.Current.SetUser(key, value)
    80  	return config.Current.SaveUserConfig()
    81  }
    82  
    83  func setUserConfigRaw(key string, value interface{}) {
    84  	config.Current.SetUser(key, value)
    85  }