-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathCli.elm
More file actions
1379 lines (1157 loc) · 53 KB
/
Cli.elm
File metadata and controls
1379 lines (1157 loc) · 53 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
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
module Cli exposing (run, withConfig)
import Ansi
import Ansi.Color
import Ansi.Font
import BackendTask exposing (BackendTask)
import BackendTask.Extra
import BackendTask.File
import BackendTask.Http
import BackendTask.Stream
import Cli.Option
import Cli.OptionsParser
import Cli.Program
import Common
import Dict
import Dict.Extra
import Elm
import FastDict
import FastSet
import FatalError exposing (FatalError)
import Json.Decode
import Json.Encode
import Json.Value
import OpenApi
import OpenApi.Common.Internal
import OpenApi.Config
import OpenApi.Generate
import Pages.Script
import Pages.Script.Spinner
import Pretty
import Regex exposing (Regex)
import Result.Extra
import String.Extra
import Url
import UrlPath
import Yaml.Decode
type alias CliOptions =
{ entryFilePath : OpenApi.Config.Path
, outputDirectory : String
, outputModuleName : Maybe String
, effectTypes : List OpenApi.Config.EffectType
, generateTodos : Bool
, autoConvertSwagger : OpenApi.Config.AutoConvertSwagger
, swaggerConversionUrl : Maybe String
, swaggerConversionCommand : Maybe String
, swaggerConversionCommandArgs : List String
, server : OpenApi.Config.Server
, overrides : List OpenApi.Config.Path
, writeMergedTo : Maybe String
, noElmFormat : Bool
}
program : Cli.Program.Config CliOptions
program =
Cli.Program.config
|> Cli.Program.add
(Cli.OptionsParser.build CliOptions
|> Cli.OptionsParser.with
(Cli.Option.requiredPositionalArg "entryFilePath"
|> Cli.Option.map OpenApi.Config.pathFromString
)
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "output-dir"
|> Cli.Option.withDefault "generated"
)
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "module-name")
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "effect-types"
|> Cli.Option.validateMap effectTypesValidation
)
|> Cli.OptionsParser.with
(Cli.Option.flag "generateTodos")
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "auto-convert-swagger"
|> Cli.Option.validateMap autoConvertValidation
)
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "swagger-conversion-url")
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "swagger-conversion-command")
|> Cli.OptionsParser.with
(Cli.Option.keywordArgList "swagger-conversion-command-args")
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "server"
|> Cli.Option.validateMap serverValidation
)
|> Cli.OptionsParser.with
(Cli.Option.keywordArgList "overrides"
|> Cli.Option.map (List.map OpenApi.Config.pathFromString)
)
|> Cli.OptionsParser.with
(Cli.Option.optionalKeywordArg "write-merged-to")
|> Cli.OptionsParser.with
(Cli.Option.flag "no-elm-format")
|> Cli.OptionsParser.withDoc """
version: 0.7.0
options:
--output-dir The directory to output to. Defaults to `generated/`.
--module-name The Elm module name. Defaults to `OAS info.title`.
--effect-types A list of which kind of APIs to generate.
Each item should be of the form `package.type`.
If `package` is omitted it defaults to `elm/http`.
If `type` is omitted it defaults to `cmd,task`.
If not specified, defaults to `cmd,task` (for elm/http).
The options for package are:
- elm/http
- dillonkearns/elm-pages
- lamdera/program-test
The options for type are:
- cmd: Cmd for elm/http,
Effect.Command for lamdera/program-test
- cmdrisky: as above, but using Http.riskyRequest
- cmdrecord: the input to Http.request
- task: Task for elm/http
Effect.Task for lamdera/program-test
BackendTask for dillonkearns/elm-pages
- taskrisky: as above, but using Http.riskyTask
cannot be used for dillonkearns/elm-pages
- taskrecord: the input to Http.task
--server The base URL for the OpenAPI server.
If not specified this will be extracted from the OAS
or default to root of the web application.
You can pass in an object to define multiple servers, like
{"dev": "http://localhost", "prod": "https://example.com"}.
This will add a `server` parameter to functions and define
a `Servers` module with your servers. You can pass in an
empty object if you have fully dynamic servers.
--auto-convert-swagger=ask If a Swagger doc is encountered, ask the user before converting
it to an Open API file. This is the default.
--auto-convert-swagger=never If a Swagger doc is encountered, error out.
--auto-convert-swagger[=always] If a Swagger doc is encountered, automatically convert it
to an Open API file.
--swagger-conversion-url The URL to use to convert a Swagger doc to an Open API
file. Defaults to `https://converter.swagger.io/api/convert`.
--swagger-conversion-command Instead of making an HTTP request to convert
from Swagger to Open API, use this command.
--swagger-conversion-command-args Additional arguments to pass to the Swagger conversion command,
before the contents of the Swagger file are passed in.
--generateTodos Whether to generate TODOs for unimplemented endpoints,
or fail when something unexpected is encountered.
Defaults to `no`. To generate `Debug.todo ""`
instead of failing use one of: `yes`, `y`, `true`.
--overrides Load an additional file to override parts of the original Open API file.
--write-merged-to Write the merged Open API spec to the given file.
--no-elm-format Don't run elm-format on the outputs.
"""
)
autoConvertValidation : Maybe String -> Result String OpenApi.Config.AutoConvertSwagger
autoConvertValidation input =
case input of
Nothing ->
Ok OpenApi.Config.AskBeforeConversion
Just "ask" ->
Ok OpenApi.Config.AskBeforeConversion
Just "" ->
Ok OpenApi.Config.AlwaysConvert
Just "always" ->
Ok OpenApi.Config.AlwaysConvert
Just "never" ->
Ok OpenApi.Config.NeverConvert
Just value ->
Err ("Unexpected value for auto-convert-swagger: " ++ value)
effectTypesValidation : Maybe String -> Result String (List OpenApi.Config.EffectType)
effectTypesValidation str =
case str of
Nothing ->
Ok []
Just v ->
v
|> String.split ","
|> List.map String.trim
|> Result.Extra.combineMap effectTypeValidation
|> Result.map List.concat
effectTypeValidation : String -> Result String (List OpenApi.Config.EffectType)
effectTypeValidation effectType =
case effectType of
"cmd" ->
Ok [ OpenApi.Config.ElmHttpCmd ]
"cmdrisky" ->
Ok [ OpenApi.Config.ElmHttpCmdRisky ]
"cmdrecord" ->
Ok [ OpenApi.Config.ElmHttpCmdRecord ]
"task" ->
Ok [ OpenApi.Config.ElmHttpTask ]
"taskrisky" ->
Ok [ OpenApi.Config.ElmHttpTaskRisky ]
"taskrecord" ->
Ok [ OpenApi.Config.ElmHttpTaskRecord ]
"elm/http" ->
Ok [ OpenApi.Config.ElmHttpCmd, OpenApi.Config.ElmHttpTask ]
"elm/http.cmd" ->
Ok [ OpenApi.Config.ElmHttpCmd ]
"elm/http.cmdrisky" ->
Ok [ OpenApi.Config.ElmHttpCmdRisky ]
"elm/http.cmdrecord" ->
Ok [ OpenApi.Config.ElmHttpCmdRecord ]
"elm/http.task" ->
Ok [ OpenApi.Config.ElmHttpTask ]
"elm/http.taskrisky" ->
Ok [ OpenApi.Config.ElmHttpTaskRisky ]
"elm/http.taskrecord" ->
Ok [ OpenApi.Config.ElmHttpTaskRecord ]
"dillonkearns/elm-pages" ->
Ok [ OpenApi.Config.DillonkearnsElmPagesTask ]
"dillonkearns/elm-pages.task" ->
Ok [ OpenApi.Config.DillonkearnsElmPagesTask ]
"dillonkearns/elm-pages.taskrecord" ->
Ok [ OpenApi.Config.DillonkearnsElmPagesTaskRecord ]
"lamdera/program-test" ->
Ok [ OpenApi.Config.LamderaProgramTestCmd, OpenApi.Config.LamderaProgramTestTask ]
"lamdera/program-test.cmd" ->
Ok [ OpenApi.Config.LamderaProgramTestCmd ]
"lamdera/program-test.cmdrisky" ->
Ok [ OpenApi.Config.LamderaProgramTestCmdRisky ]
"lamdera/program-test.cmdrecord" ->
Ok [ OpenApi.Config.LamderaProgramTestCmdRecord ]
"lamdera/program-test.task" ->
Ok [ OpenApi.Config.LamderaProgramTestTask ]
"lamdera/program-test.taskrisky" ->
Ok [ OpenApi.Config.LamderaProgramTestTaskRisky ]
"lamdera/program-test.taskrecord" ->
Ok [ OpenApi.Config.LamderaProgramTestTaskRecord ]
_ ->
Err <| "Unexpected effect type: " ++ effectType
serverValidation : Maybe String -> Result String OpenApi.Config.Server
serverValidation server =
case Maybe.withDefault "" server of
"" ->
Ok OpenApi.Config.Default
input ->
case Json.Decode.decodeString (Json.Decode.dict Json.Decode.string) input of
Ok servers ->
Ok <| OpenApi.Config.Multiple servers
Err _ ->
if String.startsWith "{" input then
Err <| "Invalid JSON: " ++ input
else
Ok <| OpenApi.Config.Single input
run : Pages.Script.Script
run =
Pages.Script.withCliOptions program
(\cliOptions ->
cliOptions
|> parseCliOptions
|> withConfig
)
parseCliOptions : CliOptions -> OpenApi.Config.Config
parseCliOptions cliOptions =
let
-- Apply an update if the input is `Just x`
maybe :
(value -> config -> config)
-> Maybe value
-> config
-> config
maybe updater maybeValue config =
case maybeValue of
Nothing ->
config
Just value ->
updater value config
-- Apply an update if a condition is met
iif : Bool -> (config -> config) -> config -> config
iif cond updater config =
if cond then
updater config
else
config
input : OpenApi.Config.Input
input =
OpenApi.Config.inputFrom cliOptions.entryFilePath
|> OpenApi.Config.withServer cliOptions.server
|> OpenApi.Config.withOverrides cliOptions.overrides
|> maybe OpenApi.Config.withWriteMergedTo cliOptions.writeMergedTo
|> maybe OpenApi.Config.withOutputModuleName (Maybe.map (String.split ".") cliOptions.outputModuleName)
|> iif (not (List.isEmpty cliOptions.effectTypes)) (OpenApi.Config.withEffectTypes cliOptions.effectTypes)
in
OpenApi.Config.init cliOptions.outputDirectory
|> OpenApi.Config.withInput input
|> OpenApi.Config.withGenerateTodos cliOptions.generateTodos
|> OpenApi.Config.withAutoConvertSwagger cliOptions.autoConvertSwagger
|> OpenApi.Config.withNoElmFormat cliOptions.noElmFormat
|> maybe OpenApi.Config.withSwaggerConversionUrl cliOptions.swaggerConversionUrl
|> maybe OpenApi.Config.withSwaggerConversionCommand
(cliOptions.swaggerConversionCommand
|> Maybe.map (\command -> { command = command, args = cliOptions.swaggerConversionCommandArgs })
)
withInnerStep :
Int
-> Int
-> String
-> (a -> BackendTask FatalError b)
-> Pages.Script.Spinner.Steps FatalError ( a, c, d )
-> Pages.Script.Spinner.Steps FatalError ( b, c, d )
withInnerStep index total label toTask =
Pages.Script.Spinner.withStep (counter index total ++ " " ++ label)
(\( input, acc1, acc2 ) -> toTask input |> BackendTask.map (\result -> ( result, acc1, acc2 )))
withConfig : OpenApi.Config.Config -> BackendTask FatalError ()
withConfig config =
let
total : Int
total =
List.length (OpenApi.Config.inputs config)
in
List.foldl
(\input ( index, steps ) ->
( index + 1
, steps
|> (case OpenApi.Config.oasPath input of
OpenApi.Config.Url url ->
withInnerStep index
total
("Download OAS from " ++ Url.toString url)
(\_ -> BackendTask.andThen (parseOriginal input) (readFromUrl url))
OpenApi.Config.File path ->
withInnerStep index
total
("Read OAS from " ++ path)
(\_ -> BackendTask.andThen (parseOriginal input) (readFromFile path))
)
|> (\prev ->
let
overrides : List OpenApi.Config.Path
overrides =
OpenApi.Config.overrides input
in
if List.isEmpty overrides then
prev
|> withInnerStep index
total
"No overrides"
(\( _, original ) -> BackendTask.succeed (Json.Value.encode original))
else
List.foldl
(\override ->
case override of
OpenApi.Config.Url url ->
withInnerStep index
total
("Download override from " ++ Url.toString url)
(\( acc, original ) -> BackendTask.map (\read -> ( ( override, read ) :: acc, original )) (readFromUrl url))
OpenApi.Config.File path ->
withInnerStep index
total
("Read override from " ++ path)
(\( acc, original ) -> BackendTask.map (\read -> ( ( override, read ) :: acc, original )) (readFromFile path))
)
prev
overrides
|> withInnerStep index total "Merging overrides" mergeOverrides
)
|> (case OpenApi.Config.writeMergedTo input of
Nothing ->
identity
Just destination ->
withInnerStep index total "Writing merged OAS" (writeMerged destination)
)
|> Pages.Script.Spinner.withStep (counter index total ++ " Parse OAS")
(\( merged, apiSpecAcc, formatsAcc ) ->
merged
|> decodeOpenApiSpecOrFail { hasAttemptedToConvertFromSwagger = False } config input
|> BackendTask.map
(\( apiSpec, formats ) ->
( ()
, ( input, apiSpec ) :: apiSpecAcc
, formats :: formatsAcc
)
)
)
)
)
( 1
, Pages.Script.Spinner.steps
|> Pages.Script.Spinner.withStep "Collecting configuration" (\_ -> BackendTask.succeed ( (), [], [] ))
)
(OpenApi.Config.inputs config)
|> Tuple.second
|> Pages.Script.Spinner.withStep "Generate Elm modules"
(\( (), apiSpecs, allFormats ) ->
OpenApi.Config.toGenerationConfig (List.concat allFormats) config apiSpecs
|> generateFilesFromOpenApiSpecs
)
|> (if OpenApi.Config.noElmFormat config then
identity
else
Pages.Script.Spinner.withStep "Format with elm-format" (onFirst attemptToFormat)
)
|> Pages.Script.Spinner.withStep "Write to disk" (onFirst (writeSdkToDisk (OpenApi.Config.outputDirectory config)))
|> Pages.Script.Spinner.runSteps
|> BackendTask.map convertElmCodegenWarnings
|> BackendTask.andThen printSuccessMessageAndWarnings
convertElmCodegenWarnings :
( List ( String, List { declaration : String, warning : String } )
, { warnings : List OpenApi.Generate.Message, requiredPackages : FastSet.Set String }
)
->
( List String
, { warnings : List OpenApi.Generate.Message, requiredPackages : FastSet.Set String }
)
convertElmCodegenWarnings ( outputPathsAndElmCodegenWarnings, { warnings, requiredPackages } ) =
( List.map Tuple.first outputPathsAndElmCodegenWarnings
, { warnings =
warnings
++ List.concatMap elmCodegenWarningToMessage outputPathsAndElmCodegenWarnings
, requiredPackages = requiredPackages
}
)
counter : Int -> Int -> String
counter index total =
let
totalString : String
totalString =
String.fromInt total
in
"["
++ String.padLeft (String.length totalString) '0' (String.fromInt index)
++ "/"
++ totalString
++ "]"
onFirst : (a -> BackendTask.BackendTask error c) -> ( a, b ) -> BackendTask.BackendTask error ( c, b )
onFirst f ( a, b ) =
f a |> BackendTask.map (\c -> ( c, b ))
parseOriginal : OpenApi.Config.Input -> String -> BackendTask.BackendTask FatalError.FatalError ( List a, Json.Value.JsonValue )
parseOriginal input original =
case decodeMaybeYaml (OpenApi.Config.oasPath input) original of
Err e ->
e
|> parseErrorToFatalError
|> BackendTask.fail
Ok decoded ->
BackendTask.succeed ( [], decoded )
mergeOverrides : ( List ( OpenApi.Config.Path, String ), Json.Value.JsonValue ) -> BackendTask.BackendTask FatalError.FatalError Json.Decode.Value
mergeOverrides ( overrides, original ) =
Result.map
(\overridesValues ->
List.foldl
(\override acc -> Result.andThen (overrideWith override) acc)
(Ok original)
overridesValues
|> Result.mapError FatalError.fromString
|> Result.map Json.Value.encode
)
(overrides
|> List.reverse
|> Result.Extra.combineMap (\( path, file ) -> decodeMaybeYaml path file)
|> Result.mapError parseErrorToFatalError
)
|> Result.Extra.join
|> BackendTask.fromResult
writeMerged : String -> Json.Decode.Value -> BackendTask.BackendTask FatalError.FatalError Json.Decode.Value
writeMerged destination spec =
Pages.Script.writeFile
{ path = destination
, body = spec |> Json.Encode.encode 4
}
|> BackendTask.allowFatal
|> BackendTask.map (\_ -> spec)
decodeOpenApiSpecOrFail :
{ hasAttemptedToConvertFromSwagger : Bool }
-> OpenApi.Config.Config
-> OpenApi.Config.Input
-> Json.Decode.Value
-> BackendTask.BackendTask FatalError.FatalError ( OpenApi.OpenApi, List { format : String, basicType : Common.BasicType } )
decodeOpenApiSpecOrFail { hasAttemptedToConvertFromSwagger } config input value =
case
Result.map2 Tuple.pair
(Json.Decode.decodeValue OpenApi.decode value)
(extractFormats value)
of
Ok pair ->
BackendTask.succeed pair
Err decodeError ->
if hasAttemptedToConvertFromSwagger then
jsonErrorToFatalError decodeError
|> BackendTask.fail
else
case Json.Decode.decodeValue swaggerFieldDecoder value of
Err _ ->
jsonErrorToFatalError decodeError
|> BackendTask.fail
Ok _ ->
let
shouldConvertTask : BackendTask error Bool
shouldConvertTask =
case OpenApi.Config.autoConvertSwagger config of
OpenApi.Config.AlwaysConvert ->
BackendTask.succeed True
OpenApi.Config.NeverConvert ->
BackendTask.succeed False
OpenApi.Config.AskBeforeConversion ->
Pages.Script.question
(Ansi.Color.fontColor Ansi.Color.brightCyan (OpenApi.Config.pathToString (OpenApi.Config.oasPath input))
++ """ is a Swagger doc (aka Open API v2) and this tool only supports Open API v3.
Would you like to use """
++ Ansi.Color.fontColor Ansi.Color.brightCyan (OpenApi.Config.swaggerConversionUrl config)
++ " to upgrade to v3? (y/n)\n"
)
|> BackendTask.map (\response -> String.toLower response == "y")
in
shouldConvertTask
|> BackendTask.andThen
(\shouldConvert ->
if shouldConvert then
convertToSwaggerAndThenDecode config input value
else
("The input "
++ inputToString input
++ """ appears to be a Swagger doc,
and the CLI was not configured to automatically convert it to an Open API spec.
See the """
++ Ansi.Color.fontColor Ansi.Color.brightCyan "--auto-convert-swagger"
++ " flag for more info."
)
|> FatalError.fromString
|> BackendTask.fail
)
inputToString : OpenApi.Config.Input -> String
inputToString input =
case OpenApi.Config.oasPath input of
OpenApi.Config.File path ->
"file " ++ path
OpenApi.Config.Url url ->
"url " ++ Url.toString url
extractFormats : Json.Decode.Value -> Result Json.Decode.Error (List { format : String, basicType : Common.BasicType })
extractFormats value =
Json.Decode.decodeValue formatDecoder value
formatDecoder : Json.Decode.Decoder (List { format : String, basicType : Common.BasicType })
formatDecoder =
let
typeDecoder : Json.Decode.Decoder Common.BasicType
typeDecoder =
Json.Decode.string
|> Json.Decode.andThen
(\type_ ->
case type_ of
"string" ->
Json.Decode.succeed Common.String
"integer" ->
Json.Decode.succeed Common.Integer
"boolean" ->
Json.Decode.succeed Common.Boolean
"number" ->
Json.Decode.succeed Common.Number
_ ->
Json.Decode.fail "Unexpected type"
)
in
Json.Decode.oneOf
[ Json.Decode.list (Json.Decode.lazy (\_ -> formatDecoder))
|> Json.Decode.map List.concat
, Json.Decode.dict Json.Decode.value
|> Json.Decode.andThen
(\dict ->
case ( Dict.get "format" dict, Dict.get "type" dict ) of
( Just format, Just type_ ) ->
Result.map2
(\fmt basicType ->
[ { format = fmt
, basicType = basicType
}
]
)
(Json.Decode.decodeValue Json.Decode.string format)
(Json.Decode.decodeValue typeDecoder type_)
|> resultToDecoder
_ ->
dict
|> Dict.values
|> Result.Extra.combineMap
(\v -> Json.Decode.decodeValue (Json.Decode.lazy (\_ -> formatDecoder)) v)
|> Result.map List.concat
|> resultToDecoder
)
, Json.Decode.succeed []
]
resultToDecoder : Result Json.Decode.Error a -> Json.Decode.Decoder a
resultToDecoder result =
case result of
Ok ok ->
Json.Decode.succeed ok
Err e ->
Json.Decode.fail (Json.Decode.errorToString e)
convertToSwaggerAndThenDecode : OpenApi.Config.Config -> OpenApi.Config.Input -> Json.Decode.Value -> BackendTask.BackendTask FatalError.FatalError ( OpenApi.OpenApi, List { format : String, basicType : Common.BasicType } )
convertToSwaggerAndThenDecode config input value =
convertSwaggerToOpenApi config (Json.Encode.encode 0 value)
|> BackendTask.andThen
(\swagger ->
parseOriginal input swagger
|> BackendTask.andThen mergeOverrides
)
|> Pages.Script.Spinner.runTask "Convert Swagger to Open API"
|> BackendTask.andThen (\converted -> decodeOpenApiSpecOrFail { hasAttemptedToConvertFromSwagger = True } config input converted)
parseErrorToFatalError : ParseError -> FatalError.FatalError
parseErrorToFatalError parseError =
case parseError of
JsonDecodeError decodeError ->
jsonErrorToFatalError decodeError
YamlParseError yamlError ->
yamlError
|> Yaml.Decode.errorToString
|> Ansi.Color.fontColor Ansi.Color.brightRed
|> FatalError.fromString
jsonErrorToFatalError : Json.Decode.Error -> FatalError.FatalError
jsonErrorToFatalError decodeError =
decodeError
|> Json.Decode.errorToString
|> Ansi.Color.fontColor Ansi.Color.brightRed
|> FatalError.fromString
overrideWith : Json.Value.JsonValue -> Json.Value.JsonValue -> Result String Json.Value.JsonValue
overrideWith override original =
case override of
Json.Value.ObjectValue overrideObject ->
case original of
Json.Value.ObjectValue originalObject ->
Dict.merge
(\key value res -> Result.map (\acc -> ( key, value ) :: acc) res)
(\key originalValue overrideValue res ->
if overrideValue == Json.Value.NullValue then
res
else if key == "security" then
Result.map (\acc -> ( key, overrideValue ) :: acc) res
else
Result.map2
(\acc newValue -> ( key, newValue ) :: acc)
res
(overrideWith overrideValue originalValue)
)
(\key value res -> Result.map (\acc -> ( key, value ) :: acc) res)
(Dict.fromList originalObject)
(Dict.fromList overrideObject)
(Ok [])
|> Result.map (\list -> Json.Value.ObjectValue (List.reverse list))
_ ->
overrideError override original
Json.Value.ArrayValue overrideArray ->
case original of
Json.Value.ArrayValue originalArray ->
mergeArrays overrideArray originalArray []
_ ->
overrideError override original
Json.Value.BoolValue _ ->
Ok override
Json.Value.NumericValue _ ->
Ok override
Json.Value.StringValue _ ->
Ok override
Json.Value.NullValue ->
Ok override
mergeArrays : List Json.Value.JsonValue -> List Json.Value.JsonValue -> List Json.Value.JsonValue -> Result String Json.Value.JsonValue
mergeArrays override original acc =
case original of
ogHead :: ogTail ->
case override of
Json.Value.NullValue :: ovTail ->
mergeArrays ovTail ogTail acc
ovHead :: ovTail ->
case overrideWith ovHead ogHead of
Ok newHead ->
mergeArrays ovTail ogTail (newHead :: acc)
Err e ->
Err e
[] ->
if List.isEmpty original then
Ok (Json.Value.ArrayValue (List.reverse acc))
else
Ok (Json.Value.ArrayValue (List.reverse acc ++ original))
[] ->
if List.isEmpty override then
Ok (Json.Value.ArrayValue (List.reverse acc))
else
Ok (Json.Value.ArrayValue (List.reverse acc ++ override))
overrideError : Json.Value.JsonValue -> Json.Value.JsonValue -> Result String Json.Value.JsonValue
overrideError override original =
let
toString : Json.Value.JsonValue -> String
toString v =
Json.Encode.encode 0 (Json.Value.encode v)
message : String
message =
"Cannot override original value " ++ toString original ++ " with override " ++ toString override
in
Err message
convertSwaggerToOpenApi : OpenApi.Config.Config -> String -> BackendTask.BackendTask FatalError.FatalError String
convertSwaggerToOpenApi config input =
case OpenApi.Config.swaggerConversionCommand config of
Just { command, args } ->
BackendTask.Stream.fromString input
|> BackendTask.Stream.pipe (BackendTask.Stream.command command args)
|> BackendTask.Stream.read
|> BackendTask.mapError
(\error ->
FatalError.fromString <|
("Attempted to convert the Swagger doc to an Open API spec using\n"
++ Ansi.Color.fontColor Ansi.Color.brightCyan
(String.join " "
(command :: args)
)
++ "\nbut encountered an issue:\n\n"
++ (Ansi.Color.fontColor Ansi.Color.brightRed <|
case error.recoverable of
BackendTask.Stream.StreamError err ->
err
BackendTask.Stream.CustomError errCode maybeBody ->
case maybeBody of
Just body ->
body
Nothing ->
String.fromInt errCode
)
)
)
|> BackendTask.map .body
Nothing ->
let
swaggerConversionUrl : String
swaggerConversionUrl =
OpenApi.Config.swaggerConversionUrl config
in
BackendTask.Http.post swaggerConversionUrl
(BackendTask.Http.stringBody "application/yaml" input)
(BackendTask.Http.expectJson Json.Decode.value)
|> BackendTask.map (Json.Encode.encode 0)
|> BackendTask.mapError
(\error ->
FatalError.fromString
("Attempted to convert the Swagger doc to an Open API spec but encountered an issue:\n\n"
++ (Ansi.Color.fontColor Ansi.Color.brightRed <|
case error.recoverable of
BackendTask.Http.BadUrl _ ->
"with the URL: " ++ swaggerConversionUrl
BackendTask.Http.Timeout ->
"the request timed out"
BackendTask.Http.NetworkError ->
"with a network error"
BackendTask.Http.BadStatus { statusCode, statusText } _ ->
"status code " ++ String.fromInt statusCode ++ ", " ++ statusText
BackendTask.Http.BadBody _ _ ->
"expected a string response body but got something else"
)
)
)
swaggerFieldDecoder : Json.Decode.Decoder String
swaggerFieldDecoder =
Json.Decode.field "swagger" Json.Decode.string
{-| Because all OpenAPI specs are objects (including the overrides), we identify JSON by searching for an open brace at the beginning of the file.
That said, because yaml is a superset of JSON, this doesn't completely rule yaml out.
-}
probablyJsonRegex : Regex
probablyJsonRegex =
Regex.fromString "^\\s*\\{"
|> Maybe.withDefault Regex.never
type ParseError
= JsonDecodeError Json.Decode.Error
| YamlParseError Yaml.Decode.Error
decodeMaybeYaml : OpenApi.Config.Path -> String -> Result ParseError Json.Value.JsonValue
decodeMaybeYaml oasPath input =
let
path : String
path =
case oasPath of
OpenApi.Config.File file ->
file
OpenApi.Config.Url url ->
url.path
isProbablyJson : Bool
isProbablyJson =
String.endsWith ".json" path || Regex.contains probablyJsonRegex input
in
-- Short-circuit the error-prone yaml parsing of JSON structures if we
-- are reasonably confident that it is a JSON file
if isProbablyJson then
case Json.Decode.decodeString Json.Value.decoder input of
Ok decoded ->
Ok decoded
Err jsonError ->
-- If it errored out, it might be yaml
case Yaml.Decode.fromString yamlToJsonValueDecoder input of
Err _ ->
-- Not valid (or not successfully parsed) yaml.
-- Because we thought it was JSON, return the JSON parsing error
Err (JsonDecodeError jsonError)
Ok jsonFromYaml ->
Ok jsonFromYaml
else
case Yaml.Decode.fromString yamlToJsonValueDecoder input of
Err yamlError ->
-- If it errored out, it might be valid JSON that the yaml parser can't handle
case Json.Decode.decodeString Json.Value.decoder input of
Err jsonError ->
let
isProbablyYaml : Bool
isProbablyYaml =
String.endsWith ".yaml" path
|| String.endsWith ".yml" path
|| not (Regex.contains probablyJsonRegex input)
in
if isProbablyYaml then
-- Not valid JSON.
-- Because we thought it was yaml, return the yaml parsing error
Err (YamlParseError yamlError)
else
Err (JsonDecodeError jsonError)
Ok decoded ->
Ok decoded
Ok jsonFromYaml ->
Ok jsonFromYaml
yamlToJsonValueDecoder : Yaml.Decode.Decoder Json.Value.JsonValue
yamlToJsonValueDecoder =
Yaml.Decode.oneOf
[ Yaml.Decode.map Json.Value.NumericValue Yaml.Decode.float
, Yaml.Decode.map (\_ -> Json.Value.NullValue) Yaml.Decode.null
, Yaml.Decode.map Json.Value.StringValue Yaml.Decode.string
, Yaml.Decode.map Json.Value.BoolValue Yaml.Decode.bool
, Yaml.Decode.map
Json.Value.ArrayValue
(Yaml.Decode.list (Yaml.Decode.lazy (\_ -> yamlToJsonValueDecoder)))
, Yaml.Decode.map
(\dict -> Json.Value.ObjectValue (Dict.toList dict))
(Yaml.Decode.dict (Yaml.Decode.lazy (\_ -> yamlToJsonValueDecoder)))
]
width : Int
width =
120
generateFilesFromOpenApiSpecs :
List ( OpenApi.Config.Generate, OpenApi.OpenApi )