skeptic-0.13.7/.cargo_vcs_info.json0000644000000001450000000000100125660ustar { "git": { "sha1": "e1781de36c45b1fcdd052aee9e9779cc3ce8e4cd" }, "path_in_vcs": "skeptic" }skeptic-0.13.7/Cargo.toml0000644000000024250000000000100105670ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "skeptic" version = "0.13.7" description = "Test your Rust markdown documentation via Cargo" homepage = "https://github.com/budziq/rust-skeptic" documentation = "https://docs.rs/skeptic" readme = "../README.md" keywords = ["markdown", "documentation", "testing"] categories = ["development-tools", "development-tools::testing"] license = "MIT/Apache-2.0" repository = "https://github.com/budziq/rust-skeptic" [dependencies.bytecount] version = "0.6" [dependencies.cargo_metadata] version = "0.14" [dependencies.error-chain] version = "0.12" default-features = false [dependencies.glob] version = "0.3" [dependencies.pulldown-cmark] version = "0.9" default-features = false [dependencies.tempfile] version = "3" [dependencies.walkdir] version = "2.2" [dev-dependencies.unindent] version = "0.1" skeptic-0.13.7/Cargo.toml.orig000064400000000000000000000013020072674642500142710ustar 00000000000000[package] description = "Test your Rust markdown documentation via Cargo" license = "MIT/Apache-2.0" name = "skeptic" version = "0.13.7" readme = "../README.md" repository = "https://github.com/budziq/rust-skeptic" homepage = "https://github.com/budziq/rust-skeptic" documentation = "https://docs.rs/skeptic" keywords = ["markdown", "documentation", "testing"] categories = ["development-tools", "development-tools::testing"] edition = "2018" [dependencies] bytecount = "0.6" cargo_metadata = "0.14" error-chain = { version = "0.12", default-features = false } glob = "0.3" pulldown-cmark = { version = "0.9", default-features = false } tempfile = "3" walkdir = "2.2" [dev-dependencies] unindent = "0.1" skeptic-0.13.7/LICENSE-APACHE000064400000000000000000000251370072674642500133420ustar 00000000000000 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. skeptic-0.13.7/LICENSE-MIT000064400000000000000000000020000072674642500130320ustar 00000000000000Permission 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. skeptic-0.13.7/src/lib.rs000064400000000000000000000347370072674642500133270ustar 00000000000000use std::collections::HashMap; use std::env; use std::fs::File; use std::io::{self, Error as IoError, Read, Write}; use std::mem; use std::path::{Path, PathBuf}; use pulldown_cmark::{CodeBlockKind, Event, HeadingLevel, Parser, Tag}; pub mod rt; #[cfg(test)] mod tests; /// Returns a list of markdown files under a directory. /// /// # Usage /// /// List markdown files of `mdbook` which are under `/book` usually: /// /// ```rust /// extern crate skeptic; /// /// use skeptic::markdown_files_of_directory; /// /// fn main() { /// let _ = markdown_files_of_directory("book/"); /// } /// ``` pub fn markdown_files_of_directory(dir: &str) -> Vec { use glob::{glob_with, MatchOptions}; let opts = MatchOptions { case_sensitive: false, require_literal_separator: false, require_literal_leading_dot: false, }; let mut out = Vec::new(); for path in glob_with(&format!("{}/**/*.md", dir), opts) .expect("Failed to read glob pattern") .filter_map(Result::ok) { out.push(path.to_str().unwrap().into()); } out } /// Generates tests for specified markdown files. /// /// # Usage /// /// Generates doc tests for the specified files. /// /// ```rust,no_run /// extern crate skeptic; /// /// use skeptic::generate_doc_tests; /// /// fn main() { /// generate_doc_tests(&["README.md"]); /// } /// ``` /// /// Or in case you want to add `mdbook` files: /// /// ```rust,no_run /// extern crate skeptic; /// /// use skeptic::*; /// /// fn main() { /// let mut mdbook_files = markdown_files_of_directory("book/"); /// mdbook_files.push("README.md".into()); /// generate_doc_tests(&mdbook_files); /// } /// ``` pub fn generate_doc_tests(docs: &[T]) where T: AsRef, { // This shortcut is specifically so examples in skeptic's on // readme can call this function in non-build.rs contexts, without // panicking below. if docs.is_empty() { return; } let docs = docs .iter() .cloned() .map(|path| path.as_ref().to_str().unwrap().to_owned()) .filter(|d| !d.ends_with(".skt.md")) .collect::>(); // Inform cargo that it needs to rerun the build script if one of the skeptic files are // modified for doc in &docs { println!("cargo:rerun-if-changed={}", doc); let skt = format!("{}.skt.md", doc); if Path::new(&skt).exists() { println!("cargo:rerun-if-changed={}", skt); } } let out_dir = env::var("OUT_DIR").unwrap(); let cargo_manifest_dir = env::var("CARGO_MANIFEST_DIR").unwrap(); let mut out_file = PathBuf::from(out_dir.clone()); out_file.push("skeptic-tests.rs"); let config = Config { out_dir: PathBuf::from(out_dir), root_dir: PathBuf::from(cargo_manifest_dir), out_file, target_triple: env::var("TARGET").expect("could not get target triple"), docs, }; run(&config); } struct Config { out_dir: PathBuf, root_dir: PathBuf, out_file: PathBuf, target_triple: String, docs: Vec, } fn run(config: &Config) { let tests = extract_tests(config).unwrap(); emit_tests(config, tests).unwrap(); } struct Test { name: String, text: Vec, ignore: bool, no_run: bool, should_panic: bool, template: Option, } struct DocTestSuite { doc_tests: Vec, } struct DocTest { path: PathBuf, old_template: Option, tests: Vec, templates: HashMap, } fn extract_tests(config: &Config) -> Result { let mut doc_tests = Vec::new(); for doc in &config.docs { let path = &mut config.root_dir.clone(); path.push(doc); let new_tests = extract_tests_from_file(path)?; doc_tests.push(new_tests); } Ok(DocTestSuite { doc_tests }) } enum Buffer { None, Code(Vec), Heading(String), } fn extract_tests_from_file(path: &Path) -> Result { let mut file = File::open(path)?; let s = &mut String::new(); file.read_to_string(s)?; let file_stem = &sanitize_test_name(path.file_stem().unwrap().to_str().unwrap()); let tests = extract_tests_from_string(s, file_stem); let templates = load_templates(path)?; Ok(DocTest { path: path.to_owned(), old_template: tests.1, tests: tests.0, templates, }) } fn extract_tests_from_string(s: &str, file_stem: &str) -> (Vec, Option) { let mut tests = Vec::new(); let mut buffer = Buffer::None; let parser = Parser::new(s); let mut section = None; let mut code_block_start = 0; // Oh this isn't actually a test but a legacy template let mut old_template = None; for (event, range) in parser.into_offset_iter() { let line_number = bytecount::count(&s.as_bytes()[0..range.start], b'\n'); match event { Event::Start(Tag::Heading(level, ..)) if level < HeadingLevel::H3 => { buffer = Buffer::Heading(String::new()); } Event::End(Tag::Heading(level, ..)) if level < HeadingLevel::H3 => { let cur_buffer = mem::replace(&mut buffer, Buffer::None); if let Buffer::Heading(sect) = cur_buffer { section = Some(sanitize_test_name(§)); } } Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(ref info))) => { let code_block_info = parse_code_block_info(info); if code_block_info.is_rust { buffer = Buffer::Code(Vec::new()); } } Event::Text(text) => { if let Buffer::Code(ref mut buf) = buffer { if buf.is_empty() { code_block_start = line_number; } buf.extend(text.lines().map(|s| format!("{}\n", s))); } else if let Buffer::Heading(ref mut buf) = buffer { buf.push_str(&*text); } } Event::End(Tag::CodeBlock(CodeBlockKind::Fenced(ref info))) => { let code_block_info = parse_code_block_info(info); if let Buffer::Code(buf) = mem::replace(&mut buffer, Buffer::None) { if code_block_info.is_old_template { old_template = Some(buf.into_iter().collect()) } else { let name = if let Some(ref section) = section { format!("{}_sect_{}_line_{}", file_stem, section, code_block_start) } else { format!("{}_line_{}", file_stem, code_block_start) }; tests.push(Test { name, text: buf, ignore: code_block_info.ignore, no_run: code_block_info.no_run, should_panic: code_block_info.should_panic, template: code_block_info.template, }); } } } _ => (), } } (tests, old_template) } fn load_templates(path: &Path) -> Result, IoError> { let file_name = format!( "{}.skt.md", path.file_name().expect("no file name").to_string_lossy() ); let path = path.with_file_name(&file_name); if !path.exists() { return Ok(HashMap::new()); } let mut map = HashMap::new(); let mut file = File::open(path)?; let s = &mut String::new(); file.read_to_string(s)?; let parser = Parser::new(s); let mut code_buffer = None; for event in parser { match event { Event::Start(Tag::CodeBlock(CodeBlockKind::Fenced(ref info))) => { let code_block_info = parse_code_block_info(info); if code_block_info.is_rust { code_buffer = Some(Vec::new()); } } Event::Text(text) => { if let Some(ref mut buf) = code_buffer { buf.push(text.to_string()); } } Event::End(Tag::CodeBlock(CodeBlockKind::Fenced(ref info))) => { let code_block_info = parse_code_block_info(info); if let Some(buf) = code_buffer.take() { if let Some(t) = code_block_info.template { map.insert(t, buf.into_iter().collect()); } } } _ => (), } } Ok(map) } fn sanitize_test_name(s: &str) -> String { s.to_ascii_lowercase() .chars() .map(|ch| { if ch.is_ascii() && ch.is_alphanumeric() { ch } else { '_' } }) .collect::() .split('_') .filter(|s| !s.is_empty()) .collect::>() .join("_") } fn parse_code_block_info(info: &str) -> CodeBlockInfo { // Same as rustdoc let tokens = info.split(|c: char| !(c == '_' || c == '-' || c.is_alphanumeric())); let mut seen_rust_tags = false; let mut seen_other_tags = false; let mut info = CodeBlockInfo { is_rust: false, should_panic: false, ignore: false, no_run: false, is_old_template: false, template: None, }; for token in tokens { match token { "" => {} "rust" => { info.is_rust = true; seen_rust_tags = true } "should_panic" => { info.should_panic = true; seen_rust_tags = true } "ignore" => { info.ignore = true; seen_rust_tags = true } "no_run" => { info.no_run = true; seen_rust_tags = true; } "skeptic-template" => { info.is_old_template = true; seen_rust_tags = true } _ if token.starts_with("skt-") => { info.template = Some(token[4..].to_string()); seen_rust_tags = true; } _ => seen_other_tags = true, } } info.is_rust &= !seen_other_tags || seen_rust_tags; info } struct CodeBlockInfo { is_rust: bool, should_panic: bool, ignore: bool, no_run: bool, is_old_template: bool, template: Option, } fn emit_tests(config: &Config, suite: DocTestSuite) -> Result<(), IoError> { let mut out = String::new(); // Test cases use the api from skeptic::rt out.push_str("extern crate skeptic;\n"); for doc_test in suite.doc_tests { for test in &doc_test.tests { let test_string = { if let Some(ref t) = test.template { let template = doc_test.templates.get(t).unwrap_or_else(|| { panic!("template {} not found for {}", t, doc_test.path.display()) }); create_test_runner(config, &Some(template.to_string()), test)? } else { create_test_runner(config, &doc_test.old_template, test)? } }; out.push_str(&test_string); } } write_if_contents_changed(&config.out_file, &out) } /// Just like Rustdoc, ignore a "#" sign at the beginning of a line of code. /// These are commonly an indication to omit the line from user-facing /// documentation but include it for the purpose of playground links or skeptic /// testing. #[allow(clippy::manual_strip)] // Relies on str::strip_prefix(), MSRV 1.45 fn clean_omitted_line(line: &str) -> &str { // XXX To silence depreciation warning of trim_left and not bump rustc // requirement upto 1.30 (for trim_start) we roll our own trim_left :( let trimmed = if let Some(pos) = line.find(|c: char| !c.is_whitespace()) { &line[pos..] } else { line }; if trimmed.starts_with("# ") { &trimmed[2..] } else if line.trim() == "#" { // line consists of single "#" which might not be followed by newline on windows &trimmed[1..] } else { line } } /// Creates the Rust code that this test will be operating on. fn create_test_input(lines: &[String]) -> String { lines .iter() .map(|s| clean_omitted_line(s).to_owned()) .collect() } fn create_test_runner( config: &Config, template: &Option, test: &Test, ) -> Result { let template = template.clone().unwrap_or_else(|| String::from("{}")); let test_text = create_test_input(&test.text); let mut s: Vec = Vec::new(); if test.ignore { writeln!(s, "#[ignore]")?; } if test.should_panic { writeln!(s, "#[should_panic]")?; } writeln!(s, "#[test] fn {}() {{", test.name)?; writeln!( s, " let s = &format!(r####\"\n{}\"####, r####\"{}\"####);", template, test_text )?; // if we are not running, just compile the test without running it if test.no_run { writeln!( s, " skeptic::rt::compile_test(r#\"{}\"#, r#\"{}\"#, r#\"{}\"#, s);", config.root_dir.to_str().unwrap(), config.out_dir.to_str().unwrap(), config.target_triple )?; } else { writeln!( s, " skeptic::rt::run_test(r#\"{}\"#, r#\"{}\"#, r#\"{}\"#, s);", config.root_dir.to_str().unwrap(), config.out_dir.to_str().unwrap(), config.target_triple )?; } writeln!(s, "}}")?; writeln!(s)?; Ok(String::from_utf8(s).unwrap()) } fn write_if_contents_changed(name: &Path, contents: &str) -> Result<(), IoError> { // Can't open in write mode now as that would modify the last changed timestamp of the file match File::open(name) { Ok(mut file) => { let mut current_contents = String::new(); file.read_to_string(&mut current_contents)?; if current_contents == contents { // No change avoid writing to avoid updating the timestamp of the file return Ok(()); } } Err(ref err) if err.kind() == io::ErrorKind::NotFound => (), Err(err) => return Err(err), } let mut file = File::create(name)?; file.write_all(contents.as_bytes())?; Ok(()) } skeptic-0.13.7/src/rt.rs000064400000000000000000000213610072674642500131730ustar 00000000000000use std::collections::hash_map::Entry; use std::collections::HashMap; use std::env; use std::ffi::OsStr; use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; use std::str::FromStr; use std::time::SystemTime; use error_chain::error_chain; use walkdir::WalkDir; pub fn compile_test(root_dir: &str, out_dir: &str, target_triple: &str, test_text: &str) { handle_test( root_dir, out_dir, target_triple, test_text, CompileType::Check, ); } pub fn run_test(root_dir: &str, out_dir: &str, target_triple: &str, test_text: &str) { handle_test( root_dir, out_dir, target_triple, test_text, CompileType::Full, ); } fn handle_test( root_dir: &str, target_dir: &str, target_triple: &str, test_text: &str, compile_type: CompileType, ) { let out_dir = tempfile::Builder::new() .prefix("rust-skeptic") .tempdir() .unwrap(); let testcase_path = out_dir.path().join("test.rs"); fs::write(&testcase_path, test_text.as_bytes()).unwrap(); // OK, here's where a bunch of magic happens using assumptions // about cargo internals. We are going to use rustc to compile // the examples, but to do that we've got to tell it where to // look for the rlibs with the -L flag, and what their names // are with the --extern flag. This is going to involve // parsing fingerprints out of the lockfile and looking them // up in the fingerprint file. let root_dir = PathBuf::from(root_dir); let mut target_dir = PathBuf::from(target_dir); target_dir.pop(); target_dir.pop(); target_dir.pop(); let mut deps_dir = target_dir.clone(); deps_dir.push("deps"); let rustc = env::var("RUSTC").unwrap_or_else(|_| String::from("rustc")); let mut cmd = Command::new(rustc); cmd.arg(testcase_path) .arg("--verbose") .arg("--crate-type=bin"); // Find the edition // This has to come before "-L". let metadata_path = root_dir.join("Cargo.toml"); let metadata = get_cargo_meta(&metadata_path).expect("failed to read Cargo.toml"); let edition = metadata .packages .iter() .map(|package| &package.edition) .max_by_key(|edition| u64::from_str(edition).unwrap()) .unwrap() .clone(); if edition != "2015" { cmd.arg(format!("--edition={}", edition)); } cmd.arg("-L") .arg(&target_dir) .arg("-L") .arg(&deps_dir) .arg("--target") .arg(&target_triple); for dep in get_rlib_dependencies(root_dir, target_dir).expect("failed to read dependencies") { cmd.arg("--extern"); cmd.arg(format!( "{}={}", dep.libname, dep.rlib.to_str().expect("filename not utf8"), )); } let binary_path = out_dir.path().join("out.exe"); match compile_type { CompileType::Full => cmd.arg("-o").arg(&binary_path), CompileType::Check => cmd.arg(format!( "--emit=dep-info={0}.d,metadata={0}.m", binary_path.display() )), }; interpret_output(cmd); if let CompileType::Check = compile_type { return; } let mut cmd = Command::new(binary_path); cmd.current_dir(out_dir.path()); interpret_output(cmd); } fn interpret_output(mut command: Command) { let output = command.output().unwrap(); print!("{}", String::from_utf8(output.stdout).unwrap()); eprint!("{}", String::from_utf8(output.stderr).unwrap()); if !output.status.success() { panic!("Command failed:\n{:?}", command); } } // Retrieve the exact dependencies for a given build by // cross-referencing the lockfile with the fingerprint file fn get_rlib_dependencies(root_dir: PathBuf, target_dir: PathBuf) -> Result> { let lock = LockedDeps::from_path(root_dir).or_else(|_| { // could not find Cargo.lock in $CARGO_MAINFEST_DIR // try relative to target_dir let mut root_dir = target_dir.clone(); root_dir.pop(); root_dir.pop(); LockedDeps::from_path(root_dir) })?; let fingerprint_dir = target_dir.join(".fingerprint/"); let locked_deps: HashMap = lock.collect(); let mut found_deps: HashMap = HashMap::new(); for finger in WalkDir::new(fingerprint_dir) .into_iter() .filter_map(|v| Fingerprint::from_path(v.ok()?.path()).ok()) { let locked_ver = match locked_deps.get(&finger.name()) { Some(ver) => ver, None => continue, }; // TODO this should be refactored to something more readable match (found_deps.entry(finger.name()), finger.version()) { (Entry::Occupied(mut e), Some(ver)) => { // we find better match only if it is exact version match // and has fresher build time if *locked_ver == ver && e.get().mtime < finger.mtime { e.insert(finger); } } (Entry::Vacant(e), ver) => { // we see an exact match or unversioned version if ver.unwrap_or_else(|| locked_ver.clone()) == *locked_ver { e.insert(finger); } } _ => (), } } Ok(found_deps .into_iter() .filter_map(|(_, val)| if val.rlib.exists() { Some(val) } else { None }) .collect()) } // An iterator over the root dependencies in a lockfile #[derive(Debug)] struct LockedDeps { dependencies: Vec, } fn get_cargo_meta + std::convert::AsRef>( path: P, ) -> Result { Ok(cargo_metadata::MetadataCommand::new() .manifest_path(&path) .exec()?) } impl LockedDeps { fn from_path>(path: P) -> Result { let path = path.as_ref().join("Cargo.toml"); let metadata = get_cargo_meta(&path)?; let workspace_members = metadata.workspace_members; let deps = metadata .resolve .ok_or("Missing dependency metadata")? .nodes .into_iter() .filter(|node| workspace_members.contains(&node.id)) .flat_map(|node| node.dependencies.into_iter()) .chain(workspace_members.clone()); Ok(LockedDeps { dependencies: deps.map(|node| node.repr).collect(), }) } } impl Iterator for LockedDeps { type Item = (String, String); fn next(&mut self) -> Option<(String, String)> { let dep = self.dependencies.pop()?; let mut parts = dep.split_whitespace(); let name = parts.next()?; let val = parts.next()?; Some((name.replace("-", "_"), val.to_owned())) } } #[derive(Debug)] struct Fingerprint { libname: String, version: Option, // version might not be present on path or vcs deps rlib: PathBuf, mtime: SystemTime, } fn guess_ext(mut path: PathBuf, exts: &[&str]) -> Result { for ext in exts { path.set_extension(ext); if path.exists() { return Ok(path); } } Err(ErrorKind::Fingerprint.into()) } impl Fingerprint { fn from_path>(path: P) -> Result { let path = path.as_ref(); // Use the parent path to get libname and hash, replacing - with _ let mut captures = path .parent() .and_then(Path::file_stem) .and_then(OsStr::to_str) .ok_or(ErrorKind::Fingerprint)? .rsplit('-'); let hash = captures.next().ok_or(ErrorKind::Fingerprint)?; let mut libname_parts = captures.collect::>(); libname_parts.reverse(); let libname = libname_parts.join("_"); path.extension() .and_then(|e| if e == "json" { Some(e) } else { None }) .ok_or(ErrorKind::Fingerprint)?; let mut rlib = PathBuf::from(path); rlib.pop(); rlib.pop(); rlib.pop(); let mut dll = rlib.clone(); rlib.push(format!("deps/lib{}-{}", libname, hash)); dll.push(format!("deps/{}-{}", libname, hash)); rlib = guess_ext(rlib, &["rlib", "so", "dylib"]).or_else(|_| guess_ext(dll, &["dll"]))?; Ok(Fingerprint { libname, version: None, rlib, mtime: fs::metadata(path)?.modified()?, }) } fn name(&self) -> String { self.libname.clone() } fn version(&self) -> Option { self.version.clone() } } error_chain! { errors { Fingerprint } foreign_links { Io(std::io::Error); Metadata(cargo_metadata::Error); } } #[derive(Clone, Copy)] enum CompileType { Full, Check, } skeptic-0.13.7/src/tests.rs000064400000000000000000000114430072674642500137100ustar 00000000000000use unindent::unindent; use super::*; #[test] fn test_omitted_lines() { let lines = unindent( r###" # use std::collections::BTreeMap as Map; # #[allow(dead_code)] fn main() { let map = Map::new(); # # let _ = map; }"###, ); let expected = unindent( r###" use std::collections::BTreeMap as Map; #[allow(dead_code)] fn main() { let map = Map::new(); let _ = map; } "###, ); assert_eq!(create_test_input(&get_lines(lines)), expected); } #[test] fn test_markdown_files_of_directory() { let files = vec![ "../testing/tests/hashtag-test.md", "../testing/tests/section-names.md", "../testing/tests/should-panic-test.md", ]; let files: Vec = files.iter().map(PathBuf::from).collect(); assert_eq!(markdown_files_of_directory("../testing/tests/"), files); } #[test] fn test_sanitization_of_testnames() { assert_eq!(sanitize_test_name("My_Fun"), "my_fun"); assert_eq!(sanitize_test_name("__my_fun_"), "my_fun"); assert_eq!(sanitize_test_name("^$@__my@#_fun#$@"), "my_fun"); assert_eq!( sanitize_test_name("my_long__fun___name___with____a_____lot______of_______spaces",), "my_long_fun_name_with_a_lot_of_spaces" ); assert_eq!(sanitize_test_name("Löwe 老虎 Léopard"), "l_we_l_opard"); } #[test] fn line_numbers_displayed_are_for_the_beginning_of_each_code_block() { let lines = unindent( r###" Rust code that should panic when running it. ```rust,should_panic",/ fn main() { panic!(\"I should panic\"); } ``` Rust code that should panic when compiling it. ```rust,no_run,should_panic",// fn add(a: u32, b: u32) -> u32 { a + b } fn main() { add(1); } ```"###, ); let tests = extract_tests_from_string(&create_test_input(&get_lines(lines)), &String::from("blah")); let test_names: Vec = tests .0 .into_iter() .map(get_line_number_from_test_name) .collect(); assert_eq!(test_names, vec!["3", "11"]); } #[test] fn line_numbers_displayed_are_for_the_beginning_of_each_section() { let lines = unindent( r###" ## Test Case Names With weird spacing are generated without error. ```rust", / struct Person<'a>(&'a str); fn main() { let _ = Person(\"bors\"); } ``` ## !@#$ Test Cases )(() with {}[] non alphanumeric characters ^$23 characters are \"`#`\" generated correctly @#$@#$ 22. ```rust", // struct Person<'a>(&'a str); fn main() { let _ = Person(\"bors\"); } ``` ## Test cases with non ASCII ö_老虎_é characters are generated correctly. ```rust",// struct Person<'a>(&'a str); fn main() { let _ = Person(\"bors\"); } ```"###, ); let tests = extract_tests_from_string(&create_test_input(&get_lines(lines)), &String::from("blah")); let test_names: Vec = tests .0 .into_iter() .map(get_line_number_from_test_name) .collect(); assert_eq!(test_names, vec!["3", "12", "21"]); } #[test] fn old_template_is_returned_for_old_skeptic_template_format() { let lines = unindent( r###" ```rust,skeptic-template ```rust,ignore use std::path::PathBuf; fn main() {{ {} }} ``` ``` "###, ); let expected = unindent( r###" ```rust,ignore use std::path::PathBuf; fn main() {{ {} }} "###, ); let tests = extract_tests_from_string(&create_test_input(&get_lines(lines)), &String::from("blah")); assert_eq!(tests.1, Some(expected)); } #[test] fn old_template_is_not_returned_if_old_skeptic_template_is_not_specified() { let lines = unindent( r###" ```rust", / struct Person<'a>(&'a str); fn main() { let _ = Person(\"bors\"); } ``` "###, ); let tests = extract_tests_from_string(&create_test_input(&get_lines(lines)), &String::from("blah")); assert_eq!(tests.1, None); } fn get_line_number_from_test_name(test: Test) -> String { String::from( test.name .split('_') .last() .expect("There were no underscores!"), ) } fn get_lines(lines: String) -> Vec { lines .split('\n') .map(|string_slice| format!("{}\n", string_slice)) //restore line endings since they are removed by split. .collect() }