Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move Yaml Validator into Persistence Part 2 #700

Merged
merged 24 commits into from
Jul 23, 2024
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
f47376e
move Yaml Validator into persistence to setup for PAC CLI integration
abaskk-msft Jul 9, 2024
cee7faf
clean yaml validator project residue to integrate into persistence an…
abaskk-msft Jul 10, 2024
ef050cd
couple schema with schema loader
abaskk-msft Jul 11, 2024
ca58cc6
iteration two, ready for consumption by pac cli
abaskk-msft Jul 15, 2024
43dfe41
supress unused member of class
abaskk-msft Jul 15, 2024
5322752
rewrite of schema loader to store schema in dll on build and access f…
abaskk-msft Jul 17, 2024
dfb79a3
clean up new schema loader
abaskk-msft Jul 17, 2024
1d5d8c7
Merge branch 'master' into users/t-abaskar/persistence-yaml-validator…
abaskk-msft Jul 17, 2024
378656e
keep current commit head
abaskk-msft Jul 17, 2024
f773b62
add suppression suggestions
abaskk-msft Jul 17, 2024
ca1d151
access assembly from type to improve performance
abaskk-msft Jul 17, 2024
54b9b17
Interfaces for external use, make classes that interact with dependen…
abaskk-msft Jul 17, 2024
be6a1bf
Merge branch 'master' into users/t-abaskar/persistence-yaml-validator…
abaskk-msft Jul 17, 2024
e4def43
delete unused files
abaskk-msft Jul 17, 2024
82f1abb
check for validator interface instead of validator
abaskk-msft Jul 18, 2024
7a07194
make schema loader internal
abaskk-msft Jul 18, 2024
32c1de6
add factory to service provider. Create internal access for test in P…
abaskk-msft Jul 18, 2024
18b912b
remove unused directive
abaskk-msft Jul 19, 2024
caa24cb
remove unused file
abaskk-msft Jul 19, 2024
d06cf27
nit: whietspace at end of file
abaskk-msft Jul 19, 2024
1cc054c
make supressions inline
abaskk-msft Jul 19, 2024
f8f3696
move yaml-validator out with changes (persistence not compatiable wit…
abaskk-msft Jul 22, 2024
dcfea66
update project name
abaskk-msft Jul 22, 2024
b39d57c
strongly sign vailidator and make it visible to tests
abaskk-msft Jul 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion .version/PipelineAssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

// This is pipeline generated file. Do not modify. This will be replaced with the actual versions in the actual Pipeline.
using System.Reflection;
using System.Runtime.CompilerServices;
[assembly: AssemblyVersion("0.0.0.0")]
[assembly: AssemblyFileVersion("0.0.0.0")]
[assembly: AssemblyInformationalVersion("0.0.0.0-dev-00000000")]
[assembly: AssemblyInformationalVersion("0.0.0.0-dev-00000000")]
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
[assembly: InternalsVisibleTo("Persistence.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")]
2 changes: 1 addition & 1 deletion src/Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -90,4 +90,4 @@
<RestoreIgnoreFailedSource>true</RestoreIgnoreFailedSource>
<RestoreOutputPath>$(BaseIntermediateOutputPath)</RestoreOutputPath>
</PropertyGroup>
</Project>
</Project>
20 changes: 20 additions & 0 deletions src/Persistence.Tests/YamlValidator/ValidatorFactoryTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

namespace Persistence.Tests.YamlValidator;

[TestClass]
public class ValidatorFactoryTest
{
[TestMethod]
public void GetValidatorTest()
{
var factory = new ValidatorFactory();
var validator = factory.GetValidator();

Assert.IsNotNull(validator);
Assert.IsInstanceOfType(validator, typeof(Validator));
}
}
19 changes: 8 additions & 11 deletions src/Persistence.Tests/YamlValidator/ValidatorTest.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Json.Schema;
using Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

namespace Persistence.Tests.YamlValidator;
Expand All @@ -16,15 +15,12 @@ public class ValidatorTest
private static readonly string _invalidPath = Path.Combine(".", "_TestData", "ValidatorTests", "InvalidYaml") +
Path.DirectorySeparatorChar;

private readonly JsonSchema _schema;
private readonly Validator _yamlValidator;
private readonly IValidator _yamlValidator;

public ValidatorTest()
{
var schemaFileLoader = new SchemaLoader();
_schema = schemaFileLoader.Load();
var resultVerbosity = new VerbosityData(Constants.Verbose);
_yamlValidator = new Validator(resultVerbosity.EvalOptions, resultVerbosity.JsonOutputOptions);
var validatorFactory = new ValidatorFactory();
_yamlValidator = validatorFactory.GetValidator();
}

[TestMethod]
Expand All @@ -34,8 +30,8 @@ public ValidatorTest()

public void TestValidationValidYaml(string filename)
{
var rawYaml = Utility.ReadFileData($@"{_validPath}{filename}");
var result = _yamlValidator.Validate(_schema, rawYaml);
var rawYaml = File.ReadAllText($@"{_validPath}{filename}");
var result = _yamlValidator.Validate(rawYaml);
Assert.IsTrue(result.SchemaValid);
}

Expand All @@ -48,10 +44,11 @@ public void TestValidationValidYaml(string filename)
[DataRow("EmptyArray.yaml")]
[DataRow("Empty.yaml")]
[DataRow("NamelessObjectNoControl.yaml")]
[DataRow("NotYaml.yaml")]
public void TestValidationInvalidYaml(string filename)
{
var rawYaml = Utility.ReadFileData($@"{_invalidPath}{filename}");
var result = _yamlValidator.Validate(_schema, rawYaml);
var rawYaml = File.ReadAllText($@"{_invalidPath}{filename}");
var result = _yamlValidator.Validate(rawYaml);
Assert.IsFalse(result.SchemaValid);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
features => [
{
name => lorem ipsum,
points => [
"bullet 1",
"bullet 2"
]
},
{
name => lorem ipsum 2,
description => lorem ipsum 3
}
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
<PublicSign>true</PublicSign>
<!-- Workaround for version range https://github.com/NuGet/Home/issues/11842 -->
<RestorePackagesWithLockFile>true</RestorePackagesWithLockFile>
<NoWarn>$(NoWarn);NU1601;CA1822</NoWarn>
<NoWarn>$(NoWarn);NU1601</NoWarn>
</PropertyGroup>

<ItemGroup Label="Global usings">
Expand All @@ -47,14 +47,11 @@
<PackageReference Include="Yaml2JsonNode" Version="2.1.0" />
</ItemGroup>

<!-- Link schemas and build them into the assembly for the YamlValidator -->
<ItemGroup>
<Content Include="..\..\docs\pa.yaml-schema.json" Link="YamlValidator\schema\pa.yaml-schema.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\subschemas\control-type-schema.json" Link="YamlValidator\schema\subschemas\control-type-schema.json" CopyToOutputDirectory="PreserveNewest" />
<Content Include="..\..\docs\subschemas\control-property-schema.json" Link="YamlValidator\schema\subschemas\control-property-schema.json" CopyToOutputDirectory="PreserveNewest" />
<EmbeddedResource Include="..\..\docs\**\*.json" >
<Link>YamlValidator\schema\%(RecursiveDir)%(Filename)%(Extension)</Link>
</EmbeddedResource>
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Persistence.Tests" Key="0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9" />
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
</ItemGroup>

</Project>
</Project>
9 changes: 3 additions & 6 deletions src/Persistence/YamlValidator/Constants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,11 @@ namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public static class Constants
{
public const string FileTypeName = "file";
public const string FolderTypeName = "folder";
public const string YamlFileExtension = ".pa.yaml";
public const string JsonFileExtension = ".json";

public const string Verbose = "verbose";
public const string notYamlError = "File is not YAML";
public const string emptyYamlError = "Empty YAML file";

// runtime constants
// default schema path
public static readonly string DefaultSchemaPath = Path.Combine(".", "schema", "pa.yaml-schema.json");
public const string subNamespace = "YamlValidator";
}
9 changes: 9 additions & 0 deletions src/Persistence/YamlValidator/IValidator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public interface IValidator
{
ValidatorResults Validate(string yamlString);
}
9 changes: 9 additions & 0 deletions src/Persistence/YamlValidator/IValidatorFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public interface IValidatorFactory
{
IValidator GetValidator();
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
}
46 changes: 36 additions & 10 deletions src/Persistence/YamlValidator/SchemaLoader.cs
Original file line number Diff line number Diff line change
@@ -1,28 +1,54 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using System.Reflection;
using Json.Schema;

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public class SchemaLoader
{
private const string _schemaFolderPath = "subschemas";
private static readonly string _schemaPath = Path.Combine(".", "YamlValidator", "schema", "pa.yaml-schema.json");
private const string _schemaFolderPath = "schema";
private const string _subschemaFolderPath = "subschemas";

[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static",
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
Justification = "Suppress to make classes stateless")]
public JsonSchema Load()
{
var node = JsonSchema.FromFile(_schemaPath);
var schemaFolder = Path.GetDirectoryName(_schemaPath);
var subschemaPaths = Directory.GetFiles($@"{schemaFolder}{Path.DirectorySeparatorChar}{_schemaFolderPath}",
$"*{Constants.JsonFileExtension}");
var assembly = typeof(SchemaLoader).Assembly;

foreach (var path in subschemaPaths)
JsonSchema? node = null;
foreach (var file in assembly.GetManifestResourceNames())
{
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
var subschema = JsonSchema.FromFile(path);
SchemaRegistry.Global.Register(subschema);
}
var fileStream = assembly.GetManifestResourceStream(file);
var assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
if (fileStream == null)
{
throw new IOException($"Resource {file} could not found in assembly {assemblyName}");
}
using var streamReader = new StreamReader(fileStream);
var jsonSchemaString = streamReader.ReadToEnd();
var schema = JsonSchema.FromText(jsonSchemaString);

// assembly name is Microsoft.PowerPlatform.PowerApps.Persistence
// subNamespace is YamlValidator, schemas live in the linked schema folder
var rootFileName = $"{assemblyName}.{Constants.subNamespace}.{_schemaFolderPath}";

if (file.StartsWith($"{rootFileName}.{_subschemaFolderPath}.", StringComparison.Ordinal))
{
// these virtual uri's are used to resolve $ref's in the schema, they aren't
// represented like this in the dll
schema.BaseUri = new Uri($"file://{_schemaFolderPath}/{_subschemaFolderPath}/");
SchemaRegistry.Global.Register(schema);
continue;
}
schema.BaseUri = new Uri($"file://{_schemaFolderPath}");
node = schema;
}
if (node == null)
{
throw new InvalidDataException("Schema was not able to be read into memory");
}
return node;
}
}
Expand Down
6 changes: 0 additions & 6 deletions src/Persistence/YamlValidator/Utility.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@ namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public class Utility
{
public static string ReadFileData(string filePath)
{
var yamlData = File.ReadAllText(filePath);
return yamlData;
}

public static YamlStream MakeYamlStream(string yamlString)
{
var stream = new YamlStream();
Expand Down
40 changes: 25 additions & 15 deletions src/Persistence/YamlValidator/Validator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,40 +4,47 @@
using Json.Schema;
using Yaml2JsonNode;
using System.Text.Json;
using YamlDotNet.Core;
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
using YamlDotNet.RepresentationModel;

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public class Validator
internal class Validator : IValidator
{
private readonly EvaluationOptions _verbosityOptions;
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0052:Remove unread private member",
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
Justification = "Suppress serializing the raw validator errors into json will be useful for future use")]
private readonly JsonSerializerOptions _serializerOptions;

public Validator(EvaluationOptions options, JsonSerializerOptions resultSerializeOptions)
private readonly JsonSchema _schema;
public Validator(EvaluationOptions options, JsonSerializerOptions resultSerializeOptions, JsonSchema schema)
{
// to do: add verbosity flag and allow users to choose verbosity of evaluation
_verbosityOptions = options;
_serializerOptions = resultSerializeOptions;
_schema = schema;
}

public ValidatorResults Validate(JsonSchema schema, string yamlFileData)
public ValidatorResults Validate(string yamlFileData)
{
var yamlStream = Utility.MakeYamlStream(yamlFileData);
YamlStream yamlStream;
try
{
yamlStream = Utility.MakeYamlStream(yamlFileData);
}
catch (YamlException)
{
return new ValidatorResults(false, new List<ValidatorError> { new(Constants.notYamlError) });
}

var jsonData = yamlStream.Documents.Count > 0 ? yamlStream.Documents[0].ToJsonNode() : null;

// here we say that empty yaml is serialized as null json
if (jsonData == null)
{
return new ValidatorResults(false, new List<ValidatorError> { new("Empty YAML file") });
return new ValidatorResults(false, new List<ValidatorError> { new(Constants.emptyYamlError) });
}
var results = schema.Evaluate(jsonData, _verbosityOptions);

// not used but may help if we ever need to serialize the evaluation results into json format to feed into
// a VSCode extension or other tool
var output = JsonSerializer.Serialize(results, _serializerOptions);
var results = _schema.Evaluate(jsonData, _verbosityOptions);

var schemaValidity = results.IsValid;
// TBD: filter actual errors versus false positives
// we look for errors that are not valid, have errors, and have an instance location (i.e are not oneOf errors)
var yamlValidatorErrors = new List<ValidatorError>();
if (!schemaValidity)
{
Expand All @@ -46,7 +53,10 @@ public ValidatorResults Validate(JsonSchema schema, string yamlFileData)
node.HasErrors).ToList();
foreach (var trace in traceList)
{
yamlValidatorErrors.Add(new ValidatorError(trace));
var instanceLocation = trace.InstanceLocation.ToString();
var schemaPath = trace.EvaluationPath.ToString();
var errors = trace.Errors;
yamlValidatorErrors.Add(new ValidatorError(instanceLocation, schemaPath, errors));
}
}

Expand Down
11 changes: 5 additions & 6 deletions src/Persistence/YamlValidator/ValidatorError.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Json.Schema;

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

public class ValidatorError
{
public string InstanceLocation { get; }
public string SchemaPath { get; }
public IReadOnlyDictionary<string, string>? Errors { get; }

public ValidatorError(EvaluationResults results)
public ValidatorError(string instancePath, string schemaPath, IReadOnlyDictionary<string, string>? errors)
{
InstanceLocation = results.InstanceLocation.ToString();
SchemaPath = results.EvaluationPath.ToString();
Errors = results.Errors;
InstanceLocation = instancePath;
SchemaPath = schemaPath;
Errors = errors;
}

public ValidatorError(string error)
Expand Down
33 changes: 33 additions & 0 deletions src/Persistence/YamlValidator/ValidatorFactory.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Json.Schema;
using System.Text.Json;

namespace Microsoft.PowerPlatform.PowerApps.Persistence.YamlValidator;

internal class ValidatorFactory : IValidatorFactory
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static",
abaskk-msft marked this conversation as resolved.
Show resolved Hide resolved
Justification = "Suppress to make classes stateless")]
public IValidator GetValidator()
{
// register schema in from memory into global schema registry
var schemaLoader = new SchemaLoader();
var serializedSchema = schemaLoader.Load();

var evalOptions = new EvaluationOptions
{
OutputFormat = OutputFormat.List
};

// pass in serailization options for validator results object to json
// This is unused for now but can be useful for producing raw json validation results which can be consumed elsewhere
var resultSerializeOptions = new JsonSerializerOptions
{
Converters = { new EvaluationResultsJsonConverter() }
};

return new Validator(evalOptions, resultSerializeOptions, serializedSchema);
}
}
2 changes: 2 additions & 0 deletions src/Persistence/YamlValidator/ValidatorResults.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ public ValidatorResults(bool schemaValid, IReadOnlyList<ValidatorError> traversa
TraversalResults = FilterErrors(traversalResults);
}

[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1822:Mark members as static",
Justification = "Suppress to make classes stateless")]
// This will filter out the false positives that are not relevant to the error output, when the validation is false
private ReadOnlyCollection<ValidatorError> FilterErrors(IReadOnlyList<ValidatorError> traversalResults)
{
Expand Down
Loading
Loading