Repository: pnkfelix/tango Branch: master Commit: b0e7716889ba Files: 14 Total size: 95.4 KB Directory structure: gitextract_2ek6czfx/ ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── build.rs ├── src/ │ ├── lib.rs │ ├── main.rs │ ├── md2rs.rs │ ├── rs2md.rs │ ├── testing/ │ │ ├── mod.rs │ │ └── test_snippets.rs │ └── timestamp.rs └── tests/ └── runner.rs ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ target *~ ================================================ FILE: Cargo.toml ================================================ [package] name = "tango" version = "0.8.3" authors = ["Felix S. Klock II "] description = "Markdown-based Literate programming in Rust, integrated with Cargo." license = "MIT/Apache-2.0" repository = "https://github.com/pnkfelix/tango" documentation = "https://github.com/pnkfelix/tango-demo/blob/master/README.md" [dependencies] ## Every time I tried to get `debug!` working with `cargo test` I am ## flummoxed. Not sure what my problem is, but for now these are not ## enough on their own, so I am leaving them out of the checked-in ## version. ## # log = "*" # env_logger = "*" filetime = "0.1" walkdir = "1.0" url = "1.4" ## dev-dependencies are only pulled in for tests/benchmarks [dev-dependencies] tempdir = "0.3" [[test]] name = "runner" ## ## Can set below to stop passing `--test` when compiling runner.rs ## (and thus use a `fn main` within it as its associated test driver). ## But for now I am trying to work within the integrated testing framework, ## which means in part avoiding global state like `env::set_current_dir` ## # harness = false ================================================ FILE: LICENSE-APACHE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: LICENSE-MIT ================================================ Copyright (c) 2015 Felix Stanley Klock II Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Status API Training Shop Blog About Help ================================================ FILE: README.md ================================================ # tango Markdown-based Literate programming in Rust, integrated with Cargo. See https://github.com/pnkfelix/tango-demo/ for a demonstration of how to use it. (At some point I hope to document the source code here, but I suspect that I will wait until after I do a rewrite so that the source code actually has some sort of sane basis with a parser or at least proper regexps.) ================================================ FILE: build.rs ================================================ fn main() { // a no-op `build.rs` to trick `cargo` into setting `OUT_DIR` env var. } ================================================ FILE: src/lib.rs ================================================ // #[macro_use] // extern crate log; // extern crate env_logger; extern crate filetime; extern crate url; extern crate walkdir; use filetime::set_file_times; use walkdir::{WalkDir}; use std::convert; use std::error::Error as ErrorTrait; use std::ffi::OsStr; use std::fmt; use std::fs::{self, File}; use std::io::{self, Read, Write}; use std::ops; use std::path::{Path, PathBuf}; use std::cell::RefCell; use self::timestamp::{Timestamp, Timestamped}; pub mod timestamp; pub const STAMP: &'static str = "tango.stamp"; //pub const SRC_DIR: &'static str = "src"; // pnkfelix wanted the `LIT_DIR` to be `lit/`, but `cargo build` // currently assumes that *all* build sources live in `src/`. So it // is easier for now to just have the two directories be the same. //pub const LIT_DIR: &'static str = "src/lit"; thread_local! { pub static SRC_DIR: RefCell = RefCell::new("src".to_string()); pub static LIT_DIR: RefCell = RefCell::new("src".to_string()); } fn set_lit_dir(directory: String) { LIT_DIR.with(|lit_dir| { *lit_dir.borrow_mut() = directory }); } fn set_src_dir(directory: String) { SRC_DIR.with(|src_dir| { *src_dir.borrow_mut() = directory }); } /// Returns the current directory for storing the literate .md files pub fn get_lit_dir() -> String { LIT_DIR.with(|lit_dir| lit_dir.borrow().clone()) } /// Returns the current directory for storing the "source" .rs files pub fn get_src_dir() -> String { SRC_DIR.with(|src_dir| src_dir.borrow().clone()) } pub struct Config { src_dir: String, lit_dir: String, rerun_if: bool, } impl Config { pub fn new() -> Config { Config { src_dir: String::from("src"), lit_dir: String::from("src"), rerun_if: false, } } pub fn set_src_dir(&mut self, new_src_dir: String) -> &mut Config { self.src_dir = new_src_dir; self } pub fn set_lit_dir(&mut self, new_lit_dir: String) -> &mut Config { self.lit_dir = new_lit_dir; self } pub fn emit_rerun_if(&mut self) -> &mut Config { self.rerun_if = true; self } } #[derive(Debug)] pub enum Error { IoError(io::Error), CheckInputError { error: check::Error }, MtimeError(PathBuf), ConcurrentUpdate { path_buf: PathBuf, old_time: mtime, new_time: mtime }, Warnings(Vec), } #[derive(Debug)] pub enum Warning { EncodedUrlMismatch { actual: String, expect: String } } impl fmt::Display for Warning { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { match *self { Warning::EncodedUrlMismatch { ref actual, ref expect } => { write!(w, "mismatch between encoded url, expect: {} actual: {}", expect, actual) } } } } impl From for Error { fn from(e: md2rs::Exception) -> Self { match e { md2rs::Exception::IoError(e) => Error::IoError(e), md2rs::Exception::Warnings(w) => Error::Warnings(w), } } } impl fmt::Display for Error { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { match *self { Error::IoError(_) => write!(w, "IO error running `tango`"), Error::CheckInputError { .. } => write!(w, "input check errors running `tango`"), Error::MtimeError(ref p) => write!(w, "modification time error from `tango` checking {}", p.to_string_lossy()), Error::ConcurrentUpdate { ref path_buf, .. } => write!(w, "concurrent update during `tango` to source file {}", path_buf.to_string_lossy()), Error::Warnings(ref warnings) => { for warn in warnings { (write!(w, "WARNING: {}", warn))?; } Ok(()) } } } } impl ErrorTrait for Error { fn source(&self) -> Option<&(dyn ErrorTrait + 'static)> { match *self { Error::IoError(ref e) => Some(e), Error::CheckInputError { ref error, .. } => { Some(error) } Error::Warnings(_) | Error::MtimeError(_) | Error::ConcurrentUpdate { .. } => None, } } } impl convert::From for Error { fn from(e: io::Error) -> Self { Error::IoError(e) } } impl convert::From for Error { fn from(e: walkdir::Error) -> Self { Error::IoError(From::from(e)) } } pub type Result = std::result::Result; #[allow(non_camel_case_types)] pub type mtime = Timestamp; #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum MtimeResult { NonExistant, Modified(mtime), } trait Mtime { fn modified(&self) -> Result; } impl Mtime for File { fn modified(&self) -> Result { // #![allow(deprecated)] // if let Some(p) = self.path() { // if !p.exists() { // return Err(Error::MtimeError(p.to_path_buf())); // } // } let m = (self.metadata())?; Ok(MtimeResult::Modified(m.timestamp())) } } impl Mtime for fs::DirEntry { fn modified(&self) -> Result { let m = (self.metadata())?; Ok(MtimeResult::Modified(m.timestamp())) } } impl Mtime for RsPath { fn modified(&self) -> Result { if self.0.exists() { let f = (File::open(&self.0))?; f.modified() } else { Ok(MtimeResult::NonExistant) } } } impl Mtime for MdPath { fn modified(&self) -> Result { if self.0.exists() { let f = (File::open(&self.0))?; f.modified() } else { Ok(MtimeResult::NonExistant) } } } pub fn process_root_with_config(config: Config) -> Result<()> { //let _root = (std::env::current_dir())?; //println!("Tango is running from: {:?}", root); //std::env::set_current_dir(_root).unwrap(); set_lit_dir(config.lit_dir); set_src_dir(config.src_dir); let emit_rerun_if = config.rerun_if; let stamp_path = Path::new(STAMP); if stamp_path.exists() { process_with_stamp((File::open(stamp_path))?, emit_rerun_if) } else { process_without_stamp(emit_rerun_if) } } pub fn process_root() -> Result<()> { //let _root = (std::env::current_dir())?; // println!("Tango is running from: {:?}", _root); let emit_rerun_if = false; let stamp_path = Path::new(STAMP); if stamp_path.exists() { process_with_stamp((File::open(stamp_path))?, emit_rerun_if) } else { process_without_stamp(emit_rerun_if) } } // Both of the functions below have the same basic outline: // // 1. gather_inputs(): Build up a list of potential transforms based // on existing files. // // 2. generate_content(): Apply each transform in turn, *iff* the // source is newer than target. // // 3. check_input_timestamps(): Ensure no input was concurrently // modified while tango ran. // // 4. adjust_stamp_timestamp(): Update the `tango.stamp` file to the // youngest timestamp we saw, creating the file if necessary. // // The reason there are two functions is that in one case we have a // pre-existing `tango.stamp` that we want to compare against during // `generate_content()` (to guard against diverging {source, target} // paths; *at most* one of {source, target} is meant to be updated in // between tango runs. // // (It probably wouldn't be hard to unify the two functions into a // single method on the `Context`, though.) fn process_with_stamp(stamp: File, emit_rerun_if: bool) -> Result<()> { println!("\n\nemit rerun if: {:?}\n\n", emit_rerun_if); if let Ok(MtimeResult::Modified(ts)) = stamp.modified() { println!("Rerunning tango; last recorded run was stamped: {}", ts.date_fulltime_badly()); } else { panic!("why are we trying to process_with_stamp when given: {:?}", stamp); } let mut c = (Context::new(Some(stamp)))?; c.emit_rerun_if = emit_rerun_if; (c.gather_inputs())?; (c.generate_content())?; (c.check_input_timestamps())?; (c.adjust_stamp_timestamp())?; // (c.report_dir(Path::new(".")))?; Ok(()) } fn process_without_stamp(emit_rerun_if: bool) -> Result<()> { println!("Running tango; no previously recorded run"); println!("\n\nemit rerun if: {:?}\n\n", emit_rerun_if); let mut c = (Context::new(None))?; c.emit_rerun_if = emit_rerun_if; (c.gather_inputs())?; (c.generate_content())?; (c.check_input_timestamps())?; (c.create_stamp())?; (c.adjust_stamp_timestamp())?; // (c.report_dir(Path::new(".")))?; Ok(()) } #[derive(Debug)] struct RsPath(PathBuf); #[derive(Debug)] struct MdPath(PathBuf); struct Context { orig_stamp: Option<(File, mtime)>, src_inputs: Vec>, lit_inputs: Vec>, newest_stamp: Option, emit_rerun_if: bool, } trait Extensions { fn extension(&self) -> Option<&str>; fn rs_extension(&self) -> bool { self.extension() == Some("rs") } fn md_extension(&self) -> bool { self.extension() == Some("md") } } impl Extensions for Path { fn extension(&self) -> Option<&str> { Path::extension(self).and_then(|s|s.to_str()) } } impl ops::Deref for RsPath { type Target = Path; fn deref(&self) -> &Path { &self.0 } } impl ops::Deref for MdPath { type Target = Path; fn deref(&self) -> &Path { &self.0 } } fn check_path(typename: &str, p: &Path, ext: &str, root: &str) { println!("\n in check_path, the root is: {r:?} , path is: {p:?}, ext is {e:?}", r=root, p=p, e=ext); if Extensions::extension(p) != Some(ext) { panic!("{t} requires `.{ext}` extension; path: {p:?}", t=typename, ext=ext, p=p); } if !p.starts_with(root) { panic!("{t} must be rooted at `{root}/`; path: {p:?}", t=typename, root=root, p=p); } } impl RsPath { fn new(p: PathBuf) -> RsPath { check_path("RsPath", &p, "rs", &get_src_dir()); RsPath(p) } fn to_md(&self) -> MdPath { let mut p = PathBuf::new(); p.push(get_lit_dir()); for c in self.0.components().skip(1) { let c: &OsStr = c.as_ref(); p.push(c.to_str().expect("how else can I replace root?")); } p.set_extension("md"); MdPath::new(p) } } impl MdPath { fn new(p: PathBuf) -> MdPath { check_path("MdPath", &p, "md", &get_lit_dir()); MdPath(p) } fn to_rs(&self) -> RsPath { let mut p = PathBuf::new(); p.push(get_src_dir()); for c in self.0.components().skip(1) { let c: &OsStr = c.as_ref(); p.push(c.to_str().expect("how else can I replace root?")); } p.set_extension("rs"); RsPath::new(p) } } trait Transforms: Sized + Mtime + fmt::Debug { type Target: Mtime + fmt::Debug; // Computes path to desired target based on self's (source) path. fn target(&self) -> Self::Target; // Constructs a transform for generating the target from self // (which is a path to the source), gathering the current // timestamps on both the source and the target. fn transform(self) -> Result> { let source_time = match self.modified() { Ok(MtimeResult::Modified(t)) => t, Ok(MtimeResult::NonExistant) => panic!("impossible for {:?} to be NonExistant", self), Err(e) => { println!("failure to extract mtime on source {:?}", self); return Err(e); } }; let target = self.target(); let target_time = match target.modified() { Ok(t) => t, Err(e) => { println!("failure to extract mtime on target {:?}", target); return Err(e); } }; Ok(Transform { source_time: source_time, target_time: target_time, original: self, generate: target, }) } } impl Transforms for RsPath { type Target = MdPath; fn target(&self) -> MdPath { self.to_md() } } impl Transforms for MdPath { type Target = RsPath; fn target(&self) -> RsPath { self.to_rs() } } #[derive(Debug)] pub struct Transform { source_time: mtime, target_time: MtimeResult, original: X, generate: Y, } pub mod check { use std::error::Error as ErrorTrait; use std::fmt; use std::ops; use std::path::{Path, PathBuf}; use std::result; use super::Transform; pub type PathTransform = Transform; #[derive(Debug)] pub enum ErrorKind { TargetYoungerThanOriginal { tgt: String, src: String }, NoTangoStampExists { tgt: String, src: String }, TangoStampOlderThanTarget { tgt: String }, } #[derive(Debug)] pub struct Error(ErrorKind, PathTransform); impl fmt::Display for Error { fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result { match self.0 { ErrorKind::TargetYoungerThanOriginal { ref tgt, ref src } => { write!(w, "target `{}` is younger than source `{}`; \ therefore we assume target has modifications that need to be preserved.", tgt, src) } ErrorKind::NoTangoStampExists { ref src, ref tgt } => { write!(w, "both source `{}` and target `{}` exist but no `tango.stamp` is present", src, tgt) } ErrorKind::TangoStampOlderThanTarget { ref tgt } => { write!(w, "`tango.stamp` is older than target `{}`; \ therefore we assume source and target have diverged since last tango run.", tgt) } } } } impl ErrorTrait for Error { fn description(&self) -> &str { match self.0 { ErrorKind::TargetYoungerThanOriginal { .. }=> { "target is younger than source; \ therefore we assume target has modifications that need to be preserved." } ErrorKind::NoTangoStampExists { .. } => { "both source and target exist but no `tango.stamp` is present" } ErrorKind::TangoStampOlderThanTarget { .. } => { "`tango.stamp` is older than target; \ therefore we assume source and target have diverged since last tango run." } } } } pub type Result = result::Result; impl Transform where X: ops::Deref, Y: ops::Deref { pub fn error(&self, kind: ErrorKind) -> Error { let t = Transform { original: self.original.to_path_buf(), generate: self.generate.to_path_buf(), source_time: self.source_time, target_time: self.target_time, }; Error(kind, t) } } } enum TransformNeed { Needed, Unneeded, } impl Context { fn new(opt_stamp: Option) -> Result { let stamp_modified = match opt_stamp { None => None, Some(stamp) => { let mtime = (stamp.modified())?; let mtime = match mtime { MtimeResult::NonExistant => panic!("impossible"), MtimeResult::Modified(t) => t, }; Some((stamp, mtime)) } }; let c = Context { orig_stamp: stamp_modified, src_inputs: Vec::new(), lit_inputs: Vec::new(), newest_stamp: None, emit_rerun_if: true, }; Ok(c) } fn check_transform(&self, t: &Transform) -> check::Result where X: ops::Deref + Mtime, Y: ops::Deref + Mtime, { use self::check::ErrorKind::*; let t_mod = match t.target_time { MtimeResult::Modified(t) => t, MtimeResult::NonExistant => { assert!(!t.generate.exists()); return Ok(TransformNeed::Needed); } }; // let src = t.original.display().to_string(); // let tgt = t.generate.display().to_string(); let s_mod = t.source_time; let same_age_at_low_precision = s_mod.to_ms() == t_mod.to_ms(); if t_mod > s_mod { // Target is newer than source: therefore we do not want to // overwrite the target via this transform. return Ok(TransformNeed::Unneeded); } // Now know: t_mod <= s_mod if same_age_at_low_precision { // 00000000011111111112222222222333333333344444444445555555555666666666677777777778 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 println!("Warning: source and target have timestamps that differ only at nanosecond level\n \ precision. Tango currently treats such timestamps as matching, and therefore\n \ will not rebuild the target file.\n\ \n \ source: {SRC:?} timestamp: {SRC_TS} \n \ target: {TGT:?} timestamp: {TGT_TS}\n", SRC=t.original.display(), SRC_TS=s_mod.date_fulltime_badly(), TGT=t.generate.display(), TGT_TS=t_mod.date_fulltime_badly()); return Ok(TransformNeed::Unneeded); } // Now know: t_mod is older than source even after truncating // to millisecond precision. match self.orig_stamp { None => return Err(t.error(NoTangoStampExists { src: t.original.display().to_string(), tgt: t.generate.display().to_string(), })), Some((_, stamp_time)) => { let older_at_high_precision = stamp_time < t_mod; let older_at_low_precision = stamp_time.to_ms() < t_mod.to_ms(); if older_at_low_precision { // The target file was updated more recently than // the tango.stamp file, even after truncation to // millisecond precision. // // Therefore, we assume that user has updated both // the source and the target independently since // the last tango run. This is a scenario that // tango cannot currently recover from, so we // issue an error and tell the user to fix the // problem. return Err(t.error(TangoStampOlderThanTarget { tgt: t.generate.display().to_string(), })); } if older_at_high_precision && !older_at_low_precision { // 00000000011111111112222222222333333333344444444445555555555666666666677777777778 // 12345678901234567890123456789012345678901234567890123456789012345678901234567890 println!("Warning: `tango.stamp` and target `{}` have timestamps that differ only at \n\ nanosecond level precision. Tango currently treats such timestamps as,\n\ matching and will rebuild the target file rather than error", t.generate.display()); } // got here: tango.stamp is not older than the target // file. So we fall through to the base case. } } // Invariant: // Target `t` exists, but, // s_mod >= t_mod (and t_mod <= stamp_time if stamp exists). // // Thus it is safe to overwrite `t` based on source content. Ok(TransformNeed::Needed) } #[cfg(not_now)] fn report_dir(&self, p: &Path) -> Result<()> { let src_dir = get_src_dir(); let lit_dir = get_lit_dir(); let src_path = Path::new(&src_dir); let lit_path = Path::new(&lit_dir); for (i, ent) in (WalkDir::new(p))?.enumerate() { let ent = (ent)?; let modified = (ent.modified())?; println!("entry[{}]: {:?} {:?}", i, ent.path(), modified); } Ok(()) } fn update_newest_time(&mut self, new_time: mtime) { if let Some(ref mut stamp) = self.newest_stamp { if new_time > *stamp { *stamp = new_time; } } else { self.newest_stamp = Some(new_time); } } fn push_src(&mut self, t: Transform) { self.update_newest_time(t.source_time); self.src_inputs.push(t); } fn push_lit(&mut self, t: Transform) { self.update_newest_time(t.source_time); self.lit_inputs.push(t); } fn gather_inputs(&mut self) -> Result<()> { // println!("gather_inputs"); let src_dir = get_src_dir(); let lit_dir = get_lit_dir(); let src_path = Path::new(&src_dir); let lit_path = Path::new(&lit_dir); fn keep_file_name(p: &Path) -> std::result::Result<(), &'static str> { match p.file_name().and_then(|x|x.to_str()) { None => Err("file name is not valid unicode"), Some(s) if s.starts_with('.') => Err("file name has leading period"), Some(..) => Ok(()), } } fn warn_if_nonexistant(m: &M) -> Result<()> { match m.modified() { Err(e) => Err(e), Ok(MtimeResult::Modified(..)) => Ok(()), Ok(MtimeResult::NonExistant) => { // This can arise; namely some tools are // generating symlinks in `src` of the form // // `src/.#lib.md -> fklock@fklock-Oenone.local.96195` // // where the target is non-existant (presumably as // a way to locally mark a file as being open by // the tool?), and then this script interprets it // as being open. println!("warning: non-existant source: {:?}", m); Ok(()) } } } // This loop gathers all of the .rs files that currently // exist, and schedules transforms that would turn them into // corresponding target .md files. // println!("gather-rs"); for ent in WalkDir::new(src_path).into_iter() { let ent = (ent)?; let p = ent.path(); if let Err(why) = keep_file_name(p) { println!("skipping {}; {}", p.display(), why); continue; } if !p.rs_extension() { // println!("gather-rs skip {} due to non .rs", p.display()); continue; } let rs = RsPath::new(p.to_path_buf()); (warn_if_nonexistant(&rs))?; if self.emit_rerun_if { println!("cargo:rerun-if-changed={}", &rs.display()); } let t = (rs.transform())?; match self.check_transform(&t) { Ok(TransformNeed::Needed) => self.push_src(t), Ok(TransformNeed::Unneeded) => {} Err(e) => { println!("gather_inputs err: {}", e); return Err(Error::CheckInputError { error: e, }) } } } // This loop gathers all of the .md files that currently // exist, and schedules transforms that would turn them into // corresponding target .rs files. //println!("gather-md, lit_path is: {:?}", lit_path); for ent in WalkDir::new(lit_path).into_iter() { //println!("ent is {:?}", ent); let ent = (ent)?; let p = ent.path(); if let Err(why) = keep_file_name(p) { println!("skipping {}; {}", p.display(), why); continue; } if !p.md_extension() { // println!("gather-md skip {} due to non .md", p.display()); continue; } let md = MdPath::new(p.to_path_buf()); (warn_if_nonexistant(&md))?; if self.emit_rerun_if { println!("cargo:rerun-if-changed={}", &md.display()); } let t = (md.transform())?; match self.check_transform(&t) { Ok(TransformNeed::Needed) => { // println!("gather-md add {:?}", t);; self.push_lit(t) } Ok(TransformNeed::Unneeded) => { // println!("gather-md discard unneeded {:?}", t);; } Err(e) => { println!("gather_inputs err: {}", e); return Err(Error::CheckInputError { error: e, }) } } } // At this point we've scheduled all the transforms we want to // run; they will be applied unconditionally, even if both // source and target exist. (The intent is that a target // younger than source would have been filtered during the // .check_transform calls above.) Ok(()) } fn generate_content(&mut self) -> Result<()> { for &Transform { ref original, ref generate, source_time, .. } in &self.src_inputs { let source = (File::open(&original.0))?; let target = (File::create(&generate.0))?; assert!(source_time > 0); println!("generating lit {:?}", &generate.0); (rs2md(source, target))?; let timestamp = source_time.to_filetime(); println!("backdating lit {:?} to {}", &generate.0, source_time.date_fulltime_badly()); (set_file_times(&generate.0, timestamp, timestamp))?; } for &mut Transform { ref original, ref generate, ref mut source_time, .. } in &mut self.lit_inputs { let source = (File::open(&original.0))?; let target = (File::create(&generate.0))?; assert!(*source_time > 0); println!("generating src {:?}", &generate.0); (md2rs(source, target))?; println!("backdating src {:?} to {}", &generate.0, source_time.date_fulltime_badly()); (set_file_times(&generate.0, source_time.to_filetime(), source_time.to_filetime()))?; let source = (File::open(&original.0))?; let target = (File::open(&generate.0))?; match (source.modified(), target.modified()) { (Ok(MtimeResult::Modified(src_time)), Ok(MtimeResult::Modified(tgt_time))) => { // At this point, we would *like* to assert this: #[cfg(not_possible_right_now)] assert_eq!(src_time, tgt_time); // but it does not work, due to this bug: // https://github.com/alexcrichton/filetime/issues/9 assert_eq!(src_time.to_ms(), tgt_time.to_ms()); } (Ok(MtimeResult::NonExistant), _) => panic!("how could source not exist"), (_, Ok(MtimeResult::NonExistant)) => panic!("how could target not exist"), (Err(_), Err(_)) => panic!("errored looking up both source and target times"), (Err(_), _) => panic!("errored looking up source time"), (_, Err(_)) => panic!("errored looking up target time"), } } Ok(()) } fn check_input_timestamps(&mut self) -> Result<()> { for &Transform { ref original, source_time, .. } in &self.src_inputs { if let MtimeResult::Modified(new_time) = (original.modified())? { if new_time != source_time { return Err(Error::ConcurrentUpdate { path_buf: original.to_path_buf(), old_time: source_time, new_time: new_time, }) } } } for &Transform { ref original, source_time, .. } in &self.lit_inputs { if let MtimeResult::Modified(new_time) = (original.modified())? { if new_time != source_time { return Err(Error::ConcurrentUpdate { path_buf: original.to_path_buf(), old_time: source_time, new_time: new_time, }) } } } Ok(()) } fn create_stamp(&mut self) -> Result<()> { let _f = (File::create(STAMP))?; Ok(()) } fn adjust_stamp_timestamp(&mut self) -> Result<()> { if let Some(stamp) = self.newest_stamp { assert!(stamp > 0); println!("re-stamping tango.stamp to {}", stamp.date_fulltime_badly()); match set_file_times(STAMP, stamp.to_filetime(), stamp.to_filetime()) { Ok(()) => Ok(()), Err(e) => Err(Error::IoError(e)), } } else { Ok(()) } } } fn rs2md(source: R, target: W) -> Result<()> { let mut converter = rs2md::Converter::new(); converter.convert(source, target).map_err(Error::IoError) } fn md2rs(source: R, target: W) -> Result<()> { let converter = md2rs::Converter::new(); converter.convert(source, target).map_err(From::from) } mod md2rs; mod rs2md; fn encode_to_url(code: &str) -> String { use url::percent_encoding as enc; // let new_code: String = enc::utf8_percent_encode(code.trim(), enc::QUERY_ENCODE_SET); let new_code: String = enc::utf8_percent_encode(code.trim(), enc::USERINFO_ENCODE_SET).collect(); format!("https://play.rust-lang.org/?code={}&version=nightly", new_code) } #[cfg(test)] mod testing; ================================================ FILE: src/main.rs ================================================ extern crate tango; use std::error::Error; pub fn main() { tango::process_root().unwrap_or_else(|e| { let mut cause: Option<&dyn Error> = Some(&e); while let Some(c) = cause { let next_cause = c.source(); if next_cause.is_some() { println!("{}, due to", c); } else { println!("root error: {}", c); } cause = next_cause; } panic!("IO error {}", e); }) } ================================================ FILE: src/md2rs.rs ================================================ use std::io::{self, BufRead, Write}; pub struct Converter { state: State, blank_line_count: usize, buffered_lines: String, warnings: Vec, } use super::Warning; #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum State { MarkdownBlank, MarkdownText, MarkdownMeta, Rust, } impl Converter { pub fn new() -> Converter { Converter { state: State::MarkdownBlank, blank_line_count: 0, buffered_lines: String::new(), warnings: vec![], } } } pub enum Exception { IoError(io::Error), Warnings(Vec), } impl From for Exception { fn from(e: io::Error) -> Self { Exception::IoError(e) } } impl Converter { pub fn convert(mut self, r:R, mut w:W) -> Result<(), Exception> { let source = io::BufReader::new(r); for line in source.lines() { let line = (line)?; (self.handle(&line, &mut w))?; } if self.warnings.is_empty() { Ok(()) } else { Err(Exception::Warnings(self.warnings)) } } pub fn handle(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> { let str9 = line.chars().take(9).collect::(); let str7 = line.chars().take(7).collect::(); match (self.state, &str7[..], &str9[..]) { (State::MarkdownBlank, "```rust", _) | (State::MarkdownText, "```rust", _) => { self.buffered_lines = String::new(); let rest = &line.chars().skip(7).collect::(); if rest != "" { (self.transition(w, State::MarkdownMeta))?; (self.meta_note(&rest, w))?; } self.transition(w, State::Rust) } (State::MarkdownBlank, _, "```{.rust") | (State::MarkdownText, _, "```{.rust") => { self.buffered_lines = String::new(); let rest = &line.chars().skip(9).collect::(); if rest != "" { (self.transition(w, State::MarkdownMeta))?; (self.meta_note(&format!(" {{{}", rest), w))?; } self.transition(w, State::Rust) } (State::Rust, "```", _) => { self.transition(w, State::MarkdownBlank) } // FIXME: accum blank lines and only emit them with // prefix if there's no state transition; otherwise // emit them with no prefix. (This is in part the // motivation for the `fn finish_section` design.) (_, "", _) => { self.blank_line(w) } _ => { // HACK: if we find anything that looks like a markdown-named playpen link ... let open_pat = "["; let close_pat = "]: https://play.rust-lang.org/?code="; if let (Some(open), Some(close)) = (line.find(open_pat), line.find(close_pat)) { // ... then we assume it is associated with the (hopefully immediately preceding) // code block, so we emit a `//@@@` named tag for that code block. // checking here that emitted code block matches // up with emitted url. If non-match, then warn // the user, and suggest they re-run `tango` after // touching the file to generate matching url. let expect = super::encode_to_url(&self.buffered_lines); let actual = &line[(close+3)..]; if expect != actual { self.warnings.push(Warning::EncodedUrlMismatch { actual: actual.to_string(), expect: expect }) } self.name_block(line, &line[open+1..close], w) } else { self.nonblank_line(line, w) } } } } pub fn meta_note(&mut self, note: &str, w: &mut dyn Write) -> io::Result<()> { assert!(note != ""); self.nonblank_line(note, w) } pub fn name_block(&mut self, _line: &str, name: &str, w: &mut dyn Write) -> io::Result<()> { assert!(name != ""); writeln!(w, "//@@@ {}", name) } pub fn nonblank_line(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> { let (blank_prefix, line_prefix) = match self.state { State::MarkdownBlank => ("", "//@ "), State::MarkdownText => ("//@", "//@ "), State::MarkdownMeta => ("//@", "//@@"), State::Rust => ("", ""), }; for _ in 0..self.blank_line_count { (writeln!(w, "{}", blank_prefix))?; } self.blank_line_count = 0; match self.state { State::MarkdownBlank => (self.transition(w, State::MarkdownText))?, State::MarkdownMeta | State::MarkdownText => {} State::Rust => { self.buffered_lines.push_str("\n"); self.buffered_lines.push_str(line); } } writeln!(w, "{}{}", line_prefix, line) } fn blank_line(&mut self, _w: &mut dyn Write) -> io::Result<()> { match self.state { State::Rust => { self.buffered_lines.push_str("\n"); } State::MarkdownBlank | State::MarkdownMeta | State::MarkdownText => {} } self.blank_line_count += 1; Ok(()) } fn finish_section(&mut self, w: &mut dyn Write) -> io::Result<()> { for _ in 0..self.blank_line_count { (writeln!(w, ""))?; } self.blank_line_count = 0; Ok(()) } fn transition(&mut self, w: &mut dyn Write, s: State) -> io::Result<()> { match s { State::MarkdownMeta => { assert!(self.state != State::Rust); (self.finish_section(w))?; } State::Rust => { assert!(self.state != State::Rust); self.buffered_lines = String::new(); } State::MarkdownText => { assert_eq!(self.state, State::MarkdownBlank); (self.finish_section(w))?; } State::MarkdownBlank => { assert_eq!(self.state, State::Rust); (self.finish_section(w))?; } } self.state = s; Ok(()) } } ================================================ FILE: src/rs2md.rs ================================================ use std::io::{self, BufRead, Write}; use super::encode_to_url; #[derive(Debug)] pub struct Converter { output_state: State, blank_line_count: usize, buffered_code: String, meta_note: Option, } #[derive(Copy, Clone, PartialEq, Eq, Debug)] enum State { MarkdownFirstLine, MarkdownLines, Rust, } impl Converter { pub fn new() -> Converter { Converter { output_state: State::MarkdownFirstLine, blank_line_count: 0, buffered_code: String::new(), meta_note: None, } } } #[derive(Debug)] enum Effect<'a> { BlankLn, WriteLn(&'a str), StartCodeBlock, FinisCodeBlock, BlankLitComment, } #[derive(Debug)] enum EffectContext<'a> { Finalize, NonblankLine(&'a str), Transition(State), } impl Converter { pub fn convert(&mut self, r:R, mut w:W) -> io::Result<()> { let source = io::BufReader::new(r); for line in source.lines() { let line = (line)?; (self.handle(&line, &mut w))?; } self.finalize(&mut w) } pub fn finalize(&mut self, w: &mut dyn Write) -> io::Result<()> { match self.output_state { State::Rust => self.effect(EffectContext::Finalize, Effect::FinisCodeBlock, w), State::MarkdownFirstLine | State::MarkdownLines => Ok(()) } } pub fn handle(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> { let line_right = line.trim_start(); if line_right.is_empty() { self.blank_line(w) } else if line_right.starts_with("//@ ") { let line = &line_right[4..]; if line.trim().is_empty() { (self.blank_line(w))? } match self.output_state { State::Rust => (self.transition(w, State::MarkdownFirstLine))?, State::MarkdownFirstLine => (self.transition(w, State::MarkdownLines))?, State::MarkdownLines => {} } if line.trim().is_empty() { Ok(()) } else { self.nonblank_line(line, w) } } else if line_right.starts_with("//@@@") { let line = &line_right[5..]; if !line.trim().is_empty() { match self.output_state { State::Rust => { (self.transition(w, State::MarkdownFirstLine))?; (self.emit_named_code(line.trim(), w))?; } State::MarkdownFirstLine => { (self.transition(w, State::MarkdownLines))?; (self.emit_named_code(line.trim(), w))?; } State::MarkdownLines => { (self.emit_named_code(line.trim(), w))?; } } } Ok(()) } else if line_right.starts_with("//@@") { let line = &line_right[4..]; if !line.trim().is_empty() { self.set_meta_note(line.trim()); } Ok(()) } else if line_right.starts_with("//@") { let line = &line_right[3..]; match self.output_state { State::Rust => (self.transition(w, State::MarkdownFirstLine))?, State::MarkdownFirstLine => (self.transition(w, State::MarkdownLines))?, State::MarkdownLines => {} } if line.trim().is_empty() { self.blank_line(w) } else { self.nonblank_line(line, w) } } else { match self.output_state { State::MarkdownFirstLine | State::MarkdownLines => (self.transition(w, State::Rust))?, _ => {} } self.nonblank_line(line, w) } } fn emit_named_code(&mut self, name: &str, w: &mut dyn Write) -> io::Result<()> { writeln!(w, "[{}]: {}", name, encode_to_url(&self.buffered_code)) } fn set_meta_note(&mut self, note: &str) { if let Some(ref prev_note) = self.meta_note { println!("warning: discarding meta note {} for {}", prev_note, note); } self.meta_note = Some(note.to_string()); } fn effect(&mut self, _c: EffectContext, e: Effect, w: &mut dyn Write) -> io::Result<()> { // println!("effect _c: {:?} e: {:?}", _c, e); match e { Effect::BlankLn => writeln!(w, ""), Effect::WriteLn(line) => writeln!(w, "{}", line), Effect::StartCodeBlock => { if let Some(ref note) = self.meta_note { assert_eq!(note.chars().next(), Some('{')); (writeln!(w, "```{{.rust{}", ¬e[1..]))?; } else { (writeln!(w, "```rust"))?; } self.meta_note = None; self.buffered_code = String::new(); Ok(()) } Effect::FinisCodeBlock => { (writeln!(w, "```"))?; Ok(()) } Effect::BlankLitComment => writeln!(w, ""), } } fn nonblank_line(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> { for _ in 0..self.blank_line_count { (self.effect(EffectContext::NonblankLine(line), Effect::BlankLn, w))?; } if State::Rust == self.output_state { self.buffered_code = format!("{}\n{}", self.buffered_code, line); } self.blank_line_count = 0; self.effect(EffectContext::NonblankLine(line), Effect::WriteLn(line), w) } fn blank_line(&mut self, _w: &mut dyn Write) -> io::Result<()> { self.blank_line_count += 1; if State::Rust == self.output_state { self.buffered_code = format!("{}\n", self.buffered_code); } Ok(()) } fn finish_section(&mut self, _w: &mut dyn Write) -> io::Result<()> { Ok(()) } fn transition(&mut self, w: &mut dyn Write, s: State) -> io::Result<()> { match s { State::MarkdownFirstLine => { assert_eq!(self.output_state, State::Rust); (self.effect(EffectContext::Transition(s), Effect::FinisCodeBlock, w))?; for _ in 0..self.blank_line_count { (self.effect(EffectContext::Transition(s), Effect::BlankLn, w))?; } self.blank_line_count = 0; } State::MarkdownLines => { assert_eq!(self.output_state, State::MarkdownFirstLine); for _ in 0..self.blank_line_count { (self.effect(EffectContext::Transition(s), Effect::BlankLitComment, w))?; } self.blank_line_count = 0; } State::Rust => { assert!(self.output_state != State::Rust); (self.finish_section(w))?; for _ in 0..self.blank_line_count { (self.effect(EffectContext::Transition(s), Effect::BlankLn, w))?; } self.blank_line_count = 0; (self.effect(EffectContext::Transition(s), Effect::StartCodeBlock, w))?; } } self.output_state = s; Ok(()) } } ================================================ FILE: src/testing/mod.rs ================================================ use super::{md2rs, rs2md}; mod test_snippets; struct DifferingLines<'a> { left_line_num: usize, left: &'a str, right_line_num: usize, right: &'a str, } enum ComparisonResult<'a> { Ok, LineDifferences(Vec>), LineCountMismatch(usize, usize, Vec), } // #[cfg(test)] fn compare_lines<'a>(a: &'a str, b: &'a str) -> ComparisonResult<'a> { let a: Vec<_> = a.lines().collect(); let b: Vec<_> = b.lines().collect(); let mut i = 0; let mut j = 0; let mut differing_lines: Vec = Vec::new(); while i < a.len() && j < b.len() { if a[i] == b[j] { i += 1; j += 1; continue; } differing_lines.push(DifferingLines { left_line_num: i, right_line_num: j, left: a[i], right: b[j], }); for j_ in (j+1)..b.len() { if a[i] == b[j_] { j = j_; continue; } } for i_ in (i+1)..a.len() { if a[i_] == b[j] { i = i_; continue; } } i += 1; j += 1; } if differing_lines.len() != 0 { ComparisonResult::LineDifferences(differing_lines) } else if i == a.len() && j == b.len() && i == j { ComparisonResult::Ok } else { let mut v = Vec::new(); if a.len() > b.len() { for i in b.len()..a.len() { v.push(a[i].to_string()); } } else { for j in a.len()..b.len() { v.push(b[j].to_string()); } } ComparisonResult::LineCountMismatch(a.len(), b.len(), v) } } fn panic_if_different<'a>(name_a: &str, a: &'a str, name_b: &str, b: &'a str) { match compare_lines(a, b) { ComparisonResult::LineDifferences(differences) => { for difference in differences { println!("lines {lnum} and {rnum} differ:\n{nl:>8}: {l}\n{nr:>8}: {r}", lnum=difference.left_line_num+1, rnum=difference.right_line_num+1, nl=name_a, l=difference.left, nr=name_b, r=difference.right); } panic!("saw differences"); } ComparisonResult::LineCountMismatch(a, b, v) => { for line in v { println!("excess line: {}", line); } panic!("Content differs:\n{nl:>8}: {l} lines\n{nr:>8}: {r} lines", nl=name_a, l=a, nr=name_b, r=b); } ComparisonResult::Ok => {} } } #[cfg(test)] fn core_test_md2rs(md: &str, rs: &str) { let mut output = Vec::new(); md2rs(md.as_bytes(), &mut output).unwrap(); let output = String::from_utf8(output).unwrap(); panic_if_different("actual", &output, "expect", rs); } #[cfg(test)] fn warn_test_md2rs(md: &str, rs: &str) { let mut output = Vec::new(); match md2rs(md.as_bytes(), &mut output) { Err(super::Error::Warnings(_)) => {} Ok(_) => panic!("expected successful conversion with warning"), Err(_) => panic!("error in converion"), } let output = String::from_utf8(output).unwrap(); panic_if_different("actual", &output, "expect", rs); } #[cfg(test)] fn core_test_rs2md(rs: &str, md: &str) { let mut output = Vec::new(); rs2md(rs.as_bytes(), &mut output).unwrap(); let output = String::from_utf8(output).unwrap(); panic_if_different("actual", &output, "expect", md); } #[test] fn test_onetext_md2rs() { core_test_md2rs(test_snippets::ONE_TEXT_LINE_MD, test_snippets::ONE_TEXT_LINE_RS); } #[test] fn test_onetext_rs2md() { core_test_rs2md(test_snippets::ONE_TEXT_LINE_RS, test_snippets::ONE_TEXT_LINE_MD); } #[test] fn test_onerust_md2rs() { core_test_md2rs(test_snippets::ONE_RUST_LINE_MD, test_snippets::ONE_RUST_LINE_RS); } #[test] fn test_onerust_rs2md() { core_test_rs2md(test_snippets::ONE_RUST_LINE_RS, test_snippets::ONE_RUST_LINE_MD); } #[test] fn test_hello_md2rs() { core_test_md2rs(test_snippets::HELLO_MD, test_snippets::HELLO_RS); } #[test] fn test_hello_rs2md() { core_test_rs2md(test_snippets::HELLO_RS, test_snippets::HELLO_MD); } #[test] fn test_hello2_md2rs() { core_test_md2rs(test_snippets::HELLO2_MD, test_snippets::HELLO2_RS); } #[test] fn test_hello2_rs2md() { core_test_rs2md(test_snippets::HELLO2_RS, test_snippets::HELLO2_MD); } #[test] fn test_hello3_md2rs() { core_test_md2rs(test_snippets::HELLO3_MD, test_snippets::HELLO3_RS); } #[test] fn test_hello3_rs2md() { core_test_rs2md(test_snippets::HELLO3_RS, test_snippets::HELLO3_MD); } #[test] fn test_hello4_md2rs() { core_test_md2rs(test_snippets::HELLO4_MD, test_snippets::HELLO4_RS); } #[test] fn test_hello4_rs2md() { core_test_rs2md(test_snippets::HELLO4_RS, test_snippets::HELLO4_MD); } #[test] fn test_prodigal5_md2rs() { core_test_md2rs(test_snippets::PRODIGAL5_MD, test_snippets::HARVEST5_RS); } #[test] fn test_prodigal5return_md2rs() { core_test_rs2md(test_snippets::HARVEST5_RS, test_snippets::RETURN5_MD); } #[test] fn test_hello6_metadata_md2rs() { core_test_md2rs(test_snippets::HELLO6_METADATA_MD, test_snippets::HELLO6_METADATA_RS); } #[test] fn test_hello6_metadata_rs2md() { core_test_rs2md(test_snippets::HELLO6_METADATA_RS, test_snippets::HELLO6_METADATA_MD); } #[test] fn test_hello7_link_to_play_md2rs() { core_test_md2rs(test_snippets::HELLO7_LINK_TO_PLAY_MD, test_snippets::HELLO7_LINK_TO_PLAY_RS); } #[test] fn test_hello7_link_to_play_rs2md() { core_test_rs2md(test_snippets::HELLO7_LINK_TO_PLAY_RS, test_snippets::HELLO7_LINK_TO_PLAY_MD); } #[test] fn test_hello8_link_to_play_md2rs() { core_test_md2rs(test_snippets::HELLO8_LINK_TO_PLAY_MD, test_snippets::HELLO8_LINK_TO_PLAY_RS); } #[test] fn test_hello8_link_to_play_rs2md() { core_test_rs2md(test_snippets::HELLO8_LINK_TO_PLAY_RS, test_snippets::HELLO8_LINK_TO_PLAY_MD); } #[test] fn test_hello9_link_to_play_md2rs_warn() { warn_test_md2rs(test_snippets::HELLO9_LINK_TO_PLAY_MD_WARN, test_snippets::HELLO9_LINK_TO_PLAY_RS); } #[test] fn test_hello10_link_to_play_eq_md2rs() { core_test_md2rs(test_snippets::HELLO10_LINK_TO_PLAY_EQ_MD, test_snippets::HELLO10_LINK_TO_PLAY_EQ_RS); } #[test] fn test_hello10_link_to_play_eq_rs2md() { core_test_rs2md(test_snippets::HELLO10_LINK_TO_PLAY_EQ_RS, test_snippets::HELLO10_LINK_TO_PLAY_EQ_MD); } #[test] fn test_hello11_link_to_play_md2rs() { core_test_md2rs(test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_MD, test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_RS); } #[test] fn test_hello11_link_to_play_rs2md() { core_test_rs2md(test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_RS, test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_MD); } #[test] fn test_hello12_link_to_play_md2rs() { core_test_md2rs(test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_MD, test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_RS); } #[test] fn test_hello12_link_to_play_rs2md() { core_test_rs2md(test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_RS, test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_MD); } ================================================ FILE: src/testing/test_snippets.rs ================================================ pub const ONE_TEXT_LINE_RS: &'static str = "//@ This is a demo without code."; pub const ONE_TEXT_LINE_MD: &'static str = "This is a demo without code."; pub const ONE_RUST_LINE_RS: &'static str = r#"fn main() { println!("one rust line"); }"#; pub const ONE_RUST_LINE_MD: &'static str = r#"```rust fn main() { println!("one rust line"); } ``` "#; pub const HELLO_RS: &'static str = r#"//@ # Hello World //@ This is a Hello World demo. // Code started here (at this normal comment) fn main() { println!("Hello World"); } //@ And then the text resumes here. "#; pub const HELLO_MD: &'static str = r#"# Hello World This is a Hello World demo. ```rust // Code started here (at this normal comment) fn main() { println!("Hello World"); } ``` And then the text resumes here. "#; pub const HELLO2_RS: &'static str = r#"//@ # Hello World //@ This is a second Hello World demo. // Code started here (at this normal comment) fn main() { println!("Hello World"); } //@ And then the text resumes here, after a line break. "#; pub const HELLO2_MD: &'static str = r#"# Hello World This is a second Hello World demo. ```rust // Code started here (at this normal comment) fn main() { println!("Hello World"); } ``` And then the text resumes here, after a line break. "#; pub const HELLO3_RS: &'static str = r#" // Code started here (at this normal comment) fn main() { hello() } //@ Here is some expository text in the middle //@ It spans ... //@ ... multiple lines // Here is yet more code! // (and we end with code, not doc) fn hello() { println!("Hello World"); } "#; pub const HELLO3_MD: &'static str = r#" ```rust // Code started here (at this normal comment) fn main() { hello() } ``` Here is some expository text in the middle It spans ... ... multiple lines ```rust // Here is yet more code! // (and we end with code, not doc) fn hello() { println!("Hello World"); } ``` "#; pub const HELLO4_MD: &'static str = r#"# Hello World Here is some expository text, but this one ... ... has a gap between its lines. "#; pub const HELLO4_RS: &'static str = r#"//@ # Hello World //@ Here is some expository text, but this one ... //@ //@ ... has a gap between its lines. "#; pub const PRODIGAL5_MD: &'static str = r#"# Hello World ```rust let code_fragment; ``` This looks like it has a nice para break before its starts, but note the tab "#; pub const HARVEST5_RS: &'static str = r#"//@ # Hello World let code_fragment; //@ //@ This looks like it has a nice para break before its starts, //@ but note the tab "#; pub const RETURN5_MD: &'static str = r#"# Hello World ```rust let code_fragment; ``` This looks like it has a nice para break before its starts, but note the tab "#; pub const HELLO6_METADATA_MD: &'static str = r#"# Hello World ```{.rust .css_class_metadata } // The question is, can we preserve the .css_class_metdata ``` "#; pub const HELLO6_METADATA_RS: &'static str = r#"//@ # Hello World //@@ { .css_class_metadata } // The question is, can we preserve the .css_class_metdata "#; pub const HELLO7_LINK_TO_PLAY_MD: &'static str = r#"# Hello World ```rust // ``` [hello7]: https://play.rust-lang.org/?code=%2F%2F&version=nightly "#; pub const HELLO7_LINK_TO_PLAY_RS: &'static str = r#"//@ # Hello World // //@@@ hello7 "#; pub const HELLO8_LINK_TO_PLAY_MD: &'static str = r#"# Hello World ```rust // Here is some content fn main() { } ``` [hello8]: https://play.rust-lang.org/?code=%2F%2F%20Here%20is%20some%20content%0Afn%20main()%20%7B%20%7D&version=nightly "#; pub const HELLO8_LINK_TO_PLAY_RS: &'static str = r#"//@ # Hello World // Here is some content fn main() { } //@@@ hello8 "#; pub const HELLO9_LINK_TO_PLAY_MD_WARN: &'static str = r#"# Hello World ```rust // Here is some content fn main() { } ``` [hello9]: https://play.rust-lang.org/?code=does_not_match&version=nightly "#; pub const HELLO9_LINK_TO_PLAY_RS: &'static str = r#"//@ # Hello World // Here is some content fn main() { } //@@@ hello9 "#; pub const HELLO10_LINK_TO_PLAY_EQ_MD: &'static str = r#"# Hello World ```rust = ``` [hello10]: https://play.rust-lang.org/?code=%3D&version=nightly "#; pub const HELLO10_LINK_TO_PLAY_EQ_RS: &'static str = r#"//@ # Hello World = //@@@ hello10 "#; pub const HELLO11_LINK_TO_PLAY_HTML_SEP_MD: &'static str = r#"# Hello World ```rust Hi ```