FemaInstaller/pkg/config/updater_config.go

76 lines
2.3 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package config
import (
"encoding/json"
"fmt"
"os"
)
// UpdaterConfig holds the configuration for the updater application
type UpdaterConfig struct {
IP string `json:"ip"`
Port string `json:"port"`
Login string `json:"login"`
Password string `json:"password"`
DownloadURL string `json:"downloadUrl"`
}
// NewUpdaterConfig creates a new updater configuration with default values
func NewUpdaterConfig() *UpdaterConfig {
return &UpdaterConfig{
IP: "127.0.0.1",
Port: "22",
Login: "root",
Password: "",
DownloadURL: "http://example.com/fema/build",
}
}
// LoadUpdaterConfig loads the updater configuration from a file
func LoadUpdaterConfig(filePath string) (*UpdaterConfig, error) {
// Check if file exists
if _, err := os.Stat(filePath); os.IsNotExist(err) {
// Create default config if file doesn't exist
config := NewUpdaterConfig()
if err := SaveUpdaterConfig(config, filePath); err != nil {
return nil, fmt.Errorf("не удалось создать конфигурационный файл: %w", err)
}
return config, nil
}
// Read file
data, err := os.ReadFile(filePath)
if err != nil {
return nil, fmt.Errorf("не удалось прочитать конфигурационный файл: %w", err)
}
// Parse JSON
var config UpdaterConfig
if err := json.Unmarshal(data, &config); err != nil {
return nil, fmt.Errorf("не удалось разобрать конфигурационный файл: %w", err)
}
return &config, nil
}
// SaveUpdaterConfig saves the updater configuration to a file
func SaveUpdaterConfig(config *UpdaterConfig, filePath string) error {
// Marshal JSON
data, err := json.MarshalIndent(config, "", " ")
if err != nil {
return fmt.Errorf("не удалось сериализовать конфигурацию: %w", err)
}
// Write file
if err := os.WriteFile(filePath, data, 0644); err != nil {
return fmt.Errorf("не удалось записать конфигурационный файл: %w", err)
}
return nil
}
// String returns a string representation of the updater configuration
func (c *UpdaterConfig) String() string {
return fmt.Sprintf("IP: %s\nПорт: %s\nЛогин: %s\nПароль: %s\nURL загрузки: %s", c.IP, c.Port, c.Login, c.Password, c.DownloadURL)
}