Skip to content

Commit

Permalink
generate help for intellisense
Browse files Browse the repository at this point in the history
  • Loading branch information
neuecc committed Jun 1, 2024
1 parent 40e31b5 commit 2699a15
Show file tree
Hide file tree
Showing 5 changed files with 91 additions and 17 deletions.
19 changes: 12 additions & 7 deletions sandbox/GeneratorSandbox/Filters.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

Expand Down Expand Up @@ -59,17 +60,21 @@ public override async Task InvokeAsync(ConsoleAppContext context, CancellationTo
}
}

internal class MutexFilter(ConsoleAppFilter next) : ConsoleAppFilter(next)
internal class PreventMultipleInstanceFilter(ConsoleAppFilter next) : ConsoleAppFilter(next)
{
public override async Task InvokeAsync(ConsoleAppContext context, CancellationToken cancellationToken)
{
// var name = context.MethodInfo.DeclaringType.Name + "." + context.MethodInfo.Name;
// using (var mutex = new Mutex(true, name, out var createdNew)) ;
// allow another command
// prevent: location + command
var basePath = Assembly.GetEntryAssembly()?.Location.Replace(Path.DirectorySeparatorChar, '_');

//if (!createdNew)
//{
// throw new Exception($"already running {name} in another process.");
//}
var mutexKey = $"{basePath}$$${context.CommandName}";

using var mutex = new Mutex(true, mutexKey, out var createdNew);
if (!createdNew)
{
throw new Exception($"already running command:{context.CommandName} in another process.");
}

await Next.InvokeAsync(context, cancellationToken);
}
Expand Down
53 changes: 49 additions & 4 deletions sandbox/GeneratorSandbox/Program.cs
Original file line number Diff line number Diff line change
@@ -1,22 +1,67 @@
using ConsoleAppFramework;
using GeneratorSandbox;
using System.ComponentModel.DataAnnotations;

var serviceCollection = new MiniDI();
serviceCollection.Register(typeof(string), "hoge!");
serviceCollection.Register(typeof(int), 9999);
ConsoleApp.ServiceProvider = serviceCollection;

var builder = ConsoleApp.Create();

builder.UseFilter<DIFilter>();

builder.Add("", (ConsoleAppContext ctx) => Console.Write("do"));
// ConsoleApp.Run(args, (int x, int y) => { });
////
//args = ["foo-bar-baz"];

builder.Run(args);
////args = ["foo-bar-baz", "-h"];

//var builder = ConsoleApp.Create();

////builder.UseFilter<PreventMultipleInstanceFilter>();




//builder.Add<MyCommand>();

//builder.


public class MyCommand
{

/// <summary>
/// <para>You can pass second argument that generates new Run overload.</para>
/// ConsoleApp.Run(args, (int x, int y) => { });<br/>
/// ConsoleApp.Run(args, Foo);<br/>
/// ConsoleApp.Run(args, &amp;Foo);<br/>
/// </summary>
public void Dispose()
{
throw new NotImplementedException();
}

public void FooBarBaz(int hogeMogeHugahuga)
{
Console.WriteLine(hogeMogeHugahuga);
}

public override int GetHashCode()
{
return base.GetHashCode();
}

public override bool Equals(object? obj)
{
return base.Equals(obj);
}

public override string? ToString()
{
return base.ToString();
}
}

internal class DIFilter(string foo, int bar, ConsoleAppFilter next)
: ConsoleAppFilter(next)
{
Expand Down
20 changes: 16 additions & 4 deletions src/ConsoleAppFramework/ConsoleAppGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -150,10 +150,22 @@ public static Action<string> LogError
set => logErrorAction = value;
}

/// <summary>
/// <para>You can pass second argument that generates new Run overload.</para>
/// ConsoleApp.Run(args, (int x, int y) => { });<br/>
/// ConsoleApp.Run(args, Foo);<br/>
/// ConsoleApp.Run(args, &amp;Foo);<br/>
/// </summary>
public static void Run(string[] args)
{
}

/// <summary>
/// <para>You can pass second argument that generates new RunAsync overload.</para>
/// ConsoleApp.RunAsync(args, (int x, int y) => { });<br/>
/// ConsoleApp.RunAsync(args, Foo);<br/>
/// ConsoleApp.RunAsync(args, &amp;Foo);<br/>
/// </summary>
public static Task RunAsync(string[] args)
{
return Task.CompletedTask;
Expand Down Expand Up @@ -264,11 +276,11 @@ static void ValidateParameter(object? value, ParameterInfo parameter, Validation
}

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool TryShowHelpOrVersion(ReadOnlySpan<string> args, int parameterCount, int helpId)
static bool TryShowHelpOrVersion(ReadOnlySpan<string> args, int requiredParameterCount, int helpId)
{
if (args.Length == 0)
{
if (parameterCount == 0) return false;
if (requiredParameterCount == 0) return false;

ShowHelp(helpId);
return true;
Expand Down Expand Up @@ -446,11 +458,11 @@ public Task RunAsync(string[] args)
static partial void ShowHelp(int helpId);

[MethodImpl(MethodImplOptions.AggressiveInlining)]
static bool TryShowHelpOrVersion(ReadOnlySpan<string> args, int parameterCount, int helpId)
static bool TryShowHelpOrVersion(ReadOnlySpan<string> args, int requiredParameterCount, int helpId)
{
if (args.Length == 0)
{
if (parameterCount == 0) return false;
if (requiredParameterCount == 0) return false;

ShowHelp(helpId);
return true;
Expand Down
14 changes: 13 additions & 1 deletion src/ConsoleAppFramework/Emitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public void EmitRun(SourceBuilder sb, CommandWithId commandWithId, bool isRunAsy
var hasArgument = command.Parameters.Any(x => x.IsArgument);
var hasValidation = command.Parameters.Any(x => x.HasValidation);
var parsableParameterCount = command.Parameters.Count(x => x.IsParsable);
var requiredParsableParameterCount = command.Parameters.Count(x => x.IsParsable && x.RequireCheckArgumentParsed);

if (command.HasFilter)
{
Expand Down Expand Up @@ -44,10 +45,21 @@ public void EmitRun(SourceBuilder sb, CommandWithId commandWithId, bool isRunAsy
var filterCancellationToken = command.HasFilter ? ", ConsoleAppContext context, CancellationToken cancellationToken" : "";
var rawArgs = !emitForBuilder ? "" : "string[] rawArgs, ";

if (!emitForBuilder)
{
sb.AppendLine("/// <summary>");
var help = CommandHelpBuilder.BuildCommandHelpMessage(commandWithId.Command);
foreach (var line in help.Split([Environment.NewLine], StringSplitOptions.None))
{
sb.AppendLine($"/// {line.Replace("<", "&lt;").Replace(">", "&gt;")}<br/>");
}
sb.AppendLine("/// </summary>");
}

// method signature
using (sb.BeginBlock($"{accessibility} static {unsafeCode}{returnType} {methodName}({rawArgs}{argsType} args{commandMethodType}{filterCancellationToken})"))
{
sb.AppendLine($"if (TryShowHelpOrVersion(args, {parsableParameterCount}, {commandWithId.Id})) return;");
sb.AppendLine($"if (TryShowHelpOrVersion(args, {requiredParsableParameterCount}, {commandWithId.Id})) return;");
sb.AppendLine();

// prepare argument variables
Expand Down
2 changes: 1 addition & 1 deletion src/ConsoleAppFramework/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ internal class Parser(SourceProductionContext context, InvocationExpressionSynta
.OfType<IMethodSymbol>()
.Where(x => x.DeclaredAccessibility == Accessibility.Public && !x.IsStatic)
.Where(x => x.MethodKind == Microsoft.CodeAnalysis.MethodKind.Ordinary)
.Where(x => !(x.Name is "Dispose" or "DisposeAsync"))
.Where(x => !(x.Name is "Dispose" or "DisposeAsync" or "GetHashCode" or "Equals" or "ToString"))
.ToArray();

var publicConstructors = type.GetMembers()
Expand Down

0 comments on commit 2699a15

Please sign in to comment.