Last active
July 2, 2018 09:55
-
-
Save atifaziz/ebb7107e4e8c3b659bd1 to your computer and use it in GitHub Desktop.
Good citizen .NET console application
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace TheGoodApp | |
{ | |
using System; | |
using System.Collections.Generic; | |
using System.Diagnostics; | |
using System.Linq; | |
partial class Program | |
{ | |
static int Main(string[] args) | |
{ | |
try | |
{ | |
var argList = args.ToList(); | |
OnProcessingArgs(argList); | |
if (argList.RemoveAll(MatchMaker("--debug")) > 0) | |
OnDebugFlagged(); | |
if (argList.RemoveAll(MatchMaker("-h", "-?", "--help")) > 0) | |
OnHelpFlagged(); | |
if (argList.RemoveAll(MatchMaker("-v", "--verbose")) > 0) | |
OnVerboseFlagged(); | |
Wain(argList); | |
return 0; | |
} | |
catch (Exception e) | |
{ | |
Console.Error.WriteLine(e.GetBaseException().Message); | |
Trace.TraceError(e.ToString()); | |
return 0xbad; | |
} | |
} | |
static partial void Wain(IEnumerable<string> args); | |
static partial void OnProcessingArgs(IList<string> args); | |
static partial void OnVerboseFlagged(); // e.g. { Trace.Listeners.Add(new ConsoleTraceListener(true)); } | |
static partial void OnDebugFlagged(); // e.g. { Debugger.Launch(); } | |
static partial void OnHelpFlagged(); | |
[DebuggerStepThrough] | |
static Predicate<T> MatchMaker<T>(params T[] searches) => | |
input => searches.Any(s => EqualityComparer<T>.Default.Equals(s, input)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@fidergo-stephane-gourichon All your observations are spot on! This is designed to be used unmodified by as much as possible. The class is partial so you can just throw it alongside other source files in a C# console application project and start with your
Wain
(which isMain
with just the M turned on its head).I intend to use this on Windows, Mac OS X and pretty much any Linux-based OS where the run-time targeted by a C# console application is available.
That doesn't mean you can't or that you shouldn't do the right thing. I often write console applications that are scripted together with other console applications (via a Windows command/batch script), either as compositions via piping or as sequential operations. For sequencing and logical decisions, it is imperative that one returns a non-zero exit code in case of failure to be able to use the
&&
and||
operators.