-
Notifications
You must be signed in to change notification settings - Fork 0
/
Program.cs
110 lines (101 loc) · 3.23 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
99
100
101
102
103
104
105
106
107
108
109
110
using MicroBatchFramework;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Reflection;
using Newtonsoft.Json;
namespace csjo
{
public class CsJo : BatchBase
{
public void Convert(
[Option(0)]string input,
[Option("a", "is array.")]bool isArray = false,
[Option("p", "pretty print json.")]bool pretty = false)
{
if (isArray)
{
Console.WriteLine(this.ConvertArrayToJson(input, pretty));
}
else
{
Console.WriteLine(this.ConvertObjToJson(input, pretty));
}
}
[Command("version")]
public void ShowVersion([Option("p", "pretty print json.")]bool pretty = false)
{
Console.WriteLine(JsonConvert.SerializeObject(new Dictionary<string, object>() {
{ "Program", "csjo" },
{ "Description", "This is inspired by jpmens/jo and skanehira/gjo" },
{ "Author", "orange634nty" },
{ "Repo", "https://github.com/orange634nty/csjo" },
{ "Version", "1.0.1" }
}, pretty ? Formatting.Indented : Formatting.None));
}
private string ConvertArrayToJson(string arr, bool pretty)
{
return JsonConvert.SerializeObject(
arr.Split(" ").Select(a => this.ConvertValue(a)),
pretty ? Formatting.Indented : Formatting.None
);
}
private string ConvertObjToJson(string obj, bool pretty)
{
var res = new Dictionary<string, object>();
foreach (string el in obj.Split(" "))
{
string[] keyValue = el.Split("=");
if (keyValue.Length == 2)
{
res.Add(keyValue[0], this.ConvertValue(keyValue[1]));
}
else
{
throw new CsJoException($"wrong format : {el}");
}
}
return JsonConvert.SerializeObject(res, pretty ? Formatting.Indented : Formatting.None);
}
private dynamic ConvertValue(string value)
{
// object
if (value.StartsWith("{") && value.EndsWith("}"))
{
return JsonConvert.DeserializeObject(value);
}
// array
if (value.StartsWith("[") && value.EndsWith("]"))
{
return JsonConvert.DeserializeObject(value);
}
// try to parse string to int
try
{
return Int32.Parse(value);
}
catch (FormatException)
{
return value;
}
catch(Exception e)
{
throw e;
}
}
}
public class CsJoException : Exception
{
public CsJoException(string message) : base(message) { }
}
class Program
{
static async Task Main(string[] args)
{
await new HostBuilder().RunBatchEngineAsync<CsJo>(args);
}
}
}