BadScript 2
Loading...
Searching...
No Matches
Program.cs
Go to the documentation of this file.
1using System;
2using System.Collections.Generic;
3using System.IO;
4using System.Linq;
5using System.Text;
6using CommandLine;
8
9namespace ReadText.Demo
10{
11 class Program
12 {
13 public static int Main(string[] args)
14 {
15 Func<IOptions, string> reader = opts =>
16 {
17 var fromTop = opts.GetType() == typeof(HeadOptions);
18 return opts.Lines.HasValue
19 ? ReadLines(opts.FileName, fromTop, (int)opts.Lines)
20 : ReadBytes(opts.FileName, fromTop, (int)opts.Bytes);
21 };
22 Func<IOptions, string> header = opts =>
23 {
24 if (opts.Quiet)
25 {
26 return string.Empty;
27 }
28 var fromTop = opts.GetType() == typeof(HeadOptions);
29 var builder = new StringBuilder("Reading ");
30 builder = opts.Lines.HasValue
31 ? builder.Append(opts.Lines).Append(" lines")
32 : builder.Append(opts.Bytes).Append(" bytes");
33 builder = fromTop ? builder.Append(" from top:") : builder.Append(" from bottom:");
34 return builder.ToString();
35 };
36 Action<string> printIfNotEmpty = text =>
37 {
38 if (text.Length == 0) { return; }
39 Console.WriteLine(text);
40 };
41
43 var texts = result
44 .MapResult(
45 (HeadOptions opts) => Tuple.Create(header(opts), reader(opts)),
46 (TailOptions opts) => Tuple.Create(header(opts), reader(opts)),
47 _ => MakeError());
48
49 printIfNotEmpty(texts.Item1);
50 printIfNotEmpty(texts.Item2);
51
52 return texts.Equals(MakeError()) ? 1 : 0;
53 }
54
55 private static string ReadLines(string fileName, bool fromTop, int count)
56 {
57 var lines = File.ReadAllLines(fileName);
58 if (fromTop)
59 {
60 return string.Join(Environment.NewLine, lines.Take(count));
61 }
62 return string.Join(Environment.NewLine, lines.Reverse().Take(count));
63 }
64
65 private static string ReadBytes(string fileName, bool fromTop, int count)
66 {
67 var bytes = File.ReadAllBytes(fileName);
68 if (fromTop)
69 {
70 return Encoding.UTF8.GetString(bytes, 0, count);
71 }
72 return Encoding.UTF8.GetString(bytes, bytes.Length - count, count);
73 }
74
75 private static Tuple<string, string> MakeError()
76 {
77 return Tuple.Create("\0", "\0");
78 }
79 }
80}
Provides methods to parse command line arguments.
Definition Parser.cs:21
ParserResult< object > ParseArguments(IEnumerable< string > args, params Type[] types)
Parses a string array of command line arguments for verb commands scenario, constructing the proper i...
Definition Parser.cs:216
static Parser Default
Gets the singleton instance created with basic defaults.
Definition Parser.cs:75
static Tuple< string, string > MakeError()
Definition Program.cs:75
static string ReadBytes(string fileName, bool fromTop, int count)
Definition Program.cs:65
static int Main(string[] args)
Definition Program.cs:13
static string ReadLines(string fileName, bool fromTop, int count)
Definition Program.cs:55