private static Dictionary <string, PropertyInfo> CreateAliasMap(Type type) { Dictionary <string, PropertyInfo> options = new Dictionary <string, PropertyInfo>(); PropertyInfo[] properties = type.GetProperties(); foreach (PropertyInfo property in properties) { AddProperty(options, property.Name, property); AliasAttribute aliasAttribute = property.GetCustomAttribute <AliasAttribute>(); if (aliasAttribute != null) { foreach (string alias in aliasAttribute.Aliases) { AddProperty(options, alias, property); } } } return(options); }
/// <summary> /// Generate a help page for the given type. /// </summary> /// <param name="type">Type of which to create a help page.</param> /// <param name="programName">The name of the program in the console.</param> /// <returns>A help page as a string.</returns> public static string GetHelpPage(Type type, string programName) { if (type == null) { throw new ArgumentNullException(nameof(type)); } PropertyInfo[] properties = type.GetProperties(); List <string> options = new List <string>(); List <string> arguments = new List <string>(); List <string> descriptions = new List <string>(); List <string> unnamedArgs = new List <string>(); for (int i = 0; i < properties.Length; i++) { PropertyInfo property = properties[i]; UnnamedAttribute unnamed = property.GetCustomAttribute <UnnamedAttribute>(); if (unnamed != null) { unnamedArgs.Add(GetArgumentName(property)); } else { StringBuilder aliases = new StringBuilder(); aliases.Append($"-{property.Name}"); AliasAttribute aliasAttribute = property.GetCustomAttribute <AliasAttribute>(); if (aliasAttribute != null) { foreach (string alias in aliasAttribute.Aliases) { aliases.Append($" -{alias}"); } } DescriptionAttribute descAttr = property.GetCustomAttribute <DescriptionAttribute>(); options.Add(aliases.ToString()); arguments.Add(GetArgumentName(property)); descriptions.Add(descAttr == null ? string.Empty : descAttr.Text); } } int optionsLength = options.Max(x => x.Length); int argumentsLength = arguments.Max(x => x.Length); StringBuilder help = new StringBuilder(); DescriptionAttribute classDescAttr = type.GetCustomAttribute <DescriptionAttribute>(); if (classDescAttr != null && classDescAttr.Text != null) { help.AppendLine(classDescAttr.Text); } help.AppendLine($"Usage: {programName} [options] {string.Join(" ", unnamedArgs.Select(x => $"[{x}]"))}".Trim()); help.AppendLine("Options:"); for (int i = 0; i < options.Count; i++) { help.Append(" ").AppendLine($"{GetTextWithFiller(options[i], optionsLength + 4)}{GetTextWithFiller(arguments[i], argumentsLength + 4)}{descriptions[i]}".Trim()); } return(help.ToString()); }