[
  {
    "path": ".gitignore",
    "content": "target\n*~\n"
  },
  {
    "path": "Cargo.toml",
    "content": "[package]\nname = \"tango\"\nversion = \"0.8.3\"\nauthors = [\"Felix S. Klock II <pnkfelix@pnkfx.org>\"]\ndescription = \"Markdown-based Literate programming in Rust, integrated with Cargo.\"\nlicense = \"MIT/Apache-2.0\"\nrepository = \"https://github.com/pnkfelix/tango\"\ndocumentation = \"https://github.com/pnkfelix/tango-demo/blob/master/README.md\"\n\n[dependencies]\n## Every time I tried to get `debug!` working with `cargo test` I am\n## flummoxed. Not sure what my problem is, but for now these are not\n## enough on their own, so I am leaving them out of the checked-in\n## version.\n##\n# log = \"*\"\n# env_logger = \"*\"\nfiletime = \"0.1\"\nwalkdir = \"1.0\"\nurl = \"1.4\"\n## dev-dependencies are only pulled in for tests/benchmarks\n[dev-dependencies]\ntempdir = \"0.3\"\n\n[[test]]\nname = \"runner\"\n##\n## Can set below to stop passing `--test` when compiling runner.rs\n## (and thus use a `fn main` within it as its associated test driver).\n## But for now I am trying to work within the integrated testing framework,\n## which means in part avoiding global state like `env::set_current_dir`\n##\n# harness = false\n"
  },
  {
    "path": "LICENSE-APACHE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"{}\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright {yyyy} {name of copyright owner}\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n\n"
  },
  {
    "path": "LICENSE-MIT",
    "content": "Copyright (c) 2015 Felix Stanley Klock II\n\nPermission is hereby granted, free of charge, to any\nperson obtaining a copy of this software and associated\ndocumentation files (the \"Software\"), to deal in the\nSoftware without restriction, including without\nlimitation the rights to use, copy, modify, merge,\npublish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software\nis furnished to do so, subject to the following\nconditions:\n\nThe above copyright notice and this permission notice\nshall be included in all copies or substantial portions\nof the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF\nANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED\nTO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\nPARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT\nSHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY\nCLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\nOF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR\nIN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER\nDEALINGS IN THE SOFTWARE.\n\n    Status API Training Shop Blog About Help \n\n"
  },
  {
    "path": "README.md",
    "content": "# tango\nMarkdown-based Literate programming in Rust, integrated with Cargo.\n\nSee https://github.com/pnkfelix/tango-demo/ for a demonstration of how to use it.\n\n(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.)\n"
  },
  {
    "path": "build.rs",
    "content": "fn main() {\n    // a no-op `build.rs` to trick `cargo` into setting `OUT_DIR` env var.\n}\n"
  },
  {
    "path": "src/lib.rs",
    "content": "// #[macro_use]\n// extern crate log;\n// extern crate env_logger;\n\nextern crate filetime;\nextern crate url;\nextern crate walkdir;\n\nuse filetime::set_file_times;\nuse walkdir::{WalkDir};\n\nuse std::convert;\nuse std::error::Error as ErrorTrait;\nuse std::ffi::OsStr;\nuse std::fmt;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Write};\nuse std::ops;\nuse std::path::{Path, PathBuf};\nuse std::cell::RefCell;\n\nuse self::timestamp::{Timestamp, Timestamped};\n\npub mod timestamp;\n\npub const STAMP: &'static str = \"tango.stamp\";\n//pub const SRC_DIR: &'static str = \"src\";\n// pnkfelix wanted the `LIT_DIR` to be `lit/`, but `cargo build`\n// currently assumes that *all* build sources live in `src/`. So it\n// is easier for now to just have the two directories be the same.\n//pub const LIT_DIR: &'static str = \"src/lit\";\n\nthread_local! {\n    pub static SRC_DIR: RefCell<String> = RefCell::new(\"src\".to_string());\n    pub static LIT_DIR: RefCell<String> = RefCell::new(\"src\".to_string());\n}\n\nfn set_lit_dir(directory: String) {\n    LIT_DIR.with(|lit_dir| {\n        *lit_dir.borrow_mut() = directory\n    });\n}\n\nfn set_src_dir(directory: String) {\n    SRC_DIR.with(|src_dir| {\n        *src_dir.borrow_mut() = directory\n    });\n}\n\n/// Returns the current directory for storing the literate .md files\npub fn get_lit_dir() -> String {\n    LIT_DIR.with(|lit_dir| lit_dir.borrow().clone())\n}\n\n/// Returns the current directory for storing the \"source\" .rs files\npub fn get_src_dir() -> String {\n    SRC_DIR.with(|src_dir| src_dir.borrow().clone())\n}\n\npub struct Config {\n    src_dir: String,\n    lit_dir: String,\n    rerun_if: bool,\n}\n\nimpl Config {\n    pub fn new() -> Config {\n        Config {\n            src_dir: String::from(\"src\"),\n            lit_dir: String::from(\"src\"),\n            rerun_if: false,\n        }\n    }\n    pub fn set_src_dir(&mut self, new_src_dir: String) -> &mut Config {\n        self.src_dir = new_src_dir;\n        self\n    }\n    pub fn set_lit_dir(&mut self, new_lit_dir: String) -> &mut Config {\n        self.lit_dir = new_lit_dir;\n        self\n    }\n    pub fn emit_rerun_if(&mut self) -> &mut Config {\n        self.rerun_if = true;\n        self\n    }\n\n}\n\n\n#[derive(Debug)]\npub enum Error {\n    IoError(io::Error),\n    CheckInputError { error: check::Error },\n    MtimeError(PathBuf),\n    ConcurrentUpdate { path_buf: PathBuf, old_time: mtime, new_time: mtime },\n    Warnings(Vec<Warning>),\n}\n\n#[derive(Debug)]\npub enum Warning {\n    EncodedUrlMismatch { actual: String, expect: String }\n}\n\nimpl fmt::Display for Warning {\n    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            Warning::EncodedUrlMismatch { ref actual, ref expect } => {\n                write!(w, \"mismatch between encoded url, expect: {} actual: {}\",\n                       expect, actual)\n            }\n        }\n    }\n}\n\nimpl From<md2rs::Exception> for Error {\n    fn from(e: md2rs::Exception) -> Self {\n        match e {\n            md2rs::Exception::IoError(e) => Error::IoError(e),\n            md2rs::Exception::Warnings(w) => Error::Warnings(w),\n        }\n    }\n}\n\nimpl fmt::Display for Error {\n    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            Error::IoError(_) =>\n                write!(w, \"IO error running `tango`\"),\n            Error::CheckInputError { .. } =>\n                write!(w, \"input check errors running `tango`\"),\n            Error::MtimeError(ref p) =>\n                write!(w, \"modification time error from `tango` checking {}\",\n                       p.to_string_lossy()),\n            Error::ConcurrentUpdate { ref path_buf, .. } =>\n                write!(w, \"concurrent update during `tango` to source file {}\",\n                       path_buf.to_string_lossy()),\n            Error::Warnings(ref warnings) => {\n                for warn in warnings {\n                    (write!(w, \"WARNING: {}\", warn))?;\n                }\n                Ok(())\n            }\n        }\n    }\n}\n\nimpl ErrorTrait for Error {\n    fn source(&self) -> Option<&(dyn ErrorTrait + 'static)> {\n        match *self {\n            Error::IoError(ref e) => Some(e),\n            Error::CheckInputError { ref error, .. } => {\n                Some(error)\n            }\n            Error::Warnings(_) |\n            Error::MtimeError(_) |\n            Error::ConcurrentUpdate { .. } => None,\n        }\n    }\n}\n\nimpl convert::From<io::Error> for Error {\n    fn from(e: io::Error) -> Self {\n        Error::IoError(e)\n    }\n}\n\nimpl convert::From<walkdir::Error> for Error {\n    fn from(e: walkdir::Error) -> Self {\n        Error::IoError(From::from(e))\n    }\n}\n\npub type Result<X> = std::result::Result<X, Error>;\n\n#[allow(non_camel_case_types)]\npub type mtime = Timestamp;\n\n#[derive(Copy, Clone, PartialEq, Eq, Debug)]\nenum MtimeResult {\n    NonExistant,\n    Modified(mtime),\n}\n\ntrait Mtime { fn modified(&self) -> Result<MtimeResult>; }\nimpl Mtime for File {\n    fn modified(&self) -> Result<MtimeResult> {\n        // #![allow(deprecated)]\n        // if let Some(p) = self.path() {\n        //     if !p.exists() {\n        //         return Err(Error::MtimeError(p.to_path_buf()));\n        //     }\n        // }\n        let m = (self.metadata())?;\n        Ok(MtimeResult::Modified(m.timestamp()))\n    }\n}\nimpl Mtime for fs::DirEntry {\n    fn modified(&self) -> Result<MtimeResult> {\n        let m = (self.metadata())?;\n        Ok(MtimeResult::Modified(m.timestamp()))\n    }\n}\nimpl Mtime for RsPath {\n    fn modified(&self) -> Result<MtimeResult> {\n        if self.0.exists() {\n            let f = (File::open(&self.0))?;\n            f.modified()\n        } else {\n            Ok(MtimeResult::NonExistant)\n        }\n    }\n}\nimpl Mtime for MdPath {\n    fn modified(&self) -> Result<MtimeResult> {\n        if self.0.exists() {\n            let f = (File::open(&self.0))?;\n            f.modified()\n        } else {\n            Ok(MtimeResult::NonExistant)\n        }\n    }\n}\n\npub fn process_root_with_config(config: Config) -> Result<()> {\n    //let _root = (std::env::current_dir())?;\n    //println!(\"Tango is running from: {:?}\", root);\n    //std::env::set_current_dir(_root).unwrap();\n    set_lit_dir(config.lit_dir);\n    set_src_dir(config.src_dir);\n    let emit_rerun_if = config.rerun_if;\n\n    let stamp_path = Path::new(STAMP);\n    if stamp_path.exists() {\n        process_with_stamp((File::open(stamp_path))?, emit_rerun_if)\n    } else {\n        process_without_stamp(emit_rerun_if)\n    }\n}\n\n\npub fn process_root() -> Result<()> {\n    //let _root = (std::env::current_dir())?;\n    // println!(\"Tango is running from: {:?}\", _root);\n\n    let emit_rerun_if = false;\n    let stamp_path = Path::new(STAMP);\n    if stamp_path.exists() {\n        process_with_stamp((File::open(stamp_path))?, emit_rerun_if)\n    } else {\n        process_without_stamp(emit_rerun_if)\n    }\n}\n\n// Both of the functions below have the same basic outline:\n//\n// 1. gather_inputs(): Build up a list of potential transforms based\n//    on existing files.\n//\n// 2. generate_content(): Apply each transform in turn, *iff* the\n//    source is newer than target.\n//\n// 3. check_input_timestamps(): Ensure no input was concurrently\n//    modified while tango ran.\n//\n// 4. adjust_stamp_timestamp(): Update the `tango.stamp` file to the\n//    youngest timestamp we saw, creating the file if necessary.\n//\n// The reason there are two functions is that in one case we have a\n// pre-existing `tango.stamp` that we want to compare against during\n// `generate_content()` (to guard against diverging {source, target}\n// paths; *at most* one of {source, target} is meant to be updated in\n// between tango runs.\n//\n// (It probably wouldn't be hard to unify the two functions into a\n//  single method on the `Context`, though.)\n\nfn process_with_stamp(stamp: File, emit_rerun_if: bool) -> Result<()> {\n    println!(\"\\n\\nemit rerun if: {:?}\\n\\n\", emit_rerun_if);\n    if let Ok(MtimeResult::Modified(ts)) = stamp.modified() {\n        println!(\"Rerunning tango; last recorded run was stamped: {}\",\n                 ts.date_fulltime_badly());\n    } else {\n        panic!(\"why are we trying to process_with_stamp when given: {:?}\", stamp);\n    }\n    let mut c = (Context::new(Some(stamp)))?;\n    c.emit_rerun_if = emit_rerun_if;\n    (c.gather_inputs())?;\n    (c.generate_content())?;\n    (c.check_input_timestamps())?;\n    (c.adjust_stamp_timestamp())?;\n    // (c.report_dir(Path::new(\".\")))?;\n    Ok(())\n}\n\nfn process_without_stamp(emit_rerun_if: bool) -> Result<()> {\n    println!(\"Running tango; no previously recorded run\");\n    println!(\"\\n\\nemit rerun if: {:?}\\n\\n\", emit_rerun_if);\n    let mut c = (Context::new(None))?;\n    c.emit_rerun_if = emit_rerun_if;\n    (c.gather_inputs())?;\n    (c.generate_content())?;\n    (c.check_input_timestamps())?;\n    (c.create_stamp())?;\n    (c.adjust_stamp_timestamp())?;\n    // (c.report_dir(Path::new(\".\")))?;\n    Ok(())\n}\n\n#[derive(Debug)]\nstruct RsPath(PathBuf);\n#[derive(Debug)]\nstruct MdPath(PathBuf);\n\n\nstruct Context {\n    orig_stamp: Option<(File, mtime)>,\n    src_inputs: Vec<Transform<RsPath, MdPath>>,\n    lit_inputs: Vec<Transform<MdPath, RsPath>>,\n    newest_stamp: Option<mtime>,\n    emit_rerun_if: bool,\n}\n\ntrait Extensions {\n    fn extension(&self) -> Option<&str>;\n    fn rs_extension(&self) -> bool {\n        self.extension() == Some(\"rs\")\n    }\n    fn md_extension(&self) -> bool {\n        self.extension() == Some(\"md\")\n    }\n}\n\nimpl Extensions for Path {\n    fn extension(&self) -> Option<&str> {\n        Path::extension(self).and_then(|s|s.to_str())\n    }\n}\n\nimpl ops::Deref for RsPath {\n    type Target = Path; fn deref(&self) -> &Path { &self.0 }\n}\n\nimpl ops::Deref for MdPath {\n    type Target = Path; fn deref(&self) -> &Path { &self.0 }\n}\n\nfn check_path(typename: &str, p: &Path, ext: &str, root: &str) {\n    println!(\"\\n in check_path, the root is: {r:?} , path is: {p:?}, ext is {e:?}\", r=root, p=p, e=ext);\n    if Extensions::extension(p) != Some(ext) { panic!(\"{t} requires `.{ext}` extension; path: {p:?}\", t=typename, ext=ext, p=p); }\n    if !p.starts_with(root) { panic!(\"{t} must be rooted at `{root}/`; path: {p:?}\", t=typename, root=root, p=p); }\n}\n\nimpl RsPath {\n    fn new(p: PathBuf) -> RsPath {\n        check_path(\"RsPath\", &p, \"rs\", &get_src_dir());\n        RsPath(p)\n    }\n    fn to_md(&self) -> MdPath {\n        let mut p = PathBuf::new();\n        p.push(get_lit_dir());\n        for c in self.0.components().skip(1) {\n            let c: &OsStr = c.as_ref();\n            p.push(c.to_str().expect(\"how else can I replace root?\"));\n        }\n        p.set_extension(\"md\");\n        MdPath::new(p)\n    }\n}\n\nimpl MdPath {\n    fn new(p: PathBuf) -> MdPath {\n        check_path(\"MdPath\", &p, \"md\", &get_lit_dir());\n        MdPath(p)\n    }\n    fn to_rs(&self) -> RsPath {\n        let mut p = PathBuf::new();\n        p.push(get_src_dir());\n        for c in self.0.components().skip(1) {\n            let c: &OsStr = c.as_ref();\n            p.push(c.to_str().expect(\"how else can I replace root?\"));\n        }\n        p.set_extension(\"rs\");\n        RsPath::new(p)\n    }\n}\n\ntrait Transforms: Sized + Mtime + fmt::Debug {\n    type Target: Mtime + fmt::Debug;\n\n    // Computes path to desired target based on self's (source) path.\n    fn target(&self) -> Self::Target;\n\n    // Constructs a transform for generating the target from self\n    // (which is a path to the source), gathering the current\n    // timestamps on both the source and the target.\n    fn transform(self) -> Result<Transform<Self, Self::Target>> {\n        let source_time = match self.modified() {\n            Ok(MtimeResult::Modified(t)) => t,\n            Ok(MtimeResult::NonExistant) => panic!(\"impossible for {:?} to be NonExistant\", self),\n            Err(e) => {\n                println!(\"failure to extract mtime on source {:?}\", self);\n                return Err(e);\n            }\n        };\n\n        let target = self.target();\n        let target_time = match target.modified() {\n            Ok(t) => t,\n            Err(e) => {\n                println!(\"failure to extract mtime on target {:?}\", target);\n                return Err(e);\n            }\n        };\n        Ok(Transform { source_time: source_time,\n                       target_time: target_time,\n                       original: self,\n                       generate: target,\n        })\n    }\n}\n\nimpl Transforms for RsPath {\n    type Target = MdPath;\n    fn target(&self) -> MdPath { self.to_md() }\n}\n\nimpl Transforms for MdPath {\n    type Target = RsPath;\n    fn target(&self) -> RsPath { self.to_rs() }\n}\n\n#[derive(Debug)]\npub struct Transform<X, Y> {\n    source_time: mtime,\n    target_time: MtimeResult,\n    original: X,\n    generate: Y,\n}\n\npub mod check {\n    use std::error::Error as ErrorTrait;\n    use std::fmt;\n    use std::ops;\n    use std::path::{Path, PathBuf};\n    use std::result;\n    use super::Transform;\n    pub type PathTransform = Transform<PathBuf, PathBuf>;\n    #[derive(Debug)]\n    pub enum ErrorKind {\n        TargetYoungerThanOriginal { tgt: String, src: String },\n        NoTangoStampExists { tgt: String, src: String },\n        TangoStampOlderThanTarget { tgt: String },\n    }\n    #[derive(Debug)]\n    pub struct Error(ErrorKind, PathTransform);\n\n    impl fmt::Display for Error {\n        fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {\n            match self.0 {\n                ErrorKind::TargetYoungerThanOriginal { ref tgt, ref src } => {\n                    write!(w, \"target `{}` is younger than source `{}`; \\\n                               therefore we assume target has modifications that need to be preserved.\",\n                           tgt, src)\n                }\n                ErrorKind::NoTangoStampExists { ref src, ref tgt } => {\n                    write!(w, \"both source `{}` and target `{}` exist but no `tango.stamp` is present\",\n                           src, tgt)\n                }\n                ErrorKind::TangoStampOlderThanTarget { ref tgt } => {\n                    write!(w, \"`tango.stamp` is older than target `{}`; \\\n                               therefore we assume source and target have diverged since last tango run.\",\n                           tgt)\n                }\n            }\n        }\n    }\n\n    impl ErrorTrait for Error {\n        fn description(&self) -> &str {\n            match self.0 {\n                ErrorKind::TargetYoungerThanOriginal { .. }=> {\n                    \"target is younger than source; \\\n                     therefore we assume target has modifications that need to be preserved.\"\n                }\n                ErrorKind::NoTangoStampExists { .. } => {\n                    \"both source and target exist but no `tango.stamp` is present\"\n                }\n                ErrorKind::TangoStampOlderThanTarget { .. } => {\n                    \"`tango.stamp` is older than target; \\\n                     therefore we assume source and target have diverged since last tango run.\"\n                }\n            }\n        }\n    }\n\n    pub type Result<X> = result::Result<X, Error>;\n\n    impl<X,Y> Transform<X, Y>\n        where X: ops::Deref<Target=Path>, Y: ops::Deref<Target=Path>\n    {\n        pub fn error(&self, kind: ErrorKind) -> Error {\n            let t = Transform { original: self.original.to_path_buf(),\n                                generate: self.generate.to_path_buf(),\n                                source_time: self.source_time,\n                                target_time: self.target_time,\n            };\n            Error(kind, t)\n        }\n    }\n}\n\nenum TransformNeed { Needed, Unneeded, }\n\nimpl Context {\n    fn new(opt_stamp: Option<File>) -> Result<Context> {\n        let stamp_modified = match opt_stamp {\n            None => None,\n            Some(stamp) => {\n                let mtime = (stamp.modified())?;\n                let mtime = match mtime {\n                    MtimeResult::NonExistant => panic!(\"impossible\"),\n                    MtimeResult::Modified(t) => t,\n                };\n                Some((stamp, mtime))\n            }\n        };\n        let c = Context {\n            orig_stamp: stamp_modified,\n            src_inputs: Vec::new(),\n            lit_inputs: Vec::new(),\n            newest_stamp: None,\n            emit_rerun_if: true,\n        };\n        Ok(c)\n    }\n\n    fn check_transform<X, Y>(&self, t: &Transform<X, Y>) -> check::Result<TransformNeed>\n        where X: ops::Deref<Target=Path> + Mtime,\n              Y: ops::Deref<Target=Path> + Mtime,\n    {\n\n        use self::check::ErrorKind::*;\n\n\n        let t_mod = match t.target_time {\n            MtimeResult::Modified(t) => t,\n            MtimeResult::NonExistant => {\n                assert!(!t.generate.exists());\n                return Ok(TransformNeed::Needed);\n            }\n        };\n        // let src = t.original.display().to_string();\n        // let tgt = t.generate.display().to_string();\n        let s_mod = t.source_time;\n\n        let same_age_at_low_precision = s_mod.to_ms() == t_mod.to_ms();\n\n        if t_mod > s_mod {\n            // Target is newer than source: therefore we do not want to\n            // overwrite the target via this transform.\n            return Ok(TransformNeed::Unneeded);\n        }\n\n        // Now know:  t_mod <= s_mod\n\n        if same_age_at_low_precision {\n            //        00000000011111111112222222222333333333344444444445555555555666666666677777777778\n            //        12345678901234567890123456789012345678901234567890123456789012345678901234567890\n            println!(\"Warning: source and target have timestamps that differ only at nanosecond level\\n    \\\n                          precision. Tango currently treats such timestamps as matching, and therefore\\n    \\\n                          will not rebuild the target file.\\n\\\n                          \\n    \\\n                          source: {SRC:?} timestamp: {SRC_TS} \\n    \\\n                          target: {TGT:?} timestamp: {TGT_TS}\\n\",\n                     SRC=t.original.display(), SRC_TS=s_mod.date_fulltime_badly(),\n                     TGT=t.generate.display(), TGT_TS=t_mod.date_fulltime_badly());\n            return Ok(TransformNeed::Unneeded);\n        }\n\n        // Now know: t_mod is older than source even after truncating\n        // to millisecond precision.\n\n        match self.orig_stamp {\n            None => return Err(t.error(NoTangoStampExists {\n                src: t.original.display().to_string(),\n                tgt: t.generate.display().to_string(),\n            })),\n            Some((_, stamp_time)) => {\n                let older_at_high_precision = stamp_time < t_mod;\n                let older_at_low_precision = stamp_time.to_ms() < t_mod.to_ms();\n                if older_at_low_precision {\n                    // The target file was updated more recently than\n                    // the tango.stamp file, even after truncation to\n                    // millisecond precision.\n                    //\n                    // Therefore, we assume that user has updated both\n                    // the source and the target independently since\n                    // the last tango run.  This is a scenario that\n                    // tango cannot currently recover from, so we\n                    // issue an error and tell the user to fix the\n                    // problem.\n                    return Err(t.error(TangoStampOlderThanTarget {\n                        tgt: t.generate.display().to_string(),\n                    }));\n                }\n                if older_at_high_precision && !older_at_low_precision {\n                    //        00000000011111111112222222222333333333344444444445555555555666666666677777777778\n                    //        12345678901234567890123456789012345678901234567890123456789012345678901234567890\n                    println!(\"Warning: `tango.stamp` and target `{}` have timestamps that differ only at \\n\\\n                                  nanosecond level precision. Tango currently treats such timestamps as,\\n\\\n                                  matching and will rebuild the target file rather than error\",\n                             t.generate.display());\n                }\n\n                // got here: tango.stamp is not older than the target\n                // file.  So we fall through to the base case.\n            }\n        }\n\n        // Invariant:\n        // Target `t` exists, but,\n        // s_mod >= t_mod (and t_mod <= stamp_time if stamp exists).\n        //\n        // Thus it is safe to overwrite `t` based on source content.\n        Ok(TransformNeed::Needed)\n    }\n\n    #[cfg(not_now)]\n    fn report_dir(&self, p: &Path) -> Result<()> {\n        let src_dir = get_src_dir();\n        let lit_dir = get_lit_dir();\n        let src_path = Path::new(&src_dir);\n        let lit_path = Path::new(&lit_dir);\n\n        for (i, ent) in (WalkDir::new(p))?.enumerate() {\n            let ent = (ent)?;\n            let modified = (ent.modified())?;\n            println!(\"entry[{}]: {:?} {:?}\", i, ent.path(), modified);\n        }\n        Ok(())\n    }\n\n    fn update_newest_time(&mut self, new_time: mtime) {\n        if let Some(ref mut stamp) = self.newest_stamp {\n            if new_time > *stamp {\n                *stamp = new_time;\n            }\n        } else {\n            self.newest_stamp = Some(new_time);\n        }\n    }\n\n    fn push_src(&mut self, t: Transform<RsPath, MdPath>) {\n        self.update_newest_time(t.source_time);\n        self.src_inputs.push(t);\n    }\n    fn push_lit(&mut self, t: Transform<MdPath, RsPath>) {\n        self.update_newest_time(t.source_time);\n        self.lit_inputs.push(t);\n    }\n\n    fn gather_inputs(&mut self) -> Result<()> {\n        // println!(\"gather_inputs\");\n        let src_dir = get_src_dir();\n        let lit_dir = get_lit_dir();\n        let src_path = Path::new(&src_dir);\n        let lit_path = Path::new(&lit_dir);\n\n        fn keep_file_name(p: &Path) -> std::result::Result<(), &'static str> {\n            match p.file_name().and_then(|x|x.to_str()) {\n                None =>\n                    Err(\"file name is not valid unicode\"),\n                Some(s) if s.starts_with('.') =>\n                    Err(\"file name has leading period\"),\n                Some(..) =>\n                    Ok(()),\n            }\n        }\n\n        fn warn_if_nonexistant<M:Mtime+fmt::Debug>(m: &M) -> Result<()> {\n            match m.modified() {\n                Err(e) => Err(e),\n                Ok(MtimeResult::Modified(..)) => Ok(()),\n                Ok(MtimeResult::NonExistant) => {\n                    // This can arise; namely some tools are\n                    // generating symlinks in `src` of the form\n                    //\n                    // `src/.#lib.md -> fklock@fklock-Oenone.local.96195`\n                    //\n                    // where the target is non-existant (presumably as\n                    // a way to locally mark a file as being open by\n                    // the tool?), and then this script interprets it\n                    // as being open.\n                    println!(\"warning: non-existant source: {:?}\", m);\n                    Ok(())\n                }\n            }\n\n        }\n\n        // This loop gathers all of the .rs files that currently\n        // exist, and schedules transforms that would turn them into\n        // corresponding target .md files.\n\n        // println!(\"gather-rs\");\n        for ent in WalkDir::new(src_path).into_iter() {\n            let ent = (ent)?;\n            let p = ent.path();\n            if let Err(why) = keep_file_name(p) {\n                println!(\"skipping {}; {}\", p.display(), why);\n                continue;\n            }\n            if !p.rs_extension() {\n                // println!(\"gather-rs skip {} due to non .rs\", p.display());\n                continue;\n            }\n            let rs = RsPath::new(p.to_path_buf());\n            (warn_if_nonexistant(&rs))?;\n\n            if self.emit_rerun_if {\n                println!(\"cargo:rerun-if-changed={}\", &rs.display());\n            }\n\n            let t = (rs.transform())?;\n            match self.check_transform(&t) {\n                Ok(TransformNeed::Needed) => self.push_src(t),\n                Ok(TransformNeed::Unneeded) => {}\n                Err(e) => {\n                    println!(\"gather_inputs err: {}\", e);\n                    return Err(Error::CheckInputError {\n                        error: e,\n                    })\n                }\n            }\n        }\n\n        // This loop gathers all of the .md files that currently\n        // exist, and schedules transforms that would turn them into\n        // corresponding target .rs files.\n\n        //println!(\"gather-md, lit_path is: {:?}\", lit_path);\n        for ent in WalkDir::new(lit_path).into_iter() {\n            //println!(\"ent is {:?}\", ent);\n            let ent = (ent)?;\n            let p = ent.path();\n            if let Err(why) = keep_file_name(p) {\n                println!(\"skipping {}; {}\", p.display(), why);\n                continue;\n            }\n            if !p.md_extension() {\n                // println!(\"gather-md skip {} due to non .md\", p.display());\n                continue;\n            }\n            let md = MdPath::new(p.to_path_buf());\n            (warn_if_nonexistant(&md))?;\n\n            if self.emit_rerun_if {\n                println!(\"cargo:rerun-if-changed={}\", &md.display());\n            }\n\n            let t = (md.transform())?;\n            match self.check_transform(&t) {\n                Ok(TransformNeed::Needed) => {\n                    // println!(\"gather-md add {:?}\", t);;\n                    self.push_lit(t)\n                }\n                Ok(TransformNeed::Unneeded) => {\n                    // println!(\"gather-md discard unneeded {:?}\", t);;\n                }\n                Err(e) => {\n                    println!(\"gather_inputs err: {}\", e);\n                    return Err(Error::CheckInputError {\n                        error: e,\n                    })\n                }\n            }\n        }\n\n        // At this point we've scheduled all the transforms we want to\n        // run; they will be applied unconditionally, even if both\n        // source and target exist. (The intent is that a target\n        // younger than source would have been filtered during the\n        // .check_transform calls above.)\n\n        Ok(())\n    }\n    fn generate_content(&mut self) -> Result<()> {\n        for &Transform { ref original, ref generate, source_time, .. } in &self.src_inputs {\n            let source = (File::open(&original.0))?;\n            let target = (File::create(&generate.0))?;\n            assert!(source_time > 0);\n            println!(\"generating lit {:?}\", &generate.0);\n            (rs2md(source, target))?;\n            let timestamp = source_time.to_filetime();\n            println!(\"backdating lit {:?} to {}\", &generate.0, source_time.date_fulltime_badly());\n            (set_file_times(&generate.0, timestamp, timestamp))?;\n        }\n        for &mut Transform { ref original, ref generate, ref mut source_time, .. } in &mut self.lit_inputs {\n            let source = (File::open(&original.0))?;\n            let target = (File::create(&generate.0))?;\n            assert!(*source_time > 0);\n            println!(\"generating src {:?}\", &generate.0);\n            (md2rs(source, target))?;\n            println!(\"backdating src {:?} to {}\", &generate.0, source_time.date_fulltime_badly());\n            (set_file_times(&generate.0,\n                                source_time.to_filetime(),\n                                source_time.to_filetime()))?;\n            let source = (File::open(&original.0))?;\n            let target = (File::open(&generate.0))?;\n            match (source.modified(), target.modified()) {\n                (Ok(MtimeResult::Modified(src_time)),\n                 Ok(MtimeResult::Modified(tgt_time))) => {\n                    // At this point, we would *like* to assert this:\n                    #[cfg(not_possible_right_now)] assert_eq!(src_time, tgt_time);\n                    // but it does not work, due to this bug:\n                    // https://github.com/alexcrichton/filetime/issues/9\n\n                    assert_eq!(src_time.to_ms(), tgt_time.to_ms());\n                }\n                (Ok(MtimeResult::NonExistant), _) => panic!(\"how could source not exist\"),\n                (_, Ok(MtimeResult::NonExistant)) => panic!(\"how could target not exist\"),\n                (Err(_), Err(_)) => panic!(\"errored looking up both source and target times\"),\n                (Err(_), _) => panic!(\"errored looking up source time\"),\n                (_, Err(_)) => panic!(\"errored looking up target time\"),\n            }\n        }\n        Ok(())\n    }\n    fn check_input_timestamps(&mut self) -> Result<()> {\n        for &Transform { ref original, source_time, .. } in &self.src_inputs {\n            if let MtimeResult::Modified(new_time) = (original.modified())? {\n                if new_time != source_time {\n                    return Err(Error::ConcurrentUpdate {\n                        path_buf: original.to_path_buf(),\n                        old_time: source_time,\n                        new_time: new_time,\n                    })\n                }\n            }\n        }\n        for &Transform { ref original, source_time, .. } in &self.lit_inputs {\n            if let MtimeResult::Modified(new_time) = (original.modified())? {\n                if new_time != source_time {\n                    return Err(Error::ConcurrentUpdate {\n                        path_buf: original.to_path_buf(),\n                        old_time: source_time,\n                        new_time: new_time,\n                    })\n                }\n            }\n        }\n        Ok(())\n    }\n    fn create_stamp(&mut self) -> Result<()> {\n        let _f = (File::create(STAMP))?;\n        Ok(())\n    }\n    fn adjust_stamp_timestamp(&mut self) -> Result<()> {\n        if let Some(stamp) = self.newest_stamp {\n            assert!(stamp > 0);\n            println!(\"re-stamping tango.stamp to {}\", stamp.date_fulltime_badly());\n\n            match set_file_times(STAMP, stamp.to_filetime(), stamp.to_filetime()) {\n                Ok(()) => Ok(()),\n                Err(e) => Err(Error::IoError(e)),\n            }\n        } else {\n            Ok(())\n        }\n    }\n}\n\nfn rs2md<R:Read, W:Write>(source: R, target: W) -> Result<()> {\n    let mut converter = rs2md::Converter::new();\n    converter.convert(source, target).map_err(Error::IoError)\n}\n\nfn md2rs<R:Read, W:Write>(source: R, target: W) -> Result<()> {\n    let converter = md2rs::Converter::new();\n    converter.convert(source, target).map_err(From::from)\n}\n\nmod md2rs;\n\nmod rs2md;\n\nfn encode_to_url(code: &str) -> String {\n    use url::percent_encoding as enc;\n    // let new_code: String = enc::utf8_percent_encode(code.trim(), enc::QUERY_ENCODE_SET);\n    let new_code: String = enc::utf8_percent_encode(code.trim(), enc::USERINFO_ENCODE_SET).collect();\n    format!(\"https://play.rust-lang.org/?code={}&version=nightly\", new_code)\n}\n\n#[cfg(test)]\nmod testing;\n"
  },
  {
    "path": "src/main.rs",
    "content": "extern crate tango;\n\nuse std::error::Error;\n\npub fn main() {\n    tango::process_root().unwrap_or_else(|e| {\n        let mut cause: Option<&dyn Error> = Some(&e);\n        while let Some(c) = cause {\n            let next_cause = c.source();\n            if next_cause.is_some() {\n                println!(\"{}, due to\", c);\n            } else {\n                println!(\"root error: {}\", c);\n            }\n            cause = next_cause;\n        }\n        panic!(\"IO error {}\", e);\n    })\n}\n"
  },
  {
    "path": "src/md2rs.rs",
    "content": "use std::io::{self, BufRead, Write};\n\npub struct Converter {\n    state: State,\n    blank_line_count: usize,\n    buffered_lines: String,\n    warnings: Vec<Warning>,\n}\n\nuse super::Warning;\n\n#[derive(Copy, Clone, PartialEq, Eq, Debug)]\nenum State { MarkdownBlank, MarkdownText, MarkdownMeta, Rust, }\nimpl Converter {\n    pub fn new() -> Converter {\n        Converter {\n            state: State::MarkdownBlank,\n            blank_line_count: 0,\n            buffered_lines: String::new(),\n            warnings: vec![],\n        }\n    }\n}\n\npub enum Exception {\n    IoError(io::Error),\n    Warnings(Vec<Warning>),\n}\n\nimpl From<io::Error> for Exception {\n    fn from(e: io::Error) -> Self {\n        Exception::IoError(e)\n    }\n}\n\nimpl Converter {\n    pub fn convert<R:io::Read, W:io::Write>(mut self, r:R, mut w:W) -> Result<(), Exception> {\n        let source = io::BufReader::new(r);\n        for line in source.lines() {\n            let line = (line)?;\n            (self.handle(&line, &mut w))?;\n        }\n        if self.warnings.is_empty() {\n            Ok(())\n        } else {\n            Err(Exception::Warnings(self.warnings))\n        }\n    }\n\n    pub fn handle(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> {\n        let str9 = line.chars().take(9).collect::<String>();\n        let str7 = line.chars().take(7).collect::<String>();\n        match (self.state, &str7[..], &str9[..]) {\n            (State::MarkdownBlank, \"```rust\", _) |\n            (State::MarkdownText, \"```rust\", _) => {\n                self.buffered_lines = String::new();\n                let rest =  &line.chars().skip(7).collect::<String>();\n                if rest != \"\" {\n                    (self.transition(w, State::MarkdownMeta))?;\n                    (self.meta_note(&rest, w))?;\n                }\n                self.transition(w, State::Rust)\n            }\n            (State::MarkdownBlank, _, \"```{.rust\") |\n            (State::MarkdownText, _, \"```{.rust\") => {\n                self.buffered_lines = String::new();\n                let rest =  &line.chars().skip(9).collect::<String>();\n                if rest != \"\" {\n                    (self.transition(w, State::MarkdownMeta))?;\n                    (self.meta_note(&format!(\" {{{}\", rest), w))?;\n                }\n                self.transition(w, State::Rust)\n            }\n            (State::Rust, \"```\", _) => {\n                self.transition(w, State::MarkdownBlank)\n            }\n\n            // FIXME: accum blank lines and only emit them with\n            // prefix if there's no state transition; otherwise\n            // emit them with no prefix. (This is in part the\n            // motivation for the `fn finish_section` design.)\n            (_, \"\", _) => {\n                self.blank_line(w)\n            }\n\n            _ => {\n                // HACK: if we find anything that looks like a markdown-named playpen link ...\n                let open_pat = \"[\";\n                let close_pat = \"]: https://play.rust-lang.org/?code=\";\n                if let (Some(open), Some(close)) = (line.find(open_pat), line.find(close_pat)) {\n                    // ... then we assume it is associated with the (hopefully immediately preceding)\n                    // code block, so we emit a `//@@@` named tag for that code block.\n\n                    // checking here that emitted code block matches\n                    // up with emitted url. If non-match, then warn\n                    // the user, and suggest they re-run `tango` after\n                    // touching the file to generate matching url.\n                    let expect = super::encode_to_url(&self.buffered_lines);\n                    let actual = &line[(close+3)..];\n                    if expect != actual {\n                        self.warnings.push(Warning::EncodedUrlMismatch {\n                            actual: actual.to_string(),\n                            expect: expect\n                        })\n                    }\n                    self.name_block(line, &line[open+1..close], w)\n                } else {\n                    self.nonblank_line(line, w)\n                }\n            }\n        }\n    }\n\n    pub fn meta_note(&mut self, note: &str, w: &mut dyn Write) -> io::Result<()> {\n        assert!(note != \"\");\n        self.nonblank_line(note, w)\n    }\n\n    pub fn name_block(&mut self, _line: &str, name: &str, w: &mut dyn Write) -> io::Result<()> {\n        assert!(name != \"\");\n        writeln!(w, \"//@@@ {}\", name)\n    }\n\n    pub fn nonblank_line(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> {\n        let (blank_prefix, line_prefix) = match self.state {\n            State::MarkdownBlank => (\"\", \"//@ \"),\n            State::MarkdownText => (\"//@\", \"//@ \"),\n            State::MarkdownMeta => (\"//@\", \"//@@\"),\n            State::Rust => (\"\", \"\"),\n        };\n        for _ in 0..self.blank_line_count {\n            (writeln!(w, \"{}\", blank_prefix))?;\n\n        }\n        self.blank_line_count = 0;\n\n        match self.state {\n            State::MarkdownBlank =>\n                (self.transition(w, State::MarkdownText))?,\n            State::MarkdownMeta |\n            State::MarkdownText => {}\n            State::Rust => {\n                self.buffered_lines.push_str(\"\\n\");\n                self.buffered_lines.push_str(line);\n            }\n        }\n\n        writeln!(w, \"{}{}\", line_prefix, line)\n    }\n\n    fn blank_line(&mut self, _w: &mut dyn Write) -> io::Result<()> {\n        match self.state {\n            State::Rust => {\n                self.buffered_lines.push_str(\"\\n\");\n            }\n            State::MarkdownBlank |\n            State::MarkdownMeta |\n            State::MarkdownText => {}\n        }\n        self.blank_line_count += 1;\n        Ok(())\n    }\n\n    fn finish_section(&mut self, w: &mut dyn Write) -> io::Result<()> {\n        for _ in 0..self.blank_line_count {\n            (writeln!(w, \"\"))?;\n        }\n        self.blank_line_count = 0;\n        Ok(())\n    }\n\n    fn transition(&mut self, w: &mut dyn Write, s: State) -> io::Result<()> {\n        match s {\n            State::MarkdownMeta => {\n                assert!(self.state != State::Rust);\n                (self.finish_section(w))?;\n            }\n            State::Rust => {\n                assert!(self.state != State::Rust);\n                self.buffered_lines = String::new();\n            }\n            State::MarkdownText => {\n                assert_eq!(self.state, State::MarkdownBlank);\n                (self.finish_section(w))?;\n            }\n            State::MarkdownBlank => {\n                assert_eq!(self.state, State::Rust);\n                (self.finish_section(w))?;\n            }\n        }\n        self.state = s;\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/rs2md.rs",
    "content": "use std::io::{self, BufRead, Write};\nuse super::encode_to_url;\n\n#[derive(Debug)]\npub struct Converter {\n    output_state: State,\n    blank_line_count: usize,\n    buffered_code: String,\n    meta_note: Option<String>,\n}\n#[derive(Copy, Clone, PartialEq, Eq, Debug)]\nenum State { MarkdownFirstLine, MarkdownLines, Rust, }\nimpl Converter {\n    pub fn new() -> Converter {\n        Converter { output_state: State::MarkdownFirstLine,\n                    blank_line_count: 0,\n                    buffered_code: String::new(),\n                    meta_note: None, }\n    }\n}\n\n#[derive(Debug)]\nenum Effect<'a> {\n    BlankLn,\n    WriteLn(&'a str),\n    StartCodeBlock,\n    FinisCodeBlock,\n    BlankLitComment,\n}\n\n#[derive(Debug)]\nenum EffectContext<'a> {\n    Finalize,\n    NonblankLine(&'a str),\n    Transition(State),\n}\n\nimpl Converter {\n    pub fn convert<R:io::Read, W:io::Write>(&mut self, r:R, mut w:W) -> io::Result<()> {\n        let source = io::BufReader::new(r);\n        for line in source.lines() {\n            let line = (line)?;\n            (self.handle(&line, &mut w))?;\n        }\n        self.finalize(&mut w)\n    }\n\n    pub fn finalize(&mut self, w: &mut dyn Write) -> io::Result<()> {\n        match self.output_state {\n            State::Rust =>\n                self.effect(EffectContext::Finalize, Effect::FinisCodeBlock, w),\n            State::MarkdownFirstLine |\n            State::MarkdownLines =>\n                Ok(())\n        }\n    }\n\n    pub fn handle(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> {\n        let line_right = line.trim_start();\n        if line_right.is_empty() {\n            self.blank_line(w)\n        } else if line_right.starts_with(\"//@ \") {\n            let line = &line_right[4..];\n            if line.trim().is_empty() {\n                (self.blank_line(w))?\n            }\n            match self.output_state {\n                State::Rust =>\n                    (self.transition(w, State::MarkdownFirstLine))?,\n                State::MarkdownFirstLine =>\n                    (self.transition(w, State::MarkdownLines))?,\n                State::MarkdownLines =>\n                    {}\n            }\n            if line.trim().is_empty() {\n                Ok(())\n            } else {\n                self.nonblank_line(line, w)\n            }\n        } else if line_right.starts_with(\"//@@@\") {\n            let line = &line_right[5..];\n            if !line.trim().is_empty() {\n                match self.output_state {\n                    State::Rust => {\n                        (self.transition(w, State::MarkdownFirstLine))?;\n                        (self.emit_named_code(line.trim(), w))?;\n                    }\n                    State::MarkdownFirstLine => {\n                        (self.transition(w, State::MarkdownLines))?;\n                        (self.emit_named_code(line.trim(), w))?;\n                    }\n                    State::MarkdownLines => {\n                        (self.emit_named_code(line.trim(), w))?;\n                    }\n                }\n            }\n            Ok(())\n        } else if line_right.starts_with(\"//@@\") {\n            let line = &line_right[4..];\n            if !line.trim().is_empty() {\n                self.set_meta_note(line.trim());\n            }\n            Ok(())\n        } else if line_right.starts_with(\"//@\") {\n            let line = &line_right[3..];\n            match self.output_state {\n                State::Rust =>\n                    (self.transition(w, State::MarkdownFirstLine))?,\n                State::MarkdownFirstLine =>\n                    (self.transition(w, State::MarkdownLines))?,\n                State::MarkdownLines =>\n                {}\n            }\n            if line.trim().is_empty() {\n                self.blank_line(w)\n            } else {\n                self.nonblank_line(line, w)\n            }\n        } else {\n            match self.output_state {\n                State::MarkdownFirstLine |\n                State::MarkdownLines =>\n                    (self.transition(w, State::Rust))?,\n                _ => {}\n            }\n            self.nonblank_line(line, w)\n        }\n    }\n\n    fn emit_named_code(&mut self, name: &str, w: &mut dyn Write) -> io::Result<()> {\n        writeln!(w, \"[{}]: {}\", name, encode_to_url(&self.buffered_code))\n    }\n\n    fn set_meta_note(&mut self, note: &str) {\n        if let Some(ref prev_note) = self.meta_note {\n            println!(\"warning: discarding meta note {} for {}\", prev_note, note);\n        }\n        self.meta_note = Some(note.to_string());\n    }\n\n    fn effect(&mut self, _c: EffectContext, e: Effect, w: &mut dyn Write) -> io::Result<()> {\n        // println!(\"effect _c: {:?} e: {:?}\", _c, e);\n        match e {\n            Effect::BlankLn => writeln!(w, \"\"),\n            Effect::WriteLn(line) => writeln!(w, \"{}\", line),\n            Effect::StartCodeBlock => {\n                if let Some(ref note) = self.meta_note {\n                    assert_eq!(note.chars().next(), Some('{'));\n                    (writeln!(w, \"```{{.rust{}\", &note[1..]))?;\n                } else {\n                    (writeln!(w, \"```rust\"))?;\n                }\n                self.meta_note = None;\n                self.buffered_code = String::new();\n                Ok(())\n            }\n            Effect::FinisCodeBlock => {\n                (writeln!(w, \"```\"))?;\n                Ok(())\n            }\n            Effect::BlankLitComment => writeln!(w, \"\"),\n        }\n    }\n\n    fn nonblank_line(&mut self, line: &str, w: &mut dyn Write) -> io::Result<()> {\n        for _ in 0..self.blank_line_count {\n            (self.effect(EffectContext::NonblankLine(line), Effect::BlankLn, w))?;\n        }\n        if State::Rust == self.output_state {\n            self.buffered_code = format!(\"{}\\n{}\", self.buffered_code, line);\n        }\n        self.blank_line_count = 0;\n        self.effect(EffectContext::NonblankLine(line), Effect::WriteLn(line), w)\n    }\n\n    fn blank_line(&mut self, _w: &mut dyn Write) -> io::Result<()> {\n        self.blank_line_count += 1;\n        if State::Rust == self.output_state {\n            self.buffered_code = format!(\"{}\\n\", self.buffered_code);\n        }\n        Ok(())\n    }\n\n    fn finish_section(&mut self, _w: &mut dyn Write) -> io::Result<()> {\n        Ok(())\n    }\n\n    fn transition(&mut self, w: &mut dyn Write, s: State) -> io::Result<()> {\n        match s {\n            State::MarkdownFirstLine => {\n                assert_eq!(self.output_state, State::Rust);\n                (self.effect(EffectContext::Transition(s), Effect::FinisCodeBlock, w))?;\n                for _ in 0..self.blank_line_count {\n                    (self.effect(EffectContext::Transition(s), Effect::BlankLn, w))?;\n                }\n                self.blank_line_count = 0;\n            }\n            State::MarkdownLines => {\n                assert_eq!(self.output_state, State::MarkdownFirstLine);\n                for _ in 0..self.blank_line_count {\n                    (self.effect(EffectContext::Transition(s), Effect::BlankLitComment, w))?;\n                }\n                self.blank_line_count = 0;\n            }\n            State::Rust => {\n                assert!(self.output_state != State::Rust);\n                (self.finish_section(w))?;\n                for _ in 0..self.blank_line_count {\n                    (self.effect(EffectContext::Transition(s), Effect::BlankLn, w))?;\n                }\n                self.blank_line_count = 0;\n                (self.effect(EffectContext::Transition(s), Effect::StartCodeBlock, w))?;\n            }\n        }\n        self.output_state = s;\n        Ok(())\n    }\n}\n"
  },
  {
    "path": "src/testing/mod.rs",
    "content": "use super::{md2rs, rs2md};\nmod test_snippets;\n\nstruct DifferingLines<'a> {\n    left_line_num: usize,\n    left: &'a str,\n    right_line_num: usize,\n    right: &'a str,\n}\n\nenum ComparisonResult<'a> {\n    Ok,\n    LineDifferences(Vec<DifferingLines<'a>>),\n    LineCountMismatch(usize, usize, Vec<String>),\n}\n\n// #[cfg(test)]\nfn compare_lines<'a>(a: &'a str, b: &'a str) -> ComparisonResult<'a> {\n    let a: Vec<_> = a.lines().collect();\n    let b: Vec<_> = b.lines().collect();\n    let mut i = 0;\n    let mut j = 0;\n\n    let mut differing_lines: Vec<DifferingLines> = Vec::new();\n\n    while i < a.len() && j < b.len() {\n        if a[i] == b[j] {\n            i += 1;\n            j += 1;\n            continue;\n        }\n\n        differing_lines.push(DifferingLines {\n            left_line_num: i,\n            right_line_num: j,\n            left: a[i],\n            right: b[j],\n        });\n\n        for j_ in (j+1)..b.len() {\n            if a[i] == b[j_] {\n                j = j_;\n                continue;\n            }\n        }\n\n        for i_ in (i+1)..a.len() {\n            if a[i_] == b[j] {\n                i = i_;\n                continue;\n            }\n        }\n\n        i += 1;\n        j += 1;\n    }\n\n    if differing_lines.len() != 0 {\n        ComparisonResult::LineDifferences(differing_lines)\n    } else if i == a.len() && j == b.len() && i == j {\n        ComparisonResult::Ok\n    } else {\n        let mut v = Vec::new();\n        if a.len() > b.len() {\n            for i in b.len()..a.len() {\n                v.push(a[i].to_string());\n            }\n        } else {\n            for j in a.len()..b.len() {\n                v.push(b[j].to_string());\n            }\n        }\n        ComparisonResult::LineCountMismatch(a.len(), b.len(), v)\n    }\n}\n\nfn panic_if_different<'a>(name_a: &str, a: &'a str, name_b: &str, b: &'a str) {\n    match compare_lines(a, b) {\n        ComparisonResult::LineDifferences(differences) => {\n            for difference in differences {\n                println!(\"lines {lnum} and {rnum} differ:\\n{nl:>8}: {l}\\n{nr:>8}: {r}\",\n                         lnum=difference.left_line_num+1,\n                         rnum=difference.right_line_num+1,\n                         nl=name_a,\n                         l=difference.left,\n                         nr=name_b,\n                         r=difference.right);\n            }\n            panic!(\"saw differences\");\n        }\n        ComparisonResult::LineCountMismatch(a, b, v) => {\n            for line in v {\n                println!(\"excess line: {}\", line);\n            }\n            panic!(\"Content differs:\\n{nl:>8}: {l} lines\\n{nr:>8}: {r} lines\",\n                     nl=name_a,\n                     l=a,\n                     nr=name_b,\n                     r=b);\n        }\n        ComparisonResult::Ok => {}\n    }\n}\n\n#[cfg(test)]\nfn core_test_md2rs(md: &str, rs: &str) {\n    let mut output = Vec::new();\n    md2rs(md.as_bytes(), &mut output).unwrap();\n    let output = String::from_utf8(output).unwrap();\n    panic_if_different(\"actual\", &output, \"expect\", rs);\n}\n\n#[cfg(test)]\nfn warn_test_md2rs(md: &str, rs: &str) {\n    let mut output = Vec::new();\n    match md2rs(md.as_bytes(), &mut output) {\n        Err(super::Error::Warnings(_)) => {}\n        Ok(_) => panic!(\"expected successful conversion with warning\"),\n        Err(_) => panic!(\"error in converion\"),\n    }\n    let output = String::from_utf8(output).unwrap();\n    panic_if_different(\"actual\", &output, \"expect\", rs);\n}\n\n#[cfg(test)]\nfn core_test_rs2md(rs: &str, md: &str) {\n    let mut output = Vec::new();\n    rs2md(rs.as_bytes(), &mut output).unwrap();\n    let output = String::from_utf8(output).unwrap();\n    panic_if_different(\"actual\", &output, \"expect\", md);\n}\n\n#[test]\nfn test_onetext_md2rs() {\n    core_test_md2rs(test_snippets::ONE_TEXT_LINE_MD,\n                    test_snippets::ONE_TEXT_LINE_RS);\n}\n\n#[test]\nfn test_onetext_rs2md() {\n    core_test_rs2md(test_snippets::ONE_TEXT_LINE_RS,\n                    test_snippets::ONE_TEXT_LINE_MD);\n}\n\n#[test]\nfn test_onerust_md2rs() {\n    core_test_md2rs(test_snippets::ONE_RUST_LINE_MD,\n                    test_snippets::ONE_RUST_LINE_RS);\n}\n\n#[test]\nfn test_onerust_rs2md() {\n    core_test_rs2md(test_snippets::ONE_RUST_LINE_RS,\n                    test_snippets::ONE_RUST_LINE_MD);\n}\n\n#[test]\nfn test_hello_md2rs() {\n    core_test_md2rs(test_snippets::HELLO_MD, test_snippets::HELLO_RS);\n}\n\n#[test]\nfn test_hello_rs2md() {\n    core_test_rs2md(test_snippets::HELLO_RS, test_snippets::HELLO_MD);\n}\n\n#[test]\nfn test_hello2_md2rs() {\n    core_test_md2rs(test_snippets::HELLO2_MD, test_snippets::HELLO2_RS);\n}\n\n#[test]\nfn test_hello2_rs2md() {\n    core_test_rs2md(test_snippets::HELLO2_RS, test_snippets::HELLO2_MD);\n}\n\n#[test]\nfn test_hello3_md2rs() {\n    core_test_md2rs(test_snippets::HELLO3_MD, test_snippets::HELLO3_RS);\n}\n\n#[test]\nfn test_hello3_rs2md() {\n    core_test_rs2md(test_snippets::HELLO3_RS, test_snippets::HELLO3_MD);\n}\n\n#[test]\nfn test_hello4_md2rs() {\n    core_test_md2rs(test_snippets::HELLO4_MD, test_snippets::HELLO4_RS);\n}\n\n#[test]\nfn test_hello4_rs2md() {\n    core_test_rs2md(test_snippets::HELLO4_RS, test_snippets::HELLO4_MD);\n}\n\n#[test]\nfn test_prodigal5_md2rs() {\n   core_test_md2rs(test_snippets::PRODIGAL5_MD, test_snippets::HARVEST5_RS);\n}\n\n#[test]\nfn test_prodigal5return_md2rs() {\n   core_test_rs2md(test_snippets::HARVEST5_RS, test_snippets::RETURN5_MD);\n}\n\n#[test]\nfn test_hello6_metadata_md2rs() {\n    core_test_md2rs(test_snippets::HELLO6_METADATA_MD,\n                    test_snippets::HELLO6_METADATA_RS);\n}\n\n#[test]\nfn test_hello6_metadata_rs2md() {\n    core_test_rs2md(test_snippets::HELLO6_METADATA_RS,\n                    test_snippets::HELLO6_METADATA_MD);\n}\n\n#[test]\nfn test_hello7_link_to_play_md2rs() {\n    core_test_md2rs(test_snippets::HELLO7_LINK_TO_PLAY_MD,\n                    test_snippets::HELLO7_LINK_TO_PLAY_RS);\n}\n\n#[test]\nfn test_hello7_link_to_play_rs2md() {\n    core_test_rs2md(test_snippets::HELLO7_LINK_TO_PLAY_RS,\n                    test_snippets::HELLO7_LINK_TO_PLAY_MD);\n}\n\n#[test]\nfn test_hello8_link_to_play_md2rs() {\n    core_test_md2rs(test_snippets::HELLO8_LINK_TO_PLAY_MD,\n                    test_snippets::HELLO8_LINK_TO_PLAY_RS);\n}\n\n#[test]\nfn test_hello8_link_to_play_rs2md() {\n    core_test_rs2md(test_snippets::HELLO8_LINK_TO_PLAY_RS,\n                    test_snippets::HELLO8_LINK_TO_PLAY_MD);\n}\n\n#[test]\nfn test_hello9_link_to_play_md2rs_warn() {\n    warn_test_md2rs(test_snippets::HELLO9_LINK_TO_PLAY_MD_WARN,\n                    test_snippets::HELLO9_LINK_TO_PLAY_RS);\n}\n\n#[test]\nfn test_hello10_link_to_play_eq_md2rs() {\n    core_test_md2rs(test_snippets::HELLO10_LINK_TO_PLAY_EQ_MD,\n                    test_snippets::HELLO10_LINK_TO_PLAY_EQ_RS);\n}\n\n#[test]\nfn test_hello10_link_to_play_eq_rs2md() {\n    core_test_rs2md(test_snippets::HELLO10_LINK_TO_PLAY_EQ_RS,\n                    test_snippets::HELLO10_LINK_TO_PLAY_EQ_MD);\n}\n\n#[test]\nfn test_hello11_link_to_play_md2rs() {\n    core_test_md2rs(test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_MD,\n                    test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_RS);\n}\n\n#[test]\nfn test_hello11_link_to_play_rs2md() {\n    core_test_rs2md(test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_RS,\n                    test_snippets::HELLO11_LINK_TO_PLAY_HTML_SEP_MD);\n}\n\n#[test]\nfn test_hello12_link_to_play_md2rs() {\n    core_test_md2rs(test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_MD,\n                    test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_RS);\n}\n\n#[test]\nfn test_hello12_link_to_play_rs2md() {\n    core_test_rs2md(test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_RS,\n                    test_snippets::HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_MD);\n}\n"
  },
  {
    "path": "src/testing/test_snippets.rs",
    "content": "pub const ONE_TEXT_LINE_RS: &'static str = \"//@ This is a demo without code.\";\npub const ONE_TEXT_LINE_MD: &'static str = \"This is a demo without code.\";\n\npub const ONE_RUST_LINE_RS: &'static str = r#\"fn main() { println!(\"one rust line\"); }\"#;\n\npub const ONE_RUST_LINE_MD: &'static str = r#\"```rust\nfn main() { println!(\"one rust line\"); }\n```\n\"#;\n\npub const HELLO_RS: &'static str = r#\"//@ # Hello World\n//@ This is a Hello World demo.\n\n// Code started here (at this normal comment)\nfn main() { println!(\"Hello World\"); }\n//@ And then the text resumes here.\n\"#;\n\npub const HELLO_MD: &'static str = r#\"# Hello World\nThis is a Hello World demo.\n\n```rust\n// Code started here (at this normal comment)\nfn main() { println!(\"Hello World\"); }\n```\nAnd then the text resumes here.\n\"#;\n\npub const HELLO2_RS: &'static str = r#\"//@ # Hello World\n//@ This is a second Hello World demo.\n\n// Code started here (at this normal comment)\nfn main() { println!(\"Hello World\"); }\n\n//@ And then the text resumes here, after a line break.\n\"#;\n\npub const HELLO2_MD: &'static str = r#\"# Hello World\nThis is a second Hello World demo.\n\n```rust\n// Code started here (at this normal comment)\nfn main() { println!(\"Hello World\"); }\n```\n\nAnd then the text resumes here, after a line break.\n\"#;\n\npub const HELLO3_RS: &'static str = r#\"\n\n// Code started here (at this normal comment)\nfn main() { hello() }\n\n//@ Here is some expository text in the middle\n//@ It spans ...\n//@ ... multiple lines\n\n// Here is yet more code!\n// (and we end with code, not doc)\nfn hello() { println!(\"Hello World\"); }\n\"#;\n\npub const HELLO3_MD: &'static str = r#\"\n\n```rust\n// Code started here (at this normal comment)\nfn main() { hello() }\n```\n\nHere is some expository text in the middle\nIt spans ...\n... multiple lines\n\n```rust\n// Here is yet more code!\n// (and we end with code, not doc)\nfn hello() { println!(\"Hello World\"); }\n```\n\"#;\n\npub const HELLO4_MD: &'static str = r#\"# Hello World\nHere is some expository text, but this one ...\n\n... has a gap between its lines.\n\"#;\n\npub const HELLO4_RS: &'static str = r#\"//@ # Hello World\n//@ Here is some expository text, but this one ...\n//@\n//@ ... has a gap between its lines.\n\"#;\n\npub const PRODIGAL5_MD: &'static str = r#\"# Hello World\n```rust\nlet code_fragment;\n```\n\t\nThis looks like it has a nice para break before its starts,\nbut note the tab\n\"#;\n\npub const HARVEST5_RS: &'static str = r#\"//@ # Hello World\nlet code_fragment;\n//@ \t\n//@ This looks like it has a nice para break before its starts,\n//@ but note the tab\n\"#;\n\npub const RETURN5_MD: &'static str = r#\"# Hello World\n```rust\nlet code_fragment;\n```\n\nThis looks like it has a nice para break before its starts,\nbut note the tab\n\"#;\n\npub const HELLO6_METADATA_MD: &'static str = r#\"# Hello World\n\n```{.rust .css_class_metadata }\n// The question is, can we preserve the .css_class_metdata\n```\n\"#;\n\npub const HELLO6_METADATA_RS: &'static str = r#\"//@ # Hello World\n\n//@@ { .css_class_metadata }\n// The question is, can we preserve the .css_class_metdata\n\"#;\n\npub const HELLO7_LINK_TO_PLAY_MD: &'static str = r#\"# Hello World\n\n```rust\n//\n```\n[hello7]: https://play.rust-lang.org/?code=%2F%2F&version=nightly\n\"#;\n\npub const HELLO7_LINK_TO_PLAY_RS: &'static str = r#\"//@ # Hello World\n\n//\n//@@@ hello7\n\"#;\n\npub const HELLO8_LINK_TO_PLAY_MD: &'static str = r#\"# Hello World\n\n```rust\n// Here is some content\nfn main() { }\n```\n[hello8]: https://play.rust-lang.org/?code=%2F%2F%20Here%20is%20some%20content%0Afn%20main()%20%7B%20%7D&version=nightly\n\"#;\n\npub const HELLO8_LINK_TO_PLAY_RS: &'static str = r#\"//@ # Hello World\n\n// Here is some content\nfn main() { }\n//@@@ hello8\n\"#;\n\npub const HELLO9_LINK_TO_PLAY_MD_WARN: &'static str = r#\"# Hello World\n\n```rust\n// Here is some content\nfn main() { }\n```\n[hello9]: https://play.rust-lang.org/?code=does_not_match&version=nightly\n\"#;\n\npub const HELLO9_LINK_TO_PLAY_RS: &'static str = r#\"//@ # Hello World\n\n// Here is some content\nfn main() { }\n//@@@ hello9\n\"#;\n\npub const HELLO10_LINK_TO_PLAY_EQ_MD: &'static str = r#\"# Hello World\n\n```rust\n=\n```\n[hello10]: https://play.rust-lang.org/?code=%3D&version=nightly\n\"#;\n\npub const HELLO10_LINK_TO_PLAY_EQ_RS: &'static str = r#\"//@ # Hello World\n\n=\n//@@@ hello10\n\"#;\n\npub const HELLO11_LINK_TO_PLAY_HTML_SEP_MD: &'static str = r#\"# Hello World\n\n```rust\nHi\n```\n<!--\n[hello11]: https://play.rust-lang.org/?code=Hi&version=nightly\n\"#;\n\npub const HELLO11_LINK_TO_PLAY_HTML_SEP_RS: &'static str = r#\"//@ # Hello World\n\nHi\n//@ <!--\n//@@@ hello11\n\"#;\n\npub const HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_MD: &'static str = r#\"# Hello World\n\n```rust\nHi\n```\n[hello12]: https://play.rust-lang.org/?code=Hi&version=nightly\n\nContent\n\"#;\n\npub const HELLO12_LINK_TO_PLAY_MARKDOWN_FOLLOW_RS: &'static str = r#\"//@ # Hello World\n\nHi\n//@@@ hello12\n\n//@ Content\n\"#;\n"
  },
  {
    "path": "src/timestamp.rs",
    "content": "use filetime::{self, FileTime};\n\nuse std::cmp::{self, PartialEq, PartialOrd};\nuse std::fs;\nuse std::io;\nuse std::path::Path;\n\npub trait Timestamped {\n    fn timestamp(&self) -> Timestamp;\n}\n\n#[derive(Copy, Clone, PartialEq, Eq, Ord, Debug)]\npub struct Timestamp { pub secs: u64, pub nsecs: u64 }\n\n#[allow(non_snake_case)]\npub fn Timestamp(ms: u64) -> Timestamp  {\n    Timestamp::new(ms / 1_000, (ms % 1_000) * 1_000_000)\n}\n\nimpl Timestamp {\n    pub fn new(secs: u64, ns: u64) -> Timestamp {\n        Timestamp { secs: secs, nsecs: ns }\n    }\n    pub fn to_filetime(&self) -> FileTime {\n        assert!(self.nsecs < ::std::u32::MAX as u64);\n        FileTime::from_seconds_since_1970(self.secs, self.nsecs as u32)\n    }\n    pub fn to_ms(&self) -> u64 {\n        self.secs * 1000 + self.nsecs / 1_000_000\n    }\n    pub fn set_file_times<P: AsRef<Path>>(&self, p: P) -> io::Result<()> {\n        let t = self.to_filetime();\n        filetime::set_file_times(p, t, t)\n    }\n    pub fn date_fulltime_badly(&self) -> String {\n        // TODO: throw away this function if/when something like Joda\n        // time is available as a Rust crate.\n\n        // (Seconds since January 1, 1970).\n        let mut remain = self.to_filetime().seconds_relative_to_1970();\n\n        let mut year = None;\n        for y in 1970.. {\n            let secs_per_year = secs_per_year(y);\n            if remain > secs_per_year {\n                remain -= secs_per_year;\n            } else {\n                year = Some(y);\n                break;\n            }\n        }\n        let year = year.unwrap();\n\n        let mut month = None;\n        for i in 0..12 {\n            let secs_per_month = if is_leap_year(year) {\n                SECS_PER_DAY * DAYS_PER_MONTH_IN_LEAP[i]\n            } else {\n                SECS_PER_DAY * DAYS_PER_MONTH_IN_COMMON[i]\n            };\n            if remain > secs_per_month {\n                remain -= secs_per_month;\n            } else {\n                month = Some(i+1); // We count months starting from 1 ...\n                break;\n            }\n        }\n        let month = month.unwrap();\n\n        let day = remain / SECS_PER_DAY + 1; // ... and we count days starting from 1\n        let remain = remain % SECS_PER_DAY;\n\n        let hour = remain / SECS_PER_HOUR; // ... but we count hours from zero (military time)\n        let remain = remain % SECS_PER_HOUR;\n\n        let min = remain / SECS_PER_MIN; // ... and likewise count minutes from zero\n        let remain = remain % SECS_PER_MIN;\n\n        let sec = remain; // ... and likewise count seconds from zero\n        let nsec = self.nsecs; // ... et cetera.\n\n        format!(\"{YEAR:04}-{MONTH:02}-{DAY:02} {HOUR:02}:{MIN:02}:{SEC:02}.{NSEC} (GMT)\",\n                YEAR=year, MONTH=month, DAY=day, HOUR=hour, MIN=min, SEC=sec, NSEC=nsec)\n    }\n}\n\nfn is_leap_year(gregorian_year: u64) -> bool {\n    let year = gregorian_year;\n    if !(year % 4 == 0) {\n        false\n    } else if !(year % 100 == 0) {\n        true\n    } else if !(year % 400 == 0) {\n        false\n    } else {\n        true\n    }\n}\n\nfn secs_per_year(gregorian_year: u64) -> u64 {\n    if is_leap_year(gregorian_year) {\n        SECS_PER_LEAP_YEAR\n    } else {\n        SECS_PER_COMMON_YEAR\n    }\n}\n\nconst SECS_PER_LEAP_YEAR: u64 = 366 * SECS_PER_DAY;\nconst SECS_PER_COMMON_YEAR: u64 = 365 * SECS_PER_DAY;\nconst DAYS_PER_MONTH_IN_LEAP: [u64; 12] = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst DAYS_PER_MONTH_IN_COMMON: [u64; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];\nconst SECS_PER_DAY: u64 = 24 * SECS_PER_HOUR;\nconst SECS_PER_HOUR: u64 = 60 * SECS_PER_MIN;\nconst SECS_PER_MIN: u64 = 60;\n\nimpl PartialEq<u64> for Timestamp {\n    fn eq(&self, other: &u64) -> bool {\n        self.to_ms().eq(other)\n    }\n}\n\nimpl PartialEq<i64> for Timestamp {\n    fn eq(&self, other: &i64) -> bool {\n        if *other < 0 {\n            false\n        } else {\n            let other = *other as u64;\n            self.to_ms().eq(&other)\n        }\n    }\n}\n\nimpl PartialOrd<u64> for Timestamp {\n    fn partial_cmp(&self, other: &u64) -> Option<cmp::Ordering> {\n        self.to_ms().partial_cmp(other)\n    }\n}\n\nimpl PartialOrd<Timestamp> for Timestamp {\n    fn partial_cmp(&self, other: &Timestamp) -> Option<cmp::Ordering> {\n        match self.secs.partial_cmp(&other.secs) {\n            Some(cmp::Ordering::Equal) => self.nsecs.partial_cmp(&other.nsecs),\n            otherwise => otherwise,\n        }\n    }\n}\n\nimpl Timestamped for fs::Metadata {\n    fn timestamp(&self) -> Timestamp {\n        let ft = FileTime::from_last_modification_time( self );\n        let s = ft.seconds_relative_to_1970();\n        let ns = ft.nanoseconds();\n        // println!(\"metadata mtime: {} ns: {}\", s, ns);\n        Timestamp::new(s as u64, ns as u64)\n    }\n}\n"
  },
  {
    "path": "tests/runner.rs",
    "content": "#![feature(test)]\n\nextern crate tango;\n\nextern crate tempdir;\nextern crate test;\nextern crate walkdir;\n\nuse tango::timestamp::{Timestamp, Timestamped};\n\nuse tempdir::TempDir;\nuse walkdir::{WalkDir};\n\nuse std::cell::RefCell;\nuse std::convert;\nuse std::env;\nuse std::error::Error;\nuse std::fmt;\nuse std::fs::{self, File};\nuse std::io::{self, Read, Write};\nuse std::path::{PathBuf};\nuse std::process::{Command};\n\nconst BINARY_FILENAME: &'static str = \"tango\";\nconst PRESERVE_TEMP_DIRS: bool = false;\nconst REPORT_DIR_CONTENTS: bool = false;\n\nconst REJECT_IF_TANGO_AFFECTS_STD_PORTS: bool = false;\n\nfn out_path() -> PathBuf {\n    let out_dir = env::var(\"OUT_DIR\").unwrap_or_else(|_| {\n        panic!(\"tango tests expect `cargo` to set OUT_DIR; \\\n                now it does not? Fix me.\");\n    });\n    PathBuf::from(&out_dir)\n}\n\nfn infer_target_dir() -> PathBuf {\n    let out_path = out_path();\n\n    let mut target_components = out_path.components().rev();\n    let mut result = PathBuf::new();\n    while let Some(next) = target_components.next() {\n        if next.as_os_str() == \"build\" {\n            for comp in target_components.rev() {\n                result.push(comp.as_os_str());\n            }\n            break;\n        }\n    }\n\n    return result;\n}\n\nfn infer_target_binary() -> PathBuf {\n    let mut dir = infer_target_dir();\n    dir.push(BINARY_FILENAME);\n    dir\n}\n\nthread_local!(static CURRENT_DIR_PREFIX: RefCell<PathBuf> = RefCell::new(PathBuf::new()));\n\nfn within_temp_dir<F, X>(name: &str, f: F) -> X where F: FnOnce() -> X {\n    let out_path = out_path();\n    let mut errors = vec![];\n\n    if !out_path.as_path().exists() {\n        let mut fail_count = 0;\n\n        while let Err(e) = fs::create_dir_all(&out_path) {\n            fail_count += 1;\n            if fail_count > 100 {\n                panic!(\"failure to create output directory at {:?} due to {}\",\n                       &out_path, e);\n            } else {\n                errors.push((e, &out_path));\n            }\n        }\n    }\n\n    if errors.len() > 0 {\n        println!(\"FYI encountered transient errors {:?} during out_path creation.\",\n                 errors);\n    }\n\n\n    let temp_dir = TempDir::new_in(&out_path, name)\n        .unwrap_or_else(|e| {\n            panic!(\"failure to create temp dir in {:?}: {}\", out_path, e);\n        });\n\n    let result = CURRENT_DIR_PREFIX.with(|prefix| {\n        *prefix.borrow_mut() = temp_dir.path().to_path_buf();\n        f()\n    });\n\n    if PRESERVE_TEMP_DIRS {\n        std::mem::forget(temp_dir);\n    } else {\n        match temp_dir.close() {\n            Ok(()) => {}\n            Err(e) => {\n                println!(\"Error cleaning up temp dir {:?}\", e);\n            }\n        }\n    }\n\n    result\n}\n\nfn indent_at_newline(s: &str) -> String {\n    let mut r = String::with_capacity(s.len());\n    for c in s.chars() {\n        r.push(c);\n        if c == '\\n' {\n            r.push_str(\"    \");\n        }\n    }\n    r\n}\n\ntrait UnwrapOrPanic { type X; fn unwrap_or_panic(self, msg: &str) -> Self::X; }\nimpl<X, Y:Error> UnwrapOrPanic for Result<X, Y> {\n    type X = X;\n    fn unwrap_or_panic(self, s: &str) -> X {\n        self.unwrap_or_else(|e| {\n            panic!(\"{} due to {}\", s, indent_at_newline(&e.to_string()));\n        })\n    }\n}\n\nfn setup_src_and_lit_dirs() {\n    CURRENT_DIR_PREFIX.with(|p| {\n        let p = p.borrow_mut();\n        let mut p_src = p.clone();\n\tlet src_dir = &tango::get_src_dir();\n\tlet lit_dir = &tango::get_lit_dir();\n        p_src.push(src_dir);\n        fs::create_dir(p_src).unwrap_or_panic(&format!(\"failed to create {}\", src_dir));\n        if lit_dir == src_dir { return; }\n        let mut p_lit = p.clone();\n        p_lit.push(lit_dir);\n        fs::create_dir(p_lit).unwrap_or_panic(&format!(\"failed to create {}\", lit_dir));\n    })\n}\n\nenum Target { Root, Src, Lit }\n\nimpl Target {\n    fn path_buf(&self, filename: &str) -> PathBuf {\n        CURRENT_DIR_PREFIX.with(|p| {\n            let p = p.borrow_mut();\n            let mut p = p.clone();\n            let src_dir = tango::get_src_dir();\n            let lit_dir = tango::get_lit_dir();\n            match *self {\n                Target::Root => {}\n                Target::Src => p.push(src_dir),\n                Target::Lit => p.push(lit_dir),\n            }\n            p.push(filename);\n            p\n        })\n    }\n}\n\nfn create_file(t: Target, filename: &str, content: &str, timestamp: Timestamp) -> io::Result<()> {\n    let p = t.path_buf(filename);\n    let p = p.as_path();\n    assert!(!p.exists(), \"path {:?} should not exist\", p);\n    let mut f = (File::create(p))?;\n    (write!(f, \"{}\", content))?;\n    (f.flush())?;\n    drop(f);\n    assert!(p.exists(), \"path {:?} must now exist\", p);\n    assert!(timestamp > 0);\n    timestamp.set_file_times(p)\n}\n\nfn touch_file(t: Target, filename: &str, timestamp: Timestamp) -> Result<(), TangoRunError> {\n    let p = t.path_buf(filename);\n    let p = p.as_path();\n    assert!(p.exists(), \"path {:?} should exist\", p);\n    match () {\n        #[cfg(not(unix))]\n        () => {}\n        #[cfg(unix)]\n        () => {\n            use std::os::unix::fs::MetadataExt;\n            println!(\"touch path {} t {:?}  pre: {} \", p.display(), timestamp,\n                     (p.metadata())?.mtime());\n        }\n    }\n    assert!(timestamp > 0);\n    let ret = timestamp.set_file_times(p).map_err(TangoRunError::IoError);\n    let p = t.path_buf(filename);\n    let p = p.as_path();\n    // let f = (File::open(p))?;\n    // try!(f.sync_all());\n    match () {\n        #[cfg(not(unix))]\n        () => {}\n        #[cfg(unix)]\n        () => {\n            use std::os::unix::fs::MetadataExt;\n            println!(\"touch path {} t {:?} post: {} \", p.display(), timestamp,\n                     (p.metadata())?.mtime());\n        }\n    }\n    ret\n}\n\nconst HELLO_WORLD_RS: &'static str = \"\nfn main() { println!(\\\"Hello World\\\"); }\n\";\n\nconst HELLO_WORLD_MD: &'static str = \"\n```rust\nfn main() { println!(\\\"Hello World\\\"); }\n```\n\";\n\nconst HELLO_WORLD2_RS: &'static str = \"\nfn main() { println!(\\\"Hello World 2\\\"); }\n\";\n\nconst HELLO_WORLD2_MD: &'static str = \"\n```rust\nfn main() { println!(\\\"Hello World 2\\\"); }\n```\n\";\n\n// work-around for lack of stable const fn.\nmacro_rules! timestamp {\n    ($ms:expr) => {\n        Timestamp { secs: $ms / 1_000,\n                    nsecs: ($ms % 1_000) * 1_000_000 }\n    }\n}\n\n#[allow(dead_code)] const TIME_A1: Timestamp = timestamp!(1000_000_000);\n#[allow(dead_code)] const TIME_A2: Timestamp = timestamp!(1000_100_000);\n#[allow(dead_code)] const TIME_A3: Timestamp = timestamp!(1000_200_000);\n#[allow(dead_code)] const TIME_B1: Timestamp = timestamp!(2000_000_000);\n#[allow(dead_code)] const TIME_B2: Timestamp = timestamp!(2000_100_000);\n#[allow(dead_code)] const TIME_B3: Timestamp = timestamp!(2000_200_000);\n#[allow(dead_code)] const TIME_C1: Timestamp = timestamp!(3000_000_000);\n#[allow(dead_code)] const TIME_C2: Timestamp = timestamp!(3000_100_000);\n#[allow(dead_code)] const TIME_C3: Timestamp = timestamp!(3000_200_000);\n\n#[derive(Debug)]\nenum TangoRunError {\n    IoError(io::Error),\n    SawOutput { stdout_len: usize, stderr_len: usize,\n                stdout: String, stderr: String, combined: String },\n}\n\nimpl fmt::Display for TangoRunError {\n    fn fmt(&self, w: &mut fmt::Formatter) -> fmt::Result {\n        match *self {\n            TangoRunError::IoError(_) =>\n                write!(w, \"IO error running `tango`\"),\n            TangoRunError::SawOutput {\n                stdout_len, stderr_len, stdout: ref o, stderr: ref e, combined: ref c\n            } =>\n                match (stdout_len > 0, stderr_len > 0) {\n                    (true, true) => write!(w, \"{}\", c),\n                    (true, false) => write!(w, \"{}\", o),\n                    (false, true) => write!(w, \"{}\", e),\n                    (false, false) => panic!(\"did not SawOutput\"),\n                }\n        }\n    }\n}\n\nimpl Error for TangoRunError  { }\n\nimpl convert::From<io::Error> for TangoRunError {\n    fn from(e: io::Error) -> Self {\n        TangoRunError::IoError(e)\n    }\n}\n\nfn run_tango() -> Result<(), TangoRunError> {\n    CURRENT_DIR_PREFIX.with(|p| -> Result<(), TangoRunError> {\n        let p = p.borrow_mut();\n        let result = infer_target_binary();\n        // println!(\"result {:?}\", result);\n        let output = match Command::new(result)\n            .current_dir(&*p)\n            .output() {\n                Ok(o) => o,\n                Err(e) => return Err(TangoRunError::IoError(e)),\n            };\n        let stdout = String::from_utf8_lossy(&output.stdout);\n        let stderr = String::from_utf8_lossy(&output.stderr);\n        if REJECT_IF_TANGO_AFFECTS_STD_PORTS &&\n            stdout.len() > 0 || stderr.len() > 0\n        {\n            return Err(TangoRunError::SawOutput {\n                stdout_len: stdout.len(),\n                stderr_len: stderr.len(),\n                stdout: format!(\"output on stdout: `{}`\", stdout),\n                stderr: format!(\"output on stderr: `{}`\", stderr),\n                combined: format!(\"output on stderr: `{err}`, stdout: `{out}`\",\n                                  err=stderr, out=stdout),\n            });\n        } else {\n            for line in stdout.lines() {\n                println!(\"stdout: {}\", line);\n            }\n            for line in stderr.lines() {\n                println!(\"stderr: {}\", line);\n            }\n        }\n        Ok(())\n    })\n}\n\nfn report_dir_contents(prefix: &str) {\n    if !REPORT_DIR_CONTENTS { return; }\n    CURRENT_DIR_PREFIX.with(|p| {\n        let p = p.borrow_mut();\n        for (i, ent) in WalkDir::new(&*p).into_iter()\n            .enumerate()\n        {\n            match ent {\n                Ok(ent) => {\n                    // println!(\"entry[{}]: {:?}\", i, ent.file_name());\n                    println!(\"{} entry[{}]: {:?}\",\n                             prefix, i, ent.path());\n                    match ent.metadata() {\n                        Err(e) => {\n                            println!(\"{} failed to extract metadata for {:?} due to {:?}\",\n                                     prefix, ent.file_name(), e);\n                        }\n                        Ok(m) => {\n                            // println!(\"{} entry[{}] metadata accessed: {:?}\",\n                            //          prefix, i, m.accessed());\n                            println!(\"{} entry[{}] metadata modified: {:?}\",\n                                     prefix, i, m.modified().unwrap());\n                        }\n                    }\n                }\n                Err(e) => {\n                    println!(\"{} entry[{}]: error due to {:?}\",\n                             prefix, i, e);\n                }\n            }\n        }\n    })\n}\n\nstruct Test<SETUP, PRE, RUN, POST> {\n    name: &'static str,\n    setup: SETUP,\n    pre: PRE,\n    run: RUN,\n    post: POST,\n}\n\nfn framework<S, PR, RUN, PO>(test: Test<S, PR, RUN, PO>) -> Result<(), TangoRunError> where\n    S: FnOnce() -> Result<(), TangoRunError>,\n   PR: FnOnce() -> Result<(), TangoRunError>,\n  RUN: FnOnce() -> Result<(), TangoRunError>,\n   PO: FnOnce() -> Result<(), TangoRunError>,\n{\n    within_temp_dir(test.name, move || -> Result<(), TangoRunError> {\n        let Test { name: _, setup, pre, run, post } = test;\n        println!(\"Setup test\");\n        setup_src_and_lit_dirs();\n        (setup())?;\n\n        report_dir_contents(\"before\");\n        println!(\"Check pre-conditions\");\n        (pre())?;\n\n        println!(\"Run the action\");\n        (run())?;\n\n        report_dir_contents(\"after\");\n        println!(\"Check post-conditions\");\n        (post())?;\n\n        Ok(())\n    })\n}\n\n//@ ## Test Matrix\n//@\n//@ We use a kernel of five files to model filesystem timestamp-based\n//@ actions: `{ STAMP, MD1, MD2, RS1, RS2 }`, where the filename for\n//@ `MDi` corresponds to the filename for `RSi`.\n//@\n//@ First, we consider every subset of the kernel. Then, since\n//@ generally all that matters is the ordering (and not the values) of\n//@ the modification timestamps, we then enumerate the permutations its\n//@ set-partitions. These orderings correspond to the orderings of the\n//@ modification timestamps.\n//@\n//@ So, for example, for the subset `{ MD1, MD2, RS1 }`, the\n//@ set-partitions are:\n//@\n//@ ```\n//@ { MD1 }{ MD2 }{ RS1 };\n//@ { MD1 MD2 }{ RS1 }; { MD1 RS1 }{ MD2 }; { MD2 RS1 }{ MD1 };\n//@ { MD1 MD2 RS1 }\n//@ ```\n//@\n//@ and then extending those to the full set of permutations adds in\n//@ the additional elements:\n//@\n//@ ```\n//@ { MD1 }{ RS1 }{ MD2 }; { MD2 }{ MD1 }{ RS1 }; { MD2 }{ RS1 }{ MD1 };\n//@ { RS1 }{ MD2 }{ MD1 }; { RS1 }{ MD1 }{ MD2 };\n//@ { RS1 }{ MD1 MD2 }; { MD2 }{ MD1 RS1 }; { MD1 }{ MD2 RS1 };\n//@ ```\n//@\n//@ Interpretation: A test case basis such as `{ MD1 RS1 }{ MD2 }`\n//@ represents the case where `MD1` and `RS1` have the same timestamp,\n//@ and `MD2` has a distinct, newer timestamp.\n\n#[test]\nfn unstamped_and_src_without_lit() {\n    framework(Test {\n        name: \"unstamped_and_src_without_lit\",\n        setup: || {\n            (create_file(Target::Src, \"foo.rs\", HELLO_WORLD_RS, TIME_B1))?;\n            Ok(())\n        },\n        // Check pre-conditions\n        pre: || {\n            assert!(!Target::Lit.path_buf(\"foo.md\").exists());\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Root.path_buf(tango::STAMP).exists());\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            // TODO: check contents\n            // TODO: check timestamps\n            Ok(())\n        },\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn unstamped_and_lit_without_src() {\n    framework(Test {\n        name: \"unstamped_and_lit_without_src\",\n        setup: || {\n            (create_file(Target::Lit, \"foo.md\", HELLO_WORLD_MD, TIME_B1))?;\n            Ok(())\n        },\n        // Check pre-conditions\n        pre: || {\n            assert!(!Target::Src.path_buf(\"foo.rs\").exists());\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Root.path_buf(tango::STAMP).exists());\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            // TODO: check contents\n            // TODO: check timestamps\n            Ok(())\n        },\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn stamp_and_src_without_lit() {\n    framework(Test {\n        name: \"stamp_and_src_without_lit\",\n        setup: || {\n            (create_file(Target::Root, tango::STAMP, \"\", TIME_A1))?;\n            (create_file(Target::Src, \"foo.rs\", HELLO_WORLD_RS, TIME_B1))?;\n            Ok(())\n        },\n        // Check pre-conditions\n        pre: || {\n            assert!(!Target::Lit.path_buf(\"foo.md\").exists());\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Root.path_buf(tango::STAMP).exists());\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            // TODO: check contents\n            // TODO: check timestamps\n            Ok(())\n        },\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn stamp_and_lit_without_src() {\n    framework(Test {\n        name: \"stamp_and_lit_without_src\",\n        setup: || {\n            (create_file(Target::Root, tango::STAMP, \"\", TIME_A1))?;\n            (create_file(Target::Lit, \"foo.md\", HELLO_WORLD_MD, TIME_B1))?;\n            Ok(())\n        },\n        pre: || {\n            assert!(!Target::Src.path_buf(\"foo.rs\").exists());\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Root.path_buf(tango::STAMP).exists());\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            // TODO: check contents\n            // TODO: check timestamps\n            Ok(())\n        },\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn stamped_then_touch_lit() {\n    framework(Test {\n        name: \"stamped_then_touch_lit\",\n        setup: || {\n            (create_file(Target::Lit, \"foo.md\", HELLO_WORLD_MD, TIME_B1))?;\n            assert!(!Target::Src.path_buf(\"foo.rs\").exists());\n            (run_tango())?;\n            touch_file(Target::Lit, \"foo.md\", TIME_B2)\n        },\n        pre: || {\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            let rs_t = (Target::Src.path_buf(\"foo.rs\").metadata())?.timestamp();\n            let md_t = (Target::Lit.path_buf(\"foo.md\").metadata())?.timestamp();\n            assert!(TIME_B1 == rs_t, \"rs_t: {:?} TIME_B1: {:?}\", rs_t, TIME_B1);\n            assert!(TIME_B2 == md_t, \"md_t: {:?} TIME_B2: {:?}\", md_t, TIME_B2);\n            assert!(TIME_B2 > TIME_B1);\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            let rs_t = (Target::Src.path_buf(\"foo.rs\").metadata())?.timestamp();\n            let md_t = (Target::Lit.path_buf(\"foo.md\").metadata())?.timestamp();\n            assert!(TIME_B2 == rs_t, \"rs_t: {:?} TIME_B2: {:?}\", rs_t, TIME_B2);\n            assert!(TIME_B2 == md_t, \"md_t: {:?} TIME_B2: {:?}\", md_t, TIME_B2);\n            // TODO: check contents\n            Ok(())\n        }\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn stamped_then_touch_src() {\n    framework(Test {\n        name: \"stamped_then_touch_src\",\n        setup: || {\n            (create_file(Target::Src, \"foo.rs\", HELLO_WORLD_RS, TIME_B1))?;\n            assert!(!Target::Lit.path_buf(\"foo.md\").exists());\n            (run_tango())?;\n            touch_file(Target::Src, \"foo.rs\", TIME_B2)\n        },\n        pre: || {\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            println!(\"try rs_t\");\n            let rs_t = (Target::Src.path_buf(\"foo.rs\").metadata())?.timestamp();\n            println!(\"try md_t\");\n            let md_t = (Target::Lit.path_buf(\"foo.md\").metadata())?.timestamp();\n            assert!(TIME_B1 == md_t, \"md_t: {:?} TIME_B1: {:?}\", md_t, TIME_B1);\n            assert!(TIME_B2 == rs_t, \"rs_t: {:?} TIME_B2: {:?}\", rs_t, TIME_B2);\n            assert!(TIME_B2 > TIME_B1);\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            assert!(Target::Lit.path_buf(\"foo.md\").exists());\n            assert!(Target::Src.path_buf(\"foo.rs\").exists());\n            let rs_t = (Target::Src.path_buf(\"foo.rs\").metadata())?.timestamp();\n            let md_t = (Target::Lit.path_buf(\"foo.md\").metadata())?.timestamp();\n            assert!(TIME_B2 == rs_t, \"rs_t: {:?} TIME_B2: {:?}\", rs_t, TIME_B2);\n            assert!(TIME_B2 == md_t, \"md_t: {:?} TIME_B2: {:?}\", md_t, TIME_B2);\n            // TODO: check contents\n            Ok(())\n        }\n    }).unwrap_or_panic(\"test error\")\n}\n\n#[test]\nfn stamped_then_update_src() {\n    framework(Test {\n        name: \"stamped_then_update_src\",\n        setup: || {\n            let rs_path = &Target::Src.path_buf(\"foo.rs\");\n            let md_path = &Target::Lit.path_buf(\"foo.md\");\n            assert!(!md_path.exists());\n            (create_file(Target::Lit, \"foo.md\", HELLO_WORLD_MD, TIME_B1))?;\n            assert!(!rs_path.exists());\n            (run_tango())?;\n            assert!(rs_path.exists());\n            let mut f = (File::create(rs_path))?;\n            (write!(f, \"{}\", HELLO_WORLD2_RS))?;\n            (f.flush())?;\n            drop(f);\n            touch_file(Target::Src, \"foo.rs\", TIME_B2)\n        },\n        pre: || {\n            let rs_path = &Target::Src.path_buf(\"foo.rs\");\n            let md_path = &Target::Lit.path_buf(\"foo.md\");\n            assert!(rs_path.exists());\n            assert!(md_path.exists());\n            let rs_t = (rs_path.metadata())?.timestamp();\n            let md_t = (md_path.metadata())?.timestamp();\n            assert!(TIME_B1 == md_t, \"md_t: {:?} TIME_B1: {:?}\", md_t, TIME_B1);\n            assert!(TIME_B2 == rs_t, \"rs_t: {:?} TIME_B2: {:?}\", rs_t, TIME_B2);\n            assert!(TIME_B2 > TIME_B1);\n            Ok(())\n        },\n        run: run_tango,\n        post: || {\n            let rs_path = &Target::Src.path_buf(\"foo.rs\");\n            let md_path = &Target::Lit.path_buf(\"foo.md\");\n            assert!(md_path.exists());\n            assert!(rs_path.exists());\n            let rs_t = (rs_path.metadata())?.timestamp();\n            let md_t = (md_path.metadata())?.timestamp();\n            assert!(TIME_B2 == rs_t, \"rs_t: {:?} TIME_B2: {:?}\", rs_t, TIME_B2);\n            assert!(TIME_B2 == md_t, \"md_t: {:?} TIME_B2: {:?}\", md_t, TIME_B2);\n            let mut f = (File::open(md_path))?;\n            let mut s = String::new();\n            (f.read_to_string(&mut s))?;\n            assert!(s == HELLO_WORLD2_MD);\n            Ok(())\n        }\n    }).unwrap_or_panic(\"test error\")\n}\n"
  }
]