Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
kurtbuilds committed Aug 4, 2024
1 parent 67e3521 commit 62cc083
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 37 deletions.
13 changes: 5 additions & 8 deletions attr/src/cfg_attr.rs
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
use syn::{Meta, Token};
use syn::parse::{Parse, ParseStream};
use syn::punctuated::Punctuated;
use syn::token::Comma;
use syn::{Meta, Token};

/// When doing static analysis, `structmeta` and `darling` do not parse attributes
/// in a cfg_attr, so we have this struct to enable that
pub struct CfgAttr {
pub condition: Meta,
// pub _condition: Meta,
pub attrs: Punctuated<Meta, Token![,]>,
}

impl Parse for CfgAttr {
fn parse(input: ParseStream) -> syn::Result<Self> {
let condition = input.parse()?;
let _condition: Meta = input.parse()?;
let _: Comma = input.parse()?;
let attrs = input.parse_terminated(Meta::parse, Token![,])?;
Ok(CfgAttr {
condition,
attrs,
})
Ok(CfgAttr { attrs })
}
}
}
86 changes: 57 additions & 29 deletions attr/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,31 +1,31 @@
#![allow(non_snake_case)]

use std::{env, fs};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::{env, fs};

use anyhow::Context;
use ignore::Walk;
use syn::{DeriveInput, Item};

use crate::derive::DeriveParser;
use crate::repr::Repr;
pub use attr::*;
pub use error::*;
pub use ext::*;
pub use ttype::*;
pub use ident::*;
pub use metadata::*;
use crate::derive::DeriveParser;
use crate::repr::Repr;
pub use ttype::*;

mod attr;
mod metadata;
mod cfg_attr;
mod derive;
mod error;
mod ext;
mod ident;
mod ttype;
mod derive;
mod cfg_attr;
mod metadata;
mod repr;
pub mod ttype;

#[derive(Default, Debug)]
pub struct LoadOptions {
Expand All @@ -48,14 +48,21 @@ struct Intermediate {
}

impl Intermediate {
fn into_models_and_types(self) -> (impl Iterator<Item=syn::ItemStruct>, impl Iterator<Item=(String, Option<Repr>)>) {
fn into_models_and_types(
self,
) -> (
impl Iterator<Item = syn::ItemStruct>,
impl Iterator<Item = (String, Option<Repr>)>,
) {
let models = self.model_structs.into_iter();
let types = self.type_structs
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))
.chain(
self.type_enums
.into_iter()
.map(|(e, a)| (e.ident.to_string(), a)),
);
(models, types)
}
Expand Down Expand Up @@ -83,7 +90,9 @@ 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 @@ -101,36 +110,51 @@ impl Intermediate {
}

pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {
let cwd = env::current_dir().unwrap_or_default();
let cwd = env::var("CARGO_MANIFEST_DIR").expect("CARGO_MANIFEST_DIR not set");
let cwd = PathBuf::from(cwd);
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");
tracing::error!(path = path.display().to_string(), "Does not exist");
}
let paths = invalid_paths.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ");
let paths = invalid_paths
.iter()
.map(|p| p.display().to_string())
.collect::<Vec<_>>()
.join(", ");
anyhow::bail!("Provided paths that did not exist: {}", paths);
}

let walk = paths.iter().flat_map(Walk::new);

let walk = walk.map(|e| e.unwrap())
.filter(|e| e.path().extension().map(|e| e == "rs")
.unwrap_or(false))
let walk = walk
.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()))?;
tracing::debug!(file=entry.display().to_string(), "Checking for Model, Type, ManualType derive attrs");
if !(contents.contains("Model") || contents.contains("Type") || contents.contains("ManualType")) {
tracing::debug!(
file = entry.display().to_string(),
"Checking for Model, Type, ManualType derive attrs"
);
if !(contents.contains("Model")
|| contents.contains("Type")
|| contents.contains("ManualType"))
{
continue;
}
let ast = syn::parse_file(&contents)
Expand All @@ -140,13 +164,17 @@ pub fn schema_from_filepaths(paths: &[&Path]) -> anyhow::Result<OrmliteSchema> {

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
2 changes: 2 additions & 0 deletions macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
use proc_macro::TokenStream;
use std::borrow::Borrow;
use std::collections::HashMap;
use std::env;
use std::env::var;
use std::ops::Deref;

use once_cell::sync::OnceCell;
Expand Down

0 comments on commit 62cc083

Please sign in to comment.