tldr-cli 0.1.6

CLI binary for TLDR code analysis tool
Documentation
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
//! Doctor command - Check and install diagnostic tools
//!
//! Provides tool detection and installation for supported languages:
//! - Detects type checkers and linters for 16 languages
//! - Reports installation status with paths
//! - Can auto-install tools for some languages
//!
//! # Example
//!
//! ```bash
//! # Check all diagnostic tools
//! tldr doctor
//!
//! # Check with JSON output
//! tldr doctor -f json
//!
//! # Install tools for a language
//! tldr doctor --install python
//! ```

use std::collections::BTreeMap;
use std::process::Command;

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

use crate::output::{OutputFormat, OutputWriter};

/// Tool information: (tool_name, install_instructions)
type ToolDef = (&'static str, &'static str);

/// Language tool definitions: type_checker and linter for each language
struct LangTools {
    type_checker: Option<ToolDef>,
    linter: Option<ToolDef>,
}

/// Tool definitions for all supported languages
fn get_tool_info() -> BTreeMap<&'static str, LangTools> {
    let mut tools = BTreeMap::new();

    tools.insert(
        "python",
        LangTools {
            type_checker: Some(("pyright", "pip install pyright  OR  npm install -g pyright")),
            linter: Some(("ruff", "pip install ruff")),
        },
    );

    tools.insert(
        "typescript",
        LangTools {
            type_checker: Some(("tsc", "npm install -g typescript")),
            linter: None,
        },
    );

    tools.insert(
        "javascript",
        LangTools {
            type_checker: None,
            linter: Some(("eslint", "npm install -g eslint")),
        },
    );

    tools.insert("go", LangTools {
        type_checker: Some(("go", "https://go.dev/dl/")),
        linter: Some(("golangci-lint", "brew install golangci-lint  OR  go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest")),
    });

    tools.insert(
        "rust",
        LangTools {
            type_checker: Some(("cargo", "https://rustup.rs/")),
            linter: Some(("cargo-clippy", "rustup component add clippy")),
        },
    );

    tools.insert(
        "java",
        LangTools {
            type_checker: Some(("javac", "Install JDK: https://adoptium.net/")),
            linter: Some((
                "checkstyle",
                "brew install checkstyle  OR  download from checkstyle.org",
            )),
        },
    );

    tools.insert(
        "c",
        LangTools {
            type_checker: Some(("gcc", "xcode-select --install  OR  apt install gcc")),
            linter: Some((
                "cppcheck",
                "brew install cppcheck  OR  apt install cppcheck",
            )),
        },
    );

    tools.insert(
        "cpp",
        LangTools {
            type_checker: Some(("g++", "xcode-select --install  OR  apt install g++")),
            linter: Some((
                "cppcheck",
                "brew install cppcheck  OR  apt install cppcheck",
            )),
        },
    );

    tools.insert(
        "ruby",
        LangTools {
            type_checker: None,
            linter: Some(("rubocop", "gem install rubocop")),
        },
    );

    tools.insert(
        "php",
        LangTools {
            type_checker: None,
            linter: Some(("phpstan", "composer global require phpstan/phpstan")),
        },
    );

    tools.insert(
        "kotlin",
        LangTools {
            type_checker: Some(("kotlinc", "brew install kotlin  OR  sdk install kotlin")),
            linter: Some(("ktlint", "brew install ktlint")),
        },
    );

    tools.insert(
        "swift",
        LangTools {
            type_checker: Some(("swiftc", "xcode-select --install")),
            linter: Some(("swiftlint", "brew install swiftlint")),
        },
    );

    tools.insert(
        "csharp",
        LangTools {
            type_checker: Some(("dotnet", "https://dotnet.microsoft.com/download")),
            linter: None,
        },
    );

    tools.insert(
        "scala",
        LangTools {
            type_checker: Some(("scalac", "brew install scala  OR  sdk install scala")),
            linter: None,
        },
    );

    tools.insert(
        "elixir",
        LangTools {
            type_checker: Some(("elixir", "brew install elixir  OR  asdf install elixir")),
            linter: Some(("mix", "Included with Elixir")),
        },
    );

    tools.insert(
        "lua",
        LangTools {
            type_checker: None,
            linter: Some(("luacheck", "luarocks install luacheck")),
        },
    );

    tools
}

/// Install commands for languages that support auto-install
fn get_install_commands() -> BTreeMap<&'static str, Vec<&'static str>> {
    let mut cmds = BTreeMap::new();

    cmds.insert("python", vec!["pip", "install", "pyright", "ruff"]);
    cmds.insert(
        "go",
        vec![
            "go",
            "install",
            "github.com/golangci/golangci-lint/cmd/golangci-lint@latest",
        ],
    );
    cmds.insert("rust", vec!["rustup", "component", "add", "clippy"]);
    cmds.insert("ruby", vec!["gem", "install", "rubocop"]);
    cmds.insert("kotlin", vec!["brew", "install", "kotlin", "ktlint"]);
    cmds.insert("swift", vec!["brew", "install", "swiftlint"]);
    cmds.insert("lua", vec!["luarocks", "install", "luacheck"]);

    cmds
}

/// Tool status in JSON output
#[derive(Debug, Serialize)]
struct ToolStatus {
    name: String,
    installed: bool,
    path: Option<String>,
    install: Option<String>,
}

