mull 0.55.0

A tool for managing a wiki stored in a plain text file.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
mod analyzer;
mod assertions;
mod cancellation;
mod error;
mod escaping;
mod file_tree;
mod format;
mod language_server;
mod line_index;
mod lsp_position;
mod parser;
mod path_util;
mod propagation;
mod scoring;
mod scripts;
mod spelled_path;
mod validator;
mod wiki;

use crate::{
    analyzer::analyze,
    cancellation::CancellationFlag,
    error::{Error, format_errors},
    format::CodeStr,
    line_index::LineIndex,
    path_util::relative_path,
    wiki::{PageTitle, WIKI_EXTENSION},
};
use clap::{ArgAction, Args, Parser, Subcommand as ClapSubcommand};
use similar::TextDiff;
use std::{
    env, fs,
    path::{Path, PathBuf},
    process::exit,
    sync::Arc,
};

// This struct represents the command-line arguments.
#[derive(Parser)]
#[command(
    about = concat!(
        env!("CARGO_PKG_DESCRIPTION"),
        "\n\n",
        "More information can be found at: ",
        env!("CARGO_PKG_HOMEPAGE"),
    ),
    version,
    display_name = "Mull",
    disable_version_flag = true
)]
struct Cli {
    #[arg(short, long, help = "Print version", action = ArgAction::Version)]
    _version: Option<bool>,

    #[command(subcommand)]
    command: Option<Subcommand>,
}

// These are the operations the program can perform.
#[derive(ClapSubcommand)]
enum Subcommand {
    #[command(about = "Check a wiki")]
    Check(WikiArgs),

    #[command(about = "Format a wiki (default)")]
    Format(WikiArgs),

    #[command(about = "Run the scripts which compute blocks in a wiki, then format it")]
    Run(WikiArgs),

    #[command(about = "Print the content of a page in a wiki")]
    Page(PageArgs),

    #[command(about = "Start the language server (editors use this)")]
    LanguageServer,
}

// These are the arguments for the operations that act on a wiki. Without a path, the wiki is the
// one a script is running in, if any, or else the nearest one.
#[derive(Args, Default)]
struct WikiArgs {
    #[arg(long, value_name = "PATH", help = "Specify the path to the wiki")]
    path: Option<PathBuf>,
}

// These are the arguments for printing a page.
#[derive(Args)]
struct PageArgs {
    #[arg(help = "The page's title")]
    title: String,

    #[command(flatten)]
    wiki_args: WikiArgs,
}

// These are the operations which act on a wiki once it's loaded.
enum Operation {
    Check,
    Format,
    Run,
    Page(String),
}

// Let the fun begin!
#[tokio::main]
async fn main() {
    // Jump to the entrypoint and handle any resulting errors.
    if let Err(errors) = entry().await {
        eprintln!("{}", format_errors(&errors));
        exit(1);
    }
}

