tsync/
lib.rs

1mod to_typescript;
2mod typescript;
3pub mod utils;
4
5use state::InitCell;
6use std::ffi::OsStr;
7use std::fs::File;
8use std::io::{BufRead, BufReader};
9use std::path::{Path, PathBuf};
10use walkdir::{DirEntry, WalkDir};
11
12/// the #[tsync] attribute macro which marks structs and types to be translated into the final typescript definitions file
13pub use tsync_macro::tsync;
14
15use crate::to_typescript::ToTypescript;
16
17pub(crate) static DEBUG: InitCell<bool> = InitCell::new();
18
19/// macro to check from an syn::Item most of them have ident attribs
20/// that is the one we want to print but not sure!
21macro_rules! check_tsync {
22    ($x: ident, in: $y: tt, $z: tt) => {
23        let has_tsync_attribute = has_tsync_attribute(&$x.attrs);
24        if *DEBUG.get() {
25            if has_tsync_attribute {
26                println!("Encountered #[tsync] {}: {}", $y, $x.ident.to_string());
27            } else {
28                println!("Encountered non-tsync {}: {}", $y, $x.ident.to_string());
29            }
30        }
31
32        if has_tsync_attribute {
33            $z
34        }
35    };
36}
37
38#[derive(Default)]
39pub struct BuildState /*<'a>*/ {
40    pub types: String,
41    pub unprocessed_files: Vec<PathBuf>,
42    // pub ignore_file_config: Option<gitignore::File<'a>>,
43}
44
45/// Settings for the build process
46#[derive(Default)]
47pub struct BuildSettings {
48    pub uses_type_interface: bool,
49    pub enable_const_enums: bool,
50}
51
52// fn should_ignore_file(ignore_file: &gitignore::File, entry: &DirEntry) -> bool {
53//     let path = entry.path();
54
55//     ignore_file.is_excluded(&path).unwrap_or(false)
56// }
57
58fn has_tsync_attribute(attributes: &[syn::Attribute]) -> bool {
59    utils::has_attribute("tsync", attributes)
60}
61
62impl BuildState {
63    fn write_comments(&mut self, comments: &Vec<String>, indentation_amount: i8) {
64        let indentation = utils::build_indentation(indentation_amount);
65        match comments.len() {
66            0 => (),
67            1 => {
68                self.types
69                    .push_str(&format!("{}/** {} */\n", indentation, &comments[0]))
70            }
71            _ => {
72                self.types
73                    .push_str(&format!("{}/**\n", indentation));
74                for comment in comments {
75                    self.types
76                        .push_str(&format!("{} * {}\n", indentation, &comment))
77                }
78                self.types
79                    .push_str(&format!("{} */\n", indentation))
80            }
81        }
82    }
83}
84
85fn process_rust_item(item: syn::Item, state: &mut BuildState, config: &BuildSettings) {
86    match item {
87        syn::Item::Const(exported_const) => {
88            check_tsync!(exported_const, in: "const", {
89                exported_const.convert_to_ts(state, config);
90            });
91        }
92        syn::Item::Struct(exported_struct) => {
93            check_tsync!(exported_struct, in: "struct", {
94                exported_struct.convert_to_ts(state, config);
95            });
96        }
97        syn::Item::Enum(exported_enum) => {
98            check_tsync!(exported_enum, in: "enum", {
99                exported_enum.convert_to_ts(state, config);
100            });
101        }
102        syn::Item::Type(exported_type) => {
103            check_tsync!(exported_type, in: "type", {
104                exported_type.convert_to_ts(state, config);
105            });
106        }
107        _ => {}
108    }
109}
110
111fn process_rust_file<P: AsRef<Path>>(
112    input_path: P,
113    state: &mut BuildState,
114    config: &BuildSettings,
115) {
116    if *DEBUG.get() {
117        println!("processing rust file: {:?}", input_path.as_ref().to_str());
118    }
119
120    let Ok(src) = std::fs::read_to_string(input_path.as_ref()) else {
121        state.unprocessed_files.push(input_path.as_ref().to_path_buf());
122        return;
123    };
124
125    let Ok(syntax) = syn::parse_file(&src) else {
126        state.unprocessed_files.push(input_path.as_ref().to_path_buf());
127        return;
128    };
129
130    syntax
131        .items
132        .into_iter()
133        .for_each(|item| process_rust_item(item, state, config))
134}
135
136fn check_path<P: AsRef<Path>>(path: P, state: &mut BuildState) -> bool {
137    if !path.as_ref().exists() {
138        if *DEBUG.get() { println!("Path `{:#?}` does not exist", path.as_ref()); }
139        state.unprocessed_files.push(path.as_ref().to_path_buf());
140        return false;
141    }
142
143    true
144}
145
146fn check_extension<P: AsRef<Path>>(ext: &OsStr, path: P) -> bool {
147    if !ext.eq_ignore_ascii_case("rs") {
148        if *DEBUG.get() {
149            println!("Encountered non-rust file `{:#?}`", path.as_ref());
150        }
151        return false
152    }
153
154    true
155}
156
157/// Ensure that the walked entry result is Ok and its path is a file. If not,
158/// return `None`, otherwise return `Some(DirEntry)`.
159fn validate_dir_entry(entry_result: walkdir::Result<DirEntry>, path: &Path) -> Option<DirEntry> {
160    match entry_result {
161        Ok(entry) => {
162            // skip dir files because they're going to be recursively crawled by WalkDir
163            if entry.path().is_dir() {
164                if *DEBUG.get() {
165                    println!("Encountered directory `{}`", path.display());
166                }
167                return None;
168            }
169
170            Some(entry)
171        }
172        Err(e) => {
173            println!("An error occurred whilst walking directory `{}`...", path.display());
174            println!("Details: {e:?}");
175            None
176        }
177    }
178}
179
180fn process_dir_entry<P: AsRef<Path>>(path: P, state: &mut BuildState, config: &BuildSettings) {
181    WalkDir::new(path.as_ref())
182        .sort_by_file_name()
183        .into_iter()
184        .filter_map(|res| validate_dir_entry(res, path.as_ref()))
185        .for_each(|entry| {
186            // make sure it is a rust file
187            if entry
188                .path()
189                .extension()
190                .is_some_and(|extension| check_extension(extension, path.as_ref()))
191            {
192                process_rust_file(entry.path(), state, config);
193            }
194        })
195}
196
197pub fn generate_typescript_defs(
198    input: Vec<PathBuf>,
199    output: PathBuf,
200    debug: bool,
201    enable_const_enums: bool,
202) {
203    DEBUG.set(debug);
204
205    let uses_type_interface = output
206        .to_str()
207        .map(|x| x.ends_with(".d.ts"))
208        .unwrap_or(true);
209
210    let config = BuildSettings {
211        uses_type_interface,
212        enable_const_enums,
213    };
214
215    let mut state = BuildState::default();
216
217    state
218        .types
219        .push_str("/* This file is generated and managed by tsync */\n");
220
221    input.into_iter().for_each(|path| {
222        if check_path(&path, &mut state) {
223            if path.is_dir() {
224                process_dir_entry(&path, &mut state, &config)
225            } else {
226                process_rust_file(&path, &mut state, &config);
227            }
228        }
229    });
230
231    if debug {
232        println!("======================================");
233        println!("FINAL FILE:");
234        println!("======================================");
235        println!("{}", state.types);
236        println!("======================================");
237        println!("Note: Nothing is written in debug mode");
238        println!("======================================");
239    } else {
240        // Verify that the output file either doesn't exists or has been generated by tsync.
241        if output.exists() {
242            if !output.is_file() {
243                panic!("Specified output path is a directory but must be a file.")
244            }
245            let original_file = File::open(&output).expect("Couldn't open output file");
246            let mut buffer = BufReader::new(original_file);
247
248            let mut first_line = String::new();
249
250            buffer
251                .read_line(&mut first_line)
252                .expect("Unable to read line");
253
254            if first_line.trim() != "/* This file is generated and managed by tsync */" {
255                panic!("Aborting: specified output file exists but doesn't have \"/* This file is generated and managed by tsync */\" as the first line.")
256            }
257        }
258
259        match std::fs::write(&output, state.types.as_bytes()) {
260            Ok(_) => println!("Successfully generated typescript types, see {:#?}", output),
261            Err(_) => println!("Failed to generate types, an error occurred."),
262        }
263    }
264
265    if !state.unprocessed_files.is_empty() {
266        println!("Could not parse the following files:");
267    }
268
269    for unprocessed_file in state.unprocessed_files {
270        println!("• {:#?}", unprocessed_file);
271    }
272}