Skip to content

Commit

Permalink
rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtbuilds committed Aug 31, 2024
1 parent 600087a commit de929fe
Show file tree
Hide file tree
Showing 49 changed files with 638 additions and 614 deletions.
1 change: 1 addition & 0 deletions .rustfmt.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
max_width = 120
4 changes: 2 additions & 2 deletions attr/src/attr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ pub struct ColumnAttributes {

#[cfg(test)]
mod test {
use syn::{Attribute, parse_quote};
use syn::{parse_quote, Attribute};

use super::*;

Expand All @@ -111,4 +111,4 @@ mod test {
let args: ColumnAttributes = attr.parse_args().unwrap();
assert!(args.join_column.is_some());
}
}
}
24 changes: 17 additions & 7 deletions attr/src/derive.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use syn::{Meta, Path, Token};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::{Meta, Path, Token};

use crate::cfg_attr::CfgAttr;

Expand Down Expand Up @@ -75,15 +75,21 @@ impl DeriveParser {
pub fn from_attributes(attrs: &[syn::Attribute]) -> Self {
let mut result = Self::default();
for attr in attrs {
let Some(ident) = attr.path().get_ident() else { continue; };
let Some(ident) = attr.path().get_ident() else {
continue;
};
if ident == Self::ATTRIBUTE {
result.merge(attr.parse_args().unwrap());
} else if ident == "cfg_attr" {
let cfg: CfgAttr = attr.parse_args().unwrap();
for attr in cfg.attrs {
let Some(ident) = attr.path().get_ident() else { continue; };
let Some(ident) = attr.path().get_ident() else {
continue;
};
if ident == Self::ATTRIBUTE {
let Meta::List(attrs) = attr else { panic!("Expected a list of attributes") };
let Meta::List(attrs) = attr else {
panic!("Expected a list of attributes")
};
result.merge(attrs.parse_args().unwrap());
}
}
Expand All @@ -108,8 +114,8 @@ impl Parse for Derive {

#[cfg(test)]
mod tests {
use crate::repr::Repr;
use super::*;
use crate::repr::Repr;

#[test]
fn test_repr() {
Expand Down Expand Up @@ -182,7 +188,9 @@ pub enum Privacy {
}
"#;
let file: syn::File = syn::parse_str(code).unwrap();
let syn::Item::Enum(item) = file.items.first().unwrap() else { panic!() };
let syn::Item::Enum(item) = file.items.first().unwrap() else {
panic!()
};
let attr = DeriveParser::from_attributes(&item.attrs);
assert!(attr.has_derive2(&["ormlite", "sqlx"], "Type"));
}
Expand All @@ -209,7 +217,9 @@ pub enum Privacy {
}
"#;
let file: syn::File = syn::parse_str(code).unwrap();
let syn::Item::Enum(item) = file.items.first().unwrap() else { panic!() };
let syn::Item::Enum(item) = file.items.first().unwrap() else {
panic!()
};
let attr = DeriveParser::from_attributes(&item.attrs);
assert_eq!(attr.has_derive("ormlite", "ManualType"), true);
}
Expand Down
2 changes: 1 addition & 1 deletion attr/src/ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,4 @@ impl DeriveInputExt for DeriveInput {
};
fields.iter()
}
}
}
46 changes: 12 additions & 34 deletions attr/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,7 @@ impl Intermediate {
.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)),
);
.chain(self.type_enums.into_iter().map(|(e, a)| (e.ident.to_string(), a)));
(models, types)
}

