Skip to content

Instantly share code, notes, and snippets.

@ZacharyPatten
Created September 10, 2020 02:16
Show Gist options
  • Save ZacharyPatten/782a23f56cdf418f3abb3bf7177f2a8d to your computer and use it in GitHub Desktop.
Save ZacharyPatten/782a23f56cdf418f3abb3bf7177f2a8d to your computer and use it in GitHub Desktop.
Towel CommandLine Comparisons

This is a comparison between Towel's CommandLine implementation and other similar command line parsers.

Here is an example of Towel's CommandLine:

using System;
using System.IO;
using static Towel.CommandLine;

namespace ConsoleApp
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args is null || args.Length <= 0) args = new[] { "run" }; // <- this line is not required.
			HandleArguments(args);
		}

		/// <summary>The run method.</summary>
		/// <param name="intOption">An option whose argument is parsed as an int.</param>
		/// <param name="boolOption">An option whose argument is parsed as a bool.</param>
		/// <param name="fileOption">An option whose argument is parsed as a FileInfo.</param>
		[Command] static void run(int intOption = 42, bool boolOption = false, FileInfo fileOption = null)
		{
			Console.WriteLine($"The value for --int-option is: {intOption}");
			Console.WriteLine($"The value for --bool-option is: {boolOption}");
			Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
		}
	}
}

Here is a comparable example using System.CommandLine:

using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.IO;

namespace ConsoleApp
{
	class Program
	{
		static int Main(string[] args)
		{
			var rootCommand = new RootCommand
			{
				new Option<int>(
					"--int-option",
					getDefaultValue: () => 42,
					description: "An option whose argument is parsed as an int"),
				new Option<bool>(
					"--bool-option",
					"An option whose argument is parsed as a bool"),
				new Option<FileInfo>(
					"--file-option",
					"An option whose argument is parsed as a FileInfo")
			};
			rootCommand.Description = "My sample app";
			rootCommand.Handler = CommandHandler.Create<int, bool, FileInfo>((intOption, boolOption, fileOption) =>
			{
				Console.WriteLine($"The value for --int-option is: {intOption}");
				Console.WriteLine($"The value for --bool-option is: {boolOption}");
				Console.WriteLine($"The value for --file-option is: {fileOption?.FullName ?? "null"}");
			});
			return rootCommand.InvokeAsync(args).Result;
		}
	}
}

As you can see, Towel's CommandLine implemtation has less boiler plate than System.CommandLine, and the source code is a fraction of the size (granted System.CommandLine has features that Towel's CommandLine does not yet have).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment