bird 0.1.2

X API CLI with entity caching, search, threads, and watchlists
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
//! bird doctor: living view of xurl status, auth state, command availability, and entity store health.

use crate::db::BirdClient;
use crate::requirements::{AuthType, command_names_with_auth, requirements_for_command};
use serde::Serialize;
use std::collections::HashMap;

#[derive(Clone, Debug, Serialize)]
pub struct XurlStatus {
    pub path: Option<String>,
    pub version: Option<String>,
    pub available: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct AuthState {
    pub authenticated: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct CommandStatus {
    pub available: bool,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

#[derive(Clone, Debug, Serialize)]
pub struct CacheStatus {
    pub path: String,
    pub exists: bool,
    pub size_mb: f64,
    pub max_size_mb: u64,
    pub tweets: u64,
    pub users: u64,
    pub raw_responses: u64,
    pub healthy: bool,
}

#[derive(Clone, Debug, Serialize)]
pub struct DoctorReport {
    pub xurl: XurlStatus,
    pub auth: AuthState,
    pub commands: HashMap<String, CommandStatus>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache: Option<CacheStatus>,
}

fn build_xurl_status(quiet: bool) -> XurlStatus {
    match crate::transport::resolve_xurl_path() {
        Ok(path) => {
            let version = crate::transport::check_xurl_version(path, quiet).ok();
            XurlStatus {
                path: Some(path.display().to_string()),
                version,
                available: true,
            }
        }
        Err(_) => XurlStatus {
            path: None,
            version: None,
            available: false,
        },
    }
}

/// Detect auth state by running `xurl whoami`. Returns username on success.
fn detect_auth() -> AuthState {
    match crate::transport::xurl_call(&["whoami"]) {
        Ok(json) => {
            let username = json
                .get("data")
                .and_then(|d| d.get("username"))
                .and_then(|u| u.as_str())
                .or_else(|| json.get("username").and_then(|u| u.as_str()))
                .map(String::from);
            AuthState {
                authenticated: true,
                username,
            }
        }
        Err(_) => AuthState {
            authenticated: false,
            username: None,
        },
    }
}

/// Command availability based on xurl + auth state.
fn build_commands_section(
    xurl_available: bool,
    authenticated: bool,
) -> HashMap<String, CommandStatus> {
    let mut cmds = HashMap::new();
    for &name in command_names_with_auth() {
        if name == "login" {
            cmds.insert(
                name.to_string(),
                CommandStatus {
                    available: xurl_available,
                    reason: if xurl_available {
                        None
                    } else {
                        Some(format!(
                            "xurl not found. {}",
                            crate::transport::XURL_INSTALL_HINT
                        ))
                    },
                },
            );
            continue;
        }
        let reqs = match requirements_for_command(name) {
            Some(r) => r,
            None => continue,
        };
        let needs_auth = reqs.accepted.iter().any(|at| !matches!(at, AuthType::None));
        let available = if needs_auth {
            xurl_available && authenticated
        } else {
            true
        };
        let reason = if !xurl_available {
            Some(format!(
                "xurl not found. {}",
                crate::transport::XURL_INSTALL_HINT
            ))
        } else if needs_auth && !authenticated {
            Some("not authenticated. Run `bird login`.".into())
        } else {
            None
        };
        cmds.insert(name.to_string(), CommandStatus { available, reason });
    }
    cmds
}

/// Build full or scoped report.
pub(crate) fn report(client: &BirdClient, scope: Option<&str>, quiet: bool) -> DoctorReport {
    let xurl = build_xurl_status(quiet);
    let auth = if xurl.available {
        detect_auth()
    } else {
        AuthState {
            authenticated: false,
            username: None,
        }
    };
    let mut commands = build_commands_section(xurl.available, auth.authenticated);
    if let Some(cmd) = scope
        && let Some(status) = commands.remove(cmd)
    {
        commands.clear();
        commands.insert(cmd.to_string(), status);
    }

    let cache = match client.db_stats() {
        Some(Ok(stats)) => {
            let path = client
                .db_path()
                .map(|p| p.display().to_string())
                .unwrap_or_else(|| "unknown".to_string());
            Some(CacheStatus {
                path,
                exists: true,
                size_mb: (stats.size_mb() * 10.0).round() / 10.0,
                max_size_mb: stats.max_size_mb() as u64,
                tweets: stats.tweet_count,
                users: stats.user_count,
                raw_responses: stats.raw_response_count,
                healthy: stats.healthy(),
            })
        }
        Some(Err(_)) => Some(CacheStatus {
            path: "unknown".to_string(),
            exists: false,
            size_mb: 0.0,
            max_size_mb: 100,
            tweets: 0,
            users: 0,
            raw_responses: 0,
            healthy: false,
        }),
        None => None,
    };

    DoctorReport {
        xurl,
        auth,
        commands,
        cache,
    }
}

fn format_pretty(report: &DoctorReport, use_color: bool, use_emoji: bool) -> String {
    use crate::output;
    let mut out = String::new();

    // Xurl section
    out.push_str(&format!("{}\n", output::section("Xurl", use_color)));
    if report.xurl.available {
        if let Some(ref path) = report.xurl.path {
            out.push_str(&format!("  path: {}\n", output::muted(path, use_color)));
        }
        if let Some(ref version) = report.xurl.version {
            out.push_str(&format!(
                "  version: {}\n",
                output::muted(version, use_color)
            ));
        }
        out.push_str(&format!(
            "  status: {}\n",
            output::success("available", use_color)
        ));
    } else {
        out.push_str(&format!(
            "  status: {}\n",
            output::error("not found", use_color)
        ));
        out.push_str(&format!("  {}\n", crate::transport::XURL_INSTALL_HINT));
    }

    // Auth section
    out.push_str(&format!("\n{}\n", output::section("Auth", use_color)));
    if report.auth.authenticated {
        if let Some(ref username) = report.auth.username {
            out.push_str(&format!(
                "  username: {}\n",
                output::muted(&format!("@{}", username), use_color)
            ));
        }
        out.push_str(&format!(
            "  status: {}\n",
            output::success("authenticated", use_color)
        ));
    } else {
        out.push_str(&format!(
            "  status: {}\n",
            output::error("not authenticated", use_color)
        ));
        out.push_str("  Run `bird login` to authenticate.\n");
    }

    // Commands section
    out.push_str(&format!("\n{}\n", output::section("Commands", use_color)));
    let mut names: Vec<_> = report.commands.keys().collect();
    names.sort();
    for name in names {
        let status = report.commands.get(name).unwrap();
        let (emoji, r) = if status.available {
            (
                output::emoji_available(use_emoji),
                output::success("available", use_color),
            )
        } else {
            let reason = status.reason.as_deref().unwrap_or("");
            (
                output::emoji_unavailable(use_emoji),
                format!(
                    "{}{}",
                    output::error("unavailable: ", use_color),
                    output::muted(reason, use_color)
                ),
            )
        };
        out.push_str(&format!(
            "  {}: {}{}\n",
            output::command(name, use_color),
            emoji,
            r
        ));
    }

    // Cache section
    if let Some(ref cache) = report.cache {
        out.push_str(&format!("\n{}\n", output::section("Cache", use_color)));
        out.push_str(&format!(
            "  path: {}\n",
            output::muted(&cache.path, use_color)
        ));
        out.push_str(&format!(
            "  size: {}\n",
            output::muted(
                &format!("{:.1} MB / {} MB", cache.size_mb, cache.max_size_mb),
                use_color
            )
        ));
        out.push_str(&format!(
            "  tweets: {}\n",
            output::muted(&cache.tweets.to_string(), use_color)
        ));
        out.push_str(&format!(
            "  users: {}\n",
            output::muted(&cache.users.to_string(), use_color)
        ));
        out.push_str(&format!(
            "  raw_responses: {}\n",
            output::muted(&cache.raw_responses.to_string(), use_color)
        ));
        let status = if cache.healthy {
            "healthy"
        } else {
            "unhealthy"
        };
        out.push_str(&format!(
            "  status: {}\n",
            if cache.healthy {
                output::success(status, use_color)
            } else {
                output::error(status, use_color)
            }
        ));
    }

    out
}

/// Run doctor: build report and print JSON (compact) or human summary.
pub fn run_doctor(
    client: &BirdClient,
    pretty: bool,
    scope: Option<&str>,
    use_color: bool,
    use_emoji: bool,
    quiet: bool,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let r = report(client, scope, quiet);
    if pretty {
        println!("{}", format_pretty(&r, use_color, use_emoji));
    } else {
        println!("{}", serde_json::to_string(&r)?);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::db::{BirdClient, CacheOpts};
    use crate::transport::tests::MockTransport;
    use std::path::Path;

    fn no_cache_client() -> BirdClient {
        let transport = Box::new(MockTransport::new(vec![]));
        BirdClient::new(
            transport,
            Path::new("/dev/null"),
            CacheOpts {
                no_store: true,
                refresh: false,
                cache_only: false,
            },
            100,
            None,
            false,
        )
    }

    #[test]
    fn doctor_report_has_commands() {
        let client = no_cache_client();
        let r = report(&client, None, false);
        assert!(!r.commands.is_empty());
        assert!(r.commands.contains_key("me"));
        assert!(r.commands.contains_key("login"));
    }

    #[test]
    fn doctor_report_scoped_has_only_that_command() {
        let client = no_cache_client();
        let r = report(&client, Some("me"), false);
        assert_eq!(r.commands.len(), 1);
        assert!(r.commands.contains_key("me"));
    }

    #[test]
    fn doctor_report_json_serializable() {
        let client = no_cache_client();
        let r = report(&client, None, false);
        let json = serde_json::to_string(&r).unwrap();
        assert!(json.contains("xurl"));
        assert!(json.contains("auth"));
        assert!(json.contains("commands"));
    }

    #[test]
    fn build_commands_not_authenticated_auth_commands_unavailable() {
        let cmds = build_commands_section(true, false);
        // login should be available (xurl is present)
        assert!(cmds.get("login").unwrap().available);
        // me requires auth, should be unavailable
        assert!(!cmds.get("me").unwrap().available);
        assert!(
            cmds.get("me")
                .unwrap()
                .reason
                .as_ref()
                .unwrap()
                .contains("not authenticated")
        );
        // usage is local-only (AuthType::None), always available
        assert!(cmds.get("usage").unwrap().available);
    }

    #[test]
    fn build_commands_authenticated_all_available() {
        let cmds = build_commands_section(true, true);
        assert!(cmds.get("me").unwrap().available);
        assert!(cmds.get("bookmarks").unwrap().available);
        assert!(cmds.get("search").unwrap().available);
    }

    #[test]
    fn build_commands_no_xurl_all_auth_commands_unavailable() {
        let cmds = build_commands_section(false, false);
        assert!(!cmds.get("login").unwrap().available);
        assert!(!cmds.get("me").unwrap().available);
        // Local-only commands still available
        assert!(cmds.get("usage").unwrap().available);
    }
}