Skip to main content

stem/
manual.rs

1use std::collections::HashMap;
2use std::path::Path;
3use std::sync::OnceLock;
4use std::time::Duration;
5
6use indexmap::IndexMap;
7use rusqlite::{Connection, params};
8
9use crate::configuration::Config;
10use crate::download::download;
11use crate::enumerations::string_enum;
12use crate::error::{Error, Result};
13use crate::process_inspection::{
14    call_with_environment, is_available, is_bsd, is_mac, is_slackware,
15};
16
17pub const MANUAL_URL: &str =
18    "https://gitlab.torproject.org/tpo/core/tor/-/raw/main/doc/man/tor.1.md";
19const SCHEMA_VERSION: i64 = 1;
20const EMBEDDED_SETTINGS: &str = include_str!("data/settings.cfg");
21const EMBEDDED_MANUAL: &str = include_str!("data/cached_manual.cfg");
22const SCHEMA: [&str; 5] = [
23    "CREATE TABLE metadata(name TEXT, synopsis TEXT, description TEXT, man_commit TEXT, \
24    stem_commit TEXT)",
25    "CREATE TABLE commandline(name TEXT PRIMARY KEY, description TEXT)",
26    "CREATE TABLE signals(name TEXT PRIMARY KEY, description TEXT)",
27    "CREATE TABLE files(name TEXT PRIMARY KEY, description TEXT)",
28    "CREATE TABLE torrc(key TEXT PRIMARY KEY, name TEXT, category TEXT, usage TEXT, \
29    summary TEXT, description TEXT, position INTEGER)",
30];
31
32string_enum!(Category {
33    General = "GENERAL",
34    Client = "CLIENT",
35    Relay = "RELAY",
36    Directory = "DIRECTORY",
37    Authority = "AUTHORITY",
38    HiddenService = "HIDDEN_SERVICE",
39    DenialOfService = "DENIAL_OF_SERVICE",
40    Testing = "TESTING",
41    Unknown = "UNKNOWN",
42});
43
44const CATEGORY_SECTIONS: [(&str, Category); 8] = [
45    ("GENERAL OPTIONS", Category::General),
46    ("CLIENT OPTIONS", Category::Client),
47    ("SERVER OPTIONS", Category::Relay),
48    ("DIRECTORY SERVER OPTIONS", Category::Directory),
49    ("DIRECTORY AUTHORITY SERVER OPTIONS", Category::Authority),
50    ("HIDDEN SERVICE OPTIONS", Category::HiddenService),
51    (
52        "DENIAL OF SERVICE MITIGATION OPTIONS",
53        Category::DenialOfService,
54    ),
55    ("TESTING NETWORK OPTIONS", Category::Testing),
56];
57
58#[derive(Debug, thiserror::Error)]
59#[error("{message}")]
60pub struct SchemaMismatch {
61    pub message: String,
62    pub database_schema: i64,
63    pub library_schema: i64,
64}
65
66impl From<SchemaMismatch> for Error {
67    fn from(mismatch: SchemaMismatch) -> Self {
68        Error::Io(std::io::Error::other(mismatch.message))
69    }
70}
71
72#[derive(Debug, Clone, PartialEq, Eq)]
73pub struct ConfigOption {
74    pub name: String,
75    pub category: String,
76    pub usage: String,
77    pub summary: String,
78    pub description: String,
79}
80
81#[derive(Debug, Clone, PartialEq, Eq, Default)]
82pub struct Manual {
83    pub name: String,
84    pub synopsis: String,
85    pub description: String,
86    pub commandline_options: IndexMap<String, String>,
87    pub signals: IndexMap<String, String>,
88    pub files: IndexMap<String, String>,
89    pub config_options: IndexMap<String, ConfigOption>,
90    pub man_commit: Option<String>,
91    pub stem_commit: Option<String>,
92    pub schema: Option<i64>,
93}
94
95struct ManualSettings {
96    summaries: HashMap<String, String>,
97    important: Vec<String>,
98    event_descriptions: HashMap<String, String>,
99}
100
101fn settings() -> &'static ManualSettings {
102    static SETTINGS: OnceLock<ManualSettings> = OnceLock::new();
103    SETTINGS.get_or_init(|| {
104        let mut config = Config::new();
105        config.load_str(EMBEDDED_SETTINGS, true);
106        let mut settings = ManualSettings {
107            summaries: HashMap::new(),
108            important: config
109                .get_values("manual.important")
110                .iter()
111                .map(|name| name.to_lowercase())
112                .collect(),
113            event_descriptions: HashMap::new(),
114        };
115        for key in config.keys() {
116            let Some(value) = config.get_value(&key) else {
117                continue;
118            };
119            if key.starts_with("manual.summary.") {
120                settings
121                    .summaries
122                    .insert(key.to_lowercase(), value.to_string());
123            }
124            if let Some(event) = key.strip_prefix("event.description.") {
125                settings
126                    .event_descriptions
127                    .insert(event.to_lowercase(), value.to_string());
128            }
129        }
130        settings
131    })
132}
133
134pub fn event_description(event: &str) -> Option<&'static str> {
135    settings()
136        .event_descriptions
137        .get(&event.to_lowercase())
138        .map(String::as_str)
139}
140
141pub fn is_important(option: &str) -> bool {
142    settings().important.contains(&option.to_lowercase())
143}
144
145fn join_lines(lines: &[String]) -> String {
146    let mut result: Vec<String> = Vec::new();
147    for line in lines {
148        match line.is_empty() {
149            true => {
150                if result.last().is_some_and(|last| last != "\n") {
151                    result.push("\n".to_string());
152                }
153            }
154            false => result.push(format!("{line}\n")),
155        }
156    }
157    result.concat().trim().to_string()
158}
159
160fn base_indentation(content: &[String]) -> usize {
161    content
162        .iter()
163        .filter(|line| line.starts_with(' '))
164        .filter(|line| !line.trim().is_empty())
165        .map(|line| line.len() - line.trim_start_matches(' ').len())
166        .min()
167        .map_or(7, |minimum| minimum.min(7))
168}
169
170fn get_categories(content: &[String]) -> IndexMap<String, Vec<String>> {
171    let mut content = content;
172    if content.first().is_some_and(|line| line.contains("TOR(1)")) {
173        content = &content[1..];
174    }
175    if content.last().is_some_and(|line| line.starts_with("Tor")) {
176        content = &content[..content.len() - 1];
177    }
178    let indentation = " ".repeat(base_indentation(content));
179    let mut categories = IndexMap::new();
180    let mut category: Option<String> = None;
181    let mut lines: Vec<String> = Vec::new();
182    for raw in content {
183        let line = raw
184            .replace('\u{2019}', "'")
185            .replace('\u{2014}', "-")
186            .replace('\u{b7}', "*");
187        if !line.is_empty() && !line.starts_with(' ') {
188            if let Some(name) = category.take() {
189                if lines.last().is_some_and(String::is_empty) {
190                    lines.pop();
191                }
192                categories.insert(name, std::mem::take(&mut lines));
193            }
194            category = Some(line.trim().to_string());
195            lines = Vec::new();
196        } else {
197            lines.push(
198                line.strip_prefix(indentation.as_str())
199                    .unwrap_or(&line)
200                    .to_string(),
201            );
202        }
203    }
204    if let Some(name) = category {
205        categories.insert(name, lines);
206    }
207    categories
208}
209
210fn indented_descriptions(lines: &[String]) -> IndexMap<String, String> {
211    let mut options: IndexMap<String, Vec<String>> = IndexMap::new();
212    let mut last_argument: Option<String> = None;
213    for line in lines {
214        if line == "    Note" {
215            last_argument = None;
216        } else if !line.is_empty() && !line.starts_with(' ') {
217            options.insert(line.clone(), Vec::new());
218            last_argument = Some(line.clone());
219        } else if let (Some(argument), Some(rest)) =
220            (&last_argument, line.strip_prefix("    "))
221        {
222            options
223                .entry(argument.clone())
224                .or_default()
225                .push(rest.to_string());
226        }
227    }
228    options
229        .into_iter()
230        .filter(|(_, description)| !description.is_empty())
231        .map(|(argument, description)| (argument, description.join(" ")))
232        .collect()
233}
234
235fn add_config_options(
236    options: &mut IndexMap<String, ConfigOption>,
237    category: &Category,
238    lines: &[String],
239) {
240    fn add_option(
241        options: &mut IndexMap<String, ConfigOption>,
242        category: &Category,
243        title: &str,
244        description: &[String],
245    ) {
246        let is_sentence =
247            title.ends_with(':') || (title.ends_with('.') && !title.ends_with("..."));
248        if title.contains("PER INSTANCE OPTIONS") || is_sentence {
249            return;
250        }
251        if title.contains(", ") {
252            for subtitle in title.split(", ") {
253                add_option(options, category, subtitle, description);
254            }
255            return;
256        }
257        let (name, usage) = title.split_once(' ').unwrap_or((title, ""));
258        let summary = settings()
259            .summaries
260            .get(&format!("manual.summary.{}", name.to_lowercase()))
261            .cloned()
262            .unwrap_or_default();
263        options.insert(
264            name.to_string(),
265            ConfigOption {
266                name: name.to_string(),
267                category: category.to_string(),
268                usage: usage.to_string(),
269                summary,
270                description: join_lines(description).trim().to_string(),
271            },
272        );
273    }
274    let mut lines = lines;
275    let end_index = lines
276        .iter()
277        .enumerate()
278        .filter(|(_, line)| {
279            line.contains("The following options") || line.contains("PER SERVICE OPTIONS")
280        })
281        .map(|(index, _)| index)
282        .max();
283    if let Some(index) = end_index {
284        lines = &lines[index..];
285        if let Some(blank) = lines.iter().position(String::is_empty) {
286            lines = &lines[blank..];
287        }
288    }
289    let mut last_title: Option<String> = None;
290    let mut description: Vec<String> = Vec::new();
291    for line in lines {
292        if !line.is_empty() && !line.starts_with(' ') {
293            if let Some(title) = last_title.take() {
294                add_option(options, category, &title, &description);
295            }
296            last_title = Some(line.clone());
297            description = Vec::new();
298        } else {
299            description.push(line.strip_prefix("    ").unwrap_or(line).to_string());
300        }
301    }
302    if let Some(title) = last_title {
303        add_option(options, category, &title, &description);
304    }
305}
306
307pub async fn download_man_page(path: &Path, url: &str, timeout: Duration) -> Result<()> {
308    if !is_available("pandoc") {
309        return Err(Error::Io(std::io::Error::other(
310            "We require pandoc to convert tor's manual into a man page",
311        )));
312    }
313    let directory = tempfile_directory()?;
314    let markdown_path = directory.join("tor.1.md");
315    let manual_path = directory.join("tor.1");
316    let outcome = async {
317        let content = download(url, Some(timeout), 0).await.map_err(|error| {
318            Error::DownloadFailed {
319                url: url.to_string(),
320                message: format!(
321                    "Unable to download tor's manual from {url} to {}: {error}",
322                    markdown_path.display()
323                ),
324            }
325        })?;
326        std::fs::write(&markdown_path, content)?;
327        let source = markdown_path.to_string_lossy().into_owned();
328        let target = manual_path.to_string_lossy().into_owned();
329        let command = [
330            "pandoc", "-s", "-f", "markdown", "-t", "man", &source, "-o", &target,
331        ];
332        call_with_environment(&command, false, None, &[]).map_err(|error| {
333            Error::Io(std::io::Error::other(format!(
334                "Unable to run '{}': {error}",
335                command.join(" ")
336            )))
337        })?;
338        if !manual_path.exists() {
339            return Err(Error::Io(std::io::Error::other(
340                "no man page was generated",
341            )));
342        }
343        if let Some(parent) = path
344            .parent()
345            .filter(|parent| !parent.as_os_str().is_empty())
346        {
347            std::fs::create_dir_all(parent)?;
348        }
349        std::fs::copy(&manual_path, path)?;
350        Ok(())
351    }
352    .await;
353    let _ = std::fs::remove_dir_all(&directory);
354    outcome
355}
356
357fn tempfile_directory() -> Result<std::path::PathBuf> {
358    let suffix: u64 = rand::random();
359    let path = std::env::temp_dir().join(format!("stem-manual-{suffix:016x}"));
360    std::fs::create_dir(&path)?;
361    Ok(path)
362}
363
364impl Manual {
365    pub fn from_cache(path: Option<&Path>) -> Result<Self> {
366        match path {
367            None => {
368                let mut config = Config::new();
369                config.load_str(EMBEDDED_MANUAL, false);
370                Ok(Self::from_config(&config))
371            }
372            Some(path)
373                if path
374                    .extension()
375                    .is_some_and(|extension| extension == "sqlite") =>
376            {
377                Self::from_sqlite_cache(path)
378            }
379            Some(path) => {
380                let mut config = Config::new();
381                config.load_with_options(path, false)?;
382                Ok(Self::from_config(&config))
383            }
384        }
385    }
386
387    fn from_config(config: &Config) -> Self {
388        let mut config_options: IndexMap<String, ConfigOption> = IndexMap::new();
389        for key in config.keys() {
390            let Some(rest) = key.strip_prefix("config_options.") else {
391                continue;
392            };
393            let name = rest.split('.').next().unwrap_or_default().to_string();
394            if config_options.contains_key(&name) {
395                continue;
396            }
397            let field = |attribute: &str| {
398                config
399                    .get_value(&format!("config_options.{name}.{attribute}"))
400                    .unwrap_or_default()
401                    .to_string()
402            };
403            config_options.insert(
404                name.clone(),
405                ConfigOption {
406                    name: field("name"),
407                    category: field("category"),
408                    usage: field("usage"),
409                    summary: field("summary"),
410                    description: field("description"),
411                },
412            );
413        }
414        Self {
415            name: config.get_value("name").unwrap_or_default().to_string(),
416            synopsis: config.get_value("synopsis").unwrap_or_default().to_string(),
417            description: config
418                .get_value("description")
419                .unwrap_or_default()
420                .to_string(),
421            commandline_options: config.get_mapping("commandline_options"),
422            signals: config.get_mapping("signals"),
423            files: config.get_mapping("files"),
424            config_options,
425            man_commit: config.get_value("man_commit").map(str::to_string),
426            stem_commit: config.get_value("stem_commit").map(str::to_string),
427            schema: None,
428        }
429    }
430
431    fn from_sqlite_cache(path: &Path) -> Result<Self> {
432        if !path.exists() {
433            return Err(Error::Io(std::io::Error::other(format!(
434                "{} doesn't exist",
435                path.display()
436            ))));
437        }
438        let failure = |error: rusqlite::Error| {
439            Error::Io(std::io::Error::other(format!(
440                "Failed to read database metadata from {}: {error}",
441                path.display()
442            )))
443        };
444        let connection =
445            Connection::open_with_flags(path, rusqlite::OpenFlags::SQLITE_OPEN_READ_ONLY)
446                .map_err(failure)?;
447        let schema: i64 = connection
448            .query_row("SELECT version FROM schema", [], |row| row.get(0))
449            .map_err(failure)?;
450        if schema != SCHEMA_VERSION {
451            return Err(SchemaMismatch {
452                message: format!(
453                    "Stem's current manual schema version is {SCHEMA_VERSION}, but {} \
454                    was version {schema}",
455                    path.display()
456                ),
457                database_schema: schema,
458                library_schema: SCHEMA_VERSION,
459            }
460            .into());
461        }
462        let (name, synopsis, description, man_commit, stem_commit) = connection
463            .query_row(
464                "SELECT name, synopsis, description, man_commit, stem_commit FROM \
465                metadata",
466                [],
467                |row| {
468                    Ok((
469                        row.get(0)?,
470                        row.get(1)?,
471                        row.get(2)?,
472                        row.get(3)?,
473                        row.get(4)?,
474                    ))
475                },
476            )
477            .map_err(failure)?;
478        let pairs = |table: &str| -> Result<IndexMap<String, String>> {
479            let mut statement = connection
480                .prepare(&format!("SELECT name, description FROM {table}"))
481                .map_err(failure)?;
482            let rows = statement
483                .query_map([], |row| {
484                    Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?))
485                })
486                .map_err(failure)?;
487            rows.collect::<std::result::Result<IndexMap<_, _>, _>>()
488                .map_err(failure)
489        };
490        let mut config_options = IndexMap::new();
491        let mut statement = connection
492            .prepare(
493                "SELECT name, category, usage, summary, description FROM torrc \
494                ORDER BY position",
495            )
496            .map_err(failure)?;
497        let rows = statement
498            .query_map([], |row| {
499                Ok(ConfigOption {
500                    name: row.get(0)?,
501                    category: row.get(1)?,
502                    usage: row.get(2)?,
503                    summary: row.get(3)?,
504                    description: row.get(4)?,
505                })
506            })
507            .map_err(failure)?;
508        for option in rows {
509            let option = option.map_err(failure)?;
510            config_options.insert(option.name.clone(), option);
511        }
512        Ok(Self {
513            name,
514            synopsis,
515            description,
516            commandline_options: pairs("commandline")?,
517            signals: pairs("signals")?,
518            files: pairs("files")?,
519            config_options,
520            man_commit,
521            stem_commit,
522            schema: Some(schema),
523        })
524    }
525
526    pub fn from_man(man_path: &str) -> Result<Self> {
527        let has_encoding_argument = !is_mac() && !is_bsd() && !is_slackware();
528        let mut command = vec!["man"];
529        if has_encoding_argument {
530            command.push("--encoding=ascii");
531        }
532        command.extend(["-P", "cat", man_path]);
533        let output =
534            call_with_environment(&command, false, None, &[("MANWIDTH", "10000000")])
535                .map_err(|error| {
536                    Error::Io(std::io::Error::other(format!(
537                        "Unable to run '{}': {error}",
538                        command.join(" ")
539                    )))
540                })?;
541        let categories = get_categories(&output);
542        let mut config_options = IndexMap::new();
543        for (header, category) in &CATEGORY_SECTIONS {
544            add_config_options(
545                &mut config_options,
546                category,
547                categories.get(*header).map_or(&[], Vec::as_slice),
548            );
549        }
550        for (category, lines) in &categories {
551            let is_extra = category.ends_with(" OPTIONS")
552                && !CATEGORY_SECTIONS
553                    .iter()
554                    .any(|(header, _)| header == category)
555                && !matches!(
556                    category.as_str(),
557                    "COMMAND-LINE OPTIONS" | "NON-PERSISTENT OPTIONS"
558                );
559            if is_extra {
560                add_config_options(&mut config_options, &Category::Unknown, lines);
561            }
562        }
563        let section = |name: &str| categories.get(name).map_or(&[][..], Vec::as_slice);
564        Ok(Self {
565            name: join_lines(section("NAME")),
566            synopsis: join_lines(section("SYNOPSIS")),
567            description: join_lines(section("DESCRIPTION")),
568            commandline_options: indented_descriptions(section("COMMAND-LINE OPTIONS")),
569            signals: indented_descriptions(section("SIGNALS")),
570            files: indented_descriptions(section("FILES")),
571            config_options,
572            ..Default::default()
573        })
574    }
575
576    pub async fn from_remote(timeout: Duration) -> Result<Self> {
577        Self::from_url(MANUAL_URL, timeout).await
578    }
579
580    pub async fn from_url(url: &str, timeout: Duration) -> Result<Self> {
581        let directory = tempfile_directory()?;
582        let path = directory.join("tor.1");
583        let outcome = async {
584            download_man_page(&path, url, timeout).await?;
585            Self::from_man(&path.to_string_lossy())
586        }
587        .await;
588        let _ = std::fs::remove_dir_all(&directory);
589        outcome
590    }
591
592    pub fn save(&self, path: &Path) -> Result<()> {
593        match path
594            .extension()
595            .is_some_and(|extension| extension == "sqlite")
596        {
597            true => self.save_as_sqlite(path),
598            false => self.save_as_config(path),
599        }
600    }
601
602    fn save_as_sqlite(&self, path: &Path) -> Result<()> {
603        let failure =
604            |error: rusqlite::Error| Error::Io(std::io::Error::other(error.to_string()));
605        let temporary = path.with_extension("sqlite.new");
606        let _ = std::fs::remove_file(&temporary);
607        {
608            let connection = Connection::open(&temporary).map_err(failure)?;
609            connection
610                .execute("CREATE TABLE schema(version INTEGER)", [])
611                .map_err(failure)?;
612            connection
613                .execute(
614                    "INSERT INTO schema(version) VALUES (?1)",
615                    params![SCHEMA_VERSION],
616                )
617                .map_err(failure)?;
618            for statement in SCHEMA {
619                connection.execute(statement, []).map_err(failure)?;
620            }
621            connection
622                .execute(
623                    "INSERT INTO metadata(name, synopsis, description, man_commit, \
624                    stem_commit) VALUES (?1,?2,?3,?4,?5)",
625                    params![
626                        self.name,
627                        self.synopsis,
628                        self.description,
629                        self.man_commit,
630                        self.stem_commit
631                    ],
632                )
633                .map_err(failure)?;
634            for (table, entries) in [
635                ("commandline", &self.commandline_options),
636                ("signals", &self.signals),
637                ("files", &self.files),
638            ] {
639                for (name, description) in entries {
640                    connection
641                        .execute(
642                            &format!(
643                                "INSERT INTO {table}(name, description) VALUES (?1,?2)"
644                            ),
645                            params![name, description],
646                        )
647                        .map_err(failure)?;
648                }
649            }
650            for (position, option) in self.config_options.values().enumerate() {
651                connection
652                    .execute(
653                        "INSERT INTO torrc(key, name, category, usage, summary, \
654                        description, position) VALUES (?1,?2,?3,?4,?5,?6,?7)",
655                        params![
656                            option.name.to_uppercase(),
657                            option.name,
658                            option.category,
659                            option.usage,
660                            option.summary,
661                            option.description,
662                            position as i64
663                        ],
664                    )
665                    .map_err(failure)?;
666            }
667        }
668        let _ = std::fs::remove_file(path);
669        std::fs::rename(&temporary, path)?;
670        Ok(())
671    }
672
673    fn save_as_config(&self, path: &Path) -> Result<()> {
674        let mut config = Config::new();
675        config.set("name", &self.name, true);
676        config.set("synopsis", &self.synopsis, true);
677        config.set("description", &self.description, true);
678        if let Some(commit) = &self.man_commit {
679            config.set("man_commit", commit, true);
680        }
681        if let Some(commit) = &self.stem_commit {
682            config.set("stem_commit", commit, true);
683        }
684        for (key, entries) in [
685            ("commandline_options", &self.commandline_options),
686            ("signals", &self.signals),
687            ("files", &self.files),
688        ] {
689            for (name, description) in entries {
690                config.set(key, &format!("{name} => {description}"), false);
691            }
692        }
693        for (key, option) in &self.config_options {
694            config.set(
695                &format!("config_options.{key}.category"),
696                &option.category,
697                true,
698            );
699            config.set(&format!("config_options.{key}.name"), &option.name, true);
700            config.set(&format!("config_options.{key}.usage"), &option.usage, true);
701            config.set(
702                &format!("config_options.{key}.summary"),
703                &option.summary,
704                true,
705            );
706            config.set(
707                &format!("config_options.{key}.description"),
708                &option.description,
709                true,
710            );
711        }
712        config.save(path)
713    }
714}
715
716pub fn manual_differences(previous: &Manual, current: &Manual) -> String {
717    let mut lines: Vec<String> = Vec::new();
718    let text_attributes = [
719        ("name", &previous.name, &current.name),
720        ("synopsis", &previous.synopsis, &current.synopsis),
721        ("description", &previous.description, &current.description),
722    ];
723    for (attribute, old, new) in text_attributes {
724        if old != new {
725            lines.push(format!("* Manual's {attribute} attribute changed\n"));
726            lines.push(format!("  Previously...\n\n{old}\n"));
727            lines.push(format!("  Updating to...\n\n{new}"));
728            lines.push("\n".to_string());
729        }
730    }
731    for (attribute, old, new) in [
732        (
733            "commandline_options",
734            &previous.commandline_options,
735            &current.commandline_options,
736        ),
737        ("signals", &previous.signals, &current.signals),
738        ("files", &previous.files, &current.files),
739    ] {
740        if old == new {
741            continue;
742        }
743        lines.push(format!("* Manual's {attribute} attribute changed\n"));
744        for (key, value) in new
745            .iter()
746            .filter(|(key, value)| old.get(*key) != Some(*value))
747        {
748            lines.push(format!("  adding {key} => {value}"));
749        }
750        for (key, value) in old
751            .iter()
752            .filter(|(key, value)| new.get(*key) != Some(*value))
753        {
754            lines.push(format!("  removing {key} => {value}"));
755        }
756        lines.push("\n".to_string());
757    }
758    if previous.config_options != current.config_options {
759        lines.push("* Manual's config_options attribute changed\n".to_string());
760        for (name, option) in &current.config_options {
761            match previous.config_options.get(name) {
762                None => lines.push(format!("  adding new config option => {name}")),
763                Some(old) if old != option => {
764                    for (attribute, new_value, old_value) in [
765                        ("name", &option.name, &old.name),
766                        ("category", &option.category, &old.category),
767                        ("usage", &option.usage, &old.usage),
768                        ("summary", &option.summary, &old.summary),
769                        ("description", &option.description, &old.description),
770                    ] {
771                        if new_value != old_value {
772                            lines.push(format!(
773                                "  modified {name} ({attribute}) => {new_value}"
774                            ));
775                        }
776                    }
777                }
778                Some(_) => {}
779            }
780        }
781        for name in previous
782            .config_options
783            .keys()
784            .filter(|name| !current.config_options.contains_key(*name))
785        {
786            lines.push(format!("  removing config option => {name}"));
787        }
788        lines.push("\n".to_string());
789    }
790    lines.join("\n")
791}