LaunchArgumentParser

This commit is contained in:
Timerix22 2023-02-03 20:46:01 +06:00
parent 702bc25dee
commit 66c53ef815
10 changed files with 178 additions and 27 deletions

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<!--package info--> <!--package info-->
<PackageId>DTLib.Dtsod</PackageId> <PackageId>DTLib.Dtsod</PackageId>
<Version>1.0.2</Version> <Version>1.0.3</Version>
<Authors>Timerix</Authors> <Authors>Timerix</Authors>
<Description>Definitely not json</Description> <Description>Definitely not json</Description>
<RepositoryType>GIT</RepositoryType> <RepositoryType>GIT</RepositoryType>
@ -33,7 +33,7 @@
<ProjectReference Include="..\DTLib\DTLib.csproj" /> <ProjectReference Include="..\DTLib\DTLib.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(Configuration)' != 'Debug' "> <ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
<PackageReference Include="DTLib" Version="1.0.1" /> <PackageReference Include="DTLib" Version="1.0.2" />
</ItemGroup> </ItemGroup>
<!--project files--> <!--project files-->

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<!--package info--> <!--package info-->
<PackageId>DTLib.Logging</PackageId> <PackageId>DTLib.Logging</PackageId>
<Version>1.0.6</Version> <Version>1.0.7</Version>
<Authors>Timerix</Authors> <Authors>Timerix</Authors>
<Description>Loggers with dependency injection</Description> <Description>Loggers with dependency injection</Description>
<RepositoryType>GIT</RepositoryType> <RepositoryType>GIT</RepositoryType>
@ -30,7 +30,7 @@
<ProjectReference Include="..\DTLib.Ben.Demystifier\DTLib.Ben.Demystifier.csproj" /> <ProjectReference Include="..\DTLib.Ben.Demystifier\DTLib.Ben.Demystifier.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(Configuration)' != 'Debug' "> <ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
<PackageReference Include="DTLib" Version="1.0.1" /> <PackageReference Include="DTLib" Version="1.0.2" />
<PackageReference Include="DTLib.Ben.Demystifier" Version="1.0.2" /> <PackageReference Include="DTLib.Ben.Demystifier" Version="1.0.2" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -2,7 +2,7 @@
<PropertyGroup> <PropertyGroup>
<!--package info--> <!--package info-->
<PackageId>DTLib.Network</PackageId> <PackageId>DTLib.Network</PackageId>
<Version>1.0.2</Version> <Version>1.0.3</Version>
<Authors>Timerix</Authors> <Authors>Timerix</Authors>
<Description>Some sick network protocols</Description> <Description>Some sick network protocols</Description>
<RepositoryType>GIT</RepositoryType> <RepositoryType>GIT</RepositoryType>
@ -32,6 +32,6 @@
<ProjectReference Include="..\DTLib.Dtsod\DTLib.Dtsod.csproj" /> <ProjectReference Include="..\DTLib.Dtsod\DTLib.Dtsod.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(Configuration)' != 'Debug' "> <ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
<PackageReference Include="DTLib.Dtsod" Version="1.0.2" /> <PackageReference Include="DTLib.Dtsod" Version="1.0.3" />
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -27,14 +27,12 @@
<ProjectReference Include="..\DTLib\DTLib.csproj" /> <ProjectReference Include="..\DTLib\DTLib.csproj" />
</ItemGroup> </ItemGroup>
<ItemGroup Condition=" '$(Configuration)' != 'Debug' "> <ItemGroup Condition=" '$(Configuration)' != 'Debug' ">
<PackageReference Include="DTLib.Network" Version="1.0.2" /> <PackageReference Include="DTLib.Network" Version="1.0.3" />
<PackageReference Include="DTLib.Logging" Version="1.0.7" />
</ItemGroup> </ItemGroup>
<!--project files--> <!--project files-->
<ItemGroup> <ItemGroup>
<None Update="Dtsod\TestResources\**\*" CopyToOutputDirectory="PreserveNewest" /> <None Update="Dtsod\TestResources\**\*" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup> </ItemGroup>
<ItemGroup>
<PackageReference Include="DTLib.Logging" Version="1.0.6" />
</ItemGroup>
</Project> </Project>

View File

@ -1,4 +1,4 @@
namespace DTLib; namespace DTLib.Console;
// //
// вывод и ввод цветного текста в консоли // вывод и ввод цветного текста в консоли
@ -32,9 +32,9 @@ public static class ColoredConsole
public static void Write(ConsoleColor color,string msg) public static void Write(ConsoleColor color,string msg)
{ {
Console.ForegroundColor = color; System.Console.ForegroundColor = color;
Console.Write(msg); System.Console.Write(msg);
Console.ForegroundColor = ConsoleColor.Gray; System.Console.ForegroundColor = ConsoleColor.Gray;
} }
public static void Write(string msg) => Write(ConsoleColor.Gray, msg); public static void Write(string msg) => Write(ConsoleColor.Gray, msg);
@ -53,18 +53,18 @@ public static class ColoredConsole
for (ushort i = 0; i < input.Length; i++) for (ushort i = 0; i < input.Length; i++)
{ {
Console.ForegroundColor = ParseColor(input[i++]); System.Console.ForegroundColor = ParseColor(input[i++]);
Console.Write(input[i]); System.Console.Write(input[i]);
} }
Console.ForegroundColor = ConsoleColor.Gray; System.Console.ForegroundColor = ConsoleColor.Gray;
} }
public static void WriteLine() => Console.WriteLine(); public static void WriteLine() => System.Console.WriteLine();
public static void WriteLine(ConsoleColor color,string msg) public static void WriteLine(ConsoleColor color,string msg)
{ {
Console.ForegroundColor = color; System.Console.ForegroundColor = color;
Console.WriteLine(msg); System.Console.WriteLine(msg);
Console.ForegroundColor = ConsoleColor.Gray; System.Console.ForegroundColor = ConsoleColor.Gray;
} }
public static void WriteLine(params string[] input) public static void WriteLine(params string[] input)
@ -76,9 +76,9 @@ public static class ColoredConsole
// ввод цветного текста // ввод цветного текста
public static string Read(ConsoleColor color) public static string Read(ConsoleColor color)
{ {
Console.ForegroundColor = color; System.Console.ForegroundColor = color;
var r = Console.ReadLine(); var r = System.Console.ReadLine();
Console.ForegroundColor = ConsoleColor.Gray; System.Console.ForegroundColor = ConsoleColor.Gray;
return r; return r;
} }

View File

@ -0,0 +1,41 @@
namespace DTLib.Console;
#nullable enable
public class LaunchArgument
{
public string[] Aliases;
public string Description;
public string? ParamName;
public Action? Handler;
public Action<string>? HandlerWithArg;
private LaunchArgument(string[] aliases, string description)
{
Aliases = aliases;
Description = description;
}
public LaunchArgument(string[] aliases, string description, Action handler)
: this(aliases, description) => Handler = handler;
public LaunchArgument(string[] aliases, string description, Action<string> handler, string paramName)
: this(aliases, description)
{
HandlerWithArg = handler;
ParamName = paramName;
}
public StringBuilder AppendHelpInfo(StringBuilder b)
{
b.Append(Aliases[0]);
for (int i = 1; i < Aliases.Length; i++)
b.Append(", ").Append(Aliases[i]);
if (!String.IsNullOrEmpty(ParamName))
b.Append(" [").Append(ParamName).Append(']');
b.Append(" - ").Append(Description);
return b;
}
public override string ToString() =>
$"{{{{{Aliases.MergeToString(", ")}}}, Handler: {Handler is null}, HandlerWithArg: {HandlerWithArg is null}}}";
}

View File

