Beispiel #1
0
        /// <summary>
        /// Writes usage for the specified command.
        /// </summary>
        /// <param name="command">The command to write help details for.</param>
        /// <param name="writer">The writer to write help output to.</param>
        protected virtual void WriteCommandUsage(ICommand command, TextWriter writer)
        {
            string description = GetUsage(command);

            WriteHeading(LocalizationResources.HelpUsageTitle(), description, writer);
            writer.WriteLine();
        }
Beispiel #2
0
 /// <summary>
 /// Get a single resource
 /// </summary>
 /// <param name="resname">Name of the resource</param>
 /// <returns></returns>
 /// <author>Thomas Kosch</author>
 public static object GetResource(string resname)
 {
     if (LocalizationResources.ContainsKey(resname))
     {
         return(LocalizationResources[resname]);
     }
     return(null);
 }
 internal FailedArgumentTypeConversionResult(
     IArgument argument,
     Type expectedType,
     string value,
     LocalizationResources localizationResources) :
     base(argument, FormatErrorMessage(argument, expectedType, value, localizationResources))
 {
 }
 internal ArgumentConversionResult(
     Argument argument,
     Type expectedType,
     string value,
     LocalizationResources localizationResources) :
     this(argument, FormatErrorMessage(argument, expectedType, value, localizationResources), ArgumentConversionResultType.FailedType)
 {
 }
Beispiel #5
0
 /// <param name="localizationResources">Resources used to localize the help output.</param>
 /// <param name="maxWidth">The maximum width in characters after which help output is wrapped.</param>
 public HelpBuilder(LocalizationResources localizationResources, int maxWidth = int.MaxValue)
 {
     LocalizationResources = localizationResources ?? throw new ArgumentNullException(nameof(localizationResources));
     if (maxWidth <= 0)
     {
         maxWidth = int.MaxValue;
     }
     MaxWidth = maxWidth;
 }
Beispiel #6
0
        /// <summary>
        /// Writes help output for additional arguments.
        /// </summary>
        protected virtual void WriteAdditionalArguments(ICommand command, TextWriter writer)
        {
            if (command.TreatUnmatchedTokensAsErrors)
            {
                return;
            }

            WriteHeading(LocalizationResources.HelpAdditionalArgumentsTitle(),
                         LocalizationResources.HelpAdditionalArgumentsDescription(), writer);
        }
Beispiel #7
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="command">The command to get argument help items for.</param>
        /// <param name="parseResult">A parse result providing context for help formatting.</param>
        /// <param name="writer">The writer to write help output to.</param>
        protected virtual void WriteSubcommands(ICommand command, TextWriter writer, ParseResult parseResult)
        {
            var subcommands = GetSubcommandRows(command, parseResult).ToArray();

            if (subcommands.Length > 0)
            {
                WriteHeading(LocalizationResources.HelpCommandsTitle(), null, writer);
                RenderAsColumns(writer, subcommands);
                writer.WriteLine();
            }
        }
