-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbuild.rs
28 lines (25 loc) · 989 Bytes
/
build.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
use regex::Regex;
use std::env;
use std::fs;
use std::path::Path;
fn main() {
let out_dir = env::var("OUT_DIR").unwrap();
let name = env::var("CARGO_PKG_NAME").unwrap();
let dest_path = Path::new(&out_dir).join("module.rs");
let source = fs::read_to_string("src/lib.rs").unwrap();
let functions = Regex::new(r"#\[pyfunction]\s*(?:\w\s+)*?fn\s+([\w0-9]+)").unwrap();
let structs = Regex::new(r"#\[pyclass]\s*(?:\w\s+)*?(?:struct|enum)\s+([\w0-9]+)").unwrap();
fs::write(dest_path, format!("#[pymodule]
fn {name}(_py: Python, m: &PyModule) -> PyResult<()> {{\n")
+ &functions
.captures_iter(&source)
.map(|f| format!(
"m.add_function(wrap_pyfunction!({}, m)?)?;\n", &f[1]))
.collect::<String>()
+ &structs
.captures_iter(&source)
.map(|s| format!(
"m.add_class::<{}>()?;\n", &s[1]))
.collect::<String>()
+ "Ok(())}").unwrap();
}