config

package
v1.0.16 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 2, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package config provides configuration management for the pvetui application.

This package handles loading configuration from multiple sources with proper precedence ordering:

  1. Command-line flags (highest priority)
  2. Environment variables
  3. Configuration files (YAML format)
  4. Default values (lowest priority)

The package follows platform-appropriate standards for configuration and cache file locations, providing a clean and predictable user experience across Windows, macOS, and Linux.

Configuration Sources:

Environment Variables:

  • PROXMOX_ADDR: Proxmox server URL
  • PROXMOX_USER: Username for authentication
  • PROXMOX_PASSWORD: Password for password-based auth
  • PROXMOX_TOKEN_ID: API token ID for token-based auth
  • PROXMOX_TOKEN_SECRET: API token secret
  • PROXMOX_REALM: Authentication realm (default: "pam")
  • PROXMOX_INSECURE: Skip TLS verification ("true"/"false")
  • PROXMOX_DEBUG: Enable debug logging ("true"/"false")
  • PROXMOX_CACHE_DIR: Custom cache directory (overrides platform defaults)

Configuration File Format (YAML):

addr: "https://pve.example.com:8006"
user: "root"
password: "secret"
realm: "pam"
insecure: false
debug: true
cache_dir: "/custom/cache/path"  # Optional: overrides platform defaults

Platform Directory Support:

The package automatically determines appropriate directories for configuration and cache files based on platform standards:

  • Windows: Config in %APPDATA%/pvetui, Cache in %LOCALAPPDATA%/pvetui
  • macOS: Config in $XDG_CONFIG_HOME/pvetui or ~/.config/pvetui, Cache in $XDG_CACHE_HOME/pvetui or ~/.cache/pvetui
  • Linux: Config in $XDG_CONFIG_HOME/pvetui or ~/.config/pvetui, Cache in $XDG_CACHE_HOME/pvetui or ~/.cache/pvetui

Authentication Methods:

The package supports both password and API token authentication:

  • Password: Requires user + password + realm
  • API Token: Requires user + token_id + token_secret + realm

Example usage:

// Load configuration with automatic source detection
config := NewConfig()
config.ParseFlags()

// Merge with config file if specified
if configPath != "" {
	err := config.MergeWithFile(configPath)
	if err != nil {
		log.Fatal("Failed to load config file:", err)
	}
}

// Set defaults and validate
config.SetDefaults()
if err := config.Validate(); err != nil {
	log.Fatal("Invalid configuration:", err)
}

Package config provides encryption utilities for sensitive configuration fields.

This module implements age-based encryption for sensitive data when SOPS is not used. It allows users to manually edit config files with cleartext, which will be automatically encrypted after successful connection verification.

Package config provides file operations for configuration management.

This file contains file-related functions that were previously part of the main config.go file.

Package config provides profile management functionality.

This file contains profile-related types and functions that were previously part of the main config.go file.

Index

Constants

This section is empty.

Variables

View Source
var DebugEnabled bool

DebugEnabled is a global flag to enable debug logging throughout the application.

This variable is set during configuration parsing and used by various components to determine whether to emit debug-level log messages.

Functions

func CreateDefaultConfigFile

func CreateDefaultConfigFile() (string, error)

CreateDefaultConfigFile creates a default configuration file and returns its path.

func CreateDefaultConfigFileAt added in v1.0.16

func CreateDefaultConfigFileAt(path string) (string, error)

CreateDefaultConfigFileAt writes the default configuration template to the provided path.

Parameters:

  • path: Full path where the config file should be created.

This function is safe to call multiple times; if the file already exists it returns the existing path without modifying it.

Example usage:

configPath := filepath.Join(os.TempDir(), "pvetui-config.yml")
_, err := CreateDefaultConfigFileAt(configPath)
if err != nil {
	log.Fatalf("create config: %v", err)
}

func DecryptConfigSensitiveFields added in v1.0.10

func DecryptConfigSensitiveFields(cfg *Config) error

DecryptConfigSensitiveFields decrypts sensitive fields in the entire Config. This includes both profile-based and legacy fields.

