forked from scriptcs/scriptcs
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConfigFileParser.cs
More file actions
93 lines (78 loc) · 3.1 KB
/
ConfigFileParser.cs
File metadata and controls
93 lines (78 loc) · 3.1 KB
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using Newtonsoft.Json;
using PowerArgs;
using ScriptCs.Contracts;
namespace ScriptCs.Argument
{
public class ConfigFileParser : IConfigFileParser
{
private readonly IConsole _console;
public ConfigFileParser(IConsole console)
{
_console = console;
}
public ScriptCsArgs Parse(string content)
{
if (!string.IsNullOrWhiteSpace(content))
{
var fromJson = ParseJson(content);
if (fromJson != null)
{
var arguments = new ScriptCsArgs();
var configFileValues = new Dictionary<string, string>(fromJson, StringComparer.InvariantCultureIgnoreCase);
foreach (var property in typeof(ScriptCsArgs).GetProperties(BindingFlags.Instance | BindingFlags.Public))
{
string key = "";
if (configFileValues.ContainsKey(property.Name))
{
key = property.Name;
}
else
{
var attributes = property.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
if (attributes.ContainsKey(typeof(ArgIgnoreAttribute).Name)) continue;
if (attributes.ContainsKey(typeof(ArgShortcut).Name))
{
var attribute = (attributes[typeof(ArgShortcut).Name] as ArgShortcut);
if (attribute != null)
{
if (string.IsNullOrEmpty(key) && configFileValues.ContainsKey(attribute.Shortcut))
{
key = attribute.Shortcut;
}
}
}
}
if (!string.IsNullOrEmpty(key))
{
string value = configFileValues[key];
var converter = TypeDescriptor.GetConverter(property.PropertyType);
var result = converter.ConvertFrom(value);
property.SetValue(arguments, result);
}
}
return arguments;
}
}
return null;
}
private Dictionary<string, string> ParseJson(string content)
{
Dictionary<string, string> dict = null;
try
{
dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(content);
}
catch
{
_console.WriteLine("Error parsing configuration file.");
}
return dict;
}
}
}