protobuf_dbml/transpiler/
config.rs

1use std::{error::Error, ffi::OsString};
2
3use inflector::Inflector;
4
5use super::transpile;
6
7/// Protobuf target version.
8#[derive(Debug, PartialEq, Clone)]
9pub enum Target {
10  Proto3,
11}
12
13/// Configuration options for the code generation.
14#[derive(Debug, PartialEq, Clone)]
15pub struct Config {
16  /// Input file path.
17  pub in_path: OsString,
18  /// Output file path.
19  pub out_path: OsString,
20  /// Protobuf target version.
21  pub target: Target,
22  /// Output package name
23  pub package_name: String,
24  /// A function for transforming the original table name from DBML.
25  /// The default funciton is pascal casing and appending "Schema" to the name.
26  pub table_name_transform_fn: fn(Option<&str>, &str, Option<&str>) -> String,
27  /// A function for transforming the original enum name from DBML.
28  /// The default funciton is pascal casing and appending "Schema" to the name.
29  pub enum_name_transform_fn: fn(Option<&str>, &str) -> String,
30  /// Output update schemas with optional all fields by default, entity's primary key field is omitted.
31  pub is_with_update_schema: bool,
32  /// Ouput create schemas with optional default fields.
33  /// The entity's primary key field is included when it is not being auto generated.
34  pub is_with_create_schema: bool,
35  /// Forcing `is_with_create_schema` wether it should include primary key field or not.
36  pub is_create_schema_primary_key_included: Option<bool>,
37  /// Config `is_with_update_schema` to include primary key field.
38  pub is_update_schema_primary_key_included: bool,
39}
40
41impl Default for Config {
42  fn default() -> Self {
43    Self {
44      in_path: OsString::from(""),
45      out_path: OsString::from(""),
46      target: Target::Proto3,
47      package_name: String::new(),
48      table_name_transform_fn: |_: Option<&str>, name: &str, _: Option<&str>| {
49        format!("{}Schema", name.to_pascal_case())
50      },
51      enum_name_transform_fn: |_: Option<&str>, name: &str| {
52        format!("{}Enum", name.to_pascal_case())
53      },
54      is_with_update_schema: false,
55      is_with_create_schema: false,
56      is_create_schema_primary_key_included: None,
57      is_update_schema_primary_key_included: false,
58    }
59  }
60}
61
62impl Config {
63  pub fn validate(&self) -> Option<&str> {
64    if self.in_path.is_empty() {
65      Some("in_path is not set")
66    } else if self.out_path.is_empty() {
67      Some("out_path is not set")
68    } else {
69      None
70    }
71  }
72
73  pub fn transpile(&self) -> Result<String, Box<dyn Error>> {
74    let sem_ast = dbml_rs::parse_file(&self.in_path)?;
75
76    let result = transpile(sem_ast, &self)?;
77
78    Ok(result)
79  }
80}