-
Notifications
You must be signed in to change notification settings - Fork 249
Expand file tree
/
Copy pathIniDataParser.cs
More file actions
468 lines (402 loc) · 16.9 KB
/
IniDataParser.cs
File metadata and controls
468 lines (402 loc) · 16.9 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
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
using System;
using System.Collections.Generic;
using IniParser.Exceptions;
using IniParser.Model;
using IniParser.Model.Configuration;
using System.Collections.ObjectModel;
namespace IniParser.Parser
{
/// <summary>
/// Responsible for parsing an string from an ini file, and creating
/// an <see cref="IniData"/> structure.
/// </summary>
public class IniDataParser
{
#region Private
// Holds a list of the exceptions catched while parsing
private List<Exception> _errorExceptions;
#endregion
#region Initialization
/// <summary>
/// Ctor
/// </summary>
/// <remarks>
/// The parser uses a <see cref="IniParserConfiguration"/> by default
/// </remarks>
public IniDataParser()
: this(new IniParserConfiguration())
{ }
/// <summary>
/// Ctor
/// </summary>
/// <param name="parserConfiguration">
/// Parser's <see cref="IniParserConfiguration"/> instance.
/// </param>
public IniDataParser(IniParserConfiguration parserConfiguration)
{
if (parserConfiguration == null)
throw new ArgumentNullException("parserConfiguration");
Configuration = parserConfiguration;
_errorExceptions = new List<Exception>();
}
#endregion
#region State
/// <summary>
/// Configuration that defines the behaviour and constraints
/// that the parser must follow.
/// </summary>
public virtual IniParserConfiguration Configuration { get; protected set; }
/// <summary>
/// True is the parsing operation encounter any problem
/// </summary>
public bool HasError { get { return _errorExceptions.Count > 0; } }
/// <summary>
/// Returns the list of errors found while parsing the ini file.
/// </summary>
/// <remarks>
/// If the configuration option ThrowExceptionOnError is false it can contain one element
/// for each problem found while parsing; otherwise it will only contain the very same
/// exception that was raised.
/// </remarks>
public ReadOnlyCollection<Exception> Errors {get {return _errorExceptions.AsReadOnly();} }
#endregion
#region Operations
/// <summary>
/// Parses a string containing valid ini data
/// </summary>
/// <param name="iniDataString">
/// String with data
/// </param>
/// <returns>
/// An <see cref="IniData"/> instance with the data contained in
/// the <paramref name="iniDataString"/> correctly parsed an structured.
/// </returns>
/// <exception cref="ParsingException">
/// Thrown if the data could not be parsed
/// </exception>
public IniData Parse(string iniDataString)
{
IniData iniData = Configuration.CaseInsensitive ? new IniDataCaseInsensitive() : new IniData();
iniData.Configuration = this.Configuration.Clone();
if (string.IsNullOrEmpty(iniDataString))
{
return iniData;
}
_errorExceptions.Clear();
_currentCommentListTemp.Clear();
_currentSectionNameTemp = null;
try
{
var lines = iniDataString.Split(new []{"\n", "\r\n"}, StringSplitOptions.None);
for (int lineNumber = 0; lineNumber < lines.Length; lineNumber++)
{
var line = lines[lineNumber];
if (line.Trim() == String.Empty) continue;
try
{
ProcessLine(line, iniData);
}
catch (Exception ex)
{
var errorEx = new ParsingException(ex.Message, lineNumber+1, line, ex);
if (Configuration.ThrowExceptionsOnError)
{
throw errorEx;
}
else
{
_errorExceptions.Add(errorEx);
}
}
}
// Orphan comments, assing to last section/key value
if (_currentCommentListTemp.Count > 0)
{
// Check if there are actually sections in the file
if (iniData.Sections.Count > 0)
{
iniData.Sections.GetSectionData(_currentSectionNameTemp).TrailingComments
.AddRange(_currentCommentListTemp);
}
// No sections, put the comment in the last key value pair
// but only if the ini file contains at least one key-value pair
else if (iniData.Global.Count > 0)
{
iniData.Global.GetLast().Comments
.AddRange(_currentCommentListTemp);
}
_currentCommentListTemp.Clear();
}
}
catch(Exception ex)
{
_errorExceptions.Add(ex);
if (Configuration.ThrowExceptionsOnError)
{
throw;
}
}
if (HasError) return null;
return (IniData)iniData.Clone();
}
#endregion
#region Template Method Design Pattern
// All this methods controls the parsing behaviour, so it can be modified
// in derived classes.
// See http://www.dofactory.com/Patterns/PatternTemplate.aspx for an
// explanation of this pattern.
// Probably for the most common cases you can change the parsing behavior
// using a custom configuration object rather than creating derived classes.
// See IniParserConfiguration interface, and IniDataParser constructor
// to change the default configuration.
/// <summary>
/// Checks if a given string contains a comment.
/// </summary>
/// <param name="line">
/// String with a line to be checked.
/// </param>
/// <returns>
/// <c>true</c> if any substring from s is a comment, <c>false</c> otherwise.
/// </returns>
protected virtual bool LineContainsAComment(string line)
{
return !string.IsNullOrEmpty(line)
&& Configuration.CommentRegex.Match(line).Success;
}
/// <summary>
/// Checks if a given string represents a section delimiter.
/// </summary>
/// <param name="line">
/// The string to be checked.
/// </param>
/// <returns>
/// <c>true</c> if the string represents a section, <c>false</c> otherwise.
/// </returns>
protected virtual bool LineMatchesASection(string line)
{
return !string.IsNullOrEmpty(line)
&& Configuration.SectionRegex.Match(line).Success;
}
/// <summary>
/// Checks if a given string represents a key / value pair.
/// </summary>
/// <param name="line">
/// The string to be checked.
/// </param>
/// <returns>
/// <c>true</c> if the string represents a key / value pair, <c>false</c> otherwise.
/// </returns>
protected virtual bool LineMatchesAKeyValuePair(string line)
{
return !string.IsNullOrEmpty(line) && line.Contains(Configuration.KeyValueAssigmentChar.ToString());
}
/// <summary>
/// Removes a comment from a string if exist, and returns the string without
/// the comment substring.
/// </summary>
/// <param name="line">
/// The string we want to remove the comments from.
/// </param>
/// <returns>
/// The string s without comments.
/// </returns>
protected virtual string ExtractComment(string line)
{
string comment = Configuration.CommentRegex.Match(line).Value.Trim();
_currentCommentListTemp.Add(comment.Substring(1, comment.Length - 1));
return line.Replace(comment, "").Trim();
}
/// <summary>
/// Processes one line and parses the data found in that line
/// (section or key/value pair who may or may not have comments)
/// </summary>
/// <param name="currentLine">The string with the line to process</param>
protected virtual void ProcessLine(string currentLine, IniData currentIniData)
{
currentLine = currentLine.Trim();
// Extract comments from current line and store them in a tmp field
if (LineContainsAComment(currentLine))
{
currentLine = ExtractComment(currentLine);
}
// By default comments must span a complete line (i.e. the comment character
// must be located at the beginning of a line, so it seems that the following
// check is not needed.
// But, if the comment parsing behaviour is changed in a derived class e.g. to
// to allow parsing comment characters in the middle of a line, the implementor
// will be forced to rewrite this complete method.
// That was actually the behaviour for parsing comments
// in earlier versions of the library, so checking if the current line is empty
// (meaning the complete line was a comment) is future-proof.
// If the entire line was a comment now should be empty,
// so no further processing is needed.
if (currentLine == String.Empty)
return;
//Process sections
if (LineMatchesASection(currentLine))
{
ProcessSection(currentLine, currentIniData);
return;
}
//Process keys
if (LineMatchesAKeyValuePair(currentLine))
{
ProcessKeyValuePair(currentLine, currentIniData);
return;
}
if (Configuration.SkipInvalidLines)
return;
throw new ParsingException(
"Unknown file format. Couldn't parse the line: '" + currentLine + "'.");
}
/// <summary>
/// Proccess a string which contains an ini section.
/// </summary>
/// <param name="line">
/// The string to be processed
/// </param>
protected virtual void ProcessSection(string line, IniData currentIniData)
{
// Get section name with delimiters from line...
string sectionName = Configuration.SectionRegex.Match(line).Value.Trim();
// ... and remove section's delimiters to get just the name
sectionName = sectionName.Substring(1, sectionName.Length - 2).Trim();
// Check that the section's name is not empty
if (sectionName == string.Empty)
{
throw new ParsingException("Section name is empty");
}
// Temporally save section name.
_currentSectionNameTemp = sectionName;
//Checks if the section already exists
if (currentIniData.Sections.ContainsSection(sectionName))
{
if (Configuration.AllowDuplicateSections)
{
return;
}
throw new ParsingException(string.Format("Duplicate section with name '{0}' on line '{1}'", sectionName, line));
}
// If the section does not exists, add it to the ini data
currentIniData.Sections.AddSection(sectionName);
// Save comments read until now and assign them to this section
currentIniData.Sections.GetSectionData(sectionName).LeadingComments = _currentCommentListTemp;
_currentCommentListTemp.Clear();
}
/// <summary>
/// Processes a string containing an ini key/value pair.
/// </summary>
/// <param name="line">
/// The string to be processed
/// </param>
protected virtual void ProcessKeyValuePair(string line, IniData currentIniData)
{
// get key and value data
string key = ExtractKey(line);
if (string.IsNullOrEmpty(key) && Configuration.SkipInvalidLines) return;
string value = ExtractValue(line);
// Check if we haven't read any section yet
if (string.IsNullOrEmpty(_currentSectionNameTemp))
{
if (!Configuration.AllowKeysWithoutSection)
{
throw new ParsingException("key value pairs must be enclosed in a section");
}
AddKeyToKeyValueCollection(key, value, currentIniData.Global, "global");
}
else
{
var currentSection = currentIniData.Sections.GetSectionData(_currentSectionNameTemp);
AddKeyToKeyValueCollection(key, value, currentSection.Keys, _currentSectionNameTemp);
}
}
/// <summary>
/// Extracts the key portion of a string containing a key/value pair..
/// </summary>
/// <param name="s">
/// The string to be processed, which contains a key/value pair
/// </param>
/// <returns>
/// The name of the extracted key.
/// </returns>
protected virtual string ExtractKey(string s)
{
int index = s.IndexOf(Configuration.KeyValueAssigmentChar, 0);
return s.Substring(0, index).Trim();
}
/// <summary>
/// Extracts the value portion of a string containing a key/value pair..
/// </summary>
/// <param name="s">
/// The string to be processed, which contains a key/value pair
/// </param>
/// <returns>
/// The name of the extracted value.
/// </returns>
protected virtual string ExtractValue(string s)
{
int index = s.IndexOf(Configuration.KeyValueAssigmentChar, 0);
return s.Substring(index + 1, s.Length - index - 1).Trim();
}
/// <summary>
/// Abstract Method that decides what to do in case we are trying to add a duplicated key to a section
/// </summary>
protected virtual void HandleDuplicatedKeyInCollection(string key, string value, KeyDataCollection keyDataCollection, string sectionName)
{
if (!Configuration.AllowDuplicateKeys)
{
throw new ParsingException(string.Format("Duplicated key '{0}' found in section '{1}", key, sectionName));
}
else if(Configuration.OverrideDuplicateKeys)
{
keyDataCollection[key] = value;
}
}
#endregion
#region Helpers
/// <summary>
/// Adds a key to a concrete <see cref="KeyDataCollection"/> instance, checking
/// if duplicate keys are allowed in the configuration
/// </summary>
/// <param name="key">
/// Key name
/// </param>
/// <param name="value">
/// Key's value
/// </param>
/// <param name="keyDataCollection">
/// <see cref="KeyData"/> collection where the key should be inserted
/// </param>
/// <param name="sectionName">
/// Name of the section where the <see cref="KeyDataCollection"/> is contained.
/// Used only for logging purposes.
/// </param>
private void AddKeyToKeyValueCollection(string key, string value, KeyDataCollection keyDataCollection, string sectionName)
{
// Check for duplicated keys
if (keyDataCollection.ContainsKey(key))
{
// We already have a key with the same name defined in the current section
HandleDuplicatedKeyInCollection(key, value, keyDataCollection, sectionName);
}
else
{
// Save the keys
keyDataCollection.AddKey(key, value);
}
keyDataCollection.GetKeyData(key).Comments = _currentCommentListTemp;
_currentCommentListTemp.Clear();
}
#endregion
#region Fields
/// <summary>
/// Temp list of comments
/// </summary>
private readonly List<string> _currentCommentListTemp = new List<string>();
/// <summary>
/// Tmp var with the name of the seccion which is being process
/// </summary>
private string _currentSectionNameTemp;
#endregion
}
}