Code Monkey home page Code Monkey logo

clifx's Introduction


๐Ÿ‘‹ Hi there!

My name is Oleksii and I do open source for fun. The projects you will find on this profile are just random things I've built at one point or another to make my life easier. Hopefully they can be useful to you as well!

Socials

Blog YouTube Twitter Discord

Stats

clifx's People

Contributors

89netram avatar adustyoldmuffin avatar alexrosenfeld10 avatar alirezanet avatar blackgad avatar cartblanche avatar dgarcia202 avatar domn1995 avatar es-rene99 avatar federico-paolillo avatar inech avatar moophic avatar nikiforovall avatar oshustov avatar rcdailey avatar ron-myers avatar tagc avatar thorhj avatar tyrrrz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

clifx's Issues

How to add logging to services

Hi!

I like this library, it looks clean and well written.
I only find the progress reporting a bit lacking because i'd like to add what im doing or processing when i report progress (e.g. 50% removing file: c:/somefolder/somefile.txt).

but to the core of my question;

I have SomeService which is injected to MyCmd, now i'd like to do some logging from out of my service. In asp.net core i inject a logger factory for this. However i'm uncertain how to go about this when using this fx. Any thoughts?

edit; playing around with trying to get IConsole from CliApplication into the container somehow.

Subcommands

Allow specifying command "routes", e.g. app.exe create file --name newfile.txt and app.exe create directory --name newdir.

Force the display of a command's help text from ExecuteAsync?

First of all, I love project! Here's the use case I'm trying figure out:

I have a pretty nested CLI app where some commands don't actually do anything, but rather just help organize the app. Example:

myapp
|_ sub1
   |_ sub-sub1

In this example, command sub1 doesn't do anything except organize the structure of the commands. As such, in the ICommand.ExecuteAsync(IConsole) implementation, I'm simply returning default. When running the app in the following manner myapp sub, it simply executes then exits without doing anything. My intended behavior, however, is for it to print its help text instead.

Is it possible to do this currently? Or is there a better way to implement this pattern?

Thanks, and again, I love the library!!! And I hope you enjoy the three coffees I bought you @Tyrrrz :)

Print help text on specific exceptions

Exceptions related to user input should probably trigger help automatically so that besides being told "you didn't specify option --required" the user will also be shown what that option actually is.

Possibly also extend CommandException so that it's possible to request help when throwing that exception.

Order changes parser behavior?

