This commit is contained in:
tk
2023-06-06 16:53:37 +08:00
parent ab0af253a4
commit c6facb89df
57 changed files with 534 additions and 414 deletions

View File

@ -10,22 +10,33 @@ indent_style = space
insert_final_newline = false insert_final_newline = false
trim_trailing_whitespace = true trim_trailing_whitespace = true
[{*.json,*.yml}]
indent_size = 2
[*.cs] [*.cs]
dotnet_analyzer_diagnostic.severity = warning dotnet_analyzer_diagnostic.severity = warning
dotnet_diagnostic.CA1200.severity = none
dotnet_diagnostic.CA1707.severity = none dotnet_diagnostic.CA1707.severity = none
dotnet_diagnostic.CA1716.severity = none dotnet_diagnostic.CA1716.severity = none
dotnet_diagnostic.CA1848.severity = none
dotnet_diagnostic.CA2254.severity = none
dotnet_diagnostic.CA5350.severity = none
dotnet_diagnostic.CA5351.severity = none
dotnet_diagnostic.IDE0005.severity = none dotnet_diagnostic.IDE0005.severity = none
dotnet_diagnostic.IDE0008.severity = none dotnet_diagnostic.IDE0008.severity = none
dotnet_diagnostic.IDE0010.severity = none dotnet_diagnostic.IDE0010.severity = none
dotnet_diagnostic.IDE0017.severity = none
dotnet_diagnostic.IDE0048.severity = none dotnet_diagnostic.IDE0048.severity = none
dotnet_diagnostic.IDE0055.severity = none dotnet_diagnostic.IDE0055.severity = none
dotnet_diagnostic.IDE0058.severity = none
dotnet_diagnostic.IDE0160.severity = none dotnet_diagnostic.IDE0160.severity = none
dotnet_diagnostic.IDE0270.severity = none
dotnet_diagnostic.RCS1123.severity = none
dotnet_diagnostic.RCS1141.severity = none
dotnet_diagnostic.RCS1142.severity = none
dotnet_diagnostic.RCS1181.severity = none
dotnet_diagnostic.RCS1186.severity = none
dotnet_diagnostic.S101.severity = none
dotnet_diagnostic.S1075.severity = none
dotnet_diagnostic.S1199.severity = none
dotnet_diagnostic.S125.severity = none
dotnet_diagnostic.S2094.severity = none
dotnet_diagnostic.S3925.severity = none
dotnet_diagnostic.S4663.severity = none
dotnet_diagnostic.SYSLIB1045.severity = none dotnet_diagnostic.SYSLIB1045.severity = none

4
.gitignore vendored
View File

@ -400,5 +400,5 @@ FodyWeavers.xsd
# User Define # User Define
dist/ dist/
nuget.config *.[Dd]esigner.cs
*.[Dd]esigner.cs *.db

View File

@ -1,4 +1,4 @@
[hook "startcommit"] [hook "startcommit"]
cmdline = code-format.cmd cmdline = dot-clean.cmd
wait = true wait = true
show = true show = true

View File

@ -1,27 +0,0 @@
#r "nuget: Newtonsoft.Json, 13.0.0"
using System.Xml;
using System.IO;
using Newtonsoft.Json.Linq;
var path = Directory.GetFiles(@".idea", "workspace.xml", SearchOption.AllDirectories).First();
XmlDocument xdoc = new XmlDocument();
using(var fs = File.Open(path, FileMode.Open)){
xdoc.Load(fs);
fs.Seek(0, SeekOrigin.Begin);
var propertiesComponent = xdoc.SelectSingleNode("""//component[@name="PropertiesComponent"]""");
var jsonStr = propertiesComponent.InnerText;
var jsonObj = JObject.Parse(jsonStr);
var keyToStringObj = jsonObj["keyToString"] as JObject;
if (keyToStringObj.ContainsKey("rider.code.cleanup.on.save")) return;
keyToStringObj.Add(new JProperty("rider.code.cleanup.on.save", "true"));
var newNode = xdoc.CreateCDataSection(jsonObj.ToString());
propertiesComponent.InnerText=string.Empty;
propertiesComponent.AppendChild(newNode);
var settings = new XmlWriterSettings { Indent = true };
using(var writer = XmlWriter.Create(fs, settings)){
xdoc.WriteTo(writer);
}
}

View File

@ -1,6 +1,6 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<CodeAnalysisRuleSet>../StyleCopAnalyzers.ruleset</CodeAnalysisRuleSet> <CodeAnalysisRuleSet>$(SolutionDir)/StyleCopAnalyzers.ruleset</CodeAnalysisRuleSet>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors> <CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild> <EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<MSBuildTreatWarningsAsErrors>true</MSBuildTreatWarningsAsErrors> <MSBuildTreatWarningsAsErrors>true</MSBuildTreatWarningsAsErrors>
@ -13,6 +13,26 @@
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="Roslynator.Analyzers" Version="4.3.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="SonarAnalyzer.CSharp" Version="9.2.0.71021">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncSuffixAnalyzer" Version="1.0.6285.32977">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="AsyncFixer" Version="1.6.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="ProductiveRage.SealedClassVerification.Net" Version="1.7.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<!-- <PackageReference Include="NSCodeAnalysis" Version="1.0.1-alpha.0.2">--> <!-- <PackageReference Include="NSCodeAnalysis" Version="1.0.1-alpha.0.2">-->
<!-- <PrivateAssets>all</PrivateAssets>--> <!-- <PrivateAssets>all</PrivateAssets>-->
<!-- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>--> <!-- <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>-->

View File

@ -0,0 +1,10 @@
<Project>
<Target Name="AfterTargetsBuild" AfterTargets="Build">
<ItemGroup>
<PackageReferenceFiles
Condition="%(PackageReference.CopyToOutputDirectory) != ''"
Include="$(NugetPackageRoot)\%(PackageReference.Identity)\%(PackageReference.Version)\%(PackageReference.CopyToOutputDirectory)" />
</ItemGroup>
<Copy SourceFiles="@(PackageReferenceFiles)" DestinationFolder="$(OutDir)" />
</Target>
</Project>

View File

@ -1,16 +1,16 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<!-- $(XXX) 定义有顺序 排序请注意-->
<SolutionDir>$(MSBuildThisFileDirectory)</SolutionDir>
<Authors>nsnail</Authors> <Authors>nsnail</Authors>
<BaseIntermediateOutputPath>../dist</BaseIntermediateOutputPath> <BaseIntermediateOutputPath>$(SolutionDir)/dist</BaseIntermediateOutputPath>
<BaseOutputPath>../dist</BaseOutputPath> <BaseOutputPath>$(SolutionDir)/dist</BaseOutputPath>
<Copyright>© 2006-2023 nsnail</Copyright> <Copyright>© 2006-2023 nsnail</Copyright>
<Description>功能全面的实用工具 - 程序员的瑞士军刀</Description> <Description>功能全面的实用工具 - 程序员的瑞士军刀</Description>
<EnableBaseIntermediateOutputPathMismatchWarning>false</EnableBaseIntermediateOutputPathMismatchWarning> <EnableBaseIntermediateOutputPathMismatchWarning>false</EnableBaseIntermediateOutputPathMismatchWarning>
<GenerateDocumentationFile>true</GenerateDocumentationFile> <GenerateDocumentationFile>true</GenerateDocumentationFile>
<ImplicitUsings>enable</ImplicitUsings> <ImplicitUsings>enable</ImplicitUsings>
<IntermediateOutputPath>$(BaseIntermediateOutputPath)/$(MSBuildProjectName)/obj</IntermediateOutputPath> <MinVerDefaultPreReleaseIdentifiers>beta</MinVerDefaultPreReleaseIdentifiers>
<MSBuildProjectExtensionsPath>$(BaseIntermediateOutputPath)/$(MSBuildProjectName)/obj</MSBuildProjectExtensionsPath>
<OutputPath>$(BaseOutputPath)/$(MSBuildProjectName)/bin</OutputPath>
<Product>dot</Product> <Product>dot</Product>
<RepositoryType>git</RepositoryType> <RepositoryType>git</RepositoryType>
<RepositoryUrl>https://github.com/nsnail/dot.git</RepositoryUrl> <RepositoryUrl>https://github.com/nsnail/dot.git</RepositoryUrl>

View File

@ -4,42 +4,62 @@
* *
*/ */
var files = Directory.EnumerateFiles(".", "*.png"
, new EnumerationOptions {
RecurseSubdirectories = true
, AttributesToSkip = FileAttributes.ReparsePoint
, IgnoreInaccessible = true
})
.ToArray();
var files = Directory
.EnumerateFiles(
".",
"*.png",
new EnumerationOptions
{
RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint,
IgnoreInaccessible = true
}
)
.ToArray();
Parallel.ForEach(files, file => { Parallel.ForEach(
var startInfo = new ProcessStartInfo { files,
FileName = "pngquant" file =>
, Arguments {
= $"\"{file}\" --force --output \"{file}\" --skip-if-larger" var startInfo = new ProcessStartInfo
}; {
using var p = Process.Start(startInfo); FileName = "pngquant",
p.WaitForExit(); Arguments = $"\"{file}\" --force --output \"{file}\" --skip-if-larger"
Console.WriteLine($"{file}: {p.ExitCode}"); };
}); using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
}
);
files = new[] { "*.jpg", "*.jpeg" } files = new[] { "*.jpg", "*.jpeg" }
.SelectMany(x => Directory.EnumerateFiles( .SelectMany(
".", x x =>
, new EnumerationOptions { Directory.EnumerateFiles(
RecurseSubdirectories = true ".",
, AttributesToSkip = FileAttributes.ReparsePoint x,
, IgnoreInaccessible = true new EnumerationOptions
})) {
.ToArray(); RecurseSubdirectories = true,
AttributesToSkip = FileAttributes.ReparsePoint,
IgnoreInaccessible = true
}
)
)
.ToArray();
Parallel.ForEach(files, file => { Parallel.ForEach(
var startInfo = new ProcessStartInfo { files,
FileName = "jpegtran" file =>
, Arguments = $"-copy none -optimize -perfect \"{file}\" \"{file}\"" {
}; var startInfo = new ProcessStartInfo
using var p = Process.Start(startInfo); {
p.WaitForExit(); FileName = "jpegtran",
Console.WriteLine($"{file}: {p.ExitCode}"); Arguments = $"-copy none -optimize -perfect \"{file}\" \"{file}\""
}); };
using var p = Process.Start(startInfo);
p.WaitForExit();
Console.WriteLine($"{file}: {p.ExitCode}");
}
);

9
NuGet.Config Normal file
View File

@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<clear />
<add key="nuget.cdn.azure.cn" value="https://nuget.cdn.azure.cn/v3/index.json" />
<add key="cnblogs" value="https://nuget.cnblogs.com/v3/index.json" />
</packageSources>
</configuration>

44
ResharperCodeClean.csx Normal file
View File

@ -0,0 +1,44 @@
using System.Text.RegularExpressions;
using System.Net.Http;
using System.Net.Http.Json;
{
var files = string.Join(
';',
Args[0]
.Split('\n', StringSplitOptions.RemoveEmptyEntries)
.Select(x => x.Replace('\\', '/').Trim())
);
Console.WriteLine(files);
using var p = Process.Start(
new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "dotnet",
Arguments = $"jb cleanupcode --include=\"{files}\" --no-build ./ShopCore.sln",
UseShellExecute = false,
RedirectStandardOutput = true
}
);
p.WaitForExit();
Console.WriteLine(p.StandardOutput.ReadToEnd());
using var p2 = Process.Start(
new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "git",
Arguments = $"status",
UseShellExecute = false,
RedirectStandardOutput = true
}
);
p2.WaitForExit();
var content = p2.StandardOutput.ReadToEnd();
Console.WriteLine(content);
return content.Contains("working tree clean") ? 0 : 1;
}

