expensive 0.2.2

Terminal dashboard for OpenCode token usage and spend
Documentation
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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
//! Configuration loading for the `expensive` binary.
//!
//! This module resolves CLI flags, optional TOML config, and OpenCode database
//! discovery into a single [`Config`]. The intended precedence is:
//! command-line arguments, config file values, then built-in defaults.

use std::{
    env, fmt, fs,
    path::{Path, PathBuf},
    process::Command,
    str::FromStr,
    time::Duration,
};

use anyhow::{anyhow, Context, Result};
use clap::{Parser, ValueEnum};
use serde::Deserialize;

use crate::time_window::{DailyStart, WeekStart};

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
pub enum Scope {
    All,
}

impl Scope {
    pub fn key(self) -> &'static str {
        match self {
            Self::All => "all",
        }
    }
}

impl fmt::Display for Scope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.key())
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
pub enum ColorTheme {
    #[default]
    Aurora,
    Ember,
    Ocean,
    Forest,
    Graphite,
}

impl ColorTheme {
    pub const ALL: [Self; 5] = [
        Self::Aurora,
        Self::Ember,
        Self::Ocean,
        Self::Forest,
        Self::Graphite,
    ];

    pub fn key(self) -> &'static str {
        match self {
            Self::Aurora => "aurora",
            Self::Ember => "ember",
            Self::Ocean => "ocean",
            Self::Forest => "forest",
            Self::Graphite => "graphite",
        }
    }

    pub fn title(self) -> &'static str {
        match self {
            Self::Aurora => "Aurora",
            Self::Ember => "Ember",
            Self::Ocean => "Ocean",
            Self::Forest => "Forest",
            Self::Graphite => "Graphite",
        }
    }
}

impl fmt::Display for ColorTheme {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.key())
    }
}

impl FromStr for ColorTheme {
    type Err = anyhow::Error;

    fn from_str(value: &str) -> Result<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "aurora" => Ok(Self::Aurora),
            "ember" => Ok(Self::Ember),
            "ocean" => Ok(Self::Ocean),
            "forest" => Ok(Self::Forest),
            "graphite" => Ok(Self::Graphite),
            _ => Err(anyhow!(
                "unsupported color theme {value:?}; expected aurora, ember, ocean, forest, or graphite"
            )),
        }
    }
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq, ValueEnum)]
pub enum ThemeScope {
    #[default]
    Calendar,
    All,
}

impl ThemeScope {
    pub fn key(self) -> &'static str {
        match self {
            Self::Calendar => "calendar",
            Self::All => "all",
        }
    }

    pub fn title(self) -> &'static str {
        match self {
            Self::Calendar => "Calendar only",
            Self::All => "Entire TUI",
        }
    }
}

impl fmt::Display for ThemeScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.key())
    }
}

impl FromStr for ThemeScope {
    type Err = anyhow::Error;

    fn from_str(value: &str) -> Result<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "calendar" | "heatmap" => Ok(Self::Calendar),
            "all" | "tui" => Ok(Self::All),
            _ => Err(anyhow!(
                "unsupported theme scope {value:?}; expected calendar or all"
            )),
        }
    }
}

#[derive(Debug, Parser)]
#[command(author, version, about = "OpenCode token and cost dashboard")]
pub struct Cli {
    #[arg(long, value_name = "PATH")]
    pub db: Option<PathBuf>,

    #[arg(long, value_name = "HH:MM")]
    pub daily_start: Option<DailyStart>,

    #[arg(long, value_name = "monday|sunday")]
    pub week_start: Option<WeekStart>,

    #[arg(long, value_name = "SECONDS")]
    pub refresh: Option<u64>,

    #[arg(long)]
    pub no_refresh: bool,

    #[arg(long, value_enum)]
    pub scope: Option<Scope>,

    #[arg(long, value_enum)]
    pub color_theme: Option<ColorTheme>,

    #[arg(long, value_enum)]
    pub theme_scope: Option<ThemeScope>,
}

#[derive(Clone, Debug)]
pub struct Config {
    pub db_path: PathBuf,
    pub config_path: Option<PathBuf>,
    pub daily_start: DailyStart,
    pub week_start: WeekStart,
    pub refresh_interval: Duration,
    pub auto_refresh: bool,
    pub scope: Scope,
    pub color_theme: ColorTheme,
    pub theme_scope: ThemeScope,
}

#[derive(Debug, Default, Deserialize)]
struct FileConfig {
    daily_start: Option<String>,
    week_start: Option<String>,
    refresh_seconds: Option<u64>,
    auto_refresh: Option<bool>,
    scope: Option<String>,
    color_theme: Option<String>,
    theme_scope: Option<String>,
}

pub fn load(cli: Cli) -> Result<Config> {
    let file_config = load_file_config()?;
    let db_path = discover_db_path(cli.db.clone());
    resolve_config(cli, file_config, db_path, config_path())
}

