-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathProgram.cs
98 lines (80 loc) · 2.49 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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
namespace WinHaste
{
class Program
{
private static readonly Regex _HasteKeyRegex = new Regex(@"{""key"":""(?<key>[a-z].*)""}", RegexOptions.Compiled);
[STAThread]
static async Task Main(string[] args)
{
var parameters = new Parameters(args);
var parseResult = parameters.Parse();
if (parseResult != Parameters.ParseResult.Success)
{
Console.WriteLine(parameters.Usage);
Console.WriteLine(Environment.NewLine + "ERROR: " + parseResult);
return;
}
var haste = !String.IsNullOrEmpty(parameters.FilePath)
? ReadFile(parameters.FilePath)
: ReadStdin();
Console.WriteLine($"{Environment.NewLine}Uploading...");
using (var client = new WebClient())
{
var response = await client.UploadStringTaskAsync(parameters.Url + "/documents", haste);
var match = _HasteKeyRegex.Match(response);
if (!match.Success)
{
Console.WriteLine(response);
return;
}
string hasteUrl = String.Concat(parameters.Url, "/", match.Groups["key"]);
string copyMessage = Clipboard.Copy(hasteUrl) ? " (copied to clipboard)" : string.Empty;
Console.WriteLine($"Haste URL: {hasteUrl}{copyMessage}{Environment.NewLine}", hasteUrl);
}
}
private static string ReadFile(string filePath)
{
using (var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var streamReader = new StreamReader(fileStream, Encoding.UTF8, true))
{
return streamReader.ReadToEnd();
}
}
private static string ReadStdin()
{
bool piped = IsInputPiped();
var haste = String.Empty;
int consoleKey = Console.Read();
while (consoleKey != -1)
{
var consoleChar = Convert.ToChar(consoleKey);
if (piped)
{
Console.Write(consoleChar);
Console.Out.Flush();
}
haste += consoleChar;
consoleKey = Console.Read();
}
return haste;
}
private static bool IsInputPiped()
{
try
{
var tmp = Console.KeyAvailable;
return false;
}
catch (InvalidOperationException)
{
return true;
}
}
}
}