View File

@ -1,17 +0,0 @@
Hotkey,^d,start
return
start:
loop,100{
send,{AppsKey}
Sleep,100
send,{Up}
Sleep,100
send,{Up}
Sleep,100
Send,{Enter}
Sleep,500
Send,{Esc},
Sleep,100
Send,{Down}
Sleep,100
}

View File

@ -56,7 +56,7 @@
<Rule Id="SA1115" Action="Warning" /> <!-- Parameter should follow comma --> <Rule Id="SA1115" Action="Warning" /> <!-- Parameter should follow comma -->
<Rule Id="SA1116" Action="Warning" /> <!-- Split parameters should start on line after declaration --> <Rule Id="SA1116" Action="Warning" /> <!-- Split parameters should start on line after declaration -->
<Rule Id="SA1117" Action="None" /> <!-- Parameters should be on same line or separate lines --> <Rule Id="SA1117" Action="None" /> <!-- Parameters should be on same line or separate lines -->
<Rule Id="SA1118" Action="Warning" /> <!-- Parameter should not span multiple lines --> <Rule Id="SA1118" Action="None"/> <!-- Parameter should not span multiple lines -->
<Rule Id="SA1120" Action="None" /> <!-- Comments should contain text --> <Rule Id="SA1120" Action="None" /> <!-- Comments should contain text -->
<Rule Id="SA1121" Action="Warning" /> <!-- Use built-in type alias --> <Rule Id="SA1121" Action="Warning" /> <!-- Use built-in type alias -->
<Rule Id="SA1122" Action="Warning" /> <!-- Use string.Empty for empty strings --> <Rule Id="SA1122" Action="Warning" /> <!-- Use string.Empty for empty strings -->
@ -111,7 +111,7 @@
<Rule Id="SA1310" Action="None" /> <!-- Field names should not contain underscore --> <Rule Id="SA1310" Action="None" /> <!-- Field names should not contain underscore -->
<Rule Id="SA1311" Action="Warning" /> <!-- Static readonly fields should begin with upper-case letter --> <Rule Id="SA1311" Action="Warning" /> <!-- Static readonly fields should begin with upper-case letter -->
<Rule Id="SA1312" Action="Warning" /> <!-- Variable names should begin with lower-case letter --> <Rule Id="SA1312" Action="Warning" /> <!-- Variable names should begin with lower-case letter -->
<Rule Id="SA1313" Action="Warning" /> <!-- Parameter names should begin with lower-case letter --> <Rule Id="SA1313" Action="None"/> <!-- Parameter names should begin with lower-case letter -->
<Rule Id="SA1314" Action="Warning" /> <!-- Type parameter names should begin with T --> <Rule Id="SA1314" Action="Warning" /> <!-- Type parameter names should begin with T -->
<Rule Id="SX1309" Action="Warning" /> <!-- Field names should begin with underscore --> <Rule Id="SX1309" Action="Warning" /> <!-- Field names should begin with underscore -->
<Rule Id="SX1309S" Action="Warning" /> <!-- Static field names should begin with underscore --> <Rule Id="SX1309S" Action="Warning" /> <!-- Static field names should begin with underscore -->

View File

