Skip to content

Commit

Permalink
Refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
tinrab committed Nov 17, 2023
1 parent 5abcaa0 commit f85e163
Show file tree
Hide file tree
Showing 19 changed files with 235 additions and 202 deletions.
4 changes: 3 additions & 1 deletion .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ jobs:
key: ${{ runner.os }}-cargo-${{ hashFiles('**/Cargo.toml') }}

- name: Lint
run: ./develop.sh lint
run: |
cargo fmt --all -- --check
cargo clippy --workspace --all-targets --all-features -- -D warnings
- name: Test
run: cargo test --workspace --all-targets --all-features
Expand Down
33 changes: 0 additions & 33 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,36 +39,3 @@ bomboni_prost = { path = "bomboni_prost", version = "0.1.5", optional = true }
bomboni_proto = { path = "bomboni_proto", version = "0.1.5", optional = true }
bomboni_request = { path = "bomboni_request", version = "0.1.5", optional = true }
bomboni_template = { path = "bomboni_template", version = "0.1.5", optional = true }

[workspace.lints.rust]
warnings = "deny"
unsafe_code = "deny"
trivial_casts = "deny"
trivial_numeric_casts = "deny"
unused_import_braces = "deny"
unused_qualifications = "deny"
# unused_results = "deny"
# TODO: Enable these
# missing_docs = "deny"

[workspace.lints.clippy]
all = { level = "deny", priority = -1 }
correctness = "deny"
suspicious = "deny"
complexity = "deny"
perf = "deny"
style = "deny"
pedantic = "deny"

module_name_repetitions = "allow"
cast_possible_truncation = "allow"
cast_possible_wrap = "allow"
must_use_candidate = "allow"
cast_sign_loss = "allow"
too_many_lines = "allow"
needless_pass_by_value = "allow"

# TODO: Enable these
missing_errors_doc = "allow"
missing_panics_doc = "allow"
# nursery = "deny"
3 changes: 0 additions & 3 deletions bomboni_common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,3 @@ sqlx = { version = "0.7", features = ["mysql"], optional = true }
[dev-dependencies]
serde_json = "1.0.108"
tokio = { version = "1.34.0", features = ["rt-multi-thread", "macros"] }

