summaryrefslogtreecommitdiff
path: root/src/Task/FileHandlers/YamlFileHandler.cs
blob: 3c86db9043089dde2ad7d957634cb14531f13d6c (plain)
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
using System.IO;
using System.Text.Json;
using System.Threading.Tasks;

using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.System.Text.Json;

namespace AggregateConfigBuildTask.FileHandlers
{
    /// <inheritdoc/>
    public class YamlFileHandler : IFileHandler
    {
        private readonly IFileSystem fileSystem;

        internal YamlFileHandler(IFileSystem fileSystem)
        {
            this.fileSystem = fileSystem;
        }

        /// <inheritdoc/>
        public async ValueTask<JsonElement> ReadInput(string inputPath)
        {
            using (TextReader reader = fileSystem.OpenText(inputPath))
            {
                return await new ValueTask<JsonElement>(
                    Task.FromResult(
                        new DeserializerBuilder()
                            .WithNamingConvention(CamelCaseNamingConvention.Instance)
                            .WithTypeConverter(new SystemTextJsonYamlTypeConverter())
                            .WithTypeInspector(x => new SystemTextJsonTypeInspector(x))
                            .Build()
                            .Deserialize<JsonElement>(reader))).ConfigureAwait(false);
            }
        }

        /// <inheritdoc/>
        public void WriteOutput(JsonElement? mergedData, string outputPath)
        {
            var serializer = new SerializerBuilder()
                .WithNamingConvention(CamelCaseNamingConvention.Instance)
                .WithTypeConverter(new SystemTextJsonYamlTypeConverter())
                .WithTypeInspector(x => new SystemTextJsonTypeInspector(x))
                .Build();
            var yamlContent = serializer.Serialize(mergedData);
            fileSystem.WriteAllText(outputPath, yamlContent);
        }
    }
}