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
//! Command-line interface.
use std::{path::PathBuf, time::Duration};
use clap::{Parser, Subcommand};
use tracing::info;
use crate::site::{self, BuildOptions};
#[derive(Parser)]
#[command(
name = "lagrange",
version,
about = "Lagrange — a pest-based markdown documentation renderer"
)]
pub struct Cli {
#[command(subcommand)]
pub command: Command,
}
#[derive(Subcommand)]
pub enum Command {
/// Build a documentation tree into a static HTML site.
Build {
/// Source docs root. Defaults to `docs`.
#[arg(long, default_value = "docs")]
src: PathBuf,
/// Output directory. Defaults to `dist` (matching mdBook / Zola).
#[arg(long, default_value = "dist")]
out: PathBuf,
/// Optional site URL.
#[arg(long)]
site_url: Option<String>,
/// Default language. Defaults to "en".
#[arg(long, default_value = "en")]
default_lang: String,
},
/// Build once, then watch for changes and rebuild automatically.
/// When `--port` is set, also starts a lightweight HTTP server that
/// serves the output directory — no external dependency needed.
Dev {
/// Source docs root. Defaults to `docs`.
#[arg(long, default_value = "docs")]
src: PathBuf,
/// Output directory. Defaults to `dist`.
#[arg(long, default_value = "dist")]
out: PathBuf,
/// Optional site URL.
#[arg(long)]
site_url: Option<String>,
/// Default language (default "en"). Used when no query param, no
/// localStorage, and no browser-preference match.
#[arg(long, default_value = "en")]
default_lang: String,
/// Polling interval in seconds (default 1).
#[arg(long, default_value = "1")]
interval: f64,
/// HTTP port to serve on. 0 picks a random available port on all
/// interfaces and prints the chosen address.
#[arg(long, default_value = "0")]
port: u16,
/// Host to bind the dev server to. Defaults to 127.0.0.1.
#[arg(long, default_value = "127.0.0.1")]
host: String,
/// Also start a local comment backend (in-memory, port --comments-port).
/// Pages built with `mode = proxied` will find it automatically.
#[arg(long)]
comments: bool,
/// Port for the local comment backend when `--comments` is set.
#[arg(long, default_value = "18099")]
comments_port: u16,
},
/// Scaffold a new lagrange documentation site.
Init {
/// Target directory. Defaults to the current directory.
#[arg(long, default_value = ".")]
dir: PathBuf,
/// Site title.
#[arg(long)]
title: Option<String>,
/// Default language code.
#[arg(long, default_value = "en")]
lang: String,
/// Comment source to wire: none | native | github-discussions | disqus.
#[arg(long, default_value = "none")]
comments: String,
},
/// Link a comment source: fetch the IDs needed and update lagrange.toml.
CommentsLink {
/// Source root containing lagrange.toml.
#[arg(long, default_value = "docs")]
src: PathBuf,
/// GitHub repo as owner/name (for github-discussions source).
#[arg(long)]
repo: Option<String>,
/// Disqus shortname (for disqus source).
#[arg(long)]
disqus: Option<String>,
},
}
/// Run the CLI.
pub fn run(cli: Cli) -> anyhow::Result<()> {
match cli.command {
Command::Build {
src,
out,
site_url,
default_lang,
} => {
let opts = BuildOptions {
src,
out,
site_url,
default_lang: Some(default_lang),
};
site::build(&opts)
}
Command::Dev {
src,
out,
site_url,
interval,
port,
host,
default_lang,
comments,
comments_port,
} => {
info!("lagrange dev — build + watch ({interval}s poll)");
let opts = BuildOptions {
src: src.clone(),
out: out.clone(),
site_url: site_url.clone(),
default_lang: Some(default_lang.clone()),
};
site::build(&opts)?;
// Spawn the axum + tower-http static-file server on a tokio
// runtime. The runtime is kept alive for the lifetime of this
// scope (i.e. until watch_loop returns).
let rt = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()?;
let bind = if port > 0 {
format!("{host}:{port}")
} else {
format!("{host}:0")
};
let bind_addr = rt.block_on(async {
match tokio::net::TcpListener::bind(&bind).await {
Ok(listener) => {
let addr = listener.local_addr().unwrap().to_string();
info!("serving {} on http://{addr}", out.display());
let app = axum::Router::new()
.fallback_service(tower_http::services::ServeDir::new(out.clone()));
tokio::spawn(async move {
if let Err(e) = axum::serve(listener, app).await {
tracing::error!("HTTP server error: {e}");
}
});
addr
}
Err(e) => {
tracing::error!("cannot bind {bind}: {e}");
bind
}
}
});
// Optionally start a local in-memory comment backend on its own
// thread, so pages built with `mode = proxied` can talk to it.
if comments {
let cport = comments_port;
std::thread::spawn(move || {
if let Err(e) = crate::scaffold::run_dev_comments(cport) {
tracing::error!("comment backend error: {e}");
}
});
info!("comment backend on http://127.0.0.1:{comments_port} (in-memory)");
}
info!(
"watching {} … open http://{bind_addr}/index.html?lang={dl}",
src.display(),
dl = default_lang,
);
// watch_loop blocks forever; rt stays alive in this scope.
watch_loop(src, out, site_url, default_lang, interval)?;
Ok(())
}
Command::Init {
dir,
title,
lang,
comments,
} => crate::scaffold::init_site(&dir, title.as_deref(), &lang, &comments),
Command::CommentsLink { src, repo, disqus } => {
crate::scaffold::comments_link(&src, repo.as_deref(), disqus.as_deref())
}
}
}
/// Poll every `interval` seconds; when any file under `src` changes, rebuild.
fn watch_loop(
src: PathBuf,
out: PathBuf,
site_url: Option<String>,
default_lang: String,
interval: f64,
) -> anyhow::Result<()> {
let interval = Duration::from_secs_f64(interval.max(0.2));
// Snapshot all files under `src` with their modification times.
let mut last_mtimes = snapshot_mtimes(&src)?;
loop {
std::thread::sleep(interval);
let current = match snapshot_mtimes(&src) {
Ok(c) => c,
Err(e) => {
tracing::warn!("cannot read {}: {e}", src.display());
continue;
}
};
if current != last_mtimes {
info!("files changed; rebuilding …");
let opts = BuildOptions {
src: src.clone(),
out: out.clone(),
site_url: site_url.clone(),
default_lang: Some(default_lang.clone()),
};
if let Err(e) = site::build(&opts) {
tracing::error!("rebuild failed: {e:?}");
}
last_mtimes = current;
}
}
}
/// Collect (relative_path, modified_time) for every file under `root`.
fn snapshot_mtimes(root: &PathBuf) -> anyhow::Result<Vec<(String, std::time::SystemTime)>> {
let mut out = Vec::new();
collect_mtimes(root, root, &mut out)?;
out.sort();
Ok(out)
}
fn collect_mtimes(
root: &PathBuf,
dir: &PathBuf,
out: &mut Vec<(String, std::time::SystemTime)>,
) -> anyhow::Result<()> {
for entry in std::fs::read_dir(dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
collect_mtimes(root, &path, out)?;
} else if path.is_file() {
let rel = path.strip_prefix(root).unwrap_or(&path);
let mtime = std::fs::metadata(&path).and_then(|m| m.modified())?;
out.push((rel.to_string_lossy().to_string(), mtime));
}
}
Ok(())
}