For some reason the first sample below works, but the second does not. For some reason the ordening of the options change the behaviour of the parser (or i'm missing something).

1>  "C:\Repos\HMI4\Tools\HmiPluginDllManager\bin\Debug\netcoreapp3.1\HmiPluginDllManager.exe" [preview] CpyPluginDlls -p "WebHmi.HmiPlugins" -c "Debug" -o "C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug\"
Parser preview:
CpyPluginDlls [-p WebHmi.HmiPlugins] [-c Debug] [-o C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug"] 
"C:\Repos\HMI4\Tools\HmiPluginDllManager\bin\Debug\netcoreapp3.1\HmiPluginDllManager.exe" [preview] CpyPluginDlls -p "WebHmi.HmiPlugins" -o "C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug\" -c "Debug"
Parser preview:
CpyPluginDlls [-p WebHmi.HmiPlugins] [-o 
 C:\Repos\HMI4\Machines\Kytl320\HmiUiKytl320\bin\Debug" -c Debug"] 

Allow scalar option/parameter types be constructed with arrays of strings

Proposal

Allow the supported types of options/parameters be constructed with enumerables of strings, not just raw strings. This is already essentially supported, but with a "wart" in a form of a requirement to implement a dummy interface (see below). For this reason, the proposal concerns only adding the support for new(ICollectionType<string> strings) signature.

Motivation

To provide a better user experience, I have been using arrays of strings instead of raw strings to not have to use quotes when specifying argument values:

[CommandParameter(0)]
string[] BookName { get; set; }
//add book The Book With A Long Title 
//instead of
//add book "The Book With A Long Title"

I decided to take advantage of CliFX's default handling of invalid/missing arguments, so I created a strong type for BookName to replace string[]:

public class Name
{
   public Name(string[] strings) => Value = string.Join(' ', strings);
   public string Value { get; set; }
}

This, unfortunately, does not work in the current version (in the README file, there is a mention of types with constructors of supported types also being supported, which lead to me to believe this was possible in the first place, but this could be attributed to me misinterpreting the documentation, since this point is under "Supports collection types" header, which logically excludes scalars). What does work (as expected), however, is the following workaround:

public class Name : IEnumerable
{
   public Name(string[] strings) => Value = string.Join(' ', strings);
   public string Value { get; set; }
   IEnumerator IEnumerable.GetEnumerator() => throw new NotImplementedException();
}

Thus I decided to file this issue to see if there would be a possibility of adding "full" support for this pattern.

Implementation

As far as I understand, this would involve refactoring the logic here to support the notion of an enumerable type being not just a type with enumerableUnderlyingType == null, but also one with the appropriate constructor. A bigger refactoring could be considered, and the notion of "fake" enumerable types could be introduced, but the determination of need for that requires a deeper understanding of the codebase, which I do not (yet) have. It would seem reasonable to me to assume that the fact that the value is a "real" enumerable is of questionable relevance, since that information could only be useful if there is a need to actually call the iterator methods, which the library currently does not do, at least according to the GitHub search for GetEnumerator.

Multiple characters for short name

From using other CLI tools it's common to have multiple character short names to avoid clashing of commands I.E. --save, -s --saveFile, -sf

Is it possible that support for this could be added?

Hide internals

A lot of implementation details are currently public. I believe the public API should be reduced to only include the interfaces/classes needed to operate the framework (e.g. CliApplicationBuilder, CommandAttribute etc.). Other code should be marked internal.

This is a benefit for the library developers, who can then easily refactor code in a non-breaking fashion, as well as consumer developers because the public API is more easily discoverable.

Allow for minimum number of items in array-backed parameters

When I have a parameter like this:

[CommandParameter(0)]
public FileInfo File { get; set; }

And I don't pass in a file, the program display the help message. However, if I make that a list:

[CommandParameter(0)]
public IReadOnlyList<FileInfo> Files { get; set; }

And don't pass in any files, the command runs. It would be really helpful to be able to specify that the parameter needs to have at least one file.

Add the ability to set exit code without displaying StackTrace details

So far working with CliFx has been excellent. I see this framework solving several of the issues I have with other options in the dotnet space today. Thank you @Tyrrrz

One edge I hit is the app that I am working on needs to set the exit code based on some application logic.

Within CliFx, it seems this can only be set by throwing an exception. I understand that as a design approach, but my need is to set the failure to a known error code without displaying a stack trace. This is an expected exception.

What I tried:

      if (WarningsAreErrors && result.Findings.Any())
      {
        // set the exit code
        throw new CommandException(string.Empty, exitCode: (int)AppExitCode.ErrorsFound);
      }

but the stack trace is still displayed:

CliFx.Exceptions.CommandException
   at UnderTest.FeatureLint.Commands.DefaultCommand.ThrowExitCodeIfError(FeatureLintResult result) in C:\dev\oss\under-test\undertest.featurelint\src\UnderTest.FeatureLint\Commands\DefaultCommand.cs:line 78
   at UnderTest.FeatureLint.Commands.DefaultCommand.ExecuteAsync(IConsole console) in C:\dev\oss\under-test\undertest.featurelint\src\UnderTest.FeatureLint\Commands\DefaultCommand.cs:line 60
   at CliFx.CliApplication.RunAsync(IReadOnlyList`1 commandLineArguments, IReadOnlyDictionary`2 environmentVariables)

So I am proposing a specific exception for this, say CommandExpectedException(open to feedback on the name)

This should just need the exception and an additional catch statement in CliApplication.RunAsync and I ready to create a PR if this is seen as a welcome change.

After upgrading from 0.0.8 to 1.0.0, Dependency injection management using Autofac failed

using Autofac;

            var builder = new ContainerBuilder();
            builder.RegisterAssemblyModules(typeof(Logic.Global).Assembly);

            builder.RegisterType<SerialCliCommand>().Named<ICommand>("serial").SingleInstance();
            builder.RegisterType<CareConfigCliCommand>().Named<ICommand>("cc").SingleInstance();
            builder.RegisterType<CareCliCommand>().Named<ICommand>("ci").SingleInstance();
            builder.RegisterType<DataCommand>().Named<ICommand>("d").SingleInstance();

            var container = builder.Build();

            await new CliApplicationBuilder()
                .AddCommandsFromThisAssembly()
                .UseTypeActivator(type => container.ResolveNamed<ICommand>(type.Name))
                .Build()
                .RunAsync(args);

Report error when option not found

It would be nice to report an error to a user when he/she specifies an unknown option.

Actual
Let's say there is an optional option error-output. You run a command:

validate file --file C:\mydir\123.txt --schema C:\mydir\123.schema --errors-output C:\mydir\results

And for some reason, it doesn't behave as expected even though you don't see any errors.

Expected
You run this command and it tells you that option errors-output doesn't exist. You quickly fix the typo.

Console.ReadKey() implementation for SystemConsole

Generally I like the analyzer's warnings about usage of System.Console. However, in case of System.Console.ReadKey() there's no corresponding method in IConsole.

Either it may be added to IConsole, or the analyzer should stop worrying about ReadKey().

Ensure that user's commands don't have conflicts with built-in options

Command types should not contain options that resolve to one of the built-in options, i.e. --help/-h and --version (only on default command).

Currently this is not validated and will lead to undefined behavior (built-in options take precedence but both kind of options will still appear in help text).

Need to add validation and corresponding tests.

Anonymous options

...aka options that don't have a name.

Allow doing something like app command <option> or even app command <option> subcommand. Currently this is not possible because <option> will be parsed as part of the command name.

Also, what do we do in case of conflicts? E.g. app command <option> where <option> matches the name of one of the subcommands.

Some inspiration can be drawn here: http://docopt.org/

Create abstractions package

Create a package with the interfaces (such as IConsole) to allow for custom implementations without importing the whole library.

Use Case

For referencing the abstractions package in a common library that may be used across CLI, UI, Web applications. For example, a Logger that can take an IConsole as a parameter and wrap the output. Allowing for methods like Error(), Information() etc, that can add extra information (like timestamps, colors, etc).

Suggested Implementation

Move the following interfaces to the package

  • IConsole
  • ICommand
  • ICliApplication
  • ICliApplicationBuilder
  • ICommandFactory

It may be helpful to include all of the core interfaces in here, however I leave that up to you.

Global options & always parsing options as 'multiple'

Hello,

first of all, I quite like this library, it is really easy to grasp, which is rare in .net world.

There are 2 features though which are a blocker for me to consider using it, so just want to ask if I missed something or not.

Problem 1

One feature which I think is missing is global or persistent options, or did I missed it?
Specified on parent command, accessible to child command (maybe dependency injection can be used here?)

some useful examples

./cmd --log-level=debug subcommand --local-option  # set loggin level for all subcommands
./ginit --repo gitlab init --project-type rust ./my_project # set that all subcommands will be run against gitlab
./cmd -q subcommand # no output for all subcommands, only return codes
./cmd --json fetch 34 --include-images # return a JSON string for all subcommands

One way to have global options might be to enable them at the end (before arguments). like e.g. 'npm' handles it

npm -g ls --depth 1   # is an equivalent to
npm ls --depth 1 -g

Problem 2

This library is always parsing options as multiple values, which I think is really unusual (and essentially blocks global options).
I can't remember used it like that in case cli supported commands and subcommands.

How I think this feature is mostly implemented:

./cmd -i test.txt -i test.txt  # used e.g. in docker cli
# or
./cmd -i test.txt,test.txt     # used in a lot of cli apps + it is native to how powershell handles it
# or
./cmd -i=test.txt,tests.txt   # used e.g. in git cli

Just wondering what was the reasoning for this implementation, because going through some modern big CLIs like (kubectl, docker, dotnet, hugo, git, github, az, npm, yarn, cargo, pip, choco, scoop, etc.) it was hard to find similar behaviour. At least for me it is simply not intuitive and more or less unexpected.

Thank you for answers,
Stefan

Force debug launch

Hm it is strange, but you merged pull request with active debug prompt and 3 days ago removed that functionality.
Is it merge errors or you decided to remove this functionality?

Add support for getting the input command

Need to add support for getting original command entered at start. I've encountered a scenario where I needed to store the original command, although could not find anything for it. If there is, can you point me towards it?

Show default values of non-required options in help

Suggested approach:

  • Resolve target command
  • Instantiate the command but don't fill the values
  • Get the values of the properties on the freshly-instantiated command, filter out those that are default and show them in help text

Options groups

Specify a group on an option. Options from the same group can/cannot be used simultaneously.

Add cursor position control to IConsole interface

Description

Sometimes you wish to overwrite previously entered output, e.g. when creating a loading bar or a spinner. This is not possible through the recommended IConsole instance, as it does not define contracts for controlling the cursor position.

Suggested solution

Add the following signatures to IConsole:

CursorLeft { get; set; }
CursorTop { get; set; }
CursorVisible { get; set; }
CursorSize { get; set; }
SetCursorPosition(int, int)

I suspect these have been left out of the interface because of the VirtualConsole implementation. Alternatively, a spinner class could be added to the framework similar to ProgressReporter.

Custom value validation

Currently, the only way to validate a value is to check it in ExecuteAsync and throw CommandExecution if it's invalid. This can be made to look nicer with tools like FluentValidation but it's still quite verbose and cumbersome.

One option is to use the standard ValidationAttribute but it has some bloat.

Support version and help commands

Many CLI tools have built-in version and help commands. For example:

>git version
git version 2.9.2.windows1

>git help
usage: git [...]
...
  • Are we interested in supporting this in CliFx?
  • Also, if supporting help as a builtin command, do we want it only for the root of the app or to all subcommands? I propose all subcommands.
  • For the builtin 'version` command, I think it would only make sense to be built in to the root of the app.

Add support for running under Microsoft.Extensions.Hosting.Host

Add support for configuring and launching the application under the .NET Generic Host.

Currently, this can be achieved in a sort of hacky way:

public static Task<int> Main(string[] args)
{
    var host = CreateHostBuilder(args).Build();
    return new CliApplicationBuilder()
        .AddCommandsFromThisAssembly()
        .UseCommandFactory(schema => (ICommand)host.Services.GetRequiredService(schema.Type))
        .Build()
        .RunAsync(args);
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureServices((hostContext, services) =>
    {
        services.AddSingleton<IConsole, SystemConsole>();
        var typesThatImplementICommand = typeof(Program).Assembly.GetTypes().Where(x => typeof(ICommand).IsAssignableFrom(x));
        foreach (var t in typesThatImplementICommand)
            services.AddTransient(t);
    })
    .UseConsoleLifetime();

I envision this as something like

public static IHostBuilder CreateHostBuilder(string[] args) =>
    Host.CreateDefaultBuilder(args)
    .ConfigureAsCliApplication()
    .ConfigureServices((hostContext, services) =>
    {
        // Add custom services here
    })
    .UseConsoleLifetime();

Then running it by either calling the existing Build().RunAsync() or .RunConsoleAsync() on IHostBuilderor adding a new.RunAsCliApplicationAsync()on eitherIHostBuilderorIHost` (or similar).

Add support for positional arguments

Commands may have an argument that is always required and makes sense semantically without an option flag. E.g.:

git checkout <ref>

Positional arguments are not supported, so the above would need to be invoked like this:

git checkout --ref <ref>

Pass-through arguments

Add support for path-through arguments.

Sometimes the application may act as a proxy to another application. An example of this is dotnet run which routes any arguments after -- directly to the executed application.

Example:

dotnet run -c Release -- arg1 arg2 --flag

Arguments arg1, arg2, --flag are passed as is to the executed application.

Allow [CommandArgumentSink] attribute on properties of type IEnumerable<string> or any other type that can be assigned from a string array or initialized with a string array (similar to how we do conversions currently). There can only be one such property.

Note: this has to play nicely with #38.

Open question:

  • Should arguments after -- only be consumed by argument sinks?
  • If not, then we need to determine how parameters/options and argument sinks should work together.

Show error when user provides an option/parameter that the command doesn't support

When the user supplies an unknown option/parameter, they should receive an error. This aligns with an optimal user experience, because the application shouldn't silently discard arguments that the user assumed would somehow change the behavior of the program.

Need to add a throw new CliFxException(...) statement somewhere in CommandSchema.InjectParameters and CommandSchema.InjectOptions.

Add corresponding tests.

Option validation attributes

Introduce a set of attributes that dictate the range of valid values an option can take.
Examples: StringLength, RegularExpression, Range.

Environment variables

Extend CommandOptionAttribute by adding EnvironmentVariableName. If the corresponding environment variable is set, the option property will take on its value, but only if the corresponding command line argument was not set. In other words, command line argument > environment variable > default value.

Allow custom formatting of output

First of all, nice framework :)

I think it would be nice to allow custom formatting of output that is currently fixed. Output that I have seen so far (not an extensive list):

  • Argument type mismatch: Can't convert value [abc] to type [System.Int32].
  • Missing argument: One or more required options were not set: id.
  • Usage/help text

Customizable option format/grammar

Currently, CliFx only accepts options in a form of --some-argument value. It would be nice if you could customize it to accept different characters in place of whitespace, e.g. --some-argument=value. The next step would also be to make the entire grammar completely customizable so the user could use different styles/standards, e.g. /some-argument:value.

Custom value conversion

Add some sort of functionality that lets users specify custom converter for command parameters/options.

Needs to work well with both scalar and non-scalar (i.e. array) arguments.

Thinking about using attributes for this, but maybe there are better options.

Tests sometimes throw ArgumentOutOfRangeException on Windows CI

See the following test run where Command may throw a specialized exception which shows only the help text FT throws an ArgumentOutOfRangeException:
https://github.com/Tyrrrz/CliFx/pull/54/checks?check_run_id=676614514

Then another run with no changes and it works fine:
https://github.com/Tyrrrz/CliFx/pull/54/checks?check_run_id=676630738

Not sure there's anything we can do about since it seems to be happening in the underlying Windows API, but worth documenting anyway.

Add option for adding multiple items when we specify List<object>?

In my api I can use something like api/projects?statuses=1,2,3 it would be perfect also use this feature.

Example code:

    ```
    Another command options (working fine)

    [CommandOption("statuses", IsRequired = false)]
    public List<ProjectStatus?> Statuses { get; set; }
    
    public async ValueTask ExecuteAsync(IConsole console)
    {
        await console.Output.WriteLineAsync("Getting projects as yaml");
        var json = await Helpers.Transformer($"{TaikunURLs.getProjects}?statuses={Statuses}");
        var swaggerDocument = Helpers.ConvertJTokenToObject(JsonConvert.DeserializeObject<JToken>(json));

        var serializer = new YamlDotNet.Serialization.Serializer();

        using var writer = new StringWriter();
        serializer.Serialize(writer, swaggerDocument);
        var yaml = writer.ToString();
        await console.Output.WriteLineAsync(yaml);
    }

P.S. tried IReadOnlyList and it was not working in this case.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.