fn resolve_config(
    cli: Cli,
    file_config: FileConfig,
    db_path: PathBuf,
    config_path: Option<PathBuf>,
) -> Result<Config> {
    let daily_start = match (cli.daily_start, file_config.daily_start.as_deref()) {
        (Some(value), _) => value,
        (None, Some(value)) => value.parse()?,
        (None, None) => DailyStart::default(),
    };

    let week_start = match (cli.week_start, file_config.week_start.as_deref()) {
        (Some(value), _) => value,
        (None, Some(value)) => value.parse()?,
        (None, None) => WeekStart::default(),
    };

    let refresh_seconds = cli.refresh.or(file_config.refresh_seconds).unwrap_or(60);
    if refresh_seconds == 0 {
        return Err(anyhow!("refresh interval must be at least 1 second"));
    }
    let auto_refresh = if cli.no_refresh {
        false
    } else {
        file_config.auto_refresh.unwrap_or(true)
    };

    let scope = match (cli.scope, file_config.scope.as_deref()) {
        (Some(value), _) => value,
        (None, Some("all")) | (None, None) => Scope::All,
        (None, Some(value)) => {
            return Err(anyhow!(
                "unsupported scope {value:?}; v1 supports only \"all\""
            ))
        }
    };

    let color_theme = match (cli.color_theme, file_config.color_theme.as_deref()) {
        (Some(value), _) => value,
        (None, Some(value)) => value.parse()?,
        (None, None) => ColorTheme::default(),
    };

    let theme_scope = match (cli.theme_scope, file_config.theme_scope.as_deref()) {
        (Some(value), _) => value,
        (None, Some(value)) => value.parse()?,
        (None, None) => ThemeScope::default(),
    };

    Ok(Config {
        db_path,
        config_path,
        daily_start,
        week_start,
        refresh_interval: Duration::from_secs(refresh_seconds),
        auto_refresh,
        scope,
        color_theme,
        theme_scope,
    })
}

fn load_file_config() -> Result<FileConfig> {
    let Some(path) = config_path() else {
        return Ok(FileConfig::default());
    };
    if !path.exists() {
        return Ok(FileConfig::default());
    }

    let content =
        fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
    toml::from_str(&content).with_context(|| format!("parsing {}", path.display()))
}

pub fn config_path() -> Option<PathBuf> {
    dirs::config_dir().map(|path| path.join("expensive").join("config.toml"))
}

pub fn save(config: &Config) -> Result<()> {
    let path = config
        .config_path
        .as_ref()
        .ok_or_else(|| anyhow!("config path is unavailable"))?;

    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
    }

    fs::write(path, format_config(config)).with_context(|| format!("writing {}", path.display()))
}

fn format_config(config: &Config) -> String {
    format!(
        concat!(
            "daily_start = \"{}\"\n",
            "week_start = \"{}\"\n",
            "refresh_seconds = {}\n",
            "auto_refresh = {}\n",
            "color_theme = \"{}\"\n",
            "theme_scope = \"{}\"\n",
            "scope = \"{}\"\n",
        ),
        config.daily_start,
        config.week_start,
        config.refresh_interval.as_secs(),
        config.auto_refresh,
        config.color_theme,
        config.theme_scope,
        config.scope,
    )
}

fn discover_db_path(cli_path: Option<PathBuf>) -> PathBuf {
    if let Some(path) = cli_path {
        return path;
    }

    if let Ok(path) = env::var("OPENCODE_DB_PATH") {
        let path = path.trim();
        if !path.is_empty() {
            return PathBuf::from(path);
        }
    }

    if let Some(path) = opencode_db_path() {
        return path;
    }

    dirs::home_dir()
        .unwrap_or_else(|| Path::new(".").to_path_buf())
        .join(".local/share/opencode/opencode.db")
}

fn opencode_db_path() -> Option<PathBuf> {
    let output = Command::new("opencode")
        .args(["db", "path"])
        .output()
        .ok()?;
    if !output.status.success() {
        return None;
    }

    let stdout = String::from_utf8(output.stdout).ok()?;
    let path = stdout.trim();
    if path.is_empty() {
        None
    } else {
        Some(PathBuf::from(path))
    }
}

#[cfg(test)]
mod tests {
    use std::{fs, path::PathBuf, time::Duration};

    use super::*;

    fn cli() -> Cli {
        Cli {
            db: None,
            daily_start: None,
            week_start: None,
            refresh: None,
            no_refresh: false,
            scope: None,
            color_theme: None,
            theme_scope: None,
        }
    }

