1use std::{io::Read, path::PathBuf};
2
3use anyhow::{Context, Result};
4use clap::Parser;
5
6use crate::{
7 auth::load_auth,
8 client::ThingsCloudClient,
9 commands::{Command, Commands},
10 dirs::append_log_dir,
11 log_cache::{fold_state_from_append_log, get_state_with_append_log},
12 logging,
13 store::{RawState, ThingsStore, fold_items},
14 wire::wire_object::WireItem,
15};
16
17#[derive(Debug, Parser)]
18#[command(name = "things3")]
19#[command(bin_name = "things3")]
20#[command(version)]
21#[command(before_help = concat!("things3 ", env!("CARGO_PKG_VERSION")))]
22#[command(disable_help_subcommand = true)]
23#[command(about = concat!(
24 "things3 v",
25 env!("CARGO_PKG_VERSION"),
26 ": Command-line interface for Things 3 via Cloud API"
27))]
28pub struct Cli {
29 #[arg(long)]
31 pub no_color: bool,
32 #[arg(long)]
34 pub no_sync: bool,
35 #[arg(long, hide = true)]
37 pub no_cloud: bool,
38 #[arg(long, value_enum, default_value_t = logging::Level::Info)]
40 pub log_level: logging::Level,
41 #[arg(long, value_enum, default_value_t = logging::LogFormat::Auto)]
43 pub log_format: logging::LogFormat,
44 #[arg(long, global = true, hide = true, value_name = "DIRECTIVE")]
46 pub log_filter: Option<String>,
47 #[arg(long, global = true, hide = true, value_name = "TIMESTAMP")]
49 pub today_ts: Option<i64>,
50 #[arg(long, global = true, hide = true, value_name = "TIMESTAMP")]
52 pub now_ts: Option<f64>,
53 #[arg(long, value_name = "FILE", hide = true)]
57 pub load_journal: Option<PathBuf>,
58 #[command(subcommand)]
59 pub command: Option<Commands>,
60}
61
62impl Cli {
63 pub fn load_state(&self) -> Result<RawState> {
64 if let Some(journal_path) = &self.load_journal {
65 let raw = if journal_path == std::path::Path::new("-") {
66 let mut buf = String::new();
67 std::io::stdin()
68 .read_to_string(&mut buf)
69 .with_context(|| "failed to read journal JSON from stdin")?;
70 buf
71 } else {
72 std::fs::read_to_string(journal_path).with_context(|| {
73 format!("failed to read journal file {}", journal_path.display())
74 })?
75 };
76 let items: Vec<WireItem> =
77 serde_json::from_str(&raw).with_context(|| "failed to parse journal JSON")?;
78 return Ok(fold_items(items));
79 }
80
81 if self.no_sync || self.no_cloud {
82 let cache_dir = append_log_dir();
83 return fold_state_from_append_log(&cache_dir);
84 }
85
86 let (email, password) = load_auth()?;
87 let mut client = ThingsCloudClient::new(email, password)?;
88 let cache_dir = append_log_dir();
89 get_state_with_append_log(&mut client, cache_dir)
90 }
91
92 pub fn load_store(&self) -> Result<ThingsStore> {
93 let state = self.load_state()?;
94 Ok(ThingsStore::from_raw_state(&state))
95 }
96}
97
98pub fn run() -> Result<()> {
99 let mut cli = Cli::parse();
100 logging::init(cli.log_level, cli.log_format, cli.log_filter.as_deref());
101 let command = cli
102 .command
103 .take()
104 .unwrap_or(Commands::Today(Default::default()));
105 command.run(&cli, &mut std::io::stdout())
106}