Files
ForgejoReleaseSync/Services/RepositoryConfig.cs
T

71 lines
2.2 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using RStein.TOML;
namespace ForgejoReleaseSync.Services;
public class RepositoryConfig
{
public List<RepoSyncConfig> Repositories { get; set; } = [];
}
public class RepoSyncConfig
{
public required string Name { get; set; }
public required string GithubUrl { get; set; }
public required string ForgejoUrl { get; set; }
public required string IncludeAssetsRegex { get; set; }
public required string ExcludeAssetsRegex { get; set; }
}
public abstract class RepoConfigLoader()
{
public static async Task<RepositoryConfig> LoadConfigAsync(string configPath,CancellationToken token = default)
{
try
{
var toml = await File.ReadAllTextAsync(configPath, token);
var tables = await TomlSerializer.DeserializeAsync(toml, token);
var result = new RepositoryConfig();
foreach (var table in tables)
{
if (table.Value is not TomlArray tableValues)
continue;
foreach (var content in tableValues)
{
if (content is not TomlTable fields)
continue;
result.Repositories.Add(new RepoSyncConfig
{
Name = table.Key.ToString(),
GithubUrl = GetRequiredString(fields, "GithubUrl"),
ForgejoUrl = GetRequiredString(fields, "ForgejoUrl"),
IncludeAssetsRegex = GetRequiredString(fields, "IncludeAssetsRegex"),
ExcludeAssetsRegex = GetRequiredString(fields, "ExcludeAssetsRegex")
});
}
}
return result;
}
catch (Exception e)
{
throw new InvalidDataException("Failed to load configuration file", e);
}
}
private static string GetRequiredString(
TomlTable table,
string key)
{
return (string?)table[key]
?? throw new InvalidDataException(
$"Missing required configuration property: {key}");
}
}