question(s): creating sub-commands on runtime; command.Invoke() row in the code
Hi,
- I have already defined couple of classes similar in Subcommands sample. (I use the inheritance).
Now, I wonder, whether it is possible to add a code in one of that already defined Sub-commands class, which will create inner sub-comands programmatically. (I face to a list of sub-comands definition, which comes from an external service, which could continuously grow, I would like to map that metadata to generate the CommandLineUtils sub-command structure on the fly). From other point of view - is it possible to combine the attribute SubCommand with a code for defining of sub-commands?
- it might relate to 1) I am not so sure though, - I little investigated the source code, I wonder about the place command.Invoke(); in Bind(IConsole console, string[] args) method of the ReflectionAppBuilder
class. What is the purpose of calling it? It sounds to me the command has already been processed at that time, while it is going to be is invoked further in the case of being matched as the target command. Could you, please, give me a little code snippet example, how to inject a code from such a command class to be invoked at that "command.Invoke()" time?
TIA, Mojmir
is it possible to combine the attribute SubCommand with a code for defining of sub-commands?
- At the moment, dynamically generating subcommands is only possible using the builder API. For example, you could do this.
class Program
{
public static int Main(string[] args)
{
var app = new CommandLineApplication
{
Name = "my-app",
};
var verbs = ExternalService.GetSubcommands();
foreach (var verb in verbs)
{
app.Command(verb.Name, subcmd =>
{
foreach (var option in verb.Options)
{
subcmd.Option(option.Template, option.Description, option.Type);
}
}
}
return app.Execute(args);
}
}
- Short answer: you should define a method named
OnExecuteon your subcommand types.
Samples https://github.com/natemcmaster/CommandLineUtils/blob/c2499313f4cd64cfba20059528f54f6d87c728b3/samples/HelloWorld.Attributes/Program.cs#L16-L20 https://github.com/natemcmaster/CommandLineUtils/blob/c2499313f4cd64cfba20059528f54f6d87c728b3/samples/Subcommands/Inheritance.cs#L24-L29
Long answer:
ReflectionAppBuilder calls command.Invoke() as an internal implementation detail. When it does, this is the method that is invoked:
https://github.com/natemcmaster/CommandLineUtils/blob/c2499313f4cd64cfba20059528f54f6d87c728b3/src/CommandLineUtils/Internal/ReflectionAppBuilder.cs#L381-L393
ReflectionAppBuilder builds up a list of "binders" that parse command-line arguments into CLR properties, as discovered via reflection. For example, the binder that takes --some-value and converts it to [Option] public bool SomeValue { get; } is defined here.
https://github.com/natemcmaster/CommandLineUtils/blob/c2499313f4cd64cfba20059528f54f6d87c728b3/src/CommandLineUtils/Internal/ReflectionAppBuilder.cs#L318-L321
This doesn't actually invoke any user code at this point. This comes later after the binding is done. After binding, the target subcommand type is examined for a method named OnExecute or OnExecuteAsync, and this is invoked.
https://github.com/natemcmaster/CommandLineUtils/blob/master/src/CommandLineUtils/CommandLineApplication.Execute.cs#L59-L68
(first, please, excuse me for not so good English - I have revised it 3rd time - hopefully now it is better to understand)
- understood, anyway thanks for the code sample - that can help me
- I somehow didn't noticed the ComandLineApplication's OnExecute method is called by the ReflectionAppBuilder's method. And that lead me in to confusions like "Why there was that call of command.Invoke() and surprisingly to me it did't call the user code, which of course would be bad at that time, because calling the user code is made further and only for the targeted command (as you mentioned above).
(for some detail, I think it is needed to mention the OnExecute a "helper-setter" of the ComandLineApplication's Invoke property. https://github.com/natemcmaster/CommandLineUtils/blob/c780b6cb1360e9e1bc4061c4bb7493cfdebf3ac1/src/CommandLineUtils/CommandLineApplication.cs#L355-L370
Now I can see, there is some kind of dynamics behind the ComandLineApplication's Invoke property, which I might not understand completely yet. At least, I can see through debug, that it is initialized to ()=>0 in the ComandLineApplication's ctor. and then set to the ReflectionAppBuilder's OnExecute method (you described above) https://github.com/natemcmaster/CommandLineUtils/blob/c780b6cb1360e9e1bc4061c4bb7493cfdebf3ac1/src/CommandLineUtils/Internal/ReflectionAppBuilder.cs#L39-L42
I guess the Invoke properties of all the commands are not changed further. (I think it is would be also good to remind, we are talking about scenario with sub-commands and attributed API)
Do I understand it correctly or is there anything to add to this?
an amendment to 2) I actually did the investigation because I needed to run an "user code" - a logger initialization regardless any target sub-command, but regards the Top (root) command parameter (IsVerbose property in example and in the real situation also some other options) . That initialization needs to be invoked before calling OnExecute of the target sub command. My Idea was to define an Initialize() method in the Top (root) command, and call it by CommandLineUtils by convention. https://github.com/rychlym/CommandLineUtils/blob/bdddb516fb8536d1f44fdfba94451e8f05ca4276/samples/Subcommands/Inheritance.cs#L35-L50
I have forked the repository and added the code doing that. (It is working with synchronous type of Initialize method. I needed also have injected raw command line parameters into the initialize. That all was possible to do with some small internal changes.
(I don't need it right now and unlikely don't have time, but I can see, it could be extended in the future to support calling initialization on the tree path to the target sub command in order and also calling async variant of invoke after clarification how it) If it seems to be worthy, you can take look at it?? Anyway, there seems to be a different solution mentioned in https://github.com/natemcmaster/CommandLineUtils/issues/31 provided by shovonnn in the game - it also able to call an initial user code.
I think you've got a correct understanding of how things work.
There are some pieces of https://github.com/rychlym/CommandLineUtils/commit/936947ce0d0e94e3f93a744c72a431a3da21ecb0 I'd like to take. For instance, the ability to get the original string[] args from the OnExecute method.
I need to think more about the "Initialize" method you are proposing. My initial reaction is that it's not immediately clear that Git.Initialize would be invoked when CommitCommand is the target subcommand. What if we added something like this instead?
[Subcommand("commit", typeof(CommitCommand))]
public class Git
{
public void Initialize()
{
}
}
public class CommitCommand
{
public CommitCommand(Git parent)
{
_parent = parent;
}
public void OnExecute()
{
_parent.Initialize();
}
}
By the way, this isn't the most obvious feature of this library, but you could already structure an app like this. The Parent property on sub command types is automatically set to the parent.
[Subcommand("commit", typeof(Commit))]
public class Git
{
public void Initialize()
{
}
}
public class Commit
{
public Git Parent { get; }
public void OnExecute()
{
Parent.Initialize();
}
}
Hi, thanks for your answers. I see the Initialize method in the fork as a CommandLineUtils convention (with a similar worth like the Parent property wrote about in the last) Problem might be in the naming of it - e.g. that meaning of the "Parent is quite obvious. I understand, that the Initialize might not be so straight forward - "Something from client code, that is called allays at the beginning (within the root command)". I am even also thinking about extending that to: "Something from client code, that is called allays at the beginning (starting from root with possibility to call at each command node up to the target command)"
I see that "Initialize call by convention" approach better then using the Parent properties, because the usage off parent properties leads to a repeatable code inside of the command classes. In case of small amount of command it does not matter. I my case, I have 3 depth tree so the "leaf" commands then would have code like Parent.Parent.Initialize()
I understand, it is not easy to add a change like that to the library. In case your first reaction is not affirmative, you can postpone it. When someone else would need that in the future, you can overtake it. (currently I am using it in my home purposes project, (a boiler control command line app in raspberry pi :) ), so I am fine with the fork, actually it is great that I am able to freely do some changes and thanks again for your support.
Just wanted to give you an update on this. I've refactored ReflectionAppBuilder to make the way this works more extensible. In fact, ReflectionAppBuilder doesn't exist anymore. It's completely been replaced by a set of default conventions. The IConvention API and CommandLineApplication<T> should make it possible for you to implement the Initialize method convention on your own without needing your own fork. Give it a shot in 2.2.0-beta and let me know if it works for you.
Thanks for informing and please excuse me I haven't found a time for a checking. I have shortly checked it with today's version by debugging the Convention example. It looks to me very impressive and the calling of the IConvention.Apply seems to be on right time, when parsed arguments/options... are ready to use in the ConventionContext instance. Still I would need for my particular needs the raw version of the arguments - did I skim it or is it possible to be as a part of the library (e.g. part of convention context) or should I use an own way of injection the raw arguments?
I have done further "debug" observations further found that:
- IConvention .Apply is called more time before executing a command - perhaps called per all the defined commands - is it so?
- the ConventionContext's Application.Options is filled only with options defined on place before actual calling of app.Conventions.AddConvention - is it a bug or a feature? 2a) the possible call of option.HasValue() from the context gives always false at time IConvention .Apply is called?? It might behaves so from principle as the context is constructed step by step, Could it be possible to do without a big effort, that the some objects inside of context can give an info they are "fully ready" like giving same results as in time OnExecute was running.
I am still curious about topic of defining one time running initialization code with possibility to have parsed options and arguments results. (for all the possible commands/options (except help) without any extra plumbing. I tried to put such code to the model constructor and was quite successful - options.HasValue() give correct results. (But it is not so clear - the time the model is created in the HandleParseResult() method, all the work with parsing is not done yet - so I would rather keep version with my fork, where I have defined an initialization method by convention.
By design, conventions are used to define the structure of a CommandLineApplication. If you want to run something after the command line application is defined, use CommandLineApplication.OnParsingComplete to add a callback.
If you want to customize how you initialize types by convention, checkout the https://github.com/natemcmaster/CommandLineUtils/blob/master/src/CommandLineUtils/Conventions/ConstructorInjectionConvention.cs. You can disable or override conventions and write your own. This conventions uses CommandLineApplication<T>.ModelFactory to customize how the types are created.
great! - the CommandLineApplication.OnParsingComplete provdes the possibility y for such an initialization, thanks for informing me.
As I told the all that staff around ICovention sounds very well for me, I will definitely soon or later use it .
Cool. It sounds to me like your original question has been answered. Ok if I close this issue now?
definitelly, thanks