summaryrefslogtreecommitdiffstats
path: root/src/commands/profile.rs
blob: 93753d75c345e55d8d448276972ef35ae1558e99 (plain)
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
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering;
use std::sync::Arc;

use anyhow::Context;
use anyhow::Result;
use clap::ArgMatches;

use crate::config::Config;
use crate::profile::Profile;

pub async fn profile(matches: &ArgMatches) -> Result<()> {
    match matches.subcommand() {
        Some(("create", m)) => profile_create(m).await,
        Some(("serve", m)) => profile_serve(m).await,
        _ => unimplemented!(),
    }
}

async fn profile_create(matches: &ArgMatches) -> Result<()> {
    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let state_dir = Profile::state_dir_path(&name)?;
    log::info!("Creating '{}' in {}", name, state_dir.display());

    let profile = Profile::create(&state_dir, &name, Config::default()).await?;
    log::info!("Saving...");
    profile.save().await?;

    log::info!("Shutting down...");
    profile.exit().await
}

async fn profile_serve(matches: &ArgMatches) -> Result<()> {
    let name = matches.value_of("name").map(String::from).unwrap(); // required
    let state_dir = Profile::state_dir_path(&name)?;

    log::info!("Loading '{}' from {}", name, state_dir.display());
    let profile = Profile::load(Config::default(), &name).await?;
    log::info!("Profile loaded");

    let running = Arc::new(AtomicBool::new(true));
    let r = running.clone();

    ctrlc::set_handler(move || {
        r.store(false, Ordering::SeqCst);
    }).context("Error setting Ctrl-C handler")?;

    log::info!("Serving...");
    while running.load(Ordering::SeqCst) {
        tokio::time::sleep(std::time::Duration::from_millis(500)).await // sleep not so busy
    }
    log::info!("Shutting down...");
    profile.exit().await
}