func DecryptField added in v1.0.10

func DecryptField(value string) (string, error)

DecryptField decrypts an encrypted field value. Returns the decrypted value, or the original value if not encrypted.

func DecryptSensitiveFields added in v1.0.10

func DecryptSensitiveFields(profile *ProfileConfig) error

DecryptSensitiveFields decrypts all sensitive fields in a ProfileConfig. Fields that are not encrypted are left unchanged.

func EncryptConfigSensitiveFields added in v1.0.10

func EncryptConfigSensitiveFields(cfg *Config) error

EncryptConfigSensitiveFields encrypts sensitive fields in the entire Config. This includes both profile-based and legacy fields.

func EncryptField added in v1.0.10

func EncryptField(value string) (string, error)

EncryptField encrypts a sensitive field value using age encryption. Returns the encrypted value with the encryption prefix, or an error.

func EncryptSensitiveFields added in v1.0.10

func EncryptSensitiveFields(profile *ProfileConfig) error

EncryptSensitiveFields encrypts all sensitive fields in a ProfileConfig. Fields that are already encrypted are left unchanged.

func ExpandHomePath added in v1.0.16

func ExpandHomePath(path string) string

ExpandHomePath expands a leading ~ in paths using the current user's home directory.

func FindDefaultConfigPath

func FindDefaultConfigPath() (string, bool)

FindDefaultConfigPath finds the default configuration file path.

func FindSOPSRule

func FindSOPSRule(startDir string) bool

FindSOPSRule checks if a SOPS rule file exists in the given directory or its parents.

func GetDefaultConfigPath

func GetDefaultConfigPath() string

GetDefaultConfigPath returns the default configuration file path.

func IsSOPSEncrypted

func IsSOPSEncrypted(path string, data []byte) bool

IsSOPSEncrypted checks if a file is SOPS-encrypted.

func ParseConfigFlags

func ParseConfigFlags()

func SaveConfigFile added in v1.0.10

func SaveConfigFile(cfg *Config, path string) error

SaveConfigFile saves the config to a file with optional encryption (if not using SOPS). This is a lower-level function that can be used from packages that can't import UI components.

func SetAgeDirOverride added in v1.0.16

func SetAgeDirOverride(dir string)

SetAgeDirOverride sets the directory used for storing age identity and recipient files. Provide an empty string to reset to the default config directory.

func ValidateKeyBindings

func ValidateKeyBindings(kb KeyBindings) error

ValidateKeyBindings checks if all key specifications are valid.

Types

type Config

type Config struct {
	Profiles       map[string]ProfileConfig `yaml:"profiles"`
	DefaultProfile string                   `yaml:"default_profile"`
	// ActiveProfile holds the currently active profile at runtime.
	// It is not persisted to disk and is used to resolve getters when set.
	ActiveProfile string `yaml:"-"`

	// The following fields are global settings, not per-profile
	Debug    bool   `yaml:"debug"`
	CacheDir string `yaml:"cache_dir"`
	// AgeDir overrides the directory used to store age identity and recipient files.
	AgeDir      string       `yaml:"age_dir,omitempty"`
	KeyBindings KeyBindings  `yaml:"key_bindings"`
	Theme       ThemeConfig  `yaml:"theme"`
	Plugins     PluginConfig `yaml:"plugins"`
	// Deprecated: legacy single-profile fields for migration
	Addr        string `yaml:"addr"`
	User        string `yaml:"user"`
	Password    string `yaml:"password"`
	TokenID     string `yaml:"token_id"`
	TokenSecret string `yaml:"token_secret"`
	Realm       string `yaml:"realm"`
	ApiPath     string `yaml:"api_path"`
	Insecure    bool   `yaml:"insecure"`
	SSHUser     string `yaml:"ssh_user"`
	VMSSHUser   string `yaml:"vm_ssh_user"`
	// contains filtered or unexported fields
}

Config represents the complete application configuration, including multiple profiles.

func NewConfig

func NewConfig() *Config

NewConfig creates a new Config instance populated with values from environment variables.

