bfom 0.1.47

Brendan's Flavor of Markdown: I'll build my own markdown format, what could go wrong?
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
// module that does the conversion
use bfom_lib::{
  utilities::processing::{copy_files, file_find_markdown},
  Converter, FrontMatter,
};

use std::collections::HashMap;
use std::{fs, io::Error, path::Path, path::PathBuf};

// to convert the toml into
use bfom_lib::utilities::processing::uppercase_first_letter;
use serde::Deserialize;

fn main() -> Result<(), Error> {
  println!("Stating BFOM converter.");
  let converter = Controller::converter_get_config();
  converter.run()?;

  println!("Finished BFOM converter.");
  Ok(())
}

#[derive(Debug)]
pub struct PartialItem {
  src: PathBuf,
  dest: PathBuf,
  filename: String,
  processed: String,
  template: Option<String>,
  template_type: Template,
  front_matter: FrontMatter,
}

#[derive(Debug, Deserialize)]
#[serde(tag = "type", content = "path")]
enum Template {
  Adjacent,
  AdjacentFolder,
  Root(PathBuf),
  RootFolder(PathBuf),
  General(PathBuf),
  Powerpoint(PathBuf),
  Default,
}

#[derive(Debug, Eq, Ord, PartialEq, PartialOrd, Clone)]
struct IndexInfo {
  number: String,
  title: String,
  date: String,
  skip_index: bool,
}

#[derive(Debug, Deserialize)]
pub struct TemplateConfig {
  #[serde(default = "TemplateConfig::default_enable")]
  enable: bool,
  #[serde(default = "TemplateConfig::default_order")]
  order: Vec<Template>,
}

impl TemplateConfig {
  fn default_enable() -> bool {
    false
  }
  fn default_order() -> Vec<Template> {
    vec![]
  }
}

#[derive(Debug, Deserialize)]
pub struct Indexing {
  #[serde(default = "Indexing::default_roots")]
  roots: Vec<PathBuf>,
  #[serde(default = "Indexing::default_render_drafts")]
  render_drafts: bool,
}

impl Indexing {
  fn default_roots() -> Vec<PathBuf> {
    vec![]
  }
  fn default_render_drafts() -> bool {
    false
  }
}

#[derive(Debug, Deserialize)]
pub struct Controller {
  #[serde(default = "Controller::default_html_void")]
  html_void: Vec<String>,
  #[serde(default = "Controller::default_indentation")]
  indentation: usize,
  #[serde(default = "Controller::default_src")]
  src: PathBuf,
  #[serde(default = "Controller::default_dest")]
  dest: PathBuf,
  #[serde(default = "Controller::default_dont_copy_paths")]
  dont_copy_paths: Vec<PathBuf>,
  template: TemplateConfig,
  indexing: Indexing,
}

impl Default for Controller {
  fn default() -> Self {
    Self::new()
  }
}

// uses templates to get the desired result
impl Controller {
  // takes the external config if provided and returns an instance of itself
  fn default_indentation() -> usize {
    2
  }
  fn default_src() -> PathBuf {
    "./src".parse().unwrap()
  }
  fn default_dest() -> PathBuf {
    "./build".parse().unwrap()
  }
  fn default_html_void() -> Vec<String> {
    vec!["area", "base", "br", "col", "command", "embed", "hr", "img", "input", "keygen", "link", "meta", "param", "source", "track", "wbr"]
      .iter()
      .map(|item| item.to_string())
      .collect::<Vec<String>>()
  }

  fn default_dont_copy_paths() -> Vec<PathBuf> {
    vec![]
  }

  pub fn new() -> Self {
    // default config
    Self {
      indentation: Self::default_indentation(),
      src: Self::default_src(),
      dest: Self::default_dest(),
      html_void: Self::default_html_void(),
      dont_copy_paths: Self::default_dont_copy_paths(),
      template: TemplateConfig {
        enable: TemplateConfig::default_enable(),
        order: TemplateConfig::default_order(),
      },
      indexing: Indexing {
        roots: Indexing::default_roots(),
        render_drafts: Indexing::default_render_drafts(),
      },
    }
  }

