winget-cli

Unnamed repository; edit this file 'description' to name the repository.
Log | Files | Refs | README | LICENSE

JsonSchemaValidation.cpp (2246B)


      1 // Copyright (c) Microsoft Corporation.
      2 // Licensed under the MIT License.
      3 #include "pch.h"
      4 #include "winget/JsonSchemaValidation.h"
      5 #include "winget/Resources.h"
      6 
      7 namespace AppInstaller::JsonSchema
      8 {
      9     Json::Value LoadSchemaDoc(std::string_view schemaStr)
     10     {
     11         Json::Value schemaJson;
     12         int schemaLength = static_cast<int>(schemaStr.length());
     13         Json::CharReaderBuilder charReaderBuilder;
     14         const std::unique_ptr<Json::CharReader> jsonReader(charReaderBuilder.newCharReader());
     15         std::string errorMsg;
     16         if (!jsonReader->parse(schemaStr.data(), schemaStr.data() + schemaLength, &schemaJson, &errorMsg))
     17         {
     18             THROW_HR_MSG(E_UNEXPECTED, "Jsoncpp parser failed to parse the schema doc. Reason: %hs", errorMsg.c_str());
     19         }
     20 
     21         return schemaJson;
     22     }
     23 
     24     Json::Value LoadResourceAsSchemaDoc(PCWSTR resourceName, PCWSTR resourceType)
     25     {
     26         return LoadSchemaDoc(Resource::GetResourceAsString(resourceName, resourceType));
     27     }
     28 
     29     void PopulateSchema(const Json::Value& schemaJson, valijson::Schema& schema)
     30     {
     31         valijson::SchemaParser schemaParser;
     32         valijson::adapters::JsonCppAdapter jsonSchemaAdapter(schemaJson);
     33         schemaParser.populateSchema(jsonSchemaAdapter, schema);
     34     }
     35 
     36     bool Validate(const valijson::Schema& schema, const Json::Value& json, valijson::ValidationResults& results)
     37     {
     38         valijson::Validator schemaValidator;
     39         valijson::adapters::JsonCppAdapter jsonAdapter(json);
     40         return schemaValidator.validate(schema, jsonAdapter, &results);
     41     }
     42 
     43     std::string GetErrorStringFromResults(valijson::ValidationResults& results)
     44     {
     45         valijson::ValidationResults::Error error;
     46         std::stringstream ss;
     47 
     48         ss << "Schema validation failed." << std::endl;
     49         while (results.popError(error))
     50         {
     51             std::string context;
     52             for (auto itr = error.context.begin(); itr != error.context.end(); itr++)
     53             {
     54                 context += *itr;
     55             }
     56 
     57             ss << "Error context: " << context << " Description: " << error.description << std::endl;
     58         }
     59 
     60         return ss.str();
     61     }
     62 }