-
-
Save FailedChecksum/d22daf217e56291ae81b025533df1dd6 to your computer and use it in GitHub Desktop.
This file contains 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
public static class Args2Json | |
{ | |
private static Dictionary<string, string> ApplyPair(this Dictionary<string, string> dict, string key, | |
string value) | |
{ | |
dict.Add(key, value); | |
return dict; | |
} | |
private static Dictionary<string, string> ApplyAssignatoryPair(this Dictionary<string, string> dict, | |
(string key, string value) tpl) => | |
dict.ApplyPair(tpl.key, tpl.value); | |
private static ExpandoObject MapProperties<T>(Dictionary<string, string> pairs) => | |
GetPropertyNames<T>() | |
.Aggregate(new ExpandoObject(), (o, p) => GetMappedArgValue(pairs, o, p)); | |
private static ExpandoObject GetMappedArgValue(Dictionary<string, string> pairs, ExpandoObject target, | |
(string propertyName, string propertyNameTest) tpl) | |
{ | |
((IDictionary<string, Object>) target).Add( | |
tpl.propertyName, | |
pairs.TryGetValue(tpl.propertyNameTest, out string value) switch | |
{ | |
true => value, | |
_ => null | |
} | |
); | |
return target; | |
} | |
private static (string, string) ParseEqualsArg(string arg, int splitIndex) => | |
(splitIndex, arg.Replace("-", "").AsMemory()) switch | |
{ | |
(-1, _) => throw new Exception($"Invalid assignatory argument: ${arg}"), | |
var (_, span) => (span.Slice(0, splitIndex -1).ToString().ToLowerInvariant(), span.Slice(splitIndex).ToString()) | |
}; | |
private static Dictionary<string, string> GetArgumentNamePairs(string[] args) => | |
args.Aggregate((new Dictionary<string, string>(), ""), ParseStreamArg).Item1; | |
private static (Dictionary<string, string>, string) ParseStreamArg( | |
(Dictionary<string, string> dict, string key) tpl, string arg) => | |
(tpl.key, arg.IndexOf('=')) switch | |
{ | |
var (_, index) when index > -1 => (tpl.dict.ApplyAssignatoryPair(ParseEqualsArg(arg, index)), ""), | |
("", _) => (tpl.dict, arg.Replace("-", "").ToLowerInvariant()), | |
_ when arg.StartsWith("-") => (tpl.dict, arg.Replace("-", "").ToLowerInvariant()), | |
_ => (tpl.dict.ApplyPair(tpl.key, arg), "") | |
}; | |
private static IEnumerable<(string, string)> GetPropertyNames<T>() => typeof(T).GetProperties() | |
.Select(property => (property.Name, property.Name.ToLowerInvariant())); | |
public static string Convert2Json<T>(string[] args) => | |
JSON.SerializeDynamic(MapProperties<T>(GetArgumentNamePairs(args)), new Options( | |
serializationNameFormat: | |
SerializationNameFormat.CamelCase) | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment