mycroforge/MycroForge.CLI/CodeGen/Source.cs

61 lines
1.6 KiB
C#

using System.Text.RegularExpressions;
namespace MycroForge.CLI.CodeGen;
public class Source
{
private string _text;
public string Text => _text;
public Source(string text)
{
_text = text;
}
public SourceMatch Find(string pattern)
{
var regex = new Regex(pattern);
var match = regex.Match(_text);
if (match.Value.Length == 0)
throw new Exception($"No match found for pattern: {pattern}");
return new SourceMatch(match.Index, match.Value);
}
public List<SourceMatch> FindAll(string pattern)
{
var regex = new Regex(pattern);
var matches = regex.Matches(_text);
return matches.Select(m => new SourceMatch(m.Index, m.Value)).ToList();
}
public Source InsertSingleLine(int index, string text)
{
_text = _text.Insert(index, string.Join('\n', text));
return this;
}
public Source InsertMultiLine(int index, params string[] text)
{
_text = _text.Insert(index, string.Join('\n', text));
return this;
}
public Source InsertMultiLineAtStart(params string[] text)
{
_text = string.Join('\n', text) + _text;
return this;
}
public Source InsertMultiLineAtEnd(params string[] text)
{
_text += (string.Join('\n', text));
return this;
}
public Source Replace(SourceMatch match, string text)
{
_text = _text.Remove(match.StartIndex, match.Text.Length);
_text = _text.Insert(match.StartIndex, text);
return this;
}
}