@ -0,0 +1,110 @@
namespace DTLib.Console;
public class LaunchArgumentParser
{
private Dictionary<string, LaunchArgument> argDict = new();
private List<LaunchArgument> argList = new();
public bool ExitIfNoArgs = true;
public class ExitAfterHelpException : Exception
{
internal ExitAfterHelpException() : base("your program can use this exception to exit after displaying help message")
{ }
}
public string CreateHelpMessage()
{
StringBuilder b = new();
foreach (var arg in argList)
arg.AppendHelpInfo(b).Append('\n');
b.Remove(b.Length-1, 1);
return b.ToString();
}
public string CreateHelpArgMessage(string argAlias)
{
StringBuilder b = new();
var arg = Get(argAlias);
arg.AppendHelpInfo(b);
return b.ToString();
}
private void HelpHandler()
{
System.Console.WriteLine(CreateHelpMessage());
throw new ExitAfterHelpException();
}
private void HelpArgHandler(string argAlias)
{
System.Console.WriteLine(CreateHelpArgMessage(argAlias));
throw new ExitAfterHelpException();
}
public LaunchArgumentParser()
{
var help = new LaunchArgument(new[] { "h", "help" },
"shows help message", HelpHandler);
Add(help);
var helpArg = new LaunchArgument( new[]{ "ha", "helparg" },
"shows help message for particular argument",
HelpArgHandler, "argAlias");
Add(helpArg);
}
public LaunchArgumentParser(ICollection<LaunchArgument> arguments) : this()
{
foreach (var arg in arguments)
Add(arg);
}
public LaunchArgumentParser(params LaunchArgument[] arguments) : this()
{
for (var i = 0; i < arguments.Length; i++)
Add(arguments[i]);
}
public void Add(LaunchArgument arg)
{
argList.Add(arg);
for(int a=0; a<arg.Aliases.Length; a++)
argDict.Add(arg.Aliases[a], arg);
}
public LaunchArgument Get(string argAlias)
{
// different argument providing patterns
if (!argDict.TryGetValue(argAlias, out var arg) && // arg
!(argAlias.StartsWith("--") && argDict.TryGetValue(argAlias.Substring(2), out arg)) && // --arg
!(argAlias.StartsWith('-') && argDict.TryGetValue(argAlias.Substring(1), out arg)) && // -arg
!(argAlias.StartsWith('/') && argDict.TryGetValue(argAlias.Substring(1), out arg))) // /arg
throw new Exception($"invalid argument: {argAlias}\n{CreateHelpMessage()}");
return arg;
}
/// <param name="args">program launch args</param>
/// <exception cref="Exception">argument {args[i]} should have a parameter after it</exception>
/// <exception cref="NullReferenceException">argument hasn't got any handlers</exception>
/// <exception cref="ExitAfterHelpException">happens after help message is displayed</exception>
public void ParseAndHandle(string[] args)
{
if (args.Length == 0 && ExitIfNoArgs)
{
HelpHandler();
}
for (int i = 0; i < args.Length; i++)
{
LaunchArgument arg = Get(args[i]);
if (arg.HandlerWithArg is not null)
{
if (i+1 >= args.Length)
throw new Exception($"argument <{args[i]}> should have a parameter after it");
arg.HandlerWithArg(args[++i]);
}
else if (arg.Handler is not null)
arg.Handler();
else throw new NullReferenceException($"argument <{args[i]}> hasn't got any handlers");
}
}
}

View File

@ -1,5 +1,4 @@
using System.Runtime.InteropServices; using System.Runtime.InteropServices;
using System.Threading;
namespace DTLib; namespace DTLib;

View File

@ -1,4 +1,6 @@
namespace DTLib.Logging; using DTLib.Console;
namespace DTLib.Logging;
// вывод лога в консоль и файл // вывод лога в консоль и файл
public class ConsoleLogger : FileLogger public class ConsoleLogger : FileLogger
@ -23,7 +25,7 @@ public class ConsoleLogger : FileLogger
lock (consolelocker) lock (consolelocker)
{ {
ColoredConsole.Write(msg); ColoredConsole.Write(msg);
Console.WriteLine(); System.Console.WriteLine();
} }
} }
} }

View File

@ -1,6 +1,7 @@
#!/usr/bin/bash #!/usr/bin/bash
set -ex set -ex
rm -rf nuget rm -rf nuget
mkdir nuget
dotnet pack -c Release -o ./nuget/ dotnet pack -c Release -o ./nuget/
rm ./nuget/DTLib.Tests.* rm ./nuget/DTLib.Tests.*
ls nuget ls nuget