tuitbot-cli 0.1.52

CLI for Tuitbot autonomous X growth assistant
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
/// `tuitbot update` — unified binary self-update + config upgrade.
///
/// Phase 1a: Check GitHub releases for a newer CLI binary, download, verify
///           SHA256, and atomically replace the current binary.
/// Phase 1b: Independently check whether `tuitbot-server` (if on PATH) is
///           behind the latest release that ships server assets. This runs
///           regardless of whether the CLI itself needed an update, fixing
///           the bootstrapping bug where a newly-updated CLI skips the server
///           because it's "already up to date."
/// Phase 2:  Run config upgrade (reuses `upgrade.rs` logic) to patch missing
///           feature groups into the user's `config.toml`.
mod binary;
mod github;
mod platform;
mod version;

#[cfg(test)]
mod tests;

use std::io::IsTerminal;

use anyhow::{bail, Context, Result};
use console::Style;
use dialoguer::Confirm;
use semver::Version;

use super::upgrade;

use binary::{detect_server_path, detect_server_version, update_cli_binary, update_target_binary};
use github::{available_asset_names, check_recent_releases, GitHubRelease};
use platform::{asset_name_for_binary, platform_asset_name};
use version::{
    is_newer, latest_compatible_release, latest_known_release, latest_release_with_server_asset,
};

const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
const UPDATE_TARGET_ENV: &str = "TUITBOT_UPDATE_TARGET";

// ---------------------------------------------------------------------------
// Public entry point
// ---------------------------------------------------------------------------

