静态 Code Review

This commit is contained in:
龙腾猫跃 committed 2026-07-10 12:04:34 +08:00
1 parent 0e2d24c0cd
commit 2744437977
13 files changed
+54 -76

No files matched your search

+4 -4
View File
@@ -68,10 +68,10 @@ public static class DirectoryUtils {
public static void Copy(string sourceFolder, string destFolder) {
sourceFolder = PathUtils.ForCompare(sourceFolder);
destFolder = PathUtils.ForCompare(destFolder);
if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
// 复制自身到自身,则不执行操作
Logger.Trace($"复制文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
// 路径仅大小写不同,等效于重命名
Logger.Trace($"复制文件夹到自身,但大小写不同,等效于重命名文件夹:{sourceFolder} → {destFolder}");
DirectoryUtils.Move(sourceFolder, destFolder);
@@ -90,10 +90,10 @@ public static class DirectoryUtils {
SafetyCheck(sourceFolder);
sourceFolder = PathUtils.ForCompare(sourceFolder);
destFolder = PathUtils.ForCompare(destFolder);
if (string.Compare(sourceFolder, destFolder, ignoreCase: false) == 0) {
if (string.CompareOrdinal(sourceFolder, destFolder) == 0) {
// 剪切自身到自身,则不执行操作
Logger.Trace($"剪切文件夹到自身,不执行操作:{sourceFolder} → {destFolder}");
} else if (string.Compare(sourceFolder, destFolder, ignoreCase: true) == 0) {
} else if (string.Compare(sourceFolder, destFolder, StringComparison.OrdinalIgnoreCase) == 0) {
// 路径仅大小写不同
Logger.Trace($"剪切文件夹到自身,但大小写不同:{sourceFolder} → {destFolder}");
var temp = Path.Combine(PathUtils.RemoveLastPart(sourceFolder), Path.GetRandomFileName());
+5 -4
View File
@@ -151,10 +151,10 @@ public static class FileUtils {
public static void Copy(string sourceFilePath, string destFilePath) {
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
destFilePath = PathUtils.ForCompare(destFilePath);
if (String.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
// 复制自身到自身,则不执行操作
Logger.Trace($"复制文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
} else if (String.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
// 路径仅大小写不同,等效于重命名
Logger.Trace($"复制文件到自身,但大小写不同,等效于重命名文件:{sourceFilePath} → {destFilePath}");
FileUtils.Move(sourceFilePath, destFilePath);
@@ -175,10 +175,10 @@ public static class FileUtils {
public static void Move(string sourceFilePath, string destFilePath) {
sourceFilePath = PathUtils.ForCompare(sourceFilePath);
destFilePath = PathUtils.ForCompare(destFilePath);
if (String.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
if (string.CompareOrdinal(sourceFilePath, destFilePath) == 0) {
// 剪切自身到自身,则不执行操作
Logger.Trace($"剪切文件到自身,不执行操作:{sourceFilePath} → {destFilePath}");
} else if (String.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
} else if (string.Compare(sourceFilePath, destFilePath, StringComparison.OrdinalIgnoreCase) == 0) {
// 路径仅大小写不同
Logger.Trace($"剪切文件到自身,但大小写不同:{sourceFilePath} → {destFilePath}");
Retrier.Attempt(delay: _ => TimeSpan.FromMilliseconds(200), isRetryAllowed: ex => ex is IOException, action: _ => {
@@ -245,6 +245,7 @@ public static class FileUtils {
try {
var iid = typeof(IShellItem).GUID;
Marshal.ThrowExceptionForHR(SHCreateItemFromParsingName(PathUtils.RemoveExtendedPrefix(target), IntPtr.Zero, ref iid, out item));
// ReSharper disable once SuspiciousTypeConversion.Global
op = (IFileOperation) new FileOperation();
op.SetOperationFlags(0x0040 | 0x0010 | 0x0004); // FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_SILENT
op.DeleteItem(item, IntPtr.Zero);
+4 -4
View File
@@ -38,7 +38,7 @@ public static class PathUtils {
}
// 逐级向上寻找已存在的文件夹,将不存在的部分挪到 suffix,不再缩短
while (!DirectoryUtils.Exists(pathToShorten) && !FileUtils.Exists(pathToShorten)) { // 如果路径不存在
string parentPath = Path.GetDirectoryName(pathToShorten);
string? parentPath = Path.GetDirectoryName(pathToShorten);
if (string.IsNullOrEmpty(parentPath) || parentPath == pathToShorten) return pathName; // 已经到达根目录,全都不存在,直接返回
pathToKeep = Path.Combine(PathUtils.GetLastPart(pathToShorten), pathToKeep);
pathToShorten = parentPath;
@@ -93,10 +93,10 @@ public static class PathUtils {
/// "https://foo.bar/file/pack.zip?arg=1" → "https://foo.bar/file"
/// </code></summary>
public static string RemoveLastPart(string pathName) {
if (pathName!.Contains("://")) { // 网络路径
if (pathName.Contains("://")) { // 网络路径
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
}
return PathUtils.RemoveSlashSuffix(pathName!).BeforeLastOfAny([@"\", "/"]);
return PathUtils.RemoveSlashSuffix(pathName).BeforeLastOfAny([@"\", "/"]);
}
/// <summary>
@@ -108,7 +108,7 @@ public static class PathUtils {
/// "https://foo.bar/file/pack.zip?arg=1" → "pack.zip"
/// </code></summary>
public static string GetLastPart(string pathName) {
if (pathName!.Contains("://")) { // 网络路径
if (pathName.Contains("://")) { // 网络路径
pathName = PathUtils.RemoveSlashSuffix(pathName.BeforeFirst("#").BeforeFirst("?")); // 去除参数
} else { // 文件路径
pathName = PathUtils.RemoveSlashSuffix(pathName);
+8 -7
View File
@@ -1,3 +1,4 @@
using System.Globalization;
using System.Text.RegularExpressions;
namespace MeloongCore;
@@ -68,7 +69,7 @@ public static class StringUtils {
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static string FormUrlEscape(string value)
=> WebUtility.UrlEncode(value);
=> WebUtility.UrlEncode(value)!;
/// <summary>
/// 表单去转义。
@@ -107,14 +108,14 @@ public static class StringUtils {
if (byteSize < 1000) { // B 级
return $"{sign}{byteSize} B";
} else if (byteSize < 1024 * 1000) { // K 级
var roundResult = Math.Round(byteSize / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} K";
var roundResult = Math.Round(byteSize / 1024D).ToString(CultureInfo.InvariantCulture);
return $"{sign}{Math.Round(byteSize / 1024D, (3 - roundResult.Length).Clamp(0, 2))} K";
} else if (byteSize < 1024 * 1024 * 1000) { // M 级
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} M";
var roundResult = Math.Round(byteSize / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
return $"{sign}{Math.Round(byteSize / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} M";
} else { // G 级
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString();
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (int) (3 - roundResult.Length).Clamp(0, 2))} G";
var roundResult = Math.Round(byteSize / 1024D / 1024D / 1024D).ToString(CultureInfo.InvariantCulture);
return $"{sign}{Math.Round(byteSize / 1024D / 1024D / 1024D, (3 - roundResult.Length).Clamp(0, 2))} G";
}
}
+5 -30
View File
@@ -14,7 +14,7 @@ public static class TaskUtils {
}
// 实际分割
var progressEach = 1d / taskList.Count;
return Task.WhenAll(taskList.Select(async (task, index) => {
return Task.WhenAll(taskList.Select(async (task, _) => {
var cp = progress?.SplitBy(progressEach)[0];
await task(cp).NoCapture();
cp?.Finish();
@@ -31,7 +31,7 @@ public static class TaskUtils {
}
// 实际分割
var progressEach = 1d / taskList.Count;
return Task.WhenAll(taskList.Select(async (task, index) => {
return Task.WhenAll(taskList.Select(async (task, _) => {
var cp = progress?.SplitBy(progressEach)[0];
var result = await task(cp).NoCapture();
cp?.Finish();
@@ -51,33 +51,6 @@ public static class TaskUtils {
public static void ForEach<T>(IEnumerable<T> source, Action<T> body)
=> Parallel.ForEach(source, body);
public static async Task ForEachAsync<T>(IEnumerable<T> source, int maxDegreeOfParallelism, Func<T, ProgressProvider?, Task> body,
CancellationToken cancellationToken = default, ProgressProvider? progress = null) {
using var linkedCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
var token = linkedCancellationTokenSource.Token;
var enumeratorLock = new object();
using var enumerator = source.GetEnumerator();
async Task WorkerAsync(ProgressProvider? cp) {
try {
while (true) {
T item;
lock (enumeratorLock) {
token.ThrowIfCancellationRequested();
if (!enumerator.MoveNext()) return;
item = enumerator.Current;
}
await body(item, cp).NoCapture();
}
} catch {
try {
linkedCancellationTokenSource.Cancel(); // 让尚未开始的 worker 尽快停止
} catch {
}
throw;
}
}
await TaskUtils.WhenAll(Enumerable.Repeat(WorkerAsync, maxDegreeOfParallelism), progress).NoCapture();
}
/// <summary>
/// 静默运行程序并等待其结束,返回其输出和退出码。
@@ -94,7 +67,9 @@ public static class TaskUtils {
RedirectStandardOutput = true, StandardOutputEncoding = encoding,
RedirectStandardError = true, StandardErrorEncoding = encoding
};
using var program = new Process { StartInfo = info, EnableRaisingEvents = true };
using var program = new Process();
program.StartInfo = info;
program.EnableRaisingEvents = true;
if (!program.Start()) throw new InvalidOperationException($"运行程序时出现意外错误:{file} {arguments}");
bool hasTimeout = timeoutMs is > 0;
Logger.Info($"运行程序,并返回其输出:{file} {arguments}{(hasTimeout ? $",最长可等待 {timeoutMs}ms" : "")}");