  pub fn converter_get_config() -> Self {
    println!("Searching for .md.toml file");
    if let Ok(config_file) = fs::read_to_string(".md.toml") {
      if let Ok(mut config) = toml::from_str::<Self>(&config_file) {
        println!("Found .md.toml, overriding defaults.");
        // sort teh roots to avoid namespace clashes
        config.indexing.roots.sort();
        config.indexing.roots.reverse();

        // the config file overrides teh defaults
        // anything not in the file is filled in from the defaults
        return config;
      }
    }

    println!("No .md.toml file, using defaults.");
    Self::new()
  }

  // this manages the conversion
  pub fn run(&self) -> Result<(), Error> {
    // wipe the existing dest folder
    if self.dest.is_dir() {
      fs::remove_dir_all(&self.dest)?;
    }

    // get all teh files in teh specified folder
    let files = file_find_markdown(&self.src)?;

    copy_files(&self.src, &self.dest, &["md"], &self.dont_copy_paths)?;

    //set up the converter
    let mut converter = Converter::new(self.html_void.clone(), self.indentation);

    let mut partials = vec![];

    // iterate through the files  replacing the extension, the src to dest
    // iterate through the files  replacing the extension, the src to dest
    for file in files {
      let src = file.clone();

      // send it to the converter function
      let (processed, front_matter) = converter.convert_file(&src, 1)?;

      // get teh template, if applicable
      let (template, template_type) = self.template_get(&src, &front_matter);

      if !self.indexing.render_drafts && front_matter.draft {
        continue;
      }

      // start off the same path
      let mut dest = src.clone();

      let filename_tmp = src.file_name().unwrap_or_default();
      let filename_tmp2 = filename_tmp.to_str().unwrap_or_default();
      let filename = filename_tmp2.replace(".md", "");

      if let Some(parent) = src.parent() {
        if let Ok(stripped) = parent.strip_prefix(&self.src) {
          dest = Path::new(&self.dest).join(stripped);

          if let Some(x) = &front_matter.slug {
            dest = dest.join(x);
          } else {
            dest = dest.join(&filename);
          }
        }
      }
      dest.set_extension("html");

      // we know the src folders exist, but check if the dest ones do
      if let Some(parent) = dest.parent() {
        fs::create_dir_all(parent)?
      }

      // dont have all the info yet
      partials.push(PartialItem {
        src,
        dest,
        filename,
        processed,
        template,
        template_type,
        front_matter,
      });
    }

    // get all teh info needed from the partials
    let index_info = self.get_index_info(&partials);

    // feed that info back in
    for partial in partials {
      // merge template and processed
      let merged = self.template_merge(&partial, &index_info);

      // save it
      fs::write(&partial.dest, merged)?;
    }

    let template_root = self.template_get_root();
    // determine the folder where the templates are stored
    for index_root in &self.indexing.roots {
      if let Some(index_info_tmp) = index_info.get(index_root) {
        let mut tmp = index_info_tmp.clone().to_vec();
        tmp.sort_by(|a, b| {
          // if the fields are numbered then use that
          if let Ok(x) = a.number.parse::<i64>() {
            if let Ok(y) = b.number.parse::<i64>() {
              return x.cmp(&y);
            }
          }
          b.number.cmp(&a.number)
        });
        tmp.reverse();
        if let Some(index_index) = self.create_index_root(&template_root.join(format!("{}_index.html", index_root.to_str().unwrap_or_default())), &tmp, index_root) {
          fs::write(self.dest.join(format!("{}/index.html", index_root.to_str().unwrap_or_default())), index_index)?;
        };
      }
    }

    Ok(())
  }

  fn template_get_root(&self) -> PathBuf {
    for item in &self.template.order {
      if let Template::Root(path) = item {
        return path.to_owned();
      }
    }
    PathBuf::from("template")
  }

