Skip to content

Commit

Permalink
Fix clippy warnings and errors
Browse files Browse the repository at this point in the history
Also includes code generation changes provided by @russcam in PR #210.
  • Loading branch information
swallez committed Aug 21, 2024
1 parent bf09d72 commit 4f248cc
Show file tree
Hide file tree
Showing 74 changed files with 1,304 additions and 1,330 deletions.
3 changes: 1 addition & 2 deletions api_generator/docs/namespaces/security.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,4 @@ Security APIs
- Manage role mappings
- Manage API keys
- Manage Bearer tokens
- Authenticate users against an OpenID Connect or SAML authentication realm when using a
custom web application other than Kibana
- Authenticate users against an OpenID Connect or SAML authentication realm when using a custom web application other than Kibana
12 changes: 6 additions & 6 deletions api_generator/src/generator/code_gen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ fn ident<I: AsRef<str>>(name: I) -> syn::Ident {
fn doc<I: Into<String>>(comment: I) -> syn::Attribute {
syn::Attribute {
style: syn::AttrStyle::Outer,
value: syn::MetaItem::NameValue(ident("doc".to_string()), lit(comment)),
value: syn::MetaItem::NameValue(ident("doc"), lit(comment)),
is_sugared_doc: true,
}
}
Expand Down Expand Up @@ -136,15 +136,15 @@ pub trait GetPath {
impl GetPath for syn::Ty {
fn get_path(&self) -> &syn::Path {
match *self {
syn::Ty::Path(_, ref p) => &p,
syn::Ty::Path(_, ref p) => p,
ref p => panic!("Expected syn::Ty::Path, but found {:?}", p),
}
}
}

impl GetPath for syn::Path {
fn get_path(&self) -> &syn::Path {
&self
self
}
}

Expand Down Expand Up @@ -172,7 +172,7 @@ fn typekind_to_ty(name: &str, kind: &TypeKind, required: bool, fn_arg: bool) ->
TypeKind::List => {
v.push_str("&'b [");
v.push_str(str_type);
v.push_str("]");
v.push(']');
}
TypeKind::Enum => match name {
// opened https://github.com/elastic/elasticsearch/issues/53212
Expand All @@ -181,7 +181,7 @@ fn typekind_to_ty(name: &str, kind: &TypeKind, required: bool, fn_arg: bool) ->
// Expand wildcards should
v.push_str("&'b [");
v.push_str(name.to_pascal_case().as_str());
v.push_str("]");
v.push(']');
}
_ => v.push_str(name.to_pascal_case().as_str()),
},
Expand Down Expand Up @@ -219,7 +219,7 @@ fn typekind_to_ty(name: &str, kind: &TypeKind, required: bool, fn_arg: bool) ->
};

if !required {
v.push_str(">");
v.push('>');
}

syn::parse_type(v.as_str()).unwrap()
Expand Down
6 changes: 3 additions & 3 deletions api_generator/src/generator/code_gen/namespace_clients.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub fn generate(api: &Api, docs_dir: &PathBuf) -> anyhow::Result<Vec<(String, St
tokens.append(use_declarations());

let namespace_pascal_case = namespace_name.to_pascal_case();
let namespace_replaced_pascal_case = namespace_name.replace("_", " ").to_pascal_case();
let namespace_replaced_pascal_case = namespace_name.replace('_', " ").to_pascal_case();
let namespace_client_name = ident(&namespace_pascal_case);
let name_for_docs = match namespace_replaced_pascal_case.as_ref() {
"Ccr" => "Cross Cluster Replication",
Expand All @@ -61,7 +61,7 @@ pub fn generate(api: &Api, docs_dir: &PathBuf) -> anyhow::Result<Vec<(String, St
"Creates a new instance of [{}]",
&namespace_pascal_case
));
let namespace_name = ident(namespace_name.to_string());
let namespace_name = ident(namespace_name);

let (builders, methods): (Vec<Tokens>, Vec<Tokens>) = namespace
.endpoints()
Expand All @@ -74,7 +74,7 @@ pub fn generate(api: &Api, docs_dir: &PathBuf) -> anyhow::Result<Vec<(String, St
name,
&builder_name,
&api.common_params,
&endpoint,
endpoint,
false,
)
.build()
Expand Down
7 changes: 2 additions & 5 deletions api_generator/src/generator/code_gen/params.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ pub fn generate(api: &Api) -> anyhow::Result<String> {
use serde::{Serialize, Deserialize};
);
for e in &api.enums {
generate_param(&mut tokens, &e);
generate_param(&mut tokens, e);
}

let generated = tokens.to_string();
Expand Down Expand Up @@ -60,10 +60,7 @@ fn generate_param(tokens: &mut Tokens, e: &ApiEnum) {
})
.unzip();

let doc = match &e.description {
Some(description) => Some(code_gen::doc(description)),
None => None,
};
let doc = e.description.as_ref().map(code_gen::doc);

