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

Add basic struct generation #1

Merged
merged 6 commits into from
Jan 14, 2024
Merged
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
/target
/output
75 changes: 75 additions & 0 deletions Cargo.lock

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

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,5 @@ license = "MIT"

[dependencies]
clap = {version = "4.4.2", features = ["derive"]}
serde = { version = "1.0.195", features = ["derive"] }
serde_yaml = "0.9.30"
210 changes: 210 additions & 0 deletions src/bindgen.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,210 @@
use serde::Deserialize;
use serde_yaml::{Number, Value};
use std::{collections::HashMap, fs::File, io::Write};

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Schema {
#[serde(rename = "openapi")]
open_api: String,
info: SchemaInfo,
paths: HashMap<String, Path>,
components: ComponentSchemas,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct SchemaInfo {
title: String,
version: String,
license: HashMap<String, String>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Path {
get: Option<PathOp>,
post: Option<PathOp>,
put: Option<PathOp>,
patch: Option<PathOp>,
delete: Option<PathOp>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct PathOp {
#[serde(rename = "operationId")]
operation_id: String,
description: String,
parameters: Option<Vec<Response>>,
responses: HashMap<String, Response>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Response {}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct ComponentSchemas {
schemas: HashMap<String, Component>,
#[serde(rename = "securitySchemes")]
security_schemes: HashMap<String, Component>,
}

#[derive(Debug, Deserialize)]
#[allow(dead_code)]
struct Component {
#[serde(rename = "type")]
typ: String,
description: Option<String>,
#[serde(default)]
properties: HashMap<String, Property>,
#[serde(default)]
required: Vec<String>,
}

#[derive(Debug, Deserialize, Default)]
#[allow(dead_code)]
struct Property {
#[serde(rename = "type")]
typ: Option<String>,
#[serde(rename = "readOnly")]
read_only: Option<bool>,
format: Option<String>,
description: Option<String>,
#[serde(rename = "minLength")]
min_length: Option<Number>,
#[serde(rename = "maxLength")]
max_length: Option<Number>,
#[serde(rename = "enum")]
enumeration: Option<Vec<String>>,
nullable: Option<bool>,
properties: Option<Value>,
items: Option<Value>,
#[serde(rename = "allOf")]
all_of: Option<Vec<Value>>,
}

/// Makes a comment out of a given string.
fn make_comment(input: String, indent: usize) -> String {
return input
.split('\n')
.map(|x| format!("{}/// {}\n", "\t".repeat(indent), x))
.collect::<Vec<_>>()
.concat();
}

fn get_inner_type(items: Value) -> String {
// Get inner type of the array.
let inner_type = match items.get("$ref") {
// Struct type
Some(y) => y.as_str().unwrap().replace("#/components/schemas/", ""),
// Normal type
None => match items.get("type") {
Some(y) => match y.as_str().unwrap() {
"integer" => "i64".to_owned(),
"number" => "f64".to_owned(),
"string" => match items.get("format") {
Some(x) => match x.as_str().unwrap() {
"uri" => "Uri".to_owned(),
"date-time" => "DateTime".to_owned(),
_ => "String".to_owned(),
},
None => "String".to_owned(),
},
"boolean" => "bool".to_owned(),
"object" => "Json".to_owned(),
"array" => get_inner_type(match items.get("items") {
Some(z) => z.clone(),
None => panic!("array is missing items section!"),
}),
_ => panic!("unhandled type!"),
},
// We don't know what this is so assume a JSON object.
None => "Json".to_owned(),
},
};
let fmt = format!("Vec<{inner_type}>");
fmt.clone()
}

/// Generates the Rust bindings from a file.
pub fn gen(input_path: impl AsRef<std::path::Path>) {
// Parse the schema.
let input = std::fs::read_to_string(input_path).unwrap();
let yaml: Schema = serde_yaml::from_str(&input).unwrap();

// Generate output folder.
_ = std::fs::create_dir("output/");

// Create and open the output file for structs.
let mut types_file = File::create("output/types.rs").unwrap();

// For every struct.
for (name, comp) in &yaml.components.schemas {
// Keep a record of all written fields for a constructor.
let mut fields = Vec::new();
// Prepend slashes to all lines in the documentation string.
let desc = match comp.description.clone() {
Some(d) => make_comment(d, 0),
None => String::new(),
};
// Write description.
types_file.write_all(desc.as_bytes()).unwrap();
// Write name.
types_file.write_all(b"pub struct ").unwrap();
types_file.write_all(name.as_bytes()).unwrap();
types_file.write_all(b" {\n").unwrap();
// For every struct field.
for (prop_name, prop) in &comp.properties {
// Get the type of this field from YAML.
let yaml_type = match prop.typ.as_ref() {
Some(val) => val.as_str(),
None => continue,
};

let mut type_result = match yaml_type {
// "string" can mean either a plain or formatted string or an enum declaration.
"string" => match &prop.format {
Some(x) => match x.as_str() {
"uri" => "Uri".to_owned(),
"date-time" => "DateTime".to_owned(),
_ => "String".to_owned(),
},
None => "String".to_owned(),
},
"integer" => "i64".to_owned(),
"number" => "f64".to_owned(),
"boolean" => "bool".to_owned(),
"array" => get_inner_type(prop.items.as_ref().unwrap().clone()),
"object" => "Json".to_owned(),
_ => todo!(),
};

// Wrap type in an Option<T> if nullable.
if prop.nullable.unwrap_or(false) {
type_result = format!("Option<{type_result}>");
}

// Escape field names if they are Rust keywords.
let name = match prop_name.as_str() {
"type" => "r#type",
_ => prop_name,
};

// Prepend slashes to all lines in the documentation string.
if let Some(d) = prop.description.as_ref() {
types_file
.write_all(make_comment(d.clone(), 1).as_bytes())
.unwrap();
};
// Write the field to file.
types_file
.write_all(format!("\t{}: {},\n", name, type_result).as_bytes())
.unwrap();
fields.push((name, type_result));
}
types_file.write_all(b"}\n\n").unwrap();
}
}
13 changes: 9 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
mod bindgen;

use clap::Parser;

/// The argument that Thanix expects to get given via the cli.
#[derive(Parser, Debug)]
#[command(author, version, about, long_about=None)]
struct Args {
/// Path to the input yaml you want to use.
/// Path to a YAML schema file.
#[arg(short, long)]
input_file: Option<String>
input_file: Option<String>,
}

fn main() {

let args: Args = Args::parse();

let ascii_art = r#"
Expand All @@ -24,10 +25,14 @@ fn main() {

// Welcome Message
println!(
"{} \n(c) The Nezara Project. (github.com/The-Nezara/Project)\n
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I knew I had a typo in there somewhere!

"{} \n(c) The Nazara Project. (github.com/The-Nazara-Project)\n
Licensed under the terms of the MIT-License.\n\
Check github.com/The-Nazara-Project/Thanix/LICENSE for more info.\n",
ascii_art
);

match args.input_file {
Some(file) => bindgen::gen(file),
None => println!("Error: You need to provide a YAML schema to generate from."),
}
}
Loading