forked from OpenAPITools/openapi-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
HaskellHttpClientCodegen.java
1421 lines (1218 loc) · 58.4 KB
/
HaskellHttpClientCodegen.java
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech)
* Copyright 2018 SmartBear Software
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openapitools.codegen.languages;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.ArraySchema;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.openapitools.codegen.*;
import org.openapitools.codegen.utils.ModelUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import static org.openapitools.codegen.utils.StringUtils.camelize;
import static org.openapitools.codegen.utils.StringUtils.underscore;
public class HaskellHttpClientCodegen extends DefaultCodegen implements CodegenConfig {
private static final Logger LOGGER = LoggerFactory.getLogger(HaskellHttpClientCodegen.class);
// source folder where to write the files
protected String sourceFolder = "lib";
protected String defaultDateFormat = "%Y-%m-%d";
protected String defaultCabalVersion = "0.1.0.0";
protected String modulePath = null;
protected Boolean useKatip = true;
protected Boolean allowNonUniqueOperationIds = false;
protected Boolean genEnums = true;
// CLI PROPS
public static final String PROP_ALLOW_FROMJSON_NULLS = "allowFromJsonNulls";
public static final String PROP_ALLOW_NONUNIQUE_OPERATION_IDS = "allowNonUniqueOperationIds";
public static final String PROP_ALLOW_TOJSON_NULLS = "allowToJsonNulls";
public static final String PROP_BASE_MODULE = "baseModule";
public static final String PROP_CABAL_PACKAGE = "cabalPackage";
public static final String PROP_CABAL_VERSION = "cabalVersion";
public static final String PROP_CONFIG_TYPE = "configType";
public static final String PROP_DATETIME_FORMAT = "dateTimeFormat";
public static final String PROP_CUSTOM_TEST_INSTANCE_MODULE = "customTestInstanceModule";
public static final String PROP_DATE_FORMAT = "dateFormat";
public static final String PROP_GENERATE_ENUMS = "generateEnums";
public static final String PROP_GENERATE_FORM_URLENCODED_INSTANCES = "generateFormUrlEncodedInstances";
public static final String PROP_GENERATE_LENSES = "generateLenses";
public static final String PROP_GENERATE_MODEL_CONSTRUCTORS = "generateModelConstructors";
public static final String PROP_INLINE_MIME_TYPES = "inlineMimeTypes";
public static final String PROP_MODEL_DERIVING = "modelDeriving";
public static final String PROP_REQUEST_TYPE = "requestType";
public static final String PROP_STRICT_FIELDS = "strictFields";
public static final String PROP_USE_KATIP = "useKatip";
// protected String MODEL_IMPORTS = "modelImports";
// protected String MODEL_EXTENSIONS = "modelExtensions";
private static final Pattern LEADING_UNDERSCORE = Pattern.compile("^_+");
static final String MEDIA_TYPE = "mediaType";
static final String MIME_NO_CONTENT = "MimeNoContent";
static final String MIME_ANY = "MimeAny";
// vendor extensions
static final String X_ALL_UNIQUE_PARAMS = "x-allUniqueParams";
static final String X_ALL_IMPORT_MAPPINGS = "x-allImportMappings";
static final String X_ALL_UNIQUE_IMPORT_PATHS = "x-allUniqueImportPaths";
static final String X_COLLECTION_FORMAT = "x-collectionFormat";
static final String X_HADDOCK_PATH = "x-haddockPath";
static final String X_HAS_BODY_OR_FORM_PARAM = "x-hasBodyOrFormParam";
static final String X_HAS_ENUM_SECTION = "x-hasEnumSection";
static final String X_HAS_IMPORT_MAPPINGS = "x-hasImportMappings";
static final String X_HAS_MIME_FORM_URL_ENCODED = "x-hasMimeFormUrlEncoded";
static final String X_HAS_NEW_TAG = "x-hasNewTag";
static final String X_HAS_OPTIONAL_PARAMS = "x-hasOptionalParams";
static final String X_HAS_UNKNOWN_MIME_TYPES = "x-hasUnknownMimeTypes";
static final String X_HAS_UNKNOWN_RETURN = "x-hasUnknownReturn";
static final String X_INLINE_CONTENT_TYPE = "x-inlineContentType";
static final String X_INLINE_ACCEPT = "x-inlineAccept";
static final String X_IS_BODY_OR_FORM_PARAM = "x-isBodyOrFormParam";
static final String X_IS_BODY_PARAM = "x-isBodyParam";
static final String X_IS_MAYBE_VALUE = "x-isMaybeValue";
static final String X_MEDIA_DATA_TYPE = "x-mediaDataType";
static final String X_DATA_TYPE = "x-dataType";
static final String X_ENUM_VALUES = "x-enumValues";
static final String X_MEDIA_IS_JSON = "x-mediaIsJson";
static final String X_MEDIA_IS_WILDCARD = "x-mediaIsWildcard";
static final String X_MIME_TYPES = "x-mimeTypes";
static final String X_OPERATION_TYPE = "x-operationType";
static final String X_PARAM_NAME_TYPE = "x-paramNameType";
static final String X_PATH = "x-path";
static final String X_RETURN_TYPE = "x-returnType";
static final String X_STRICT_FIELDS = "x-strictFields";
static final String X_UNKNOWN_MIME_TYPES = "x-unknownMimeTypes";
static final String X_USE_KATIP = "x-useKatip";
static final String X_ALLOW_NONUNIQUE_OPERATION_IDS = "x-allowNonUniqueOperationIds";
static final String X_NEWTYPE = "x-newtype";
static final String X_ENUM = "x-enum";
protected ArrayList<Map<String, String>> unknownMimeTypes = new ArrayList<>();
protected Map<String, Map<String, Object>> uniqueParamNameTypes = new HashMap<>();
protected Map<String, Set<String>> modelMimeTypes = new HashMap<>();
protected Map<String, String> knownMimeDataTypes = new HashMap<>();
protected Set<String> typeNames = new HashSet<String>();
protected Set<String> modelTypeNames = new HashSet<String>();
final private static Pattern JSON_MIME_PATTERN = Pattern.compile("(?i)application/.*json(;.*)?");
public CodegenType getTag() {
return CodegenType.CLIENT;
}
public String getName() {
return "haskell-http-client";
}
public String getHelp() {
return "Generates a Haskell http-client library.";
}
public HaskellHttpClientCodegen() {
super();
this.prependFormOrBodyParameters = true;
// override the mapping to keep the original mapping in Haskell
specialCharReplacements.put("-", "Dash");
specialCharReplacements.put(">", "GreaterThan");
specialCharReplacements.put("<", "LessThan");
// backslash and double quote need double the escapement for both Java and Haskell
specialCharReplacements.remove("\\");
specialCharReplacements.remove("\"");
specialCharReplacements.put("\\\\", "Back_Slash");
specialCharReplacements.put("\\\"", "Double_Quote");
// set the output folder here
outputFolder = "generated-code/haskell-http-client";
embeddedTemplateDir = templateDir = "haskell-http-client";
apiPackage = "API";
//modelPackage = "Model";
// default HIDE_GENERATION_TIMESTAMP to true
hideGenerationTimestamp = Boolean.TRUE;
// Haskell keywords and reserved function names, taken mostly from https://wiki.haskell.org/Keywords
setReservedWordsLowerCase(
Arrays.asList(
// Keywords
"as", "case", "of",
"class", "data", "family",
"default", "deriving",
"do", "forall", "foreign", "hiding",
"if", "then", "else",
"import", "infix", "infixl", "infixr",
"instance", "let", "in",
"mdo", "module", "newtype",
"proc", "qualified", "rec",
"type", "where", "pure", "return",
"Accept", "ContentType"
)
);
supportingFiles.add(new SupportingFile("README.mustache", "", "README.md"));
supportingFiles.add(new SupportingFile("stack.mustache", "", "stack.yaml"));
supportingFiles.add(new SupportingFile("Setup.mustache", "", "Setup.hs"));
supportingFiles.add(new SupportingFile("gitignore.mustache", "", ".gitignore"));
supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml"));
supportingFiles.add(new SupportingFile("git_push.sh.mustache", "", "git_push.sh"));
supportingFiles.add(new SupportingFile("tests/ApproxEq.mustache", "tests", "ApproxEq.hs"));
supportingFiles.add(new SupportingFile("tests/Instances.mustache", "tests", "Instances.hs"));
supportingFiles.add(new SupportingFile("tests/PropMime.mustache", "tests", "PropMime.hs"));
supportingFiles.add(new SupportingFile("tests/Test.mustache", "tests", "Test.hs"));
languageSpecificPrimitives = new HashSet<String>(
Arrays.asList(
"Bool",
"String",
"Int",
"Integer",
"Float",
"Char",
"Double",
"List",
"FilePath",
"Text"
)
);
typeMapping.clear();
// prim
typeMapping.put("boolean", "Bool");
typeMapping.put("int", "Int");
typeMapping.put("long", "Integer");
typeMapping.put("short", "Int");
typeMapping.put("char", "Char");
typeMapping.put("float", "Float");
typeMapping.put("double", "Double");
typeMapping.put("number", "Double");
typeMapping.put("BigDecimal", "Double");
typeMapping.put("integer", "Int");
typeMapping.put("file", "FilePath");
// lib
typeMapping.put("string", "Text");
typeMapping.put("UUID", "Text");
typeMapping.put("URI", "Text");
typeMapping.put("any", "A.Value");
typeMapping.put("set", "Set.Set");
// newtype
typeMapping.put("binary", "Binary");
typeMapping.put("ByteArray", "ByteArray");
typeMapping.put("date", "Date");
typeMapping.put("DateTime", "DateTime");
knownMimeDataTypes.put("application/json", "MimeJSON");
knownMimeDataTypes.put("application/xml", "MimeXML");
knownMimeDataTypes.put("application/x-www-form-urlencoded", "MimeFormUrlEncoded");
knownMimeDataTypes.put("application/octet-stream", "MimeOctetStream");
knownMimeDataTypes.put("multipart/form-data", "MimeMultipartFormData");
knownMimeDataTypes.put("text/plain", "MimePlainText");
knownMimeDataTypes.put("*/*", MIME_ANY);
importMapping.clear();
//cliOptions.add(CliOption.newString(CodegenConstants.MODEL_PACKAGE, CodegenConstants.MODEL_PACKAGE_DESC));
//cliOptions.add(CliOption.newString(CodegenConstants.API_PACKAGE, CodegenConstants.API_PACKAGE_DESC));
cliOptions.add(CliOption.newString(PROP_CABAL_PACKAGE, "Set the cabal package name, which consists of one or more alphanumeric words separated by hyphens"));
cliOptions.add(CliOption.newString(PROP_CABAL_VERSION, "Set the cabal version number, consisting of a sequence of one or more integers separated by dots"));
cliOptions.add(CliOption.newString(PROP_BASE_MODULE, "Set the base module namespace"));
cliOptions.add(CliOption.newString(PROP_REQUEST_TYPE, "Set the name of the type used to generate requests"));
cliOptions.add(CliOption.newString(PROP_CONFIG_TYPE, "Set the name of the type used for configuration"));
cliOptions.add(CliOption.newBoolean(PROP_ALLOW_FROMJSON_NULLS, "allow JSON Null during model decoding from JSON").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_ALLOW_TOJSON_NULLS, "allow emitting JSON Null during model encoding to JSON").defaultValue(Boolean.FALSE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_ALLOW_NONUNIQUE_OPERATION_IDS, "allow different API modules to contain the same operationId. Each API must be imported qualified").defaultValue(Boolean.FALSE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_GENERATE_LENSES, "Generate Lens optics for Models").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_GENERATE_MODEL_CONSTRUCTORS, "Generate smart constructors (only supply required fields) for models").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_GENERATE_ENUMS, "Generate specific datatypes for OpenAPI enums").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_GENERATE_FORM_URLENCODED_INSTANCES, "Generate FromForm/ToForm instances for models that are used by operations that produce or consume application/x-www-form-urlencoded").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newBoolean(PROP_INLINE_MIME_TYPES, "Inline (hardcode) the content-type and accept parameters on operations, when there is only 1 option").defaultValue(Boolean.TRUE.toString()));
cliOptions.add(CliOption.newString(PROP_MODEL_DERIVING, "Additional classes to include in the deriving() clause of Models"));
cliOptions.add(CliOption.newBoolean(PROP_STRICT_FIELDS, "Add strictness annotations to all model fields").defaultValue((Boolean.TRUE.toString())));
cliOptions.add(CliOption.newBoolean(PROP_USE_KATIP, "Sets the default value for the UseKatip cabal flag. If true, the katip package provides logging instead of monad-logger").defaultValue((Boolean.TRUE.toString())));
cliOptions.add(CliOption.newString(PROP_DATETIME_FORMAT, "format string used to parse/render a datetime"));
cliOptions.add(CliOption.newString(PROP_DATE_FORMAT, "format string used to parse/render a date").defaultValue(defaultDateFormat));
cliOptions.add(CliOption.newString(PROP_CUSTOM_TEST_INSTANCE_MODULE, "test module used to provide typeclass instances for types not known by the generator"));
cliOptions.add(CliOption.newBoolean(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC).defaultValue(Boolean.TRUE.toString()));
}
public void setAllowNonUniqueOperationIds(Boolean value) {
additionalProperties.put(X_ALLOW_NONUNIQUE_OPERATION_IDS, value);
this.allowNonUniqueOperationIds = value;
}
public void setAllowFromJsonNulls(Boolean value) {
additionalProperties.put(PROP_ALLOW_FROMJSON_NULLS, value);
}
public void setAllowToJsonNulls(Boolean value) {
additionalProperties.put(PROP_ALLOW_TOJSON_NULLS, value);
}
public void setGenerateModelConstructors(Boolean value) {
additionalProperties.put(PROP_GENERATE_MODEL_CONSTRUCTORS, value);
}
public void setGenerateEnums(Boolean value) {
additionalProperties.put(PROP_GENERATE_ENUMS, value);
genEnums = value;
}
public void setGenerateFormUrlEncodedInstances(Boolean value) {
additionalProperties.put(PROP_GENERATE_FORM_URLENCODED_INSTANCES, value);
}
public void setInlineMimeTypes(Boolean value) {
additionalProperties.put(PROP_INLINE_MIME_TYPES, value);
}
public void setGenerateLenses(Boolean value) {
additionalProperties.put(PROP_GENERATE_LENSES, value);
}
public void setModelDeriving(String value) {
if (StringUtils.isBlank(value)) {
additionalProperties.remove(PROP_MODEL_DERIVING);
} else {
additionalProperties.put(PROP_MODEL_DERIVING, StringUtils.join(value.split(" "), ","));
}
}
public void setDateTimeFormat(String value) {
setStringProp(PROP_DATETIME_FORMAT, value);
}
public void setDateFormat(String value) { setStringProp(PROP_DATE_FORMAT, value); }
public void setCabalPackage(String value) {
setStringProp(PROP_CABAL_PACKAGE, value);
}
public void setCabalVersion(String value) {
setStringProp(PROP_CABAL_VERSION, value);
}
public void setBaseModule(String value) {
setStringProp(PROP_BASE_MODULE, value);
}
public void setRequestType(String value) {
setStringProp(PROP_REQUEST_TYPE, value);
}
public void setConfigType(String value) {
setStringProp(PROP_CONFIG_TYPE, value);
}
public void setStrictFields(Boolean value) {
additionalProperties.put(X_STRICT_FIELDS, value);
}
public void setUseKatip(Boolean value) {
additionalProperties.put(X_USE_KATIP, value);
this.useKatip = value;
}
public void setCustomTestInstanceModule(String value) { setStringProp(PROP_CUSTOM_TEST_INSTANCE_MODULE, value); }
private void setStringProp(String key, String value) {
if (StringUtils.isBlank(value)) {
additionalProperties.remove(key);
} else {
additionalProperties.put(key, value);
}
}
private String getStringProp(String key) {
return (String) additionalProperties.get(key);
}
@Override
public void processOpts() {
super.processOpts();
if (StringUtils.isEmpty(System.getenv("HASKELL_POST_PROCESS_FILE"))) {
LOGGER.info("Hint: Environment variable HASKELL_POST_PROCESS_FILE not defined so the Haskell code may not be properly formatted. To define it, try 'export HASKELL_POST_PROCESS_FILE=\"$HOME/.local/bin/hfmt -w\"' (Linux/Mac)");
}
if (additionalProperties.containsKey(PROP_ALLOW_FROMJSON_NULLS)) {
setAllowFromJsonNulls(convertPropertyToBoolean(PROP_ALLOW_FROMJSON_NULLS));
} else {
setAllowFromJsonNulls(true);
}
if (additionalProperties.containsKey(PROP_ALLOW_TOJSON_NULLS)) {
setAllowToJsonNulls(convertPropertyToBoolean(PROP_ALLOW_TOJSON_NULLS));
} else {
setAllowToJsonNulls(false);
}
if (additionalProperties.containsKey(PROP_ALLOW_NONUNIQUE_OPERATION_IDS)) {
setAllowNonUniqueOperationIds(convertPropertyToBoolean(PROP_ALLOW_NONUNIQUE_OPERATION_IDS));
} else {
setAllowNonUniqueOperationIds(false);
}
if (additionalProperties.containsKey(PROP_GENERATE_MODEL_CONSTRUCTORS)) {
setGenerateModelConstructors(convertPropertyToBoolean(PROP_GENERATE_MODEL_CONSTRUCTORS));
} else {
setGenerateModelConstructors(true);
}
if (additionalProperties.containsKey(PROP_GENERATE_ENUMS)) {
setGenerateEnums(convertPropertyToBoolean(PROP_GENERATE_ENUMS));
} else {
setGenerateEnums(true);
}
if (additionalProperties.containsKey(PROP_GENERATE_FORM_URLENCODED_INSTANCES)) {
setGenerateFormUrlEncodedInstances(convertPropertyToBoolean(PROP_GENERATE_FORM_URLENCODED_INSTANCES));
} else {
setGenerateFormUrlEncodedInstances(true);
}
if (additionalProperties.containsKey(PROP_INLINE_MIME_TYPES)) {
setInlineMimeTypes(convertPropertyToBoolean(PROP_INLINE_MIME_TYPES));
} else {
setInlineMimeTypes(true);
}
if (additionalProperties.containsKey(PROP_GENERATE_LENSES)) {
setGenerateLenses(convertPropertyToBoolean(PROP_GENERATE_LENSES));
} else {
setGenerateLenses(true);
}
if (additionalProperties.containsKey(PROP_MODEL_DERIVING)) {
setModelDeriving(additionalProperties.get(PROP_MODEL_DERIVING).toString());
} else {
setModelDeriving("");
}
if (additionalProperties.containsKey(PROP_DATETIME_FORMAT)) {
setDateTimeFormat(additionalProperties.get(PROP_DATETIME_FORMAT).toString());
} else {
setDateTimeFormat(null); // default should be null
}
if (additionalProperties.containsKey(PROP_DATE_FORMAT)) {
setDateFormat(additionalProperties.get(PROP_DATE_FORMAT).toString());
} else {
setDateFormat(defaultDateFormat);
}
if (additionalProperties.containsKey(PROP_STRICT_FIELDS)) {
setStrictFields(convertPropertyToBoolean(PROP_STRICT_FIELDS));
} else {
setStrictFields(true);
}
if (additionalProperties.containsKey(PROP_USE_KATIP)) {
setUseKatip(convertPropertyToBoolean(PROP_USE_KATIP));
} else {
setUseKatip(true);
}
if (additionalProperties.containsKey(PROP_CABAL_PACKAGE)) {
setCabalPackage(additionalProperties.get(PROP_CABAL_PACKAGE).toString());
}
if (additionalProperties.containsKey(PROP_CABAL_VERSION)) {
setCabalVersion(additionalProperties.get(PROP_CABAL_VERSION).toString());
} else {
setCabalVersion(defaultCabalVersion);
}
if (additionalProperties.containsKey(PROP_BASE_MODULE)) {
setBaseModule(additionalProperties.get(PROP_BASE_MODULE).toString());
}
if (additionalProperties.containsKey(PROP_REQUEST_TYPE)) {
setRequestType(additionalProperties.get(PROP_REQUEST_TYPE).toString());
}
if (additionalProperties.containsKey(PROP_CONFIG_TYPE)) {
setConfigType(additionalProperties.get(PROP_CONFIG_TYPE).toString());
}
if (additionalProperties.containsKey(PROP_CUSTOM_TEST_INSTANCE_MODULE)) {
setCustomTestInstanceModule(additionalProperties.get(PROP_CUSTOM_TEST_INSTANCE_MODULE).toString());
}
}
@Override
public void preprocessOpenAPI(OpenAPI openAPI) {
String baseTitle = openAPI.getInfo().getTitle();
if (baseTitle == null) {
baseTitle = "OpenAPI";
} else {
baseTitle = baseTitle.trim();
// Drop any API suffix
if (baseTitle.toUpperCase(Locale.ROOT).endsWith("API")) {
baseTitle = baseTitle.substring(0, baseTitle.length() - 3);
}
}
if (!additionalProperties.containsKey(PROP_CABAL_PACKAGE)) {
List<String> words = new ArrayList<>();
for (String word : baseTitle.split(" ")) {
words.add(word.toLowerCase(Locale.ROOT));
}
setCabalPackage(StringUtils.join(words, "-"));
}
if (!additionalProperties.containsKey(PROP_BASE_MODULE)) {
List<String> wordsCaps = new ArrayList<String>();
for (String word : baseTitle.split(" ")) {
wordsCaps.add(firstLetterToUpper(word));
}
setBaseModule(StringUtils.join(wordsCaps, ""));
}
modulePath = sourceFolder + File.separator + getStringProp(PROP_BASE_MODULE).replace('.', File.separatorChar);
String topLevelPath = StringUtils.substringBeforeLast(modulePath, String.valueOf(File.separatorChar));
String lastPath = StringUtils.substringAfterLast(modulePath, String.valueOf(File.separatorChar));
if (!additionalProperties.containsKey(PROP_REQUEST_TYPE)) {
setRequestType(lastPath + "Request");
}
if (!additionalProperties.containsKey(PROP_CONFIG_TYPE)) {
setConfigType(lastPath + "Config");
}
// root
supportingFiles.add(new SupportingFile("haskell-http-client.cabal.mustache", "", getStringProp(PROP_CABAL_PACKAGE) + ".cabal"));
supportingFiles.add(new SupportingFile("openapi.mustache", "", "openapi.yaml"));
// lib
supportingFiles.add(new SupportingFile("TopLevel.mustache", topLevelPath, lastPath + ".hs"));
supportingFiles.add(new SupportingFile("Client.mustache", modulePath, "Client.hs"));
if (!allowNonUniqueOperationIds) {
supportingFiles.add(new SupportingFile("APIS.mustache", modulePath, "API.hs"));
}
supportingFiles.add(new SupportingFile("Core.mustache", modulePath, "Core.hs"));
supportingFiles.add(new SupportingFile("Model.mustache", modulePath, "Model.hs"));
supportingFiles.add(new SupportingFile("MimeTypes.mustache", modulePath, "MimeTypes.hs"));
// logger
supportingFiles.add(new SupportingFile("Logging.mustache", modulePath, "Logging.hs"));
supportingFiles.add(new SupportingFile("LoggingMonadLogger.mustache", modulePath, "LoggingMonadLogger.hs"));
supportingFiles.add(new SupportingFile("LoggingKatip.mustache", modulePath, "LoggingKatip.hs"));
apiTemplateFiles.put("API.mustache", ".hs");
// modelTemplateFiles.put("Model.mustache", ".hs");
// lens
if ((boolean) additionalProperties.get(PROP_GENERATE_LENSES)) {
supportingFiles.add(new SupportingFile("ModelLens.mustache", modulePath, "ModelLens.hs"));
}
additionalProperties.put("cabalName", getStringProp(PROP_CABAL_PACKAGE));
additionalProperties.put("pathsName", getStringProp(PROP_CABAL_PACKAGE).replace('-', '_'));
additionalProperties.put("requestType", getStringProp(PROP_REQUEST_TYPE));
additionalProperties.put("configType", getStringProp(PROP_CONFIG_TYPE));
additionalProperties.put("openApiVersion", openAPI.getOpenapi());
List<String> allUniqueImportPaths = this.importMapping.values().stream().distinct().collect(Collectors.toList());
if (allUniqueImportPaths.size() > 0) {
additionalProperties.put(X_ALL_UNIQUE_IMPORT_PATHS, allUniqueImportPaths);
supportingFiles.add(new SupportingFile("ImportMappings.mustache", modulePath, "ImportMappings.hs"));
List<Map<String, String>> allImportMappings = new ArrayList<>();
for (Map.Entry<String, String> entry : this.importMapping.entrySet()) {
Map<String, String> importMappingEntry = new HashMap<>();
importMappingEntry.put("dataType", entry.getKey());
importMappingEntry.put("importPath", entry.getValue());
allImportMappings.add(importMappingEntry);
}
additionalProperties.put(X_ALL_IMPORT_MAPPINGS, allImportMappings);
additionalProperties.put(X_HAS_IMPORT_MAPPINGS, true);
}
super.preprocessOpenAPI(openAPI);
}
@Override
public Map<String, Object> postProcessSupportingFileData(Map<String, Object> objs) {
generateYAMLSpecFile(objs);
return super.postProcessSupportingFileData(objs);
}
@Override
public String getTypeDeclaration(Schema p) {
if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
Schema inner = ap.getItems();
return "[" + getTypeDeclaration(inner) + "]";
} else if (ModelUtils.isMapSchema(p)) {
Schema inner = ModelUtils.getAdditionalProperties(p);
return "(Map.Map String " + getTypeDeclaration(inner) + ")";
}
return super.getTypeDeclaration(p);
}
@Override
public String getSchemaType(Schema p) {
String openAPIType = super.getSchemaType(p);
if (typeMapping.containsKey(openAPIType)) {
return typeMapping.get(openAPIType);
} else if ("object".equals(openAPIType)) {
return "A.Value";
} else {
return toModelName(openAPIType);
}
}
@Override
public String toInstantiationType(Schema p) {
if (ModelUtils.isMapSchema(p)) {
Schema additionalProperties2 = ModelUtils.getAdditionalProperties(p);
String type = additionalProperties2.getType();
if (null == type) {
LOGGER.error("No Type defined for Additional Schema " + additionalProperties2 + "\n" //
+ "\tIn Schema: " + p);
}
String inner = getSchemaType(additionalProperties2);
return "(Map.Map Text " + inner + ")";
} else if (ModelUtils.isArraySchema(p)) {
ArraySchema ap = (ArraySchema) p;
return getSchemaType(ap.getItems());
} else {
return null;
}
}
@Override
public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation op, Map<String, List<CodegenOperation>> operations) {
List<CodegenOperation> opList = operations.get(tag);
if (opList == null || opList.isEmpty()) {
opList = new ArrayList<CodegenOperation>();
operations.put(tag, opList);
}
// check for operationId uniqueness
String uniqueName = op.operationId;
String uniqueNameType = toTypeName("Op", uniqueName);
int counter = 0;
HashSet<String> opIds = new HashSet<>();
for (CodegenOperation o : opList) {
opIds.add(o.operationId);
}
while (opIds.contains(uniqueName) ||
(allowNonUniqueOperationIds
? modelTypeNames.contains(uniqueNameType) // only check for model conflicts
: typeNames.contains(uniqueNameType))) { // check globally across all types
uniqueName = op.operationId + counter;
uniqueNameType = toTypeName("Op", uniqueName);
counter++;
}
if (!op.operationId.equals(uniqueName)) {
LOGGER.warn("generated unique operationId `" + uniqueName + "`");
}
op.operationId = uniqueName;
op.operationIdLowerCase = uniqueName.toLowerCase(Locale.ROOT);
op.operationIdCamelCase = camelize(uniqueName);
op.operationIdSnakeCase = underscore(uniqueName);
opList.add(op);
op.baseName = tag;
// prevent aliasing/sharing of operation.vendorExtensions reference
op.vendorExtensions = new LinkedHashMap();
String operationType = toTypeName("Op", op.operationId);
op.vendorExtensions.put(X_OPERATION_TYPE, operationType);
typeNames.add(operationType);
op.vendorExtensions.put(X_HADDOCK_PATH, String.format(Locale.ROOT, "%s %s", op.httpMethod, op.path.replace("/", "\\/")));
op.vendorExtensions.put(X_HAS_BODY_OR_FORM_PARAM, op.getHasBodyParam() || op.getHasFormParams());
for (CodegenParameter param : op.allParams) {
param.vendorExtensions = new LinkedHashMap(); // prevent aliasing/sharing
param.vendorExtensions.put(X_OPERATION_TYPE, operationType);
param.vendorExtensions.put(X_IS_BODY_OR_FORM_PARAM, param.isBodyParam || param.isFormParam);
if (!StringUtils.isBlank(param.collectionFormat)) {
param.vendorExtensions.put(X_COLLECTION_FORMAT, mapCollectionFormat(param.collectionFormat));
} else if (!param.isBodyParam && (param.isListContainer || param.dataType.startsWith("["))) { // param.isListContainer is sometimes false for list types
// defaulting due to https://github.com/wing328/openapi-generator/issues/72
param.collectionFormat = "csv";
param.vendorExtensions.put(X_COLLECTION_FORMAT, mapCollectionFormat(param.collectionFormat));
}
if (!param.required) {
op.vendorExtensions.put(X_HAS_OPTIONAL_PARAMS, true);
}
if (typeMapping.containsKey(param.dataType)
|| param.isMapContainer || param.isListContainer
|| param.isPrimitiveType || param.isFile || param.isEnum) {
String dataType = genEnums && param.isEnum ? param.datatypeWithEnum : param.dataType;
String paramNameType = toDedupedModelName(toTypeName("Param", param.paramName), dataType, !param.isEnum);
param.vendorExtensions.put(X_PARAM_NAME_TYPE, paramNameType);
HashMap<String, Object> props = new HashMap<>();
props.put(X_IS_BODY_PARAM, param.isBodyParam);
addToUniques(X_NEWTYPE, paramNameType, dataType, props);
}
}
processPathExpr(op);
processProducesConsumes(op);
processReturnType(op);
}
@Override
public List<CodegenSecurity> fromSecurity(Map<String, SecurityScheme> schemes) {
List<CodegenSecurity> secs = super.fromSecurity(schemes);
for (CodegenSecurity sec : secs) {
String prefix = "";
if (sec.isBasic) prefix = "AuthBasic";
if (sec.isApiKey) prefix = "AuthApiKey";
if (sec.isOAuth) prefix = "AuthOAuth";
sec.name = prefix + toTypeName("", sec.name);
}
return secs;
}
@Override
public Map<String, Object> postProcessAllModels(Map<String, Object> objs) {
updateGlobalAdditionalProps();
return super.postProcessAllModels(objs);
}
public void updateGlobalAdditionalProps() {
additionalProperties.put(X_HAS_UNKNOWN_MIME_TYPES, !unknownMimeTypes.isEmpty());
Collections.sort(unknownMimeTypes, new Comparator<Map<String, String>>() {
@Override
public int compare(Map<String, String> o1, Map<String, String> o2) {
return o1.get(MEDIA_TYPE).compareTo(o2.get(MEDIA_TYPE));
}
});
additionalProperties.put(X_UNKNOWN_MIME_TYPES, unknownMimeTypes);
ArrayList<Map<String, Object>> params = new ArrayList<>(uniqueParamNameTypes.values());
Collections.sort(params, new Comparator<Map<String, Object>>() {
@Override
public int compare(Map<String, Object> o1, Map<String, Object> o2) {
return
((String) o1.get(X_PARAM_NAME_TYPE))
.compareTo(
(String) o2.get(X_PARAM_NAME_TYPE));
}
});
additionalProperties.put(X_ALL_UNIQUE_PARAMS, params);
}
@Override
public Map<String, Object> postProcessOperationsWithModels(Map<String, Object> objs, List<Object> allModels) {
Map<String, Object> ret = super.postProcessOperationsWithModels(objs, allModels);
HashMap<String, Object> pathOps = (HashMap<String, Object>) ret.get("operations");
ArrayList<CodegenOperation> ops = (ArrayList<CodegenOperation>) pathOps.get("operation");
if (ops.size() > 0) {
ops.get(0).vendorExtensions.put(X_HAS_NEW_TAG, true);
}
updateGlobalAdditionalProps();
for (Object o : allModels) {
HashMap<String, Object> h = (HashMap<String, Object>) o;
CodegenModel m = (CodegenModel) h.get("model");
if (modelMimeTypes.containsKey(m.classname)) {
Set<String> mimeTypes = modelMimeTypes.get(m.classname);
m.vendorExtensions.put(X_MIME_TYPES, mimeTypes);
if ((boolean) additionalProperties.get(PROP_GENERATE_FORM_URLENCODED_INSTANCES) && mimeTypes.contains("MimeFormUrlEncoded")) {
Boolean hasMimeFormUrlEncoded = true;
for (CodegenProperty v : m.vars) {
if (!(v.isPrimitiveType || v.isString || v.isDate || v.isDateTime)) {
hasMimeFormUrlEncoded = false;
}
}
if (hasMimeFormUrlEncoded) {
m.vendorExtensions.put(X_HAS_MIME_FORM_URL_ENCODED, true);
}
}
}
}
return ret;
}
@Override
public CodegenModel fromModel(String name, Schema mod) {
CodegenModel model = super.fromModel(name, mod);
// while (typeNames.contains(model.classname)) {
// model.classname = generateNextName(model.classname);
// }
typeNames.add(model.classname);
modelTypeNames.add(model.classname);
// From the model name, compute the prefix for the fields.
String prefix = StringUtils.uncapitalize(model.classname);
for (CodegenProperty prop : model.vars) {
prop.name = toVarName(prefix, prop.name);
}
return model;
}
@Override
public String escapeReservedWord(String name) {
if (this.reservedWordsMappings().containsKey(name)) {
return this.reservedWordsMappings().get(name);
}
return "_" + name;
}
@Override
public String escapeQuotationMark(String input) {
// remove " to avoid code injection
return input.replace("\"", "");
}
@Override
public String escapeUnsafeCharacters(String input) {
return input.replace("{-", "{_-").replace("-}", "-_}");
}
@Override
public boolean isDataTypeFile(String dataType) {
return dataType != null && dataType.equals("FilePath");
}
@Override
public boolean isDataTypeBinary(final String dataType) {
return dataType != null && dataType.equals("B.ByteString");
}
private void processReturnType(CodegenOperation op) {
String returnType = op.returnType;
if (returnType == null || returnType.equals("null")) {
if (op.hasProduces) {
returnType = "res";
op.vendorExtensions.put(X_HAS_UNKNOWN_RETURN, true);
} else {
returnType = "NoContent";
if (!op.vendorExtensions.containsKey(X_INLINE_ACCEPT)) {
SetNoContent(op, X_INLINE_ACCEPT);
}
}
}
if (returnType.contains(" ")) {
returnType = "(" + returnType + ")";
}
op.vendorExtensions.put(X_RETURN_TYPE, returnType);
}
private void processProducesConsumes(CodegenOperation op) {
if (!(Boolean) op.vendorExtensions.get(X_HAS_BODY_OR_FORM_PARAM)) {
SetNoContent(op, X_INLINE_CONTENT_TYPE);
}
if (op.hasConsumes) {
// deduplicate
Map<String, Map<String, String>> consumes = new HashMap<>();
for (Map<String, String> m : op.consumes) {
consumes.put(m.get(MEDIA_TYPE), m);
}
op.consumes = new ArrayList<>(consumes.values());
// add metadata
for (Map<String, String> m : op.consumes) {
processMediaType(op, m);
processInlineConsumesContentType(op, m);
}
if (isMultipartOperation(op.consumes)) {
op.isMultipart = Boolean.TRUE;
}
}
if (op.hasProduces) {
// deduplicate
Map<String, Map<String, String>> produces = new HashMap<>();
for (Map<String, String> m : op.produces) {
produces.put(m.get(MEDIA_TYPE), m);
}
op.produces = new ArrayList<>(produces.values());
// add metadata
for (Map<String, String> m : op.produces) {
processMediaType(op, m);
processInlineProducesContentType(op, m);
}
}
}
private void processInlineConsumesContentType(CodegenOperation op, Map<String, String> m) {
if (op.vendorExtensions.containsKey(X_INLINE_CONTENT_TYPE)) return;
if ((boolean) additionalProperties.get(PROP_INLINE_MIME_TYPES)
&& op.consumes.size() == 1
&& !MIME_ANY.equals(op.consumes.get(0).get(X_MEDIA_DATA_TYPE))
&& !MIME_NO_CONTENT.equals(op.consumes.get(0).get(X_MEDIA_DATA_TYPE))) {
op.vendorExtensions.put(X_INLINE_CONTENT_TYPE, m);
for (CodegenParameter param : op.allParams) {
if (param.isBodyParam && param.required) {
param.vendorExtensions.put(X_INLINE_CONTENT_TYPE, m);
}
}
}
}
private void processInlineProducesContentType(CodegenOperation op, Map<String, String> m) {
if ((boolean) additionalProperties.get(PROP_INLINE_MIME_TYPES)
&& op.produces.size() == 1
&& !MIME_ANY.equals(op.produces.get(0).get(X_MEDIA_DATA_TYPE))
&& !MIME_NO_CONTENT.equals(op.produces.get(0).get(X_MEDIA_DATA_TYPE))) {
op.vendorExtensions.put(X_INLINE_ACCEPT, m);
}
}
private void SetNoContent(CodegenOperation op, String inlineExtentionName) {
Map<String, String> m = new HashMap<>();
m.put(X_MEDIA_DATA_TYPE, MIME_NO_CONTENT);
op.vendorExtensions.put(inlineExtentionName, m);
}
private String toDedupedModelName(String paramNameType, String dataType, Boolean appendDataType) {
if (appendDataType
&& uniqueParamNameTypes.containsKey(paramNameType)
&& !isDuplicate(paramNameType, dataType)) {
paramNameType = toTypeName("", paramNameType + dataType);
}
while (typeNames.contains(paramNameType)) {
if (isDuplicate(paramNameType, dataType)) {
break;
}
paramNameType = generateNextName(paramNameType);
}
typeNames.add(paramNameType);
modelTypeNames.add(paramNameType);
return paramNameType;
}
public Boolean isDuplicate(String paramNameType, String dataType) {
Map<String, Object> lastParam = this.uniqueParamNameTypes.get(paramNameType);
if (lastParam != null) {
String comparisonKey = lastParam.containsKey(X_ENUM) ? X_ENUM_VALUES : X_DATA_TYPE;
String lastParamDataType = (String) lastParam.get(comparisonKey);
if (lastParamDataType != null && lastParamDataType.equals(dataType)) {
return true;
}
}
return false;
}
private Pair<Boolean, String> isDuplicateEnumValues(String enumValues) {
for (Map<String, Object> vs : uniqueParamNameTypes.values()) {
if (enumValues.equals(vs.get(X_ENUM_VALUES))) {
return Pair.of(true, (String) vs.get(X_PARAM_NAME_TYPE));
}
}
return Pair.of(false, null);
}
private void addToUniques(String xGroup, String paramNameType, String dataType, Map<String, Object> props) {
HashMap<String, Object> m = new HashMap<>();
m.put(X_PARAM_NAME_TYPE, paramNameType);
m.put(X_DATA_TYPE, dataType);
m.put(xGroup, true);
m.putAll(props);
uniqueParamNameTypes.put(paramNameType, m);
}
private void addEnumToUniques(String paramNameType, String datatype, String enumValues, Map<String, Object> allowableValues, String description) {
HashMap<String, Object> props = new HashMap<>();
props.put("allowableValues", allowableValues);
if (StringUtils.isNotBlank(description)) {
props.put("description", description);
}
props.put(X_ENUM_VALUES, enumValues);
addToUniques(X_ENUM, paramNameType, datatype, props);
additionalProperties.put(X_HAS_ENUM_SECTION, true);
}
// build the parameterized path segments, according to pathParams
private void processPathExpr(CodegenOperation op) {
String xPath = "[\"" + escapeText(op.path) + "\"]";
if (op.getHasPathParams()) {
for (CodegenParameter param : op.allParams) {
if (param.isPathParam) {
xPath = xPath.replaceAll("\\{" + param.baseName + "\\}", "\",toPath " + param.paramName + ",\"");
}
}
xPath = xPath.replaceAll(",\"\",", ",");
xPath = xPath.replaceAll("\"\",", ",");
xPath = xPath.replaceAll(",\"\"", ",");
xPath = xPath.replaceAll("^\\[,", "[");
xPath = xPath.replaceAll(",\\]$", "]");
}