Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatted project using cargo fmt #28

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions attr/src/attr.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use structmeta::{Flag, NameValue, StructMeta};
use syn::{Ident, LitStr, Path};


/// Available attributes on a struct
#[derive(StructMeta, Debug)]
pub struct ModelAttributes {
Expand Down Expand Up @@ -117,4 +116,4 @@ mod test {
let args: ColumnAttributes = attr.parse_args().unwrap();
assert!(args.join_column.is_some());
}
}
}
2 changes: 1 addition & 1 deletion attr/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,4 +26,4 @@ impl FieldExt for Field {
fn name(&self) -> String {
self.ident.as_ref().unwrap().to_string().replace("r#", "")
}
}
}
56 changes: 38 additions & 18 deletions attr/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
#![allow(non_snake_case)]

mod attr;
mod metadata;
mod error;
mod ext;
mod metadata;
mod syndecode;

use ignore::Walk;
use std::collections::HashMap;
use std::fs;
use std::path::Path;
use syn::{DeriveInput, Item};
use ignore::Walk;

use syndecode::{Attributes};
pub use metadata::*;
pub use attr::*;
pub use error::*;
pub use ext::*;
pub use metadata::*;
use syndecode::Attributes;

#[derive(Default, Debug)]
pub struct LoadOptions {
Expand All @@ -41,10 +41,22 @@ struct Intermediate {
}

impl Intermediate {
fn into_models_and_types(self) -> (impl Iterator<Item=WithAttr<syn::ItemStruct>>, impl Iterator<Item=WithAttr<String>>) {
fn into_models_and_types(
self,
) -> (
impl Iterator<Item = WithAttr<syn::ItemStruct>>,
impl Iterator<Item = WithAttr<String>>,
) {
let models = self.model_structs.into_iter();
let types = self.type_structs.into_iter().map(|(s, a)| (s.ident.to_string(), a))
.chain(self.type_enums.into_iter().map(|(e, a)| (e.ident.to_string(), a)));
let types = self
.type_structs
.into_iter()
.map(|(s, a)| (s.ident.to_string(), a))
.chain(
self.type_enums
.into_iter()
.map(|(e, a)| (e.ident.to_string(), a)),
);
(models, types)
}

Expand Down Expand Up @@ -91,13 +103,15 @@ impl Intermediate {
pub fn schema_from_filepaths(paths: &[&Path], opts: &LoadOptions) -> anyhow::Result<OrmliteSchema> {
let walk = paths.iter().flat_map(Walk::new);

let walk = walk.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|e| e == "rs")
.unwrap_or(false))
let walk = walk
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|e| e == "rs").unwrap_or(false))
.map(|e| e.into_path())
.chain(paths.iter()
.filter(|p| p.ends_with(".rs"))
.map(|p| p.to_path_buf())
.chain(
paths
.iter()
.filter(|p| p.ends_with(".rs"))
.map(|p| p.to_path_buf()),
);

let mut tables = vec![];
Expand All @@ -116,11 +130,13 @@ pub fn schema_from_filepaths(paths: &[&Path], opts: &LoadOptions) -> anyhow::Res

for (item, _attrs) in models {
let derive: DeriveInput = item.into();
let table = TableMetadata::try_from(&derive)
.map_err(|e| SyndecodeError(format!(
let table = TableMetadata::try_from(&derive).map_err(|e| {
SyndecodeError(format!(
"{}: Encountered an error while scanning for #[derive(Model)] structs: {}",
entry.display(), e))
)?;
entry.display(),
e
))
})?;
tables.push(table);
}

Expand All @@ -130,7 +146,11 @@ pub fn schema_from_filepaths(paths: &[&Path], opts: &LoadOptions) -> anyhow::Res
if attr.name != "repr" {
continue;
}
ty = attr.args.first().expect("repr attribute must have at least one argument").clone();
ty = attr
.args
.first()
.expect("repr attribute must have at least one argument")
.clone();
}
type_aliases.insert(name, ty);
}
Expand Down
100 changes: 55 additions & 45 deletions attr/src/metadata.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
use derive_builder::Builder;
use syn::{DeriveInput, Field, PathArguments};
use crate::{ColumnAttributes, ModelAttributes, SyndecodeError};
use crate::DeriveInputExt;
use crate::{ColumnAttributes, ModelAttributes, SyndecodeError};
use convert_case::{Case, Casing};
use derive_builder::Builder;
use proc_macro2::TokenStream;
use quote::{TokenStreamExt};
use quote::TokenStreamExt;
use syn::{DeriveInput, Field, PathArguments};

