-
-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathConfig.cs
More file actions
1052 lines (957 loc) · 35.7 KB
/
Copy pathConfig.cs
File metadata and controls
1052 lines (957 loc) · 35.7 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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using NpgsqlRest;
namespace NpgsqlRestClient;
public class Config
{
public IConfigurationRoot Cfg { get; private set; } = null!;
public IConfigurationSection NpgsqlRestCfg { get; private set; } = null!;
public IConfigurationSection ConnectionSettingsCfg { get; private set; } = null!;
public bool UseJsonApplicationName { get; private set; }
public string CurrentDir => Directory.GetCurrentDirectory();
public Dictionary<string, string>? EnvDict { get; private set; } = null;
public string? ConfigFilter { get; private set; }
public void Build(string[] args, string[] skip)
{
if (args.Length >= 1 && skip.Contains(args[0], StringComparer.CurrentCultureIgnoreCase))
{
args = [];
}
var tempBuilder = new ConfigurationBuilder();
IConfigurationRoot tempCfg;
var arguments = new Out();
var (configFiles, commandLineArgs) = BuildFromArgs(args);
if (configFiles.Count > 0)
{
foreach (var (fileName, optional) in configFiles)
{
tempBuilder.AddJsonFile(Path.GetFullPath(fileName, CurrentDir), optional: optional);
}
tempCfg = tempBuilder.Build();
}
else
{
tempCfg = tempBuilder
.AddJsonFile(Path.GetFullPath("appsettings.json", CurrentDir), optional: true)
.AddJsonFile(Path.GetFullPath("appsettings.Development.json", CurrentDir), optional: true)
.Build();
}
var cfgCfg = tempCfg.GetSection("Config");
ConfigurationBuilder configBuilder = new();
var useEnv = cfgCfg != null && GetConfigBool("AddEnvironmentVariables", cfgCfg);
if (configFiles.Count > 0)
{
foreach (var (fileName, optional) in configFiles)
{
configBuilder.AddJsonFile(Path.GetFullPath(fileName, CurrentDir), optional: optional);
}
if (useEnv)
{
configBuilder.AddEnvironmentVariables();
}
configBuilder.AddCommandLine(commandLineArgs);
Cfg = configBuilder.Build();
}
else
{
if (useEnv)
{
Cfg = configBuilder
.AddJsonFile(Path.GetFullPath("appsettings.json", CurrentDir), optional: true)
.AddJsonFile(Path.GetFullPath("appsettings.Development.json", CurrentDir), optional: true)
.AddEnvironmentVariables()
.AddCommandLine(commandLineArgs)
.Build();
}
else
{
Cfg = configBuilder
.AddJsonFile(Path.GetFullPath("appsettings.json", CurrentDir), optional: true)
.AddJsonFile(Path.GetFullPath("appsettings.Development.json", CurrentDir), optional: true)
.AddCommandLine(commandLineArgs)
.Build();
}
}
NpgsqlRestCfg = Cfg.GetSection("NpgsqlRest");
ConnectionSettingsCfg = Cfg.GetSection("ConnectionSettings");
var parseEnv = cfgCfg != null && GetConfigBool("ParseEnvironmentVariables", cfgCfg, true) is true;
if (useEnv || parseEnv)
{
var envFilePath = cfgCfg?.GetSection("EnvFile")?.Value;
if (envFilePath is not null)
{
var fullPath = Path.GetFullPath(envFilePath, CurrentDir);
if (File.Exists(fullPath))
{
LoadEnvFile(fullPath);
}
}
}
if (parseEnv)
{
EnvDict = new Dictionary<string, string>();
var envVars = Environment.GetEnvironmentVariables();
foreach (var key in envVars.Keys)
{
EnvDict.Add(key.ToString()!, envVars[key.ToString()!]?.ToString()!);
}
}
UseJsonApplicationName = GetConfigBool("UseJsonApplicationName", ConnectionSettingsCfg);
}
public bool Exists(IConfigurationSection? section)
{
if (section is null)
{
return false;
}
if (section.GetChildren().Any() is false)
{
return false;
}
return true;
}
public bool GetConfigBool(string key, IConfiguration? subsection = null, bool defaultVal = false)
{
var section = subsection?.GetSection(key) ?? Cfg.GetSection(key);
if (string.IsNullOrEmpty(section.Value))
{
return defaultVal;
}
var value = EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
// Handle various boolean representations
return value.ToLowerInvariant() switch
{
"true" or "yes" or "1" => true,
"false" or "no" or "0" => false,
_ => throw new InvalidOperationException($"Invalid boolean value '{value}' for configuration key '{key}'. Valid values are: true, false, yes, no, 1, 0")
};
}
public string? GetConfigStr(string key, IConfiguration? subsection = null)
{
var section = subsection?.GetSection(key) ?? Cfg.GetSection(key);
if (string.IsNullOrEmpty(section.Value))
{
return null;
}
return EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
}
public int? GetConfigInt(string key, IConfiguration? subsection = null)
{
var section = subsection?.GetSection(key) ?? Cfg.GetSection(key);
if (string.IsNullOrEmpty(section.Value))
{
return null;
}
var configValue = EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
return int.TryParse(configValue, out var value) ? value :
throw new InvalidOperationException($"Invalid integer value '{configValue}' for configuration key '{key}'.");
}
public T? GetConfigEnum<T>(string key, IConfiguration? subsection = null)
{
var section = subsection?.GetSection(key) ?? Cfg.GetSection(key);
if (string.IsNullOrEmpty(section.Value))
{
return default;
}
var value = EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
return GetEnum<T>(section?.Value);
}
public T? GetEnum<T>(string? value)
{
if (value is null)
{
return default;
}
var type = typeof(T);
var nullable = Nullable.GetUnderlyingType(type);
var names = Enum.GetNames(nullable ?? type);
foreach (var name in names)
{
if (string.Equals(value, name, StringComparison.OrdinalIgnoreCase))
{
return (T)Enum.Parse(nullable ?? type, name);
}
}
return default;
}
public IEnumerable<string>? GetConfigEnumerable(string key, IConfiguration? subsection = null)
{
var section = subsection is not null ? subsection?.GetSection(key) : Cfg.GetSection(key);
if (section.Exists() is false)
{
return null;
}
var children = section?.GetChildren().ToArray();
if (children is null || (children.Length == 0 && section?.Value == ""))
{
return null;
}
if (EnvDict is not null)
{
return children
.Where(c => string.IsNullOrEmpty(c.Value) is false)
.Select(c => Formatter.FormatString(c.Value.AsSpan(), EnvDict).ToString());
}
return children
.Where(c => string.IsNullOrEmpty(c.Value) is false)
.Select(c => c.Value!);
}
public T? GetConfigFlag<T>(string key, IConfiguration? subsection = null)
{
var array = GetConfigEnumerable(key, subsection)?.ToArray();
if (array is null)
{
return default;
}
var type = typeof(T);
var nullable = Nullable.GetUnderlyingType(type);
var names = Enum.GetNames(nullable ?? type);
T? result = default;
foreach (var value in array)
{
foreach (var name in names)
{
if (string.Equals(value, name, StringComparison.OrdinalIgnoreCase))
{
var e = (T)Enum.Parse(nullable ?? type, name);
if (result is null)
{
result = e;
}
else
{
result = (T)Enum.ToObject(type, Convert.ToInt32(result) | Convert.ToInt32(e));
}
}
}
}
return result;
}
public Dictionary<string, string>? GetConfigDict(IConfiguration config)
{
var result = new Dictionary<string, string>();
foreach (var section in config.GetChildren())
{
if (section.Value is not null)
{
var value = EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
result.TryAdd(section.Key, value);
}
}
return result.Count == 0 ? null : result;
}
public string Serialize()
{
var defaults = ConfigDefaults.GetDefaults();
var actual = SerializeConfig(Cfg);
var merged = ConfigDefaults.MergeWithDefaults(defaults, actual);
return merged?.ToJsonString(new JsonSerializerOptions() { WriteIndented = true }) ?? "{}";
}
public string SerializeWithComments()
{
var defaults = ConfigDefaults.GetDefaults();
var actual = SerializeConfig(Cfg, stripPasswords: false);
var merged = ConfigDefaults.MergeWithDefaults(defaults, actual);
if (merged is not JsonObject root)
{
return "{}";
}
// If merged config matches defaults, output the exact JSONC template
// This preserves all hand-crafted formatting, inline comments, and special sections
var defaultsClone = ConfigDefaults.GetDefaults();
if (defaultsClone is not null && JsonNodesEqual(root, defaultsClone))
{
return ConfigSchemaGenerator.DefaultConfigJsonc;
}
// Fallback: use template-based substitution for overridden configs
return SubstituteTemplateValues(root);
}
/// <summary>
/// Walks the JSONC template and substitutes values from the merged config where they differ from defaults.
/// </summary>
private string SubstituteTemplateValues(JsonObject merged)
{
var template = ConfigSchemaGenerator.DefaultConfigJsonc;
var flatMerged = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
FlattenJsonNode(merged, "", flatMerged);
var flatDefaults = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
var defaults = ConfigDefaults.GetDefaults();
if (defaults is not null)
{
FlattenJsonNode(defaults, "", flatDefaults);
}
// Find paths where values differ
var changedPaths = new Dictionary<string, string?>(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in flatMerged)
{
if (!flatDefaults.TryGetValue(kvp.Key, out var defaultVal) || defaultVal != kvp.Value)
{
changedPaths[kvp.Key] = kvp.Value;
}
}
if (changedPaths.Count == 0)
{
return template;
}
// Walk the template and substitute changed values
var lines = template.Split('\n');
var sb = new StringBuilder();
var pathStack = new List<string>();
var inComment = false;
for (int i = 0; i < lines.Length; i++)
{
var line = lines[i];
var trimmed = line.TrimEnd('\r').TrimStart();
// Track multi-line comments
if (trimmed.StartsWith("/*"))
{
inComment = true;
}
if (inComment)
{
sb.Append(lines[i].TrimEnd('\r'));
if (i < lines.Length - 1) sb.Append('\n');
if (trimmed.Contains("*/"))
{
inComment = false;
}
continue;
}
// Skip single-line comments
if (trimmed.StartsWith("//"))
{
sb.Append(lines[i].TrimEnd('\r'));
if (i < lines.Length - 1) sb.Append('\n');
continue;
}
// Track nesting
if (trimmed.StartsWith('"'))
{
// Try to extract key from "key": ...
var colonIdx = trimmed.IndexOf(':');
if (colonIdx > 0)
{
var key = trimmed[1..trimmed.IndexOf('"', 1)];
var currentPath = pathStack.Count > 0 ? string.Join(":", pathStack) + ":" + key : key;
var afterColon = trimmed[(colonIdx + 1)..].TrimStart();
// Check if this is a value line (not object or array open)
bool isObjectOpen = afterColon.StartsWith('{') && !afterColon.StartsWith("{ }") && !afterColon.TrimEnd(',').EndsWith('}');
bool isArrayOpen = afterColon.StartsWith('[') && !afterColon.TrimEnd(',').EndsWith(']');
if (isObjectOpen)
{
pathStack.Add(key);
}
else if (isArrayOpen)
{
pathStack.Add(key);
}
else if (changedPaths.TryGetValue(currentPath, out var newVal))
{
// Substitute the value
var indent = line.TrimEnd('\r')[..^(line.TrimEnd('\r').Length - line.TrimEnd('\r').Length + line.TrimEnd('\r').Length - line.TrimEnd('\r').TrimStart().Length)];
var endsWithComma = trimmed.TrimEnd().EndsWith(',');
var inlineComment = "";
// Preserve inline comments
var valueAndRest = afterColon;
var commentIdx = FindInlineCommentIndex(valueAndRest);
if (commentIdx >= 0)
{
inlineComment = " " + valueAndRest[commentIdx..].TrimEnd(',').TrimEnd();
if (endsWithComma && !inlineComment.EndsWith(','))
{
// comma was after inline comment
}
}
var prefix = line.TrimEnd('\r')[..(line.TrimEnd('\r').IndexOf(':') + 2)];
var comma = endsWithComma ? "," : "";
sb.Append($"{prefix}{newVal ?? "null"}{comma}{inlineComment}");
if (i < lines.Length - 1) sb.Append('\n');
continue;
}
}
}
// Track closing braces
if (trimmed.StartsWith('}') || trimmed.StartsWith(']'))
{
if (pathStack.Count > 0)
{
pathStack.RemoveAt(pathStack.Count - 1);
}
}
sb.Append(lines[i].TrimEnd('\r'));
if (i < lines.Length - 1) sb.Append('\n');
}
return sb.ToString();
}
private static int FindInlineCommentIndex(string s)
{
bool inString = false;
bool escape = false;
for (int i = 0; i < s.Length - 1; i++)
{
if (escape) { escape = false; continue; }
if (s[i] == '\\') { escape = true; continue; }
if (s[i] == '"') { inString = !inString; continue; }
if (!inString && s[i] == '/' && s[i + 1] == '/')
{
return i;
}
}
return -1;
}
private static void FlattenJsonNode(JsonNode node, string prefix, Dictionary<string, string?> result)
{
if (node is JsonObject obj)
{
foreach (var kvp in obj)
{
var path = string.IsNullOrEmpty(prefix) ? kvp.Key : $"{prefix}:{kvp.Key}";
if (kvp.Value is JsonObject || kvp.Value is JsonArray)
{
FlattenJsonNode(kvp.Value, path, result);
}
else
{
result[path] = kvp.Value?.ToJsonString();
}
}
}
else if (node is JsonArray arr)
{
for (int i = 0; i < arr.Count; i++)
{
var path = $"{prefix}:{i}";
if (arr[i] is JsonObject || arr[i] is JsonArray)
{
FlattenJsonNode(arr[i]!, path, result);
}
else
{
result[path] = arr[i]?.ToJsonString();
}
}
}
}
private static bool JsonNodesEqual(JsonNode? a, JsonNode? b)
{
if (a is null && b is null) return true;
if (a is null || b is null) return false;
if (a is JsonObject aObj && b is JsonObject bObj)
{
if (aObj.Count != bObj.Count) return false;
foreach (var kvp in aObj)
{
if (!bObj.ContainsKey(kvp.Key)) return false;
if (!JsonNodesEqual(kvp.Value, bObj[kvp.Key])) return false;
}
return true;
}
if (a is JsonArray aArr && b is JsonArray bArr)
{
if (aArr.Count != bArr.Count) return false;
for (int i = 0; i < aArr.Count; i++)
{
if (!JsonNodesEqual(aArr[i], bArr[i])) return false;
}
return true;
}
return a.ToJsonString() == b.ToJsonString();
}
public string FilterConfig(string filter)
{
var source = SerializeWithComments();
var lines = source.Split('\n');
// Parse entries inside the outermost { }
var entries = ParseJsoncEntries(lines, 1, lines.Length - 1);
// Collect filtered blocks (each block = list of lines, no trailing comma on last line)
var blocks = CollectFilteredBlocks(entries, lines, filter);
if (blocks.Count == 0)
{
return $"// No results for \"{filter}\"";
}
var sb = new StringBuilder();
sb.AppendLine("{");
for (int i = 0; i < blocks.Count; i++)
{
var block = blocks[i];
for (int j = 0; j < block.Count; j++)
{
var line = block[j];
if (j == block.Count - 1)
{
line = StripTrailingComma(line);
if (i < blocks.Count - 1)
{
line = AddTrailingComma(line);
}
}
sb.AppendLine(line);
}
}
sb.Append('}');
return sb.ToString();
}
private sealed class JsoncEntry
{
public int CommentStart; // first line of preceding comments/blanks
public int KeyLine; // the "key": value or "key": { line
public int EndLine; // last line (value line for leaves, } line for sections)
public string Key = "";
public bool IsSection;
public List<JsoncEntry> Children = [];
}
private static List<JsoncEntry> ParseJsoncEntries(string[] lines, int start, int end)
{
var entries = new List<JsoncEntry>();
int i = start;
while (i < end)
{
var trimmed = lines[i].AsSpan().Trim();
// Skip pure blank lines and collect comment start position
if (trimmed.IsEmpty || trimmed.StartsWith("//"))
{
// This might be the start of a new entry's comment block
int commentStart = i;
while (i < end)
{
var t = lines[i].AsSpan().Trim();
if (t.IsEmpty || t.StartsWith("//"))
{
i++;
continue;
}
break;
}
if (i >= end) break;
// Now lines[i] should be a key line
var entry = ParseKeyLine(lines, commentStart, i, end);
if (entry is not null)
{
entries.Add(entry);
i = entry.EndLine + 1;
}
else
{
i++;
}
}
else if (trimmed.Length > 0 && trimmed[0] == '"')
{
// Key line without preceding comments
var entry = ParseKeyLine(lines, i, i, end);
if (entry is not null)
{
entries.Add(entry);
i = entry.EndLine + 1;
}
else
{
i++;
}
}
else
{
i++;
}
}
return entries;
}
private static JsoncEntry? ParseKeyLine(string[] lines, int commentStart, int keyLine, int end)
{
var line = lines[keyLine];
var trimmed = line.AsSpan().Trim();
// Extract key name from "key": ...
if (trimmed.Length == 0 || trimmed[0] != '"') return null;
int closeQuote = trimmed[1..].IndexOf('"');
if (closeQuote < 0) return null;
closeQuote += 1; // adjust for the slice offset
var key = trimmed[1..closeQuote].ToString();
// Check if value opens a section
var afterKey = trimmed[(closeQuote + 1)..].TrimStart();
if (afterKey.Length > 0 && afterKey[0] == ':')
{
var valueStart = afterKey[1..].TrimStart();
if (valueStart.Length > 0 && valueStart[0] == '{')
{
// Section — find matching closing }
int depth = 0;
for (int i = keyLine; i < end; i++)
{
var lt = lines[i].AsSpan().Trim();
if (lt.StartsWith("//")) continue;
depth += CountBraces(lines[i]);
if (depth == 0)
{
var entry = new JsoncEntry
{
CommentStart = commentStart,
KeyLine = keyLine,
EndLine = i,
Key = key,
IsSection = true,
Children = ParseJsoncEntries(lines, keyLine + 1, i)
};
return entry;
}
}
// If we can't find matching brace, treat as leaf
}
}
// Leaf entry
return new JsoncEntry
{
CommentStart = commentStart,
KeyLine = keyLine,
EndLine = keyLine,
Key = key,
IsSection = false
};
}
private static int CountBraces(string line)
{
int count = 0;
bool inString = false;
var span = line.AsSpan();
// Skip comment lines
if (span.TrimStart().StartsWith("//")) return 0;
for (int i = 0; i < span.Length; i++)
{
if (span[i] == '\\' && inString) { i++; continue; }
if (span[i] == '"') { inString = !inString; continue; }
if (!inString)
{
if (span[i] == '{') count++;
else if (span[i] == '}') count--;
}
}
return count;
}
private static bool EntryMatches(JsoncEntry entry, string[] lines, string filter)
{
var cmp = StringComparison.OrdinalIgnoreCase;
// Check key name
if (entry.Key.Contains(filter, cmp)) return true;
// Check comment and value lines
for (int i = entry.CommentStart; i <= Math.Min(entry.KeyLine, entry.EndLine); i++)
{
if (lines[i].Contains(filter, cmp)) return true;
}
// For leaf entries, check the value line
if (!entry.IsSection && lines[entry.KeyLine].Contains(filter, cmp)) return true;
// For sections, check if any child matches
if (entry.IsSection)
{
foreach (var child in entry.Children)
{
if (EntryMatches(child, lines, filter)) return true;
}
}
return false;
}
private static bool EntryDirectlyMatches(JsoncEntry entry, string[] lines, string filter)
{
var cmp = StringComparison.OrdinalIgnoreCase;
if (entry.Key.Contains(filter, cmp)) return true;
for (int i = entry.CommentStart; i <= entry.KeyLine; i++)
{
if (lines[i].Contains(filter, cmp)) return true;
}
return false;
}
private static List<List<string>> CollectFilteredBlocks(List<JsoncEntry> entries, string[] lines, string filter)
{
var blocks = new List<List<string>>();
foreach (var entry in entries)
{
if (!EntryMatches(entry, lines, filter)) continue;
if (!entry.IsSection)
{
// Leaf: copy comment lines + value line
var block = ExtractLines(lines, entry.CommentStart, entry.EndLine);
StripTrailingCommaFromLastLine(block);
blocks.Add(block);
}
else if (EntryDirectlyMatches(entry, lines, filter))
{
// Section name/comment matches — include entire section
var block = ExtractLines(lines, entry.CommentStart, entry.EndLine);
StripTrailingCommaFromLastLine(block);
blocks.Add(block);
}
else
{
// Section has matching children — include section wrapper with only matched children
var childBlocks = CollectFilteredBlocks(entry.Children, lines, filter);
if (childBlocks.Count == 0) continue;
var block = new List<string>();
// Section comments and opening line
for (int i = entry.CommentStart; i <= entry.KeyLine; i++)
{
block.Add(lines[i]);
}
// Matched children with commas between them
for (int ci = 0; ci < childBlocks.Count; ci++)
{
var cb = childBlocks[ci];
if (ci < childBlocks.Count - 1)
{
AddTrailingCommaToLastLine(cb);
}
block.AddRange(cb);
}
// Closing line
block.Add(StripTrailingComma(lines[entry.EndLine]));
blocks.Add(block);
}
}
return blocks;
}
private static List<string> ExtractLines(string[] lines, int start, int end)
{
var result = new List<string>(end - start + 1);
for (int i = start; i <= end; i++)
{
result.Add(lines[i]);
}
return result;
}
private static int FindJsonContentEnd(string line)
{
// Find the end of JSON content, skipping inline // comments
bool inString = false;
for (int i = 0; i < line.Length; i++)
{
if (line[i] == '\\' && inString) { i++; continue; }
if (line[i] == '"') { inString = !inString; continue; }
if (!inString && i + 1 < line.Length && line[i] == '/' && line[i + 1] == '/')
{
// Found inline comment — JSON content ends before this
int end = i;
while (end > 0 && char.IsWhiteSpace(line[end - 1])) end--;
return end;
}
}
// No inline comment — trim trailing whitespace
int e = line.Length;
while (e > 0 && char.IsWhiteSpace(line[e - 1])) e--;
return e;
}
private static string StripTrailingComma(string line)
{
int end = FindJsonContentEnd(line);
if (end > 0 && line[end - 1] == ',')
{
return line[..(end - 1)] + line[end..];
}
return line;
}
private static string AddTrailingComma(string line)
{
int end = FindJsonContentEnd(line);
if (end > 0 && line[end - 1] != ',')
{
return line[..end] + "," + line[end..];
}
return line;
}
private static void StripTrailingCommaFromLastLine(List<string> block)
{
for (int i = block.Count - 1; i >= 0; i--)
{
var trimmed = block[i].AsSpan().Trim();
if (trimmed.IsEmpty || trimmed.StartsWith("//")) continue;
block[i] = StripTrailingComma(block[i]);
break;
}
}
private static void AddTrailingCommaToLastLine(List<string> block)
{
for (int i = block.Count - 1; i >= 0; i--)
{
var trimmed = block[i].AsSpan().Trim();
if (trimmed.IsEmpty || trimmed.StartsWith("//")) continue;
block[i] = AddTrailingComma(block[i]);
break;
}
}
/// <summary>
/// Validates configuration keys against known defaults.
/// Returns the validation mode and list of unknown key paths.
/// Mode is "Ignore", "Warning" (default), or "Error".
/// </summary>
public (string mode, List<string> warnings) ValidateConfigKeys()
{
var cfgCfg = Cfg.GetSection("Config");
var mode = GetConfigStr("ValidateConfigKeys", cfgCfg) ?? "Warning";
if (string.Equals(mode, "Ignore", StringComparison.OrdinalIgnoreCase))
{
return (mode, []);
}
var defaults = ConfigDefaults.GetDefaults();
var actual = SerializeConfig(Cfg);
return (mode, ConfigDefaults.FindUnknownConfigKeys(defaults, actual));
}
internal JsonNode? SerializeConfig(IConfiguration config, bool stripPasswords = true)
{
JsonObject obj = [];
foreach (var child in config.GetChildren())
{
if (child.Path.EndsWith(":0"))
{
var arr = new JsonArray();
foreach (var arrayChild in config.GetChildren())
{
arr.Add(SerializeConfig(arrayChild, stripPasswords));
}
return arr;
}
obj.Add(child.Key, SerializeConfig(child, stripPasswords));
}
if (obj.Count == 0 && config is IConfigurationSection section)
{
if (section.Value is null)
{
return null;
}
var value = EnvDict is not null ?
Formatter.FormatString(section.Value.AsSpan(), EnvDict).ToString() :
section.Value;
if (bool.TryParse(value, out bool boolean))
{
return JsonValue.Create(boolean);
}
// Don't parse strings with leading zeros as numbers (e.g., PostgreSQL error codes "08000")
bool hasLeadingZero = value.Length > 1 && value[0] == '0' && char.IsDigit(value[1]);
if (!hasLeadingZero)
{
if (decimal.TryParse(value, out decimal real))
{
return JsonValue.Create(real);
}
else if (long.TryParse(value, out long integer))
{
return JsonValue.Create(integer);
}
}
if (stripPasswords && section.Path.StartsWith("ConnectionStrings:"))
{
return JsonValue.Create(string.Join(';',
value.Split(';').Where(p => p.StartsWith("password", StringComparison.OrdinalIgnoreCase) is false)));
}
return JsonValue.Create(value);
}
return obj;
}
private static void LoadEnvFile(string path)
{
foreach (var line in File.ReadLines(path))
{
var trimmed = line.Trim();
if (string.IsNullOrEmpty(trimmed) || trimmed.StartsWith('#'))
{
continue;
}
var separatorIndex = trimmed.IndexOf('=');
if (separatorIndex <= 0)
{
continue;
}
var key = trimmed[..separatorIndex].Trim();
var value = trimmed[(separatorIndex + 1)..].Trim();
// Remove surrounding quotes if present
if (value.Length >= 2 &&
((value.StartsWith('"') && value.EndsWith('"')) ||
(value.StartsWith('\'') && value.EndsWith('\''))))
{
value = value[1..^1];
}
Environment.SetEnvironmentVariable(key, value);
}
}
private (List<(string fileName, bool optional)> configFiles, string[] commanLineArgs) BuildFromArgs(string[] args)
{
var configFiles = new List<(string fileName, bool optional)>();
var commandLineArgs = new List<string>();
bool nextIsOptional = false;
for (int i = 0; i < args.Length; i++)
{
var arg = args[i];
if (arg.StartsWith('-'))
{
var lower = arg.ToLowerInvariant();
if (lower is "-o" or "--optional")
{
nextIsOptional = true;
}
else if (lower.StartsWith("--config="))
{
commandLineArgs.Add("--config");
ConfigFilter = arg[9..];
}
else if (string.Equals("--config", lower))
{
commandLineArgs.Add(arg);
// Peek: if next arg exists and doesn't start with '-', it's the filter
if (i + 1 < args.Length && !args[i + 1].StartsWith('-'))
{
ConfigFilter = args[++i];
}
}