Tyrrrz / CliFx

Class-first framework for building command-line interfaces
MIT License
1.5k stars 61 forks source link

How to pass a collection of objects as command option #93

Closed mirsahibmovsumov closed 3 years ago

mirsahibmovsumov commented 3 years ago

There is a CLI command like below

[Command("service bind projects")]
    public class BindProjects:  ICommand
    {
        [CommandOption("projects", IsRequired = true)]
        public IList<UpdateUserProjectDto> Projects { get; set; }

        [CommandOption("userId", IsRequired = true)]
        public string UserId { get; set; }

        public async ValueTask ExecuteAsync(IConsole console)
        {
            var command = new BindProjectsCommand { Projects = Projects, UserId = UserId };
            // execute command and show result
        }
    }

public class UpdateUserProjectDto
    {
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public bool IsBound { get; set; }
    }

I wanna pass a list of UpdateUserProjectDto as Projects but I cannot do it. Could you suggest to me how to add this?

Tyrrrz commented 3 years ago

You can either add a static Parse(string value) method on UpdateUserProjectDto or create a converter deriving from ArgumentValueConverter and specify it in the attribute.

First approach is easier:

public class UpdateUserProjectDto
    {
        public int ProjectId { get; set; }
        public string ProjectName { get; set; }
        public bool IsBound { get; set; }

        public static UpdateUserProjectDto Parse(string value)
        {
              // Parse the value from string here
             var projectId = ...;
             var projectName = ...;
             var isBond = ...;

             return new UpdateUserProjectDto{ ProjectId = projectId, ProjectName = projectName, IsBound = isBond };
        }
}    
mirsahibmovsumov commented 3 years ago

Thanks a lot It seems there's no generic way to pass a collection of objects

Tyrrrz commented 3 years ago

Nope, only if they have Parse(...).