/
main.rs
146 lines (123 loc) · 4.14 KB
/
main.rs
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
use clap::Parser;
use color_eyre::Result;
use eyre::WrapErr;
use rayon::prelude::*;
use regex::Regex;
use simple_pagerank::Pagerank;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
lazy_static::lazy_static! {
static ref LINK_RE: Regex = Regex::new(r"\[\[(?P<name>[^#]+?)(#\^[\w\d\-])?(\|.+?)?\]\]").unwrap();
}
#[derive(Debug, Parser)]
struct Opts {
#[clap(long, default_value("."))]
root: PathBuf,
/// A value between 0 and 100
#[clap(long, default_value("80"))]
damping_factor: u8,
}
impl Opts {
fn run(&self) -> Result<()> {
let files = self.discover_files().wrap_err("could not discover files")?;
let links = self
.discover_links(&files)
.context("could not discover links")?;
let pagerank = self
.calculate_pagerank(&links)
.wrap_err("could not calculate pagerank")?;
println!(
"{}",
pagerank
.nodes()
.iter()
.map(|(node, score)| format!("{score:.3}\t{node}"))
.collect::<Vec<String>>()
.join("\n")
);
Ok(())
}
fn discover_files(&self) -> Result<Vec<PathBuf>> {
let mut types_builder = ignore::types::TypesBuilder::new();
types_builder.add_defaults();
types_builder.select("markdown");
let mut out = Vec::new();
for entry_res in ignore::WalkBuilder::new(&self.root)
.types(
types_builder
.build()
.wrap_err("could not build matching types")?,
)
.build()
{
match entry_res {
Ok(entry) => match entry.file_type() {
Some(ft) if ft.is_file() => out.push(entry.into_path()),
_ => continue,
},
Err(problem) => return Err(problem).wrap_err("could not read files"),
}
}
Ok(out)
}
fn discover_links(&self, files: &Vec<PathBuf>) -> Result<HashMap<String, HashSet<String>>> {
let mut out = HashMap::with_capacity(files.len());
let links: Vec<Result<(String, HashSet<String>)>> = files
.par_iter()
.map(|path| {
let name = path
.file_stem()
.and_then(|stem| stem.to_str())
.ok_or_else(|| {
eyre::eyre!(
"no stem for `{}`, or filename wasn't unicode",
path.display()
)
})?
.to_string();
let contents = std::fs::read_to_string(path)
.wrap_err_with(|| format!("could not read {}", path.display()))?;
let mut links = HashSet::with_capacity(1);
for capture in LINK_RE.captures_iter(&contents) {
if let Some(name) = capture.name("name") {
links.insert(name.as_str().to_string());
}
}
Ok((name, links))
})
.collect();
for link_res in links {
match link_res {
Ok((name, links)) => {
out.insert(name, links);
}
Err(problem) => return Err(problem).wrap_err("could not calculate link"),
}
}
return Ok(out);
}
fn calculate_pagerank<'links>(
&self,
links: &'links HashMap<String, HashSet<String>>,
) -> Result<Pagerank<&'links String>> {
let mut pagerank = Pagerank::new();
pagerank
.set_damping_factor(self.damping_factor)
.map_err(|e| eyre::eyre!(e))
.wrap_err("could not set damping factor")?;
for (name, out_edges) in links {
for link in out_edges {
pagerank.add_edge(name, link)
}
}
pagerank.calculate();
Ok(pagerank)
}
}
fn main() {
let opts = Opts::parse();
if let Err(problem) = opts.run() {
eprintln!("{problem:?}");
std::process::exit(1);
}
}