sync_code/lib.rs
1//! Synchronize code blocks between different files.
2//!
3//! It can replace `macros` in certain scenarios.
4//! For example, when your code isn’t duplicated many times but the design is
5//! relatively complex (e.g., involving generics), using `sync-code` instead
6//! of a `macro` will give you much better readability and easier maintenance.
7//! Features like Go-to-definition and intelligent auto-completion also work
8//! properly without using `macros`.
9//!
10//! # Usage
11//! `Cargo.toml`:
12//! ```toml
13//! [build-dependencies]
14//! sync-code = "0.1.0"
15//! ```
16//!
17//! `build.rs`:
18//! ```rust
19//! fn main() {
20//! sync_code::Builder::new()
21//! .add("src/target1.rs", "src/source1.rs")
22//! .add("src/target2.rs", "src/source2.rs")
23//! .sync();
24//! }
25//!
26//! ```
27//!
28//! `your_code.rs`:
29//! ```rust
30//! // $sync block_name
31//!
32//! fn code_you_want_to_sync() {
33//! }
34//!
35//! // $sync end
36//! ```
37
38mod sync;
39
40use std::path::Path;
41use sync::Sync;
42
43pub struct Builder {
44 table: Vec<Sync>,
45}
46
47impl Builder {
48 pub fn new() -> Self {
49 Builder { table: Vec::new() }
50 }
51
52 pub fn add<P: AsRef<Path>>(mut self, file: P, dep_file: P) -> Self {
53 println!("cargo:rerun-if-changed={}", dep_file.as_ref().display());
54 self.table.push(Sync::new(
55 file.as_ref().to_path_buf(),
56 dep_file.as_ref().to_path_buf(),
57 ));
58 self
59 }
60
61 pub fn sync(&mut self) {
62 println!("Start syncing code ... {}", self.table.len());
63 for sync in &self.table {
64 sync.sync();
65 }
66 }
67}