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

YamlDocument for introspection #981

Closed
StephenHodgson opened this issue Sep 24, 2024 · 1 comment
Closed

YamlDocument for introspection #981

StephenHodgson opened this issue Sep 24, 2024 · 1 comment

Comments

@StephenHodgson
Copy link

It'd be nice to have something similar to System.Text.Json.JsonDocument to do introspection of the yaml document itself and possibly preserve aspects of the document when existing items are only modified and written back to the same file that was edited.

In theory this would help preserve the scalar styles, sequence styles and comments.

@StephenHodgson
Copy link
Author

After some time I was able to successfully figure out how to do this with current implementation but could be simpler:

Console.WriteLine("Enter the path to the YAML file:");
var inputPath = Console.ReadLine();

// check that path is valid and file exists
if (!File.Exists(inputPath))
{
    Console.WriteLine("File does not exist");
    return;
}

// open the file and read the contents as a string
var yamlContent = await File.ReadAllTextAsync(inputPath);
using var stringReader = new StringReader(yamlContent);
var yamlStream = new YamlStream();

try
{
    yamlStream.Load(stringReader);
}
finally
{
    stringReader.Close();
}

var yamlDocument = yamlStream.Documents[0];
var rootNode = (YamlMappingNode)yamlDocument.RootNode;
var yamlObject = rootNode.Children;
Console.WriteLine("YAML file loaded successfully");

// modify the yamlDocument to set the workflow name property to TEST
yamlObject["name"] = "TEST";

// After modifying the yamlObject, serialize and write it back to the same input file
var serializer = new SerializerBuilder()
    .WithIndentedSequences()
    .Build();
await using var output = new StringWriter();

try
{
    serializer.Serialize(output, rootNode);
    var modifiedYamlContent = output.ToString();
    await File.WriteAllTextAsync(inputPath, modifiedYamlContent);
    Console.WriteLine("YAML file modified successfully");
}
finally
{
    output.Close();
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant