Add a utility for YAML loading. (#98)
This commit is contained in:
34
src/Yaml.cs
Normal file
34
src/Yaml.cs
Normal file
@@ -0,0 +1,34 @@
|
||||
using System.IO;
|
||||
using System.Threading.Tasks;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
|
||||
namespace k8s
|
||||
{
|
||||
/// <summary>
|
||||
/// This is a utility class that helps you load objects from YAML files.
|
||||
/// </summary>
|
||||
|
||||
public class Yaml {
|
||||
public static async Task<T> LoadFromStreamAsync<T>(Stream stream) {
|
||||
var reader = new StreamReader(stream);
|
||||
var content = await reader.ReadToEndAsync();
|
||||
return LoadFromString<T>(content);
|
||||
}
|
||||
|
||||
public static async Task<T> LoadFromFileAsync<T> (string file) {
|
||||
using (FileStream fs = File.Open(file, FileMode.Open, FileAccess.Write, FileShare.None)) {
|
||||
return await LoadFromStreamAsync<T>(fs);
|
||||
}
|
||||
}
|
||||
|
||||
public static T LoadFromString<T>(string content) {
|
||||
var deserializer =
|
||||
new DeserializerBuilder()
|
||||
.WithNamingConvention(new CamelCaseNamingConvention())
|
||||
.Build();
|
||||
var obj = deserializer.Deserialize<T>(content);
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
}
|
||||
39
tests/YamlTests.cs
Normal file
39
tests/YamlTests.cs
Normal file
@@ -0,0 +1,39 @@
|
||||
using System.IO;
|
||||
using k8s.Models;
|
||||
using Xunit;
|
||||
|
||||
namespace k8s.Tests
|
||||
{
|
||||
public class YamlTests {
|
||||
[Fact]
|
||||
public void LoadFromString()
|
||||
{
|
||||
var content = @"apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: foo
|
||||
";
|
||||
|
||||
var obj = Yaml.LoadFromString<V1Pod>(content);
|
||||
|
||||
Assert.Equal("foo", obj.Metadata.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void LoadFromStream()
|
||||
{
|
||||
var content = @"apiVersion: v1
|
||||
kind: Pod
|
||||
metadata:
|
||||
name: foo
|
||||
";
|
||||
|
||||
using (MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(content)))
|
||||
{
|
||||
var obj = Yaml.LoadFromStreamAsync<V1Pod>(stream).Result;
|
||||
|
||||
Assert.Equal("foo", obj.Metadata.Name);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user