1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
//! Generate a GitHub API.

#![allow(clippy::tabs_in_doc_comments)]
#![deny(missing_docs)]

// proc-macro
use proc_macro::TokenStream;
// crates.io
use convert_case::{Case, Casing};
use quote::format_ident;
use syn::{
	parse::{Parse, ParseStream},
	punctuated::Punctuated,
	*,
};

#[derive(Debug)]
enum ApiProperty {
	Category(String),
	Accept(String),
	Uri(String),
}
impl Parse for ApiProperty {
	fn parse(input: ParseStream) -> Result<Self> {
		let name = input.parse::<Ident>()?.to_string();
		let value = if input.peek(Token![=]) {
			input.parse::<Token![=]>()?;

			if input.peek(LitStr) {
				input.parse::<LitStr>()?.value()
			} else {
				unreachable!()
			}
		} else {
			unreachable!()
		};

		Ok(match name.as_str() {
			"category" => ApiProperty::Category(value),
			"accept" => ApiProperty::Accept(value),
			"uri" => ApiProperty::Uri(value),
			_ => unreachable!(),
		})
	}
}

/// Generate a GitHub API.
///
/// # Example
/// ```ignore
/// use githuber::prelude::*;
///
/// #[api_impl::api]
/// #[properties(category = "repos", accept = "application/vnd.github+json", uri = "/orgs/{}/repos")]
/// pub struct ListOrganizationRepositories<'a> {
/// 	pub org: &'a str,
/// 	pub r#type: Option<&'a str>,
/// 	pub sort: Option<&'a str>,
/// 	pub direction: Option<&'a str>,
/// 	pub per_page: Option<u8>,
/// 	pub page: Option<u16>,
/// }
/// ```
#[proc_macro_attribute]
pub fn api(_: TokenStream, input: TokenStream) -> TokenStream {
	let api_struct = syn::parse_macro_input!(input as ItemStruct);

	// dbg!(&api_struct);

	let api_attrs = api_struct.attrs;

	// dbg!(&api_attrs);

	let api_name = api_struct.ident;
	let mut api_doc = String::new();
	let mut api_accept = String::new();
	let mut api_uri = String::new();

	api_attrs
		.into_iter()
		.filter(|attr| attr.path.is_ident("properties"))
		.flat_map(|attr| {
			attr.parse_args_with(Punctuated::<ApiProperty, Token![,]>::parse_terminated)
				.unwrap()
				.into_iter()
		})
		.for_each(|property| match property {
			ApiProperty::Category(category) =>
				api_doc = format!(
					" - <https://docs.github.com/en/rest/{category}/{category}#{}>",
					api_name.to_string().to_case(Case::Kebab)
				),
			ApiProperty::Accept(accept) => api_accept = accept,
			ApiProperty::Uri(uri) => api_uri = format!("{{}}{uri}"),
		});

	let api_vis = api_struct.vis;
	let api_generics = api_struct.generics;
	let mut api_fields = Vec::new();
	let mut api_ess_fields = Vec::new();
	let mut api_ess_fields_types = Vec::new();
	let mut api_opt_fields = Vec::new();
	let mut api_opt_fields_types = Vec::new();

	if let Fields::Named(fields) = api_struct.fields {
		fields.named.into_iter().for_each(|field| {
			api_fields.push(field.clone());

			if let Type::Path(path) = field.ty {
				if &path.path.segments[0].ident.to_string() == "Option" {
					api_opt_fields.push(field.ident);

					if let PathArguments::AngleBracketed(args) = &path.path.segments[0].arguments {
						if let GenericArgument::Type(ty) = &args.args[0] {
							api_opt_fields_types.push(ty.to_owned());
						}
					}
				}
			} else {
				api_ess_fields.push(field.ident);
				api_ess_fields_types.push(field.ty);
			}
		});
	}

	let api_opt_fields_names = api_opt_fields
		.iter()
		.map(|field| {
			field.as_ref().map(|field| field.to_string().trim_start_matches("r#").to_owned())
		})
		.collect::<Vec<_>>();
	let api_name_snake_case = format_ident!("{}", api_name.to_string().to_case(Case::Snake));

	quote::quote! {
		/// GitHub reference(s):
		#[doc = #api_doc]
		#[derive(Debug, Clone, PartialEq, Eq)]
		#api_vis struct #api_name #api_generics {
			#(
				#[allow(missing_docs)]
				#api_fields,
			)*
		}
		impl #api_generics #api_name #api_generics {
			#[doc = concat!("Build a [`", stringify!(#api_name), "`] instance.")]
			#api_vis fn new(#(#api_ess_fields: #api_ess_fields_types,)*) -> Self {
				Self {
					#(#api_ess_fields,)*
					#(#api_opt_fields: None,)*
				}
			}

			#(
				#[doc = concat!(
					"Set a new [`",
					stringify!(#api_ess_fields),
					"`](",
					stringify!(#api_name),
					"#structfield.",
					stringify!(#api_ess_fields),
					")."
				)]
				#api_vis fn #api_ess_fields(mut self, #api_ess_fields: #api_ess_fields_types) -> Self {
					self.#api_ess_fields = #api_ess_fields;

					self
				}
			)*

			#(
				#[doc = concat!(
					"Set a new [`",
					stringify!(#api_opt_fields),
					"`](",
					stringify!(#api_name),
					"#structfield.",
					stringify!(#api_opt_fields),
					")."
				)]
				#api_vis fn #api_opt_fields(mut self, #api_opt_fields: #api_opt_fields_types) -> Self {
					self.#api_opt_fields = Some(#api_opt_fields);

					self
				}
			)*
		}
		impl #api_generics ApiGet #api_generics for #api_name #api_generics {
			const ACCEPT: &'static str = #api_accept;

			fn query_parameters(&self) -> Vec<(&'static str, String)> {
				let mut query_parameters = Vec::new();

				#(
					if let Some(#api_opt_fields) = self.#api_opt_fields {
						query_parameters.push((#api_opt_fields_names, #api_opt_fields.to_string()));
					}
				)*

				query_parameters
			}

			fn api(&self) -> String {
				format!(#api_uri, Self::BASE_URI, #(self.#api_ess_fields,)*)
			}
		}
		#[doc = concat!("Build a [`", stringify!(#api_name), "`] instance.")]
		#api_vis fn #api_name_snake_case #api_generics(#(#api_ess_fields: #api_ess_fields_types,)*) -> #api_name #api_generics {
			#api_name::new(#(#api_ess_fields,)*)
		}
	}
	.into()
}