@ -1,14 +1,17 @@
using System.Text.RegularExpressions; using System.Text.RegularExpressions;
var slnFile = Directory.GetFiles(@".", "*.sln").First(); var slnFile = Directory.GetFiles(@".", "*.sln").First();
var content = File.ReadAllText(slnFile); var content = File.ReadAllText(slnFile);
content = Regex.Replace(content,@"ProjectSection\(SolutionItems\) = preProject(?:.|\n)*?EndProjectSection", content = Regex.Replace(
$""" content,
@"ProjectSection\(SolutionItems\) = preProject(?:.|\n)*?EndProjectSection",
$"""
ProjectSection(SolutionItems) = preProject ProjectSection(SolutionItems) = preProject
{string.Join('\n', {string.Join('\n',
Directory.GetFiles(@".", "*").Where(x => !x.EndsWith(".sln") && !x.EndsWith(".user")) Directory.GetFiles(@".", "*").Where(x => !x.EndsWith(".sln") && !x.EndsWith(".user"))
.Select(x=>$"\t\t{Path.GetFileName(x)} = {Path.GetFileName(x)}"))} .Select(x=>$"\t\t{Path.GetFileName(x)} = {Path.GetFileName(x)}"))}
{'\t'}EndProjectSection {'\t'}EndProjectSection
"""); """
Console.WriteLine(content); );
File.WriteAllText(slnFile, content); Console.WriteLine(content);
File.WriteAllText(slnFile, content);

13
dot.sln
View File

@ -12,10 +12,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "meta", "meta", "{AD79881E-7
.gitignore = .gitignore .gitignore = .gitignore
.tgitconfig = .tgitconfig .tgitconfig = .tgitconfig
build.cake = build.cake build.cake = build.cake
code-format.cmd = code-format.cmd
CodeCleanupOnSave.csx = CodeCleanupOnSave.csx
CodeQuality.props = CodeQuality.props CodeQuality.props = CodeQuality.props
CopyPackageXmlCommentFiles.targets = CopyPackageXmlCommentFiles.targets
Directory.Build.props = Directory.Build.props Directory.Build.props = Directory.Build.props
dot-clean.cmd = dot-clean.cmd
dot.sln.DotSettings = dot.sln.DotSettings dot.sln.DotSettings = dot.sln.DotSettings
dotnet-tools.json = dotnet-tools.json dotnet-tools.json = dotnet-tools.json
GenerateResx.targets = GenerateResx.targets GenerateResx.targets = GenerateResx.targets
@ -23,14 +23,15 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "meta", "meta", "{AD79881E-7
global.json = global.json global.json = global.json
ImageOptimize.csx = ImageOptimize.csx ImageOptimize.csx = ImageOptimize.csx
LICENSE = LICENSE LICENSE = LICENSE
NuGet.Config = NuGet.Config
package.json = package.json
README.md = README.md README.md = README.md
README.zh-CN.md = README.zh-CN.md README.zh-CN.md = README.zh-CN.md
SafetyDelUnusedResx.ahk = SafetyDelUnusedResx.ahk resharper-clean-full.cmd = resharper-clean-full.cmd
resharper-clean.ps1 = resharper-clean.ps1
ResharperCodeClean.csx = ResharperCodeClean.csx
stylecop.json = stylecop.json stylecop.json = stylecop.json
StyleCopAnalyzers.ruleset = StyleCopAnalyzers.ruleset StyleCopAnalyzers.ruleset = StyleCopAnalyzers.ruleset
switch-nuget.cmd = switch-nuget.cmd
switch-project.cmd = switch-project.cmd
switcher.nsext.json = switcher.nsext.json
SyncMetaFiles.csx = SyncMetaFiles.csx SyncMetaFiles.csx = SyncMetaFiles.csx
EndProjectSection EndProjectSection
EndProject EndProject

View File

@ -5,7 +5,8 @@
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_ACCESSORHOLDER_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_RECORD_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String> <s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_RECORD_FIELD_ATTRIBUTE_ON_SAME_LINE_EX/@EntryValue">NEVER</s:String>
<s:Boolean x:Key="/Default/ReSpeller/ReSpellerEnabled/@EntryValue">False</s:Boolean> <s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=UI/@EntryIndexedValue">UI</s:String>
<s:Boolean x:Key="/Default/ReSpeller/ReSpellerEnabled/@EntryValue">True</s:Boolean>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/@EntryValue">1</s:Int64> <s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_CODE/@EntryValue">1</s:Int64>
<s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue">1</s:Int64> <s:Int64 x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_BLANK_LINES_IN_DECLARATIONS/@EntryValue">1</s:Int64>
<s:String x:Key="/Default/CodeInspection/Highlighting/AnalysisEnabled/@EntryValue">OFF</s:String> <s:String x:Key="/Default/CodeInspection/Highlighting/AnalysisEnabled/@EntryValue">OFF</s:String>
@ -58,4 +59,15 @@
&lt;/Entry&gt; &lt;/Entry&gt;
&lt;/TypePattern&gt; &lt;/TypePattern&gt;
&lt;/Patterns&gt;</s:String> &lt;/Patterns&gt;</s:String>
<s:Boolean x:Key="/Default/UserDictionary/Words/=CHANGECBCHAIN/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=DRAWCLIPBOARD/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=fract/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=fsrw/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=hwnd/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Kbdllhooks/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=KEYEVENTF/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=LBUTTONDOWN/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=lpfn/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Pbox/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Rbom/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary> </wpf:ResourceDictionary>

View File

@ -1,12 +1,30 @@
{ {
"version": 1, "version": 1,
"isRoot": true, "isRoot": true,
"tools": { "tools": {
"dotnet-t4": { "dotnet-t4": {
"version": "2.3.1", "version": "2.3.1",
"commands": [ "commands": [
"t4" "t4"
] ]
} },
"cake.tool": {
"version": "3.0.0",
"commands": [
"dotnet-cake"
]
},
"dotnet-script": {
"version": "1.4.0",
"commands": [
"dotnet-script"
]
},
"jetbrains.resharper.globaltools": {
"version": "2022.3.2",
"commands": [
"jb"
]
} }
}
} }

View File

@ -1,10 +1,10 @@
{ {
"sdk": { "sdk": {
"version": "7.0.100", "version": "7.0.100",
"allowPrerelease": true, "allowPrerelease": true,
"rollForward": "major" "rollForward": "major"
}, },
"tools": { "tools": {
"dotnet": "7.0.100" "dotnet": "7.0.100"
} }
} }

12
package.json Normal file
View File

@ -0,0 +1,12 @@
{
"devDependencies": {
"cz-conventional-changelog": "^3.3.0",
"prettier": "2.8.1",
"prettier-plugin-csharp": "0.6.0-development"
},
"config": {
"commitizen": {
"path": "./node_modules/cz-conventional-changelog"
}
}
}

1
resharper-clean-full.cmd Normal file
View File

@ -0,0 +1 @@
dotnet jb cleanupcode --no-build ./dot.sln

4
resharper-clean.ps1 Normal file
View File

@ -0,0 +1,4 @@
$files=$(foreach ($line in $(git diff head origin/dev --stat-width 200) | findstr '\|'){$line.split('\|')[0].trim()}) -join ';'
echo $files
dotnet jb cleanupcode --no-build --include="$files" ./ShopCore.sln
dotnet script ./PushSign.csx

View File

@ -11,7 +11,7 @@ namespace Dot.Color;
// ReSharper disable once ClassNeverInstantiated.Global // ReSharper disable once ClassNeverInstantiated.Global
internal sealed class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
protected override Task Core() protected override Task CoreAsync()
{ {
Application.Run(new WinMain()); Application.Run(new WinMain());
return Task.CompletedTask; return Task.CompletedTask;

View File

@ -10,30 +10,32 @@ namespace Dot.Color;
internal sealed class WinInfo : Form internal sealed class WinInfo : Form
{ {
private const int _WINDOW_SIZE = 480; // 窗口大小 private const int _WINDOW_SIZE = 480; // 窗口大小
private const int _ZOOM_RATE = 16; // 缩放倍率 private const int _ZOOM_RATE = 16; // 缩放倍率
private readonly Graphics _graphics; private readonly Graphics _graphics;
private readonly PictureBox _pbox; private readonly PictureBox _pbox;
private bool _disposed; private bool _disposed;
public WinInfo() public WinInfo()
{ {
FormBorderStyle = FormBorderStyle.None; #pragma warning disable IDE0017
TopMost = true; FormBorderStyle = FormBorderStyle.None;
MinimizeBox = false; TopMost = true;
MaximizeBox = false; MinimizeBox = false;
Size = new Size(_WINDOW_SIZE, _WINDOW_SIZE); MaximizeBox = false;
StartPosition = FormStartPosition.Manual; Size = new Size(_WINDOW_SIZE, _WINDOW_SIZE);
Location = new Point(0, 0); StartPosition = FormStartPosition.Manual;
_pbox = new PictureBox(); Location = new Point(0, 0);
_pbox.Location = new Point(0, 0); _pbox = new PictureBox();
_pbox.Size = Size; _pbox.Location = new Point(0, 0);
_pbox.Image = new Bitmap(_WINDOW_SIZE, _WINDOW_SIZE); _pbox.Size = Size;
_graphics = Graphics.FromImage(_pbox.Image); _pbox.Image = new Bitmap(_WINDOW_SIZE, _WINDOW_SIZE);
_graphics.InterpolationMode = InterpolationMode.NearestNeighbor; // 指定最临近插值法,禁止平滑缩放(模糊) _graphics = Graphics.FromImage(_pbox.Image);
_graphics.CompositingQuality = CompositingQuality.HighQuality; _graphics.InterpolationMode = InterpolationMode.NearestNeighbor; // 指定最临近插值法,禁止平滑缩放(模糊)
_graphics.SmoothingMode = SmoothingMode.None; _graphics.CompositingQuality = CompositingQuality.HighQuality;
_pbox.MouseEnter += PboxOnMouseEnter; _graphics.SmoothingMode = SmoothingMode.None;
_pbox.MouseEnter += PboxOnMouseEnter;
Controls.Add(_pbox); Controls.Add(_pbox);
#pragma warning restore IDE0017
} }
~WinInfo() ~WinInfo()
@ -46,13 +48,13 @@ internal sealed class WinInfo : Form
// 计算复制小图的区域 // 计算复制小图的区域
var copySize = new Size(_WINDOW_SIZE / _ZOOM_RATE, _WINDOW_SIZE / _ZOOM_RATE); var copySize = new Size(_WINDOW_SIZE / _ZOOM_RATE, _WINDOW_SIZE / _ZOOM_RATE);
_graphics.DrawImage(img, new Rectangle(0, 0, _WINDOW_SIZE, _WINDOW_SIZE) // _graphics.DrawImage(img, new Rectangle(0, 0, _WINDOW_SIZE, _WINDOW_SIZE) //
, x - copySize.Width / 2 // 左移x使光标位置居中 , x - copySize.Width / 2 // 左移x使光标位置居中
, y - copySize.Height / 2 // 上移y使光标位置居中 , y - copySize.Height / 2 // 上移y使光标位置居中
, copySize.Width, copySize.Height, GraphicsUnit.Pixel); , copySize.Width, copySize.Height, GraphicsUnit.Pixel);
using var pen = new Pen(System.Drawing.Color.Aqua); // 绘制准星 using var pen = new Pen(System.Drawing.Color.Aqua); // 绘制准星
_graphics.DrawRectangle(pen, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 // _graphics.DrawRectangle(pen, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 //
, _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 // , _WINDOW_SIZE / 2 - _ZOOM_RATE / 2 //
, _ZOOM_RATE, _ZOOM_RATE); , _ZOOM_RATE, _ZOOM_RATE);
// 取鼠标位置颜色 // 取鼠标位置颜色
var posColor = img.GetPixel(x, y); var posColor = img.GetPixel(x, y);
@ -61,8 +63,8 @@ internal sealed class WinInfo : Form
_graphics.FillRectangle(Brushes.Black, 0, _WINDOW_SIZE - 30, _WINDOW_SIZE, 30); _graphics.FillRectangle(Brushes.Black, 0, _WINDOW_SIZE - 30, _WINDOW_SIZE, 30);
_graphics.DrawString( // _graphics.DrawString( //
$"{Ln.ClickCopyColor} X: {x} Y: {y} RGB({posColor.R},{posColor.G},{posColor.B})" $"{Ln.ClickCopyColor} X: {x} Y: {y} RGB({posColor.R},{posColor.G},{posColor.B})"
, new Font(FontFamily.GenericSerif, 10) // , new Font(FontFamily.GenericSerif, 10) //
, Brushes.White, 0, _WINDOW_SIZE - 20); , Brushes.White, 0, _WINDOW_SIZE - 20);
// 触发重绘 // 触发重绘
_pbox.Refresh(); _pbox.Refresh();

View File

@ -17,14 +17,14 @@ internal sealed class WinMain : Form
public WinMain() public WinMain()
{ {
// 隐藏控制台窗口,避免捕获到截屏 // 隐藏控制台窗口,避免捕获到截屏
Win32.ShowWindow(Win32.GetConsoleWindow(), Win32.SW_HIDE); _ = Win32.ShowWindow(Win32.GetConsoleWindow(), Win32.SW_HIDE);
FormBorderStyle = FormBorderStyle.None; FormBorderStyle = FormBorderStyle.None;
Size = Screen.PrimaryScreen!.Bounds.Size; Size = Screen.PrimaryScreen!.Bounds.Size;
StartPosition = FormStartPosition.Manual; StartPosition = FormStartPosition.Manual;
Location = new Point(0, 0); Location = new Point(0, 0);
Opacity = 0.01d; // 主窗体加载截图过程设置为透明避免闪烁 Opacity = 0.01d; // 主窗体加载截图过程设置为透明避免闪烁
_bmp = new Bitmap(Size.Width, Size.Height); _bmp = new Bitmap(Size.Width, Size.Height);
using var g = Graphics.FromImage(_bmp); using var g = Graphics.FromImage(_bmp);
g.CopyFromScreen(0, 0, 0, 0, Size); g.CopyFromScreen(0, 0, 0, 0, Size);
} }

View File

@ -4,12 +4,12 @@ namespace Dot;
// ReSharper disable once UnusedType.Global // ReSharper disable once UnusedType.Global
// ReSharper disable once UnusedMember.Global // ReSharper disable once UnusedMember.Global
internal sealed class CsxEditor internal static class CsxEditor
{ {
// ReSharper disable once UnusedMember.Local // ReSharper disable once UnusedMember.Local
#pragma warning disable IDE0051 #pragma warning disable S1144, RCS1213, IDE0051
private static void Run() private static void Run()
#pragma warning restore IDE0051 #pragma warning restore IDE0051, RCS1213, S1144
{ {
/* /*
for %%i in (*.png) do pngquant %%i --force --output %%i --skip-if-larger for %%i in (*.png) do pngquant %%i --force --output %%i --skip-if-larger

View File

@ -2,7 +2,7 @@
namespace Dot; namespace Dot;
internal class DirOption : OptionBase internal abstract class DirOption : OptionBase
{ {
[CommandOption("-e|--exclude")] [CommandOption("-e|--exclude")]
[Description(nameof(Ln.ExcludePathRegexes))] [Description(nameof(Ln.ExcludePathRegexes))]

View File

@ -10,14 +10,14 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
where TOption : DirOption where TOption : DirOption
{ {
// ReSharper disable once StaticMemberInGenericType // ReSharper disable once StaticMemberInGenericType
private static readonly object _lock = new(); // 线程锁 private readonly object _lock = new(); // 线程锁
private readonly ConcurrentDictionary<string, int> _writeStats = new(); // 写入统计:后缀,数量 private readonly ConcurrentDictionary<string, int> _writeStats = new(); // 写入统计:后缀,数量
private int _breakCnt; // 跳过文件数 private int _breakCnt; // 跳过文件数
private ProgressTask _childTask; // 子任务进度 private ProgressTask _childTask; // 子任务进度
private int _excludeCnt; // 排除文件数 private int _excludeCnt; // 排除文件数
private int _readCnt; // 读取文件数 private int _readCnt; // 读取文件数
private int _totalCnt; // 总文件数 private int _totalCnt; // 总文件数
private int _writeCnt; // 写入文件数 private int _writeCnt; // 写入文件数
protected static FileStream CreateTempFile(out string file) protected static FileStream CreateTempFile(out string file)
{ {
@ -37,7 +37,7 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
File.SetAttributes(file, new FileInfo(file).Attributes & ~FileAttributes.ReadOnly); File.SetAttributes(file, new FileInfo(file).Attributes & ~FileAttributes.ReadOnly);
fsr = new FileStream(file, mode, access, share); fsr = new FileStream(file, mode, access, share);
} }
catch (Exception) { catch {
// ignored // ignored
} }
} }
@ -48,15 +48,15 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
return fsr; return fsr;
} }
protected override Task Core() protected override Task CoreAsync()
{ {
return !Directory.Exists(Opt.Path) return !Directory.Exists(Opt.Path)
? throw new ArgumentException( // ? throw new ArgumentException( //
nameof(Opt.Path), string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path)) nameof(Opt.Path), string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path))
: CoreInternal(); : CoreInternalAsync();
} }
protected abstract ValueTask FileHandle(string file, CancellationToken cancelToken); protected abstract ValueTask FileHandleAsync(string file, CancellationToken cancelToken);
protected void ShowMessage(int readCnt, int writeCnt, int breakCnt) protected void ShowMessage(int readCnt, int writeCnt, int breakCnt)
{ {
@ -78,7 +78,7 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
_ = _writeStats.AddOrUpdate(key, 1, (_, oldValue) => oldValue + 1); _ = _writeStats.AddOrUpdate(key, 1, (_, oldValue) => oldValue + 1);
} }
private async Task CoreInternal() private async Task CoreInternalAsync()
{ {
if (!Opt.WriteMode) { if (!Opt.WriteMode) {
AnsiConsole.MarkupLine(CultureInfo.InvariantCulture, "[gray]{0}[/]", Ln.ExerciseMode); AnsiConsole.MarkupLine(CultureInfo.InvariantCulture, "[gray]{0}[/]", Ln.ExerciseMode);
@ -93,15 +93,15 @@ internal abstract class FilesTool<TOption> : ToolBase<TOption>
, new SpinnerColumn() // , new SpinnerColumn() //
, new TaskDescriptionColumn { Alignment = Justify.Left }) // , new TaskDescriptionColumn { Alignment = Justify.Left }) //
.StartAsync(async ctx => { .StartAsync(async ctx => {
var taskSearchfile = ctx.AddTask(Ln.SearchingFile).IsIndeterminate(); var taskSearchFile = ctx.AddTask(Ln.SearchingFile).IsIndeterminate();
_childTask = ctx.AddTask("-/-", false); _childTask = ctx.AddTask("-/-", false);
fileList = EnumerateFiles(Opt.Path, Opt.Filter, out _excludeCnt); fileList = EnumerateFiles(Opt.Path, Opt.Filter, out _excludeCnt);
_totalCnt = fileList.Count(); _totalCnt = fileList.Count();
taskSearchfile.StopTask(); taskSearchFile.StopTask();
_childTask.MaxValue = _totalCnt; _childTask.MaxValue = _totalCnt;
_childTask.StartTask(); _childTask.StartTask();
await Parallel.ForEachAsync(fileList, FileHandle); await Parallel.ForEachAsync(fileList, FileHandleAsync);
}); });
var grid = new Grid().AddColumn(new GridColumn().NoWrap().PadRight(16)) var grid = new Grid().AddColumn(new GridColumn().NoWrap().PadRight(16))

View File

@ -8,11 +8,12 @@ namespace Dot.Get;
[Description(nameof(Ln.DownloadTool))] [Description(nameof(Ln.DownloadTool))]
[Localization(typeof(Ln))] [Localization(typeof(Ln))]
internal sealed partial class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
private const string _PART = "part"; private const string _PART = "part";
private static readonly Regex _partRegex = new($"(\\d+)\\.{_PART}", RegexOptions.Compiled);
protected override async Task Core() protected override async Task CoreAsync()
{ {
using var http = new HttpClient(); using var http = new HttpClient();
string attachment = default; string attachment = default;
@ -28,7 +29,9 @@ internal sealed partial class Main : ToolBase<Option>
attachment = content.Headers.ContentDisposition?.FileName ?? attachment = content.Headers.ContentDisposition?.FileName ??
Opt.Url[(Opt.Url.LastIndexOf('/') + 1)..]; Opt.Url[(Opt.Url.LastIndexOf('/') + 1)..];
foreach (var kv in content.Headers) { foreach (var kv in content.Headers) {
#pragma warning disable IDE0058
table.AddRow(kv.Key, string.Join(Environment.NewLine, kv.Value)); table.AddRow(kv.Key, string.Join(Environment.NewLine, kv.Value));
#pragma warning restore IDE0058
} }
}); });
AnsiConsole.Write(table); AnsiConsole.Write(table);
@ -59,38 +62,41 @@ internal sealed partial class Main : ToolBase<Option>
tParent.Increment(x); tParent.Increment(x);
}); });
tParent.MaxValue = tParent.Value; // 写完了 tParent.MaxValue = tParent.Value; // 写完了
tParent.IsIndeterminate(false); _ = tParent.IsIndeterminate(false);
tParent.StopTask(); tParent.StopTask();
} }
// 已知文件长度,多线程下载: // 已知文件长度,多线程下载:
else { else {
tParent.IsIndeterminate(false); _ = tParent.IsIndeterminate(false);
tParent.MaxValue = contentLength; tParent.MaxValue = contentLength;
var chunkSize = contentLength / Opt.ChunkNumbers; var chunkSize = contentLength / Opt.ChunkNumbers;
Parallel.For(0, Opt.ChunkNumbers async void BodyAction(int i)
, new ParallelOptions { MaxDegreeOfParallelism = Opt.MaxParallel } // {
, i => { var tChild = ctx.AddTask( //
var tChild = ctx.AddTask( $"{Ln.Thread}{i} {Ln.RemainingTime}:", maxValue: chunkSize);
$"{Ln.Thread}{i} {Ln.RemainingTime}:", maxValue: chunkSize); using var getReq = new HttpRequestMessage(HttpMethod.Get, Opt.Url);
using var getReq = new HttpRequestMessage(HttpMethod.Get, Opt.Url); var startPos = i * chunkSize;
var startPos = i * chunkSize; var endPos = startPos + chunkSize - 1;
var endPos = startPos + chunkSize - 1; if (i == Opt.ChunkNumbers - 1) {
if (i == Opt.ChunkNumbers - 1) { endPos += contentLength % chunkSize;
endPos += contentLength % chunkSize; }
}
getReq.Headers.Range = new RangeHeaderValue(startPos, endPos); getReq.Headers.Range = new RangeHeaderValue(startPos, endPos);
// ReSharper disable once AccessToDisposedClosure // ReSharper disable once AccessToDisposedClosure
using var getRsp using var getRsp
= http.Send(getReq, HttpCompletionOption.ResponseHeadersRead); = await http.SendAsync(getReq, HttpCompletionOption.ResponseHeadersRead);
WritePart(getRsp, mainFilePath, i, startPos, endPos, x => { WritePart(getRsp, mainFilePath, i, startPos, endPos, x => {
tChild.Increment(x); tChild.Increment(x);
tParent.Increment(x); tParent.Increment(x);
}); });
}); }
_ = Parallel.For(0, Opt.ChunkNumbers
, new ParallelOptions { MaxDegreeOfParallelism = Opt.MaxParallel } //
, BodyAction);
MergeParts(mainFilePath); MergeParts(mainFilePath);
} }
@ -109,14 +115,14 @@ internal sealed partial class Main : ToolBase<Option>
private static string BuildFilePath(string path, string file) private static string BuildFilePath(string path, string file)
{ {
// path 是一个存在的文件,已追加尾标 // path 是一个存在的文件,已追加尾标
if (GetUseablePath(ref path)) { if (GetUsablePath(ref path)) {
return path; return path;
} }
// ReSharper disable once InvertIf // ReSharper disable once InvertIf
if (Directory.Exists(path)) { // path 是一个存在的目录。 if (Directory.Exists(path)) { // path 是一个存在的目录。
path = Path.Combine(path, file); // 构建文件路径 path = Path.Combine(path, file); // 构建文件路径
GetUseablePath(ref path); // 追加序号。 _ = GetUsablePath(ref path); // 追加序号。
return path; return path;
} }
@ -124,15 +130,14 @@ internal sealed partial class Main : ToolBase<Option>
return path; return path;
} }
private static bool GetUseablePath(ref string path) private static bool GetUsablePath(ref string path)
{ {
var dir = Path.GetDirectoryName(path); var dir = Path.GetDirectoryName(path);
var name = Path.GetFileNameWithoutExtension(path); var name = Path.GetFileNameWithoutExtension(path);
var ext = Path.GetExtension(path); var ext = Path.GetExtension(path);
var ret = false; var ret = false;
#pragma warning disable SA1002
for (var i = 1;; ++i) { for (var i = 1; ; ++i) {
#pragma warning restore SA1002
if (File.Exists(path)) { if (File.Exists(path)) {
path = Path.Combine(dir!, $"{name}({i}){ext}"); path = Path.Combine(dir!, $"{name}({i}){ext}");
ret = true; ret = true;
@ -153,7 +158,7 @@ internal sealed partial class Main : ToolBase<Option>
.OrderBy(x => x) .OrderBy(x => x)
.ToArray(); .ToArray();
using var fs = File.Create(mainFilePath); using var fs = File.Create(mainFilePath);
fs.SetLength(PartRegex().Match(files.Last()).Groups[1].Value.Int64()); fs.SetLength(_partRegex.Match(files[^1]).Groups[1].Value.Int64());
foreach (var file in files) { foreach (var file in files) {
using var fsc = File.OpenRead(file); using var fsc = File.OpenRead(file);
fsc.CopyTo(fs); fsc.CopyTo(fs);
@ -162,9 +167,6 @@ internal sealed partial class Main : ToolBase<Option>
} }
} }
[GeneratedRegex($"(\\d+)\\.{_PART}")]
private static partial Regex PartRegex();
private void StreamCopy(Stream source, Stream dest, Action<int> rateHandle) private void StreamCopy(Stream source, Stream dest, Action<int> rateHandle)
{ {
Span<byte> buf = stackalloc byte[Opt.BufferSize]; Span<byte> buf = stackalloc byte[Opt.BufferSize];

View File

@ -15,16 +15,16 @@ internal sealed class Main : ToolBase<Option>
private ConcurrentDictionary<string, StringBuilder> _repoRsp; // 仓库信息容器 private ConcurrentDictionary<string, StringBuilder> _repoRsp; // 仓库信息容器
private ConcurrentDictionary<string, TaskStatusColumn.Statues> _repoStatus; private ConcurrentDictionary<string, TaskStatusColumn.Statues> _repoStatus;
protected override Task Core() protected override Task CoreAsync()
{ {
return !Directory.Exists(Opt.Path) return !Directory.Exists(Opt.Path)
? throw new ArgumentException( // ? throw new ArgumentException( //
nameof(Opt.Path) // nameof(Opt.Path) //
, string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path)) , string.Format(CultureInfo.InvariantCulture, Ln.PathNotFound, Opt.Path))
: CoreInternal(); : CoreInternalAsync();
} }
private async Task CoreInternal() private async Task CoreInternalAsync()
{ {
_gitOutputEnc = Encoding.GetEncoding(Opt.GitOutputEncoding); _gitOutputEnc = Encoding.GetEncoding(Opt.GitOutputEncoding);
var progressBar = new ProgressBarColumn { Width = 10 }; var progressBar = new ProgressBarColumn { Width = 10 };
@ -63,7 +63,7 @@ internal sealed class Main : ToolBase<Option>
taskFinder.StopTask(); taskFinder.StopTask();
taskFinder.State.Status(TaskStatusColumn.Statues.Succeed); taskFinder.State.Status(TaskStatusColumn.Statues.Succeed);
await Parallel.ForEachAsync(tasks, DirHandle); await Parallel.ForEachAsync(tasks, DirHandleAsync);
}); });
var table = new Table().AddColumn(new TableColumn(Ln.Repository) { Width = 50 }) var table = new Table().AddColumn(new TableColumn(Ln.Repository) { Width = 50 })
@ -74,17 +74,16 @@ internal sealed class Main : ToolBase<Option>
.Succeed)}[/]/{_repoStatus.Count}"); .Succeed)}[/]/{_repoStatus.Count}");
foreach (var repo in _repoRsp) { foreach (var repo in _repoRsp) {
var status = _repoStatus[repo.Key].Desc(); var status = _repoStatus[repo.Key].ResDesc<Ln>();
table.AddRow(status.Replace(_repoStatus[repo.Key].ToString(), new DirectoryInfo(repo.Key).Name), Opt.Args _ = table.AddRow( //
, status.Replace(_repoStatus[repo.Key].ToString(), repo.Value.ToString())); status.Replace(_repoStatus[repo.Key].ToString(), new DirectoryInfo(repo.Key).Name), Opt.Args
, status.Replace(_repoStatus[repo.Key].ToString(), repo.Value.ToString()));
} }
AnsiConsole.Write(table); AnsiConsole.Write(table);
} }
#pragma warning disable SA1313 private async ValueTask DirHandleAsync(KeyValuePair<string, ProgressTask> payload, CancellationToken ct)
private async ValueTask DirHandle(KeyValuePair<string, ProgressTask> payload, CancellationToken _)
#pragma warning restore SA1313
{ {
payload.Value.StartTask(); payload.Value.StartTask();
payload.Value.State.Status(TaskStatusColumn.Statues.Executing); payload.Value.State.Status(TaskStatusColumn.Statues.Executing);
@ -97,7 +96,7 @@ internal sealed class Main : ToolBase<Option>
} }
var msg = Encoding.UTF8.GetString(_gitOutputEnc.GetBytes(e.Data)); var msg = Encoding.UTF8.GetString(_gitOutputEnc.GetBytes(e.Data));
_repoRsp[payload.Key].Append(msg.EscapeMarkup()); _ = _repoRsp[payload.Key].Append(msg.EscapeMarkup());
} }
// 启动git进程 // 启动git进程
@ -119,14 +118,14 @@ internal sealed class Main : ToolBase<Option>
if (p.ExitCode == 0) { if (p.ExitCode == 0) {
payload.Value.State.Status(TaskStatusColumn.Statues.Succeed); payload.Value.State.Status(TaskStatusColumn.Statues.Succeed);
_repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Succeed _ = _repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Succeed
, (_, _) => TaskStatusColumn.Statues.Succeed); , (_, _) => TaskStatusColumn.Statues.Succeed);
payload.Value.StopTask(); payload.Value.StopTask();
} }
else { else {
payload.Value.State.Status(TaskStatusColumn.Statues.Failed); payload.Value.State.Status(TaskStatusColumn.Statues.Failed);
_repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Failed _ = _repoStatus.AddOrUpdate(payload.Key, _ => TaskStatusColumn.Statues.Failed
, (_, _) => TaskStatusColumn.Statues.Failed); , (_, _) => TaskStatusColumn.Statues.Failed);
} }
payload.Value.StopTask(); payload.Value.StopTask();

View File

@ -14,7 +14,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Ready /// Ready
/// </summary> /// </summary>
[Description($"[gray]{nameof(Ready)}[/]")] [Description($"[gray]{nameof(Ready)}[/]")]
Ready Ready = 0
, ,
@ -22,7 +22,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Executing /// Executing
/// </summary> /// </summary>
[Description($"[yellow]{nameof(Executing)}[/]")] [Description($"[yellow]{nameof(Executing)}[/]")]
Executing Executing = 1
, ,
@ -30,7 +30,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Succeed /// Succeed
/// </summary> /// </summary>
[Description($"[green]{nameof(Succeed)}[/]")] [Description($"[green]{nameof(Succeed)}[/]")]
Succeed Succeed = 2
, ,
@ -38,7 +38,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Failed /// Failed
/// </summary> /// </summary>
[Description($"[red]{nameof(Failed)}[/]")] [Description($"[red]{nameof(Failed)}[/]")]
Failed Failed = 3
} }
/// <summary> /// <summary>
@ -53,6 +53,6 @@ internal sealed class TaskStatusColumn : ProgressColumn
public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime) public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime)
{ {
var text = task.State.Get<Statues>(nameof(TaskStatusColumn)); var text = task.State.Get<Statues>(nameof(TaskStatusColumn));
return new Markup(text.Desc()).Overflow(Overflow.Ellipsis).Justify(Alignment); return new Markup(text.ResDesc<Ln>()).Overflow(Overflow.Ellipsis).Justify(Alignment);
} }
} }

View File

@ -10,7 +10,7 @@ namespace Dot.Guid;
[Localization(typeof(Ln))] [Localization(typeof(Ln))]
internal sealed class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
protected override Task Core() protected override Task CoreAsync()
{ {
var guid = System.Guid.NewGuid().ToString(); var guid = System.Guid.NewGuid().ToString();
if (Opt.Upper) { if (Opt.Upper) {

View File

@ -9,7 +9,9 @@ namespace Dot.IP;
[Localization(typeof(Ln))] [Localization(typeof(Ln))]
internal sealed class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
protected override async Task Core() private const string _HTTP_BIN_ORG_IP = "http://httpbin.org/ip";
protected override async Task CoreAsync()
{ {
foreach (var item in NetworkInterface.GetAllNetworkInterfaces()) { foreach (var item in NetworkInterface.GetAllNetworkInterfaces()) {
if (item.NetworkInterfaceType != NetworkInterfaceType.Ethernet || if (item.NetworkInterfaceType != NetworkInterfaceType.Ethernet ||
@ -21,13 +23,13 @@ internal sealed class Main : ToolBase<Option>
Environment.NewLine Environment.NewLine
, item.GetIPProperties() , item.GetIPProperties()
.UnicastAddresses.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork) .UnicastAddresses.Where(x => x.Address.AddressFamily == AddressFamily.InterNetwork)
.Select(x => @$"{item.Name}: {x.Address}")); .Select(x => $"{item.Name}: {x.Address}"));
Console.WriteLine(output); Console.WriteLine(output);
} }
using var http = new HttpClient(); using var http = new HttpClient();
Console.Write(Ln.PublicIP); Console.Write(Ln.PublicIP);
var str = await http.GetStringAsync("http://httpbin.org/ip"); var str = await http.GetStringAsync(_HTTP_BIN_ORG_IP);
Console.WriteLine(str); Console.WriteLine(str);
} }
} }

View File

@ -14,7 +14,7 @@ internal sealed class Main : ToolBase<Option>
{ {
private object _inputObj; private object _inputObj;
protected override Task Core() protected override Task CoreAsync()
{ {
var inputText = Opt.InputText; var inputText = Opt.InputText;
@ -43,7 +43,7 @@ internal sealed class Main : ToolBase<Option>
throw new ArgumentException(Ln.InvalidJsonString); throw new ArgumentException(Ln.InvalidJsonString);
} }
return CoreInternal(); return CoreInternalAsync();
} }
private static string UnescapeString(string text) private static string UnescapeString(string text)
@ -51,24 +51,23 @@ internal sealed class Main : ToolBase<Option>
return text.Replace("\\\"", "\""); return text.Replace("\\\"", "\"");
} }
private async Task<string> ConvertToString() private async Task<string> ConvertToStringAsync()
{ {
var ret = await JsonCompress(); var ret = await JsonCompressAsync();
ret = ret.Replace("\"", "\\\""); return ret.Replace("\"", "\\\"");
return ret;
} }
private async Task CoreInternal() private async Task CoreInternalAsync()
{ {
string result = null; string result = null;
if (Opt.Compress) { if (Opt.Compress) {
result = await JsonCompress(); result = await JsonCompressAsync();
} }
else if (Opt.ConvertToString) { else if (Opt.ConvertToString) {
result = await ConvertToString(); result = await ConvertToStringAsync();
} }
else if (Opt.Format) { else if (Opt.Format) {
result = await JsonFormat(); result = await JsonFormatAsync();
} }
if (!result.NullOrWhiteSpace()) { if (!result.NullOrWhiteSpace()) {
@ -78,15 +77,15 @@ internal sealed class Main : ToolBase<Option>
} }
} }
private Task<string> JsonCompress() private Task<string> JsonCompressAsync()
{ {
var ret = _inputObj.Json(); var ret = _inputObj.Json();
return Task.FromResult(ret); return Task.FromResult(ret);
} }
private Task<string> JsonFormat() private Task<string> JsonFormatAsync()
{ {
var ret = _inputObj.Json(true); var ret = _inputObj.Json(new JsonSerializerOptions { WriteIndented = true });
return Task.FromResult(ret); return Task.FromResult(ret);
} }
} }

View File

@ -50,7 +50,7 @@
<value>Screen coordinate color selection tool</value> <value>Screen coordinate color selection tool</value>
</data> </data>
<data name="DownloadTool" xml:space="preserve"> <data name="DownloadTool" xml:space="preserve">
<value>Multithreaded download tool</value> <value>Multi-Threaded download tool</value>
</data> </data>
<data name="TextTool" xml:space="preserve"> <data name="TextTool" xml:space="preserve">
<value>Text encoding tool</value> <value>Text encoding tool</value>

View File

@ -34,7 +34,7 @@ internal sealed class KeyboardHook : IDisposable
private static nint SetHook(Win32.HookProc lpfn) private static nint SetHook(Win32.HookProc lpfn)
{ {
using var process = Process.GetCurrentProcess(); using var process = Process.GetCurrentProcess();
using var module = process.MainModule; using var module = process.MainModule;
return Win32.SetWindowsHookExA(Win32.WH_KEYBOARD_LL, lpfn, module!.BaseAddress, 0); return Win32.SetWindowsHookExA(Win32.WH_KEYBOARD_LL, lpfn, module!.BaseAddress, 0);
} }
@ -49,7 +49,7 @@ internal sealed class KeyboardHook : IDisposable
} }
if (_hookId != default) { if (_hookId != default) {
Win32.UnhookWindowsHookExA(_hookId); _ = Win32.UnhookWindowsHookExA(_hookId);
} }
_disposed = true; _disposed = true;

View File

@ -21,7 +21,7 @@ internal sealed class MouseHook : IDisposable
Dispose(false); Dispose(false);
} }
public event MouseEventHandler MouseMoveEvent; public event EventHandler<MouseEventArgs> MouseMoveEvent;
public void Dispose() public void Dispose()
{ {
@ -32,7 +32,7 @@ internal sealed class MouseHook : IDisposable
private static nint SetHook(Win32.HookProc lpfn) private static nint SetHook(Win32.HookProc lpfn)
{ {
using var process = Process.GetCurrentProcess(); using var process = Process.GetCurrentProcess();
using var module = process.MainModule; using var module = process.MainModule;
return Win32.SetWindowsHookExA(Win32.WH_MOUSE_LL, lpfn, module!.BaseAddress, 0); return Win32.SetWindowsHookExA(Win32.WH_MOUSE_LL, lpfn, module!.BaseAddress, 0);
} }
@ -47,7 +47,7 @@ internal sealed class MouseHook : IDisposable
} }
if (_hookId != default) { if (_hookId != default) {
Win32.UnhookWindowsHookExA(_hookId); _ = Win32.UnhookWindowsHookExA(_hookId);
} }
_disposed = true; _disposed = true;
@ -58,7 +58,7 @@ internal sealed class MouseHook : IDisposable
// ReSharper disable once InvertIf // ReSharper disable once InvertIf
if (wParam == Win32.WM_MOUSEMOVE) { if (wParam == Win32.WM_MOUSEMOVE) {
var hookStruct = (Msllhookstruct)Marshal.PtrToStructure(lParam, typeof(Msllhookstruct))!; var hookStruct = (Msllhookstruct)Marshal.PtrToStructure(lParam, typeof(Msllhookstruct))!;
MouseMoveEvent?.Invoke(null, new MouseEventArgs(MouseButtons.None, 0, hookStruct.X, hookStruct.Y, 0)); MouseMoveEvent?.Invoke(this, new MouseEventArgs(MouseButtons.None, 0, hookStruct.X, hookStruct.Y, 0));
} }
return Win32.CallNextHookEx(_hookId, nCode, wParam, lParam); return Win32.CallNextHookEx(_hookId, nCode, wParam, lParam);

View File

@ -1,6 +1,6 @@
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
// ReSharper disable IdentifierTypo
#pragma warning disable CS1591 // ReSharper disable CommentTypo
namespace Dot.Native; namespace Dot.Native;

View File

@ -1,7 +1,7 @@
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMethodReturnValue.Global // ReSharper disable UnusedMethodReturnValue.Global
#pragma warning disable SA1307, SX1309 #pragma warning disable SA1307,SX1309
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
@ -71,7 +71,7 @@ internal static partial class Win32
public static partial int SetClipboardViewer(nint hWnd); public static partial int SetClipboardViewer(nint hWnd);
[LibraryImport(_KERNEL32_DLL)] [LibraryImport(_KERNEL32_DLL)]
public static partial void SetLocalTime(Systemtime st); public static partial void SetLocalTime(SystemTime st);
[LibraryImport(_USER32_DLL)] [LibraryImport(_USER32_DLL)]
public static partial nint SetWindowsHookExA(int idHook, HookProc lpfn, nint hMod, uint dwThreadId); public static partial nint SetWindowsHookExA(int idHook, HookProc lpfn, nint hMod, uint dwThreadId);
@ -136,7 +136,7 @@ internal static partial class Win32
} }
[StructLayout(LayoutKind.Explicit)] [StructLayout(LayoutKind.Explicit)]
public ref struct Systemtime public ref struct SystemTime
{ {
[FieldOffset(6)] [FieldOffset(6)]
public ushort wDay; public ushort wDay;

View File

@ -18,7 +18,7 @@ internal sealed class Main : ToolBase<Option>
, "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".ToCharArray() , "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~".ToCharArray()
}; };
protected override Task Core() protected override Task CoreAsync()
{ {
unsafe { unsafe {
var pSource = stackalloc char[_charTable.Sum(x => x.Length)]; var pSource = stackalloc char[_charTable.Sum(x => x.Length)];

View File

@ -8,10 +8,11 @@ internal sealed class Option : OptionBase
[Flags] [Flags]
public enum GenerateTypes public enum GenerateTypes
{ {
Number = 0b0001 None = 0
, LowerCaseLetter = 0b0010 , Number = 1
, UpperCaseLetter = 0b0100 , LowerCaseLetter = 1 << 1
, SpecialCharacter = 0b1000 , UpperCaseLetter = 1 << 2
, SpecialCharacter = 1 << 3
} }
[CommandArgument(1, "<password length>")] [CommandArgument(1, "<password length>")]

View File

@ -8,7 +8,7 @@ internal sealed class Main : FilesTool<Option>
{ {
private readonly byte[] _utf8Bom = { 0xef, 0xbb, 0xbf }; private readonly byte[] _utf8Bom = { 0xef, 0xbb, 0xbf };
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken) protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{ {
ShowMessage(1, 0, 0); ShowMessage(1, 0, 0);

View File

@ -15,9 +15,9 @@ namespace Dot.Text;
internal sealed class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
#if NET7_0_WINDOWS #if NET7_0_WINDOWS
protected override async Task Core() protected override async Task CoreAsync()
#else #else
protected override Task Core() protected override Task CoreAsync()
#endif #endif
{ {
#if NET7_0_WINDOWS #if NET7_0_WINDOWS
@ -39,15 +39,18 @@ internal sealed class Main : ToolBase<Option>
{ {
Output ret; Output ret;
var inputHex = text.Hex(enc); var inputHex = text.Hex(enc);
ret.Base64DeCodeHex = ReadOnlySpan<char>.Empty;
ret.Base64DeCode = ReadOnlySpan<char>.Empty; ret.Base64DeCodeHex = ReadOnlySpan<char>.Empty;
ret.EncodingName = enc.EncodingName; ret.Base64DeCode = ReadOnlySpan<char>.Empty;
ret.Hex = inputHex.String(); ret.EncodingName = enc.EncodingName;
ret.Base64 = text.Base64(enc); ret.Hex = inputHex.Str();
ret.Md5 = MD5.HashData(inputHex).String(); ret.Base64 = text.Base64(enc);
ret.Sha1 = SHA1.HashData(inputHex).String(); #pragma warning disable CA5351, CA5350
ret.Sha256 = SHA256.HashData(inputHex).String(); ret.Md5 = MD5.HashData(inputHex).Str();
ret.Sha512 = SHA512.HashData(inputHex).String(); ret.Sha1 = SHA1.HashData(inputHex).Str();
#pragma warning restore CA5350, CA5351
ret.Sha256 = SHA256.HashData(inputHex).Str();
ret.Sha512 = SHA512.HashData(inputHex).Str();
ret.UrlEncode = text.Url(); ret.UrlEncode = text.Url();
ret.UrlDecode = text.UrlDe(); ret.UrlDecode = text.UrlDe();
ret.HtmlDecode = text.HtmlDe(); ret.HtmlDecode = text.HtmlDe();
@ -58,9 +61,9 @@ internal sealed class Main : ToolBase<Option>
ret.UnicodeDecode = text.UnicodeDe(); ret.UnicodeDecode = text.UnicodeDe();
if (Equals(enc, Encoding.BigEndianUnicode)) { if (Equals(enc, Encoding.BigEndianUnicode)) {
ret.PercentUnicode = inputHex.String(false, "%u", 2); ret.PercentUnicode = inputHex.Str(false, "%u", 2);
ret.AndUnicode = inputHex.String(false, @";&#x", 2)[1..] + ";"; ret.AndUnicode = inputHex.Str(false, ";&#x", 2)[1..] + ";";
ret.BacksLantUnicode = inputHex.String(false, @"\u", 2); ret.BacksLantUnicode = inputHex.Str(false, @"\u", 2);
} }
if (!text.IsBase64String()) { if (!text.IsBase64String()) {
@ -71,7 +74,7 @@ internal sealed class Main : ToolBase<Option>
try { try {
base64DeHex = text.Base64De(); base64DeHex = text.Base64De();
} }
catch (Exception) { catch {
// ignored // ignored
} }
@ -79,7 +82,7 @@ internal sealed class Main : ToolBase<Option>
return ret; return ret;
} }
ret.Base64DeCodeHex = base64DeHex.String(); ret.Base64DeCodeHex = base64DeHex.Str();
ret.Base64DeCode = enc.GetString(base64DeHex); ret.Base64DeCode = enc.GetString(base64DeHex);
return ret; return ret;
@ -89,29 +92,29 @@ internal sealed class Main : ToolBase<Option>
{ {
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine( // _ = sb.AppendLine( //
CultureInfo.InvariantCulture CultureInfo.InvariantCulture
, $"{new string('-', 20)} {o.EncodingName} {new string('-', 30 - o.EncodingName.Length)}"); , $"{new string('-', 20)} {o.EncodingName} {new string('-', 30 - o.EncodingName.Length)}");
sb.AppendLine(CultureInfo.InvariantCulture, $"hex: {o.Hex}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"hex: {o.Hex}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64: {o.Base64}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64: {o.Base64}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode-hex: {o.Base64DeCodeHex}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode-hex: {o.Base64DeCodeHex}");
sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode: {o.Base64DeCode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"base64-decode: {o.Base64DeCode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"md5: {o.Md5}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"md5: {o.Md5}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha1: {o.Sha1}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha1: {o.Sha1}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha256: {o.Sha256}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha256: {o.Sha256}");
sb.AppendLine(CultureInfo.InvariantCulture, $"sha512: {o.Sha512}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"sha512: {o.Sha512}");
sb.AppendLine(CultureInfo.InvariantCulture, $"url-encode: {o.UrlEncode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"url-encode: {o.UrlEncode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"url-decode: {o.UrlDecode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"url-decode: {o.UrlDecode}");
if (o.EncodingName.Equals(Encoding.BigEndianUnicode.EncodingName, StringComparison.OrdinalIgnoreCase)) { if (o.EncodingName.Equals(Encoding.BigEndianUnicode.EncodingName, StringComparison.OrdinalIgnoreCase)) {
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-percent: {o.PercentUnicode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-percent: {o.PercentUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-and: {o.AndUnicode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-and: {o.AndUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-backslant: {o.BacksLantUnicode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-back-slant: {o.BacksLantUnicode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-decode: {o.UnicodeDecode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"unicode-decode: {o.UnicodeDecode}");
} }
sb.AppendLine(CultureInfo.InvariantCulture, $"html-encode: {o.HtmlEncode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"html-encode: {o.HtmlEncode}");
sb.AppendLine(CultureInfo.InvariantCulture, $"html-decode: {o.HtmlDecode}"); _ = sb.AppendLine(CultureInfo.InvariantCulture, $"html-decode: {o.HtmlDecode}");
return sb.ToString(); return sb.ToString();
} }
@ -124,10 +127,10 @@ internal sealed class Main : ToolBase<Option>
var unicodeBigEndian = BuildOutput(text, Encoding.BigEndianUnicode); var unicodeBigEndian = BuildOutput(text, Encoding.BigEndianUnicode);
var sb = new StringBuilder(); var sb = new StringBuilder();
sb.AppendLine(BuildTemplate(ansi)); sb.AppendLine(BuildTemplate(ansi))
sb.AppendLine(BuildTemplate(utf8)); .AppendLine(BuildTemplate(utf8))
sb.AppendLine(BuildTemplate(unicodeLittleEndian)); .AppendLine(BuildTemplate(unicodeLittleEndian))
sb.AppendLine(BuildTemplate(unicodeBigEndian)); .AppendLine(BuildTemplate(unicodeBigEndian));
var str = sb.ToString(); var str = sb.ToString();
Console.WriteLine(str); Console.WriteLine(str);

View File

@ -12,6 +12,7 @@ internal sealed class Main : ToolBase<Option>
private const int _MAX_DEGREE_OF_PARALLELISM = 10; private const int _MAX_DEGREE_OF_PARALLELISM = 10;
private const int _NTP_PORT = 123; private const int _NTP_PORT = 123;
// ReSharper disable StringLiteralTypo
private readonly string[] _ntpServers = { private readonly string[] _ntpServers = {
"ntp.ntsc.ac.cn", "cn.ntp.org.cn", "edu.ntp.org.cn", "cn.pool.ntp.org" "ntp.ntsc.ac.cn", "cn.ntp.org.cn", "edu.ntp.org.cn", "cn.pool.ntp.org"
, "time.pool.aliyun.com", "time1.aliyun.com", "time2.aliyun.com" , "time.pool.aliyun.com", "time1.aliyun.com", "time2.aliyun.com"
@ -30,11 +31,12 @@ internal sealed class Main : ToolBase<Option>
, "stdtime.gov.hk" , "stdtime.gov.hk"
}; };
// ReSharper restore StringLiteralTypo
private double _offsetAvg; private double _offsetAvg;
private int _successCnt; private int _successCnt;
protected override async Task Core() protected override async Task CoreAsync()
{ {
await AnsiConsole.Progress() await AnsiConsole.Progress()
.Columns( // .Columns( //
@ -50,7 +52,7 @@ internal sealed class Main : ToolBase<Option>
await Parallel.ForEachAsync( await Parallel.ForEachAsync(
tasks, new ParallelOptions { MaxDegreeOfParallelism = _MAX_DEGREE_OF_PARALLELISM } tasks, new ParallelOptions { MaxDegreeOfParallelism = _MAX_DEGREE_OF_PARALLELISM }
, ServerHandle); , ServerHandleAsync);
_offsetAvg = tasks.Where(x => x.Value.State.Status() == TaskStatusColumn.Statues.Succeed) _offsetAvg = tasks.Where(x => x.Value.State.Status() == TaskStatusColumn.Statues.Succeed)
.Average(x => x.Value.State.Result().TotalMilliseconds); .Average(x => x.Value.State.Result().TotalMilliseconds);
@ -60,14 +62,14 @@ internal sealed class Main : ToolBase<Option>
, _ntpServers.Length, $"[yellow]{_offsetAvg:f2}[/]"); , _ntpServers.Length, $"[yellow]{_offsetAvg:f2}[/]");
if (Opt.Sync) { if (Opt.Sync) {
SetSysteTime(DateTime.Now.AddMilliseconds(-_offsetAvg)); SetSystemTime(DateTime.Now.AddMilliseconds(-_offsetAvg));
AnsiConsole.MarkupLine($"[green]{Ln.LocalTimeSyncDone}[/]"); AnsiConsole.MarkupLine($"[green]{Ln.LocalTimeSyncDone}[/]");
} }
} }
protected override async Task Run() protected override async Task RunAsync()
{ {
await Core(); await CoreAsync();
if (Opt.KeepSession) { if (Opt.KeepSession) {
var table = new Table().HideHeaders() var table = new Table().HideHeaders()
.AddColumn(new TableColumn(string.Empty)) .AddColumn(new TableColumn(string.Empty))
@ -94,9 +96,9 @@ internal sealed class Main : ToolBase<Option>
} }
} }
private static void SetSysteTime(DateTime time) private static void SetSystemTime(DateTime time)
{ {
var timeToSet = new Win32.Systemtime { var timeToSet = new Win32.SystemTime {
wDay = (ushort)time.Day wDay = (ushort)time.Day
, wDayOfWeek = (ushort)time.DayOfWeek , wDayOfWeek = (ushort)time.DayOfWeek
, wHour = (ushort)time.Hour , wHour = (ushort)time.Hour
@ -145,9 +147,7 @@ internal sealed class Main : ToolBase<Option>
} }
} }
#pragma warning disable SA1313 private ValueTask ServerHandleAsync(KeyValuePair<string, ProgressTask> payload, CancellationToken ct)
private ValueTask ServerHandle(KeyValuePair<string, ProgressTask> payload, CancellationToken _)
#pragma warning restore SA1313
{ {
payload.Value.StartTask(); payload.Value.StartTask();
payload.Value.State.Status(TaskStatusColumn.Statues.Connecting); payload.Value.State.Status(TaskStatusColumn.Statues.Connecting);
@ -158,7 +158,7 @@ internal sealed class Main : ToolBase<Option>
else { else {
payload.Value.State.Status(TaskStatusColumn.Statues.Succeed); payload.Value.State.Status(TaskStatusColumn.Statues.Succeed);
payload.Value.State.Result(offset); payload.Value.State.Result(offset);
Interlocked.Increment(ref _successCnt); _ = Interlocked.Increment(ref _successCnt);
} }
payload.Value.StopTask(); payload.Value.StopTask();

View File

@ -14,7 +14,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Ready /// Ready
/// </summary> /// </summary>
[Description($"[gray]{nameof(Ready)}[/]")] [Description($"[gray]{nameof(Ready)}[/]")]
Ready Ready = 0
, ,
@ -22,7 +22,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Connecting /// Connecting
/// </summary> /// </summary>
[Description($"[yellow]{nameof(Connecting)}[/]")] [Description($"[yellow]{nameof(Connecting)}[/]")]
Connecting Connecting = 1
, ,
@ -30,7 +30,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Succeed /// Succeed
/// </summary> /// </summary>
[Description($"[green]{nameof(Succeed)}[/]")] [Description($"[green]{nameof(Succeed)}[/]")]
Succeed Succeed = 2
, ,
@ -38,7 +38,7 @@ internal sealed class TaskStatusColumn : ProgressColumn
/// Failed /// Failed
/// </summary> /// </summary>
[Description($"[red]{nameof(Failed)}[/]")] [Description($"[red]{nameof(Failed)}[/]")]
Failed Failed = 3
} }
/// <summary> /// <summary>
@ -53,6 +53,6 @@ internal sealed class TaskStatusColumn : ProgressColumn
public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime) public override IRenderable Render(RenderOptions options, ProgressTask task, TimeSpan deltaTime)
{ {
var text = task.State.Get<Statues>(nameof(TaskStatusColumn)); var text = task.State.Get<Statues>(nameof(TaskStatusColumn));
return new Markup(text.Desc()).Overflow(Overflow.Ellipsis).Justify(Alignment); return new Markup(text.ResDesc<Ln>()).Overflow(Overflow.Ellipsis).Justify(Alignment);
} }
} }

View File

@ -6,7 +6,7 @@ namespace Dot.ToLf;
[Localization(typeof(Ln))] [Localization(typeof(Ln))]
internal sealed class Main : FilesTool<Option> internal sealed class Main : FilesTool<Option>
{ {
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken) protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{ {
ShowMessage(1, 0, 0); ShowMessage(1, 0, 0);
@ -48,7 +48,9 @@ internal sealed class Main : FilesTool<Option>
} }
} }
#pragma warning disable S2583
if (hasWrote && !isBin) { if (hasWrote && !isBin) {
#pragma warning restore S2583
if (Opt.WriteMode) { if (Opt.WriteMode) {
File.Copy(tmpFile, file, true); File.Copy(tmpFile, file, true);
} }

View File

@ -8,15 +8,15 @@ internal abstract class ToolBase<TOption> : Command<TOption>
public override int Execute(CommandContext context, TOption settings) public override int Execute(CommandContext context, TOption settings)
{ {
Opt = settings; Opt = settings;
Run().Wait(); RunAsync().Wait();
return 0; return 0;
} }
protected abstract Task Core(); protected abstract Task CoreAsync();
protected virtual async Task Run() protected virtual async Task RunAsync()
{ {
await Core(); await CoreAsync();
if (Opt.KeepSession) { if (Opt.KeepSession) {
AnsiConsole.MarkupLine(Ln.PressAnyKey); AnsiConsole.MarkupLine(Ln.PressAnyKey);
_ = AnsiConsole.Console.Input.ReadKey(true); _ = AnsiConsole.Console.Input.ReadKey(true);

View File

@ -23,7 +23,7 @@ internal static class BaiduSignCracker
case < 2048: case < 2048:
e.Add((k >> 6) | 192); e.Add((k >> 6) | 192);
break; break;
default: { default:
if ((k & 64512) == 55296 && i + 1 < hash.Length && (hash[i + 1] & 64512) == 56320) { if ((k & 64512) == 55296 && i + 1 < hash.Length && (hash[i + 1] & 64512) == 56320) {
k = 65536 + ((k & 1023) << 10) + (hash[++i] & 1023); k = 65536 + ((k & 1023) << 10) + (hash[++i] & 1023);
e.Add((k >> 18) | 240); e.Add((k >> 18) | 240);
@ -36,7 +36,6 @@ internal static class BaiduSignCracker
} }
break; break;
}
} }
} }
@ -55,7 +54,7 @@ internal static class BaiduSignCracker
var c = password[i + 2]; var c = password[i + 2];
var moveBit = c >= 'a' ? c - 87 : c.ToString().Int32(); var moveBit = c >= 'a' ? c - 87 : c.ToString().Int32();
var d = password[i + 1] == '+' ? number >>> moveBit : number << moveBit; var d = password[i + 1] == '+' ? number >>> moveBit : number << moveBit;
number = password[i] == '+' ? (number + d) & (int)uint.MaxValue : number ^ d; number = password[i] == '+' ? number + d : number ^ d;
} }
} }

View File

@ -2,8 +2,10 @@
// ReSharper disable ClassNeverInstantiated.Global // ReSharper disable ClassNeverInstantiated.Global
// ReSharper disable UnusedMember.Global // ReSharper disable UnusedMember.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global // ReSharper disable UnusedAutoPropertyAccessor.Global
// ReSharper disable IdentifierTypo
#pragma warning disable IDE1006,SA1300 #pragma warning disable IDE1006,SA1300
namespace Dot.Tran.Dto; namespace Dot.Tran.Dto;
internal sealed record BaiduTranslateResultDto internal sealed record BaiduTranslateResultDto
@ -26,7 +28,9 @@ internal sealed record BaiduTranslateResultDto
public string trg_str { get; set; } public string trg_str { get; set; }
} }
#pragma warning disable S1144
public sealed record Root public sealed record Root
#pragma warning restore S1144
{ {
public string errmsg { get; set; } public string errmsg { get; set; }

View File

@ -12,14 +12,14 @@ namespace Dot.Tran;
internal sealed class Main : ToolBase<Option> internal sealed class Main : ToolBase<Option>
{ {
[SupportedOSPlatform(nameof(OSPlatform.Windows))] [SupportedOSPlatform(nameof(OSPlatform.Windows))]
protected override Task Core() protected override Task CoreAsync()
{ {
AnsiConsole.MarkupLine(Ln.StartTranslate); AnsiConsole.MarkupLine(Ln.StartTranslate);
AnsiConsole.MarkupLine(Ln.HideTranslate); AnsiConsole.MarkupLine(Ln.HideTranslate);
var th = new Thread(() => { var th = new Thread(() => {
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException); Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
AppDomain.CurrentDomain.UnhandledException += UnhandledException; AppDomain.CurrentDomain.UnhandledException += UnhandledException;
Application.ThreadException += UIThreadException; Application.ThreadException += UIThreadException;
using var frm = new WinMain(); using var frm = new WinMain();
try { try {
Application.Run(); Application.Run();
@ -37,7 +37,7 @@ internal sealed class Main : ToolBase<Option>
private static void Log(string msg) private static void Log(string msg)
{ {
var file = Path.Combine(Path.GetTempPath(), $"{DateTime.Now.yyyyMMdd()}.dotlog"); var file = Path.Combine(Path.GetTempPath(), $"{DateTime.Now.yyyyMMdd()}.dotlog");
File.AppendAllText(file, $"{Environment.NewLine}{msg}"); File.AppendAllText(file, Environment.NewLine + msg);
} }
private static void UIThreadException(object sender, ThreadExceptionEventArgs e) private static void UIThreadException(object sender, ThreadExceptionEventArgs e)

View File

@ -12,22 +12,22 @@ using Size = System.Drawing.Size;
namespace Dot.Tran; namespace Dot.Tran;
[SupportedOSPlatform(nameof(OSPlatform.Windows))] [SupportedOSPlatform(nameof(OSPlatform.Windows))]
internal sealed partial class WinMain : Form internal sealed class WinMain : Form
{ {
private const int _RETRY_WAIT_MIL_SEC = 1000; private const int _RETRY_WAIT_MIL_SEC = 1000;
private const string _TRANSLATE_API_URL = $"{_TRANSLATE_HOME_URL}/v2transapi"; private const string _TRANSLATE_API_URL = $"{_TRANSLATE_HOME_URL}/v2transapi";
private const string _TRANSLATE_HOME_URL = "https://fanyi.baidu.com"; private const string _TRANSLATE_HOME_URL = "https://fanyi.baidu.com";
private readonly HttpClient _httpClient = new(new HttpClientHandler { UseProxy = false }); private static readonly Regex _tokenRegex = new("token: '(\\w+)'", RegexOptions.Compiled);
private readonly KeyboardHook _keyboardHook = new(); private readonly HttpClient _httpClient = new(new HttpClientHandler { UseProxy = false });
private readonly Label _labelDest = new(); private readonly KeyboardHook _keyboardHook = new();
private readonly MouseHook _mouseHook = new(); private readonly Label _labelDest = new();
private readonly Size _mouseMargin = new(10, 10); private readonly MouseHook _mouseHook = new();
private readonly string _stateFile = Path.Combine(Path.GetTempPath(), "dot-tran-state.tmp"); private readonly Size _mouseMargin = new(10, 10);
private bool _capsLockPressed; private readonly string _stateFile = Path.Combine(Path.GetTempPath(), "dot-tran-state.tmp");
private volatile string _cookie; private bool _capsLockPressed;
private bool _disposed; private bool _disposed;
private nint _nextClipMonitor; private nint _nextClipMonitor;
private volatile string _token; private volatile string _token;
public WinMain() public WinMain()
{ {
@ -59,7 +59,7 @@ internal sealed partial class WinMain : Form
_keyboardHook?.Dispose(); _keyboardHook?.Dispose();
} }
Win32.ChangeClipboardChain(Handle, _nextClipMonitor); // 从剪贴板监视链移除本窗体 _ = Win32.ChangeClipboardChain(Handle, _nextClipMonitor); // 从剪贴板监视链移除本窗体
_disposed = true; _disposed = true;
} }
@ -94,9 +94,6 @@ internal sealed partial class WinMain : Form
} }
} }
[GeneratedRegex("token: '(\\w+)'")]
private static partial Regex TokenRegex();
private void InitClipMonitor() private void InitClipMonitor()
{ {
_nextClipMonitor = Win32.SetClipboardViewer(Handle); _nextClipMonitor = Win32.SetClipboardViewer(Handle);
@ -104,12 +101,12 @@ internal sealed partial class WinMain : Form
private void InitForm() private void InitForm()
{ {
AutoSize = true; AutoSize = true;
AutoSizeMode = AutoSizeMode.GrowAndShrink; AutoSizeMode = AutoSizeMode.GrowAndShrink;
MaximumSize = Screen.FromHandle(Handle).Bounds.Size / 2; MaximumSize = Screen.FromHandle(Handle).Bounds.Size / 2;
FormBorderStyle = FormBorderStyle.None; FormBorderStyle = FormBorderStyle.None;
TopMost = true; TopMost = true;
Visible = false; Visible = false;
} }
private unsafe void InitHook() private unsafe void InitHook()
@ -121,27 +118,29 @@ internal sealed partial class WinMain : Form
}; };
_keyboardHook.KeyUpEvent += (_, e) => { _keyboardHook.KeyUpEvent += (_, e) => {
switch (e.vkCode) { switch (e.vkCode) {
case VkCode.VK_CAPITAL: { case VkCode.VK_CAPITAL:
var keyInputs = new Win32.InputStruct[4]; var keyInputs = new Win32.InputStruct[4];
keyInputs[0].type = Win32.INPUT_KEYBOARD; keyInputs[0].type = Win32.INPUT_KEYBOARD;
keyInputs[0].ki.wVk = VkCode.VK_CONTROL; keyInputs[0].ki.wVk = VkCode.VK_CONTROL;
keyInputs[1].type = Win32.INPUT_KEYBOARD; keyInputs[1].type = Win32.INPUT_KEYBOARD;
keyInputs[1].ki.wVk = VkCode.VK_C; keyInputs[1].ki.wVk = VkCode.VK_C;
keyInputs[2].type = Win32.INPUT_KEYBOARD; keyInputs[2].type = Win32.INPUT_KEYBOARD;
keyInputs[2].ki.wVk = VkCode.VK_C; keyInputs[2].ki.wVk = VkCode.VK_C;
keyInputs[2].ki.dwFlags = Win32.KEYEVENTF_KEYUP; keyInputs[2].ki.dwFlags = Win32.KEYEVENTF_KEYUP;
keyInputs[3].type = Win32.INPUT_KEYBOARD; keyInputs[3].type = Win32.INPUT_KEYBOARD;
keyInputs[3].ki.wVk = VkCode.VK_CONTROL; keyInputs[3].ki.wVk = VkCode.VK_CONTROL;
keyInputs[3].ki.dwFlags = Win32.KEYEVENTF_KEYUP; keyInputs[3].ki.dwFlags = Win32.KEYEVENTF_KEYUP;
#pragma warning disable IDE0058
Win32.SendInput((uint)keyInputs.Length, keyInputs, sizeof(Win32.InputStruct)); Win32.SendInput((uint)keyInputs.Length, keyInputs, sizeof(Win32.InputStruct));
#pragma warning restore IDE0058
_capsLockPressed = true; _capsLockPressed = true;
return true; return true;
}
case VkCode.VK_ESCAPE: case VkCode.VK_ESCAPE:
Hide(); Hide();
@ -158,15 +157,15 @@ internal sealed partial class WinMain : Form
{ {
_httpClient.DefaultRequestHeaders.Add( // _httpClient.DefaultRequestHeaders.Add( //
"User-Agent" "User-Agent"
, "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36"); , "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36");
} }
private void InitLabelDest() private void InitLabelDest()
{ {
_labelDest.Font = new Font(_labelDest.Font.FontFamily, 16); _labelDest.Font = new Font(_labelDest.Font.FontFamily, 16);
_labelDest.BorderStyle = BorderStyle.None; _labelDest.BorderStyle = BorderStyle.None;
_labelDest.Dock = DockStyle.Fill; _labelDest.Dock = DockStyle.Fill;
_labelDest.AutoSize = true; _labelDest.AutoSize = true;
Controls.Add(_labelDest); Controls.Add(_labelDest);
} }
@ -175,11 +174,10 @@ internal sealed partial class WinMain : Form
if (File.Exists(_stateFile)) { if (File.Exists(_stateFile)) {
var lines = File.ReadLines(_stateFile).ToArray(); var lines = File.ReadLines(_stateFile).ToArray();
_token = lines[0]; _token = lines[0];
_cookie = lines[1]; _httpClient.DefaultRequestHeaders.Add(nameof(Cookie), lines[1]);
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), _cookie);
} }
else { else {
Task.Run(UpdateStateFile); _ = Task.Run(UpdateStateFile);
} }
} }
@ -191,10 +189,10 @@ internal sealed partial class WinMain : Form
} }
_labelDest.Text = Ln.Translating; _labelDest.Text = Ln.Translating;
Task.Run(() => { _ = Task.Run(() => {
var translateText = TranslateText(clipText); var translateText = TranslateText(clipText);
ClipboardService.SetText(translateText); ClipboardService.SetText(translateText);
Invoke(() => { _labelDest.Text = translateText; }); _ = Invoke(() => _labelDest.Text = translateText);
}); });
var point = Cursor.Position; var point = Cursor.Position;
@ -209,17 +207,17 @@ internal sealed partial class WinMain : Form
var sign = BaiduSignCracker.Sign(sourceText); var sign = BaiduSignCracker.Sign(sourceText);
var content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> { var content = new FormUrlEncodedContent(new List<KeyValuePair<string, string>> {
new("from", "auto") new("from", "auto")
, new( // , new( //
"to" "to"
, CultureInfo.CurrentCulture.TwoLetterISOLanguageName) , CultureInfo.CurrentCulture.TwoLetterISOLanguageName)
, new("query", sourceText) , new("query", sourceText)
, new("simple_means_flag", "3") , new("simple_means_flag", "3")
, new("sign", sign) , new("sign", sign)
, new("token", _token) , new("token", _token)
, new("domain", "common") , new("domain", "common")
}); });
var rsp = _httpClient.PostAsync(_TRANSLATE_API_URL, content).Result; var rsp = _httpClient.PostAsync(_TRANSLATE_API_URL, content).Result;
var rspObj = rsp.Content.ReadAsStringAsync().Result.Object<BaiduTranslateResultDto.Root>(); var rspObj = rsp.Content.ReadAsStringAsync().Result.Object<BaiduTranslateResultDto.Root>();
if (rspObj.error == 0) { if (rspObj.error == 0) {
return string.Join(Environment.NewLine, rspObj.trans_result.data.Select(x => x.dst)); return string.Join(Environment.NewLine, rspObj.trans_result.data.Select(x => x.dst));
@ -236,15 +234,14 @@ internal sealed partial class WinMain : Form
private void UpdateStateFile() private void UpdateStateFile()
{ {
var rsp = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, _TRANSLATE_HOME_URL)).Result; var rsp = _httpClient.SendAsync(new HttpRequestMessage(HttpMethod.Head, _TRANSLATE_HOME_URL)).Result;
_cookie = string.Join( var cookie = string.Join(';', rsp.Headers.First(x => x.Key == "Set-Cookie").Value.Select(x => x.Split(';')[0]));
';', rsp.Headers.First(x => x.Key == "Set-Cookie").Value.Select(x => x.Split(';').First())); _ = _httpClient.DefaultRequestHeaders.Remove(nameof(Cookie));
_httpClient.DefaultRequestHeaders.Remove(nameof(Cookie)); _httpClient.DefaultRequestHeaders.Add(nameof(Cookie), cookie);
_httpClient.DefaultRequestHeaders.Add(nameof(Cookie), _cookie);
var html = _httpClient.GetStringAsync(_TRANSLATE_HOME_URL).Result; var html = _httpClient.GetStringAsync(_TRANSLATE_HOME_URL).Result;
_token = TokenRegex().Match(html).Groups[1].Value; _token = _tokenRegex.Match(html).Groups[1].Value;
File.WriteAllLines(_stateFile, new[] { _token, _cookie }); File.WriteAllLines(_stateFile, new[] { _token, cookie });
} }
} }
#endif #endif

View File

@ -8,7 +8,7 @@ namespace Dot.Trim;
[Localization(typeof(Ln))] [Localization(typeof(Ln))]
internal sealed class Main : FilesTool<Option> internal sealed class Main : FilesTool<Option>
{ {
protected override async ValueTask FileHandle(string file, CancellationToken cancelToken) protected override async ValueTask FileHandleAsync(string file, CancellationToken cancelToken)
{ {
ShowMessage(1, 0, 0); ShowMessage(1, 0, 0);
int spacesCnt; int spacesCnt;

View File

@ -11,9 +11,9 @@
<DefineConstants>$(DefineConstants);NET7_0_WINDOWS</DefineConstants> <DefineConstants>$(DefineConstants);NET7_0_WINDOWS</DefineConstants>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="NSExt" Version="1.0.11-alpha.0.1" /> <PackageReference Include="NSExt" Version="1.0.15-alpha.0.1" />
<PackageReference Include="Spectre.Console.Cli.NS" Version="0.45.1-preview.0.48" /> <PackageReference Include="Spectre.Console.Cli.NS" Version="0.45.1-preview.0.74" />
<PackageReference Include="Spectre.Console.NS" Version="0.45.1-preview.0.48" /> <PackageReference Include="Spectre.Console.NS" Version="0.45.1-preview.0.74" />
<PackageReference Condition="'$(TargetFramework)' == 'net7.0-windows'" Include="TextCopy" Version="6.2.1" /> <PackageReference Condition="'$(TargetFramework)' == 'net7.0-windows'" Include="TextCopy" Version="6.2.1" />
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>

View File

@ -1,9 +1,10 @@
{ {
"$schema": "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json", "$schema":
"settings": { "https://raw.githubusercontent.com/DotNetAnalyzers/StyleCopAnalyzers/master/StyleCop.Analyzers/StyleCop.Analyzers/Settings/stylecop.schema.json",
"indentation": { "settings": {
"useTabs": false, "indentation": {
"indentationSize": 4 "useTabs": false,
} "indentationSize": 4
} }
}
} }

View File

@ -1,2 +0,0 @@
@rem https://github.com/RicoSuter/DNT#switch-to-projects
dnt switch-to-packages

View File

@ -1,2 +0,0 @@
@rem https://github.com/RicoSuter/DNT#switch-to-projects
dnt switch-to-projects

View File

@ -1,8 +0,0 @@
{
"solution": "NetAdmin.sln",
"solutionFolder": null,
"mappings": {
"NSExt": "../../../../ForkedGitReps/ns-ext/src/NSExt.csproj"
},
"removeProjects": true
}

View File

@ -5,14 +5,14 @@
<RootNamespace>Dot.Tests</RootNamespace> <RootNamespace>Dot.Tests</RootNamespace>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0-preview-20221003-04" /> <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.6.1" />
<PackageReference Include="NUnit" Version="3.13.3" /> <PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="NUnit3TestAdapter" Version="4.3.1" /> <PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.5.0"> <PackageReference Include="NUnit.Analyzers" Version="3.6.1">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="coverlet.collector" Version="3.2.0"> <PackageReference Include="coverlet.collector" Version="6.0.0">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>