/// Execute the `update` command.
pub async fn execute(
    non_interactive: bool,
    check_only: bool,
    config_only: bool,
    config_path_str: &str,
    out: crate::output::CliOutput,
) -> Result<()> {
    let bold = Style::new().bold();
    let dim = Style::new().dim();
    let green = Style::new().green().bold();
    let current = Version::parse(CURRENT_VERSION).context("Failed to parse current version")?;

    let mut binary_updated = false;

    // Phase 1: Binary update
    if !config_only {
        out.info(&format!("{}", bold.apply_to("Checking for updates...")));
        out.info("");

        let fetched_releases = check_recent_releases().await;

        match &fetched_releases {
            Ok(releases) => match latest_known_release(releases) {
                Some((latest_release, latest)) if is_newer(&latest, &current) => {
                    out.info(&format!(
                        "  {} {}{}",
                        green.apply_to("New version available:"),
                        current,
                        latest
                    ));

                    if check_only {
                        if out.is_json() {
                            return out.json(&serde_json::json!({
                                "update_available": true,
                                "current_version": current.to_string(),
                                "latest_version": latest.to_string(),
                            }));
                        }
                        out.info("");
                        out.info(&format!(
                            "{}",
                            dim.apply_to("Run 'tuitbot update' to install the update.")
                        ));
                        return Ok(());
                    }

                    // Confirm with user in interactive mode
                    if !non_interactive && std::io::stdin().is_terminal() {
                        eprintln!();
                        let proceed = Confirm::new()
                            .with_prompt(format!("Update tuitbot to v{latest}?"))
                            .default(true)
                            .interact()?;

                        if !proceed {
                            out.info(&format!("{}", dim.apply_to("Update skipped.")));
                            out.info("");
                            // Fall through to config upgrade
                            return run_config_upgrade(
                                non_interactive,
                                config_path_str,
                                &bold,
                                &dim,
                                out,
                            )
                            .map(|_| ());
                        }
                    }

                    let asset_name = match platform_asset_name()
                        .context("Unsupported platform for binary self-update")
                    {
                        Ok(name) => name,
                        Err(e) => {
                            let reason = format!("{e}");
                            out.info("");
                            out.info(&format!(
                                "  {} Binary update skipped: {e}",
                                Style::new().yellow().bold().apply_to(""),
                            ));
                            out.info(&format!(
                                    "  {}",
                                    dim.apply_to(
                                        "No prebuilt binary is published for this platform. Build from source or install manually."
                                    )
                                ));
                            out.info(&format!(
                                    "  {}",
                                    dim.apply_to(
                                        "Manual downloads: https://github.com/aramirez087/TuitBot/releases"
                                    )
                                ));
                            out.info("");
                            if non_interactive && out.is_json() {
                                out.json(&serde_json::json!({
                                    "binary_updated": false,
                                    "binary_skipped": true,
                                    "reason": reason,
                                    "current_version": current.to_string(),
                                    "latest_version": latest.to_string(),
                                }))?;
                                std::process::exit(1);
                            }
                            if non_interactive {
                                bail!("Binary update skipped: {e}");
                            }
                            return run_config_upgrade(
                                non_interactive,
                                config_path_str,
                                &bold,
                                &dim,
                                out,
                            )
                            .map(|_| ());
                        }
                    };

                    let (release_for_update, release_version) = match latest_compatible_release(
                        releases,
                        &current,
                        &asset_name,
                    ) {
                        Some(found) => found,
                        None => {
                            let reason = format!("no compatible asset found for '{asset_name}'");
                            out.info("");
                            out.info(&format!(
                                "  {} Binary update skipped: {reason}",
                                Style::new().yellow().bold().apply_to(""),
                            ));
                            out.info(&format!(
                                "  {} Latest release checked: {}",
                                dim.apply_to("Tag:"),
                                latest_release.tag_name,
                            ));
                            out.info(&format!(
                                "  {} {}",
                                dim.apply_to("Available assets:"),
                                available_asset_names(latest_release),
                            ));
                            out.info(&format!(
                                    "  {}",
                                    dim.apply_to(
                                        "Manual downloads: https://github.com/aramirez087/TuitBot/releases"
                                    )
                                ));
                            out.info("");
                            if non_interactive && out.is_json() {
                                out.json(&serde_json::json!({
                                    "binary_updated": false,
                                    "binary_skipped": true,
                                    "reason": reason,
                                    "current_version": current.to_string(),
                                    "latest_version": latest.to_string(),
                                }))?;
                                std::process::exit(1);
                            }
                            if non_interactive {
                                bail!("Binary update skipped: {reason}");
                            }
                            return run_config_upgrade(
                                non_interactive,
                                config_path_str,
                                &bold,
                                &dim,
                                out,
                            )
                            .map(|_| ());
                        }
                    };

                    if release_version != latest {
                        out.info(&format!(
                            "  {} Latest version v{} has no '{}' asset; installing newest compatible v{}.",
                            Style::new().yellow().bold().apply_to(""),
                            latest,
                            asset_name,
                            release_version
                        ));
                    }

                    // Phase 1a: Update CLI binary
                    match update_cli_binary(release_for_update).await {
                        Ok(()) => {
                            binary_updated = true;
                            out.info("");
                            out.info(&format!(
                                "  {} Updated tuitbot to v{}",
                                green.apply_to(""),
                                release_version
                            ));
                        }
                        Err(e) => {
                            out.info("");
                            out.info(&format!(
                                "  {} CLI binary update failed: {e}",
                                Style::new().red().bold().apply_to(""),
                            ));
                            out.info(&format!(
                                "  {}",
                                dim.apply_to(
                                    "You can download manually from: https://github.com/aramirez087/TuitBot/releases"
                                )
                            ));
                        }
                    }
                }
                Some((_, latest)) => {
                    out.info(&format!("  Already up to date (v{current})."));
                    if latest != current {
                        out.info(&format!(
                            "  {}",
                            dim.apply_to(format!("(latest release: v{latest})"))
                        ));
                    }

                    if check_only {
                        if out.is_json() {
                            return out.json(&serde_json::json!({
                                "update_available": false,
                                "current_version": current.to_string(),
                            }));
                        }
                        return Ok(());
                    }
                }
                None => {
                    out.info(&format!(
                        "  {} Could not find a parseable CLI release tag",
                        Style::new().yellow().bold().apply_to(""),
                    ));

                    if check_only {
                        if out.is_json() {
                            return out.json(&serde_json::json!({
                                "update_available": false,
                                "current_version": current.to_string(),
                                "warning": "Could not find a parseable CLI release tag",
                            }));
                        }
                        return Ok(());
                    }
                }
            },
            Err(e) => {
                out.info(&format!(
                    "  {} Could not check for updates: {e}",
                    Style::new().yellow().bold().apply_to(""),
                ));
                out.info(&format!(
                    "  {}",
                    dim.apply_to("Skipping binary update, continuing with config upgrade...")
                ));
            }
        }

        // Phase 1b: Standalone server update check
        // Runs independently of the CLI update — fixes the bootstrapping bug where
        // the server stays stuck at an old version when the CLI is already current.
        if !check_only {
            if let Ok(releases) = &fetched_releases {
                check_and_update_server(releases, &green, &dim, out).await;
            }
        }

        out.info("");
    } else if check_only {
        bail!("--check and --config-only cannot be used together.");
    }

    // Phase 2: Config upgrade
    let config_up_to_date = run_config_upgrade(non_interactive, config_path_str, &bold, &dim, out)?;

    // Emit JSON summary for the full update flow (non-check-only).
    if out.is_json() {
        out.json(&serde_json::json!({
            "current_version": current.to_string(),
            "binary_updated": binary_updated,
            "config_up_to_date": config_up_to_date,
        }))?;
    }

    Ok(())
}