  fn template_get(&self, input: &Path, fm: &FrontMatter) -> (Option<String>, Template) {
    if !self.template.enable {
      return (None, Template::Default);
    }

    for item in &self.template.order {
      match item {
        Template::Adjacent => {
          // check for <path>/<name>.html
          let mut input_test = input.to_path_buf();
          input_test.set_extension("html");

          if let Ok(template_file) = fs::read_to_string(input_test) {
            return (Some(template_file), Template::Adjacent);
          }
        }
        Template::General(template) => {
          // see if general is set in teh config
          // then see if that files actually exists
          if let Ok(template_file) = fs::read_to_string(template) {
            return (Some(template_file), Template::General(Default::default()));
          }
        }
        Template::AdjacentFolder => {
          // check for <path>/<name>.html
          let path = input.to_path_buf();

          // need to check if there is a html file the same name as the folder

          // using soem of my original code
          if let Some(parent) = path.parent() {
            if let Some(parent_name) = parent.file_name() {
              let mut to_be_tested = PathBuf::from(parent);
              to_be_tested.push(parent_name);
              to_be_tested.set_extension("html");

              // test if there is a file with teh same name as the folder this resides in
              if fs::read_to_string(&to_be_tested).is_ok() {
                if let Ok(template_file) = fs::read_to_string(&to_be_tested) {
                  return (Some(template_file), Template::AdjacentFolder);
                }
              }
            }
          }
        }

        // special types of config
        Template::Powerpoint(template) => {
          if fm.slides {
            if let Ok(template_file) = fs::read_to_string(template) {
              return (Some(template_file), Template::Powerpoint(Default::default()));
            }
          }
        }
        Template::Root(template) => {
          for root in &self.indexing.roots {
            if (input.to_str().unwrap_or_default()).contains(root.to_str().unwrap_or_default()) {
              if let Ok(template_file) = fs::read_to_string(&format!("{}/{}.html", template.to_str().unwrap_or_default(), root.to_str().unwrap_or_default())) {
                return (Some(template_file), Template::Root(Default::default()));
              }
            }
          }
        }
        Template::RootFolder(template) => {
          let mut is_index = false;

          for index in &self.indexing.roots {
            if input.ends_with(index) {
              is_index = true;
            }
          }

          if !is_index {
            continue;
          }

          let path = input.to_path_buf();
          // yes this looks cursed to me too

          // using soem of my original code
          if let Some(parent) = path.parent() {
            let mut to_be_tested = PathBuf::from(parent);
            to_be_tested.set_extension("md");

            // test if there is a file with teh same name as the folder this resides in
            if fs::read_to_string(to_be_tested).is_ok() {
              if let Ok(template_file) = fs::read_to_string(template) {
                return (Some(template_file), Template::RootFolder(Default::default()));
              }
            }
          }
        }

        // fall back to this if needed
        Template::Default => {
          // check for <path>/<name>.html
          let tmp = r#"
<!DOCTYPE html>
  <html lang='en'>
  <head>
    <title>{title}</title>
  </head>
  <body>
{body}
  </body>
</html>
          "#;

          return (Some(tmp.to_string()), Template::Default);
        }
      }
    }

    (None, Template::Default)
  }

