45 lines
1.5 KiB
C#
45 lines
1.5 KiB
C#
using System.Text.Json;
|
|
|
|
namespace Sdt.Config;
|
|
|
|
public static class ConfigLoader
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNameCaseInsensitive = true,
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
AllowTrailingCommas = true,
|
|
ReadCommentHandling = JsonCommentHandling.Skip,
|
|
};
|
|
|
|
/// <summary>
|
|
/// Walks up from <paramref name="startDir"/> (or CWD) until it finds devtool.json.
|
|
/// Returns null if not found.
|
|
/// </summary>
|
|
public static (DevToolConfig Config, string ProjectRoot)? FindAndLoad(string? startDir = null)
|
|
{
|
|
var dir = new DirectoryInfo(startDir ?? Directory.GetCurrentDirectory());
|
|
while (dir is not null)
|
|
{
|
|
var candidate = Path.Combine(dir.FullName, "devtool.json");
|
|
if (File.Exists(candidate))
|
|
{
|
|
try
|
|
{
|
|
var json = File.ReadAllText(candidate);
|
|
var config = JsonSerializer.Deserialize<DevToolConfig>(json, JsonOptions)
|
|
?? throw new InvalidOperationException("devtool.json deserialized to null.");
|
|
return (config, dir.FullName);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Failed to parse devtool.json at {candidate}: {ex.Message}", ex);
|
|
}
|
|
}
|
|
dir = dir.Parent!;
|
|
}
|
|
return null;
|
|
}
|
|
}
|