-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcppClassGenerator.go
More file actions
309 lines (286 loc) · 10.5 KB
/
cppClassGenerator.go
File metadata and controls
309 lines (286 loc) · 10.5 KB
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
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
package OAPIClientGenerator
import (
"fmt"
"os"
"strings"
)
const headerImports = `#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "Runtime/Online/HTTP/Public/Http.h"
#include "Runtime/JsonUtilities/Public/JsonObjectConverter.h"
#include "%s.generated.h"
`
const headerBase = `
UCLASS()
class %s %s : public AActor
{
GENERATED_BODY()
public:
FHttpModule* Http;
// Sets default values for this actor's properties
%s();
`
const headerEnd = `
};
`
const classInclude = `
#include "%s"
`
const classBase = `
%s::%s()
{
Http = &FHttpModule::Get();
}
`
const requestFuncHeader = `
void %s::%s(%s)
{
`
const requestFuncBody = ` TSharedRef<IHttpRequest, ESPMode::ThreadSafe> Request = Http->CreateRequest();
Request->OnProcessRequestComplete().BindUObject(this, &%s::%s);
//This is the url on which to process the request
Request->SetURL("%s");
Request->SetVerb("%s");
Request->SetHeader(TEXT("User-Agent"), "X-UnrealEngine-Agent");
Request->SetHeader("Content-Type", TEXT("application/json"));
`
const requestParameter = `
TSharedPtr<FJsonObject> %sJsonObject = FJsonObjectConverter::UStructToJsonObject<%s>(%s);
FString %sContentString;
TSharedRef< TJsonWriter<> > %sWriter = TJsonWriterFactory<>::Create(&%sContentString);
FJsonSerializer::Serialize(%sJsonObject.ToSharedRef(), %sWriter);
Request->SetContentAsString(%sContentString);
`
const requestFuncEnd = `
Request->ProcessRequest();
}`
const responseFuncBody = `
void %s::%s(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful)
{
`
const responseFuncBodyEnd = `
}
`
// int32 recievedInt = JsonObject->GetIntegerField("customInt");
const responseFuncArguments = ` result.%s = JsonObject->Get%sField("%s");
`
const responseCheck = ` if (Response->GetResponseCode() == %s) {
`
const responseCheckElse = ` else {
`
const responseCheckEnd = ` }
`
const resultCreation = ` %s result;
`
const resultArrayCreation = ` TArray<%s> result;
`
const responseSingleObject = ` TSharedPtr<FJsonObject> JsonObject;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonObject))
{
`
const responseSingleObjectEnd = ` }
`
const responseArray = ` TArray<TSharedPtr<FJsonValue>> JsonArray;
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
if (FJsonSerializer::Deserialize(Reader, JsonArray)) {
for (int i = 0; i < JsonArray.Num(); i++) {
`
const responseArrayLoopEnd = ` }
`
const responseArrayEnd = ` }
`
const responseFuncCreateItem = ` %s Item;
`
const responseFuncArrayItems = ` Item.%s = JsonArray[i]->AsObject()->Get%sField("%s");
`
const responseFuncCreateItemEnd = ` result.Add(Item);
`
func withUEClassPrefix(name string) string {
return "A" + name
}
func GenerateHeader(projectName, className, exportPath string, oapi OAPI) error {
headerContent := fmt.Sprintf(headerImports, className)
// generate definitions
for definitionName, definition := range oapi.Definitions {
cppStructure := definition.generateCppStructure(definitionName)
if cppStructure != "" {
headerContent += cppStructure
}
}
headerContent += fmt.Sprintf(headerBase, strings.ToUpper(projectName)+"_API", withUEClassPrefix(className), withUEClassPrefix(className))
// generate functions
for path, methods := range oapi.Paths {
for method, endpoint := range methods {
funcName, pathArgs := getFuncName(path, method)
parameters := getParameters(endpoint.Parameters)
headerContent += "\n\tUFUNCTION(BlueprintCallable, Category = OAPI)"
headerContent += "\n\tvoid " + funcName + "(" + strings.Join(append(pathArgs, parameters...), ",") + ");" //todo add params
headerContent += "\n\tvoid " + getResponseFuncName(funcName) + "(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful);" //todo return values?
for responseCode, response := range endpoint.Responses {
definitionName := refToDefName(response.Schema.Ref)
definition := oapi.Definitions[definitionName]
if responseCode == "default" {
responseCode = "Error"
}
headerContent += "\n\tUFUNCTION(BlueprintImplementableEvent, Category = OAPI)"
switch {
case definitionName == "":
headerContent += "\n\tvoid " + getResponseFuncName(funcName) + responseCode + "();"
case definition.Type == "array":
headerContent += "\n\tvoid " + getResponseFuncName(funcName) + responseCode + "(const TArray<" + withUEStructPrefix(refToDefName(definition.Items.Ref)) + "> &Result);"
case definition.Type == "object":
headerContent += "\n\tvoid " + getResponseFuncName(funcName) + responseCode + "(" + withUEStructPrefix(definitionName) + " Result);"
}
}
}
}
headerContent += `
UFUNCTION(BlueprintImplementableEvent, Category = OAPI)
void OnOapiError(const FString &text);`
headerContent += headerEnd
return os.WriteFile(exportPath+className+".h", []byte(headerContent), 0644)
}
func getParameters(parameters []OAPIParameter) []string {
result := []string{}
for _, parameter := range parameters {
if parameter.Ref != "" {
defName := refToDefName(parameter.Ref)
name := parameter.Name
if name == "" {
name = strings.ToLower(defName)
}
result = append(result, withUEStructPrefix(defName)+" "+name)
}
}
return result
}
func getFuncName(path, method string) (string, []string) {
pathArgs := []string{}
pathCrumbs := strings.Split(path, "/")
funcNameParts := []string{}
for i := 0; i < len(pathCrumbs); i++ {
if pathCrumbs[i] == "" {
continue
}
if strings.HasPrefix(pathCrumbs[i], "{") && strings.HasSuffix(pathCrumbs[i], "}") {
pathArg := strings.TrimSuffix(strings.TrimPrefix(pathCrumbs[i], "{"), "}")
pathArgs = append(pathArgs, "FString "+pathArg)
funcNameParts = append(funcNameParts, "By"+strings.Title(pathArg))
continue
}
funcNameParts = append(funcNameParts, strings.Title(pathCrumbs[i]))
}
return strings.Title(method) + strings.Join(funcNameParts, ""), pathArgs
}
func getResponseFuncName(funcName string) string {
return "On" + funcName + "Response"
}
func GenerateClass(className, exportPath string, oapi OAPI) error {
classContent := fmt.Sprintf(classInclude, className+".h")
// generate constructor
classContent += fmt.Sprintf(classBase, withUEClassPrefix(className), withUEClassPrefix(className))
// generate functions
for path, methods := range oapi.Paths {
for method, endpoint := range methods {
funcName, pathArgs := getFuncName(path, method)
parameters := getParameters(endpoint.Parameters)
responseFuncName := getResponseFuncName(funcName)
url := getUrlWithParameters(oapi.Host, oapi.BasePath, path)
classContent += fmt.Sprintf(requestFuncHeader, withUEClassPrefix(className), funcName, strings.Join(append(pathArgs, parameters...), ","))
classContent += fmt.Sprintf(requestFuncBody, withUEClassPrefix(className), responseFuncName, url, method)
for _, parameter := range parameters {
split := strings.Split(parameter, " ")
parameterName := split[1]
parameterType := split[0]
classContent += fmt.Sprintf(requestParameter, parameterName, parameterType, parameterName, parameterName, parameterName, parameterName, parameterName, parameterName, parameterName)
}
classContent += fmt.Sprint(requestFuncEnd)
classContent += fmt.Sprintf(responseFuncBody, withUEClassPrefix(className), responseFuncName)
var defaultResponse *OAPIResponse
for responseCode, response := range endpoint.Responses {
if responseCode == "default" {
defaultResponse = &response
continue
}
classContent += fmt.Sprintf(responseCheck, responseCode)
classContent += getResponsePart(responseCode, responseFuncName, response, oapi)
classContent += fmt.Sprint(responseCheckEnd)
}
if defaultResponse != nil {
classContent += fmt.Sprint(responseCheckElse)
classContent += getResponsePart("default", responseFuncName, *defaultResponse, oapi)
classContent += fmt.Sprint(responseCheckEnd)
classContent += fmt.Sprintf(` OnOapiError("` + funcName + ` error");`)
}
classContent += responseFuncBodyEnd
}
}
return os.WriteFile(exportPath+className+".cpp", []byte(classContent), 0644)
}
func getUrlWithParameters(host, basePath, path string) string {
url := host + basePath + path
split := strings.Split(url, "/")
for i := 0; i < len(split); i++ {
if strings.HasPrefix(split[i], "{") && strings.HasSuffix(split[i], "}") {
split[i] = `"+` + strings.TrimSuffix(strings.TrimPrefix(split[i], "{"), "}") + `+"`
}
}
return strings.Join(split, "/")
}
func refToDefName(ref string) string {
return strings.TrimPrefix(ref, "#/definitions/")
}
func getResponsePart(responseCode, responseFuncName string, response OAPIResponse, oapi OAPI) string {
result := ""
if responseCode == "default" {
responseCode = "Error"
}
definitionName := refToDefName(response.Schema.Ref)
if definitionName != "" {
if definition, ok := oapi.Definitions[definitionName]; ok {
if definition.Type == "object" {
result += fmt.Sprintf(resultCreation, withUEStructPrefix(definitionName))
result += fmt.Sprint(responseSingleObject)
for propertyName, property := range definition.Properties {
result += fmt.Sprintf(responseFuncArguments, strings.Title(propertyName), getJsonType(getCppType(property.Type, property.Format)), propertyName) //todo arguments
}
result += ` ` + responseFuncName + responseCode + `(result);`
result += ` ` + "return;"
result += fmt.Sprint(responseSingleObjectEnd)
} else if definition.Type == "array" {
itemName := refToDefName(definition.Items.Ref)
result += fmt.Sprintf(resultArrayCreation, withUEStructPrefix(itemName))
result += fmt.Sprint(responseArray)
var item = oapi.Definitions[itemName]
result += fmt.Sprintf(responseFuncCreateItem, withUEStructPrefix(itemName))
for propertyName, property := range item.Properties {
result += fmt.Sprintf(responseFuncArrayItems, strings.Title(propertyName), getJsonType(getCppType(property.Type, property.Format)), propertyName) //todo arguments
}
result += fmt.Sprint(responseFuncCreateItemEnd)
result += fmt.Sprint(responseArrayLoopEnd)
result += ` ` + responseFuncName + responseCode + `(result);`
result += ` ` + "return;"
result += fmt.Sprint(responseArrayEnd)
}
} else {
//error
}
} else {
result += ` ` + responseFuncName + responseCode + `();
`
}
return result
}
func getJsonType(cppType string) string {
switch cppType {
case "int32":
fallthrough
case "int":
return "Integer"
case "FString":
return "String"
}
return ""
}