[lints]
workspace = true
10 changes: 5 additions & 5 deletions bomboni_common/src/id/generator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub struct Generator {
const SLEEP_DURATION: Duration = Duration::from_secs(1);

#[cfg(feature = "tokio")]
pub type IdGeneratorArc = std::sync::Arc<tokio::sync::Mutex<Generator>>;
pub type GeneratorArc = std::sync::Arc<tokio::sync::Mutex<Generator>>;

impl Generator {
#[must_use]
Expand All @@ -31,9 +31,9 @@ impl Generator {
/// Basic usage:
///
/// ```
/// use bomboni_common::id::generator::IdGenerator;
/// use bomboni_common::id::generator::Generator;
///
/// let mut g = IdGenerator::new(1);
/// let mut g = Generator::new(1);
/// assert_ne!(g.generate(), g.generate());
/// ```
pub fn generate(&mut self) -> Id {
Expand Down Expand Up @@ -73,9 +73,9 @@ impl Generator {
///
/// ```
/// # use std::collections::HashSet;
/// use bomboni_common::id::generator::IdGenerator;
/// use bomboni_common::id::generator::Generator;
///
/// let mut g = IdGenerator::new(1);
/// let mut g = Generator::new(1);
/// let ids = g.generate_multiple(3);
/// let id_set: HashSet<_> = ids.iter().collect();
/// assert_eq!(id_set.len(), ids.len());
Expand Down
3 changes: 0 additions & 3 deletions bomboni_derive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,3 @@ proc-macro2 = { version = "1.0.69", features = ["proc-macro"] }
syn = "2.0.39"
quote = "1.0.33"
darling = "0.20.3"

[lints]
workspace = true
7 changes: 2 additions & 5 deletions bomboni_prost/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,9 @@ path = "src/lib.rs"
[dependencies]
itertools = "0.12.0"
convert_case = "0.6.0"
prost = "0.12.1"
prost-types = "0.12.1"
prost = "0.12.2"
prost-types = "0.12.2"
proc-macro2 = "1.0.69"
syn = { version = "2.0.39", features = ["full"] }
quote = "1.0.33"
prettyplease = "0.2.15"

[lints]
workspace = true
14 changes: 11 additions & 3 deletions bomboni_prost/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,12 @@ pub struct CompileConfig {

#[derive(Debug, Clone)]
pub struct ApiConfig {
pub names: bool,
pub field_names: bool,
pub type_url: bool,
pub oneof_utility: bool,
pub domain: Option<String>,
pub enable_field_names: bool,
pub serde: bool,
}

impl Default for CompileConfig {
Expand All @@ -21,16 +25,20 @@ impl Default for CompileConfig {
.join("fd.pb"),
output_path: std::env::var_os("OUT_DIR").unwrap().into(),
format: true,
api: Default::default(),
api: ApiConfig::default(),
}
}
}

impl Default for ApiConfig {
fn default() -> Self {
Self {
names: true,
field_names: true,
type_url: true,
oneof_utility: true,
domain: None,
enable_field_names: true,
serde: true,
}
}
}
4 changes: 2 additions & 2 deletions bomboni_prost/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub struct Context<'a> {
impl<'a> Context<'a> {
pub fn get_type_ident(&self, name: &str) -> ExprPath {
let mut ident = String::new();
for parent in self.path.iter() {
for parent in &self.path {
ident.push_str(&parent.to_case(Case::Snake));
ident.push_str("::");
}
Expand All @@ -35,7 +35,7 @@ impl<'a> Context<'a> {
oneof: &OneofDescriptorProto,
) -> ExprPath {
let mut ident = String::new();
for parent in self.path.iter() {
for parent in &self.path {
ident.push_str(&parent.to_case(Case::Snake));
ident.push_str("::");
}
Expand Down
31 changes: 18 additions & 13 deletions bomboni_prost/src/enums.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,47 @@ use quote::{format_ident, quote};
use crate::context::Context;

pub fn write_enum(context: &Context, s: &mut TokenStream, enum_type: &EnumDescriptorProto) {
if context.config.names {
write_name(context, s, enum_type);
}
if context.config.field_names {
write_value_names(context, s, enum_type);
}
if context.config.serde {
write_serde(context, s, enum_type);
}
}

fn write_name(context: &Context, s: &mut TokenStream, enum_type: &EnumDescriptorProto) {
let enum_ident = context.get_type_ident(enum_type.name());
let enum_proto_name = context.get_proto_type_name(enum_type.name());
let package_proto_name = Literal::string(&context.package_name);

// Enum name
s.extend(quote! {
impl #enum_ident {
pub const NAME: &'static str = #enum_proto_name;
pub const PACKAGE: &'static str = #package_proto_name;
}});
}

fn write_value_names(context: &Context, s: &mut TokenStream, enum_type: &EnumDescriptorProto) {
let enum_ident = context.get_type_ident(enum_type.name());

let mut value_names = TokenStream::new();
let mut value_names_array = TokenStream::new();

for value in enum_type.value.iter() {
for value in &enum_type.value {
let value_name_ident =
format_ident!("{}_VALUE_NAME", value.name().to_case(Case::ScreamingSnake));
let value_name = Literal::string(value.name());
// let variant_ident = format_ident!("{}", value.name().to_case(Case::Pascal));

value_names.extend(quote! {
pub const #value_name_ident: &'static str = #value_name;
});

// if config.add_enum_value_names {
value_names_array.extend(quote! {
Self::#value_name_ident,
});
// } else {
// let value_name = Literal::string(value.name());
// values.extend(quote! {
// #value_name,
// });
// }
}

s.extend(quote! {
Expand All @@ -49,11 +56,9 @@ pub fn write_enum(context: &Context, s: &mut TokenStream, enum_type: &EnumDescri
pub const VALUE_NAMES: &'static [&'static str] = &[#value_names_array];
}
});

write_enum_serde(context, s, enum_type);
}

fn write_enum_serde(context: &Context, s: &mut TokenStream, enum_type: &EnumDescriptorProto) {
fn write_serde(context: &Context, s: &mut TokenStream, enum_type: &EnumDescriptorProto) {
let enum_ident = context.get_type_ident(enum_type.name());

// Serialize as string
Expand Down
12 changes: 6 additions & 6 deletions bomboni_prost/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ pub fn compile(config: CompileConfig) -> Result<(), Box<dyn Error>> {
let descriptor = FileDescriptorSet::decode(buf.as_slice())?;

let flush = |package: &str, content: TokenStream| -> Result<(), Box<dyn Error>> {
let output_path = config.output_path.join(format!("./{}.plus.rs", package));
let output_path = config.output_path.join(format!("./{package}.plus.rs"));
println!(
"writing package `{}` to file `{}`",
package,
Expand All @@ -56,9 +56,9 @@ pub fn compile(config: CompileConfig) -> Result<(), Box<dyn Error>> {
};

// Clear files
for file in descriptor.file.iter() {
for file in &descriptor.file {
let package_name = file.package.clone().unwrap();
let output_path = config.output_path.join(format!("{}.plus.rs", package_name));
let output_path = config.output_path.join(format!("{package_name}.plus.rs"));
let mut output_file = OpenOptions::new()
.write(true)
.truncate(true)
Expand Down Expand Up @@ -91,13 +91,13 @@ pub fn compile(config: CompileConfig) -> Result<(), Box<dyn Error>> {
config: &config.api,
descriptor: &descriptor,
package_name,
path: Default::default(),
path: Vec::default(),
};

for message in file.message_type.iter() {
for message in &file.message_type {
write_message(&context, &mut current_content, message);
}
for enum_type in file.enum_type.iter() {
for enum_type in &file.enum_type {
write_enum(&context, &mut current_content, enum_type);
}
}
Expand Down
66 changes: 45 additions & 21 deletions bomboni_prost/src/messages.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,23 @@ use quote::{format_ident, quote};
use crate::{context::Context, oneofs::write_message_oneofs, utility::macros::format_comment};

pub fn write_message(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
write_message_name(context, s, message);
write_message_field_names(context, s, message);
write_message_oneofs(context, s, message);
if context.config.names {
write_name(context, s, message);
}
if context.config.field_names {
write_field_names(context, s, message);
}
if context.config.type_url {
write_type_url(context, s, message);
}
if context.config.oneof_utility {
write_message_oneofs(context, s, message);
}

if !message.nested_type.is_empty() {
let mut path = context.path.clone();
path.push(message.name.clone().unwrap());
for nested_message in message.nested_type.iter() {
for nested_message in &message.nested_type {
// Skip map entries
if nested_message
.options
Expand All @@ -36,21 +46,19 @@ pub fn write_message(context: &Context, s: &mut TokenStream, message: &Descripto
}
}

fn write_message_name(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
fn write_name(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
let message_ident = context.get_type_ident(message.name());
let message_proto_name = context.get_proto_type_name(message.name());
let package_proto_name = Literal::string(&context.package_name);

let type_url = if let Some(domain) = context.config.domain.as_ref() {
Literal::string(&format!(
"{}/{}.{}",
domain, &context.package_name, message_proto_name
))
let type_url = if context.config.type_url {
quote!(
fn type_url() -> String {
Self::TYPE_URL.into()
}
)
} else {
Literal::string(&format!(
"/{}.{}",
&context.package_name, message_proto_name
))
quote!()
};

let comment = format_comment!("Implement [`prost::Name`] for `{}`.", message_proto_name);
Expand All @@ -60,27 +68,43 @@ fn write_message_name(context: &Context, s: &mut TokenStream, message: &Descript
impl ::prost::Name for #message_ident {
const NAME: &'static str = #message_proto_name;
const PACKAGE: &'static str = #package_proto_name;

fn full_name() -> String {
format!("{}.{}", Self::PACKAGE, Self::NAME)
}

fn type_url() -> String {
Self::TYPE_URL.into()
}
#type_url
}
});
}

fn write_type_url(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
let message_ident = context.get_type_ident(message.name());
let message_proto_name = context.get_proto_type_name(message.name());

let type_url = if let Some(domain) = context.config.domain.as_ref() {
Literal::string(&format!(
"{}/{}.{}",
domain, &context.package_name, message_proto_name
))
} else {
Literal::string(&format!(
"/{}.{}",
&context.package_name, message_proto_name
))
};

s.extend(quote! {
impl #message_ident {
pub const TYPE_URL: &'static str = #type_url;
}
});
}

fn write_message_field_names(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
fn write_field_names(context: &Context, s: &mut TokenStream, message: &DescriptorProto) {
if message.field.is_empty() {
return;
}
let mut names = TokenStream::new();
for field in message.field.iter() {
for field in &message.field {
let field_name_ident =
format_ident!("{}_FIELD_NAME", field.name().to_case(Case::ScreamingSnake));
let field_name = Literal::string(field.name());
Expand Down
Loading

0 comments on commit f85e163

Please sign in to comment.