2.1 KiB · text History 2977adf
//! Command implementations and the context they share.

pub mod auth;
pub mod issue;
pub mod key;
pub mod org;
pub mod project;
pub mod release;

use anyhow::{Result, bail};
use serde::Serialize;

use crate::api::Client;
use crate::config::Settings;

/// Everything a command needs that isn't its own arguments.
pub struct Ctx {
    pub api: Client,
    pub settings: Settings,
    pub json: bool,
}

impl Ctx {
    pub fn new(settings: Settings, json: bool) -> Result<Self> {
        Ok(Self {
            api: Client::new(&settings.url, &settings.token)?,
            settings,
            json,
        })
    }

    /// The organization this invocation is about: `--org`, `VIGIL_ORG`,
    /// the saved default, or the only one the token's user belongs to.
    pub fn org(&self) -> Result<String> {
        if let Some(org) = &self.settings.org {
            return Ok(org.clone());
        }
        let orgs = self.api.organizations()?;
        match orgs.data.as_slice() {
            [only] => Ok(only.slug.clone()),
            [] => bail!("this token's user belongs to no organization"),
            many => bail!(
                "which organization? pass --org (or set VIGIL_ORG): {}",
                many.iter()
                    .map(|o| o.slug.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            ),
        }
    }

    /// The project: an explicit argument, else `--project`, `VIGIL_PROJECT`
    /// or the saved default.
    pub fn project(&self, explicit: Option<&str>) -> Result<String> {
        match explicit.or(self.settings.project.as_deref()) {
            Some(p) => Ok(p.to_string()),
            None => bail!(
                "which project? pass --project (or set VIGIL_PROJECT, or save one with `vgl login --project P`)"
            ),
        }
    }

    /// Prints raw JSON if `--json` was passed; `true` means the command has
    /// said all it needs to.
    pub fn emitted<T: Serialize>(&self, raw: &T) -> Result<bool> {
        if self.json {
            crate::output::print_json(raw)?;
            return Ok(true);
        }
        Ok(false)
    }
}