-
Notifications
You must be signed in to change notification settings - Fork 105
/
Copy pathConfigurationConverter.cs
108 lines (94 loc) · 3.45 KB
/
ConfigurationConverter.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
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Xml.Linq;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.LanguageServer.Protocol;
namespace OmniSharp.Extensions.LanguageServer.Server.Configuration
{
class ConfigurationConverter
{
public void ParseClientConfiguration(IDictionary<string, string> data, JToken settings, string prefix = null)
{
if (settings == null || settings.Type == JTokenType.Null || settings.Type == JTokenType.None) return;
// The null request (appears) to always come second
// this handler is set to use the SerialAttribute
// TODO: Figure out the best way to plugin to handle additional configurations (toml, yaml?)
try
{
foreach (var item in
JObject.FromObject(settings)
.Descendants()
.Where(p => !p.Any())
.OfType<JValue>()
.Select(
item =>
new KeyValuePair<string, string>(
GetKey(item, prefix),
item.ToString(CultureInfo.InvariantCulture)
)
))
{
data[item.Key] = item.Value;
}
}
catch (JsonReaderException)
{
// Might not have been json... try xml.
foreach (var item in
XDocument.Parse(settings.ToString())
.Descendants()
.Where(p => !p.Descendants().Any())
.Select(
item =>
new KeyValuePair<string, string>(GetKey(item, prefix), item.ToString())
))
{
data[item.Key] = item.Value;
}
}
}
private static string GetKey(JToken token, string prefix)
{
var items = new Stack<string>();
while (token.Parent != null)
{
if (token.Parent is JArray arr)
{
items.Push(arr.IndexOf(token).ToString());
}
if (token is JProperty p)
{
items.Push(p.Name);
}
token = token.Parent;
}
if (!string.IsNullOrWhiteSpace(prefix))
{
items.Push(prefix);
}
return string.Join(":", items);
}
private static string GetKey(XElement token, string prefix)
{
var items = new Stack<string>();
while (token.Parent != null)
{
if (token.Parent.Elements().Count() > 1)
{
items.Push(Array.IndexOf(token.Parent.Elements().ToArray(), token).ToString());
}
items.Push(token.Name.ToString());
token = token.Parent;
}
if (!string.IsNullOrWhiteSpace(prefix))
{
items.Push(prefix);
}
return string.Join(":", items);
}
}
}