Skip to main content

claude_wrapper/command/
auth.rs

1use crate::Claude;
2use crate::command::ClaudeCommand;
3use crate::error::Result;
4use crate::exec::{self, CommandOutput};
5
6/// Check authentication status.
7///
8/// # Example
9///
10/// ```no_run
11/// use claude_wrapper::{Claude, ClaudeCommand, AuthStatusCommand};
12///
13/// # async fn example() -> claude_wrapper::Result<()> {
14/// let claude = Claude::builder().build()?;
15/// let status = AuthStatusCommand::new().execute_json(&claude).await?;
16/// println!("logged in: {}", status.logged_in);
17/// # Ok(())
18/// # }
19/// ```
20#[derive(Debug, Clone, Default)]
21pub struct AuthStatusCommand {
22    json: bool,
23}
24
25impl AuthStatusCommand {
26    /// Create a new auth status command.
27    #[must_use]
28    pub fn new() -> Self {
29        Self { json: true }
30    }
31
32    /// Request text output instead of JSON.
33    #[must_use]
34    pub fn text(mut self) -> Self {
35        self.json = false;
36        self
37    }
38
39    /// Execute and parse the JSON result into an [`AuthStatus`](crate::types::AuthStatus).
40    #[cfg(feature = "json")]
41    pub async fn execute_json(&self, claude: &Claude) -> Result<crate::types::AuthStatus> {
42        let mut cmd = self.clone();
43        cmd.json = true;
44
45        let output = exec::run_claude(claude, cmd.args()).await?;
46
47        serde_json::from_str(&output.stdout).map_err(|e| crate::error::Error::Json {
48            message: format!("failed to parse auth status: {e}"),
49            source: e,
50        })
51    }
52}
53
54impl ClaudeCommand for AuthStatusCommand {
55    type Output = CommandOutput;
56
57    fn args(&self) -> Vec<String> {
58        let mut args = vec!["auth".to_string(), "status".to_string()];
59        if self.json {
60            args.push("--json".to_string());
61        } else {
62            args.push("--text".to_string());
63        }
64        args
65    }
66
67    async fn execute(&self, claude: &Claude) -> Result<CommandOutput> {
68        exec::run_claude(claude, self.args()).await
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75
76    #[test]
77    fn test_auth_status_args() {
78        let cmd = AuthStatusCommand::new();
79        assert_eq!(cmd.args(), vec!["auth", "status", "--json"]);
80    }
81
82    #[test]
83    fn test_auth_status_text() {
84        let cmd = AuthStatusCommand::new().text();
85        assert_eq!(cmd.args(), vec!["auth", "status", "--text"]);
86    }
87}