Expand All @@ -90,9 +86,7 @@ impl Intermediate {
}
Item::Enum(e) => {
let attrs = DeriveParser::from_attributes(&e.attrs);
if attrs.has_derive("ormlite", "Type")
|| attrs.has_derive("ormlite", "ManualType")
{
if attrs.has_derive("ormlite", "Type") || attrs.has_derive("ormlite", "ManualType") {
tracing::debug!(r#type=%e.ident.to_string(), "Found");
let repr = Repr::from_attributes(&e.attrs);
type_enums.push((e, repr));
Expand All @@ -110,14 +104,12 @@ impl Intermediate {
}

pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {
let cwd = env::var("CARGO_MANIFEST_DIR").map(PathBuf::from)
let cwd = env::var("CARGO_MANIFEST_DIR")
.map(PathBuf::from)
.or_else(|_| env::current_dir())
.expect("Failed to get current directory for schema");
let paths = paths.iter().map(|p| cwd.join(p)).collect::<Vec<_>>();
let invalid_paths = paths
.iter()
.filter(|p| fs::metadata(p).is_err())
.collect::<Vec<_>>();
let invalid_paths = paths.iter().filter(|p| fs::metadata(p).is_err()).collect::<Vec<_>>();
if !invalid_paths.is_empty() {
for path in &invalid_paths {
tracing::error!(path = path.display().to_string(), "Does not exist");
Expand All @@ -136,46 +128,32 @@ pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {
.map(|e| e.unwrap())
.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![];
let mut type_aliases = HashMap::new();
for entry in walk {
let contents = fs::read_to_string(&entry)
.context(format!("failed to read file: {}", entry.display()))?;
let contents = fs::read_to_string(&entry).context(format!("failed to read file: {}", entry.display()))?;
tracing::debug!(
file = entry.display().to_string(),
"Checking for Model, Type, ManualType derive attrs"
);
if !(contents.contains("Model")
|| contents.contains("Type")
|| contents.contains("ManualType"))
{
if !(contents.contains("Model") || contents.contains("Type") || contents.contains("ManualType")) {
continue;
}
let ast = syn::parse_file(&contents)
.context(format!("Failed to parse file: {}", entry.display()))?;
let ast = syn::parse_file(&contents).context(format!("Failed to parse file: {}", entry.display()))?;
let intermediate = Intermediate::from_file(ast);
let (models, types) = intermediate.into_models_and_types();

for item in models {
let derive: DeriveInput = item.into();
let table = ModelMetadata::from_derive(&derive).context(format!(
"Failed to parse model: {}",
derive.ident.to_string()
))?;
let table = ModelMetadata::from_derive(&derive)
.context(format!("Failed to parse model: {}", derive.ident.to_string()))?;
tables.push(table);
}

for (name, repr) in types {
let ty = repr
.map(|s| s.to_string())
.unwrap_or_else(|| "String".to_string());
let ty = repr.map(|s| s.to_string()).unwrap_or_else(|| "String".to_string());
type_aliases.insert(name, ty);
}
}
Expand Down
23 changes: 13 additions & 10 deletions attr/src/metadata/column.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use proc_macro2::TokenStream;
use syn::Field;
use crate::{ColumnAttributes, SyndecodeError};
use crate::ident::Ident;
use crate::ttype::{InnerType, TType};
use crate::{ColumnAttributes, SyndecodeError};
use proc_macro2::TokenStream;
use syn::Field;

#[derive(Debug, Clone)]
pub enum Join {
Expand Down Expand Up @@ -110,7 +110,6 @@ impl ColumnMetadata {
}
}


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

Expand Down Expand Up @@ -176,7 +175,6 @@ impl TryFrom<&Field> for ColumnMetadata {
}
}


#[derive(Clone, Debug)]
pub struct ForeignKey {
pub model: String,
Expand All @@ -185,18 +183,23 @@ pub struct ForeignKey {

#[cfg(test)]
mod tests {
use syn::{Fields, ItemStruct};
use super::*;
use syn::{Fields, ItemStruct};

#[test]
fn test_from_field() {
let item: ItemStruct = syn::parse_str(r#"
let item: ItemStruct = syn::parse_str(
r#"
struct Foo {
#[ormlite(default_value = "\"foo\".to_string()")]
pub name: String
}
"#).unwrap();
let Fields::Named(fields) = item.fields else { panic!(); };
"#,
)
.unwrap();
let Fields::Named(fields) = item.fields else {
panic!();
};
let field = fields.named.first().unwrap();
let column = ColumnMetadata::try_from(field).unwrap();
assert_eq!(column.column_name, "name");
Expand All @@ -206,4 +209,4 @@ pub name: String
assert_eq!(column.rust_default, Some("\"foo\".to_string()".to_string()));
assert_eq!(column.identifier, Ident::new("name"));
}
}
}
41 changes: 23 additions & 18 deletions attr/src/metadata/model.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use syn::DeriveInput;
use crate::ident::Ident;
use crate::metadata::column::ColumnMetadata;
use crate::{ModelAttributes, SyndecodeError};
use crate::metadata::table::TableMetadata;
use crate::{ModelAttributes, SyndecodeError};
use syn::DeriveInput;

/// Metadata used for IntoArguments, TableMeta, and (subset of) Model
#[derive(Debug, Clone)]
Expand All @@ -16,10 +16,7 @@ impl ModelMetadata {
pub fn new(name: &str, columns: Vec<ColumnMetadata>) -> Self {
let inner = TableMetadata::new(name, columns);
Self {
pkey: inner.columns.iter()
.find(|c| c.column_name == "id")
.unwrap()
.clone(),
pkey: inner.columns.iter().find(|c| c.column_name == "id").unwrap().clone(),
inner,
insert_struct: None,
}
Expand All @@ -38,21 +35,23 @@ impl ModelMetadata {
Ident(s)
}

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

pub fn database_columns(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
pub fn database_columns(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.inner.database_columns()
}

pub fn many_to_one_joins(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
pub fn many_to_one_joins(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.inner.many_to_one_joins()
}

pub fn columns(&self) -> impl Iterator<Item=&ColumnMetadata> + '_ {
pub fn columns(&self) -> impl Iterator<Item = &ColumnMetadata> + '_ {
self.inner.columns.iter()
}

Expand All @@ -65,13 +64,16 @@ impl ModelMetadata {
let pkey = inner.columns.iter().find(|&c| c.column_name == pkey).unwrap().clone();
let mut insert_struct = None;
for attr in ast.attrs.iter().filter(|a| a.path().is_ident("ormlite")) {
let args: ModelAttributes = attr.parse_args()
.map_err(|e| SyndecodeError(e.to_string()))?;
let args: ModelAttributes = attr.parse_args().map_err(|e| SyndecodeError(e.to_string()))?;
if let Some(value) = args.insertable {
insert_struct = Some(value.to_string());
}
}
Ok(Self { inner, insert_struct, pkey })
Ok(Self {
inner,
insert_struct,
pkey,
})
}
}

Expand All @@ -85,17 +87,20 @@ impl std::ops::Deref for ModelMetadata {

#[cfg(test)]
mod tests {
use syn::ItemStruct;
use super::*;
use syn::ItemStruct;

#[test]
fn test_decode_metadata() {
let ast = syn::parse_str::<ItemStruct>(r#"struct User {
let ast = syn::parse_str::<ItemStruct>(
r#"struct User {
#[ormlite(column = "Id")]
id: i32,
}"#).unwrap();
}"#,
)
.unwrap();
let input = DeriveInput::from(ast);
let meta = ModelMetadata::from_derive(&input).unwrap();
assert_eq!(meta.pkey.column_name, "Id");
}
}
}
Loading

0 comments on commit de929fe

Please sign in to comment.