j-maly / CommandLineParser

Command line parser. Declarative arguments support. Rich set of argument types (switches, enums, files, etc...). Mutually exclusive arguments validations.
MIT License
136 stars 30 forks source link

Suggestion: Argument file support #36

Open LightTempler opened 7 years ago

LightTempler commented 7 years ago

For use cases like Windows Planned Tasks or longer, auto generated commandlines using a textfile instead of commandline has advantages. I just checked successfully, a single line of code is enough to get full argument file support for CommandLineParser :

MyApp.exe "C:\Configs\MyCmdlineFile.txt"

VB.NET (checked)

Sub Main(args() As String)

Dim MyOptionsClass As new cMyOptionsClass
Dim clParser As New CommandLineParser.CommandLineParser
Try
     clParser.ExtractArgumentAttributes(MyOptionsClass)

    ' JUST ADD THIS LINE:
    If args IsNot Nothing AndAlso args.Count = 1 AndAlso File.Exists(args(0)) = True Then args= File.ReadAllText(args(0)).Trim.Split(New String(){" ", vbCrLf}, StringSplitOptions.RemoveEmptyEntries)

    clParser.ParseCommandLine(args)

    ' Here we go using values ...

    Catch clEx As CommandLineException
            Console.WriteLine(clEx.Message)

    Catch ex As Exception
            Console.WriteLine(Ex.Message)
End Try
End Sub

C# (unchecked!, sorry)

static class MyApp
{   public static void Main(string[] args)
    {
        cMyOptionsClass MyOptionsClass = new cMyOptionsClass();
        CommandLineParser.CommandLineParser clParser = new CommandLineParser.CommandLineParser();
        try {
            clParser.ExtractArgumentAttributes(MyOptionsClass);

            // JUST ADD THIS LINE:
            if (args != null && args.Count == 1 && File.Exists(args(0)) == true)
                args = File.ReadAllText(args(0)).Trim.Split(new string[] {
                    " ",
                    Strings.Chr(13) + Strings.Chr(10)
                }, StringSplitOptions.RemoveEmptyEntries);

            clParser.ParseCommandLine(args);

            // Here we go using values ...

        } catch (CommandLineException clEx) {
            Console.WriteLine(clEx.Message);

        } catch (Exception ex) {
            Console.WriteLine(ex.Message);
        }
    }
}

Maybe this could be a switchable, build-in feature in a further version or it is worth to add to docu.

alexandre-lecoq commented 5 years ago

IMHO, from a code perspective, this is better done outside ParseCommandLine as in the example. For the scheduling use case, this could also be done by generating bat files or ps1 files.