1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// SPDX-FileCopyrightText: 2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT
use std::{
fs,
path::{Path, PathBuf}
};
use serde::{Deserialize, Serialize};
use crate::error::TwcError;
/// Output format preference.
#[derive(Debug, Clone, Serialize, Deserialize, Default, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OutputPreference {
/// Human-readable table (default).
#[default]
Table,
/// Machine-readable JSON.
Json,
/// Minimal output.
Quiet
}
/// Dashboard customization preferences, persisted in the config file.
#[cfg(feature = "tui")]
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DashboardPrefs {
/// IDs of widgets the user has hidden from the layout.
#[serde(default)]
pub hidden_widgets: Vec<String>,
/// Resource-list panel width, as a percentage of the content area.
#[serde(default = "default_list_width")]
pub list_width_pct: u16,
/// Hide resource tabs that currently have no items.
#[serde(default)]
pub hide_empty_tabs: bool
}
#[cfg(feature = "tui")]
const fn default_list_width() -> u16 {
40
}
#[cfg(feature = "tui")]
impl Default for DashboardPrefs {
fn default() -> Self {
Self {
hidden_widgets: Vec::new(),
list_width_pct: default_list_width(),
hide_empty_tabs: false
}
}
}
/// UI language for the dashboard and CLI output. English is the default.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Language {
/// English (default).
#[default]
En,
/// Russian.
Ru
}
impl Language {
/// The `rust_i18n` locale code this language resolves to.
#[must_use]
pub const fn locale(self) -> &'static str {
match self {
Self::En => "en",
Self::Ru => "ru"
}
}
}
/// File-based configuration stored at `~/.config/twc-rs/config.toml`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppConfig {
/// Timeweb Cloud API token for the default profile.
#[serde(skip_serializing_if = "Option::is_none")]
pub token: Option<String>,
/// UI language (default English).
#[serde(default)]
pub language: Language,
/// Named profiles, mapping a profile name to its API token. Selected with
/// `--profile <name>` (or the `TWC_PROFILE` env var).
#[serde(default, skip_serializing_if = "std::collections::HashMap::is_empty")]
pub profiles: std::collections::HashMap<String, String>,
/// TUI color theme.
#[cfg(feature = "tui")]
#[serde(default)]
pub theme: crate::tui::themes::Theme,
/// Default output format.
#[serde(default, alias = "output")]
pub output: OutputPreference,
/// Default region for new servers.
#[serde(skip_serializing_if = "Option::is_none")]
pub default_region: Option<String>,
/// Auto-refresh interval in seconds for TUI monitor.
#[serde(default = "default_refresh_interval")]
pub refresh_interval: u64,
/// Dashboard layout customization.
#[cfg(feature = "tui")]
#[serde(default)]
pub dashboard: DashboardPrefs
}
const fn default_refresh_interval() -> u64 {
5
}
impl Default for AppConfig {
fn default() -> Self {
Self {
token: None,
profiles: std::collections::HashMap::new(),
language: Language::default(),
#[cfg(feature = "tui")]
theme: crate::tui::themes::Theme::default(),
output: OutputPreference::Table,
default_region: None,
refresh_interval: 5,
#[cfg(feature = "tui")]
dashboard: DashboardPrefs::default()
}
}
}
impl AppConfig {
/// Returns the token for the given profile, or the default token when no
/// profile is named.
///
/// # Errors
///
/// Returns [`TwcError::ConfigNotFound`] when the named profile does not
/// exist.
pub fn token_for(&self, profile: Option<&str>) -> Result<Option<String>, TwcError> {
profile.map_or_else(
|| Ok(self.token.clone()),
|name| {
self.profiles.get(name).cloned().map(Some).ok_or_else(|| {
TwcError::ConfigNotFound(format!("profile '{name}' not found in config"))
})
}
)
}
/// Returns the path to the configuration file.
///
/// # Overview
///
/// Resolves `~/.config/twc-rs/config.toml` using the `dirs` crate.
///
/// # Errors
///
/// Returns [`TwcError::ConfigNotFound`] when the config directory
/// cannot be determined by the OS.
pub fn path() -> Result<PathBuf, TwcError> {
let dir = dirs::config_dir().ok_or_else(|| {
TwcError::ConfigNotFound("unable to determine config directory".to_string())
})?;
Ok(dir.join("twc-rs").join("config.toml"))
}
/// Loads the configuration from disk.
///
/// # Overview
///
/// Reads and deserializes the TOML config file. Returns default
/// configuration when the file does not exist. Creates the config
/// file with defaults on first access.
///
/// # Errors
///
/// Returns [`TwcError::ConfigNotFound`] or [`TwcError::ConfigParse`]
/// on read / deserialization failure.
pub fn load() -> Result<Self, TwcError> {
let path = Self::path()?;
if !path.exists() {
let cfg = Self::default();
cfg.save()?;
return Ok(cfg);
}
let content = fs::read_to_string(&path)
.map_err(|e| TwcError::ConfigNotFound(format!("{}: {e}", path.display())))?;
let config: Self = toml::from_str(&content)?;
Ok(config)
}
/// Persists the configuration to disk.
///
/// # Overview
///
/// Creates parent directories as needed, then writes the TOML file.
///
/// # Errors
///
/// Returns [`TwcError::ConfigWrite`] on serialization or I/O failure.
pub fn save(&self) -> Result<(), TwcError> {
self.save_to(&Self::path()?)
}
/// Persists the configuration to a specific path.
///
/// # Overview
///
/// Creates parent directories as needed, then writes the TOML file to
/// `path`. Used by callers that manage their own config location (and by
/// tests, to avoid touching the real user config).
///
/// # Errors
///
/// Returns [`TwcError::ConfigWrite`] on serialization or I/O failure.
pub fn save_to(&self, path: &Path) -> Result<(), TwcError> {
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).map_err(|e| {
TwcError::ConfigWrite(format!("failed to create dir {}: {e}", parent.display()))
})?;
}
let content = toml::to_string_pretty(self)?;
fs::write(path, content).map_err(|e| {
TwcError::ConfigWrite(format!("failed to write {}: {e}", path.display()))
})?;
Ok(())
}
}
#[cfg(test)]
mod tests;