8.7 KiB · text History 2977adf
//! The command surface.

use clap::{Args, Parser, Subcommand, ValueEnum};

#[derive(Debug, Parser)]
#[command(
    name = "vgl",
    version,
    about = "Command-line client for a Vigil error tracker",
    long_about = "Manages a Vigil (Sentry-compatible) server over its /api/0 API.\n\
                  Sign in once with `vgl login`; set a default organization and project \
                  there, with VIGIL_ORG / VIGIL_PROJECT, or with --org / --project.",
    propagate_version = true
)]
pub struct Cli {
    /// Server base URL [env: VIGIL_URL] (default: the one saved by `vgl login`).
    #[arg(long, global = true, value_name = "URL")]
    pub url: Option<String>,

    /// API token [env: VIGIL_TOKEN] (default: the one saved by `vgl login`).
    #[arg(long, global = true, value_name = "TOKEN")]
    pub token: Option<String>,

    /// Organization slug [env: VIGIL_ORG].
    #[arg(short = 'o', long, global = true, value_name = "ORG")]
    pub org: Option<String>,

    /// Project slug [env: VIGIL_PROJECT].
    #[arg(short = 'p', long, global = true, value_name = "PROJECT")]
    pub project: Option<String>,

    /// Print the server's JSON instead of a table.
    #[arg(long, global = true)]
    pub json: bool,

    #[command(subcommand)]
    pub command: Command,
}

#[derive(Debug, Subcommand)]
pub enum Command {
    /// Check credentials against a server and save them.
    Login(LoginArgs),

    /// Forget the saved credentials (the token itself stays valid).
    Logout,

    /// Who the token belongs to, and its scopes.
    Whoami,

    /// The organizations the token's user belongs to.
    #[command(visible_alias = "organizations")]
    Orgs,

    /// The organization's teams.
    Teams,

    /// Projects: list, create, show, edit, delete.
    #[command(visible_alias = "project")]
    Projects(ProjectsArgs),

    /// A project's DSN keys.
    #[command(visible_alias = "key")]
    Keys(KeysArgs),

    /// Print the project's DSN (its first active key's), for scripts.
    Dsn,

    /// A project's issues: list them, change their status.
    #[command(visible_alias = "issue")]
    Issues(IssuesArgs),

    /// Releases, read-only.
    #[command(visible_alias = "release")]
    Releases(ReleasesArgs),

    /// Cron monitors, read-only.
    #[command(visible_alias = "monitor")]
    Monitors(ListOnly),

    /// Uptime monitors, read-only.
    Uptime(ListOnly),
}

// ── auth ─────────────────────────────────────────────────────────────

#[derive(Debug, Args)]
pub struct LoginArgs {
    /// Read the token from stdin rather than a prompt or --token, so it
    /// stays out of the shell history and the process table.
    #[arg(long)]
    pub token_stdin: bool,
}

// ── projects ─────────────────────────────────────────────────────────

#[derive(Debug, Args)]
pub struct ProjectsArgs {
    #[command(subcommand)]
    pub command: Option<ProjectsCommand>,
}

#[derive(Debug, Subcommand)]
pub enum ProjectsCommand {
    /// The projects this token can see (the default).
    List,
    /// Make a project on a team; it gets a first DSN key.
    Create(ProjectCreate),
    /// One project (--project, or the default).
    Show(ProjectTarget),
    /// Rename, re-slug or re-platform a project.
    Edit(ProjectEdit),
    /// Delete a project (its data is swept later).
    Delete(ProjectDelete),
}

#[derive(Debug, Args)]
pub struct ProjectTarget {
    /// Project slug (default: --project, VIGIL_PROJECT, or the saved one).
    #[arg(value_name = "PROJECT")]
    pub target_slug: Option<String>,
}

#[derive(Debug, Args)]
pub struct ProjectCreate {
    /// The project's name; its slug is made from it unless --slug is given.
    pub name: String,
    /// The team the project joins.
    #[arg(long, short = 't', value_name = "TEAM")]
    pub team: String,
    #[arg(long)]
    pub slug: Option<String>,
    /// Sentry platform id: python, javascript, node, elixir, go, …
    #[arg(long)]
    pub platform: Option<String>,
}

#[derive(Debug, Args)]
pub struct ProjectEdit {
    #[command(flatten)]
    pub target: ProjectTarget,
    #[arg(long)]
    pub name: Option<String>,
    #[arg(long)]
    pub slug: Option<String>,
    #[arg(long)]
    pub platform: Option<String>,
}