  fn template_merge(&self, item: &PartialItem, index_info: &HashMap<PathBuf, Vec<IndexInfo>>) -> String {
    if let Some(mut template_string) = item.template.clone() {
      // fill in teh details of teh body
      template_string = template_string.replace("{body}", &item.processed);

      // index stuff
      if let Template::Root(_) = item.template_type {
        for index_root in &self.indexing.roots {
          let src = item.src.to_str().unwrap_or_default();
          let root = index_root.to_str().unwrap_or_default();
          let windows = format!("{}\\", root);
          let linux = format!("{}/", root);
          if src.contains(&windows) || src.contains(&linux) {
            let index_info_tmp = index_info.get(index_root).unwrap();

            let current = if let Some(y) = &item.front_matter.slug {
              y
            } else {
              continue;
            };

            let mut index = 0;
            for item_tmp in index_info_tmp {
              if &item_tmp.number == current {
                break;
              } else {
                index += 1;
              }
            }

            let info = &index_info_tmp[index];

            // now get forward and back
            let (first, prev) = if index > 0 {
              (index_info_tmp[0].number.to_string(), index_info_tmp[index - 1].number.to_string())
            } else {
              (index_info_tmp[0].number.to_string(), index_info_tmp[0].number.to_string())
            };
            let (next, last) = if index < (index_info_tmp.len() - 1) {
              (index_info_tmp[index + 1].number.to_string(), index_info_tmp[index_info_tmp.len() - 1].number.to_string())
            } else {
              (index_info_tmp[index_info_tmp.len() - 1].number.to_string(), index_info_tmp[index_info_tmp.len() - 1].number.to_string())
            };

            template_string = template_string
              .replace("{first}", &first)
              .replace("{prev}", &prev)
              .replace("{next}", &next)
              .replace("{last}", &last)
              .replace("{title}", &info.title)
              .replace("{date}", &info.date);
          }
        }
      }

      if let Template::RootFolder(_) = item.template_type {
        // use the file name for the title
        let input_test = item.src.to_path_buf();

        if let Some(parent) = input_test.parent() {
          if let Some(parent_name) = parent.file_name() {
            if let Some(unwrapped) = parent_name.to_str() {
              template_string = template_string.replace("{folder}", unwrapped);
            }
          }
        };

        if let Some(unwrapped) = &item.front_matter.title {
          template_string = template_string.replace("{title}", unwrapped);
        }
      }

      // if its not done above then fallback ehre
      template_string = template_string.replace("{title}", &item.filename);

      template_string
    } else {
      // no template, just return teh processed right back
      item.processed.to_owned()
    }
  }

  fn get_index_info(&self, partials: &[PartialItem]) -> HashMap<PathBuf, Vec<IndexInfo>> {
    let mut result_hash: HashMap<PathBuf, Vec<IndexInfo>> = HashMap::new();

    for index_root in &self.indexing.roots {
      let mut result = vec![];

      // go to ./src/index
      // iterate through teh files
      // if a filename is a number then add it to teh array
      let mut post = PathBuf::from(&self.src);
      post.push(index_root);

      for partial in partials {
        if !partial.src.starts_with(&post) {
          continue;
        }

        let mut tmp = IndexInfo {
          number: "".to_string(),
          title: "".to_string(),
          date: "".to_string(),
          skip_index: partial.front_matter.skip_index,
        };

        if let Some(x) = &partial.front_matter.slug {
          tmp.number = x.to_owned();
        }

        if let Some(x) = &partial.front_matter.title {
          tmp.title = x.to_owned();
        }

        if let Some(x) = &partial.front_matter.date {
          tmp.date = x.to_owned();
        }

        if !tmp.title.is_empty() {
          result.push(tmp);
        }
      }

      // sort array
      result.sort_by(|a, b| b.number.cmp(&a.number));
      result.reverse();

      result_hash.insert(index_root.to_path_buf(), result);
    }

    result_hash
  }

  fn create_index_root(&self, template: &PathBuf, index_info: &[IndexInfo], index_root: &Path) -> Option<String> {
    let mut table: String = String::new();
    table.push_str("<table>\n");
    table.push_str("  <thead><tr><th> Number </th><th> Date </th><th> Title </th> </tr></thead>\n");
    table.push_str("  <tbody>\n");
    for entry in index_info.iter().rev() {
      if entry.skip_index {
        continue;
      }
      table.push_str(&format!("    <tr><td>{}</td><td>{}</td><td><a target=\"_blank\" rel=\"noopener noreferrer\" href=\"./{}\" title=\"{}\">{}</a></td></tr>\n", entry.number, entry.date, entry.number, entry.title, entry.title));
    }
    table.push_str("  </tbody>\n");
    table.push_str("</table>");

    if let Ok(template_string) = fs::read_to_string(template) {
      Some(
        template_string
          .replace("{title}", &uppercase_first_letter(index_root.to_str().unwrap_or_default()))
          .replace("{body}", &table),
      )
    } else {
      None
    }
  }
}