Skip to content

Commit

Permalink
feat: upgrade System.CommandLine
Browse files Browse the repository at this point in the history
  • Loading branch information
tautcony committed Dec 22, 2023
1 parent 8f5ed59 commit 32694e9
Show file tree
Hide file tree
Showing 3 changed files with 151 additions and 167 deletions.
7 changes: 4 additions & 3 deletions OKP.Core/OKP.Core.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<PublishSingleFile>true</PublishSingleFile>
<PublishAot>true</PublishAot>
<Version>1.0.2-beta</Version>
<Copyright>Copyright (C) 2023 AmusementClub
Released under the GNU GPLv3+.
Expand All @@ -18,8 +18,9 @@ Released under the GNU GPLv3+.
<PackageReference Include="Serilog" Version="3.1.1" />
<PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" />
<PackageReference Include="Serilog.Sinks.File" Version="5.0.0" />
<PackageReference Include="Spectre.Console" Version="0.48.0" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.22272.1" />
<PackageReference Include="System.CommandLine" Version="2.0.0-beta4.23407.1" />
<PackageReference Include="System.CommandLine.Generator" Version="2.0.0-beta4.23307.1" />
<PackageReference Include="System.CommandLine.NamingConventionBinder" Version="2.0.0-beta4.23407.1" />
<PackageReference Include="Tomlyn" Version="0.17.0" />
</ItemGroup>

Expand Down
305 changes: 141 additions & 164 deletions OKP.Core/Program.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
using System.CommandLine;
using System.CommandLine.Builder;
using System.CommandLine.Help;
using System.CommandLine.Parsing;
using OKP.Core.Interface;
using OKP.Core.Interface.Acgnx;
using OKP.Core.Interface.Acgrip;
Expand All @@ -12,7 +9,6 @@
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Spectre.Console;
using Constants = OKP.Core.Utils.Constants;

