Skip to content

Commit

Permalink
Localized demo
Browse files Browse the repository at this point in the history
  • Loading branch information
tkouba committed Jul 24, 2019
1 parent 86d7582 commit 7ede4da
Show file tree
Hide file tree
Showing 12 changed files with 1,195 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="utf-8"?>
<Root Type="DevExpress.CodeRush.Foundation.Navigation.QuickFileNav.SolutionFileInfosContainer">
<Options Language="Neutral">
<Items>
<Item Id="{62fa45be-9e28-4fdc-b57e-974ea27ae9a4}">
<Filename>LocalizableAttributeProperty.cs</Filename>
<FilePath>d:\work\arci\commandline\src\commandline\infrastructure\localizableattributeproperty.cs</FilePath>
<Folders>
<Item>Infrastructure</Item>
</Folders>
<ProjectFileName>d:\WORK\ARCI\commandline\src\CommandLine\CommandLine.csproj</ProjectFileName>
<ProjectName>CommandLine</ProjectName>
</Item>
</Items>
</Options>
</Root>
122 changes: 122 additions & 0 deletions demo/ReadText.LocalizedDemo/LocalizableSentenceBuilder.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CommandLine;
using CommandLine.Text;

namespace ReadText.LocalizedDemo
{
public class LocalizableSentenceBuilder : SentenceBuilder
{
public override Func<string> RequiredWord
{
get { return () => Properties.Resources.SentenceRequiredWord; }
}

public override Func<string> ErrorsHeadingText
{
// Cannot be pluralized
get { return () => Properties.Resources.SentenceErrorsHeadingText; }
}

public override Func<string> UsageHeadingText
{
get { return () => Properties.Resources.SentenceUsageHeadingText; }
}

public override Func<bool, string> HelpCommandText
{
get
{
return isOption => isOption
? Properties.Resources.SentenceHelpCommandTextOption
: Properties.Resources.SentenceHelpCommandTextVerb;
}
}

public override Func<bool, string> VersionCommandText
{
get { return _ => Properties.Resources.SentenceVersionCommandText; }
}

public override Func<Error, string> FormatError
{
get
{
return error =>
{
switch (error.Tag)
{
case ErrorType.BadFormatTokenError:
return String.Format(Properties.Resources.SentenceBadFormatTokenError, ((BadFormatTokenError)error).Token);
case ErrorType.MissingValueOptionError:
return String.Format(Properties.Resources.SentenceMissingValueOptionError, ((MissingValueOptionError)error).NameInfo.NameText);
case ErrorType.UnknownOptionError:
return String.Format(Properties.Resources.SentenceUnknownOptionError, ((UnknownOptionError)error).Token);
case ErrorType.MissingRequiredOptionError:
var errMisssing = ((MissingRequiredOptionError)error);
return errMisssing.NameInfo.Equals(NameInfo.EmptyName)
? Properties.Resources.SentenceMissingRequiredOptionError
: String.Format(Properties.Resources.SentenceMissingRequiredOptionError, errMisssing.NameInfo.NameText);
case ErrorType.BadFormatConversionError:
var badFormat = ((BadFormatConversionError)error);
return badFormat.NameInfo.Equals(NameInfo.EmptyName)
? Properties.Resources.SentenceBadFormatConversionErrorValue
: String.Format(Properties.Resources.SentenceBadFormatConversionErrorOption, badFormat.NameInfo.NameText);
case ErrorType.SequenceOutOfRangeError:
var seqOutRange = ((SequenceOutOfRangeError)error);
return seqOutRange.NameInfo.Equals(NameInfo.EmptyName)
? Properties.Resources.SentenceSequenceOutOfRangeErrorValue
: String.Format(Properties.Resources.SentenceSequenceOutOfRangeErrorOption,
seqOutRange.NameInfo.NameText);
case ErrorType.BadVerbSelectedError:
return String.Format(Properties.Resources.SentenceBadVerbSelectedError, ((BadVerbSelectedError)error).Token);
case ErrorType.NoVerbSelectedError:
return Properties.Resources.SentenceNoVerbSelectedError;
case ErrorType.RepeatedOptionError:
return String.Format(Properties.Resources.SentenceRepeatedOptionError, ((RepeatedOptionError)error).NameInfo.NameText);
case ErrorType.SetValueExceptionError:
var setValueError = (SetValueExceptionError)error;
return String.Format(Properties.Resources.SentenceSetValueExceptionError, setValueError.NameInfo.NameText, setValueError.Exception.Message);
}
throw new InvalidOperationException();
};
}
}

public override Func<IEnumerable<MutuallyExclusiveSetError>, string> FormatMutuallyExclusiveSetErrors
{
get
{
return errors =>
{
var bySet = from e in errors
group e by e.SetName into g
select new { SetName = g.Key, Errors = g.ToList() };
var msgs = bySet.Select(
set =>
{
var names = String.Join(
String.Empty,
(from e in set.Errors select String.Format("'{0}', ", e.NameInfo.NameText)).ToArray());
var namesCount = set.Errors.Count();
var incompat = String.Join(
String.Empty,
(from x in
(from s in bySet where !s.SetName.Equals(set.SetName) from e in s.Errors select e)
.Distinct()
select String.Format("'{0}', ", x.NameInfo.NameText)).ToArray());
//TODO: Pluralize by namesCount
return
String.Format(Properties.Resources.SentenceMutuallyExclusiveSetErrors,
names.Substring(0, names.Length - 2), incompat.Substring(0, incompat.Length - 2));
}).ToArray();
return string.Join(Environment.NewLine, msgs);
};
}
}
}
}
69 changes: 69 additions & 0 deletions demo/ReadText.LocalizedDemo/Options.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
using CommandLine;
using CommandLine.Text;
using System.Collections.Generic;

