-
Notifications
You must be signed in to change notification settings - Fork 82
/
skeptic.rs
100 lines (77 loc) · 2.7 KB
/
skeptic.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
extern crate skeptic;
fn main() {
let mut files = generate_doc_tpl_tests().unwrap();
files.push("README.md".to_string());
let files_ref: Vec<&str> = files.iter().map(|x| x.as_str()).collect();
skeptic::generate_doc_tests(files_ref.as_slice());
}
const DOC_TPL_HEADER: &'static str = r###"
//////////////////////////////////////////////////////////////////
// START of Header
// NOTE:
// - This file is auto-generated by the `build.rs` script.
// - The following skeptic-template is a Rust format specifier,
// so braces are treated specially, and need to be escaped
// with double-braces.
// See: https://github.com/brson/rust-skeptic#skeptic-templates
```rust,skeptic-template
#[macro_use]
extern crate derive_builder;
#[derive(Builder)]
struct Foo {{
#[allow(dead_code)]
default: bool,
}}
fn main() {{
{}
}}
```
// END of Header
//////////////////////////////////////////////////////////////////
"###;
use std::error::Error;
use std::path::Path;
use std::env;
use std::fs::{File, DirBuilder, read_to_string};
use std::io::Write;
const DOC_TPL_DIR: &'static str = "src/doc_tpl/";
const DOC_TPL_OUT_DIR: &'static str = "doc_tpl/";
fn generate_doc_tpl_tests() -> Result<Vec<String>, Box<dyn Error>> {
let tpl_dir = Path::new(&env::var("CARGO_MANIFEST_DIR")?).join(DOC_TPL_DIR);
let out_dir = Path::new(&env::var("OUT_DIR")?).join(DOC_TPL_OUT_DIR);
if !out_dir.is_dir() {
DirBuilder::new().create(&out_dir)?;
}
let docs = tpl_dir.read_dir()
.map_err(|e| format!("Could not open {}: {}.", tpl_dir.display(), e))?;
let mut files = Vec::<String>::new();
for doc in docs {
let path = doc?.path();
if !is_markdown(&path) {
continue;
}
let filename = match path.file_name() {
Some(filename) => filename,
None => continue,
};
let tpl = read_to_string(&path)
.map_err(|e| format!("Cannot read file {}: {}.", path.display(), e))?;
println!("cargo:rerun-if-changed={}", path.display());
let out_file = out_dir.join(filename);
let mut out = File::create(&out_file)
.map_err(|e| format!("Cannot create file {}: {}.", out_file.display(), e))?;
out.write_all(DOC_TPL_HEADER.as_bytes())?;
let tpl = tpl.replace("{struct_name}", "Foo")
.replace("{builder_name}", "FooBuilder")
.replace("{field_name}", "default");
out.write_all(tpl.as_ref())?;
files.push(out_file.to_str()
.ok_or_else(|| "Path must not be empty")?
.to_string()
);
}
Ok(files)
}
fn is_markdown(path: &Path) -> bool {
path.extension().map_or(false, |extension| extension == "md")
}