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 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602
use self::super::{MachineDataKind, ScriptElement, StyleElement, CenterOrder, LanguageTag, FeedType, feed_type_footer, feed_type_header}; use self::super::super::util::{concat_path, path_depth, mul_str}; use std::collections::{BTreeMap, BTreeSet}; use toml::de::from_str as from_toml_str; use self::super::super::Error; use std::io::{Write, Read}; use std::fs::{self, File}; use std::path::PathBuf; /// Generic blogue metadata. #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct BlogueDescriptor { /// The blogue's display name. pub name: String, /// The blogue's main author(s). /// /// Overriden by post metadata, if present. /// /// If not present, defaults to the current system user's name, which, if not detected, errors out. pub author: Option<String>, /// Data to put before post HTML, templated. /// /// Default: `"$ROOT/header.html"`, then `"$ROOT/header.htm"`. pub header_file: (String, PathBuf), /// Data to put after post HTML, templated. /// /// Default: `"$ROOT/footer.html"`, then `"$ROOT/footer.htm"`. pub footer_file: (String, PathBuf), /// Subfolder to move assets to, relative to the output root, if present. /// /// The value is stripped of leading slashes. All backslashes are normalised to forward ones. /// The value is ended off with a slash, if not already specified. /// /// No override is applied if not present – assets are copied alongside the posts' HTML. pub asset_dir_override: Option<String>, /// Metadata specifying how to generate the blogue index file. /// /// If not present, index not generated. pub index: Option<BlogueDescriptorIndex>, /// Where and which machine datasets to put. /// /// Each value here is a prefix appended to the output directory under which to put the machine data. /// /// Values can't be empty (to put machine data at post root use "./"). pub machine_data: BTreeMap<MachineDataKind, String>, /// Where and which feeds to put. /// /// Each value here is a file path appended to the output directory into which to put the machine data. pub feeds: BTreeMap<FeedType, String>, /// Default post language. /// /// Overriden by post metadata, if present. /// /// If not present, defaults to the current system language, which, if not detected, defaults to en-GB. pub language: Option<LanguageTag>, /// A set of style descriptors. /// /// If not present, defaults to empty. pub styles: Vec<StyleElement>, /// A set of style descriptors. /// /// If not present, defaults to empty. pub scripts: Vec<ScriptElement>, /// Additional static data to substitute in header and footer. /// /// If not present, defaults to empty. pub data: BTreeMap<String, String>, } /// Metadata pertaining specifically to generating an index file. #[derive(Debug, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct BlogueDescriptorIndex { /// Data to put start index HTML with, templated. /// /// Default: `"$ROOT/index_header.html"`, then `"$ROOT/index_header.htm"`, /// then `"$ROOT/idx_header.html"`, then `"$ROOT/idx_header.htm"`. pub header_file: (String, PathBuf), /// Data to put in index HTML for each post, templated. /// /// Default: `"$ROOT/index_center.html"`, then `"$ROOT/index_center.htm"`, /// then `"$ROOT/idx_center.html"`, then `"$ROOT/idx_center.htm"`. pub center_file: (String, PathBuf), /// Data to put to end index HTML with, templated. /// /// Default: `"$ROOT/index_footer.html"`, then `"$ROOT/index_footer.htm"`, /// then `"$ROOT/idx_footer.html"`, then `"$ROOT/idx_footer.htm"`. pub footer_file: (String, PathBuf), /// The order to put center templates in. /// /// If not present, defaults to forward. pub center_order: CenterOrder, /// A set of style descriptors. /// /// If not present, defaults to empty. pub styles: Vec<StyleElement>, /// A set of style descriptors. /// /// If not present, defaults to empty. pub scripts: Vec<ScriptElement>, /// Additional static data to substitute in header and footer. /// /// If not present, defaults to empty. pub data: BTreeMap<String, String>, } #[derive(Deserialize)] struct BlogueDescriptorSerialised { pub name: String, pub author: Option<String>, pub header: Option<String>, pub footer: Option<String>, pub asset_dir: Option<String>, pub index: Option<BlogueDescriptorIndexSerialised>, pub machine_data: Option<BTreeMap<MachineDataKind, String>>, pub feeds: Option<BTreeMap<FeedType, String>>, pub language: Option<LanguageTag>, pub styles: Option<Vec<StyleElement>>, pub scripts: Option<Vec<ScriptElement>>, pub data: Option<BTreeMap<String, String>>, } #[derive(Deserialize)] struct BlogueDescriptorIndexSerialised { pub generate: Option<bool>, pub header: Option<String>, pub center: Option<String>, pub footer: Option<String>, pub order: Option<CenterOrder>, pub styles: Option<Vec<StyleElement>>, pub scripts: Option<Vec<ScriptElement>>, pub data: Option<BTreeMap<String, String>>, } impl BlogueDescriptor { /// Read the blogue descriptor from the specified root firectory. /// /// # Examples /// /// Given the following directory layout: /// /// ```plaintext /// $ROOT /// blogue.toml /// head.html /// footer.htm /// idx_head.html /// центр.html /// index_footer.htm /// ``` /// /// Given `$ROOT/blogue.toml` containing: /// /// ```toml /// name = "Блогг" /// header = "head.html" /// language = "pl" /// asset_dir = "assets" /// /// [index] /// header = "idx_head.html" /// center = "центр.html" /// order = "backward" /// styles = ["literal:.indented { text-indent: 1em; }"] /// /// [[scripts]] /// class = "link" /// data = "/content/assets/syllable.js" /// /// [[scripts]] /// class = "file" /// data = "MathJax-config.js" /// /// [machine_data] /// JSON = "metadata/json/" /// /// [feeds] /// RSS = "feed.rss" /// ATOM = "feed.atom" /// /// [data] /// preferred_system = "capitalism" /// ``` /// /// The following holds: /// /// ``` /// # use bloguen::ops::{BlogueDescriptorIndex, BlogueDescriptor, MachineDataKind, ScriptElement, StyleElement, /// # CenterOrder, FeedType}; /// # use std::fs::{self, File}; /// # use std::env::temp_dir; /// # use std::io::Write; /// # let root = temp_dir().join("bloguen-doctest").join("ops-descriptor-read"); /// # fs::create_dir_all(&root).unwrap(); /// # File::create(root.join("blogue.toml")).unwrap().write_all("\ /// # name = \"Блогг\"\n\ /// # header = \"head.html\"\n\ /// # language = \"pl\"\n\ /// # asset_dir = \"assets\"\n\ /// # \n\ /// # [index]\n\ /// # header = \"idx_head.html\"\n\ /// # center = \"центр.html\"\n\ /// # order = \"backward\"\n\ /// # styles = [\"literal:.indented { text-indent: 1em; }\"]\n\ /// # \n\ /// # [[scripts]]\n\ /// # class = \"link\"\n\ /// # data = \"/content/assets/syllable.js\"\n\ /// # \n\ /// # [[scripts]]\n\ /// # class = \"file\"\n\ /// # data = \"MathJax-config.js\"\n\ /// # \n\ /// # [machine_data]\n\ /// # JSON = \"metadata/json/\"\n\ /// # \n\ /// # [feeds]\n\ /// # RSS = \"feed.rss\"\n\ /// # Atom = \"feed.atom\"\n\ /// # \n\ /// # [data]\n\ /// # preferred_system = \"capitalism\"\n\ /// # ".as_bytes()).unwrap(); /// # File::create(root.join("head.html")).unwrap().write_all("header".as_bytes()).unwrap(); /// # File::create(root.join("footer.htm")).unwrap().write_all("footer".as_bytes()).unwrap(); /// # File::create(root.join("idx_head.html")).unwrap().write_all("index header".as_bytes()).unwrap(); /// # File::create(root.join("центр.html")).unwrap().write_all("index центр".as_bytes()).unwrap(); /// # File::create(root.join("index_footer.htm")).unwrap().write_all("index footer".as_bytes()).unwrap(); /// # /* /// let root: PathBuf = /* obtained elsewhere */; /// # */ /// let read_tokens = BlogueDescriptor::read(&("$ROOT/".to_string(), root.clone())).unwrap(); /// assert_eq!( /// read_tokens, /// BlogueDescriptor { /// name: "Блогг".to_string(), /// author: None, /// header_file: ("$ROOT/head.html".to_string(), root.join("head.html")), /// footer_file: ("$ROOT/footer.htm".to_string(), root.join("footer.htm")), /// asset_dir_override: Some("assets/".to_string()), /// machine_data: vec![(MachineDataKind::Json, "metadata/json/".to_string())].into_iter().collect(), /// feeds: vec![(FeedType::Rss, "feed.rss".to_string()), /// (FeedType::Atom, "feed.atom".to_string())].into_iter().collect(), /// language: Some("pl".parse().unwrap()), /// styles: vec![], /// scripts: vec![ScriptElement::from_link("/content/assets/syllable.js"), /// ScriptElement::from_path("MathJax-config.js")], /// index: Some(BlogueDescriptorIndex { /// header_file: ("$ROOT/idx_head.html".to_string(), root.join("idx_head.html")), /// center_file: ("$ROOT/центр.html".to_string(), root.join("центр.html")), /// footer_file: ("$ROOT/index_footer.htm".to_string(), root.join("index_footer.htm")), /// center_order: CenterOrder::Backward, /// styles: vec![StyleElement::from_literal(".indented { text-indent: 1em; }")], /// scripts: vec![], /// data: vec![].into_iter().collect(), /// }), /// data: vec![("preferred_system".to_string(), /// "capitalism".to_string())].into_iter().collect(), /// }); /// ``` pub fn read(root: &(String, PathBuf)) -> Result<BlogueDescriptor, Error> { let mut buf = String::new(); File::open(root.1.join("blogue.toml")).map_err(|_| { Error::FileNotFound { who: "blogue descriptor", path: format!("{}blogue.toml", root.0).into(), } })? .read_to_string(&mut buf) .map_err(|_| { Error::Io { desc: "blogue descriptor".into(), op: "read", more: "not UTF-8".into(), } })?; let serialised: BlogueDescriptorSerialised = from_toml_str(&buf).map_err(move |err| { Error::FileParsingFailed { desc: "blogue descriptor".into(), errors: err.to_string().into(), } })?; let asset_dir_override = serialised.asset_dir.map(|mut ad| { if let Some(i) = ad.find(|c| !['/', '\\'].contains(&c)) { ad.replace_range(..i, ""); } let mut last_slash = 0; while let Some(backslash) = ad[last_slash..].find('\\') { ad.replace_range(last_slash + backslash..last_slash + backslash + 1, "/"); last_slash += backslash + 1; } if !ad.ends_with('/') { ad.push('/'); } ad }); let machine_data = serialised.machine_data.unwrap_or_default(); for (ref k, ref v) in &machine_data { if v.find(|c| !['/', '\\'].contains(&c)).is_none() { return Err(Error::Parse { tp: "path chunk", wher: "blogue descriptor".into(), more: format!("{} subdir selector empty", k).into(), }); } } let feeds = serialised.feeds.unwrap_or_default(); for (ref k, ref v) in &feeds { let more = if v.is_empty() { Some(format!("{} filename empty", k)) } else if v.ends_with(|c| ['/', '\\'].contains(&c)) { Some(format!("{} filename {:?} ends with path separator", k, v)) } else { None }; if let Some(more) = more { return Err(Error::Parse { tp: "path chunk", wher: "blogue descriptor".into(), more: more.into(), }); } } { let mut feeds_fnames = BTreeSet::new(); for v in feeds.values() { if !feeds_fnames.insert(v) { return Err(Error::Parse { tp: "path chunk", wher: "blogue descriptor".into(), more: format!("feed filename {:?} duplicate", v).into(), }); } } } Ok(BlogueDescriptor { name: serialised.name, author: serialised.author, header_file: additional_file(serialised.header, root, "header", "post header")?, footer_file: additional_file(serialised.footer, root, "footer", "post footer")?, asset_dir_override: asset_dir_override, index: match serialised.index { Some(mut si) => { match si.generate { None | Some(true) => { Some(BlogueDescriptorIndex { header_file: additional_file(si.header.clone(), root, "index_header", "index header") .or_else(|_| additional_file(si.header.take(), root, "idx_header", "index header"))?, center_file: additional_file(si.center.clone(), root, "index_center", "index center") .or_else(|_| additional_file(si.center.take(), root, "idx_center", "index center"))?, footer_file: additional_file(si.footer.clone(), root, "index_footer", "index footer") .or_else(|_| additional_file(si.footer.take(), root, "idx_footer", "index footer"))?, center_order: si.order.unwrap_or_default(), styles: si.styles.unwrap_or_default(), scripts: si.scripts.unwrap_or_default(), data: si.data.unwrap_or_default(), }) } Some(false) => None, } } None => None, }, machine_data: machine_data, feeds: feeds, language: serialised.language, styles: serialised.styles.unwrap_or_default(), scripts: serialised.scripts.unwrap_or_default(), data: serialised.data.unwrap_or_default(), }) } /// Create a feed output file of the specified type into the specified subpath in the specified output directory. /// /// # Examples /// /// ``` /// # use bloguen::ops::{BlogueDescriptor, FeedType}; /// # use std::fs::{self, File}; /// # use std::env::temp_dir; /// # use std::io::Write; /// # let root = temp_dir().join("bloguen-doctest").join("ops-descriptor-create_feed_output"); /// # fs::create_dir_all(&root).unwrap(); /// # File::create(root.join("blogue.toml")).unwrap().write_all("name = \"Блогг\"\n".as_bytes()).unwrap(); /// # File::create(root.join("header.html")).unwrap(); /// # File::create(root.join("footer.html")).unwrap(); /// # let descriptor = BlogueDescriptor::read(&("$ROOT/".to_string(), root.clone())).unwrap(); /// # /* /// let root: PathBuf = /* obtained elsewhere */; /// let descriptor: BlogueDescriptor = /* irrelevant */; /// # */ /// descriptor.create_feed_output(&("$ROOT/".to_string(), root.clone()), "feeds/rss.xml", /// &FeedType::Rss).unwrap(); /// /// assert!(root.join("feeds").join("rss.xml").is_file()); /// ``` pub fn create_feed_output(&self, into: &(String, PathBuf), fname: &str, tp: &FeedType) -> Result<File, Error> { let feed_path = concat_path(&into.1, fname); if let Some(feed_parent) = feed_path.parent() { fs::create_dir_all(feed_parent).map_err(|e| { Error::Io { desc: format!("{} parent directory", fname).into(), op: "create", more: e.to_string().into(), } })?; } File::create(feed_path).map_err(|e| { Error::Io { desc: format!("{} feed", tp).into(), op: "create", more: e.to_string().into(), } }) } /// Generate header for the specified type of feed for this descriptor. /// /// # Examples /// /// Given `$ROOT/blogue.toml` containing: /// /// ```plaintext /// name = "Блогг" /// index = {} /// ``` /// /// The following holds: /// /// ``` /// # use bloguen::ops::{BlogueDescriptor, FeedType}; /// # use bloguen::util::LANGUAGE_EN_GB; /// # use std::fs::{self, File}; /// # use std::env::temp_dir; /// # use std::io::Write; /// # let root = temp_dir().join("bloguen-doctest").join("ops-descriptor-generate_feed_head"); /// # fs::create_dir_all(&root).unwrap(); /// # File::create(root.join("blogue.toml")).unwrap().write_all("name = \"Блогг\"\nindex = {}\n".as_bytes()).unwrap(); /// # File::create(root.join("header.html")).unwrap(); /// # File::create(root.join("footer.html")).unwrap(); /// # File::create(root.join("idx_header.html")).unwrap(); /// # File::create(root.join("idx_center.html")).unwrap(); /// # File::create(root.join("idx_footer.html")).unwrap(); /// # /* /// let root: PathBuf = /* obtained elsewhere */; /// # */ /// let mut descriptor = BlogueDescriptor::read(&("$ROOT/".to_string(), root.clone())).unwrap(); /// /// let mut out = vec![]; /// descriptor.generate_feed_head(&mut out, &FeedType::Rss, "feeds/rss.xml", /// &LANGUAGE_EN_GB, "nabijaczleweli").unwrap(); /// /// let out = String::from_utf8(out).unwrap(); /// # let mut gendate_local_rfc2822 = out.lines().find(|l| l.contains("lastBuildDate")).unwrap(); /// # gendate_local_rfc2822 = &gendate_local_rfc2822[4 + 1 + 13 + 1..gendate_local_rfc2822.len() - (1 + 13 + 1 + 1)]; /// # /* /// let gendate_local_rfc2822 = /* extracted from output's lastBuildDate tag */; /// # */ /// assert_eq!(out, format!(r###"<?xml version="1.0" encoding="UTF-8"?> /// <rss version="2.0"> /// <channel> /// <docs>https://validator.w3.org/feed/docs/rss2.html</docs> /// <title>Блогг</title> /// <author>nabijaczleweli</author> /// <link>../index.html</link> /// <description>Блогг</description> /// <language>en-GB</language> /// <generator>bloguen 0.1.1</generator> /// <pubDate>{0}</pubDate> /// <lastBuildDate>{0}</lastBuildDate> /// "###, gendate_local_rfc2822)); /// /// // And /// /// let mut out = vec![]; /// descriptor.index = None; /// descriptor.generate_feed_head(&mut out, &FeedType::Rss, "feeds/rss.xml", /// &LANGUAGE_EN_GB, "nabijaczleweli").unwrap(); /// /// let out = String::from_utf8(out).unwrap(); /// # let mut gendate_local_rfc2822 = out.lines().find(|l| l.contains("lastBuildDate")).unwrap(); /// # gendate_local_rfc2822 = &gendate_local_rfc2822[4 + 1 + 13 + 1..gendate_local_rfc2822.len() - (1 + 13 + 1 + 1)]; /// # /* /// let gendate_local_rfc2822 = /* extracted from output's lastBuildDate tag */; /// # */ /// assert_eq!(out, format!(r###"<?xml version="1.0" encoding="UTF-8"?> /// <rss version="2.0"> /// <channel> /// <docs>https://validator.w3.org/feed/docs/rss2.html</docs> /// <title>Блогг</title> /// <author>nabijaczleweli</author> /// <description>Блогг</description> /// <language>en-GB</language> /// <generator>bloguen 0.1.1</generator> /// <pubDate>{0}</pubDate> /// <lastBuildDate>{0}</lastBuildDate> /// "###, gendate_local_rfc2822)); /// ``` pub fn generate_feed_head<T: Write>(&self, into: &mut T, tp: &FeedType, fname: &str, language: &LanguageTag, author: &str) -> Result<(), Error> { feed_type_header(tp)(&self.name, language, author, self.index.as_ref().map(|_| { let depth = path_depth(fname); if depth - 1 > 0 { (mul_str("../", depth as usize - 1) + "index.html").into() } else { "index.html".into() } }), into, format!("{} feed output", tp.name()))?; Ok(()) } /// Generate footer for the specified type of feed for this descriptor. /// /// # Examples /// /// ``` /// # use bloguen::ops::{BlogueDescriptor, FeedType}; /// # use std::fs::{self, File}; /// # use std::env::temp_dir; /// # use std::io::Write; /// # let root = temp_dir().join("bloguen-doctest").join("ops-descriptor-generate_feed_foot"); /// # fs::create_dir_all(&root).unwrap(); /// # File::create(root.join("blogue.toml")).unwrap().write_all("name = \"Блогг\"\n".as_bytes()).unwrap(); /// # File::create(root.join("header.html")).unwrap(); /// # File::create(root.join("footer.html")).unwrap(); /// # let descriptor = BlogueDescriptor::read(&("$ROOT/".to_string(), root.clone())).unwrap(); /// # /* /// let root: PathBuf = /* obtained elsewhere */; /// let descriptor: BlogueDescriptor = /* irrelevant */; /// # */ /// /// let mut out = vec![]; /// descriptor.generate_feed_foot(&mut out, &FeedType::Rss).unwrap(); /// /// assert_eq!(String::from_utf8(out).unwrap(), r###" </channel> /// </rss> /// "###); /// ``` pub fn generate_feed_foot<T: Write>(&self, into: &mut T, tp: &FeedType) -> Result<(), Error> { feed_type_footer(tp)(into, format!("{} feed output", tp.name()))?; Ok(()) } } fn additional_file(file_opt: Option<String>, root: &(String, PathBuf), tp: &str, error_n: &'static str) -> Result<(String, PathBuf), Error> { file_opt.map_or_else(|| { check_additional_file(root, &format!("{}.html", tp)).or_else(|| check_additional_file(root, &format!("{}.htm", tp))).ok_or_else(|| { Error::FileNotFound { who: error_n, path: format!("{}{{{1}.html/{1}.htm}}", root.0, tp).into(), } }) }, |af| { let file = concat_path(root.1.clone(), &af); let file_s = format!("{}{}", root.0, af); if file.exists() { if file.is_file() { Ok((file_s, file)) } else { Err(Error::WrongFileState { what: "a file", path: file_s.into(), }) } } else { Err(Error::FileNotFound { who: error_n, path: file_s.into(), }) } }) } fn check_additional_file(root: &(String, PathBuf), fname: &str) -> Option<(String, PathBuf)> { let file = root.1.join(fname); if file.is_file() { Some((format!("{}{}", root.0, fname), file)) } else { None } }