-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.rs
More file actions
330 lines (277 loc) Β· 8.73 KB
/
Copy pathmain.rs
File metadata and controls
330 lines (277 loc) Β· 8.73 KB
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
mod models;
mod formatters;
mod auth;
mod api;
mod workouts;
mod utils;
mod parsers;
mod fetch;
mod table;
mod heatmap;
mod list;
use clap::{Parser, Subcommand};
use wxrust::credentials;
use crate::api::{ReqwestClient, ApiClient};
#[derive(Parser)]
#[command(name = "wxrust")]
#[command(about = "WeightXReps Rust client")]
struct Args {
#[arg(short, long, help = "Where to find credentials.txt file")]
credentials: Option<String>,
#[arg(short = 'a', long = "force-authentication", help = "Do not use cached auth token")]
force_auth: bool,
#[arg(long, help = "Not allowed to connect to server")]
no_network: bool,
#[arg(long, help = "Not allosed to read from cache")]
no_cache: bool,
#[arg(long, help = "Not allowed to write to cache")]
no_cache_write: bool,
#[arg(long, default_value = "auto", help = "Color output policy: auto, always, never")]
color: String,
#[arg(short, long, help = "Enable debug output")]
verbose: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
List(ListArgs),
Show(ShowArgs),
Fetch(FetchArgs),
Table(TableArgs),
Heatmap(HeatmapArgs),
}
async fn setup_auth_and_data_access(
client: &ReqwestClient,
credentials_path: &str,
token_path: &str,
no_network: bool,
force_auth: bool,
) -> (Option<String>, Option<u32>) {
let (token, uid) = if no_network {
// Load uid from cached token, no network login
let uid = match auth::load_uid_from_cache(token_path) {
Ok(u) => u,
Err(e) => {
eprintln!("Failed to load cached token: {}", e);
eprintln!("Use without --no-network to authenticate first.");
utils::exit_with_error("");
}
};
(None, Some(uid))
} else {
// Normal login
let token = match auth::login(client, credentials_path, token_path, force_auth).await {
Ok(t) => t,
Err(e) => utils::exit_with_error(e),
};
let uid = match auth::decode_token(&token) {
Ok(claims) => claims.id,
Err(e) => utils::exit_with_error(format!("Failed to decode token: {}", e)),
};
let _user = match client.get_user_info(&token).await {
Ok(u) => u,
Err(e) => utils::exit_with_error(e),
};
(Some(token), Some(uid))
};
(token, uid)
}
#[derive(Parser)]
struct ListArgs {
#[arg(short, long)]
details: bool,
#[arg(short, long)]
summary: bool,
#[arg(short, long)]
reverse: bool,
#[arg(short = 'A', long)]
all: bool,
#[arg(short, long)]
before: Option<String>,
#[arg(short, long)]
count: Option<u32>,
/// filter on dates (YYYY, YYYY-MM, YYYY-MM-DD, etc.) or exercise names (or substrings)
args: Vec<String>,
}
#[derive(Parser)]
struct ShowArgs {
#[arg(short, long)]
summary: bool,
date: Option<String>,
}
#[derive(Parser)]
struct FetchArgs {
#[arg(long)]
diff: bool,
#[arg(long)]
force: bool,
#[arg(long, value_name = "FILE")]
file: Option<String>,
dates: Vec<String>,
}
#[derive(Parser)]
struct TableArgs {
/// provide a 1RM or Weight x Reps, and see how it stacks up
#[arg(long)]
dream: Vec<String>,
/// filter on dates (YYYY, YYYY-MM, YYYY-MM-DD, etc.) or exercise names (or substrings)
args: Vec<String>,
}
#[derive(Parser)]
struct HeatmapArgs {
#[arg(long, group = "metric")]
sets: bool,
#[arg(long, group = "metric")]
reps: bool,
#[arg(long, group = "metric")]
volume: bool,
#[arg(long, group = "metric")]
weight: bool,
#[arg(long, group = "metric")]
onerm: bool,
#[arg(long)]
green: bool,
/// filter on dates (YYYY, YYYY-MM, YYYY-MM-DD, etc.) or exercise names (or substrings)
args: Vec<String>,
}
async fn handle_show(
show: &ShowArgs,
data_access: api::DataAccess<'_, ReqwestClient>,
verbose: bool,
) {
let date = if let Some(d) = &show.date {
d.clone()
} else {
// Show last workout
let dates = match workouts::get_dates(&data_access, None, None, 1, false).await {
Ok(d) => d,
Err(e) => utils::exit_with_error(e),
};
if let Some(d) = dates.first() {
d.clone()
} else {
utils::exit_with_error("No workouts found");
}
};
let jday = match workouts::get_jday(&data_access, &date, verbose).await {
Ok(j) => j,
Err(e) => utils::exit_with_error(e),
};
let user_wants_kg = workouts::resolve_user_wants_kg(&data_access).await;
if show.summary {
let fmt_date = formatters::color_date(&date);
let summary = formatters::summarize_workout(&jday, user_wants_kg, &[]);
println!("{} {}", fmt_date, summary);
} else {
let workout = formatters::format_workout(&date, &jday, user_wants_kg);
print!("{}", workout);
if !workout.ends_with('\n') {
println!();
}
}
}
async fn handle_fetch(
fetch_args: &FetchArgs,
data_access: api::DataAccess<'_, ReqwestClient>,
verbose: bool,
) {
if let Err(e) = fetch::fetch_command(
&data_access,
&fetch_args.dates,
fetch_args.diff,
fetch_args.force,
fetch_args.file.as_deref(),
verbose,
).await {
utils::exit_with_error(e);
}
}
#[cfg_attr(tarpaulin, ignore)]
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let args = Args::parse();
// Validate mutually exclusive options
if args.no_network && args.no_cache {
utils::exit_with_error("Error: --no-network and --no-cache are mutually exclusive");
}
unsafe { std::env::set_var("WXRUST_COLOR", &args.color); }
let token_path = match workouts::get_cache_base_dir() {
Ok(dir) => dir.join("token").to_string_lossy().to_string(),
Err(_) => {
let home = std::env::var("HOME").unwrap_or(".".to_string());
format!("{}/.cache/wxrust/token", home)
}
};
// Set credentials path if provided
if let Some(path) = &args.credentials {
credentials::set_credentials_path(path);
}
// Ensure credentials path is available
let credentials_path = match credentials::get_credentials_path() {
Ok(p) => p,
Err(e) => {
eprintln!("ERROR: {}", e);
eprintln!();
eprintln!("Please create it with email on first line and password on second line at one of these locations:");
if let Some(config_dir) = dirs::config_dir() {
eprintln!("- {}", config_dir.join("wxrust").join("credentials.txt").display());
}
if let Ok(home) = std::env::var("HOME") {
eprintln!("- {}/.config/wxrust/credentials.txt", home);
}
eprintln!("- ./credentials.txt");
utils::exit_with_error("");
}
};
let client = ReqwestClient::new_with_verbose(args.verbose);
let (token, uid) = setup_auth_and_data_access(&client, &credentials_path, &token_path, args.no_network, args.force_auth).await;
let data_access = api::DataAccess {
client: &client,
token: token.as_deref(),
uid,
use_network: !args.no_network,
use_cache: !args.no_cache,
write_cache: !args.no_cache_write,
};
match args.command {
Commands::List(list) => {
list::handle_list(&list, &client, &token, data_access, args.verbose).await;
},
Commands::Show(show) => {
handle_show(&show, data_access, args.verbose).await;
},
Commands::Fetch(fetch_args) => {
handle_fetch(&fetch_args, data_access, args.verbose).await;
},
Commands::Table(table_args) => {
table::handle_table(&client, &token, data_access, &table_args.args, &table_args.dream, args.verbose).await;
},
Commands::Heatmap(heatmap_args) => {
// Determine metric - default to OneRm
let metric = if heatmap_args.sets {
heatmap::Metric::Sets
} else if heatmap_args.reps {
heatmap::Metric::Reps
} else if heatmap_args.volume {
heatmap::Metric::Volume
} else if heatmap_args.weight {
heatmap::Metric::Weight
} else if heatmap_args.onerm {
heatmap::Metric::OneRm
} else {
heatmap::Metric::OneRm // default
};
heatmap::handle_heatmap(
&client,
&token,
data_access,
metric,
heatmap_args.green,
&heatmap_args.args,
args.verbose,
).await;
}
}
Ok(())
}