    #[test]
    fn default_config_matches_dashboard_expectations() {
        let config = resolve_config(
            cli(),
            FileConfig::default(),
            PathBuf::from("/tmp/opencode.db"),
            Some(PathBuf::from("/tmp/config.toml")),
        )
        .unwrap();

        assert_eq!(config.db_path, PathBuf::from("/tmp/opencode.db"));
        assert_eq!(config.config_path, Some(PathBuf::from("/tmp/config.toml")));
        assert_eq!(config.daily_start, DailyStart::default());
        assert_eq!(config.week_start, WeekStart::default());
        assert_eq!(config.refresh_interval, Duration::from_secs(60));
        assert!(config.auto_refresh);
        assert_eq!(config.scope, Scope::All);
        assert_eq!(config.color_theme, ColorTheme::Aurora);
        assert_eq!(config.theme_scope, ThemeScope::Calendar);
    }

    #[test]
    fn cli_values_override_file_config() {
        let mut cli = cli();
        cli.daily_start = Some("06:30".parse().unwrap());
        cli.week_start = Some(WeekStart::Sunday);
        cli.refresh = Some(10);
        cli.no_refresh = true;
        cli.scope = Some(Scope::All);
        cli.color_theme = Some(ColorTheme::Ocean);
        cli.theme_scope = Some(ThemeScope::All);

        let file_config = FileConfig {
            daily_start: Some("04:00".to_string()),
            week_start: Some("monday".to_string()),
            refresh_seconds: Some(60),
            auto_refresh: Some(true),
            scope: Some("all".to_string()),
            color_theme: Some("ember".to_string()),
            theme_scope: Some("calendar".to_string()),
        };

        let config =
            resolve_config(cli, file_config, PathBuf::from("/tmp/opencode.db"), None).unwrap();

        assert_eq!(
            config.daily_start,
            DailyStart {
                hour: 6,
                minute: 30
            }
        );
        assert_eq!(config.week_start, WeekStart::Sunday);
        assert_eq!(config.refresh_interval, Duration::from_secs(10));
        assert!(!config.auto_refresh);
        assert_eq!(config.scope, Scope::All);
        assert_eq!(config.color_theme, ColorTheme::Ocean);
        assert_eq!(config.theme_scope, ThemeScope::All);
    }

    #[test]
    fn file_config_supports_theme_and_week_start() {
        let file_config = FileConfig {
            week_start: Some("sunday".to_string()),
            auto_refresh: Some(false),
            color_theme: Some("forest".to_string()),
            theme_scope: Some("all".to_string()),
            ..FileConfig::default()
        };

        let config =
            resolve_config(cli(), file_config, PathBuf::from("/tmp/opencode.db"), None).unwrap();

        assert_eq!(config.week_start, WeekStart::Sunday);
        assert!(!config.auto_refresh);
        assert_eq!(config.color_theme, ColorTheme::Forest);
        assert_eq!(config.theme_scope, ThemeScope::All);
    }

    #[test]
    fn saves_editable_config_values() {
        let tempdir = tempfile::tempdir().unwrap();
        let path = tempdir.path().join("expensive").join("config.toml");
        let config = Config {
            db_path: PathBuf::from("/tmp/opencode.db"),
            config_path: Some(path.clone()),
            daily_start: "05:30".parse().unwrap(),
            week_start: WeekStart::Sunday,
            refresh_interval: Duration::from_secs(15),
            auto_refresh: false,
            scope: Scope::All,
            color_theme: ColorTheme::Forest,
            theme_scope: ThemeScope::All,
        };

        save(&config).unwrap();

        let content = fs::read_to_string(path).unwrap();
        assert!(content.contains(r#"daily_start = "05:30""#));
        assert!(content.contains(r#"week_start = "sunday""#));
        assert!(content.contains("refresh_seconds = 15"));
        assert!(content.contains("auto_refresh = false"));
        assert!(content.contains(r#"color_theme = "forest""#));
        assert!(content.contains(r#"theme_scope = "all""#));
        assert!(content.contains(r#"scope = "all""#));
    }

    #[test]
    fn rejects_zero_refresh_interval() {
        let mut cli = cli();
        cli.refresh = Some(0);

        let error = resolve_config(
            cli,
            FileConfig::default(),
            PathBuf::from("/tmp/opencode.db"),
            None,
        )
        .unwrap_err()
        .to_string();

        assert!(error.contains("refresh interval"));
    }

    #[test]
    fn rejects_unknown_file_scope() {
        let file_config = FileConfig {
            scope: Some("current".to_string()),
            ..FileConfig::default()
        };

        let error = resolve_config(cli(), file_config, PathBuf::from("/tmp/opencode.db"), None)
            .unwrap_err()
            .to_string();

        assert!(error.contains("unsupported scope"));
    }

    #[test]
    fn rejects_unknown_theme_values() {
        let file_config = FileConfig {
            color_theme: Some("sparkles".to_string()),
            ..FileConfig::default()
        };

        let error = resolve_config(cli(), file_config, PathBuf::from("/tmp/opencode.db"), None)
            .unwrap_err()
            .to_string();

        assert!(error.contains("unsupported color theme"));
    }
}