let cfg_attr = e.stability.outer_cfg_attr();
let cfg_doc = stability_doc(e.stability);
Expand Down
24 changes: 12 additions & 12 deletions api_generator/src/generator/code_gen/request/request_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use crate::generator::{
use inflector::Inflector;
use quote::{ToTokens, Tokens};
use reqwest::Url;
use std::path::Path;
use std::{collections::BTreeMap, fs, path::PathBuf, str};
use syn::{Field, FieldValue, ImplItem, TraitBoundModifier, TyParamBound};

Expand Down Expand Up @@ -245,7 +246,7 @@ impl<'a> RequestBuilder<'a> {
default_fields: &[&syn::Ident],
accepts_nd_body: bool,
) -> syn::ImplItem {
let fields: Vec<FieldValue> = default_fields
let fields = default_fields
.iter()
.filter(|&&part| part != &ident("body"))
.map(|&part| syn::FieldValue {
Expand All @@ -257,8 +258,7 @@ impl<'a> RequestBuilder<'a> {
)
.into(),
is_shorthand: false,
})
.collect();
});

let (fn_arg, field_arg, ret_ty) = if accepts_nd_body {
(
Expand Down Expand Up @@ -401,9 +401,9 @@ impl<'a> RequestBuilder<'a> {

/// Creates the AST for a builder fn for a builder impl
fn create_impl_fn(f: (&String, &Type)) -> syn::ImplItem {
let name = valid_name(&f.0).to_lowercase();
let name = valid_name(f.0).to_lowercase();
let (ty, value_ident, fn_generics) = {
let ty = typekind_to_ty(&f.0, &f.1.ty, true, true);
let ty = typekind_to_ty(f.0, &f.1.ty, true, true);
match ty {
syn::Ty::Path(ref _q, ref p) => {
if p.get_ident().as_ref() == "Into" {
Expand Down Expand Up @@ -552,7 +552,7 @@ impl<'a> RequestBuilder<'a> {
// add a body impl if supported
if supports_body {
let body_fn = Self::create_body_fn(
&builder_name,
builder_name,
&builder_ident,
&default_fields,
accepts_nd_body,
Expand All @@ -566,9 +566,9 @@ impl<'a> RequestBuilder<'a> {
builder_fns.dedup_by(|a, b| a.ident.eq(&b.ident));

let new_fn =
Self::create_new_fn(&builder_name, &builder_ident, enum_builder, &default_fields);
Self::create_new_fn(builder_name, &builder_ident, enum_builder, &default_fields);

let method_expr = Self::create_method_expression(&builder_name, &endpoint);
let method_expr = Self::create_method_expression(builder_name, endpoint);

let query_string_params = {
let mut p = endpoint.params.clone();
Expand Down Expand Up @@ -669,7 +669,7 @@ impl<'a> RequestBuilder<'a> {
/// Creates the AST for a fn that returns a new instance of a builder struct
/// from the root or namespace client
fn create_builder_struct_ctor_fns(
docs_dir: &PathBuf,
docs_dir: &Path,
namespace_name: &str,
name: &str,
builder_name: &str,
Expand Down Expand Up @@ -697,7 +697,7 @@ impl<'a> RequestBuilder<'a> {
let api_name_for_docs = split_on_pascal_case(builder_name);

let markdown_doc = {
let mut path = docs_dir.clone();
let mut path = docs_dir.to_owned();
path.push("functions");
path.push(format!("{}.{}.md", namespace_name, name));
if path.exists() {
Expand Down Expand Up @@ -759,10 +759,10 @@ impl<'a> RequestBuilder<'a> {
/// Creates the AST for a field for a struct
fn create_struct_field(f: (&String, &Type)) -> syn::Field {
syn::Field {
ident: Some(ident(valid_name(&f.0).to_lowercase())),
ident: Some(ident(valid_name(f.0).to_lowercase())),
vis: syn::Visibility::Inherited,
attrs: vec![],
ty: typekind_to_ty(&f.0, &f.1.ty, false, false),
ty: typekind_to_ty(f.0, &f.1.ty, false, false),
}
}

Expand Down
1 change: 1 addition & 0 deletions api_generator/src/generator/code_gen/root.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ pub fn generate(api: &Api, docs_dir: &PathBuf) -> anyhow::Result<String> {
tokens.append(quote!(
#(#builders)*

#[allow(clippy::needless_lifetimes)]
impl Elasticsearch {
#(#methods)*
}
Expand Down
19 changes: 10 additions & 9 deletions api_generator/src/generator/code_gen/url/enum_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ impl<'a> EnumBuilder<'a> {
0 => Self::parts_none(),
_ => {
self.has_lifetime = true;
Self::parts(&path)
Self::parts(path)
}
};

Expand All @@ -113,18 +113,18 @@ impl<'a> EnumBuilder<'a> {
.join("");

let doc = match params.len() {
1 => doc(params[0].replace("_", " ").to_pascal_case()),
1 => doc(params[0].replace('_', " ").to_pascal_case()),
n => {
let mut d: String = params
.iter()
.enumerate()
.filter(|&(i, _)| i != n - 1)
.map(|(_, e)| e.replace("_", " ").to_pascal_case())
.map(|(_, e)| e.replace('_', " ").to_pascal_case())
.collect::<Vec<_>>()
.join(", ");

d.push_str(
format!(" and {}", params[n - 1].replace("_", " ").to_pascal_case()).as_str(),
format!(" and {}", params[n - 1].replace('_', " ").to_pascal_case()).as_str(),
);
doc(d)
}
Expand Down Expand Up @@ -181,7 +181,7 @@ impl<'a> EnumBuilder<'a> {
.iter()
.map(|&p| {
syn::Pat::Ident(
syn::BindingMode::ByRef(syn::Mutability::Immutable),
syn::BindingMode::ByValue(syn::Mutability::Immutable),
ident(valid_name(p)),
None,
)
Expand Down Expand Up @@ -282,6 +282,7 @@ impl<'a> EnumBuilder<'a> {
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("Debug"))),
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("Clone"))),
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("PartialEq"))),
syn::NestedMetaItem::MetaItem(syn::MetaItem::Word(ident("Eq"))),
],
),
},
Expand All @@ -299,7 +300,7 @@ impl<'a> From<&'a (String, ApiEndpoint)> for EnumBuilder<'a> {
let endpoint = &value.1;
let mut builder = EnumBuilder::new(value.0.to_pascal_case().as_ref());
for path in &endpoint.url.paths {
builder = builder.with_path(&path);
builder = builder.with_path(path);
}

builder
Expand Down Expand Up @@ -391,7 +392,7 @@ mod tests {
assert_eq!(ty_b("SearchParts"), enum_ty);

let expected_decl = quote!(
#[derive(Debug, Clone, PartialEq)]
#[derive(Debug, Clone, PartialEq, Eq)]
#[doc = "API parts for the Search API"]
pub enum SearchParts<'b> {
#[doc = "No parts"]
Expand All @@ -411,7 +412,7 @@ mod tests {
pub fn url(self) -> Cow<'static, str> {
match self {
SearchParts::None => "/_search".into(),
SearchParts::Index(ref index) => {
SearchParts::Index(index) => {
let index_str = index.join(",");
let encoded_index: Cow<str> = percent_encode(index_str.as_bytes(), PARTS_ENCODED).into();
let mut p = String::with_capacity(9usize + encoded_index.len());
Expand All @@ -420,7 +421,7 @@ mod tests {
p.push_str("/_search");
p.into()
}
SearchParts::IndexType(ref index, ref ty) => {
SearchParts::IndexType(index, ty) => {
let index_str = index.join(",");
let ty_str = ty.join(",");
let encoded_index: Cow<str> = percent_encode(index_str.as_bytes(), PARTS_ENCODED).into();
Expand Down
22 changes: 13 additions & 9 deletions api_generator/src/generator/code_gen/url/url_builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,9 +170,9 @@ impl<'a> UrlBuilder<'a> {
/// Build the AST for an allocated url from the path literals and params.
fn build_owned(self) -> syn::Block {
// collection of let {name}_str = [self.]{name}.[join(",")|to_string()];
let let_params_exprs = Self::let_parameters_exprs(&self.path, &self.parts);
let let_params_exprs = Self::let_parameters_exprs(&self.path, self.parts);

let mut let_encoded_params_exprs = Self::let_encoded_exprs(&self.path, &self.parts);
let mut let_encoded_params_exprs = Self::let_encoded_exprs(&self.path, self.parts);

let url_ident = ident("p");
let len_expr = {
Expand Down Expand Up @@ -275,7 +275,7 @@ impl<'a> UrlBuilder<'a> {
.filter_map(|p| match *p {
PathPart::Param(p) => {
let name = valid_name(p);
let name_ident = ident(&name);
let name_ident = ident(name);
let ty = &parts[p].ty;

// don't generate an assignment expression for strings
Expand Down Expand Up @@ -405,8 +405,15 @@ impl<'a> UrlBuilder<'a> {
url.iter()
.map(|p| match *p {
PathPart::Literal(p) => {
let lit = syn::Lit::Str(p.to_string(), syn::StrStyle::Cooked);
syn::Stmt::Semi(Box::new(parse_expr(quote!(#url_ident.push_str(#lit)))))
let push = if p.len() == 1 {
let lit = syn::Lit::Char(p.chars().next().unwrap());
quote!(#url_ident.push(#lit))
} else {
let lit = syn::Lit::Str(p.to_string(), syn::StrStyle::Cooked);
quote!(#url_ident.push_str(#lit))
};

syn::Stmt::Semi(Box::new(parse_expr(push)))
}
PathPart::Param(p) => {
let name = format!("encoded_{}", valid_name(p));
Expand All @@ -420,10 +427,7 @@ impl<'a> UrlBuilder<'a> {
}

pub fn build(self) -> syn::Expr {
let has_params = self.path.iter().any(|p| match *p {
PathPart::Param(_) => true,
_ => false,
});
let has_params = self.path.iter().any(|p| matches!(*p, PathPart::Param(_)));

if has_params {
self.build_owned().into_expr()
Expand Down
Loading

0 comments on commit 4f248cc

Please sign in to comment.