/// Language status in JSON output
#[derive(Debug, Serialize)]
struct LangStatus {
    type_checker: Option<ToolStatus>,
    linter: Option<ToolStatus>,
}

/// Check and install diagnostic tools for supported languages
///
/// Unlike most tldr commands, doctor defaults to text output for better UX.
/// Use `-f json` to get JSON output.
#[derive(Debug, Args)]
pub struct DoctorArgs {
    /// Install diagnostic tools for a specific language
    #[arg(long)]
    pub install: Option<String>,
}

impl DoctorArgs {
    /// Run the doctor command
    ///
    /// Note: Doctor defaults to text format for better UX (diagnostic output is meant to be
    /// human-readable). Use `-f json -q` to get JSON output.
    pub fn run(&self, format: OutputFormat, quiet: bool) -> Result<()> {
        if let Some(lang) = &self.install {
            self.run_install(lang)
        } else {
            self.run_check(format, quiet)
        }
    }

    /// Run install mode - install tools for a specific language
    fn run_install(&self, lang: &str) -> Result<()> {
        let lang_lower = lang.to_lowercase();
        let install_commands = get_install_commands();

        let Some(cmd_args) = install_commands.get(lang_lower.as_str()) else {
            let available: Vec<&str> = install_commands.keys().copied().collect();
            bail!(
                "No auto-install available for '{}'. Available: {}. unknown language.",
                lang,
                available.join(", ")
            );
        };

        eprintln!(
            "Installing tools for {}: {}",
            lang_lower,
            cmd_args.join(" ")
        );

        let status = Command::new(cmd_args[0]).args(&cmd_args[1..]).status();

        match status {
            Ok(exit_status) if exit_status.success() => {
                eprintln!("Installed {} tools", lang_lower);
                Ok(())
            }
            Ok(exit_status) => {
                bail!("Install failed with exit code: {:?}", exit_status.code());
            }
            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
                bail!("Command not found: {}", cmd_args[0]);
            }
            Err(e) => {
                bail!("Install failed: {}", e);
            }
        }
    }

    /// Run check mode - detect all diagnostic tools
    fn run_check(&self, format: OutputFormat, quiet: bool) -> Result<()> {
        let writer = OutputWriter::new(format, quiet);
        let tool_info = get_tool_info();

        let mut results: BTreeMap<String, LangStatus> = BTreeMap::new();

        for (lang, tools) in &tool_info {
            let type_checker = tools.type_checker.map(|(name, install_cmd)| {
                let path = which::which(name).ok().map(|p| p.display().to_string());
                let installed = path.is_some();
                ToolStatus {
                    name: name.to_string(),
                    installed,
                    path,
                    install: if installed {
                        None
                    } else {
                        Some(install_cmd.to_string())
                    },
                }
            });

            let linter = tools.linter.map(|(name, install_cmd)| {
                let path = which::which(name).ok().map(|p| p.display().to_string());
                let installed = path.is_some();
                ToolStatus {
                    name: name.to_string(),
                    installed,
                    path,
                    install: if installed {
                        None
                    } else {
                        Some(install_cmd.to_string())
                    },
                }
            });

            results.insert(
                lang.to_string(),
                LangStatus {
                    type_checker,
                    linter,
                },
            );
        }

        if writer.is_text() {
            let text = format_doctor_text(&results);
            writer.write_text(&text)?;
        } else {
            writer.write(&results)?;
        }

        Ok(())
    }
}

/// Format doctor results for human-readable text output
fn format_doctor_text(results: &BTreeMap<String, LangStatus>) -> String {
    use colored::Colorize;

    let mut output = String::new();

    // Header
    output.push_str(&"TLDR Diagnostics Check\n".bold().to_string());
    output.push_str("==================================================\n\n");

    let mut missing_count = 0;

    for (lang, status) in results {
        let mut lines: Vec<String> = Vec::new();

        if let Some(tc) = &status.type_checker {
            if tc.installed {
                lines.push(format!(
                    "  {} {} - {}",
                    "[OK]".green(),
                    tc.name,
                    tc.path.as_deref().unwrap_or("unknown")
                ));
            } else {
                lines.push(format!("  {} {} - not found", "[X]".red(), tc.name));
                if let Some(install) = &tc.install {
                    lines.push(format!("    -> {}", install));
                }
                missing_count += 1;
            }
        }

        if let Some(linter) = &status.linter {
            if linter.installed {
                lines.push(format!(
                    "  {} {} - {}",
                    "[OK]".green(),
                    linter.name,
                    linter.path.as_deref().unwrap_or("unknown")
                ));
            } else {
                lines.push(format!("  {} {} - not found", "[X]".red(), linter.name));
                if let Some(install) = &linter.install {
                    lines.push(format!("    -> {}", install));
                }
                missing_count += 1;
            }
        }

        if !lines.is_empty() {
            // Capitalize the language name for display
            let display_name = format!(
                "{}{}:",
                lang.chars().next().unwrap().to_uppercase(),
                &lang[1..]
            );
            output.push_str(&display_name);
            output.push('\n');
            for line in lines {
                output.push_str(&line);
                output.push('\n');
            }
            output.push('\n');
        }
    }

    if missing_count > 0 {
        output.push_str(&format!(
            "Missing {} tool(s). Run: tldr doctor --install <lang>\n",
            missing_count
        ));
    } else {
        output.push_str("All diagnostic tools installed!\n");
    }

    output
}