ploidy_codegen_rust/
lib.rs

1use std::{collections::BTreeMap, path::Path};
2
3use itertools::Itertools;
4use proc_macro2::TokenStream;
5use quote::quote;
6
7use ploidy_core::codegen::{IntoCode, write_to_disk};
8
9mod cargo;
10mod client;
11mod config;
12mod derives;
13mod enum_;
14mod graph;
15mod naming;
16mod operation;
17mod primitive;
18mod ref_;
19mod resource;
20mod schema;
21mod statics;
22mod struct_;
23mod tagged;
24mod types;
25mod untagged;
26
27#[cfg(test)]
28mod tests;
29
30pub use cargo::*;
31pub use client::*;
32pub use config::*;
33pub use graph::*;
34pub use naming::*;
35pub use operation::*;
36pub use primitive::*;
37pub use resource::*;
38pub use schema::*;
39pub use statics::*;
40pub use types::*;
41
42pub fn write_types_to_disk(output: &Path, graph: &CodegenGraph<'_>) -> miette::Result<()> {
43    for view in graph.schemas() {
44        let code = CodegenSchemaType::new(&view).into_code();
45        write_to_disk(output, code)?;
46    }
47
48    write_to_disk(output, CodegenTypesModule::new(graph))?;
49
50    Ok(())
51}
52
53pub fn write_client_to_disk(output: &Path, graph: &CodegenGraph<'_>) -> miette::Result<()> {
54    let by_resource = graph
55        .operations()
56        .fold(BTreeMap::<_, Vec<_>>::new(), |mut map, view| {
57            let resource = view.resource();
58            map.entry(resource).or_default().push(view);
59            map
60        });
61
62    for (resource, operations) in &by_resource {
63        let code = CodegenResource::new(resource, operations);
64        write_to_disk(output, code)?;
65    }
66
67    let resources = by_resource.keys().copied().collect_vec();
68    let mod_code = CodegenClientModule::new(graph, &resources);
69    write_to_disk(output, mod_code)?;
70
71    Ok(())
72}
73
74/// Generates one or more `#[doc]` attributes for a schema description,
75/// wrapping at 80 characters for readability.
76pub fn doc_attrs(description: &str) -> TokenStream {
77    let lines = textwrap::wrap(description, 80)
78        .into_iter()
79        .map(|line| quote!(#[doc = #line]));
80    quote! { #(#lines)* }
81}