This function reads all supported environment variables and creates a Config with those values. Environment variables that are not set will result in zero values for the corresponding fields.

Environment variables read:

  • PVETUI_ADDR: Server URL
  • PVETUI_USER: Username
  • PVETUI_PASSWORD: Password for password auth
  • PVETUI_TOKEN_ID: Token ID for token auth
  • PVETUI_TOKEN_SECRET: Token secret for token auth
  • PVETUI_REALM: Authentication realm (default: "pam")
  • PVETUI_API_PATH: API base path (default: "/api2/json")
  • PVETUI_INSECURE: Skip TLS verification ("true"/"false")
  • PVETUI_SSH_USER: SSH username
  • PVETUI_AGE_DIR: Custom age key directory (overrides platform defaults)
  • PVETUI_DEBUG: Enable debug logging ("true"/"false")
  • PVETUI_CACHE_DIR: Custom cache directory (overrides platform defaults)

The returned Config should typically be further configured with command-line flags and/or configuration files before validation.

Returns a new Config instance with environment variable values.

Example usage:

config := NewConfig()
config.ParseFlags()
config.SetDefaults()
if err := config.Validate(); err != nil {
	log.Fatal("Invalid config:", err)
}

func (*Config) ApplyProfile

func (c *Config) ApplyProfile(profileName string) error

ApplyProfile applies the settings from a named profile to the main config.

func (*Config) FindGroupProfileNameConflicts added in v1.0.15

func (c *Config) FindGroupProfileNameConflicts() []string

FindGroupProfileNameConflicts returns group names that also exist as profile names.

func (*Config) GetAPIToken

func (c *Config) GetAPIToken() string

GetAPIToken returns the full API token string in the format required by Proxmox Format: PVEAPIToken=USER@REALM!TOKENID=SECRET.

func (*Config) GetActiveProfile

func (c *Config) GetActiveProfile() string

GetActiveProfile returns the name of the currently active profile.

func (*Config) GetAddr

func (c *Config) GetAddr() string

GetAddr returns the configured server address.

func (*Config) GetGroups added in v1.0.14

func (c *Config) GetGroups() map[string][]string

GetGroups returns a map of group names to their member profile names. Only includes profiles that have non-empty Groups.

func (*Config) GetInsecure

func (c *Config) GetInsecure() bool

GetInsecure returns the configured insecure flag.

func (*Config) GetPassword

func (c *Config) GetPassword() string

GetPassword returns the configured password.

func (*Config) GetProfileNames

func (c *Config) GetProfileNames() []string

GetProfileNames returns a list of available profile names.

func (*Config) GetProfileNamesInGroup added in v1.0.14

func (c *Config) GetProfileNamesInGroup(groupName string) []string

GetProfileNamesInGroup returns profile names belonging to a specific group.

func (*Config) GetProfilesInGroup added in v1.0.14

func (c *Config) GetProfilesInGroup(groupName string) []ProfileConfig

GetProfilesInGroup returns all profiles belonging to a specific group.

func (*Config) GetRealm

func (c *Config) GetRealm() string

GetRealm returns the configured realm.

func (*Config) GetTokenID

func (c *Config) GetTokenID() string

GetTokenID returns the configured token ID.

func (*Config) GetTokenSecret

func (c *Config) GetTokenSecret() string

GetTokenSecret returns the configured token secret.

func (*Config) GetUser

func (c *Config) GetUser() string

GetUser returns the configured username.

func (*Config) HasCleartextSensitiveData added in v1.0.11

func (c *Config) HasCleartextSensitiveData() bool

func (*Config) HasGroups added in v1.0.14

func (c *Config) HasGroups() bool

HasGroups returns true if any profiles are configured with groups.

func (*Config) HasProfiles

func (c *Config) HasProfiles() bool

HasProfiles returns true if the configuration has any profiles defined.

func (*Config) IsGroup added in v1.0.14

func (c *Config) IsGroup(name string) bool

IsGroup checks if a name refers to a group rather than a profile.

func (*Config) IsUsingTokenAuth

