1use std::io::Write;
10
11use anyhow::{Context, Result, bail};
12use clap::CommandFactory;
13use clap_mangen::Man;
14use roff::{Roff, bold, roman};
15
16use crate::cli::args::{Cli, long_version};
17
18pub struct ManPageGenerator;
20
21impl ManPageGenerator {
22 pub fn generate_main_man_page() -> Result<String> {
24 let mut cmd = Cli::command();
25 cmd = cmd.name("vtcode");
26 if cmd.get_about().is_none() && cmd.get_long_about().is_none() {
27 cmd = cmd.about("Advanced coding agent with Decision Ledger");
28 }
29 if cmd.get_version().is_none() {
30 let version: &'static str = Box::leak(long_version(env!("CARGO_PKG_VERSION")).into_boxed_str());
32 cmd = cmd.version(version);
33 }
34 Self::render_page(cmd, None, &|buf| Self::append_main_sections(buf))
35 }
36
37 pub fn generate_command_man_page(command: &str) -> Result<String> {
39 let mut cmd = Cli::command();
40 cmd.build();
41 let Some(sub) = cmd.find_subcommand(command).filter(|sub| !sub.is_hide_set()).cloned() else {
42 bail!("Unknown command: {command}");
43 };
44 let name = sub.get_name().to_owned();
45 let examples: &[&str] = match name.as_str() {
46 "ask" => &[
47 "vtcode ask \"what is a monad?\"",
48 "echo \"summarize this\" | vtcode ask",
49 "vtcode ask --output-format json \"explain ownership in Rust\"",
50 ],
51 "benchmark" => &["vtcode benchmark"],
52 "check" => &["vtcode check ast-grep"],
53 "chat" => &["vtcode chat"],
54 "create-project" => &[
55 "vtcode create-project myapp --feature web --feature auth",
56 "vtcode create-project simple_app",
57 ],
58 "init" => &["vtcode init", "vtcode init --force"],
59 "man" => &["vtcode man", "vtcode man chat", "vtcode man chat --output chat.1"],
60 _ => &[],
61 };
62 let title = format!("vtcode-{name}");
63 let sub = sub.display_name(&title);
64 Self::render_page(sub, Some(title), &|buf| Self::append_command_sections(buf, examples))
65 }
66
67 pub fn generate_all_man_pages(dir: &std::path::Path) -> Result<usize> {
71 std::fs::create_dir_all(dir)
72 .with_context(|| format!("failed to create man page directory {}", dir.display()))?;
73
74 let mut cmd = Cli::command();
75 cmd.build();
76 let main_page = Self::generate_main_man_page()?;
77 let mut count = Self::write_page(dir, "vtcode", &main_page)?;
78 for sub in cmd.get_subcommands().filter(|sub| !sub.is_hide_set()) {
79 let name = sub.get_name();
80 count += Self::write_page(dir, &format!("vtcode-{name}"), &Self::generate_command_man_page(name)?)?;
81 }
82 Ok(count)
83 }
84
85 fn write_page(dir: &std::path::Path, name: &str, content: &str) -> Result<usize> {
87 let path = dir.join(format!("{name}.1"));
88 std::fs::write(&path, content).with_context(|| format!("failed to write man page {}", path.display()))?;
89 Ok(1)
90 }
91
92 fn render_page(
94 cmd: clap::Command,
95 title: Option<String>,
96 append: &dyn Fn(&mut Vec<u8>) -> Result<()>,
97 ) -> Result<String> {
98 let mut man = Man::new(cmd);
99 if let Some(title) = title {
100 man = man.title(title.to_uppercase());
101 }
102 let man = man
103 .date(chrono::Utc::now().format("%Y-%m-%d").to_string())
104 .manual(crate::config::constants::app::DISPLAY_NAME)
105 .source(crate::config::constants::app::DISPLAY_NAME);
106
107 let mut buf = Vec::new();
108 man.render(&mut buf).context("failed to render clap-derived man page")?;
109 append(&mut buf)?;
110 String::from_utf8(buf).context("man page output is not valid UTF-8")
111 }
112
113 fn append_main_sections(buf: &mut Vec<u8>) -> Result<()> {
115 let mut roff = Roff::new();
116 roff.control("SH", ["ENVIRONMENT"]);
117 for (name, description) in [
118 ("GEMINI_API_KEY", "API key for Google Gemini (default provider)"),
119 ("OPENAI_API_KEY", "API key for OpenAI GPT models"),
120 ("ANTHROPIC_API_KEY", "API key for Anthropic Claude models"),
121 ("DEEPSEEK_API_KEY", "API key for DeepSeek models"),
122 ("META_API_KEY", "API key for Meta AI Muse models"),
123 ("MODEL_API_KEY", "Meta AI's documented API key variable"),
124 ("ZAI_API_KEY", "API key for Z.AI GLM models"),
125 ("MOONSHOT_API_KEY", "API key for Moonshot AI Kimi models"),
126 ("OPENROUTER_API_KEY", "API key for OpenRouter models"),
127 ("NVIDIA_API_KEY", "API key for NVIDIA NIM models"),
128 ("MERGE_GATEWAY_API_KEY", "API key for Merge Gateway routes"),
129 (
130 "MERGE_GATEWAY_BASE_URL",
131 "Optional Merge Gateway endpoint override; /v1/openai selects legacy compatibility",
132 ),
133 ("AI_GATEWAY_API_KEY", "API key for Vercel AI Gateway models"),
134 (
135 "VERCEL_AI_GATEWAY_BASE_URL",
136 "Optional Vercel AI Gateway endpoint override (default: https://ai-gateway.vercel.sh/v1)",
137 ),
138 ] {
139 roff.control("TP", []).text([bold(name)]).text([roman(description)]);
140 }
141
142 roff.control("SH", ["FILES"]);
143 roff.control("TP", []).text([bold("vtcode.toml")]).text([roman(
144 "Configuration file (current directory or the canonical user config directory)",
145 )]);
146 roff.control("TP", [])
147 .text([bold(".vtcode/")])
148 .text([roman("Project cache and context directory")]);
149
150 roff.control("SH", ["SAFETY"]);
151 roff.control("TP", []).text([roman(
152 "apply_patch: reserve for reviewed diffs or small batches. For large refactors or critical files, stage local backups and prefer edit_file/write_file to avoid partial rewrites if a patch fails.",
153 )]);
154 roff.control("TP", []).text([roman(
155 "Timeout governance: tune [timeouts] in vtcode.toml to clamp tool duration. VT Code warns once execution passes the configured warning threshold so you can cancel runaway commands.",
156 )]);
157
158 roff.control("SH", ["EXAMPLES"]);
159 for (label, example) in [
160 ("Start interactive chat:", "vtcode chat"),
161 ("Ask a question:", "vtcode ask \"Explain Rust ownership\""),
162 ("Create a web project:", "vtcode create-project myapp --feature web --feature auth"),
163 ("Generate man page:", "vtcode man chat"),
164 ("Run ast-grep checks for the current workspace:", "vtcode check ast-grep"),
165 ] {
166 roff.text([roman(label)]);
167 roff.text([bold(format!(" {example}"))]);
168 }
169
170 roff.control("SH", ["SEE ALSO"]);
171 roff.text([roman("Full documentation: https://github.com/vinhnx/vtcode")]);
172 roff.text([roman("Related commands: cargo(1), rustc(1), git(1)")]);
173
174 Self::append_roff(buf, &roff)
175 }
176
177 fn append_command_sections(buf: &mut Vec<u8>, examples: &[&str]) -> Result<()> {
179 let mut roff = Roff::new();
180 if !examples.is_empty() {
181 roff.control("SH", ["EXAMPLES"]);
182 for example in examples {
183 roff.text([bold(format!(" {example}"))]);
184 }
185 }
186 roff.control("SH", ["SEE ALSO"]);
187 roff.text([bold("vtcode(1)")]);
188 Self::append_roff(buf, &roff)
189 }
190
191 fn append_roff(buf: &mut Vec<u8>, roff: &Roff) -> Result<()> {
194 let rendered = roff.render();
195 let body = match rendered.find(".SH ") {
196 Some(index) => &rendered[index..],
197 None => return Ok(()),
198 };
199 buf.write_all(body.as_bytes()).context("failed to append man page sections")?;
200 Ok(())
201 }
202}