-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathGraphQLParser.java
More file actions
472 lines (389 loc) · 13.6 KB
/
GraphQLParser.java
File metadata and controls
472 lines (389 loc) · 13.6 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
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
package com.ebay.graphql.parser;
import java.io.File;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.regex.Pattern;
import com.ebay.graphql.model.GraphQLSchema;
import com.ebay.graphql.parser.matcher.GraphQLMatcher;
import com.ebay.graphql.parser.matcher.GraphQLMatcher.LineType;
import com.ebay.graphql.types.GraphQLEnum;
import com.ebay.graphql.types.GraphQLObject;
import com.ebay.graphql.types.GraphQLScalar;
import com.ebay.graphql.types.GraphQLScalar.GraphQLScalarValue;
import com.ebay.graphql.types.GraphQLType;
import com.ebay.graphql.types.FieldKeyValuePair;
public class GraphQLParser {
private static final String IMPLEMENTS_KEYWORD = " implements ";
public GraphQLSchema parseGraphQL(File schemaFile) {
GraphQLSchema completeSchema = new GraphQLSchema();
if (schemaFile == null || !schemaFile.exists()) {
return completeSchema;
}
// Check folder containing schema file for other graphql schema definitions to
// load to complete the schema.
if (schemaFile.isFile()) {
schemaFile = schemaFile.getParentFile();
}
List<File> schemaFiles = getGraphQLSchemaFiles(schemaFile);
GraphQLSchema schema;
for (File file : schemaFiles) {
GraphQLFile graphQLFile = new GraphQLFile(file);
schema = processLinesOfText(graphQLFile);
completeSchema.addSchema(schema);
}
return completeSchema;
}
protected final List<File> getGraphQLSchemaFiles(File directory) {
List<File> graphQLSchemaFiles = new ArrayList<>();
if (!directory.isDirectory()) {
graphQLSchemaFiles.add(directory);
return graphQLSchemaFiles;
}
File[] files = directory.listFiles(new GraphQLFilenameFilter());
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
graphQLSchemaFiles.addAll(getGraphQLSchemaFiles(file));
} else {
graphQLSchemaFiles.add(file);
}
}
}
return graphQLSchemaFiles;
}
protected final GraphQLSchema processLinesOfText(GraphQLFile graphQLFile) {
GraphQLSchema schema = new GraphQLSchema();
String line;
LineType lineType;
@SuppressWarnings("unused")
String lastDescription = null;
try {
while (graphQLFile.hasMoreLines()) {
line = graphQLFile.getCurrentLine();
lineType = GraphQLMatcher.getLineType(line);
switch (lineType) {
case COMMENT:
// Advance, but don't process. We don't process comments.
graphQLFile.getNextLine();
break;
case MULTI_LINE_DESCRIPTION_IN_ONE_LINE:
lastDescription = processSingleLineDescription(graphQLFile);
break;
case MULTI_LINE_DESCRIPTION_OPEN_OR_CLOSE_SIGNATURE:
lastDescription = processMultiLineDescription(graphQLFile);
break;
case SINGLE_LINE_DESCRIPTION:
lastDescription = processSingleLineDescription(graphQLFile);
break;
case SCHEMA:
// Advance - nothing to process.
graphQLFile.getNextLine();
break;
case SCHEMA_QUERY:
processSchemaQuery(graphQLFile, schema);
break;
case SCHEMA_MUTATION:
processSchemaMutation(graphQLFile, schema);
break;
case SCHEMA_SUBSCRIPTION:
processSchemaSubscription(graphQLFile, schema);
break;
case QUERY:
processQuery(graphQLFile, schema);
break;
case MUTATION:
processMutation(graphQLFile, schema);
break;
case SUBSCRIPTION:
processSubscription(graphQLFile, schema);
break;
case OBJECT_DEFINITION:
String objectTypeName = getObjectTypeName(line);
if (objectTypeName.equals(schema.getQueryTypeName())) {
processQuery(graphQLFile, schema);
} else if (objectTypeName.equals(schema.getMutationTypeName())) {
processMutation(graphQLFile, schema);
} else if (objectTypeName.equals(schema.getSubscriptionTypeName())) {
processSubscription(graphQLFile, schema);
} else {
processObject(graphQLFile, schema);
}
break;
case SCALAR_DEFINITION:
processScalar(graphQLFile, schema);
break;
case UNION_DEFINITION:
processUnion(graphQLFile, schema);
break;
case ENUM_DEFINITION:
processEnum(graphQLFile, schema);
break;
case UNMATCHED_TEXT:
default:
System.out.println(String.format("Unmatched line of text [%s] [ln: %d].", line,
graphQLFile.getCurrentLineNumber()));
// Advance - nothing to process.
graphQLFile.getNextLine();
break;
}
}
} catch (ParseException e) {
e.printStackTrace();
}
return schema;
}
/**
* Process single line description. Can be one or three " wrapping the line.
*
* @param graphQLFile GraphQL file to process.
* @return Description.
*/
protected final String processSingleLineDescription(GraphQLFile graphQLFile) {
String line = graphQLFile.getCurrentLineAndThenAdvance();
line = line.replaceFirst("^\"*", "");
line = line.replaceFirst("\"*$", "");
return line.trim();
}
/**
* Process multiple line description. Turn it into a single line string.
*
* @param graphQLFile GraphQL file to process.
* @return Multi-line description as a single line stirng.
*/
protected final String processMultiLineDescription(GraphQLFile graphQLFile) {
StringBuilder builder = new StringBuilder();
String line = graphQLFile.getCurrentLine();
line = line.replaceFirst("^\"*", "");
builder.append(line);
while (graphQLFile.hasMoreLines()) {
line = graphQLFile.getNextLine().trim();
if (GraphQLMatcher.getLineType(line) == LineType.MULTI_LINE_DESCRIPTION_OPEN_OR_CLOSE_SIGNATURE) {
line = line.replaceFirst("\"*$", "").trim();
if (builder.length() > 0 && !line.isEmpty()) {
builder.append(" ");
}
builder.append(line);
graphQLFile.getNextLine();
break;
}
if (builder.length() > 0) {
builder.append(" ");
}
builder.append(line);
}
return builder.toString();
}
protected final void processSchemaQuery(GraphQLFile graphQLFile, GraphQLSchema schema) {
String line = graphQLFile.getCurrentLineAndThenAdvance();
line = line.substring(line.indexOf(":") + 1).trim();
schema.setQueryTypeName(line);
}
protected final void processQuery(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
Optional<FieldKeyValuePair> kvp;
String line = graphQLFile.getCurrentLine();
while (GraphQLMatcher.getLineType(line) != LineType.CLOSING_CURLY_BRACE && line != null) {
kvp = extractOperationApi(graphQLFile);
if (!kvp.isPresent()) {
continue;
}
schema.addQuery(kvp.get().getKey(), kvp.get().getValue());
line = graphQLFile.peekNextLine();
}
}
protected final void processSchemaMutation(GraphQLFile graphQLFile, GraphQLSchema schema) {
String line = graphQLFile.getCurrentLineAndThenAdvance();
line = line.substring(line.indexOf(":") + 1).trim();
schema.setMutationTypeName(line);
}
protected final void processMutation(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
Optional<FieldKeyValuePair> kvp;
String line = graphQLFile.getCurrentLine();
while (GraphQLMatcher.getLineType(line) != LineType.CLOSING_CURLY_BRACE && line != null) {
kvp = extractOperationApi(graphQLFile);
if (!kvp.isPresent()) {
line = graphQLFile.peekNextLine();
continue;
}
schema.addMutation(kvp.get().getKey(), kvp.get().getValue());
line = graphQLFile.peekNextLine();
}
}
protected final void processSchemaSubscription(GraphQLFile graphQLFile, GraphQLSchema schema) {
String line = graphQLFile.getCurrentLineAndThenAdvance();
line = line.substring(line.indexOf(":") + 1).trim();
schema.setSubscriptionTypeName(line);
}
protected final void processSubscription(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
Optional<FieldKeyValuePair> kvp;
String line = graphQLFile.getCurrentLine();
while (GraphQLMatcher.getLineType(line) != LineType.CLOSING_CURLY_BRACE && line != null) {
kvp = extractOperationApi(graphQLFile);
if (!kvp.isPresent()) {
continue;
}
schema.addSubscription(kvp.get().getKey(), kvp.get().getValue());
line = graphQLFile.peekNextLine();
}
}
protected final String getObjectTypeName(String currentLine) {
currentLine = currentLine.replaceFirst("^\\s*type\\s", "");
currentLine = currentLine.replace("{", "");
currentLine = currentLine.replaceAll("(@.*)\\s*$", "");
// Drop the interface if it exists
if (currentLine.contains(IMPLEMENTS_KEYWORD)) {
currentLine = currentLine.substring(0, currentLine.indexOf(IMPLEMENTS_KEYWORD));
}
currentLine = currentLine.trim();
return currentLine;
}
protected final void processObject(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
String objectName = getObjectTypeName(graphQLFile.getCurrentLine());
GraphQLObject graphQLObject = new GraphQLObject();
FieldKeyValuePair kvp;
String line;
boolean nullable = true;
while (GraphQLMatcher.getLineType(line = graphQLFile.getNextLine()) != LineType.CLOSING_CURLY_BRACE
&& line != null) {
nullable = true;
if (canIgnoreLine(line)) {
continue;
}
line = line.trim();
if (line.contains("@")) {
line = line.replaceAll("(@.*)\\s*$", "");
}
if (line.endsWith("!")) {
nullable = false;
line = line.substring(0, line.length() - 1);
}
line = line.trim();
kvp = new FieldKeyValuePair(line);
GraphQLType value = kvp.getValue();
if (!nullable) {
value.makeNonNullable();
}
graphQLObject.addField(kvp.getKey(), value);
}
schema.addType(objectName, graphQLObject);
}
protected final void processScalar(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
String line = graphQLFile.getCurrentLineAndThenAdvance();
line = line.replaceFirst("^^\\s*scalar", "").replaceFirst("@specifiedBy.*$", "").trim();
schema.addType(line, new GraphQLScalar(GraphQLScalarValue.STRING));
}
protected final void processUnion(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
/*
* Unions may span multiple lines. Handle both cases.
*
* 1) union Food = Apple | Banana | Pear
*
* 2) union Food = | Apple | Banana | Pear
*/
List<String> unionTypes = new ArrayList<>();
String unionName = null;
String line = graphQLFile.getCurrentLine();
line = line.replaceFirst("union", "");
String[] union = line.split("=");
if (union.length > 0) {
unionName = union[0].trim();
}
if (union.length == 2) {
union = union[1].split("\\|");
for (String u : union) {
unionTypes.add(u.trim());
}
}
while (GraphQLMatcher.getLineType(line = graphQLFile.getNextLine()) == LineType.UNION_MEMBER) {
line = line.replace("|", "").trim();
unionTypes.add(line);
}
if (unionName != null) {
schema.addUnion(unionName, unionTypes);
}
}
protected final void processEnum(GraphQLFile graphQLFile, GraphQLSchema schema) throws ParseException {
String enumName = graphQLFile.getCurrentLine();
enumName = enumName.replace("enum", "");
enumName = enumName.replace("{", "");
enumName = enumName.trim();
GraphQLEnum graphQLEnum = new GraphQLEnum();
String line;
while (GraphQLMatcher.getLineType(line = graphQLFile.getNextLine()) != LineType.CLOSING_CURLY_BRACE
&& line != null) {
line = line.trim();
if (!Pattern.matches("^([A-Za-z0-9_]*)$", line)) {
continue;
}
graphQLEnum.addEnumValue(line);
}
schema.addType(enumName, graphQLEnum);
}
protected final Optional<FieldKeyValuePair> extractOperationApi(GraphQLFile graphQLFile) throws ParseException {
/*
* Operation APIs can take on two forms:
*
* 1) translate(fromLanguage: Language, toLanguage: Language, text: String):
* String 2) translate( fromLanguage: Language toLanguage: Language text: String
* ): String
*/
StringBuilder queryBuilder = new StringBuilder();
LineType lineType;
String line;
boolean insideParameterList = false;
while (GraphQLMatcher.getLineType(line = graphQLFile.getNextLine()) != LineType.CLOSING_CURLY_BRACE
&& line != null) {
// Skip the line that is the opening definition for a schema definition, and empty lines.
if (line.contains("{") || line.isEmpty()) {
continue;
}
lineType = GraphQLMatcher.getLineType(line);
if (lineType == LineType.COMMENT || lineType == LineType.SINGLE_LINE_DESCRIPTION
|| lineType == LineType.MULTI_LINE_DESCRIPTION_IN_ONE_LINE) {
continue;
} else if (lineType == LineType.MULTI_LINE_DESCRIPTION_OPEN_OR_CLOSE_SIGNATURE) {
while (GraphQLMatcher.getLineType(
line = graphQLFile.getNextLine()) != LineType.MULTI_LINE_DESCRIPTION_OPEN_OR_CLOSE_SIGNATURE) {
// Churn through the multi-line description until we get to the end signature.
; // NOPMD - ignore this
}
continue;
}
if (line.contains("(")) {
insideParameterList = true;
}
// DO NOT combine this with the above check as an 'else if'.
// This allows us to handle the case where the parameter list is defined in a
// single line.
if (line.contains(")")) {
insideParameterList = false;
}
if (queryBuilder.length() > 0 && !line.isEmpty()) {
queryBuilder.append(" ");
}
queryBuilder.append(line.trim());
// When we find a line with a ':' outside the parameter set we have found the
// type definition and can consider the operation API parsed.
if (!insideParameterList && line.contains(":")) {
break;
}
}
if (queryBuilder.length() == 0) {
return Optional.empty();
}
return Optional.of(new FieldKeyValuePair(queryBuilder.toString()));
}
private boolean canIgnoreLine(String line) {
switch (GraphQLMatcher.getLineType(line)) {
case COMMENT:
case SINGLE_LINE_DESCRIPTION:
case MULTI_LINE_DESCRIPTION_IN_ONE_LINE:
case MULTI_LINE_DESCRIPTION_OPEN_OR_CLOSE_SIGNATURE:
case UNMATCHED_TEXT:
return true;
default:
return false;
}
}
}