typeshare_java/
config.rs

1use std::{collections::HashMap, io::Write};
2
3use serde::{Deserialize, Serialize};
4
5use crate::util::indented_writer::IndentedWriter;
6
7#[derive(Debug, Serialize, Deserialize)]
8#[serde(default)]
9pub struct JavaConfig {
10    /// The header comment to prepend to generated files
11    pub header_comment: HeaderComment,
12    /// Name of the Java package
13    pub package: Option<String>,
14    /// The prefix to append to user-defined types
15    pub prefix: Option<String>,
16    /// Conversions from Rust type names to Java type names
17    pub type_mappings: HashMap<String, String>,
18    /// Whether generated Java classes should be wrapped in a namespace class
19    pub namespace_class: bool,
20    /// Output code for a specific serializer. Currently only Gson is supported.
21    pub serializer: JavaSerializerOptions,
22    /// Determines the type and size of indentation.
23    pub indent: IndentOptions,
24}
25
26impl Default for JavaConfig {
27    fn default() -> Self {
28        Self {
29            header_comment: HeaderComment::None,
30            package: None,
31            prefix: None,
32            type_mappings: HashMap::with_capacity(0),
33            namespace_class: true,
34            serializer: JavaSerializerOptions::None,
35            indent: IndentOptions::default(),
36        }
37    }
38}
39
40#[derive(Debug, Serialize, Deserialize)]
41#[serde(tag = "type")]
42pub enum HeaderComment {
43    None,
44    Custom { comment: String },
45    Default,
46}
47
48#[derive(PartialEq, Eq, Debug, Serialize, Deserialize)]
49#[serde(tag = "type")]
50pub enum JavaSerializerOptions {
51    None,
52    Gson,
53}
54
55#[derive(Debug, Serialize, Deserialize)]
56#[serde(tag = "type")]
57pub enum IndentOptions {
58    Tabs { size: usize },
59    Spaces { size: usize },
60}
61
62impl IndentOptions {
63    pub fn char(&self) -> char {
64        match self {
65            Self::Tabs { .. } => '\t',
66            Self::Spaces { .. } => ' ',
67        }
68    }
69
70    pub fn size(&self) -> usize {
71        match self {
72            IndentOptions::Tabs { size } => *size,
73            IndentOptions::Spaces { size } => *size,
74        }
75    }
76
77    pub fn to_indented_writer<'a, W: Write>(&self, w: &'a mut W) -> IndentedWriter<'a, W> {
78        IndentedWriter::new(w, self.char(), self.size())
79    }
80
81    pub fn indent_whitespace(&self, indent: usize) -> String {
82        self.char().to_string().repeat(indent * self.size())
83    }
84
85    pub fn indent<S: AsRef<str>>(&self, line: S, indent: usize) -> String {
86        format!("{}{}", self.indent_whitespace(indent), line.as_ref())
87    }
88
89    pub fn indent_once<S: AsRef<str>>(&self, line: S) -> String {
90        format!("{}{}", self.indent_whitespace(1), line.as_ref())
91    }
92}
93
94impl Default for IndentOptions {
95    fn default() -> Self {
96        Self::Tabs { size: 1 }
97    }
98}