// Run the requested operation.
#[allow(
    clippy::too_many_lines,
    reason = "The function dispatches each subcommand once the wiki they share is loaded."
)]
async fn entry() -> Result<(), Vec<Error>> {
    // Parse the command-line arguments.
    let cli = Cli::parse();

    // Start the language server without requiring a wiki, or select the requested wiki operation.
    let (operation, WikiArgs { path }) = match cli
        .command
        .unwrap_or(Subcommand::Format(WikiArgs::default()))
    {
        Subcommand::Check(wiki_args) => (Operation::Check, wiki_args),
        Subcommand::Format(wiki_args) => (Operation::Format, wiki_args),
        Subcommand::Run(wiki_args) => (Operation::Run, wiki_args),
        Subcommand::Page(PageArgs { title, wiki_args }) => (Operation::Page(title), wiki_args),
        Subcommand::LanguageServer => {
            language_server::run().await;
            return Ok(());
        }
    };

    // Select the wiki and make its path relative when it's contained in the current directory.
    let current_directory = env::current_dir().map_err(|error| {
        vec![Error::new(
            "Unable to determine the current directory.",
            None,
            None,
            Some(Arc::new(error)),
            None,
        )]
    })?;
    let wiki_path = relative_path(
        &current_directory,
        &path
            .or_else(|| env::var_os("MULL_WIKI").map(PathBuf::from))
            .map_or_else(|| find_wiki(&current_directory), Ok)
            .map_err(|error| vec![error])?,
    )
    .to_owned();

    // Load the wiki and require its contents to be valid UTF-8.
    let wiki_bytes = fs::read(&wiki_path).map_err(|error| {
        vec![Error::new(
            "Unable to read the wiki.",
            Some(&wiki_path),
            None,
            Some(Arc::new(error)),
            None,
        )]
    })?;
    let wiki_contents = String::from_utf8(wiki_bytes).map_err(|error| {
        vec![Error::new(
            "The wiki isn't valid UTF-8.",
            Some(&wiki_path),
            None,
            Some(Arc::new(error)),
            None,
        )]
    })?;

    // Print a page, or run the scripts and save the result, reporting any scripts which failed.
    match operation {
        Operation::Page(title) => return print_page(&wiki_path, &wiki_contents, &title),
        Operation::Run => {
            let (run_contents, failures) = scripts::run(&wiki_path, &wiki_contents)?;
            if run_contents != wiki_contents {
                fs::write(&wiki_path, run_contents).map_err(|error| {
                    vec![Error::new(
                        "Unable to write the wiki.",
                        Some(&wiki_path),
                        None,
                        Some(Arc::new(error)),
                        None,
                    )]
                })?;
            }
            if !failures.is_empty() {
                return Err(failures);
            }
            println!("Ran the scripts in {}.", wiki_path.code_str());
            return Ok(());
        }
        Operation::Check | Operation::Format => {}
    }

    // Analyze and render the wiki. The command line has nothing to cancel, so the analysis always
    // runs to completion.
    let rendered_wiki = analyze(
        Some(&wiki_path),
        &wiki_contents,
        &CancellationFlag::default(),
    )
    .assume_completed()?
    .to_string();

    // Accept a canonical wiki, then either format a noncanonical one or reject it with a diff.
    if wiki_contents == rendered_wiki {
        println!("Wiki {} looks good.", wiki_path.code_str());
    } else if matches!(operation, Operation::Format) {
        fs::write(&wiki_path, rendered_wiki).map_err(|error| {
            vec![Error::new(
                "Unable to write the wiki.",
                Some(&wiki_path),
                None,
                Some(Arc::new(error)),
                None,
            )]
        })?;

        // Report that the wiki was formatted.
        println!("Formatted {}.", wiki_path.code_str());
    } else {
        return Err(vec![Error::new(
            &format!(
                "The wiki isn't formatted correctly. Run {} to format it.\n\n{}",
                "mull format".code_str(),
                TextDiff::from_lines(&wiki_contents, &rendered_wiki)
                    .unified_diff()
                    .header("wiki", "rendered"),
            ),
            Some(&wiki_path),
            None,
            None,
            None,
        )]);
    }

    // Everything succeeded.
    Ok(())
}

// Print a page's content as formatting would write it, for scripts to read.
fn print_page(wiki_path: &Path, wiki_contents: &str, title: &str) -> Result<(), Vec<Error>> {
    // Read the wiki without validating it, which needs only its syntax.
    let (wiki, errors) = parser::parse(
        Some(wiki_path),
        wiki_contents,
        &LineIndex::new(wiki_contents),
    );
    if !errors.is_empty() {
        return Err(errors);
    }

    // Find the page.
    let page = PageTitle::parse(title)
        .ok()
        .and_then(|title| wiki.pages.get(&title))
        .ok_or_else(|| {
            vec![Error::new(
                &format!("Page {} not found.", title.code_str()),
                Some(wiki_path),
                None,
                None,
                None,
            )]
        })?;
    println!("{}", wiki.page_content(page));
    Ok(())
}