#[derive(Debug, Args)]
pub struct ProjectDelete {
    #[command(flatten)]
    pub target: ProjectTarget,
    /// Don't ask for confirmation (required when not on a terminal).
    #[arg(long, short = 'y')]
    pub yes: bool,
}

// ── keys ─────────────────────────────────────────────────────────────

#[derive(Debug, Args)]
pub struct KeysArgs {
    #[command(subcommand)]
    pub command: Option<KeysCommand>,
}

#[derive(Debug, Subcommand)]
pub enum KeysCommand {
    /// The project's keys and their DSNs (the default).
    List,
    /// Make another key.
    Create {
        /// A label for the key.
        #[arg(long)]
        name: Option<String>,
    },
    /// Delete a key, so its DSN stops working; --disable only switches it off.
    Revoke {
        /// The key's id (its public key, as `vgl keys list` shows it).
        id: String,
        /// Deactivate rather than delete: events are refused, and the key
        /// can be switched back on in the web UI.
        #[arg(long)]
        disable: bool,
    },
}

// ── issues ───────────────────────────────────────────────────────────

#[derive(Debug, Args)]
pub struct IssuesArgs {
    #[command(subcommand)]
    pub command: Option<IssuesCommand>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, ValueEnum)]
pub enum IssueStatus {
    Unresolved,
    Resolved,
    Ignored,
    All,
}

impl IssueStatus {
    pub fn as_str(self) -> &'static str {
        match self {
            IssueStatus::Unresolved => "unresolved",
            IssueStatus::Resolved => "resolved",
            IssueStatus::Ignored => "ignored",
            IssueStatus::All => "all",
        }
    }
}

#[derive(Debug, Subcommand)]
pub enum IssuesCommand {
    /// Issues, latest activity first (the default: unresolved ones).
    List(IssuesList),
    /// Mark issues resolved.
    Resolve(IssueIds),
    /// Back to unresolved.
    Unresolve(IssueIds),
    /// Ignore issues: their events still count, but they don't reopen.
    #[command(visible_alias = "mute")]
    Ignore(IssueIds),
}

#[derive(Debug, Default, Args)]
pub struct IssuesList {
    /// Search, as in the web UI: free text, level:error, release:1.2, …
    #[arg(long, short = 'q')]
    pub query: Option<String>,
    #[arg(long, short = 's', value_enum)]
    pub status: Option<IssueStatus>,
    /// At most this many.
    #[arg(long, short = 'n', default_value_t = 50)]
    pub limit: usize,
}

#[derive(Debug, Args)]
pub struct IssueIds {
    /// Issue ids: the short id (`WEB-12` or `12`) or the issue's UUID.
    #[arg(required = true, value_name = "ID")]
    pub ids: Vec<String>,
}

// ── releases, monitors ───────────────────────────────────────────────

#[derive(Debug, Args)]
pub struct ReleasesArgs {
    #[command(subcommand)]
    pub command: Option<ReleasesCommand>,
}

#[derive(Debug, Subcommand)]
pub enum ReleasesCommand {
    /// Newest first: the project's when one is set (flag, env or saved), else the organization's.
    List {
        #[arg(long, short = 'n', default_value_t = 50)]
        limit: usize,
    },
    /// One release.
    Show {
        #[arg(value_name = "VERSION")]
        release: String,
    },
}

#[derive(Debug, Args)]
pub struct ListOnly {
    #[command(subcommand)]
    pub command: Option<ListCommand>,
}

#[derive(Debug, Subcommand)]
pub enum ListCommand {
    /// List them (the default).
    List,
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn the_command_line_is_well_formed() {
        Cli::command().debug_assert();
    }

    #[test]
    fn global_flags_go_anywhere() {
        let cli = Cli::parse_from([
            "vgl", "issues", "list", "--org", "acme", "-p", "web", "--json", "-s", "resolved",
        ]);
        assert_eq!(cli.org.as_deref(), Some("acme"));
        assert_eq!(cli.project.as_deref(), Some("web"));
        assert!(cli.json);
        match cli.command {
            Command::Issues(IssuesArgs {
                command: Some(IssuesCommand::List(list)),
            }) => assert_eq!(list.status, Some(IssueStatus::Resolved)),
            other => panic!("parsed as {other:?}"),
        }
    }
}