Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c774ae4c85 | ||
|
|
2336fd237c | ||
|
|
ae6676cd90 | ||
|
|
201948eac8 | ||
|
|
d4a98babd3 | ||
|
|
2a954ba52f | ||
|
|
52290ece97 | ||
|
|
794d1c1c79 | ||
|
|
97d5dc9d17 | ||
|
|
36ecaf29b6 | ||
|
|
8a7e33c66a | ||
|
|
53935f225d | ||
|
|
c20feff8ab | ||
|
|
3ed3a98bc3 | ||
|
|
9d877cc32c | ||
|
|
6b292a45f7 | ||
|
|
3f4bc4df2e | ||
|
|
bd319ff0d3 | ||
|
|
6c56050be8 | ||
|
|
811438aa3c | ||
|
|
d6186caa8b | ||
|
|
cea547982f | ||
|
|
5a6dce8b96 | ||
|
|
995d0e5859 |
No files matched your search
+47
-77
@@ -1,88 +1,58 @@
|
||||
# MeloongCore 项目架构
|
||||
# Shared 复用指南
|
||||
|
||||
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||
[代码约定](../仓库指示.md) · [Wpf](../Wpf/架构分析.md) · [Tests](../Tests/架构分析.md)
|
||||
|
||||
## 1. 项目定位
|
||||
## 按功能定位
|
||||
|
||||
`MeloongCore/Shared/MeloongCore.csproj` 是通用 C# 基础库,目标框架为 .NET Standard 2.0,使用 C# 13、Nullable、Implicit Usings 和 PolySharp。
|
||||
| 场景 | 源码入口 |
|
||||
| --- | --- |
|
||||
| 初始化、应用目录 | [Main.cs](../../Shared/Main.cs)、[PathUtils.cs](../../Shared/Utils/PathUtils.cs) |
|
||||
| 强类型键、JSON 配置 | [Config.cs](../../Shared/General/Config.cs) |
|
||||
| 日志接入 | [Logger.cs](../../Shared/General/Logger.cs) |
|
||||
| 分阶段进度 | [Progress.cs](../../Shared/General/Progress.cs) |
|
||||
| 节流、防抖、取消后重跑 | [Worker](../../Shared/General/Worker) |
|
||||
| 异步并发、进程执行 | [TaskUtils.cs](../../Shared/Utils/TaskUtils.cs) |
|
||||
| 并发列表、联合值、范围 | [ConcurrentList.cs](../../Shared/General/ConcurrentList.cs)、[OneOf.cs](../../Shared/General/OneOf.cs)、[ValueRange.cs](../../Shared/General/ValueRange.cs) |
|
||||
| 集合、字符串、异常、Task、HTTP 克隆扩展 | [Extensions](../../Shared/Extensions) |
|
||||
| 文件、目录、路径、压缩、校验 | [FileUtils.cs](../../Shared/Utils/FileUtils.cs)、[DirectoryUtils.cs](../../Shared/Utils/DirectoryUtils.cs)、[PathUtils.cs](../../Shared/Utils/PathUtils.cs) |
|
||||
| 格式化、数学、枚举、类型、加密 | [Utils](../../Shared/Utils) |
|
||||
| 注册表、Windows 增量补丁 | [RegistryUtils.cs](../../Shared/Utils/RegistryUtils.cs)、[MsDelta.cs](../../Shared/General/MsDelta.cs) |
|
||||
|
||||
它属于独立 Git 仓库,不应依赖具体上层应用或 WPF。其目标是为 Windows、macOS 及不同上层应用提供一致的基础能力。
|
||||
扩展方法主要位于 `MeloongCore.Extensions`,MathUtils、EnumUtils 的扩展位于 `MeloongCore`;项目全局 using 不传播到引用方。新框架同名方法可能改变重载绑定,替换前核对语义。注册表和 MsDelta 是 Windows 专属,Shared 的目标框架不代表所有入口均可跨平台使用。
|
||||
|
||||
## 2. 目录结构
|
||||
以下保留不易从名称判断的行为;具体重载和实现以链接源码为准。
|
||||
|
||||
```text
|
||||
MeloongCore/Shared/
|
||||
├─ Main.cs # 库初始化与应用名
|
||||
├─ Extensions/ # 集合、字符串、异常、任务和网络扩展
|
||||
├─ General/
|
||||
│ ├─ Config.cs # JSON 配置抽象
|
||||
│ ├─ Logger.cs # 日志抽象
|
||||
│ ├─ Progress.cs # 进度模型
|
||||
│ ├─ Worker/ # 限流与可重做 Worker
|
||||
│ └─ 其他通用数据结构
|
||||
└─ Utils/ # 文件、目录、路径、任务、网络、加密等工具
|
||||
```
|
||||
## 初始化、配置与日志
|
||||
|
||||
## 3. 主要能力
|
||||
- 首次访问默认配置前调用 `Main.Init(appName)`;它设置应用名和默认正则超时,不初始化 WPF 或文件日志。默认 provider 静态初始化后,修改应用名不会迁移其路径。
|
||||
- `ConfigEntry<T>` 绑定固定 provider,`DynamicConfigEntry<T>` 每次操作传 provider。替换 `ConfigProviders.Default` 不改变已有 entry 的绑定。
|
||||
- `ConfigUtils.GetSecret` 独立读取 `Paths.AppData/Meloong/Dev/secret.json`,使用 `CryptographyUtils.AesDecrypt` ,首次读取后缓存 JSON 对象;不使用配置 provider、不参与 SaveAll。文件不存在或键为 null/缺失时抛出缺键异常;解密或解析失败抛出脱敏异常,不覆盖文件。默认密钥仅用于避免明文存储,不提供可靠保密保护。
|
||||
- 同一 provider 的同一键固定使用同一类型;显式 JSON null 算已存值。Get 返回对象缓存,修改对象后需 Edit/Set 才安排保存;Edit 不是原子更新。
|
||||
- Set 即使值相同也触发 Changed;动态 entry 的 Changed 不携带 provider。PreviewGet 仅修正本次读取,不自动写回。
|
||||
- JSON 写入防抖 500 ms;明确落盘点可用 `ConfigUtils.SaveAll()`。DiscardCache 不保存变更;Save 写盘失败不保证恢复 dirty。整文件加载失败回退空对象,不代表所有键读取错误都会回退默认值。
|
||||
- `Logger.Instance` 可替换;基类不实现 LogBehavior 所表达的 UI 动作。BaseLogger 构造时启动后台线程并调用虚方法 Init;Output 通常在日志线程,HandleBehavior 在调用线程。
|
||||
- FileLogger 创建后修改路径字段可能晚于初始化;退出时先 Flush 再 Dispose,但尚未就绪时 Flush 会返回,Dispose 不保证排空或等待线程。
|
||||
|
||||
### 3.1 文件与路径
|
||||
## 进度与后台任务
|
||||
|
||||
`FileUtils`、`DirectoryUtils` 和 `PathUtils` 封装文件读写、压缩包、目录遍历、路径标准化和父子关系判断,供不同上层应用复用。
|
||||
- ProgressProvider 用 SplitBy/SplitTo 分阶段;Reset 不清除单调观测历史,全新任务需要新 provider。Finish/Skip 可结算子项,IsFinished 不代表业务成功。
|
||||
- ProgressObserver 订阅并节流 GetIncreasing,构造时不立即刷新,结束时 Dispose;回调不保证 UI 线程。
|
||||
- RateLimitedWorker 的 ImmediateThenMerge 为节流,ImmediateThenIgnore 忽略密集后续请求,WaitUnillNoNewInvoke 为尾随防抖。复用同一实例;Dispose 不补执行最后一次。
|
||||
- RedoableWorker 在运行中 Start 会请求取消旧负载并合并重跑,负载必须协作取消。WaitIfRunning* 只等待空闲,不重抛负载错误,也不保证事件回调已结束。
|
||||
- RedoableWorker 的 HasSucceeded/LastResult 可保留历史成功,判断最近运行用 LastSucceeded;事件在工作线程。Worker 接受同步委托,不等待 async lambda 内的异步工作。
|
||||
- TaskUtils.WhenAll 聚合进度但不限并发;ForEach 是同步并行,异步限并发用 ForEachAsync。后者失败会停止领取新项,但内部取消令牌不传入 body,在途动作需自行响应外部令牌。
|
||||
- RunProgramAsync 返回 Output/ExitCode,非零退出码不自动抛错;输出按 stdout + stderr 拼接。取消/超时不保证终止子进程树;参数会写日志,不应包含密钥。
|
||||
|
||||
### 3.2 异步与 Worker
|
||||
## 数据结构与扩展语义
|
||||
|
||||
- `TaskUtils` 提供程序执行、并发遍历、聚合等待等通用任务能力;
|
||||
- `ProgressProvider` 支持切分与聚合子进度;
|
||||
- `RateLimitedWorker` 合并或限制高频调用;
|
||||
- `RedoableWorker` 管理可重做的异步工作。
|
||||
|
||||
上层应用可以按需使用这些抽象组织异步任务与进度。
|
||||
|
||||
### 3.3 配置
|
||||
|
||||
`IConfigProvider` 定义读、写、删除、缓存丢弃等能力。默认 `JsonConfigProvider`:
|
||||
|
||||
- 从 JSON 文件惰性读取;
|
||||
- 缓存反序列化后的值;
|
||||
- 通过 Worker 延迟 500 ms 合并写盘;
|
||||
- 使用 `ConfigEntry<T>` 提供固定 provider 的强类型配置;
|
||||
- 使用 `DynamicConfigEntry<T>` 支持运行时选择 provider。
|
||||
|
||||
默认配置位于应用数据目录的 `config.json`,敏感配置 provider 指向 `secret.json`。加密写入目前仍有未实现分支,使用前需要核对现状。
|
||||
|
||||
### 3.4 日志与通用类型
|
||||
|
||||
库提供可替换的 Logger、并发列表、OneOf、值范围、数学和字符串工具等。上层应用可以替换 Logger 实例,将底层日志接入自身日志系统。
|
||||
|
||||
## 4. 依赖
|
||||
|
||||
- `Microsoft.Win32.Registry`:跨目标框架暴露注册表能力;
|
||||
- `Newtonsoft.Json`:配置与 JSON 工具;
|
||||
- `ThrottleDebounce`:限流/防抖基础;
|
||||
- `PolySharp`:为旧运行目标补足现代 C# 编译支持。
|
||||
|
||||
## 5. 架构边界
|
||||
|
||||
适合放入 MeloongCore 的代码应满足:
|
||||
|
||||
- 不依赖具体上层应用的页面、全局状态或业务领域;
|
||||
- 不直接依赖 WPF 类型;
|
||||
- API 对其他 .NET 应用也有合理含义;
|
||||
- Windows 专属能力被清楚隔离,不阻塞 macOS 使用通用部分。
|
||||
|
||||
WPF 特有实现应进入 `MeloongCore.Wpf`,上层应用特有实现应保留在对应应用仓库中。
|
||||
|
||||
## 6. 优势与风险
|
||||
|
||||
优势:
|
||||
|
||||
- 目标框架和依赖方向支持跨项目复用;
|
||||
- 工具与配置已有对应测试;
|
||||
- 现代 C# API 提高了新代码的类型安全和可读性。
|
||||
|
||||
风险:
|
||||
|
||||
- 通用工具类较多,新增 API 时容易形成重复或过宽的职责;
|
||||
- 注册表等 Windows 能力出现在 Shared 中,需要保持调用层面的平台防护;
|
||||
- `JsonConfigProvider` 加密写入尚未实现完整;
|
||||
- 作为公共依赖修改时,需要考虑已有引用方的兼容性和独立发布节奏。
|
||||
- ConcurrentList 单次操作加锁,复合操作需共用 SyncRoot;枚举及与 List 的转换都复制列表,元素仍共享引用。
|
||||
- OneOf 的 default 没有有效分支;Is<T> 按声明类型精确匹配,取错分支会抛错。
|
||||
- ValueRange.Intersect 无交集仍返回范围,应检查 IsEmpty;IsEmpty 不识别离散域空区间。范围可变,不应修改已作为字典键的实例。
|
||||
- EnumerableExtensions 的并行 DistinctBy 不保证首项,重复枚举沿用已见键;MaxBy/MinBy 空输入返回 default;二维数组 ToDictionary 重复键以后者覆盖。
|
||||
- RemoveIf/KeepIf 原地修改;RemoveAll 对每项仅移除一次;Except(单值) 还会去重;ForAll 立即顺序枚举且不等待 async lambda。
|
||||
- 字符串 Before/After 系列未找到分隔符时保留原文;Between 从最后一个起始分隔符之后截取,不做括号配对。Split 去空模式对空串返回空数组,SplitLines 不修剪行内空白。
|
||||
- RegexSearch 的惰性枚举仍可能抛超时;RegexSeek/RegexCheck 捕获失败,而 RegexReplace 直接抛错。
|
||||
- ReadString 不关闭输入流;默认 GetString 尝试 BOM、严格 UTF-8,再回退 GB18030。DeserializeJson<T> 用于 JToken 子类,解析错误可能包含原文。
|
||||
- ExceptionExtensions.IsCanceled 对混有其他错误的聚合也可返回 true;RootException 只沿单条 InnerException,Flatten 扩展与 AggregateException 同名实例方法含义不同。ThrowIfCanceled 不保证保留原堆栈;IsBadNetwork 可能把主动取消判为网络不佳。
|
||||
- TaskExtensions.Run 同步阻塞;NoCapture 仅为 ConfigureAwait(false),不保证切到后台线程。
|
||||
- HTTP CloneAsync 缓冲复制全部内容,Properties 中的对象仍共享;无取消令牌重载。WebUtils.cs 定义 HttpRequestCodeException,未提供自动发送或失败状态检查。
|
||||
+10
-37
@@ -1,43 +1,16 @@
|
||||
# MeloongCore.Tests 项目架构
|
||||
# Tests 定位与环境
|
||||
|
||||
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||
[代码约定](../仓库指示.md) · [WPF 构建要求](../Wpf/架构分析.md)
|
||||
|
||||
## 1. 项目定位
|
||||
Tests 是 TUnit 可执行测试项目,引用 Shared 与 Wpf,运行目标为 .NET Framework 4.8;其运行结果不能证明 macOS 兼容性。运行机制和资源复制配置见 [项目文件](../../Tests/MeloongCore.Tests.csproj)。
|
||||
|
||||
`MeloongCore/Tests/MeloongCore.Tests.csproj` 是基于 TUnit 的 .NET Framework 4.8 测试程序,同时引用 `MeloongCore` 与 `MeloongCore.Wpf`。
|
||||
|
||||
它主要保护通用基础库,不覆盖引用本库的上层应用业务。
|
||||
|
||||
## 2. 测试范围
|
||||
|
||||
| 测试文件 | 覆盖能力 |
|
||||
| 修改能力 | 对应测试目录或文件(相对于 Tests/) |
|
||||
| --- | --- |
|
||||
| `General/ConfigTest.cs` | JSON 配置读写、默认值与缓存 |
|
||||
| `General/ProgressTest.cs` | 进度切分与聚合 |
|
||||
| `General/WorkerTest.cs` | Worker 调度、限流或重做语义 |
|
||||
| `Utils/CryptographyUtilsTest.cs` | 加密工具 |
|
||||
| `Utils/DirectoryUtilsTest.cs` | 目录操作 |
|
||||
| `Utils/FileUtilsTest.cs` | 文件与压缩包处理 |
|
||||
| `Utils/PathUtilsTest.cs` | 路径规范化和关系判断 |
|
||||
| `Utils/TaskUtilsTest.cs` | 异步任务与进程能力 |
|
||||
| `TestUtils.cs` | 测试公共支持 |
|
||||
| 配置、进度、Worker | `General/` |
|
||||
| 加密、目录、文件、路径、任务和进程 | `Utils/` |
|
||||
| 初始化、日志接入、临时目录 | `TestUtils.cs` |
|
||||
| 压缩格式、编码、损坏文件与 Zip Slip | `TestFiles/FileUtils/` |
|
||||
|
||||
`TestFiles/FileUtils` 中包含正常、损坏、不同编码和恶意路径的压缩包样本,用于验证 Zip Slip 等边界。
|
||||
[TestUtils.cs](../../Tests/TestUtils.cs) 中 TestBase 初始化 MeloongCore 并接入测试日志;TestWithFolder 在系统临时目录下创建含 GUID、特殊字符和长路径的测试目录,样本从输出目录复制。
|
||||
|
||||
## 3. 项目特点
|
||||
|
||||
- 输出类型为 `Exe`,由 TUnit 测试运行机制执行;
|
||||
- 测试资源复制到输出目录;
|
||||
- 同时引用 WPF 层,因此可以覆盖少量 WPF 相关基础能力。
|
||||
|
||||
## 4. 测试缺口
|
||||
|
||||
当前测试主要集中于 Shared 的通用工具、配置、进度与 Worker,Wpf 层的平台行为覆盖仍较少。
|
||||
|
||||
## 5. 建议
|
||||
|
||||
测试范围应保持在 MeloongCore 的公共行为内:
|
||||
|
||||
1. 保持本项目只测试 MeloongCore 与 WPF 适配层;
|
||||
2. 上层应用的业务测试由对应应用仓库维护;
|
||||
3. 新增公共能力时,优先补充与其行为和平台边界相对应的测试。
|
||||
测试目前主要覆盖 Shared,引用 Wpf 不意味着已覆盖其平台行为。按本次修改选择相关行为验证,上层应用业务测试留在引用方仓库。
|
||||
+12
-45
@@ -1,51 +1,18 @@
|
||||
# MeloongCore.Wpf 项目架构
|
||||
# Wpf 入口与构建
|
||||
|
||||
[返回 MeloongCore 仓库指示](../仓库指示.md)
|
||||
[代码约定](../仓库指示.md) · [Shared](../Shared/架构分析.md)
|
||||
|
||||
## 1. 项目定位
|
||||
构建 WPF 工程使用 Visual Studio 2022 的 `MSBuild.exe`。本项目为通用 Windows/WPF 适配层,依赖 Shared;纯 .NET 逻辑留在 Shared,应用专用外观和页面逻辑留在引用方。
|
||||
|
||||
`MeloongCore/Wpf/MeloongCore.Wpf.csproj` 是 MeloongCore 的 WPF/Windows 适配层,面向 .NET Framework 4.8,依赖 `MeloongCore`。
|
||||
路径相对于 `Wpf/`:
|
||||
|
||||
它的存在使 Shared 项目无需引用 WPF,同时让多个上层 WPF 应用复用窗口、对话框、转换器与 Windows API 封装。
|
||||
|
||||
## 2. 源码组成
|
||||
|
||||
| 文件 | 职责 |
|
||||
| 场景 | 入口 |
|
||||
| --- | --- |
|
||||
| `Main.cs` | WPF 层初始化 |
|
||||
| `Controls/ModernTooltipService.cs` | 现代化 ToolTip 行为 |
|
||||
| `Extensions/WpfExtensions.cs` | WPF 对象和控件扩展 |
|
||||
| `General/Dialogs.cs` | 文件、文件夹和消息对话框封装 |
|
||||
| `General/ValueConverters.cs` | WPF Binding 值转换器 |
|
||||
| `Utils/WindowsUtils.cs` | Windows 权限、窗口和系统相关工具 |
|
||||
| WPF 初始化 | `Main.cs` |
|
||||
| ToolTip 附加行为 | `Controls/ModernTooltipService.cs` |
|
||||
| 控件与对象扩展 | `Extensions/WpfExtensions.cs` |
|
||||
| 文件、文件夹与消息对话框 | `General/Dialogs.cs` |
|
||||
| Binding 转换器 | `General/ValueConverters.cs` |
|
||||
| Windows 权限、窗口与系统操作 | `Utils/WindowsUtils.cs` |
|
||||
|
||||
## 3. 依赖
|
||||
|
||||
- `MeloongCore`;
|
||||
- WPF 的 `PresentationCore`、`PresentationFramework`、`System.Xaml`;
|
||||
- `System.Windows.Forms`,用于部分 Windows UI 互操作;
|
||||
- `Ookii.Dialogs.Wpf`;
|
||||
- `Newtonsoft.Json` 与 PolySharp。
|
||||
|
||||
## 4. 架构边界
|
||||
|
||||
此项目适合承载“可被多个 WPF 应用复用”的平台代码,例如:
|
||||
|
||||
- WPF 控件扩展和附加行为;
|
||||
- 通用值转换器;
|
||||
- Windows 窗口与权限操作;
|
||||
- 文件夹选择等系统对话框。
|
||||
|
||||
它不适合承载:
|
||||
|
||||
- 特定上层应用的控件外观或页面逻辑;
|
||||
- 具体应用的领域业务;
|
||||
- 只被一个调用点使用的小型包装;
|
||||
- 可以留在 Shared 的纯 .NET 逻辑。
|
||||
|
||||
## 5. 维护关注点
|
||||
|
||||
- 本项目承载 Windows/WPF 特有能力,而 Shared 仍需考虑 macOS;平台 API 必须留在本项目或明确受保护的代码路径中。
|
||||
- `System.Windows.Forms` 与 WPF 混用时要注意 DPI、窗口句柄和线程模型。
|
||||
- 该项目由多个上层应用和 Tests 引用,公共 API 变更影响面较大。
|
||||
- 应避免把具体上层应用的全局日志、设置或窗口实例反向引入本项目。
|
||||
System.Windows.Forms 与 WPF 互操作涉及 DPI、窗口句柄和线程模型;调整相关行为时检查调用线程与窗口归属。
|
||||
+15
-29
@@ -1,35 +1,21 @@
|
||||
# MeloongCore 仓库指示
|
||||
# MeloongCore 代码约定
|
||||
|
||||
## 技术栈
|
||||
## 风格与复用
|
||||
|
||||
- 使用 C# 13、Nullable、Implicit Usings 和 PolySharp。
|
||||
- `Shared` 面向 .NET Standard 2.0,不依赖 WPF。
|
||||
- `Wpf` 与 `Tests` 面向 .NET Framework 4.8。
|
||||
- 保持现代、清晰的 C# 写法,但不做过度抽象、优化或防御性检查。
|
||||
- 简化类结构,少留空行,但保留必要的注释。
|
||||
- 修改已有代码时优先保持最小改动,并删除修改后确定无用的内容。
|
||||
- 不添加只有一两行的小型辅助方法;仅有一个引用的方法或变量应积极考虑内联。
|
||||
- 使用 C# 13、Nullable、Implicit Usings 和 PolySharp;保持目标框架兼容。
|
||||
- 保持改动精简、结构紧凑并保留必要注释;避免无实际收益的抽象、优化和防御性检查。
|
||||
- 不为一两行逻辑添加辅助方法;仅有一个引用的方法或变量优先考虑内联。
|
||||
- 新增工具前检查现有 Extensions、General 和 Utils,避免重复实现。
|
||||
|
||||
## C# 代码风格
|
||||
## C# 风格
|
||||
|
||||
- 大括号不换行;变量名使用小驼峰,类型、属性和方法名使用大驼峰。
|
||||
- 没有 `else`、逻辑较短且仅含一条语句的 `if` 写在一行并省略大括号,例如 `if (flag) break;`;`if` 一旦换行,必须添加大括号。
|
||||
- 单行大括号内的内容前后不加空格,例如 `{element}`。
|
||||
- 行尾注释与代码之间、`//` 与注释正文之间各留一个空格,例如 `break; // 注释`。XML 文档注释引用参数时使用 `<paramref name="..."/>`。
|
||||
- 优先使用 C# 13 下更简洁且清晰的写法,例如 using 声明、本地函数和集合表达式。
|
||||
- 使用 `""` 表示空字符串,不使用 `string.Empty`。
|
||||
- 大括号不换行;变量名小驼峰,类型、属性和方法名大驼峰。
|
||||
- 无 `else`、简短且仅一条语句的 `if` 写成 `if (flag) break;`;换行则加大括号。单行大括号内部不留首尾空格,如 `{element}`。
|
||||
- 行尾注释格式为 `break; // 注释`;XML 文档参数引用用 `<paramref name="..."/>`。
|
||||
- 使用 `""` 表示空字符串;优先采用 C# 13 下简洁清晰的写法。
|
||||
|
||||
## 项目边界
|
||||
## 公共 API 与平台边界
|
||||
|
||||
- `Shared` 只存放可跨产品复用的通用能力,不得依赖具体上层应用的业务领域或 UI 页面。
|
||||
- Windows 与 WPF 特有功能优先放入 `Wpf`,避免破坏 Shared 的 macOS 可用性。
|
||||
- `Tests` 负责保护 Shared 与 Wpf 的公共行为,不应反向依赖引用本库的上层应用项目。
|
||||
- 新增工具前先检查现有 Extensions、General 和 Utils,避免重复实现。
|
||||
- 公共 API 会影响所有引用方,修改签名或语义前应检查兼容性。
|
||||
|
||||
## 仓库安全
|
||||
|
||||
- MeloongCore 是独立 Git 仓库,提交内容不得依赖特定引用方的私有目录结构或开发流程。
|
||||
- 构建 WPF 工程时使用 Visual Studio 2022 的 `MSBuild.exe`。
|
||||
- 保留用户已有的未提交修改,不覆盖或清理无关文件。
|
||||
- 不提交密钥、访问令牌、构建产物、测试结果或本地环境文件。
|
||||
- Shared 承载跨产品通用能力;Windows/WPF 特有功能优先放入 Wpf,已有平台专属入口需保持明确的调用边界。
|
||||
- 上层应用的业务、页面和全局状态留在引用方;Tests 只保护本库公共行为,不反向依赖应用项目。
|
||||
- 修改公共 API 签名或语义时检查已有引用方的兼容性。
|
||||
@@ -1,15 +1,16 @@
|
||||
# Agents 指南
|
||||
# MeloongCore Agents 指南
|
||||
|
||||
本仓库的详细开发指示保存在 `.agents` 目录中。
|
||||
- 使用中文沟通;文本使用 UTF-8 无 BOM(65001),PowerShell 文本读写显式指定 UTF-8 编码。
|
||||
- 通用代码兼顾 Windows 与 macOS;Shared 面向 .NET Standard 2.0,不依赖 WPF。Wpf 与 Tests 面向 .NET Framework 4.8。
|
||||
- 本库是独立仓库,不依赖引用方的业务、私有目录或开发流程。
|
||||
|
||||
## 基础环境
|
||||
## 按任务查阅
|
||||
|
||||
- 使用中文沟通。
|
||||
- 通用代码需要同时考虑 Windows 与 macOS;平台特有代码必须保持明确边界。
|
||||
- 文本文件统一使用 UTF-8 无 BOM(代码页 65001)。使用 Windows PowerShell 读取或写入文本时必须显式指定 `-Encoding UTF8`。
|
||||
| 任务 | 文档 |
|
||||
| --- | --- |
|
||||
| 修改代码或公共 API | [代码约定](.agents/仓库指示.md) |
|
||||
| 查找通用能力、扩展方法及其语义差异 | [Shared 复用指南](.agents/Shared/架构分析.md) |
|
||||
| 修改 Windows/WPF 能力或构建 WPF 工程 | [Wpf 说明](.agents/Wpf/架构分析.md) |
|
||||
| 定位测试与测试环境 | [Tests 说明](.agents/Tests/架构分析.md) |
|
||||
|
||||
处理本仓库内容前,必须完整读取并遵循:
|
||||
|
||||
- [MeloongCore 仓库指示](.agents/仓库指示.md)
|
||||
|
||||
该文件是本仓库规则的组成部分,不是可选参考资料。若指示文件无法读取,应先向用户说明,不得自行猜测或忽略缺失的规则。
|
||||
只读当前任务相关资料;入口、约定或关键行为变化时更新对应文档。
|
||||
@@ -1,6 +1,23 @@
|
||||
namespace MeloongCore.Extensions;
|
||||
public static class EnumerableExtensions {
|
||||
|
||||
#region 查找
|
||||
|
||||
/// <summary>
|
||||
/// 按优先级依次查找,返回首个有匹配结果的条件所匹配的第一个元素。
|
||||
/// 所有条件均无匹配时返回 default。每尝试一个条件都会重新枚举序列。
|
||||
/// </summary>
|
||||
public static TSource? FirstOrDefault<TSource>(this IEnumerable<TSource> source, params Func<TSource, bool>[] predicates) {
|
||||
foreach (var predicate in predicates) {
|
||||
foreach (var item in source) {
|
||||
if (predicate(item)) return item;
|
||||
}
|
||||
}
|
||||
return default;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 去重
|
||||
|
||||
/// <summary>
|
||||
|
||||
@@ -37,13 +37,6 @@ public static class StringExtensions {
|
||||
public static bool ContainsIgnoreCase(this string value, string subString)
|
||||
=> value.IndexOf(subString, StringComparison.OrdinalIgnoreCase) >= 0;
|
||||
|
||||
/// <summary>
|
||||
/// 非区域性的 <see cref="string.Contains(string)"/>。
|
||||
/// </summary>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool ContainsF(this string? value, string subString, bool ignoreCase = false)
|
||||
=> value?.IndexOf(subString, ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal) >= 0;
|
||||
|
||||
/// <summary>
|
||||
/// 非区域性的 <see cref="string.IndexOf(string)"/>。
|
||||
/// </summary>
|
||||
|
||||
@@ -106,19 +106,21 @@ public class JsonConfigProvider : IConfigProvider {
|
||||
private readonly RateLimitedWorker saveWorker;
|
||||
private bool isDirty = false;
|
||||
public void MakeDirty() {
|
||||
isDirty = true;
|
||||
lock (this) isDirty = true;
|
||||
saveWorker.Start();
|
||||
}
|
||||
/// <summary>同步保存配置,并等待同一实例正在进行的保存完成;保存失败时保留待保存状态。</summary>
|
||||
public void Save() {
|
||||
lock (this) {
|
||||
if (!isDirty) return;
|
||||
FileUtils.WriteAtomic(filePath, json.Value.ToString(Formatting.Indented));
|
||||
isDirty = false;
|
||||
lock (this) FileUtils.Write(filePath, json.Value.ToString(Formatting.Indented));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static class ConfigProviders {
|
||||
public static JsonConfigProvider Default = new(Path.Combine(Paths.AppDataThenName, "config.json"));
|
||||
public static readonly JsonConfigProvider Secret = new(Path.Combine(Paths.AppData, "secret.json"));
|
||||
}
|
||||
|
||||
#endregion
|
||||
@@ -224,8 +226,24 @@ public static class ConfigUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>从 secret.json 中读取特定密钥,如果未找到对应密钥则抛出异常。</summary>
|
||||
public static string GetSecret(string key)
|
||||
=> ConfigProviders.Secret.Read<string>(key, null, false) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
|
||||
private static readonly Lazy<JObject> secret = new(() => {
|
||||
string filePath = Path.Combine(Paths.AppData, "Meloong", "Dev", "secret.json");
|
||||
try {
|
||||
return FileUtils.Exists(filePath) ? JObject.Parse(FileUtils.ReadAsString(filePath)) : [];
|
||||
} catch {
|
||||
// JSON 异常可能包含凭据内容,不保留原始异常,也不回退空配置。
|
||||
throw new InvalidDataException($"读取密钥文件失败({filePath}),请检查文件内容与加密格式。");
|
||||
}
|
||||
});
|
||||
|
||||
/// <summary>从 secret.json 中读取加密的密钥;如果未找到对应密钥则抛出异常。</summary>
|
||||
public static string GetSecret(string key) {
|
||||
string value = secret.Value.Value<string>(key) ?? throw new KeyNotFoundException($"未找到密钥:{key}");
|
||||
try {
|
||||
return CryptographyUtils.AesDecrypt(value)!;
|
||||
} catch {
|
||||
throw new InvalidDataException($"读取密钥失败({key}),请检查文件内容与加密格式。");
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -200,12 +200,12 @@ public sealed class ValueRange<T>(
|
||||
}
|
||||
public override int GetHashCode() {
|
||||
int hashCode = 169504101;
|
||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(lower);
|
||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(upper);
|
||||
hashCode=hashCode*-1521134295+hasLower.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+hasUpper.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+isLowerInclusive.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+isUpperInclusive.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Lower);
|
||||
hashCode=hashCode*-1521134295+EqualityComparer<T?>.Default.GetHashCode(Upper);
|
||||
hashCode=hashCode*-1521134295+HasLower.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+HasUpper.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+IsLowerInclusive.GetHashCode();
|
||||
hashCode=hashCode*-1521134295+IsUpperInclusive.GetHashCode();
|
||||
return hashCode;
|
||||
}
|
||||
#pragma warning disable CS8604 // 引用类型参数可能为 null。
|
||||
|
||||
@@ -71,7 +71,7 @@ public static class DirectoryUtils {
|
||||
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||
// 复制自身到自身,则不执行操作
|
||||
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||
} else if (PathUtils.IsSame(sourceFolder, destFolder)) {
|
||||
// 路径仅大小写不同,等效于重命名
|
||||
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
|
||||
DirectoryUtils.Move(sourceFolder, destFolder);
|
||||
@@ -93,7 +93,7 @@ public static class DirectoryUtils {
|
||||
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
|
||||
// 剪切自身到自身,则不执行操作
|
||||
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
|
||||
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||
} else if (PathUtils.IsSame(sourceFolder, destFolder)) {
|
||||
// 路径仅大小写不同
|
||||
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
|
||||
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
|
||||
@@ -167,7 +167,7 @@ public static class DirectoryUtils {
|
||||
/// <exception cref="UnauthorizedAccessException" />
|
||||
private static void SafetyCheck(string folder) {
|
||||
folder = PathUtils.ForCompare(folder);
|
||||
if (folder == PathUtils.ForCompare(Path.GetPathRoot(folder)))
|
||||
if (PathUtils.IsSame(folder, Path.GetPathRoot(folder)))
|
||||
throw new UnauthorizedAccessException($"不应操作磁盘根目录:{folder}");
|
||||
if (criticalFolders.Value.Any(f => PathUtils.IsParentOf(folder, f)))
|
||||
throw new UnauthorizedAccessException($"不应操作文件夹:{folder}");
|
||||
|
||||
@@ -24,6 +24,9 @@ public static class EnumUtils {
|
||||
}
|
||||
}
|
||||
|
||||
public static bool HasFlagF<T>(this T value, T flag) where T : struct, Enum
|
||||
=> value.HasFlag(flag) && !EqualityComparer<T>.Default.Equals(flag, default);
|
||||
|
||||
/// <summary>
|
||||
/// 对于具有 <see cref="FlagsAttribute"/> 的枚举,返回其所有 Flag 值。
|
||||
/// 建议仅对没有极端值的正数枚举使用。
|
||||
|
||||
@@ -100,11 +100,34 @@ public static class FileUtils {
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(filePath));
|
||||
Logger.Trace($"写入文件:{filePath}({content.Length} 字节)");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
FileUtils.Delete(filePath);
|
||||
File.WriteAllBytes(PathUtils.ForApi(filePath), content);
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 原子写入文件。成功时目标文件完整切换为新内容,失败时已有目标文件保持不变。
|
||||
/// 不提供并发写入合并保证。
|
||||
/// </summary>
|
||||
public static void WriteAtomic(string filePath, string text, Encoding? encoding = null) =>
|
||||
FileUtils.WriteAtomic(filePath, (encoding ?? new UTF8Encoding()).GetBytes(text));
|
||||
/// <summary>
|
||||
/// 原子写入文件。成功时目标文件完整切换为新内容,失败时已有目标文件保持不变。
|
||||
/// 不提供并发写入合并保证。
|
||||
/// </summary>
|
||||
public static void WriteAtomic(string filePath, byte[] content) {
|
||||
string tempPath = $"{filePath}.{Guid.NewGuid():N}.tmp";
|
||||
try {
|
||||
FileUtils.Write(tempPath, content);
|
||||
if (FileUtils.Exists(filePath)) {
|
||||
File.Replace(PathUtils.ForApi(tempPath), PathUtils.ForApi(filePath), null, true);
|
||||
} else {
|
||||
File.Move(PathUtils.ForApi(tempPath), PathUtils.ForApi(filePath));
|
||||
}
|
||||
} finally {
|
||||
FileUtils.Delete(tempPath);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建文件,并将 <paramref name="stream" /> 写入文件。
|
||||
/// 会将流的位置主动重置到开头。
|
||||
@@ -165,7 +188,7 @@ public static class FileUtils {
|
||||
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||
// 复制自身到自身,则不执行操作
|
||||
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||
} else if (PathUtils.IsSame(sourceFilePath, destFilePath)) {
|
||||
// 路径仅大小写不同,等效于重命名
|
||||
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
|
||||
FileUtils.Move(sourceFilePath, destFilePath);
|
||||
@@ -182,14 +205,15 @@ public static class FileUtils {
|
||||
/// <summary>
|
||||
/// 剪切文件。
|
||||
/// 会创建对应文件夹、覆盖已有的文件。
|
||||
/// 若指定了 <paramref name="toRecycleBin"/>,则在覆盖前将老文件删除到回收站。
|
||||
/// </summary>
|
||||
public static void Move(string sourceFilePath, string destFilePath) {
|
||||
public static void Move(string sourceFilePath, string destFilePath, bool toRecycleBin = false) {
|
||||
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
|
||||
destFilePath = PathUtils.ForCompare(destFilePath);
|
||||
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
|
||||
// 剪切自身到自身,则不执行操作
|
||||
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
|
||||
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
|
||||
} else if (PathUtils.IsSame(sourceFilePath, destFilePath)) {
|
||||
// 路径仅大小写不同
|
||||
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
@@ -202,7 +226,7 @@ public static class FileUtils {
|
||||
} else {
|
||||
// 实际的剪切
|
||||
DirectoryUtils.Create(PathUtils.RemoveLastPart(destFilePath));
|
||||
FileUtils.Delete(destFilePath);
|
||||
FileUtils.Delete(destFilePath, toRecycleBin);
|
||||
Logger.Trace($"剪切文件:{sourceFilePath} → {destFilePath}");
|
||||
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
FileUtils.SetReadOnly(sourceFilePath, false);
|
||||
@@ -360,7 +384,7 @@ public static class FileUtils {
|
||||
compressionFile = PathUtils.ForApi(compressionFile);
|
||||
DirectoryUtils.Create(outputDirectory);
|
||||
// 解压 gz(gz 不需要考虑编码)
|
||||
if (compressionFile.EndsWithF(".gz", true)) {
|
||||
if (PathUtils.GetExtension(compressionFile) == "gz") {
|
||||
string outFilePath = Path.Combine(outputDirectory, PathUtils.GetFileNameWithoutExtension(compressionFile));
|
||||
Logger.Trace($"解压 gz 文件:{compressionFile} → {outFilePath}");
|
||||
using var fileStream = FileUtils.ReadAsStream(compressionFile);
|
||||
@@ -437,6 +461,22 @@ public static class FileUtils {
|
||||
public static bool Exists(string filePath)
|
||||
=> File.Exists(PathUtils.ForApi(filePath));
|
||||
|
||||
/// <summary>
|
||||
/// 检查文件是否未被其他进程占用
|
||||
/// <para>被占用或无权读取时返回 <see langword="false"/>。</para>
|
||||
/// </summary>
|
||||
public static bool IsAvailable(string filePath) {
|
||||
if (!Exists(filePath)) return true;
|
||||
try {
|
||||
Retrier.Attempt(maxAttempts: 3, delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
|
||||
using var stream = new FileStream(PathUtils.ForApi(filePath), FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
});
|
||||
return true;
|
||||
} catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 <see cref="FileInfo"/> 对象。
|
||||
/// </summary>
|
||||
@@ -488,6 +528,7 @@ public class FileChecker {
|
||||
/// </summary>
|
||||
public bool IsJson = false;
|
||||
|
||||
// TODO: 重构此函数,使它变成 void,并抛出异常
|
||||
/// <summary>
|
||||
/// 检查文件。
|
||||
/// <para/>若成功则返回 <c>null</c>,失败则返回错误的描述文本(文本不以句号结尾)。
|
||||
|
||||
@@ -24,9 +24,11 @@ public static class PathUtils {
|
||||
/// <para/>结果的开头不含 <c>\\?\</c>,结尾不含分隔符。
|
||||
/// </summary>
|
||||
public static string ToShortPath(string pathName) {
|
||||
// 快速返回
|
||||
if (string.IsNullOrEmpty(pathName)) return pathName;
|
||||
if (!pathName.Contains(":")) return pathName;
|
||||
if (pathName.Length <= 220) return pathName; // 快速返回
|
||||
if (!pathName.Contains(":") || pathName.Contains("://")) return pathName;
|
||||
if (pathName.Length <= 220) return pathName;
|
||||
// 开始实际处理
|
||||
pathName = PathUtils.ForCompare(pathName);
|
||||
// 尽量保留原始文件名
|
||||
string pathToKeep = "";
|
||||
@@ -43,7 +45,7 @@ public static class PathUtils {
|
||||
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
|
||||
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
|
||||
string? parentPath = Path.GetDirectoryName(pathToShorten);
|
||||
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
|
||||
if (string.IsNullOrEmpty(parentPath) || PathUtils.IsSame(parentPath, pathToShorten)) return pathName; // 已经到达根目录,全都不存在,直接返回
|
||||
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
|
||||
pathToShorten = parentPath;
|
||||
}
|
||||
@@ -223,6 +225,27 @@ public static class PathUtils {
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 比较两个路径是否相同。<c>null</c> 与空字符串视为相同的空路径。
|
||||
/// </summary>
|
||||
public static bool IsSame(string? path1, string? path2) {
|
||||
return PathUtils.Compare(path1, path2) == 0;
|
||||
}
|
||||
/// <summary>
|
||||
/// 比较两个路径,忽略大小写。
|
||||
/// <para/><c>null</c> 与空字符串视为相同的空路径,空路径排在非空路径之前。
|
||||
/// </summary>
|
||||
/// <returns>
|
||||
/// 小于 0:<paramref name="path1"/> 排在 <paramref name="path2"/> 之前。
|
||||
/// <para/>等于 0:两个路径相等。
|
||||
/// <para/>大于 0:<paramref name="path1"/> 排在 <paramref name="path2"/> 之后。
|
||||
/// </returns>
|
||||
public static int Compare(string? path1, string? path2) {
|
||||
if (string.IsNullOrEmpty(path1)) return string.IsNullOrEmpty(path2) ? 0 : -1;
|
||||
if (string.IsNullOrEmpty(path2)) return 1;
|
||||
return string.Compare(PathUtils.ForCompare(path1!), PathUtils.ForCompare(path2!), StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 将路径转换为兼容各种 Windows API 的格式。
|
||||
/// <para/>具体而言:将分隔符改为 \。添加前导的 <c>\\?\</c>。若为驱动器则添加末尾分隔符,否则去除分隔符。
|
||||
@@ -242,7 +265,7 @@ public static class PathUtils {
|
||||
public static bool IsParentOf(string parentPath, string childPath) {
|
||||
parentPath = PathUtils.ForCompare(parentPath);
|
||||
childPath = PathUtils.ForCompare(childPath);
|
||||
return childPath.StartsWithF(parentPath + @"\") || childPath == parentPath;
|
||||
return childPath.StartsWithF(parentPath + @"\", true) || PathUtils.IsSame(childPath, parentPath);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+84
-10
@@ -7,12 +7,12 @@ public class ConfigTest : TestWithFolder {
|
||||
public async Task JsonConfigProvider_字符串列表() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<List<string>>("list", [], provider);
|
||||
var entry = new ConfigEntry<List<string>>("list", [], provider: provider);
|
||||
|
||||
entry.Set(["Alpha", "中文", "123"]);
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<List<string>>("list", [], new JsonConfigProvider(configFile));
|
||||
var reloadedEntry = new ConfigEntry<List<string>>("list", [], provider: new JsonConfigProvider(configFile));
|
||||
var reloadedValue = reloadedEntry.Get();
|
||||
await Assert.That(reloadedValue is not null).IsTrue();
|
||||
await Assert.That(string.Join("|", reloadedValue!)).IsEqualTo("Alpha|中文|123");
|
||||
@@ -23,7 +23,7 @@ public class ConfigTest : TestWithFolder {
|
||||
public async Task JsonConfigProvider_自定义类列表() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<List<TestConfigItem>>("items", [], provider);
|
||||
var entry = new ConfigEntry<List<TestConfigItem>>("items", [], provider: provider);
|
||||
|
||||
entry.Set([
|
||||
new() { Name = "Fabric", Count = 2, Enabled = true },
|
||||
@@ -31,7 +31,7 @@ public class ConfigTest : TestWithFolder {
|
||||
]);
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<List<TestConfigItem>>("items", [], new JsonConfigProvider(configFile));
|
||||
var reloadedEntry = new ConfigEntry<List<TestConfigItem>>("items", [], provider: new JsonConfigProvider(configFile));
|
||||
var reloadedValue = reloadedEntry.Get();
|
||||
await Assert.That(reloadedValue is not null).IsTrue();
|
||||
await Assert.That(string.Join("|", reloadedValue!.Select(i => $"{i.Name}:{i.Count}:{i.Enabled}"))).IsEqualTo("Fabric:2:True|Forge 中文:5:False");
|
||||
@@ -49,12 +49,12 @@ public class ConfigTest : TestWithFolder {
|
||||
public async Task ConfigEntry_SetNull_RoundTripsThroughJson() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("nullable", "fallback", provider);
|
||||
var entry = new ConfigEntry<string>("nullable", "fallback", provider: provider);
|
||||
|
||||
entry.Set(null);
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("nullable", "fallback", new JsonConfigProvider(configFile));
|
||||
var reloadedEntry = new ConfigEntry<string>("nullable", "fallback", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.HasValue()).IsTrue();
|
||||
await Assert.That(reloadedEntry.Get() is null).IsTrue();
|
||||
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"nullable\": null");
|
||||
@@ -64,12 +64,12 @@ public class ConfigTest : TestWithFolder {
|
||||
public async Task ConfigEntry_SetString_RoundTripsThroughJson() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "fallback", provider);
|
||||
var entry = new ConfigEntry<string>("text", "fallback", provider: provider);
|
||||
|
||||
entry.Set("plain text 中文");
|
||||
provider.Save();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", new JsonConfigProvider(configFile));
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("plain text 中文");
|
||||
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"text\": \"plain text 中文\"");
|
||||
}
|
||||
@@ -78,17 +78,91 @@ public class ConfigTest : TestWithFolder {
|
||||
public async Task ConfigUtils_SaveAll_WritesPendingChangesImmediately() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "fallback", provider);
|
||||
var entry = new ConfigEntry<string>("text", "fallback", provider: provider);
|
||||
|
||||
entry.Set("pending 中文");
|
||||
ConfigUtils.SaveAll();
|
||||
ConfigUtils.SaveAll();
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", new JsonConfigProvider(configFile));
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "fallback", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("pending 中文");
|
||||
await Assert.That(FileUtils.ReadAsString(configFile)).Contains("\"text\": \"pending 中文\"");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_原子替换且不残留临时文件() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
FileUtils.Write(configFile, "{\"existing\":true}");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
|
||||
entry.Set("updated");
|
||||
provider.Save();
|
||||
|
||||
Newtonsoft.Json.Linq.JObject config = FileUtils.ReadAsJson<Newtonsoft.Json.Linq.JObject>(configFile)!;
|
||||
await Assert.That(config.Value<bool>("existing")).IsTrue();
|
||||
await Assert.That(config.Value<string>("text")).IsEqualTo("updated");
|
||||
await Assert.That(DirectoryUtils.EnumerateFiles(tempFolder, searchPattern: "config.json.*.tmp")).IsEmpty();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_等待正在进行的保存() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
using var firstStarted = new ManualResetEventSlim(false);
|
||||
using var secondStarted = new ManualResetEventSlim(false);
|
||||
Task firstSave, secondSave;
|
||||
bool firstBlocked, secondRunning, returnedEarly;
|
||||
|
||||
lock (provider) {
|
||||
entry.Set("pending");
|
||||
Thread? firstThread = null;
|
||||
firstSave = Task.Factory.StartNew(() => {
|
||||
firstThread = Thread.CurrentThread;
|
||||
firstStarted.Set();
|
||||
provider.Save();
|
||||
}, TaskCreationOptions.LongRunning);
|
||||
// 阻止首次保存写盘,稳定复现第二次 Save 在写盘完成前返回的窗口。
|
||||
firstBlocked = firstStarted.Wait(3000) && SpinWait.SpinUntil(
|
||||
() => (firstThread!.ThreadState & ThreadState.WaitSleepJoin) != 0, 3000);
|
||||
secondSave = Task.Factory.StartNew(() => {
|
||||
secondStarted.Set();
|
||||
provider.Save();
|
||||
}, TaskCreationOptions.LongRunning);
|
||||
secondRunning = secondStarted.Wait(3000);
|
||||
returnedEarly = secondSave.Wait(200);
|
||||
}
|
||||
await Task.WhenAll(firstSave, secondSave);
|
||||
|
||||
await Assert.That(firstBlocked).IsTrue();
|
||||
await Assert.That(secondRunning).IsTrue();
|
||||
await Assert.That(returnedEarly).IsFalse();
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("pending");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task JsonConfigProvider_Save_写入失败后可直接重试() {
|
||||
string configFile = Path.Combine(tempFolder, "config.json");
|
||||
var provider = new JsonConfigProvider(configFile);
|
||||
var entry = new ConfigEntry<string>("text", "", provider: provider);
|
||||
entry.Set("before");
|
||||
provider.Save();
|
||||
|
||||
lock (provider) {
|
||||
entry.Set("after");
|
||||
using (var stream = new FileStream(PathUtils.ForApi(configFile), FileMode.Open, FileAccess.Read, FileShare.None)) {
|
||||
Assert.Throws<IOException>(() => provider.Save());
|
||||
}
|
||||
// 无需再次 Set,失败的内容仍应处于待保存状态。
|
||||
provider.Save();
|
||||
}
|
||||
|
||||
var reloadedEntry = new ConfigEntry<string>("text", "", provider: new JsonConfigProvider(configFile));
|
||||
await Assert.That(reloadedEntry.Get()).IsEqualTo("after");
|
||||
}
|
||||
|
||||
public class TestConfigItem {
|
||||
public string Name { get; set; } = "";
|
||||
public int Count { get; set; }
|
||||
|
||||
@@ -1,6 +1,39 @@
|
||||
namespace MeloongCore.Tests;
|
||||
public class FileUtilsTest : TestWithFolder {
|
||||
|
||||
[Test]
|
||||
public async Task 文件可用性_只读与占用() {
|
||||
string path = Path.Combine(tempFolder, "available.txt");
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
FileUtils.Write(path, "test");
|
||||
string apiPath = PathUtils.ForApi(path);
|
||||
File.SetAttributes(apiPath, FileAttributes.ReadOnly);
|
||||
try {
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
await Assert.That((File.GetAttributes(apiPath) & FileAttributes.ReadOnly) != 0).IsTrue();
|
||||
} finally {
|
||||
File.SetAttributes(apiPath, FileAttributes.Normal);
|
||||
}
|
||||
using (var stream = new FileStream(apiPath, FileMode.Open, FileAccess.Read, FileShare.None)) {
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsFalse();
|
||||
}
|
||||
await Assert.That(FileUtils.IsAvailable(path)).IsTrue();
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task 文件可用性_短暂占用后重试() {
|
||||
string path = Path.Combine(tempFolder, "temporary-lock.txt");
|
||||
FileUtils.Write(path, "test");
|
||||
using var stream = new FileStream(PathUtils.ForApi(path), FileMode.Open, FileAccess.Read, FileShare.None);
|
||||
var release = Task.Run(async () => {
|
||||
await Task.Delay(100);
|
||||
stream.Dispose();
|
||||
});
|
||||
bool available = FileUtils.IsAvailable(path);
|
||||
await release;
|
||||
await Assert.That(available).IsTrue();
|
||||
}
|
||||
|
||||
#region 解压
|
||||
|
||||
[Test]
|
||||
|
||||
@@ -142,17 +142,7 @@ public static class ModernTooltipService {
|
||||
|
||||
private static void OnPreviewMouseUp(object sender, MouseButtonEventArgs e) {
|
||||
if (sender is not FrameworkElement reference) return;
|
||||
|
||||
reference.Dispatcher.BeginInvoke(new Action(() => {
|
||||
if (currentOwner is null) return;
|
||||
|
||||
var owner = FindCurrentTooltipOwner(reference);
|
||||
if (owner is null) {
|
||||
Close(true);
|
||||
} else {
|
||||
BeginShow(owner, Mouse.GetPosition(owner));
|
||||
}
|
||||
}), DispatcherPriority.Input);
|
||||
reference.Dispatcher.BeginInvoke(new Action(() => RefreshCurrentOwner(reference)), DispatcherPriority.Input);
|
||||
}
|
||||
|
||||
private static void OnToolTipOpening(object sender, ToolTipEventArgs e) {
|
||||
@@ -315,7 +305,8 @@ public static class ModernTooltipService {
|
||||
|
||||
private static void Show(FrameworkElement owner, Point point) {
|
||||
if (!ReferenceEquals(owner, currentOwner) || !CanShowModernTooltip(owner) || !TryGetToolTip(owner, out var content, out var sourceToolTip)) return;
|
||||
if (!ReferenceEquals(owner, FindCurrentTooltipOwner(owner))) {
|
||||
// 禁用控件由原生 ToolTipOpening 确认命中,无法通过常规 InputHitTest 可靠地重新定位。
|
||||
if (owner.IsEnabled && !ReferenceEquals(owner, FindCurrentTooltipOwner(owner))) {
|
||||
Close(false);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -27,7 +27,7 @@ public static class Dialogs {
|
||||
Logger.Info($"保存弹窗返回:{result}");
|
||||
if (!result.Contains(Path.DirectorySeparatorChar)) return null;
|
||||
// AddExtension 可能失效,需要手动补全(#8214)
|
||||
if (filters != null && !string.IsNullOrEmpty(result) && !filters.Any(f => result.EndsWithF("." + f.Extension))) {
|
||||
if (filters != null && !string.IsNullOrEmpty(result) && !filters.Any(f => result.EndsWithF("." + f.Extension, true))) {
|
||||
result += "." + filters[dialog.FilterIndex - 1].Extension;
|
||||
Logger.Warn($"选择文件的返回无扩展名,将会手动添加,修改后为:{result}");
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user