forked from commandlineparser/commandline
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProgram.cs
83 lines (75 loc) · 3.01 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
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");
}
}
}