namespace OKP.Core
Expand All @@ -22,49 +18,46 @@ internal class Program
{
public static void Main(string[] args)
{
var torrentArgument = new Argument<IEnumerable<string>?>(
name: "torrent",
description: "Torrents to be published. (Or Cookie file exported by Get Cookies.txt.)"
);
var torrentArgument = new CliArgument<IEnumerable<string>?>("torrent")
{
Description = "Torrents to be published. (Or Cookie file exported by Get Cookies.txt.)"
};

var cookiesOption = new Option<string?>(
name: "--cookies",
getDefaultValue: () => null,
description: "Cookie file to be used."
);
var cookiesOption = new CliOption<string?>("--cookies")
{
DefaultValueFactory = _ => null,
Description = "Cookie file to be used."
};

var settingOption = new Option<string>(
name: "--setting",
getDefaultValue: () => Constants.DefaultSettingFileName,
description: "(Not required) Specific setting file."
);
settingOption.AddAlias("-s");
var settingOption = new CliOption<string>("--setting", "-s")
{
DefaultValueFactory = _ => Constants.DefaultSettingFileName,
Description = "(Not required) Specific setting file."
};

var logLevelOption = new Option<string?>(
name: "--log_level",
getDefaultValue: () => "Debug",
description: "Log level."
);
logLevelOption.AddAlias("-l");
var logLevelOption = new CliOption<string>("--log_level", "-l")
{
DefaultValueFactory = _ => "Debug",
Description = "Log level."
};

var logFileOption = new Option<string>(
name: "--log_file",
getDefaultValue: () => Constants.DefaultLogFileName,
description: "Log file."
);
var logFileOption = new CliOption<string>("--log_file")
{
DefaultValueFactory = _ => Constants.DefaultLogFileName,
Description = "Log file."
};

var noReactionOption = new Option<bool>(
name: "--no_reaction",
description: "Skip reaction."
);
noReactionOption.AddAlias("-y");
var noReactionOption = new CliOption<bool>("--no_reaction", "-y")
{
Description = "Skip reaction."
};

var allowSkipOption = new Option<bool>(
name: "--allow_skip",
description: "Ignore login fail and continue publishing."
);
var allowSkipOption = new CliOption<bool>("--allow_skip")
{
Description = "Ignore login fail and continue publishing."
};

var rootCommand = new RootCommand("One Key Publish")
var rootCommand = new CliRootCommand("One Key Publish")
{
torrentArgument,
cookiesOption,
Expand All @@ -75,145 +68,129 @@ public static void Main(string[] args)
allowSkipOption,
};

rootCommand.SetHandler((
torrentFile,
cookies,
settingFile,
logLevel,
logFile,
noReaction,
allowSkip) =>
rootCommand.SetAction((result, _) =>
{
var torrentFile = result.GetValue(torrentArgument);
var cookies = result.GetValue(cookiesOption);
var settingFile = result.GetValue(settingOption);
var logLevel = result.GetValue(logLevelOption);
var logFile = result.GetValue(logFileOption);
var noReaction = result.GetValue(noReactionOption);
var allowSkip = result.GetValue(allowSkipOption);

ActionHandler(torrentFile, cookies , settingFile, logLevel, logFile, noReaction, allowSkip);

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, win-x64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, win-arm64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, linux-x64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, linux-arm64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, osx-x64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.

Check warning on line 81 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, osx-arm64)

Possible null reference argument for parameter 'logFile' in 'void Program.ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)'.
return Task.CompletedTask;
});

rootCommand.Parse(args).Invoke();
IOHelper.ReadLine();
}

private static void ActionHandler(IEnumerable<string>? torrentFile, string? cookies, string? settingFile, string? logLevel, string logFile, bool noReaction, bool allowSkip)
{
var levelSwitch = new LoggingLevelSwitch
{
MinimumLevel = logLevel?.ToLower() switch
{
var levelSwitch = new LoggingLevelSwitch
{
MinimumLevel = logLevel?.ToLower() switch
{
"verbose" => LogEventLevel.Verbose,
"debug" => LogEventLevel.Debug,
"info" => LogEventLevel.Information,
_ => LogEventLevel.Debug
}
};
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.Console()
.WriteTo.File(logFile,
rollingInterval: RollingInterval.Month,
rollOnFileSizeLimit: true)
.CreateLogger();
IOHelper.NoReaction = noReaction;
if (torrentFile is null)
{
Log.Fatal("o.TorrentFile is null");
return;
}
var addCookieCount = 0;
foreach (var file in torrentFile)
{
if (!File.Exists(file))
{
Log.Error("文件{File}不存在", file);
continue;
}
var extension = (Path.GetExtension(file) ?? "").ToLower();
"verbose" => LogEventLevel.Verbose,
"debug" => LogEventLevel.Debug,
"info" => LogEventLevel.Information,
_ => LogEventLevel.Debug
}
};
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.Console()
.WriteTo.File(logFile,
rollingInterval: RollingInterval.Month,
rollOnFileSizeLimit: true)
.CreateLogger();
IOHelper.NoReaction = noReaction;
if (torrentFile is null)
{
Log.Fatal("o.TorrentFile is null");
return;
}
var addCookieCount = 0;
foreach (var file in torrentFile)
{
if (!File.Exists(file))
{
Log.Error("文件{File}不存在", file);
continue;
}
var extension = (Path.GetExtension(file) ?? "").ToLower();

if (extension == ".torrent")
if (extension == ".torrent")
{
Log.Information("正在发布 {File}", file);
SinglePublish(file, settingFile, cookies, allowSkip);

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, win-x64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, win-arm64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, linux-x64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, linux-arm64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, osx-x64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.

Check warning on line 127 in OKP.Core/Program.cs

View workflow job for this annotation

GitHub Actions / build (Release, osx-arm64)

Possible null reference argument for parameter 'settingFile' in 'void Program.SinglePublish(string file, string settingFile, string? cookies, bool allowSkip)'.
continue;
}
if (extension == ".txt")
{
if (cookies is null)
{
Log.Information("请输入Cookie文件名,不需要包含扩展名,相对目录默认为{DefaultPath}",
IOHelper.BasePath(Constants.DefaultCookiePath));
IOHelper.HintText(Constants.DefaultCookieFile);
var filename = IOHelper.ReadLine();
if (File.Exists(filename))
{
Log.Information("正在发布 {File}", file);
SinglePublish(file, settingFile, cookies, allowSkip);
continue;
cookies = filename;
Log.Error("你指定的Cookie文件{File}已经存在!继续添加可能会覆盖之前保存的Cookie!", cookies);
IOHelper.ReadLine();
HttpHelper.GlobalCookieContainer.LoadFromTxt(cookies);
}
if (extension == ".txt")
else
{
if (cookies is null)
if (!Directory.Exists(IOHelper.BasePath(Constants.DefaultCookiePath)))
{
Log.Information("请输入Cookie文件名,不需要包含扩展名,相对目录默认为{DefaultPath}",
IOHelper.BasePath(Constants.DefaultCookiePath));
IOHelper.HintText(Constants.DefaultCookieFile);
var filename = IOHelper.ReadLine();
if (File.Exists(filename))
{
cookies = filename;
Log.Error("你指定的Cookie文件{File}已经存在!继续添加可能会覆盖之前保存的Cookie!", cookies);
IOHelper.ReadLine();
HttpHelper.GlobalCookieContainer.LoadFromTxt(cookies);
}
else
{
if (!Directory.Exists(IOHelper.BasePath(Constants.DefaultCookiePath)))
{
Directory.CreateDirectory(IOHelper.BasePath(Constants.DefaultCookiePath));
}
cookies = IOHelper.BasePath(Constants.DefaultCookiePath,
(filename?.Length == 0 ? Constants.DefaultCookieFile : filename) + ".txt");
if (File.Exists(cookies))
{
Log.Error("你指定的Cookie文件{File}已经存在!继续添加可能会覆盖之前保存的Cookie!", cookies);
IOHelper.ReadLine();
HttpHelper.GlobalCookieContainer.LoadFromTxt(cookies);
}
}
Log.Information("请输入你使用的浏览器UserAgent:");
var ua = IOHelper.ReadLine();
while (ua is null || !HttpHelper.UaRegex.IsMatch(ua))
{
Log.Information("你必须输入一个合法的UserAgent以确保你的cookie可以正常使用:");
ua = IOHelper.ReadLine();
}
HttpHelper.GlobalUserAgent = ua;
Directory.CreateDirectory(IOHelper.BasePath(Constants.DefaultCookiePath));
}
if (File.Exists(IOHelper.BasePath(Constants.DefaultCookiePath,
Constants.DefaultCookieFile + ".txt")))
cookies = IOHelper.BasePath(Constants.DefaultCookiePath,
(filename?.Length == 0 ? Constants.DefaultCookieFile : filename) + ".txt");
if (File.Exists(cookies))
{
HttpHelper.GlobalCookieContainer.LoadFromTxt(IOHelper.BasePath(Constants.DefaultCookiePath,
Constants.DefaultCookieFile + ".txt"));
Log.Error("你指定的Cookie文件{File}已经存在!继续添加可能会覆盖之前保存的Cookie!", cookies);
IOHelper.ReadLine();
HttpHelper.GlobalCookieContainer.LoadFromTxt(cookies);
}
Log.Information("正在添加Cookie文件{File}", file);
AddCookies(file);
addCookieCount++;
Log.Information("Cookie文件{File}添加完成,按回车键继续添加", file);
IOHelper.ReadLine();
}
else
Log.Information("请输入你使用的浏览器UserAgent:");
var ua = IOHelper.ReadLine();
while (ua is null || !HttpHelper.UaRegex.IsMatch(ua))
{
Log.Error("不受支持的文件格式{File}", file);
}
if (cookies is not null)
{
Log.Information("共输入了{Count}个Cookie文件", addCookieCount);
HttpHelper.GlobalCookieContainer.SaveToTxt(cookies, HttpHelper.GlobalUserAgent);
Log.Information("保存成功,Cookie文件保存在{Path}", cookies);
Log.Information("你必须输入一个合法的UserAgent以确保你的cookie可以正常使用:");
ua = IOHelper.ReadLine();
}
HttpHelper.GlobalUserAgent = ua;
}
},
torrentArgument,
cookiesOption,
settingOption,
logLevelOption,
logFileOption,
noReactionOption,
allowSkipOption);

var parser = new CommandLineBuilder(rootCommand)
.UseDefaults()
.UseHelp(ctx =>
if (File.Exists(IOHelper.BasePath(Constants.DefaultCookiePath,
Constants.DefaultCookieFile + ".txt")))
{
HttpHelper.GlobalCookieContainer.LoadFromTxt(IOHelper.BasePath(Constants.DefaultCookiePath,
Constants.DefaultCookieFile + ".txt"));
}
Log.Information("正在添加Cookie文件{File}", file);
AddCookies(file);
addCookieCount++;
Log.Information("Cookie文件{File}添加完成,按回车键继续添加", file);
IOHelper.ReadLine();
}
else
{
ctx.HelpBuilder.CustomizeLayout(
_ =>
HelpBuilder.Default
.GetLayout()
.Skip(1) // Skip the default command description section.
.Prepend(hc => hc.Output.Write("Copyright (C) 2023 AmusementClub\nReleased under the GNU GPLv3+.\n"))
.Prepend(
_ => AnsiConsole.Write(
new FigletText(rootCommand.Description!))
));
})
.Build();

parser.Invoke(args);
IOHelper.ReadLine();
Log.Error("不受支持的文件格式{File}", file);
}
if (cookies is not null)
{
Log.Information("共输入了{Count}个Cookie文件", addCookieCount);
HttpHelper.GlobalCookieContainer.SaveToTxt(cookies, HttpHelper.GlobalUserAgent);
Log.Information("保存成功,Cookie文件保存在{Path}", cookies);
}
}
}

private static void SinglePublish(string file, string settingFile, string? cookies,bool allowSkip)
{
if (!File.Exists(file))
Expand Down
6 changes: 6 additions & 0 deletions nuget.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="dotnet-libraries" value="https://pkgs.dev.azure.com/dnceng/public/_packaging/dotnet-libraries/nuget/v3/index.json" />
</packageSources>
</configuration>

0 comments on commit 32694e9

Please sign in to comment.