main.rs

  1use anyhow::{Context, Result};
  2use mdbook::BookItem;
  3use mdbook::book::{Book, Chapter};
  4use mdbook::preprocess::CmdPreprocessor;
  5use regex::Regex;
  6use settings::KeymapFile;
  7use std::borrow::Cow;
  8use std::collections::{HashMap, HashSet};
  9use std::io::{self, Read};
 10use std::process;
 11use std::sync::{LazyLock, OnceLock};
 12use util::paths::PathExt;
 13
 14static KEYMAP_MACOS: LazyLock<KeymapFile> = LazyLock::new(|| {
 15    load_keymap("keymaps/default-macos.json").expect("Failed to load MacOS keymap")
 16});
 17
 18static KEYMAP_LINUX: LazyLock<KeymapFile> = LazyLock::new(|| {
 19    load_keymap("keymaps/default-linux.json").expect("Failed to load Linux keymap")
 20});
 21
 22static ALL_ACTIONS: LazyLock<Vec<ActionDef>> = LazyLock::new(dump_all_gpui_actions);
 23
 24const FRONT_MATTER_COMMENT: &str = "<!-- ZED_META {} -->";
 25
 26fn main() -> Result<()> {
 27    zlog::init();
 28    zlog::init_output_stderr();
 29    // call a zed:: function so everything in `zed` crate is linked and
 30    // all actions in the actual app are registered
 31    zed::stdout_is_a_pty();
 32    let args = std::env::args().skip(1).collect::<Vec<_>>();
 33
 34    match args.get(0).map(String::as_str) {
 35        Some("supports") => {
 36            let renderer = args.get(1).expect("Required argument");
 37            let supported = renderer != "not-supported";
 38            if supported {
 39                process::exit(0);
 40            } else {
 41                process::exit(1);
 42            }
 43        }
 44        Some("postprocess") => handle_postprocessing()?,
 45        _ => handle_preprocessing()?,
 46    }
 47
 48    Ok(())
 49}
 50
 51#[derive(Debug, Clone, PartialEq, Eq, Hash)]
 52enum PreprocessorError {
 53    ActionNotFound { action_name: String },
 54    DeprecatedActionUsed { used: String, should_be: String },
 55    InvalidFrontmatterLine(String),
 56}
 57
 58impl PreprocessorError {
 59    fn new_for_not_found_action(action_name: String) -> Self {
 60        for action in &*ALL_ACTIONS {
 61            for alias in action.deprecated_aliases {
 62                if alias == &action_name {
 63                    return PreprocessorError::DeprecatedActionUsed {
 64                        used: action_name.clone(),
 65                        should_be: action.name.to_string(),
 66                    };
 67                }
 68            }
 69        }
 70        PreprocessorError::ActionNotFound {
 71            action_name: action_name.to_string(),
 72        }
 73    }
 74}
 75
 76impl std::fmt::Display for PreprocessorError {
 77    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 78        match self {
 79            PreprocessorError::InvalidFrontmatterLine(line) => {
 80                write!(f, "Invalid frontmatter line: {}", line)
 81            }
 82            PreprocessorError::ActionNotFound { action_name } => {
 83                write!(f, "Action not found: {}", action_name)
 84            }
 85            PreprocessorError::DeprecatedActionUsed { used, should_be } => write!(
 86                f,
 87                "Deprecated action used: {} should be {}",
 88                used, should_be
 89            ),
 90        }
 91    }
 92}
 93
 94fn handle_preprocessing() -> Result<()> {
 95    let mut stdin = io::stdin();
 96    let mut input = String::new();
 97    stdin.read_to_string(&mut input)?;
 98
 99    let (_ctx, mut book) = CmdPreprocessor::parse_input(input.as_bytes())?;
100
101    let mut errors = HashSet::<PreprocessorError>::new();
102
103    handle_frontmatter(&mut book, &mut errors);
104    template_and_validate_keybindings(&mut book, &mut errors);
105    template_and_validate_actions(&mut book, &mut errors);
106
107    if !errors.is_empty() {
108        const ANSI_RED: &str = "\x1b[31m";
109        const ANSI_RESET: &str = "\x1b[0m";
110        for error in &errors {
111            eprintln!("{ANSI_RED}ERROR{ANSI_RESET}: {}", error);
112        }
113        return Err(anyhow::anyhow!("Found {} errors in docs", errors.len()));
114    }
115
116    serde_json::to_writer(io::stdout(), &book)?;
117
118    Ok(())
119}
120
121fn handle_frontmatter(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
122    let frontmatter_regex = Regex::new(r"(?s)^\s*---(.*?)---").unwrap();
123    for_each_chapter_mut(book, |chapter| {
124        let new_content = frontmatter_regex.replace(&chapter.content, |caps: &regex::Captures| {
125            let frontmatter = caps[1].trim();
126            let frontmatter = frontmatter.trim_matches(&[' ', '-', '\n']);
127            let mut metadata = HashMap::<String, String>::default();
128            for line in frontmatter.lines() {
129                let Some((name, value)) = line.split_once(':') else {
130                    errors.insert(PreprocessorError::InvalidFrontmatterLine(format!(
131                        "{}: {}",
132                        chapter_breadcrumbs(chapter),
133                        line
134                    )));
135                    continue;
136                };
137                let name = name.trim();
138                let value = value.trim();
139                metadata.insert(name.to_string(), value.to_string());
140            }
141            FRONT_MATTER_COMMENT.replace(
142                "{}",
143                &serde_json::to_string(&metadata).expect("Failed to serialize metadata"),
144            )
145        });
146        if let Cow::Owned(content) = new_content {
147            chapter.content = content;
148        }
149    });
150}
151
152fn template_and_validate_keybindings(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
153    let regex = Regex::new(r"\{#kb (.*?)\}").unwrap();
154
155    for_each_chapter_mut(book, |chapter| {
156        chapter.content = regex
157            .replace_all(&chapter.content, |caps: &regex::Captures| {
158                let action = caps[1].trim();
159                if find_action_by_name(action).is_none() {
160                    errors.insert(PreprocessorError::new_for_not_found_action(
161                        action.to_string(),
162                    ));
163                    return String::new();
164                }
165                let macos_binding = find_binding("macos", action).unwrap_or_default();
166                let linux_binding = find_binding("linux", action).unwrap_or_default();
167
168                if macos_binding.is_empty() && linux_binding.is_empty() {
169                    return "<div>No default binding</div>".to_string();
170                }
171
172                format!("<kbd class=\"keybinding\">{macos_binding}|{linux_binding}</kbd>")
173            })
174            .into_owned()
175    });
176}
177
178fn template_and_validate_actions(book: &mut Book, errors: &mut HashSet<PreprocessorError>) {
179    let regex = Regex::new(r"\{#action (.*?)\}").unwrap();
180
181    for_each_chapter_mut(book, |chapter| {
182        chapter.content = regex
183            .replace_all(&chapter.content, |caps: &regex::Captures| {
184                let name = caps[1].trim();
185                let Some(action) = find_action_by_name(name) else {
186                    errors.insert(PreprocessorError::new_for_not_found_action(
187                        name.to_string(),
188                    ));
189                    return String::new();
190                };
191                format!("<code class=\"hljs\">{}</code>", &action.human_name)
192            })
193            .into_owned()
194    });
195}
196
197fn find_action_by_name(name: &str) -> Option<&ActionDef> {
198    ALL_ACTIONS
199        .binary_search_by(|action| action.name.cmp(name))
200        .ok()
201        .map(|index| &ALL_ACTIONS[index])
202}
203
204fn find_binding(os: &str, action: &str) -> Option<String> {
205    let keymap = match os {
206        "macos" => &KEYMAP_MACOS,
207        "linux" | "freebsd" => &KEYMAP_LINUX,
208        _ => unreachable!("Not a valid OS: {}", os),
209    };
210
211    // Find the binding in reverse order, as the last binding takes precedence.
212    keymap.sections().rev().find_map(|section| {
213        section.bindings().rev().find_map(|(keystroke, a)| {
214            if name_for_action(a.to_string()) == action {
215                Some(keystroke.to_string())
216            } else {
217                None
218            }
219        })
220    })
221}
222
223/// Removes any configurable options from the stringified action if existing,
224/// ensuring that only the actual action name is returned. If the action consists
225/// only of a string and nothing else, the string is returned as-is.
226///
227/// Example:
228///
229/// This will return the action name unmodified.
230///
231/// ```
232/// let action_as_str = "assistant::Assist";
233/// let action_name = name_for_action(action_as_str);
234/// assert_eq!(action_name, "assistant::Assist");
235/// ```
236///
237/// This will return the action name with any trailing options removed.
238///
239///
240/// ```
241/// let action_as_str = "\"editor::ToggleComments\", {\"advance_downwards\":false}";
242/// let action_name = name_for_action(action_as_str);
243/// assert_eq!(action_name, "editor::ToggleComments");
244/// ```
245fn name_for_action(action_as_str: String) -> String {
246    action_as_str
247        .split(",")
248        .next()
249        .map(|name| name.trim_matches('"').to_string())
250        .unwrap_or(action_as_str)
251}
252
253fn chapter_breadcrumbs(chapter: &Chapter) -> String {
254    let mut breadcrumbs = Vec::with_capacity(chapter.parent_names.len() + 1);
255    breadcrumbs.extend(chapter.parent_names.iter().map(String::as_str));
256    breadcrumbs.push(chapter.name.as_str());
257    format!("[{:?}] {}", chapter.source_path, breadcrumbs.join(" > "))
258}
259
260fn load_keymap(asset_path: &str) -> Result<KeymapFile> {
261    let content = util::asset_str::<settings::SettingsAssets>(asset_path);
262    KeymapFile::parse(content.as_ref())
263}
264
265fn for_each_chapter_mut<F>(book: &mut Book, mut func: F)
266where
267    F: FnMut(&mut Chapter),
268{
269    book.for_each_mut(|item| {
270        let BookItem::Chapter(chapter) = item else {
271            return;
272        };
273        func(chapter);
274    });
275}
276
277#[derive(Debug, serde::Serialize)]
278struct ActionDef {
279    name: &'static str,
280    human_name: String,
281    deprecated_aliases: &'static [&'static str],
282}
283
284fn dump_all_gpui_actions() -> Vec<ActionDef> {
285    let mut actions = gpui::generate_list_of_all_registered_actions()
286        .map(|action| ActionDef {
287            name: action.name,
288            human_name: command_palette::humanize_action_name(action.name),
289            deprecated_aliases: action.deprecated_aliases,
290        })
291        .collect::<Vec<ActionDef>>();
292
293    actions.sort_by_key(|a| a.name);
294
295    actions
296}
297
298fn handle_postprocessing() -> Result<()> {
299    let logger = zlog::scoped!("render");
300    let mut ctx = mdbook::renderer::RenderContext::from_json(io::stdin())?;
301    let output = ctx
302        .config
303        .get_mut("output")
304        .expect("has output")
305        .as_table_mut()
306        .expect("output is table");
307    let zed_html = output.remove("zed-html").expect("zed-html output defined");
308    let default_description = zed_html
309        .get("default-description")
310        .expect("Default description not found")
311        .as_str()
312        .expect("Default description not a string")
313        .to_string();
314    let default_title = zed_html
315        .get("default-title")
316        .expect("Default title not found")
317        .as_str()
318        .expect("Default title not a string")
319        .to_string();
320
321    output.insert("html".to_string(), zed_html);
322    mdbook::Renderer::render(&mdbook::renderer::HtmlHandlebars::new(), &ctx)?;
323    let ignore_list = ["toc.html"];
324
325    let root_dir = ctx.destination.clone();
326    let mut files = Vec::with_capacity(128);
327    let mut queue = Vec::with_capacity(64);
328    queue.push(root_dir.clone());
329    while let Some(dir) = queue.pop() {
330        for entry in std::fs::read_dir(&dir).context(dir.to_sanitized_string())? {
331            let Ok(entry) = entry else {
332                continue;
333            };
334            let file_type = entry.file_type().context("Failed to determine file type")?;
335            if file_type.is_dir() {
336                queue.push(entry.path());
337            }
338            if file_type.is_file()
339                && matches!(
340                    entry.path().extension().and_then(std::ffi::OsStr::to_str),
341                    Some("html")
342                )
343            {
344                if ignore_list.contains(&&*entry.file_name().to_string_lossy()) {
345                    zlog::info!(logger => "Ignoring {}", entry.path().to_string_lossy());
346                } else {
347                    files.push(entry.path());
348                }
349            }
350        }
351    }
352
353    zlog::info!(logger => "Processing {} `.html` files", files.len());
354    let meta_regex = Regex::new(&FRONT_MATTER_COMMENT.replace("{}", "(.*)")).unwrap();
355    for file in files {
356        let contents = std::fs::read_to_string(&file)?;
357        let mut meta_description = None;
358        let mut meta_title = None;
359        let contents = meta_regex.replace(&contents, |caps: &regex::Captures| {
360            let metadata: HashMap<String, String> = serde_json::from_str(&caps[1]).with_context(|| format!("JSON Metadata: {:?}", &caps[1])).expect("Failed to deserialize metadata");
361            for (kind, content) in metadata {
362                match kind.as_str() {
363                    "description" => {
364                        meta_description = Some(content);
365                    }
366                    "title" => {
367                        meta_title = Some(content);
368                    }
369                    _ => {
370                        zlog::warn!(logger => "Unrecognized frontmatter key: {} in {:?}", kind, pretty_path(&file, &root_dir));
371                    }
372                }
373            }
374            String::new()
375        });
376        let meta_description = meta_description.as_ref().unwrap_or_else(|| {
377            zlog::warn!(logger => "No meta description found for {:?}", pretty_path(&file, &root_dir));
378            &default_description
379        });
380        let page_title = extract_title_from_page(&contents, pretty_path(&file, &root_dir));
381        let meta_title = meta_title.as_ref().unwrap_or_else(|| {
382            zlog::debug!(logger => "No meta title found for {:?}", pretty_path(&file, &root_dir));
383            &default_title
384        });
385        let meta_title = format!("{} | {}", page_title, meta_title);
386        zlog::trace!(logger => "Updating {:?}", pretty_path(&file, &root_dir));
387        let contents = contents.replace("#description#", meta_description);
388        let contents = title_regex()
389            .replace(&contents, |_: &regex::Captures| {
390                format!("<title>{}</title>", meta_title)
391            })
392            .to_string();
393        // let contents = contents.replace("#title#", &meta_title);
394        std::fs::write(file, contents)?;
395    }
396    return Ok(());
397
398    fn pretty_path<'a>(
399        path: &'a std::path::PathBuf,
400        root: &'a std::path::PathBuf,
401    ) -> &'a std::path::Path {
402        path.strip_prefix(&root).unwrap_or(path)
403    }
404    fn extract_title_from_page(contents: &str, pretty_path: &std::path::Path) -> String {
405        let title_tag_contents = &title_regex()
406            .captures(contents)
407            .with_context(|| format!("Failed to find title in {:?}", pretty_path))
408            .expect("Page has <title> element")[1];
409
410        title_tag_contents
411            .trim()
412            .strip_suffix("- Zed")
413            .unwrap_or(title_tag_contents)
414            .trim()
415            .to_string()
416    }
417}
418
419fn title_regex() -> &'static Regex {
420    static TITLE_REGEX: OnceLock<Regex> = OnceLock::new();
421    TITLE_REGEX.get_or_init(|| Regex::new(r"<title>\s*(.*?)\s*</title>").unwrap())
422}