static void doAnalyzeSwaggerDefinitionReferences()

in rest-api/src/jetbrains/buildServer/server/rest/swagger/SwaggerUtil.java [34:102]


  static void doAnalyzeSwaggerDefinitionReferences(final Swagger swagger) {
    final HashSet<String> usedReferences = new HashSet<String>();

    // Collect usages in paths
    for (Path path : swagger.getPaths().values()) {
      for (Operation operation : path.getOperations()) {
        final List<Parameter> parameters = operation.getParameters();
        for (Parameter parameter : parameters) {
          if (parameter instanceof BodyParameter) {
            final BodyParameter bp = (BodyParameter)parameter;
            final Model schema = bp.getSchema();
            if (schema instanceof RefModel) {
              RefModel rm = (RefModel)schema;
              final String ref = rm.getSimpleRef();
              usedReferences.add(ref);
            }
          }
        }
        final Map<String, Response> responses = operation.getResponses();
        for (Response response : responses.values()) {
          final Property schema = response.getSchema();
          if (schema instanceof RefProperty) {
            RefProperty rp = (RefProperty)schema;
            final String ref = rp.getSimpleRef();
            usedReferences.add(ref);
          }
        }
      }
    }

    final Map<String, Model> definitions = swagger.getDefinitions();

    final ArrayDeque<String> queue = new ArrayDeque<String>();

    queue.addAll(usedReferences);

    while (!queue.isEmpty()) {
      final String name = queue.pop();
      final Model model = definitions.get(name);
      if (model == null) {
        LOG.warn("Swagger definition '" + name + "' referenced but not found.");
        continue;
      }
      final Map<String, Property> properties = model.getProperties();
      if (properties == null) continue;
      for (Property property : properties.values()) {
        final String ref = getPropertySimpleRef(property);
        if (ref != null) {
          if (usedReferences.add(ref)) {
            queue.add(ref);
          }
        }
      }
    }

    final int used = usedReferences.size();
    final int total = definitions.size();
    LOG.info("Swagger definitions stats: Total=" + total + " Used=" + used);
    if (used != total) {
      final LinkedHashSet<String> unused = new LinkedHashSet<String>(definitions.keySet());
      unused.removeAll(usedReferences);
      if (unused.size() > 30) {
        LOG.warn("Too much unused definitions. Enable debug logs to see them");
        LOG.debug("Unused definitions: " + unused);
      } else {
        LOG.info("Unused definitions: " + unused);
      }
    }
  }