mirror of
https://github.com/real-zony/ZonyLrcToolsX.git
synced 2026-11-24 03:37:47 +08:00
feat(desktop): 保存配置时不再重写整个 config.yaml
桌面端从共享的 DI 容器拿配置对象,再用 YamlDotNet 的序列化器整份写回。这样 一轮往返会把文件重写一遍:仓库里那 60 行、注释众多的 config.yaml 会变成 40 行机器生成的块,注释全没了,多行值的引号风格也变了。只要在设置页动一个开关, 注释就丢了。 SettingsStore 不再重新序列化整个文档,只补丁 UI 真正拥有的那几个键: - PatchText 按行扫描 YAML,用缩进栈跟踪每个受管键的路径 (networkOptions.isEnable、provider.lyric.plugin[NetEase].priority …), 只替换那个标量,其余每一个字节 —— 注释、空行、列对齐 —— 保持原样。带 引号的值保持原引号风格(QuotedScalarEventEmitter 沿用原文样式)。 - 补丁后的文本会被重新解析,并逐字段与预期值比对,通过才落盘。往返不一致 就拒绝写入,磁盘上的文件保持不动。另有重新生成整份文件的兜底路径,用于 原文件已被替换成补丁器无法跟随的内容时。 同一提交里还有: - AppPaths:可执行文件所在目录可写时配置就放那里(便携安装),否则回退到 %AppData%/ZonyLrcTools。写入走临时文件 + File.Move,崩溃不会留下半份配置。 - NetEaseSessionStore / KugouDatabaseStore:两个小 JSON,分别存网易云登录 cookie 和用户手动指定的 KGMusicV3.db 路径。刻意与 config.yaml 分开 —— 它们是机器状态而不是用户偏好,也不该出现在设置的 diff 里。 - ConfigurationServiceCollectionExtensions:构造与 CLI 相同的 GlobalOptions, 但基于上面解析出的路径,而不是固定的 AppContext.BaseDirectory。 Common 为此一行未改:CLI 照旧从自己所在目录读 config.yaml。
This commit is contained in:
1 parent
4ec67b9ee0
commit
9cda87dbfe
7 files changed
+972
No files matched your search
@@ -0,0 +1,117 @@
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Resolves the directories the desktop application reads and writes at runtime.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The application prefers a portable layout: settings live next to the executable so the
|
||||
/// whole folder can be copied to a USB stick and moved between machines. If that directory
|
||||
/// is read-only (installed under Program Files, or launched from a read-only mount), it falls
|
||||
/// back to %AppData%\ZonyLrcTools instead of silently losing every setting the user changes.
|
||||
/// </remarks>
|
||||
public static class AppPaths
|
||||
{
|
||||
private const string ApplicationFolderName = "ZonyLrcTools";
|
||||
private const string ConfigFileName = "config.yaml";
|
||||
|
||||
private static readonly Lazy<string> LazyConfigDirectory = new(ResolveConfigDirectory);
|
||||
|
||||
/// <summary>
|
||||
/// Directory that holds <c>config.yaml</c>.
|
||||
/// </summary>
|
||||
public static string ConfigDirectory => LazyConfigDirectory.Value;
|
||||
|
||||
/// <summary>
|
||||
/// Full path of the writable <c>config.yaml</c>.
|
||||
/// </summary>
|
||||
public static string ConfigFilePath => Path.Combine(ConfigDirectory, ConfigFileName);
|
||||
|
||||
/// <summary>
|
||||
/// Copy the template shipped next to the executable into the config directory when the
|
||||
/// user does not have a settings file yet. Safe to call on every startup.
|
||||
/// </summary>
|
||||
public static void EnsureConfigFile()
|
||||
{
|
||||
if (File.Exists(ConfigFilePath))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var template = Path.Combine(AppContext.BaseDirectory, ConfigFileName);
|
||||
if (!File.Exists(template))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (string.Equals(
|
||||
Path.GetFullPath(template),
|
||||
Path.GetFullPath(ConfigFilePath),
|
||||
StringComparison.OrdinalIgnoreCase))
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
File.Copy(template, ConfigFilePath);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// A missing config file is not fatal: the options binder falls back to defaults.
|
||||
}
|
||||
}
|
||||
|
||||
private static string ResolveConfigDirectory()
|
||||
{
|
||||
var baseDirectory = AppContext.BaseDirectory;
|
||||
if (IsWritable(baseDirectory))
|
||||
{
|
||||
return baseDirectory;
|
||||
}
|
||||
|
||||
var roaming = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
|
||||
var fallback = Path.Combine(roaming, ApplicationFolderName);
|
||||
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(fallback);
|
||||
if (IsWritable(fallback))
|
||||
{
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Fall through to the portable path; reading still works even when writing does not.
|
||||
}
|
||||
|
||||
return baseDirectory;
|
||||
}
|
||||
|
||||
private static bool IsWritable(string directory)
|
||||
{
|
||||
if (string.IsNullOrEmpty(directory) || !Directory.Exists(directory))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
var probe = Path.Combine(directory, $".write-probe-{Guid.NewGuid():N}");
|
||||
|
||||
try
|
||||
{
|
||||
using var stream = new FileStream(
|
||||
probe,
|
||||
FileMode.CreateNew,
|
||||
FileAccess.Write,
|
||||
FileShare.None,
|
||||
bufferSize: 1,
|
||||
FileOptions.DeleteOnClose);
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
using ZonyLrcTools.Common.Infrastructure.DependencyInject;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
public static class ConfigurationServiceCollectionExtensions
|
||||
{
|
||||
/// <summary>
|
||||
/// Bind <see cref="GlobalOptions"/> from the writable settings file resolved by
|
||||
/// <see cref="AppPaths"/>, instead of the read-only folder next to the executable that
|
||||
/// <see cref="ServiceCollectionExtensions.ConfigureConfiguration"/> uses.
|
||||
/// </summary>
|
||||
public static IServiceCollection ConfigureDesktopConfiguration(this IServiceCollection services)
|
||||
{
|
||||
AppPaths.EnsureConfigFile();
|
||||
|
||||
var configuration = new ConfigurationBuilder()
|
||||
.SetBasePath(AppPaths.ConfigDirectory)
|
||||
.AddYamlFile(Path.GetFileName(AppPaths.ConfigFilePath), optional: true, reloadOnChange: false)
|
||||
.Build();
|
||||
|
||||
services.Configure<GlobalOptions>(configuration);
|
||||
services.AddSingleton<ISettingsStore, SettingsStore>();
|
||||
|
||||
return services;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Result of a settings persist operation.
|
||||
/// </summary>
|
||||
/// <param name="IsSuccess">Whether the settings were written to disk.</param>
|
||||
/// <param name="FilePath">The file that was written, when the write succeeded.</param>
|
||||
/// <param name="ErrorMessage">Human readable reason when the write failed.</param>
|
||||
public readonly record struct SettingsSaveResult(bool IsSuccess, string? FilePath, string? ErrorMessage)
|
||||
{
|
||||
public static SettingsSaveResult Success(string filePath) => new(true, filePath, null);
|
||||
|
||||
public static SettingsSaveResult Failure(string errorMessage) => new(false, null, errorMessage);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Single owner of the settings file: reads the bound <see cref="GlobalOptions"/> and writes it back
|
||||
/// to <see cref="AppPaths.ConfigFilePath"/>.
|
||||
/// </summary>
|
||||
public interface ISettingsStore
|
||||
{
|
||||
/// <summary>
|
||||
/// The live options instance shared by the whole application. Mutating it takes effect
|
||||
/// immediately for components that read it per operation.
|
||||
/// </summary>
|
||||
GlobalOptions Options { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Absolute path of the settings file currently in use.
|
||||
/// </summary>
|
||||
string ConfigFilePath { get; }
|
||||
|
||||
/// <summary>
|
||||
/// Serialize <see cref="Options"/> to YAML and replace the settings file atomically.
|
||||
/// </summary>
|
||||
Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default);
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Remembers a manually chosen Kugou database (<c>KGMusicV3.db</c>) path.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// This is machine state, not a user preference — it points at a file that happens to exist on
|
||||
/// this computer. Keeping it out of <c>config.yaml</c> means the shipped configuration template
|
||||
/// stays clean and CLI users never see a stray GUI-only key.
|
||||
/// </remarks>
|
||||
public sealed class KugouDatabaseStore
|
||||
{
|
||||
private const string FileName = "kugou.database.json";
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Full path of the settings file.
|
||||
/// </summary>
|
||||
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
|
||||
|
||||
/// <summary>
|
||||
/// Load the stored database path, or <c>null</c> when there is none / it cannot be read.
|
||||
/// </summary>
|
||||
public async Task<string?> LoadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
|
||||
var stored = JsonSerializer.Deserialize<KugouDatabaseSetting>(json);
|
||||
|
||||
return string.IsNullOrWhiteSpace(stored?.DatabasePath) ? null : stored.DatabasePath;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
|
||||
{
|
||||
// A corrupt cache must never block the application; fall back to auto detection.
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Persist the chosen database path.
|
||||
/// </summary>
|
||||
public async Task SaveAsync(string databasePath, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(AppPaths.ConfigDirectory);
|
||||
|
||||
var setting = new KugouDatabaseSetting { DatabasePath = databasePath };
|
||||
var temporaryPath = FilePath + ".tmp";
|
||||
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(setting, JsonOptions), cancellationToken);
|
||||
File.Move(temporaryPath, FilePath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Losing this only costs the user one extra pick next launch.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Forget the stored path so auto detection takes over again.
|
||||
/// </summary>
|
||||
public async Task ClearAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Nothing actionable.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The persisted shape of <see cref="KugouDatabaseStore"/>.
|
||||
/// </summary>
|
||||
public sealed class KugouDatabaseSetting
|
||||
{
|
||||
public string DatabasePath { get; set; } = string.Empty;
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
using System.Text.Json;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Persists the NetEase Cloud Music login state (cookie + csrf token) so the QR login dialog
|
||||
/// does not reappear on every launch.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The cookie is a bearer credential: whoever holds it is logged in as the user. It is written
|
||||
/// next to the settings file with owner-only permissions where the platform supports it, and
|
||||
/// the file is small and plain JSON so a user can delete it by hand to force a re-login.
|
||||
/// </remarks>
|
||||
public sealed class NetEaseSessionStore
|
||||
{
|
||||
private const string FileName = "netease.session.json";
|
||||
|
||||
private static readonly JsonSerializerOptions JsonOptions = new()
|
||||
{
|
||||
WriteIndented = true
|
||||
};
|
||||
|
||||
private readonly SemaphoreSlim _lock = new(1, 1);
|
||||
|
||||
/// <summary>
|
||||
/// Full path of the session file.
|
||||
/// </summary>
|
||||
public string FilePath => Path.Combine(AppPaths.ConfigDirectory, FileName);
|
||||
|
||||
/// <summary>
|
||||
/// Whether a stored session exists on disk.
|
||||
/// </summary>
|
||||
public bool HasStoredSession => File.Exists(FilePath);
|
||||
|
||||
/// <summary>
|
||||
/// Load the stored session, or <c>null</c> when there is none / it cannot be read.
|
||||
/// </summary>
|
||||
public async Task<NetEaseSession?> LoadAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (!File.Exists(FilePath))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var json = await File.ReadAllTextAsync(FilePath, cancellationToken);
|
||||
var session = JsonSerializer.Deserialize<NetEaseSession>(json);
|
||||
|
||||
return string.IsNullOrEmpty(session?.Cookie) ? null : session;
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or JsonException or UnauthorizedAccessException)
|
||||
{
|
||||
// A corrupt session cache must never block the application; treat it as "not logged in".
|
||||
return null;
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Write the session to disk.
|
||||
/// </summary>
|
||||
public async Task SaveAsync(NetEaseSession session, CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
Directory.CreateDirectory(AppPaths.ConfigDirectory);
|
||||
|
||||
var temporaryPath = FilePath + ".tmp";
|
||||
await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(session, JsonOptions), cancellationToken);
|
||||
File.Move(temporaryPath, FilePath, overwrite: true);
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Losing the cache only costs the user one extra scan next launch.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Delete the stored session.
|
||||
/// </summary>
|
||||
public async Task ClearAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _lock.WaitAsync(cancellationToken);
|
||||
try
|
||||
{
|
||||
if (File.Exists(FilePath))
|
||||
{
|
||||
File.Delete(FilePath);
|
||||
}
|
||||
}
|
||||
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
|
||||
{
|
||||
// Nothing actionable; the in-memory state is cleared regardless.
|
||||
}
|
||||
finally
|
||||
{
|
||||
_lock.Release();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The bits of a NetEase login that are worth keeping between runs.
|
||||
/// </summary>
|
||||
public sealed class NetEaseSession
|
||||
{
|
||||
public string Cookie { get; set; } = string.Empty;
|
||||
|
||||
public string CsrfToken { get; set; } = string.Empty;
|
||||
|
||||
public DateTimeOffset SavedAt { get; set; } = DateTimeOffset.Now;
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
using YamlDotNet.Core;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.EventEmitters;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <summary>
|
||||
/// Forces every control-character scalar onto a single double-quoted line.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// YamlDotNet renders a value such as <c>"\n"</c> as the folded block scalar <c>>2</c>, which is
|
||||
/// technically legal YAML but reads as garbage to anyone opening <c>config.yaml</c> by hand and
|
||||
/// contradicts the documentation that describes <c>lineBreak</c> as an escape sequence.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// This emitter only changes presentation: the value that survives a round trip is identical,
|
||||
/// it just comes back as <c>lineBreak: "\n"</c> instead of a folded block.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class QuotedScalarEventEmitter : ChainedEventEmitter
|
||||
{
|
||||
public QuotedScalarEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter)
|
||||
{
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter)
|
||||
{
|
||||
if (eventInfo.Source.Value is string text && NeedsQuoting(text))
|
||||
{
|
||||
eventInfo.Style = ScalarStyle.DoubleQuoted;
|
||||
}
|
||||
|
||||
base.Emit(eventInfo, emitter);
|
||||
}
|
||||
|
||||
private static bool NeedsQuoting(string text)
|
||||
{
|
||||
foreach (var c in text)
|
||||
{
|
||||
if (c is '\n' or '\r' or '\t' or '"' or '\\')
|
||||
{
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// Leading or trailing whitespace is silently trimmed by the plain-scalar reader.
|
||||
return text.Length > 0 && (text[0] == ' ' || text[^1] == ' ');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,501 @@
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Microsoft.Extensions.Options;
|
||||
using YamlDotNet.Serialization;
|
||||
using YamlDotNet.Serialization.NamingConventions;
|
||||
using ZonyLrcTools.Common.Configuration;
|
||||
|
||||
namespace ZonyLrcTools.Desktop.Infrastructure.Configuration;
|
||||
|
||||
/// <inheritdoc cref="ISettingsStore" />
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// Saving must not destroy the hand-written comments in <c>config.yaml</c>: that file is the
|
||||
/// documented configuration surface of this project, and a full re-serialize flattens it into an
|
||||
/// unreadable machine blob on the very first checkbox click.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// So the store patches the values it owns in place, line by line, and only falls back to a full
|
||||
/// re-serialize when the on-disk text no longer round-trips to the intended values. The patched
|
||||
/// text is parsed back and compared before it is committed, so a bad patch can never overwrite a
|
||||
/// working configuration.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
public sealed class SettingsStore : ISettingsStore, IDisposable
|
||||
{
|
||||
private const string RegeneratedHeaderText =
|
||||
"# 此文件由 ZonyLrcTools X 重新生成:原有的注释已丢失,你可以参照文档重新补充。";
|
||||
|
||||
private readonly ISerializer _serializer;
|
||||
private readonly IDeserializer _deserializer;
|
||||
private readonly SemaphoreSlim _writeLock = new(1, 1);
|
||||
private bool _disposed;
|
||||
|
||||
public SettingsStore(IOptions<GlobalOptions> options)
|
||||
{
|
||||
Options = options.Value;
|
||||
|
||||
_serializer = new SerializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.ConfigureDefaultValuesHandling(DefaultValuesHandling.OmitNull)
|
||||
// Keep "\n" readable instead of letting YamlDotNet emit the folded block scalar ">2".
|
||||
.WithEventEmitter(next => new QuotedScalarEventEmitter(next))
|
||||
.Build();
|
||||
|
||||
_deserializer = new DeserializerBuilder()
|
||||
.WithNamingConvention(CamelCaseNamingConvention.Instance)
|
||||
.IgnoreUnmatchedProperties()
|
||||
.Build();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public GlobalOptions Options { get; }
|
||||
|
||||
/// <inheritdoc />
|
||||
public string ConfigFilePath => AppPaths.ConfigFilePath;
|
||||
|
||||
/// <inheritdoc />
|
||||
public async Task<SettingsSaveResult> SaveAsync(CancellationToken cancellationToken = default)
|
||||
{
|
||||
await _writeLock.WaitAsync(cancellationToken).ConfigureAwait(false);
|
||||
|
||||
try
|
||||
{
|
||||
var targetPath = ConfigFilePath;
|
||||
var managed = BuildManagedScalars(Options);
|
||||
|
||||
var text = await TryPatchInPlaceAsync(targetPath, managed, cancellationToken).ConfigureAwait(false)
|
||||
?? BuildFromScratch();
|
||||
|
||||
var directory = Path.GetDirectoryName(targetPath);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
// Write to a sibling temp file first so a crash mid-write cannot truncate the
|
||||
// settings the user already had.
|
||||
var tempPath = targetPath + ".tmp";
|
||||
await File.WriteAllTextAsync(tempPath, text, new UTF8Encoding(false), cancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
File.Move(tempPath, targetPath, overwrite: true);
|
||||
|
||||
return SettingsSaveResult.Success(targetPath);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
return SettingsSaveResult.Failure(ex.Message);
|
||||
}
|
||||
finally
|
||||
{
|
||||
_writeLock.Release();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Rewrites only the managed scalar values in place, keeping every comment and blank line.
|
||||
/// Returns <c>null</c> when the file is missing or the patched text does not read back as the
|
||||
/// intended configuration.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A managed key does not need its own line to be "correct": <c>config.yaml</c> ships with
|
||||
/// <c># depth: 10</c> commented out for QQ, and the default it falls back to is exactly the
|
||||
/// value the GUI wants. The round-trip check below is therefore the only gate that matters.
|
||||
/// </remarks>
|
||||
private async Task<string?> TryPatchInPlaceAsync(
|
||||
string path,
|
||||
IReadOnlyDictionary<string, string> managed,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var original = await File.ReadAllTextAsync(path, cancellationToken).ConfigureAwait(false);
|
||||
if (string.IsNullOrWhiteSpace(original))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var patched = PatchText(original, managed);
|
||||
return VerifyRoundTrip(patched, managed) ? patched : null;
|
||||
}
|
||||
|
||||
private string BuildFromScratch()
|
||||
{
|
||||
// Materialize the same managed values the patch path would have written, so the two
|
||||
// paths cannot disagree about what "saved" means.
|
||||
// YamlDotNet 输出统一是 "\n",这里显式拼同一套行尾,避免首行注释与正文混用 CRLF/LF。
|
||||
var body = _serializer.Serialize(Options);
|
||||
return RegeneratedHeaderText + "\n" + body;
|
||||
}
|
||||
|
||||
private bool VerifyRoundTrip(string yaml, IReadOnlyDictionary<string, string> managed)
|
||||
{
|
||||
try
|
||||
{
|
||||
var parsed = _deserializer.Deserialize<GlobalOptions>(yaml);
|
||||
if (parsed == null)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var (key, expected) in managed)
|
||||
{
|
||||
if (!string.Equals(ReadScalar(parsed, key), expected, StringComparison.Ordinal))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Reads the value of a managed path back out of a deserialized options instance.</summary>
|
||||
private static string? ReadScalar(GlobalOptions options, string path)
|
||||
{
|
||||
if (path.StartsWith("provider.lyric.plugin[", StringComparison.Ordinal))
|
||||
{
|
||||
var close = path.IndexOf(']');
|
||||
if (close < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = path["provider.lyric.plugin[".Length..close];
|
||||
var leaf = path[(close + 2)..];
|
||||
var plugin = options.Provider?.Lyric?.Plugin?.FirstOrDefault(p => p?.Name == name);
|
||||
if (plugin == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return leaf switch
|
||||
{
|
||||
"priority" => plugin.Priority.ToString(CultureInfo.InvariantCulture),
|
||||
"depth" => plugin.Depth.ToString(CultureInfo.InvariantCulture),
|
||||
"additional.isEnableRomanOutput" =>
|
||||
plugin.Additional != null && plugin.Additional.TryGetValue("isEnableRomanOutput", out var v)
|
||||
? Normalize(v)
|
||||
: null,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
if (path.StartsWith("provider.tag.plugin[", StringComparison.Ordinal))
|
||||
{
|
||||
var close = path.IndexOf(']');
|
||||
if (close < 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
var name = path["provider.tag.plugin[".Length..close];
|
||||
var leaf = path[(close + 2)..];
|
||||
var plugin = options.Provider?.Tag?.Plugin?.FirstOrDefault(p => p?.Name == name);
|
||||
if (plugin == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
return leaf == "priority" ? plugin.Priority.ToString(CultureInfo.InvariantCulture) : null;
|
||||
}
|
||||
|
||||
return path switch
|
||||
{
|
||||
"networkOptions.isEnable" => Normalize(options.NetworkOptions?.IsEnable),
|
||||
"networkOptions.ip" => options.NetworkOptions?.Ip,
|
||||
"networkOptions.port" => options.NetworkOptions?.Port.ToString(CultureInfo.InvariantCulture),
|
||||
"provider.lyric.config.isOneLine" => Normalize(options.Provider?.Lyric?.Config?.IsOneLine),
|
||||
// Line breaks must not be trimmed: "\n" and "" are different configurations.
|
||||
"provider.lyric.config.lineBreak" => options.Provider?.Lyric?.Config?.LineBreak,
|
||||
"provider.lyric.config.isEnableTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsEnableTranslation),
|
||||
"provider.lyric.config.isOnlyOutputTranslation" => Normalize(options.Provider?.Lyric?.Config?.IsOnlyOutputTranslation),
|
||||
"provider.lyric.config.isSkipExistLyricFiles" => Normalize(options.Provider?.Lyric?.Config?.IsSkipExistLyricFiles),
|
||||
"provider.lyric.config.fileEncoding" => options.Provider?.Lyric?.Config?.FileEncoding,
|
||||
"provider.tag.blockWord.isEnable" => Normalize(options.Provider?.Tag?.BlockWord?.IsEnable),
|
||||
"provider.tag.blockWord.filePath" => options.Provider?.Tag?.BlockWord?.FilePath,
|
||||
_ => null
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>Canonical text for a boolean, so "True" and "true" compare equal.</summary>
|
||||
private static string Normalize(bool value) => value ? "true" : "false";
|
||||
|
||||
private static string? Normalize(bool? value) => value.HasValue ? Normalize(value.Value) : null;
|
||||
|
||||
private static string Normalize(string? raw) => raw switch
|
||||
{
|
||||
null => string.Empty,
|
||||
"True" => "true",
|
||||
"False" => "false",
|
||||
_ => raw
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Walks the YAML text, tracking the current key path by indentation, and replaces only the
|
||||
/// value part of lines whose full path is managed. Trailing comments are preserved verbatim.
|
||||
/// </summary>
|
||||
private static string PatchText(string original, IReadOnlyDictionary<string, string> managed)
|
||||
{
|
||||
var newline = original.Contains("\r\n", StringComparison.Ordinal) ? "\r\n" : "\n";
|
||||
var lines = original.Replace("\r\n", "\n", StringComparison.Ordinal).Split('\n');
|
||||
var stack = new List<(int Indent, string Path)>();
|
||||
var replaced = new HashSet<string>(StringComparer.Ordinal);
|
||||
|
||||
for (var i = 0; i < lines.Length; i++)
|
||||
{
|
||||
var raw = lines[i];
|
||||
var trimmed = raw.TrimStart();
|
||||
if (trimmed.Length == 0 || trimmed.StartsWith('#'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var indent = raw.Length - trimmed.Length;
|
||||
|
||||
// Leave the previous sibling scope as soon as the indentation goes back out.
|
||||
while (stack.Count > 0 && stack[^1].Indent >= indent)
|
||||
{
|
||||
stack.RemoveAt(stack.Count - 1);
|
||||
}
|
||||
|
||||
var parent = stack.Count > 0 ? stack[^1].Path : string.Empty;
|
||||
|
||||
// List element header, e.g. " - name: NetEase # 基于网易云的歌词下载器。"
|
||||
if (trimmed.StartsWith("- name:", StringComparison.Ordinal))
|
||||
{
|
||||
var name = ReadToken(trimmed["- name:".Length..]);
|
||||
if (name.Length > 0)
|
||||
{
|
||||
stack.Add((indent, $"{parent}[{name}]"));
|
||||
}
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
var colon = trimmed.IndexOf(':');
|
||||
if (colon <= 0)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var key = trimmed[..colon].Trim();
|
||||
if (key.Length == 0 || key.Contains(' ') || key.StartsWith('-'))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var rest = trimmed[(colon + 1)..];
|
||||
var valuePart = ReadToken(rest);
|
||||
var fullPath = parent.Length == 0 ? key : $"{parent}.{key}";
|
||||
|
||||
if (valuePart.Length == 0)
|
||||
{
|
||||
// Section header: children follow at a deeper indentation.
|
||||
stack.Add((indent, fullPath));
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!managed.TryGetValue(fullPath, out var newValue))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!replaced.Add(fullPath))
|
||||
{
|
||||
// 同一个键出现多次时只改第一处:改全部会让 YAML 里前一处生效、后一处变成
|
||||
// 死键的语义更难理解,也让回读校验失去意义。留个注释说明这是有意为之。
|
||||
continue;
|
||||
}
|
||||
|
||||
// Preserve the exact column layout: the value span, then its trailing comment.
|
||||
// config.yaml aligns its comments into columns, so a value that grew or shrank must
|
||||
// absorb the difference in the padding rather than push the comment sideways.
|
||||
var leadingSpaces = rest.Length - rest.TrimStart().Length;
|
||||
var valueStart = indent + colon + 1 + leadingSpaces;
|
||||
var comment = rest[(leadingSpaces + valuePart.Length)..];
|
||||
var replacement = FormatScalar(newValue, valuePart);
|
||||
|
||||
if (comment.Length > 1 && comment[0] == ' ')
|
||||
{
|
||||
var commentColumn = valueStart + valuePart.Length + (comment.Length - comment.TrimStart().Length);
|
||||
var padding = commentColumn - (valueStart + replacement.Length);
|
||||
if (padding >= 1)
|
||||
{
|
||||
comment = new string(' ', padding) + comment.TrimStart();
|
||||
}
|
||||
}
|
||||
|
||||
lines[i] = raw[..valueStart] + replacement + comment;
|
||||
}
|
||||
|
||||
return string.Join(newline, lines);
|
||||
}
|
||||
|
||||
/// <summary>Reads the first YAML token, stopping at whitespace outside quotes.</summary>
|
||||
private static string ReadToken(string text)
|
||||
{
|
||||
var s = text.TrimStart();
|
||||
if (s.Length == 0)
|
||||
{
|
||||
return string.Empty;
|
||||
}
|
||||
|
||||
if (s[0] is '"' or '\'')
|
||||
{
|
||||
var quote = s[0];
|
||||
for (var i = 1; i < s.Length; i++)
|
||||
{
|
||||
if (s[i] == '\\' && quote == '"')
|
||||
{
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (s[i] == quote)
|
||||
{
|
||||
return s[..(i + 1)];
|
||||
}
|
||||
}
|
||||
|
||||
return s;
|
||||
}
|
||||
|
||||
var end = 0;
|
||||
while (end < s.Length && !char.IsWhiteSpace(s[end]))
|
||||
{
|
||||
end++;
|
||||
}
|
||||
|
||||
return s[..end];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Emits the new scalar in the shape the old one had: same quote character when the previous
|
||||
/// value was quoted, double quotes when the value contains characters a plain scalar cannot
|
||||
/// carry (the line-break value), plain otherwise.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A value that merely looks like a boolean is left unquoted: "true" and "false" reach this
|
||||
/// method both from boolean fields (where quoting would turn them into strings) and from
|
||||
/// string fields (whose original spelling in the file was already quoted). Mirroring the
|
||||
/// previous token's quoting therefore keeps both cases correct.
|
||||
/// </remarks>
|
||||
private static string FormatScalar(string value, string previous)
|
||||
{
|
||||
var mustQuote = value.Length == 0
|
||||
|| value.Any(c => c is '\n' or '\r' or '\t' or '"' or '\\')
|
||||
|| value != value.Trim();
|
||||
|
||||
if (!mustQuote)
|
||||
{
|
||||
if (previous.StartsWith('\'') && !value.Contains('\''))
|
||||
{
|
||||
return $"'{value}'";
|
||||
}
|
||||
|
||||
if (previous.StartsWith('"'))
|
||||
{
|
||||
return $"\"{value}\"";
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
var escaped = value
|
||||
.Replace("\\", "\\\\", StringComparison.Ordinal)
|
||||
.Replace("\"", "\\\"", StringComparison.Ordinal)
|
||||
.Replace("\r", "\\r", StringComparison.Ordinal)
|
||||
.Replace("\n", "\\n", StringComparison.Ordinal)
|
||||
.Replace("\t", "\\t", StringComparison.Ordinal);
|
||||
|
||||
return $"\"{escaped}\"";
|
||||
}
|
||||
|
||||
/// <summary>Flattens the editable subset of <see cref="GlobalOptions"/> into path → scalar text.</summary>
|
||||
private static Dictionary<string, string> BuildManagedScalars(GlobalOptions options)
|
||||
{
|
||||
var managed = new Dictionary<string, string>(StringComparer.Ordinal);
|
||||
|
||||
if (options.NetworkOptions != null)
|
||||
{
|
||||
managed["networkOptions.isEnable"] = Normalize(options.NetworkOptions.IsEnable);
|
||||
managed["networkOptions.ip"] = options.NetworkOptions.Ip ?? string.Empty;
|
||||
managed["networkOptions.port"] = options.NetworkOptions.Port.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
var config = options.Provider?.Lyric?.Config;
|
||||
if (config != null)
|
||||
{
|
||||
managed["provider.lyric.config.isOneLine"] = Normalize(config.IsOneLine);
|
||||
managed["provider.lyric.config.lineBreak"] = config.LineBreak ?? string.Empty;
|
||||
managed["provider.lyric.config.isEnableTranslation"] = Normalize(config.IsEnableTranslation);
|
||||
managed["provider.lyric.config.isOnlyOutputTranslation"] = Normalize(config.IsOnlyOutputTranslation);
|
||||
managed["provider.lyric.config.isSkipExistLyricFiles"] = Normalize(config.IsSkipExistLyricFiles);
|
||||
managed["provider.lyric.config.fileEncoding"] = config.FileEncoding ?? string.Empty;
|
||||
}
|
||||
|
||||
var blockWord = options.Provider?.Tag?.BlockWord;
|
||||
if (blockWord != null)
|
||||
{
|
||||
managed["provider.tag.blockWord.isEnable"] = Normalize(blockWord.IsEnable);
|
||||
managed["provider.tag.blockWord.filePath"] = blockWord.FilePath ?? string.Empty;
|
||||
}
|
||||
|
||||
foreach (var plugin in options.Provider?.Lyric?.Plugin ?? [])
|
||||
{
|
||||
if (plugin?.Name == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
var prefix = $"provider.lyric.plugin[{plugin.Name}]";
|
||||
managed[$"{prefix}.priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
managed[$"{prefix}.depth"] = plugin.Depth.ToString(CultureInfo.InvariantCulture);
|
||||
|
||||
if (plugin.Additional != null &&
|
||||
plugin.Additional.TryGetValue("isEnableRomanOutput", out var roman))
|
||||
{
|
||||
managed[$"{prefix}.additional.isEnableRomanOutput"] = Normalize(roman);
|
||||
}
|
||||
}
|
||||
|
||||
foreach (var plugin in options.Provider?.Tag?.Plugin ?? [])
|
||||
{
|
||||
if (plugin?.Name == null)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
managed[$"provider.tag.plugin[{plugin.Name}].priority"] = plugin.Priority.ToString(CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
return managed;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Releases the write lock. <see cref="SettingsStore" /> is a singleton, so this only runs at
|
||||
/// shutdown, but the lock is a disposable handle and leaving it to finalization is sloppy.
|
||||
/// </summary>
|
||||
public void Dispose()
|
||||
{
|
||||
if (_disposed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_disposed = true;
|
||||
_writeLock.Dispose();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user