aoc-toolkit 0.1.0-alpha.4

A toolkit for solving Advent of Code problems
Documentation
use clap::{Args, Subcommand};

use crate::adapters::browser::SystemBrowser;
use crate::application::auth;
use crate::cli::error::CliError;
use crate::cli::output::auth::{
    MANUAL_LOGIN_HELP, print_auth_status, print_login_instructions, print_login_success,
    print_logout_success,
};

#[derive(Debug, Args)]
pub struct AuthArgs {
    #[command(subcommand)]
    command: AuthCommand,
}

#[derive(Debug, Subcommand)]
enum AuthCommand {
    /// Authenticate with Advent of Code
    #[command(after_help = MANUAL_LOGIN_HELP)]
    Login {
        /// Enter a session token without opening the browser
        #[arg(long)]
        manual: bool,
    },

    /// Check whether a session is stored
    Status,

    /// Remove the stored session
    Logout,
}

pub(crate) fn execute(args: &AuthArgs) -> Result<(), CliError> {
    match args.command {
        AuthCommand::Login { manual } => {
            login(manual)?;
        }

        AuthCommand::Status => {
            print_auth_status(auth::status()?);
        }

        AuthCommand::Logout => {
            auth::logout()?;

            print_logout_success();
        }
    }

    Ok(())
}

pub(super) fn login(manual: bool) -> Result<(), CliError> {
    if !manual {
        SystemBrowser::open_login()?;
    }

    print_login_instructions();

    let token =
        rpassword::prompt_password("Advent of Code session: ").map_err(CliError::ReadSession)?;

    auth::login(token.trim())?;

    print_login_success();

    Ok(())
}