// Find the nearest wiki in the current directory or one of its ancestors.
fn find_wiki(current_directory: &Path) -> Result<PathBuf, Error> {
    // Search each directory from nearest to farthest, choosing files deterministically.
    for directory in current_directory.ancestors() {
        let entries = fs::read_dir(directory).map_err(|error| {
            Error::new(
                &format!("Unable to read {}.", directory.code_str()),
                None,
                None,
                Some(Arc::new(error)),
                None,
            )
        })?;
        let mut wikis = Vec::<PathBuf>::new();

        // Inspect each directory entry and retain regular wikis.
        for entry in entries {
            let entry = entry.map_err(|error| {
                Error::new(
                    &format!("Unable to read an entry in {}.", directory.code_str()),
                    None,
                    None,
                    Some(Arc::new(error)),
                    None,
                )
            })?;
            let path = entry.path();
            let has_wiki_extension = path
                .extension()
                .and_then(|extension| extension.to_str())
                .is_some_and(|extension| extension.eq_ignore_ascii_case(WIKI_EXTENSION));
            if has_wiki_extension {
                let metadata = fs::metadata(&path).map_err(|error| {
                    Error::new(
                        &format!("Unable to inspect {}.", path.code_str()),
                        None,
                        None,
                        Some(Arc::new(error)),
                        None,
                    )
                })?;
                if metadata.is_file() {
                    wikis.push(path);
                }
            }
        }
        wikis.sort();

        // Reject multiple wikis because there's no unambiguous choice.
        if wikis.len() > 1 {
            let file_names = wikis
                .iter()
                .map(|path| {
                    Path::new(
                        path.file_name()
                            .expect("A directory entry's path should end with its name."),
                    )
                    .code_str()
                    .to_string()
                })
                .collect::<Vec<String>>()
                .join(", ");
            return Err(Error::new(
                &format!(
                    "Found multiple wikis in {}: {file_names}",
                    directory.code_str(),
                ),
                None,
                None,
                None,
                None,
            ));
        }

        // Return the wiki in this directory, if one exists.
        if let Some(wiki) = wikis.into_iter().next() {
            return Ok(wiki);
        }
    }

    // Report that the search completed without finding a wiki.
    Err(Error::new(
        &format!(
            "No wiki found in {} or its ancestors.",
            current_directory.code_str(),
        ),
        None,
        None,
        None,
        None,
    ))
}

#[cfg(test)]
mod tests {
    use super::{Cli, PageArgs, Subcommand, WikiArgs};
    use clap::{CommandFactory, Parser};
    use std::path::PathBuf;

    #[test]
    fn verify_cli() {
        Cli::command().debug_assert();
    }

    // Ensure all supported subcommands can be parsed.
    #[test]
    fn parse_subcommands() {
        assert!(matches!(
            Cli::try_parse_from(["mull", "check"]).unwrap().command,
            Some(Subcommand::Check(_)),
        ));
        assert!(matches!(
            Cli::try_parse_from(["mull", "format"]).unwrap().command,
            Some(Subcommand::Format(_)),
        ));
        assert!(matches!(
            Cli::try_parse_from(["mull", "run"]).unwrap().command,
            Some(Subcommand::Run(_)),
        ));
        let Some(Subcommand::Page(PageArgs { title, .. })) =
            Cli::try_parse_from(["mull", "page", "Home"])
                .unwrap()
                .command
        else {
            panic!("The page subcommand should be parsed.");
        };
        assert_eq!(title, "Home");
        assert!(matches!(
            Cli::try_parse_from(["mull", "language-server"])
                .unwrap()
                .command,
            Some(Subcommand::LanguageServer),
        ));
    }

    // Accept an explicit wiki path after the subcommand that acts on the wiki.
    #[test]
    fn parse_path() {
        for subcommand in ["check", "format", "run"] {
            let Some(
                Subcommand::Check(WikiArgs { path })
                | Subcommand::Format(WikiArgs { path })
                | Subcommand::Run(WikiArgs { path }),
            ) = Cli::try_parse_from(["mull", subcommand, "--path", "notes.mull"])
                .unwrap()
                .command
            else {
                panic!("The {subcommand} subcommand should be parsed.");
            };
            assert_eq!(path, Some(PathBuf::from("notes.mull")));
        }
    }
}