Skip to main content

setu_cli/
parser.rs

1use std::{fs, path::PathBuf};
2
3use pulldown_cmark::{Event, Parser, Tag, TextMergeStream};
4use reqwest::Client;
5
6use crate::checker::MarkdownCheckResult;
7
8pub async fn parse_markdown(path: &PathBuf, concerns: &Option<Vec<u16>>) -> MarkdownCheckResult {
9    let markdown_input = match fs::read_to_string(&path) {
10        Ok(contents) => contents.to_string(),
11        Err(_) => {
12            return MarkdownCheckResult {
13                success: false,
14                checks: vec![],
15            };
16        }
17    };
18
19    let iterator = TextMergeStream::new(Parser::new(&markdown_input));
20    let mut remotes: Vec<String> = Vec::new();
21    let mut locals: Vec<String> = Vec::new();
22
23    for event in iterator {
24        if let Event::Start(Tag::Link { dest_url, .. }) = event {
25            let destination = dest_url.to_string();
26            if is_remote_url(&destination) {
27                remotes.push(destination);
28            } else {
29                locals.push(destination);
30            }
31        }
32    }
33    let client = Client::new();
34    let remote_checks = crate::checker::remote::evaluate(path, remotes, &client, concerns).await;
35    let local_checks = crate::checker::local::evaluate(path, locals);
36
37    let checks = local_checks.into_iter().chain(remote_checks).collect();
38
39    MarkdownCheckResult {
40        success: true,
41        checks,
42    }
43}
44
45fn is_remote_url(url: &str) -> bool {
46    url.starts_with("https://") || url.starts_with("http://")
47}