2121import io .airlift .airline .Option ;
2222
2323import io .swagger .parser .OpenAPIParser ;
24+ import io .swagger .v3 .oas .models .OpenAPI ;
2425import io .swagger .v3 .parser .core .models .SwaggerParseResult ;
26+ import org .openapitools .codegen .utils .ModelUtils ;
2527
2628import java .util .HashSet ;
2729import java .util .List ;
@@ -34,26 +36,58 @@ public class Validate implements Runnable {
3436 description = "location of the OpenAPI spec, as URL or file (required)" )
3537 private String spec ;
3638
39+ @ Option (name = { "--recommend" }, title = "recommend spec improvements" )
40+ private Boolean recommend ;
41+
3742 @ Override
3843 public void run () {
3944 System .out .println ("Validating spec (" + spec + ")" );
4045
4146 SwaggerParseResult result = new OpenAPIParser ().readLocation (spec , null , null );
4247 List <String > messageList = result .getMessages ();
43- Set <String > messages = new HashSet <String >(messageList );
48+ Set <String > errors = new HashSet <String >(messageList );
49+ Set <String > warnings = new HashSet <String >();
4450
45- if (messages .size () > 0 ) {
46- StringBuilder sb = new StringBuilder ();
47- sb .append (System .lineSeparator ());
48- for (String message : messages ) {
49- sb .append (String .format ("\t - %s%s" , message , System .lineSeparator ()));
51+ StringBuilder sb = new StringBuilder ();
52+ OpenAPI specification = result .getOpenAPI ();
53+
54+ if (Boolean .TRUE .equals (recommend )) {
55+ if (specification != null ) {
56+ // Add information about unused models to the warnings set.
57+ List <String > unusedModels = ModelUtils .getUnusedSchemas (specification );
58+ if (unusedModels != null ) {
59+ unusedModels .forEach (name -> warnings .add ("Unused model: " + name ));
60+ }
5061 }
62+ }
63+
64+ if (errors .size () > 0 ) {
65+ sb .append ("Errors:" ).append (System .lineSeparator ());
66+ errors .forEach (msg ->
67+ sb .append ("\t -" ).append (msg ).append (System .lineSeparator ())
68+ );
69+ }
70+
71+ if (!warnings .isEmpty ()) {
72+ sb .append ("Warnings: " ).append (System .lineSeparator ());
73+ warnings .forEach (msg ->
74+ sb .append ("\t -" ).append (msg ).append (System .lineSeparator ())
75+ );
76+ }
77+
78+ if (!errors .isEmpty ()) {
5179 sb .append (System .lineSeparator ());
52- sb .append ("[error] Spec is invalid ." );
80+ sb .append ("[error] Spec has " ). append ( errors . size ()). append ( " errors ." );
5381 System .err .println (sb .toString ());
5482 System .exit (1 );
83+ } else if (!warnings .isEmpty ()) {
84+ sb .append (System .lineSeparator ());
85+ sb .append ("[info] Spec has " ).append (warnings .size ()).append (" recommendation(s)." );
5586 } else {
56- System .out .println ("No validation errors detected." );
87+ // we say "issues" here rather than "errors" to account for both errors and issues.
88+ sb .append ("No validation issues detected." );
5789 }
90+
91+ System .out .println (sb .toString ());
5892 }
5993}
0 commit comments