func (c *Config) IsUsingTokenAuth() bool

IsUsingTokenAuth returns true if the configuration is set up for API token authentication.

func (*Config) MarkSensitiveDataEncrypted added in v1.0.11

func (c *Config) MarkSensitiveDataEncrypted()

func (*Config) MarshalYAML added in v1.0.11

func (cfg *Config) MarshalYAML() (any, error)

MarshalYAML implements yaml.Marshaler to ensure legacy single-profile fields are omitted when profile-based configuration is in use.

func (*Config) MergeWithFile

func (c *Config) MergeWithFile(path string) error

func (*Config) MigrateLegacyToProfiles

func (c *Config) MigrateLegacyToProfiles() bool

MigrateLegacyToProfiles migrates legacy configuration fields to the new profile system.

func (*Config) SetDefaults

func (c *Config) SetDefaults()

SetDefaults sets default values for unspecified configuration options.

func (*Config) Validate

func (c *Config) Validate() error

func (*Config) ValidateGroups added in v1.0.14

func (c *Config) ValidateGroups() error

ValidateGroups checks that group configurations are valid.

type KeyBindings

type KeyBindings struct {
	SwitchView        string `yaml:"switch_view"` // Switch between pages
	SwitchViewReverse string `yaml:"switch_view_reverse"`
	NodesPage         string `yaml:"nodes_page"`   // Jump to Nodes page
	GuestsPage        string `yaml:"guests_page"`  // Jump to Guests page
	TasksPage         string `yaml:"tasks_page"`   // Jump to Tasks page
	Menu              string `yaml:"menu"`         // Open context menu
	GlobalMenu        string `yaml:"global_menu"`  // Open global context menu
	Shell             string `yaml:"shell"`        // Open shell session
	VNC               string `yaml:"vnc"`          // Open VNC console
	Refresh           string `yaml:"refresh"`      // Manual refresh
	AutoRefresh       string `yaml:"auto_refresh"` // Toggle auto-refresh
	Search            string `yaml:"search"`       // Activate search
	Help              string `yaml:"help"`         // Toggle help modal
	Quit              string `yaml:"quit"`         // Quit application
}

KeyBindings defines customizable key mappings for common actions. Each field represents a single keyboard key that triggers the action. Only single characters and function keys (e.g. "F1") are supported.

func DefaultKeyBindings

func DefaultKeyBindings() KeyBindings

DefaultKeyBindings returns a KeyBindings struct with the default key mappings.

type PluginConfig added in v1.0.7

type PluginConfig struct {
	// Enabled lists plugin identifiers that should be activated.
	Enabled []string `yaml:"enabled"`
}

PluginConfig holds plugin related configuration options.

type ProfileConfig

type ProfileConfig struct {
	Addr        string `yaml:"addr"`
	User        string `yaml:"user"`
	Password    string `yaml:"password"`
	TokenID     string `yaml:"token_id"`
	TokenSecret string `yaml:"token_secret"`
	Realm       string `yaml:"realm"`
	ApiPath     string `yaml:"api_path"`
	Insecure    bool   `yaml:"insecure"`
	SSHUser     string `yaml:"ssh_user"`
	VMSSHUser   string `yaml:"vm_ssh_user"`

	// Groups is a list of group identifiers.
	// This allows a profile to belong to multiple groups.
	// Profiles in the same group will be combined into a single "group cluster" view.
	Groups []string `yaml:"groups,omitempty"`
}

ProfileConfig holds a single connection profile's settings.

func (*ProfileConfig) Validate

func (p *ProfileConfig) Validate() error

Validate validates a single profile configuration.

type ThemeConfig

type ThemeConfig struct {
	// Name specifies the built-in theme to use as a base (e.g., "default", "catppuccin-mocha").
	// If empty, defaults to "default".
	Name string `yaml:"name"`
	// Colors specifies the color overrides for theme elements.
	// Users can use any tcell-supported color value (ANSI name, W3C name, or hex code).
	Colors map[string]string `yaml:"colors"`
}

ThemeConfig defines theme-related configuration options.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL