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