summaryrefslogtreecommitdiffstats
path: root/generator/src/main.rs
blob: 60588077d6e2809e5341830d29be9542c8a62cca (plain)
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
use std::ffi::{OsStr, OsString};

mod methods;
mod openapi;
mod structs;

use heck::ToSnakeCase;
use openapi::*;

fn main() -> eyre::Result<()> {
    let spec = get_spec()?;
    let mut s = String::new();
    s.push_str(&methods::create_methods(&spec)?);
    s.push_str(&structs::create_structs(&spec)?);
    save_generated(&s)?;
    Ok(())
}

fn get_spec() -> eyre::Result<OpenApiV2> {
    let path = std::env::var_os("FORGEJO_API_SPEC_PATH")
        .unwrap_or_else(|| OsString::from("./swagger.v1.json"));
    let file = std::fs::read(path)?;
    let spec = serde_json::from_slice::<OpenApiV2>(&file)?;
    spec.validate()?;
    Ok(spec)
}

fn save_generated(contents: &str) -> eyre::Result<()> {
    let path = std::env::var_os("FORGEJO_API_GENERATED_PATH")
        .unwrap_or_else(|| OsString::from("./src/generated.rs"));
    std::fs::write(path.as_os_str(), contents)?;
    run_rustfmt_on(path.as_os_str());
    Ok(())
}

fn run_rustfmt_on(path: &OsStr) {
    let mut rustfmt = std::process::Command::new("rustfmt");

    rustfmt.arg(path);
    rustfmt.args(["--edition", "2021"]);

    if let Err(e) = rustfmt.status() {
        println!("Tried to format {path:?}, but failed to do so! :(");
        println!("Error:\n{e}");
    }
}

fn schema_ref_type_name(spec: &OpenApiV2, schema: &MaybeRef<Schema>) -> eyre::Result<String> {
    let (name, schema) = deref_definition(spec, &schema)?;
    schema_type_name(spec, name, schema)
}

fn schema_type_name(
    spec: &OpenApiV2,
    definition_name: Option<&str>,
    schema: &Schema,
) -> eyre::Result<String> {
    if let Some(ty) = &schema._type {
        match ty {
            SchemaType::One(prim) => {
                let name = match prim {
                    Primitive::String => match schema.format.as_deref() {
                        Some("date") => "time::Date",
                        Some("date-time") => "time::OffsetDateTime",
                        _ => "String",
                    }
                    .to_string(),
                    Primitive::Number => match schema.format.as_deref() {
                        Some("float") => "f32",
                        Some("double") => "f64",
                        _ => "f64",
                    }
                    .to_string(),
                    Primitive::Integer => match schema.format.as_deref() {
                        Some("int32") => "u32",
                        Some("int64") => "u64",
                        _ => "u32",
                    }
                    .to_string(),
                    Primitive::Boolean => "bool".to_string(),
                    Primitive::Array => {
                        let item_name = match &schema.items {
                            Some(item_schema) => schema_ref_type_name(spec, item_schema)?,
                            None => "serde_json::Value".into(),
                        };
                        format!("Vec<{item_name}>")
                    }
                    Primitive::Null => "()".to_string(),
                    Primitive::Object => {
                        match (&schema.title, definition_name) {
                            // Some of the titles are actually descriptions; not sure why
                            // Checking for a space filters that out
                            (Some(title), _) if !title.contains(' ') => title.to_string(),
                            (_, Some(definition_name)) => definition_name.to_string(),
                            (_, None) => "serde_json::Map<String, serde_json::Value>".to_string(),
                        }
                    }
                };
                Ok(name.to_owned())
            }
            SchemaType::List(_) => todo!(),
        }
    } else {
        Ok("()".into())
    }
}

fn deref_definition<'a>(
    spec: &'a OpenApiV2,
    r: &'a MaybeRef<Schema>,
) -> eyre::Result<(Option<&'a str>, &'a Schema)> {
    let r = match r {
        MaybeRef::Value { value } => return Ok((None, value)),
        MaybeRef::Ref { _ref } => _ref,
    };
    let name = r
        .strip_prefix("#/definitions/")
        .ok_or_else(|| eyre::eyre!("invalid definition reference"))?;
    let global_definitions = spec
        .definitions
        .as_ref()
        .ok_or_else(|| eyre::eyre!("no global definitions"))?;
    let definition = global_definitions
        .get(name)
        .ok_or_else(|| eyre::eyre!("referenced definition does not exist"))?;
    Ok((Some(name), definition))
}

fn schema_is_string(spec: &OpenApiV2, schema: &MaybeRef<Schema>) -> eyre::Result<bool> {
    let (_, schema) = deref_definition(spec, schema)?;
    let is_str = match schema._type {
        Some(SchemaType::One(Primitive::String)) => true,
        _ => false,
    };
    Ok(is_str)
}

fn sanitize_ident(s: &str) -> String {
    let mut s = s.to_snake_case();
    let keywords = [
        "as",
        "break",
        "const",
        "continue",
        "crate",
        "else",
        "enum",
        "extern",
        "false",
        "fn",
        "for",
        "if",
        "impl",
        "in",
        "let",
        "loop",
        "match",
        "mod",
        "move",
        "mut",
        "pub",
        "ref",
        "return",
        "self",
        "Self",
        "static",
        "struct",
        "super",
        "trait",
        "true",
        "type",
        "unsafe",
        "use",
        "where",
        "while",
        "abstract",
        "become",
        "box",
        "do",
        "final",
        "macro",
        "override",
        "priv",
        "typeof",
        "unsized",
        "virtual",
        "yield",
        "async",
        "await",
        "dyn",
        "try",
        "macro_rules",
        "union",
    ];
    if s == "self" {
        s = "this".into();
    }
    if keywords.contains(&&*s) {
        s.insert_str(0, "r#");
    }
    s
}