#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Ident(pub String);
Expand All @@ -23,7 +23,10 @@ impl From<&proc_macro2::Ident> for Ident {

impl quote::ToTokens for Ident {
fn to_tokens(&self, tokens: &mut TokenStream) {
tokens.append(proc_macro2::Ident::new(&self.0, proc_macro2::Span::call_site()))
tokens.append(proc_macro2::Ident::new(
&self.0,
proc_macro2::Span::call_site(),
))
}
}

Expand Down Expand Up @@ -131,7 +134,7 @@ impl TType {
quote::quote! {
#(#segments)::* #ident
}
},
}
TType::Option(ty) => ty.qualified_inner_name(),
TType::Vec(ty) => ty.qualified_inner_name(),
TType::Join(ty) => ty.qualified_inner_name(),
Expand All @@ -141,26 +144,30 @@ impl TType {

impl From<&syn::Path> for InnerType {
fn from(path: &syn::Path) -> Self {
let segment = path.segments.last().expect("path must have at least one segment");
let args: Option<Box<InnerType>> = if let PathArguments::AngleBracketed(args) = &segment.arguments {
let args = &args.args;
let syn::GenericArgument::Type(ty) = args.first().unwrap() else {
let segment = path
.segments
.last()
.expect("path must have at least one segment");
let args: Option<Box<InnerType>> =
if let PathArguments::AngleBracketed(args) = &segment.arguments {
let args = &args.args;
let syn::GenericArgument::Type(ty) = args.first().unwrap() else {
panic!("Option must have a type parameter");
};
let syn::Type::Path(path) = &ty else {
let syn::Type::Path(path) = &ty else {
panic!("Option must have a type parameter");
};
Some(Box::new(InnerType::from(&path.path)))
} else {
None
};
let mut path = path.segments.iter().map(|s| Ident::from(&s.ident)).collect::<Vec<_>>();
Some(Box::new(InnerType::from(&path.path)))
} else {
None
};
let mut path = path
.segments
.iter()
.map(|s| Ident::from(&s.ident))
.collect::<Vec<_>>();
let ident = path.pop().expect("path must have at least one segment");
InnerType {
path,
args,
ident,
}
InnerType { path, args, ident }
}
}

Expand Down Expand Up @@ -270,13 +277,16 @@ impl TableMetadata {
TableMetadataBuilder::default()
}

pub fn builder_from_struct_attributes(ast: &DeriveInput) -> Result<TableMetadataBuilder, SyndecodeError> {
pub fn builder_from_struct_attributes(
ast: &DeriveInput,
) -> Result<TableMetadataBuilder, SyndecodeError> {
let mut builder = TableMetadata::builder();
builder.insert_struct(None);
builder.struct_name(Ident::from(&ast.ident));
let mut databases = vec![];
for attr in ast.attrs.iter().filter(|a| a.path.is_ident("ormlite")) {
let args: ModelAttributes = attr.parse_args()
let args: ModelAttributes = attr
.parse_args()
.map_err(|e| SyndecodeError(e.to_string()))?;
if let Some(value) = args.table {
builder.table_name(value.value());
Expand All @@ -292,41 +302,46 @@ impl TableMetadata {
Ok(builder)
}

pub fn all_fields(&self) -> impl Iterator<Item=&Ident> + '_ {
self.columns.iter()
.map(|c| &c.identifier)
pub fn all_fields(&self) -> impl Iterator<Item = &Ident> + '_ {
self.columns.iter().map(|c| &c.identifier)
}

pub fn database_columns(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
self.columns.iter()
.filter(|&c| !c.skip)
pub fn database_columns(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.columns.iter().filter(|&c| !c.skip)
}

pub fn database_columns_except_pkey(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
self.columns.iter()
pub fn database_columns_except_pkey(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.columns
.iter()
.filter(|&c| !c.skip)
.filter(|&c| c.column_name != self.pkey.column_name)
}

pub fn many_to_one_joins(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
self.columns.iter()
pub fn many_to_one_joins(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.columns
.iter()
.filter(|&c| c.many_to_one_column_name.is_some())
}
}


impl TableMetadataBuilder {
pub fn complete_with_struct_body(&mut self, ast: &DeriveInput) -> Result<TableMetadata, SyndecodeError> {
pub fn complete_with_struct_body(
&mut self,
ast: &DeriveInput,
) -> Result<TableMetadata, SyndecodeError> {
let model = &ast.ident;
let model_lowercased = model.to_string().to_case(Case::Snake);
self.table_name.get_or_insert(model_lowercased);

let mut cols = ast.fields()
let mut cols = ast
.fields()
.map(ColumnMetadata::try_from)
.collect::<Result<Vec<_>, _>>().unwrap();
.collect::<Result<Vec<_>, _>>()
.unwrap();
let mut pkey = cols
.iter()
.find(|&c| c.marked_primary_key).map(|c| c.clone());
.find(|&c| c.marked_primary_key)
.map(|c| c.clone());
if pkey.is_none() {
let candidates = sqlmo::util::pkey_column_names(&self.table_name.as_ref().unwrap());
for c in &mut cols {
Expand All @@ -344,13 +359,11 @@ impl TableMetadataBuilder {
}
}


impl TryFrom<&DeriveInput> for TableMetadata {
type Error = SyndecodeError;

fn try_from(ast: &DeriveInput) -> Result<Self, Self::Error> {
TableMetadata::builder_from_struct_attributes(ast)?
.complete_with_struct_body(ast)
TableMetadata::builder_from_struct_attributes(ast)?.complete_with_struct_body(ast)
}
}

Expand Down Expand Up @@ -464,7 +477,6 @@ impl ColumnMetadata {
}
}


impl TryFrom<&Field> for ColumnMetadata {
type Error = SyndecodeError;

Expand All @@ -487,8 +499,7 @@ impl TryFrom<&Field> for ColumnMetadata {
.one_to_many_foreign_key(None)
.skip(false)
.experimental_encode_as_json(false)
.rust_default(None)
;
.rust_default(None);
let mut has_join_directive = false;
for attr in f.attrs.iter().filter(|&a| a.path.is_ident("ormlite")) {
let args: ColumnAttributes = attr.parse_args().unwrap();
Expand Down Expand Up @@ -538,7 +549,6 @@ impl TryFrom<&Field> for ColumnMetadata {
}
}


#[cfg(test)]
mod test {
use super::*;
Expand Down
Loading