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
use globset::{Glob, GlobSet, GlobSetBuilder};
use log::{debug, info, trace};
use pathdiff::diff_paths;
use serde_json::json;
use std::cell::RefMut;
use std::default::Default;
use std::fs;
use std::io::{BufRead, BufReader, Read, Write};
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
pub use log;
pub use serde_json as json;
pub use std::collections::HashMap;
pub use ware::Ware;
pub type RefIR<'a> = RefMut<'a, IR>;
pub type Plugin = Box<dyn Fn(RefIR) -> ()>;
mod frontmatter;
pub mod plugins;
pub struct Shtola {
ware: Ware<IR>,
ir: IR,
}
impl Shtola {
pub fn new() -> Shtola {
let config: Config = Default::default();
let ir = IR {
files: HashMap::new(),
config,
metadata: HashMap::new(),
};
Shtola {
ware: Ware::new(),
ir,
}
}
pub fn ignores(&mut self, vec: &mut Vec<String>) {
self.ir.config.ignores.append(vec);
self.ir.config.ignores.dedup();
}
pub fn source_ignores(&mut self, path: &Path) -> Result<(), std::io::Error> {
let sourcepath = self.ir.config.source.clone().canonicalize()?;
let file = fs::File::open(path)?;
let reader = BufReader::new(file);
let mut ignores: Vec<String> = reader.lines().map(|l| l.unwrap()).collect();
self.ignores(&mut ignores);
self.ignores(&mut vec![path
.canonicalize()?
.strip_prefix(sourcepath)
.unwrap_or(path)
.to_str()
.unwrap()
.to_string()]);
Ok(())
}
pub fn source<T: Into<PathBuf>>(&mut self, path: T) {
self.ir.config.source = fs::canonicalize(path.into()).unwrap();
}
pub fn destination<T: Into<PathBuf> + Clone>(&mut self, path: T) {
fs::create_dir_all(path.clone().into()).expect("Unable to create destination directory!");
self.ir.config.destination = fs::canonicalize(path.into()).unwrap();
}
pub fn clean(&mut self, b: bool) {
self.ir.config.clean = b;
}
pub fn frontmatter(&mut self, b: bool) {
self.ir.config.frontmatter = b;
}
pub fn register(&mut self, func: Box<dyn Fn(RefIR)>) {
self.ware.wrap(func);
}
pub fn build(&mut self) -> Result<IR, std::io::Error> {
trace!("Starting IR config: {:?}", self.ir.config);
if self.ir.config.clean {
info!("Cleaning before build...");
debug!("Removing {:?}", &self.ir.config.destination);
fs::remove_dir_all(&self.ir.config.destination)?;
debug!("Recreating {:?}", &self.ir.config.destination);
fs::create_dir_all(&self.ir.config.destination)
.expect("Unable to recreate destination directory!");
}
let path_clone = self.ir.config.destination.clone();
let pathstr = path_clone.to_str().expect("No destination provided!");
self.ignores(&mut vec![pathstr.to_string()]);
let mut builder = GlobSetBuilder::new();
for item in &self.ir.config.ignores {
builder.add(Glob::new(item).unwrap());
}
let set = builder.build().unwrap();
info!("Reading files...");
let files = read_dir(&self.ir.config.source, self.ir.config.frontmatter, set)?;
trace!("{} file(s) read", &files.len());
self.ir.files = files;
info!("Running plugins...");
let result_ir = self.ware.run(self.ir.clone());
info!("Writing to disk...");
write_dir(result_ir.clone(), &self.ir.config.destination)?;
info!("OK, done");
Ok(result_ir)
}
}
#[derive(Debug, Clone)]
pub struct IR {
pub files: HashMap<PathBuf, ShFile>,
pub config: Config,
pub metadata: HashMap<String, json::Value>,
}
#[derive(Debug, Clone)]
pub struct Config {
pub ignores: Vec<String>,
pub source: PathBuf,
pub destination: PathBuf,
pub clean: bool,
pub frontmatter: bool,
}
impl Default for Config {
fn default() -> Self {
Config {
ignores: vec![".git/**/*".into()],
source: PathBuf::from("."),
destination: PathBuf::from("./dest"),
clean: false,
frontmatter: true,
}
}
}
#[derive(Debug, Clone)]
pub struct ShFile {
pub frontmatter: json::Value,
pub content: Vec<u8>,
pub raw_content: Option<Vec<u8>>,
}
impl Default for ShFile {
fn default() -> ShFile {
ShFile {
content: Vec::new(),
frontmatter: json::Value::Null,
raw_content: None,
}
}
}
impl ShFile {
pub fn empty() -> ShFile {
ShFile {
frontmatter: json!(null),
content: Vec::new(),
raw_content: None,
}
}
}
fn read_dir(
source: &PathBuf,
frontmatter: bool,
set: GlobSet,
) -> Result<HashMap<PathBuf, ShFile>, std::io::Error> {
let mut result = HashMap::new();
let iters = WalkDir::new(source)
.into_iter()
.filter_entry(|e| {
let path = diff_paths(e.path(), source).unwrap();
!set.is_match(path)
})
.filter(|e| !e.as_ref().ok().unwrap().file_type().is_dir());
for entry in iters {
let entry = entry?;
let path = entry.path();
let file: ShFile;
let mut content = Vec::new();
debug!("Reading file at {:?}", &path);
fs::File::open(path)?.read_to_end(&mut content)?;
if let Ok(content_string) = std::str::from_utf8(&content) {
if frontmatter {
let (matter, content) = frontmatter::lexer(content_string);
if matter.len() > 0 {
debug!("Lexing frontmatter for {:?}", &path);
}
let json = frontmatter::to_json(&matter);
file = ShFile {
frontmatter: json,
content: content.into(),
raw_content: None,
};
} else {
file = ShFile {
frontmatter: json!(null),
content,
raw_content: None,
};
}
} else {
file = ShFile {
frontmatter: json!(null),
content: Vec::new(),
raw_content: Some(content),
}
}
let rel_path = diff_paths(path, source).unwrap();
result.insert(rel_path, file);
}
Ok(result)
}
fn write_dir(ir: IR, dest: &PathBuf) -> Result<(), std::io::Error> {
for (path, file) in ir.files {
let dest_path = dest.join(&path);
debug!("Writing {:?} to {:?}", &path, &dest_path);
fs::create_dir_all(dest_path.parent().unwrap())
.expect("Unable to create destination subdirectory!");
if let Some(raw) = file.raw_content {
fs::File::create(dest_path)?.write_all(&raw)?;
} else {
fs::File::create(dest_path)?.write_all(&file.content)?;
}
}
Ok(())
}