namespace ReadText.LocalizedDemo
{
interface IOptions
{
[Option('n', "lines",
Default = 5U,
SetName = "bylines",
HelpText = "HelpTextLines",
ResourceType = typeof(Properties.Resources))]
uint? Lines { get; set; }

[Option('c', "bytes",
SetName = "bybytes",
HelpText = "HelpTextBytes",
ResourceType = typeof(Properties.Resources))]
uint? Bytes { get; set; }

[Option('q', "quiet",
HelpText = "HelpTextQuiet",
ResourceType = typeof(Properties.Resources))]
bool Quiet { get; set; }

[Value(0, MetaName = "input file",
HelpText = "HelpTextFileName",
Required = true,
ResourceType = typeof(Properties.Resources))]
string FileName { get; set; }
}

[Verb("head", HelpText = "HelpTextVerbHead", ResourceType = typeof(Properties.Resources))]
class HeadOptions : IOptions
{
public uint? Lines { get; set; }

public uint? Bytes { get; set; }

public bool Quiet { get; set; }

public string FileName { get; set; }

[Usage(ApplicationAlias = "ReadText.LocalizedDemo.exe")]
public static IEnumerable<Example> Examples
{
get
{
yield return new Example(Properties.Resources.ExamplesNormalScenario, new HeadOptions { FileName = "file.bin"});
yield return new Example(Properties.Resources.ExamplesSpecifyBytes, new HeadOptions { FileName = "file.bin", Bytes=100 });
yield return new Example(Properties.Resources.ExamplesSuppressSummary, UnParserSettings.WithGroupSwitchesOnly(), new HeadOptions { FileName = "file.bin", Quiet = true });
yield return new Example(Properties.Resources.ExamplesReadMoreLines, new[] { UnParserSettings.WithGroupSwitchesOnly(), UnParserSettings.WithUseEqualTokenOnly() }, new HeadOptions { FileName = "file.bin", Lines = 10 });
}
}
}

[Verb("tail", HelpText = "HelpTextVerbTail", ResourceType = typeof(Properties.Resources))]
class TailOptions : IOptions
{
public uint? Lines { get; set; }

public uint? Bytes { get; set; }

public bool Quiet { get; set; }

public string FileName { get; set; }
}
}
83 changes: 83 additions & 0 deletions demo/ReadText.LocalizedDemo/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using CommandLine;
using CommandLine.Text;

namespace ReadText.LocalizedDemo
{
class Program
{
public static int Main(string[] args)
{
// Set sentence builder to localizable
SentenceBuilder.Factory = () => new LocalizableSentenceBuilder();

Func<IOptions, string> reader = opts =>
{
var fromTop = opts.GetType() == typeof(HeadOptions);
return opts.Lines.HasValue
? ReadLines(opts.FileName, fromTop, (int)opts.Lines)
: ReadBytes(opts.FileName, fromTop, (int)opts.Bytes);
};
Func<IOptions, string> header = opts =>
{
if (opts.Quiet)
{
return string.Empty;
}
var fromTop = opts.GetType() == typeof(HeadOptions);
var builder = new StringBuilder(Properties.Resources.Reading);
builder = opts.Lines.HasValue
? builder.Append(opts.Lines).Append(Properties.Resources.Lines)
: builder.Append(opts.Bytes).Append(Properties.Resources.Bytes);
builder = fromTop ? builder.Append(Properties.Resources.FromTop) : builder.Append(Properties.Resources.FromBottom);
return builder.ToString();
};
Action<string> printIfNotEmpty = text =>
{
if (text.Length == 0) { return; }
Console.WriteLine(text);
};

var result = Parser.Default.ParseArguments<HeadOptions, TailOptions>(args);
var texts = result
.MapResult(
(HeadOptions opts) => Tuple.Create(header(opts), reader(opts)),
(TailOptions opts) => Tuple.Create(header(opts), reader(opts)),
_ => MakeError());

printIfNotEmpty(texts.Item1);
printIfNotEmpty(texts.Item2);

return texts.Equals(MakeError()) ? 1 : 0;
}

private static string ReadLines(string fileName, bool fromTop, int count)
{
var lines = File.ReadAllLines(fileName);
if (fromTop)
{
return string.Join(Environment.NewLine, lines.Take(count));
}
return string.Join(Environment.NewLine, lines.Reverse().Take(count));
}

private static string ReadBytes(string fileName, bool fromTop, int count)
{
var bytes = File.ReadAllBytes(fileName);
if (fromTop)
{
return Encoding.UTF8.GetString(bytes, 0, count);
}
return Encoding.UTF8.GetString(bytes, bytes.Length - count, count);
}

private static Tuple<string, string> MakeError()
{
return Tuple.Create("\0", "\0");
}
}
}
11 changes: 11 additions & 0 deletions demo/ReadText.LocalizedDemo/Properties/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
using System.Reflection;
using System.Runtime.CompilerServices;

[assembly: AssemblyTitle("ReadText.Demo")]
[assembly: AssemblyDescription("ReadText.Demo for Command Line Parser Library")]
[assembly: AssemblyTrademark("")]
#if DEBUG
[assembly: AssemblyConfiguration("Debug")]
#else
[assembly: AssemblyConfiguration("Release")]
#endif
Loading

0 comments on commit 7ede4da

Please sign in to comment.