Beispiel #8
0
        /// <summary>
        /// Writes help output for the specified command's arguments.
        /// </summary>
        /// <param name="command">The command to write out argument help for.</param>
        /// <param name="writer">The writer to write help output to.</param>
        /// <param name="parseResult">A parse result providing context for help formatting.</param>
        protected virtual void WriteCommandArguments(ICommand command, TextWriter writer, ParseResult parseResult)
        {
            TwoColumnHelpRow[] commandArguments = GetCommandArgumentRows(command, parseResult).ToArray();

            if (commandArguments.Length > 0)
            {
                WriteHeading(LocalizationResources.HelpArgumentsTitle(), null, writer);
                RenderAsColumns(writer, commandArguments);
                writer.WriteLine();
            }
        }
        internal static ArgumentConversionResult ConvertObject(
            Argument argument,
            Type type,
            object?value,
            LocalizationResources localizationResources)
        {
            switch (value)
            {
            case Token singleValue:
                return(ConvertToken(argument, type, singleValue, localizationResources));

            case IReadOnlyList <Token> manyValues:
                return(ConvertTokens(argument, type, manyValues, localizationResources));

            default:
                return(None(argument));
            }
        }
        private static ArgumentConversionResult ConvertTokens(
            Argument argument,
            Type type,
            IReadOnlyList <Token> tokens,
            LocalizationResources localizationResources,
            ArgumentResult?argumentResult = null)
        {
            var itemType = type.GetElementTypeIfEnumerable() ?? typeof(string);
            var values   = CreateEnumerable(type, itemType, tokens.Count);
            var isArray  = values is Array;

            for (var i = 0; i < tokens.Count; i++)
            {
                var token = tokens[i];

                var result = ConvertToken(argument, itemType, token, localizationResources);

                switch (result.Result)
                {
                case ArgumentConversionResultType.Successful:
                    if (isArray)
                    {
                        values[i] = result.Value;
                    }
                    else
                    {
                        values.Add(result.Value);
                    }

                    break;

                default:     // failures
                    if (argumentResult is { Parent: CommandResult })
                    {
                        argumentResult.OnlyTake(i);

                        i = tokens.Count;
                        break;
                    }

                    return(result);
                }
            }
Beispiel #11
0
        /// <summary>
        /// Gets the usage for the specified command.
        /// </summary>
        /// <param name="command">The command to get usage for.</param>
        protected string GetUsage(ICommand command)
        {
            return(string.Join(" ", GetUsageParts().Where(x => !string.IsNullOrWhiteSpace(x))));

            IEnumerable <string> GetUsageParts()
            {
                IEnumerable <ICommand> parentCommands =
                    command
                    .RecurseWhileNotNull(c => c.Parents.FirstOrDefaultOfType <ICommand>())
                    .Reverse();


                foreach (ICommand parentCommand in parentCommands)
                {
                    yield return(parentCommand.Name);

                    yield return(FormatArgumentUsage(parentCommand.Arguments));
                }

                var hasCommandWithHelp = command.Children
                                         .OfType <ICommand>()
                                         .Any(x => !x.IsHidden);

                if (hasCommandWithHelp)
                {
                    yield return(LocalizationResources.HelpUsageCommandTitle());
                }

                var displayOptionTitle = command.Options.Any(x => !x.IsHidden);

                if (displayOptionTitle)
                {
                    yield return(LocalizationResources.HelpUsageOptionsTitle());

                    displayOptionTitle = false;
                }

                if (!command.TreatUnmatchedTokensAsErrors)
                {
                    yield return(LocalizationResources.HelpUsageAdditionalArguments());
                }
            }
        }
        private static ArgumentConversionResult ConvertToken(
            Argument argument,
            Type type,
            Token token,
            LocalizationResources localizationResources)
        {
            var value = token.Value;

            if (type.TryGetNullableType(out var nullableType))
            {
                return(ConvertToken(argument, nullableType, token, localizationResources));
            }

            if (_stringConverters.TryGetValue(type, out var tryConvert))
            {
                if (tryConvert(value, out var converted))
                {
                    return(Success(argument, converted));
                }
                else
                {
                    return(Failure(argument, type, value, localizationResources));
                }
            }

            if (type.IsEnum)
            {
                try
                {
                    return(Success(argument, Enum.Parse(type, value, true)));
                }
                catch (ArgumentException)
                {
                    // TODO: find a way to do this without the try..catch
                }
            }

            return(Failure(argument, type, value, localizationResources));
        }
        private static string FormatErrorMessage(
            IArgument argument,
            Type expectedType,
            string value,
            LocalizationResources localizationResources)
        {
            if (argument is Argument a &&
                a.Parents.Count == 1)
            {
                var firstParent = (IIdentifierSymbol)a.Parents[0];
                var alias       = firstParent.Aliases.First();

                switch (firstParent)
                {
                case ICommand _:
                    return(localizationResources.ArgumentConversionCannotParseForCommand(value, alias, expectedType));

                case IOption _:
                    return(localizationResources.ArgumentConversionCannotParseForOption(value, alias, expectedType));
                }
            }

            return(localizationResources.ArgumentConversionCannotParse(value, expectedType));
        }
 public CustomHelpBuilder(IConsole console, LocalizationResources localizationResources,
                          int maxWidth = int.MaxValue)
     : base(localizationResources, maxWidth)
 {
     Console = console;
 }
 public ShoppingListLocalization()
 {
     Strings = new LocalizationResources();
 }
Beispiel #16
0
 /// <summary>
 /// Writes the synopsis for the specified command.
 /// </summary>
 /// <param name="command">The command to write help details for.</param>
 /// <param name="writer">The writer to write help output to.</param>
 protected virtual void WriteSynopsis(ICommand command, TextWriter writer)
 {
     WriteHeading(LocalizationResources.HelpDescriptionTitle(), command.Description, writer);
     writer.WriteLine();
 }
Beispiel #17
0
        public LocalizationResources BuildResources()
        {
            var data = new LocalizationResources();

            foreach (var domainName in Options.Domains)
            {
                var domain = Context.LocalizeDomains.SingleOrDefault(d => d.Name == domainName);
                if (domain == null)
                {
                    continue;
                }
                if (domain.Cultures == null)
                {
                    continue;
                }

                // Retrieve cultures (no "'" allowed to prevent SQL Injection when using queries):
                var cultures = domain.Cultures.Replace('\'', '*').Split(',').Select(s => s.Trim()).Where(s => s.Length > 0).ToArray();
                if (cultures.Length == 0)
                {
                    continue;
                }

                // Create keys from queries:
                foreach (var query in Context.LocalizeQueries.Where(q => q.DomainId == domain.Id))
                {
                    using (var conn = new SqlConnection(Configuration.GetConnectionString(query.ConnectionName)))
                        using (var cmd = conn.CreateCommand())
                        {
                            cmd.CommandText = query.Sql
                                              .Replace("{cultures}", String.Join("','", cultures));

                            if (conn.State == System.Data.ConnectionState.Closed)
                            {
                                conn.Open();
                            }

                            using (var reader = cmd.ExecuteReader())
                            {
                                var keyCount = (reader.GetColumnSchema().Count - 1) / 2;
                                while (reader.Read())
                                {
                                    var culture = reader.GetString(0);
                                    if (cultures.Contains(culture))
                                    {
                                        for (int c = 0; c < keyCount; c++)
                                        {
                                            var key   = reader.GetString(c * 2 + 1);
                                            var value = reader.GetString(c * 2 + 2);
                                            data.AddResourceValue(key, culture, value);
                                        }
                                    }
                                }
                            }
                        }
                }

                // Create keys from keys:
                foreach (var key in Context.LocalizeKeys.Include(k => k.Values).Where(k => k.DomainId == domain.Id))
                {
                    var resource = new LocalizationResource();
                    resource.ForPath = key.ForPath;
                    var namedParameters = (key.ParameterNames ?? "").Split(',').Select(s => s.Trim()).Where(s => s.Length > 0).ToArray();
                    foreach (var value in key.Values)
                    {
                        if (value.Value == null && value.Reviewed == false)
                        {
                            continue;
                        }
                        if (cultures.Contains(value.Culture))
                        {
                            if (namedParameters.Length > 0)
                            {
                                for (int i = 0; i < namedParameters.Length; i++)
                                {
                                    value.Value = (value.Value ?? "").Replace("{" + namedParameters[i], "{" + i);
                                }
                            }
                            resource.Values[value.Culture] = (value.Value ?? "");
                        }
                    }
                    data.AddResource(key.Name, resource);
                }
            }

            return(data);
        }