Sharp.Augeas/CodeLiturgy.Augeas/Augeas.cs

114 lines
3.4 KiB
C#

using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using CodeLiturgy.Augeas.Test;
using static CodeLiturgy.Augeas.AugeasExtern;
using static CodeLiturgy.Augeas.AugFlags;
namespace CodeLiturgy.Augeas
{
/// <summary>
/// Augeas Core containing the settings of this instance.
/// We can have multiple augeas cores during the execution.
/// </summary>
public unsafe partial class Augeas
{
private readonly IntPtr _augeas;
/// <summary>
/// Augeas Core Destructor
/// </summary>
~Augeas()
{
// Effectively free the pointer
close_aug(_augeas);
}
/// <summary>
/// Augeas Core constructor
/// </summary>
/// <param name="augSettings">Augeas core instance settings</param>
public Augeas(AugSettings augSettings)
{
_augeas = init_aug(augSettings, NO_STDINC | NO_LOAD);
}
/// <summary>
/// Prints a preview of the desired segment in <see cref="matchPath"/>
/// </summary>
/// <param name="matchPath">Augeas path to filter out the configuration</param>
/// <param name="filePath">The actual configuration file path</param>
public void PrintPreview(string matchPath)
{
print_preview(_augeas, matchPath);
}
/// <summary>
/// Finalize the augeas instance.
/// </summary>
public void Close()
{
close_aug(_augeas);
}
/// <summary>
/// Finalize the augeas instance.
/// </summary>
public void LoadFile(string configurationFilePath)
{
load_file(_augeas, configurationFilePath);
}
/// <summary>
/// Prints the Aug Tree of a segment
/// </summary>
/// <param name="matchPath"></param>
/// <param name="filePath"></param>
public void PrintAugTree(string matchPath)
{
print_tree(_augeas, matchPath);
}
/// <summary>
/// Returns the tree given the augeas configuration path.
/// </summary>
/// <param name="matchPath">configuration path.</param>
/// <returns>Dictionary with the Tree</returns>
public Dictionary<string,string> GetTree(string matchPath)
{
var result = new Dictionary<string, string>();
var raw = get_tree(_augeas, matchPath);
string sb = Marshal.PtrToStringAnsi((IntPtr)raw);
if (sb == null) return result;
free_str(raw);
var lines = sb.Split(";ENDL;");
foreach (var line in lines)
{
var pair = line.Split(";VAL;");
if (pair.Length == 2)
{
result.Add(pair[0].Remove(0, 3), pair[1]);
}
}
return result;
}
public static void Benchmark(Action act, int iterations)
{
GC.Collect();
act.Invoke(); // run once outside of loop to avoid initialization costs
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < iterations; i++)
{
act.Invoke();
}
sw.Stop();
Console.WriteLine((sw.ElapsedMilliseconds / iterations).ToString());
}
}
}