/// Pre-run check: hint about `tuitbot update` when config has missing features.
pub async fn check_before_run(config_path_str: &str) -> Result<()> {
    let config_path = upgrade::expand_tilde(config_path_str);

    if !config_path.exists() {
        return Ok(());
    }

    let missing = upgrade::detect_missing_features(&config_path)?;
    if missing.is_empty() {
        return Ok(());
    }

    let bold = Style::new().bold();
    let dim = Style::new().dim();

    eprintln!();
    eprintln!(
        "{}",
        bold.apply_to("New features available in your config:")
    );
    for group in &missing {
        eprintln!("{}{}", group.display_name(), group.description());
    }
    eprintln!();

    let configure_now = Confirm::new()
        .with_prompt("Configure new features now?")
        .default(false)
        .interact()?;

    if !configure_now {
        eprintln!(
            "{}",
            dim.apply_to("Tip: Run 'tuitbot update' any time to configure new features.")
        );
        eprintln!();
        return Ok(());
    }

    upgrade::run_upgrade_wizard(&config_path, &missing)?;

    Ok(())
}

// ---------------------------------------------------------------------------
// Server update (Phase 1b) — standalone, non-fatal
// ---------------------------------------------------------------------------

/// Check whether `tuitbot-server` is installed, behind, and update it.
///
/// This runs independently of the CLI update check so the server can be updated
/// even when the CLI is already at the latest version (bootstrapping fix).
async fn check_and_update_server(
    releases: &[GitHubRelease],
    green: &Style,
    dim: &Style,
    out: crate::output::CliOutput,
) {
    let server_exe = match detect_server_path() {
        Some(path) => path,
        None => return, // server not installed — nothing to do
    };

    let server_asset = match asset_name_for_binary("tuitbot-server") {
        Some(name) => name,
        None => {
            out.info(&format!(
                "  {} Server update skipped: unsupported platform",
                dim.apply_to(""),
            ));
            return;
        }
    };

    // Find the newest release that ships a server binary
    let (release, release_version) = match latest_release_with_server_asset(releases, &server_asset)
    {
        Some(found) => found,
        None => return, // no release has server assets — skip silently
    };

    // Compare against the installed server version (if detectable)
    if let Some(server_version) = detect_server_version(&server_exe) {
        if server_version >= release_version {
            out.info(&format!(
                "  {} tuitbot-server is up to date (v{server_version}).",
                dim.apply_to(""),
            ));
            return;
        }
        out.info(&format!(
            "  {} tuitbot-server v{server_version} → v{release_version}",
            green.apply_to("Server update available:"),
        ));
    } else {
        out.info(&format!(
            "  {} Could not detect server version; attempting update to v{release_version}.",
            dim.apply_to(""),
        ));
    }

    match update_target_binary(release, "tuitbot-server", &server_asset, &server_exe).await {
        Ok(()) => {
            out.info(&format!(
                "  {} Updated tuitbot-server at {}",
                green.apply_to(""),
                server_exe.display()
            ));
            out.info(&format!(
                "  {}",
                dim.apply_to(
                    "Restart the server to use the new version (e.g., sudo systemctl restart tuitbot)."
                )
            ));
        }
        Err(e) => {
            out.info(&format!(
                "  {} Server update failed: {e}",
                Style::new().yellow().bold().apply_to(""),
            ));
            let hint = if cfg!(unix) && server_exe.starts_with("/usr") {
                "Hint: You may need to run with sudo to update the server binary."
            } else {
                "Hint: Make sure tuitbot-server is not running, then try again."
            };
            out.info(&format!("  {}", dim.apply_to(hint)));
        }
    }
}

// ---------------------------------------------------------------------------
// Config upgrade (Phase 2)
// ---------------------------------------------------------------------------

/// Run config upgrade. Returns `true` if config was already up to date.
fn run_config_upgrade(
    non_interactive: bool,
    config_path_str: &str,
    bold: &Style,
    dim: &Style,
    out: crate::output::CliOutput,
) -> Result<bool> {
    let config_path = upgrade::expand_tilde(config_path_str);

    if !config_path.exists() {
        out.info(&format!(
            "  {}",
            dim.apply_to("No config file found — run 'tuitbot init' to create one.")
        ));
        return Ok(true);
    }

    out.info(&format!("{}", bold.apply_to("Checking configuration...")));

    let missing = upgrade::detect_missing_features(&config_path)?;

    if missing.is_empty() {
        out.info("  Config is up to date.");
        return Ok(true);
    }

    out.info("  New feature groups to configure:");
    for group in &missing {
        out.info(&format!(
            "{}{}",
            group.display_name(),
            group.description()
        ));
    }
    out.info("");

    if non_interactive {
        upgrade::apply_defaults(&config_path, &missing, out)?;
    } else if std::io::stdin().is_terminal() {
        upgrade::run_upgrade_wizard(&config_path, &missing)?;
    } else {
        out.info(&format!(
            "  {}",
            dim.apply_to(
                "Non-interactive terminal detected. Use --non-interactive to apply defaults."
            )
        ));
    }

    Ok(false)
}