-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCSV.cs
301 lines (260 loc) · 9.29 KB
/
CSV.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using UnityEditor;
namespace Minerva.Module
{
public interface IRow : IEnumerable<string>
{
string this[string col] { get; set; }
string Name { get; }
int Count { get; }
public static IRow Of(string name, Dictionary<string, string> value)
{
return new Row(name, value);
}
struct Row : IRow
{
string key;
Dictionary<string, string> value;
public Row(KeyValuePair<string, Dictionary<string, string>> item)
{
this.key = item.Key;
this.value = item.Value;
}
public Row(string Key, Dictionary<string, string> Value)
{
this.key = Key;
this.value = Value;
}
public string this[string col] { get => value[col]; set => this.value[col] = value; }
public string Name => key;
public int Count => value.Count;
public IEnumerator<string> GetEnumerator()
{
return value.Values.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return value.Values.GetEnumerator();
}
}
}
public interface ITable : IEnumerable, IEnumerable<IRow>
{
string this[string row, string col] { get; set; }
IRow this[string row] { get; }
int Count { get; }
string[] ColumnNames { get; }
string[] RowNames { get; }
IRow GetOrCreateRow(string rowName);
public static Dictionary<string, Dictionary<string, string>> ToDictionaries(ITable table)
{
var @this = table;
Dictionary<string, Dictionary<string, string>> res = new Dictionary<string, Dictionary<string, string>>();
foreach (var rowName in @this.RowNames)
{
Dictionary<string, string> t = new();
res.Add(rowName, t);
var row = @this[rowName];
foreach (var colName in @this.ColumnNames)
{
t.Add(colName, row[colName]);
}
}
return res;
}
public static void Convert<TSource, TTarget>(TSource sourceTable, TTarget target) where TSource : ITable where TTarget : ITable
{
foreach (var rowName in sourceTable.RowNames)
{
IRow targetRow = target.GetOrCreateRow(rowName);
IRow sourceRow = sourceTable[rowName];
foreach (var colName in sourceTable.ColumnNames)
{
targetRow[colName] = sourceRow[colName];
}
}
}
public static TTarget Convert<TSource, TTarget>(TSource sourceTable) where TSource : ITable where TTarget : ITable, new()
{
var target = new TTarget();
Convert(sourceTable, target);
return target;
}
}
public class CSVFile : ITable
{
public Dictionary<string, Dictionary<string, string>> table;
public string[] cols;
public string[] rows;
public CSVFile()
{
table = new();
cols = Array.Empty<string>();
rows = Array.Empty<string>();
}
public IRow this[string row] => throw new System.NotImplementedException();
public string this[string row, string col] { get => throw new System.NotImplementedException(); set => throw new System.NotImplementedException(); }
public int Count => table.Count;
public string[] ColumnNames => cols;
public string[] RowNames => rows;
public IRow GetOrCreateRow(string rowName)
{
if (table.TryGetValue(rowName, out var value))
return IRow.Of(rowName, value);
Array.Resize(ref rows, rows.Length + 1);
rows[^1] = rowName;
value = new Dictionary<string, string>();
table.Add(rowName, value);
return IRow.Of(rowName, value);
}
public IEnumerator<IRow> GetEnumerator()
{
foreach (var item in table)
{
yield return IRow.Of(item.Key, item.Value);
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
/// <summary>
/// The CSV Reader/Writer used in lcoalization
/// </summary>
public static class CSV
{
private const char CSV_SEPARATOR = ',';
public static string ConvertToCSV(string name, ITable table)
{
StringBuilder sb = new(name);
sb.Append(CSV_SEPARATOR);
sb.Append(string.Join(CSV_SEPARATOR, table.ColumnNames));
sb.Append('\n');
foreach (var item in table)
{
sb.Append(item.Name);
sb.Append(CSV_SEPARATOR);
sb.AppendJoin(CSV_SEPARATOR, table.ColumnNames.Select(r => item[r]).Select(
text => text.Contains('"') || text.Contains(',')
? $"\"{ToProperyString(text)}\""
: text));
sb.Append("\n");
}
return sb.ToString();
}
private static string ToProperyString(string text)
{
StringBuilder builder = new StringBuilder();
foreach (char c in text)
{
switch (c)
{
case '\r':
continue;
case '\n':
builder.Append("\\n");
break;
case '"':
builder.Append('"', 2);
break;
default:
builder.Append(c);
break;
}
}
return builder.ToString();
}
public static CSVFile Import(string path)
{
string input = File.ReadAllText(path);
var file = new CSVFile();
var entries = new Queue<string>(input.Split('\n'));
file.cols = entries.Dequeue().Split(CSV_SEPARATOR)[1..].ToArray();
var rows = new List<string>();
while (entries.Count != 0)
{
var entry = entries.Dequeue();
if (string.IsNullOrEmpty(entry) || string.IsNullOrWhiteSpace(entry)) continue;
List<string> words = GetWords(entry);
while (file.cols.Length > words.Count - 1)
{
words.Add(string.Empty);
//Debug.LogError(file.cols.Count);
//Debug.LogError(words.Count);
//foreach (var item in words)
//{
// Debug.Log(item);
//}
//throw new InvalidDataException();
}
string row = words[0];
rows.Add(row);
words.RemoveAt(0);
var dict = new Dictionary<string, string>();
for (int i = 0; i < file.cols.Length; i++)
{
dict.Add(file.cols[i], words[i]);
}
file.table.Add(row, dict);
}
file.rows = rows.ToArray();
return file;
}
private static List<string> GetWords(string entry)
{
List<string> words = new();
StringBuilder stringBuilder = new StringBuilder();
bool isInQuote = false;
for (int i = 0; i < entry.Length; i++)
{
char c = entry[i];
switch (c)
{
case ',':
// in quote, save
if (isInQuote)
{
stringBuilder.Append(c);
}
// not in quote, end of word
else
{
words.Add(stringBuilder.ToString());
stringBuilder.Clear();
}
break;
case '\"':
// start of a new word, start with "
if (!isInQuote && stringBuilder.Length == 0)
{
isInQuote = true;
continue;
}
// a "", means literal "
if (i + 1 < entry.Length && entry[i + 1] == '\"')
{
stringBuilder.Append(c);
i++;
}
// else the end of the word
else
{
isInQuote = false;
}
break;
default:
stringBuilder.Append(c);
break;
}
}
words.Add(stringBuilder.ToString());
return words;
}
}
}