wsb 0.275.7622

Workspace tools for every project under $PRJ: git across submodules, template stamping, GitHub, and the workbench
Documentation
//! `wsb machine name [NEW]`: what this machine is called.
//!
//! The name is the machine's identity's, in its folder under the workshop's
//! `.state`, and the daemon holds that identity: it is what paired machines
//! show this one as. So the name is read and changed through the daemon,
//! which starts if it is not running; peers see the new name from their next
//! connection.

use serde::Deserialize;

use crate::daemon::Client;

/// The route that names this machine.
pub const ROUTE: &str = "/api/v1/machine";

/// The route that renames it.
pub const RENAME: &str = "/api/v1/machine/name";

#[derive(Deserialize)]
struct Named {
    name: String,
}

pub fn name(new: Option<&str>) -> u8 {
    match run(new) {
        Ok(()) => 0,
        Err(message) => {
            crate::errln!("wsb machine: {message}");
            1
        }
    }
}

fn run(new: Option<&str>) -> Result<(), String> {
    let client = daemon()?;
    match new {
        None => {
            let named: Named = client.get_json(ROUTE)?;
            crate::outln!("{}", named.name);
        }
        Some(name) => {
            let named: Named = client.post_json(RENAME, &serde_json::json!({ "name": name }))?;
            crate::outln!("this machine is now called {}", named.name);
        }
    }
    Ok(())
}

fn daemon() -> Result<Client, String> {
    let machine_dir = crate::daemon::machine_dir()?;
    let cwd = std::env::current_dir().map_err(|e| format!("cannot determine the current directory: {e}"))?;
    let (client, _info, _started) =
        crate::daemon::ensure_running(&machine_dir, &cwd, &crate::daemon::Spawn::default())?;
    Ok(client)
}