forked from git-ecosystem/git-credential-manager
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitConfiguration.cs
More file actions
964 lines (835 loc) · 37.3 KB
/
GitConfiguration.cs
File metadata and controls
964 lines (835 loc) · 37.3 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text;
namespace GitCredentialManager
{
/// <summary>
/// Invoked for each Git configuration entry during an enumeration (<see cref="IGitConfiguration.Enumerate"/>).
/// </summary>
/// <param name="entry">Current configuration entry.</param>
/// <returns>True to continue enumeration, false to stop enumeration.</returns>
public delegate bool GitConfigurationEnumerationCallback(GitConfigurationEntry entry);
public enum GitConfigurationLevel
{
All,
System,
Global,
Local,
Unknown,
}
public enum GitConfigurationType
{
Raw,
Bool,
Path
}
public interface IGitConfiguration
{
/// <summary>
/// Enumerate all configuration entries invoking the specified callback for each entry.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="cb">Callback to invoke for each configuration entry.</param>
void Enumerate(GitConfigurationLevel level, GitConfigurationEnumerationCallback cb);
/// <summary>
/// Try and get the value of a configuration entry as a string.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="type">Type constraint to which the config value should be canonicalized.</param>
/// <param name="name">Configuration entry name.</param>
/// <param name="value">Configuration entry value.</param>
/// <returns>True if the value was found, false otherwise.</returns>
bool TryGet(GitConfigurationLevel level, GitConfigurationType type, string name, out string value);
/// <summary>
/// Set the value of a configuration entry.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="name">Configuration entry name.</param>
/// <param name="value">Configuration entry value.</param>
void Set(GitConfigurationLevel level, string name, string value);
/// <summary>
/// Add a new value for a configuration entry.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="name">Configuration entry name.</param>
/// <param name="value">Configuration entry value.</param>
void Add(GitConfigurationLevel level, string name, string value);
/// <summary>
/// Deletes a configuration entry from the highest level.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="name">Configuration entry name.</param>
void Unset(GitConfigurationLevel level, string name);
/// <summary>
/// Get all value of a multivar configuration entry.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="type">Type constraint to which the config values should be canonicalized.</param>
/// <param name="name">Configuration entry name.</param>
/// <returns>All values of the multivar configuration entry.</returns>
IEnumerable<string> GetAll(GitConfigurationLevel level, GitConfigurationType type, string name);
/// <summary>
/// Get all values of a multivar configuration entry.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="type">Type constraint to which the config values should be canonicalized.</param>
/// <param name="nameRegex">Configuration entry name regular expression.</param>
/// <param name="valueRegex">Regular expression to filter which variables we're interested in. Use null to indicate all.</param>
/// <returns>All values of the multivar configuration entry.</returns>
IEnumerable<string> GetRegex(GitConfigurationLevel level, GitConfigurationType type, string nameRegex, string valueRegex);
/// <summary>
/// Set a multivar configuration entry value.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="nameRegex">Configuration entry name regular expression.</param>
/// <param name="valueRegex">Regular expression to indicate which values to replace.</param>
/// <param name="value">Configuration entry value.</param>
/// <remarks>If the regular expression does not match any existing entry, a new entry is created.</remarks>
void ReplaceAll(GitConfigurationLevel level, string nameRegex, string valueRegex, string value);
/// <summary>
/// Deletes one or several entries from a multivar.
/// </summary>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="name">Configuration entry name.</param>
/// <param name="valueRegex">Regular expression to indicate which values to delete.</param>
void UnsetAll(GitConfigurationLevel level, string name, string valueRegex);
}
/// <summary>
/// Represents a single configuration entry with its origin and level.
/// </summary>
internal class ConfigCacheEntry
{
public string Origin { get; set; }
public string Value { get; set; }
public GitConfigurationLevel Level { get; set; }
public ConfigCacheEntry(string origin, string value)
{
Origin = origin;
Value = value;
Level = DetermineLevel(origin);
}
private static GitConfigurationLevel DetermineLevel(string origin)
{
if (string.IsNullOrEmpty(origin))
return GitConfigurationLevel.Unknown;
// Origins look like: "file:/path/to/config", "command line:", "standard input:"
if (!origin.StartsWith("file:"))
return GitConfigurationLevel.Unknown;
string path = origin.Substring(5); // Remove "file:" prefix
// System config is typically in /etc/gitconfig or $(prefix)/etc/gitconfig
if (path.Contains("/etc/gitconfig") || path.EndsWith("/gitconfig"))
return GitConfigurationLevel.System;
// Global config is typically in ~/.gitconfig or ~/.config/git/config
if (path.Contains("/.gitconfig") || path.Contains("/.config/git/config"))
return GitConfigurationLevel.Global;
// Local config is typically in .git/config within a repository
if (path.Contains("/.git/config"))
return GitConfigurationLevel.Local;
return GitConfigurationLevel.Unknown;
}
}
/// <summary>
/// Cache for Git configuration entries loaded from 'git config list --show-origin -z'.
/// </summary>
internal class ConfigCache
{
private Dictionary<string, List<ConfigCacheEntry>> _entries;
private readonly object _lock = new object();
public bool IsLoaded => _entries != null;
public void Load(string data, ITrace trace)
{
lock (_lock)
{
var entries = new Dictionary<string, List<ConfigCacheEntry>>(GitConfigurationKeyComparer.Instance);
var origin = new StringBuilder();
var key = new StringBuilder();
var value = new StringBuilder();
int i = 0;
while (i < data.Length)
{
origin.Clear();
key.Clear();
value.Clear();
// Read origin (NUL terminated)
while (i < data.Length && data[i] != '\0')
{
origin.Append(data[i++]);
}
if (i >= data.Length)
{
trace.WriteLine("Invalid Git configuration output. Expected null terminator (\\0) after origin.");
break;
}
// Skip the NUL terminator
i++;
// Read key (newline terminated)
while (i < data.Length && data[i] != '\n')
{
key.Append(data[i++]);
}
if (i >= data.Length)
{
trace.WriteLine("Invalid Git configuration output. Expected newline terminator (\\n) after key.");
break;
}
// Skip the newline terminator
i++;
// Read value (NUL terminated)
while (i < data.Length && data[i] != '\0')
{
value.Append(data[i++]);
}
if (i >= data.Length)
{
trace.WriteLine("Invalid Git configuration output. Expected null terminator (\\0) after value.");
break;
}
// Skip the NUL terminator
i++;
string keyStr = key.ToString();
var entry = new ConfigCacheEntry(origin.ToString(), value.ToString());
if (!entries.ContainsKey(keyStr))
{
entries[keyStr] = new List<ConfigCacheEntry>();
}
entries[keyStr].Add(entry);
}
_entries = entries;
}
}
public bool TryGet(string name, GitConfigurationLevel level, out string value)
{
lock (_lock)
{
if (_entries == null)
{
value = null;
return false;
}
if (!_entries.TryGetValue(name, out var entryList))
{
value = null;
return false;
}
// Find the first entry matching the level filter
foreach (var entry in entryList)
{
if (level == GitConfigurationLevel.All || entry.Level == level)
{
value = entry.Value;
return true;
}
}
value = null;
return false;
}
}
public IEnumerable<string> GetAll(string name, GitConfigurationLevel level)
{
lock (_lock)
{
if (_entries == null || !_entries.TryGetValue(name, out var entryList))
{
return Array.Empty<string>();
}
var results = new List<string>();
foreach (var entry in entryList)
{
if (level == GitConfigurationLevel.All || entry.Level == level)
{
results.Add(entry.Value);
}
}
return results;
}
}
public void Enumerate(GitConfigurationLevel level, GitConfigurationEnumerationCallback cb)
{
lock (_lock)
{
if (_entries == null)
return;
foreach (var kvp in _entries)
{
foreach (var entry in kvp.Value)
{
if (level == GitConfigurationLevel.All || entry.Level == level)
{
var configEntry = new GitConfigurationEntry(kvp.Key, entry.Value);
if (!cb(configEntry))
{
return;
}
}
}
}
}
}
public void Clear()
{
lock (_lock)
{
_entries = null;
}
}
}
public class GitProcessConfiguration : IGitConfiguration
{
private static readonly GitVersion TypeConfigMinVersion = new GitVersion(2, 18, 0);
private readonly ITrace _trace;
private readonly GitProcess _git;
private readonly ConfigCache _cache;
private readonly bool _useCache;
internal GitProcessConfiguration(ITrace trace, GitProcess git) : this(trace, git, useCache: true)
{
}
internal GitProcessConfiguration(ITrace trace, GitProcess git, bool useCache)
{
EnsureArgument.NotNull(trace, nameof(trace));
EnsureArgument.NotNull(git, nameof(git));
_trace = trace;
_git = git;
_useCache = useCache;
_cache = useCache ? new ConfigCache() : null;
}
private void EnsureCacheLoaded()
{
if (!_useCache || _cache.IsLoaded)
return;
using (ChildProcess git = _git.CreateProcess("config list --show-origin -z"))
{
git.Start(Trace2ProcessClass.Git);
// To avoid deadlocks, always read the output stream first and then wait
string data = git.StandardOutput.ReadToEnd();
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
_cache.Load(data, _trace);
break;
default:
_trace.WriteLine($"Failed to load config cache (exit={git.ExitCode})");
// Don't throw - fall back to individual commands
break;
}
}
}
private void InvalidateCache()
{
if (_useCache)
{
_cache.Clear();
}
}
public void Enumerate(GitConfigurationLevel level, GitConfigurationEnumerationCallback cb)
{
if (_useCache)
{
EnsureCacheLoaded();
if (_cache.IsLoaded)
{
_cache.Enumerate(level, cb);
return;
}
}
// Fall back to original implementation
string levelArg = GetLevelFilterArg(level);
using (ChildProcess git = _git.CreateProcess($"config --null {levelArg} --list"))
{
git.Start(Trace2ProcessClass.Git);
// To avoid deadlocks, always read the output stream first and then wait
// TODO: don't read in all the data at once; stream it
string data = git.StandardOutput.ReadToEnd();
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
break;
default:
_trace.WriteLine($"Failed to enumerate config entries (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, "Failed to enumerate all Git configuration entries");
}
var name = new StringBuilder();
var value = new StringBuilder();
int i = 0;
while (i < data.Length)
{
name.Clear();
value.Clear();
// Read key name (LF terminated)
while (i < data.Length && data[i] != '\n')
{
name.Append(data[i++]);
}
if (i >= data.Length)
{
_trace.WriteLine("Invalid Git configuration output. Expected newline terminator (\\n) after key.");
break;
}
// Skip the LF terminator
i++;
// Read value (null terminated)
while (i < data.Length && data[i] != '\0')
{
value.Append(data[i++]);
}
if (i >= data.Length)
{
_trace.WriteLine("Invalid Git configuration output. Expected null terminator (\\0) after value.");
break;
}
// Skip the null terminator
i++;
var entry = new GitConfigurationEntry(name.ToString(), value.ToString());
if (!cb(entry))
{
break;
}
}
}
}
public bool TryGet(GitConfigurationLevel level, GitConfigurationType type, string name, out string value)
{
// Use cache for raw types only - typed queries need Git's canonicalization
if (_useCache && type == GitConfigurationType.Raw)
{
EnsureCacheLoaded();
if (_cache.IsLoaded && _cache.TryGet(name, level, out value))
{
return true;
}
}
// Fall back to individual git config command for typed queries or cache miss
string levelArg = GetLevelFilterArg(level);
string typeArg = GetCanonicalizeTypeArg(type);
using (ChildProcess git = _git.CreateProcess($"config --null {levelArg} {typeArg} {QuoteCmdArg(name)}"))
{
git.Start(Trace2ProcessClass.Git);
// To avoid deadlocks, always read the output stream first and then wait
// TODO: don't read in all the data at once; stream it
string data = git.StandardOutput.ReadToEnd();
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
break;
case 1: // Not found
value = null;
return false;
default: // Error
_trace.WriteLine($"Failed to read Git configuration entry '{name}'. (exit={git.ExitCode}, level={level})");
value = null;
return false;
}
string[] entries = data.Split('\0');
if (entries.Length > 0)
{
value = entries[0];
return true;
}
value = null;
return false;
}
}
public void Set(GitConfigurationLevel level, string name, string value)
{
EnsureSpecificLevel(level);
string levelArg = GetLevelFilterArg(level);
using (ChildProcess git = _git.CreateProcess($"config {levelArg} {QuoteCmdArg(name)} {QuoteCmdArg(value)}"))
{
git.Start(Trace2ProcessClass.Git);
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
InvalidateCache();
break;
default:
_trace.WriteLine($"Failed to set config entry '{name}' to value '{value}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to set Git configuration entry '{name}'");
}
}
}
public void Add(GitConfigurationLevel level, string name, string value)
{
EnsureSpecificLevel(level);
string levelArg = GetLevelFilterArg(level);
using (ChildProcess git = _git.CreateProcess($"config {levelArg} --add {QuoteCmdArg(name)} {QuoteCmdArg(value)}"))
{
git.Start(Trace2ProcessClass.Git);
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
InvalidateCache();
break;
default:
_trace.WriteLine($"Failed to add config entry '{name}' with value '{value}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to add Git configuration entry '{name}'");
}
}
}
public void Unset(GitConfigurationLevel level, string name)
{
EnsureSpecificLevel(level);
string levelArg = GetLevelFilterArg(level);
using (ChildProcess git = _git.CreateProcess($"config {levelArg} --unset {QuoteCmdArg(name)}"))
{
git.Start(Trace2ProcessClass.Git);
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
case 5: // Trying to unset a value that does not exist
InvalidateCache();
break;
default:
_trace.WriteLine($"Failed to unset config entry '{name}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to unset Git configuration entry '{name}'");
}
}
}
public IEnumerable<string> GetAll(GitConfigurationLevel level, GitConfigurationType type, string name)
{
// Use cache for raw types only - typed queries need Git's canonicalization
if (_useCache && type == GitConfigurationType.Raw)
{
EnsureCacheLoaded();
if (_cache.IsLoaded)
{
var cachedValues = _cache.GetAll(name, level);
foreach (var val in cachedValues)
{
yield return val;
}
yield break;
}
}
// Fall back to individual git config command
string levelArg = GetLevelFilterArg(level);
string typeArg = GetCanonicalizeTypeArg(type);
var gitArgs = $"config --null {levelArg} {typeArg} --get-all {QuoteCmdArg(name)}";
using (ChildProcess git = _git.CreateProcess(gitArgs))
{
git.Start(Trace2ProcessClass.Git);
// To avoid deadlocks, always read the output stream first and then wait
// TODO: don't read in all the data at once; stream it
string data = git.StandardOutput.ReadToEnd();
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
string[] entries = data.Split('\0');
// Because each line terminates with the \0 character, splitting leaves us with one
// bogus blank entry at the end of the array which we should ignore
for (var i = 0; i < entries.Length - 1; i++)
{
yield return entries[i];
}
break;
case 1: // No results
break;
default:
_trace.WriteLine($"Failed to get all config entries '{name}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to get all Git configuration entries '{name}'");
}
}
}
public IEnumerable<string> GetRegex(GitConfigurationLevel level, GitConfigurationType type, string nameRegex, string valueRegex)
{
string levelArg = GetLevelFilterArg(level);
string typeArg = GetCanonicalizeTypeArg(type);
var gitArgs = $"config --null {levelArg} {typeArg} --get-regex {QuoteCmdArg(nameRegex)}";
if (valueRegex != null)
{
gitArgs += $" {QuoteCmdArg(valueRegex)}";
}
using (ChildProcess git = _git.CreateProcess(gitArgs))
{
git.Start(Trace2ProcessClass.Git);
// To avoid deadlocks, always read the output stream first and then wait
// TODO: don't read in all the data at once; stream it
string data = git.StandardOutput.ReadToEnd();
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
case 1: // No results
break;
default:
_trace.WriteLine($"Failed to get all multivar regex '{nameRegex}' and value regex '{valueRegex}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to get Git configuration multi-valued entries with name regex '{nameRegex}'");
}
string[] entries = data.Split('\0');
foreach (string entry in entries)
{
string[] kvp = entry.Split(new[]{'\n'}, count: 2);
if (kvp.Length == 2)
{
yield return kvp[1];
}
}
}
}
public void ReplaceAll(GitConfigurationLevel level, string name, string valueRegex, string value)
{
EnsureSpecificLevel(level);
string levelArg = GetLevelFilterArg(level);
var gitArgs = $"config {levelArg} --replace-all {QuoteCmdArg(name)} {QuoteCmdArg(value)}";
if (valueRegex != null)
{
gitArgs += $" {QuoteCmdArg(valueRegex)}";
}
using (ChildProcess git = _git.CreateProcess(gitArgs))
{
git.Start(Trace2ProcessClass.Git);
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
InvalidateCache();
break;
default:
_trace.WriteLine($"Failed to replace all multivar '{name}' and value regex '{valueRegex}' with new value '{value}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to replace all Git configuration multi-valued entries '{name}'");
}
}
}
public void UnsetAll(GitConfigurationLevel level, string name, string valueRegex)
{
EnsureSpecificLevel(level);
string levelArg = GetLevelFilterArg(level);
var gitArgs = $"config {levelArg} --unset-all {QuoteCmdArg(name)}";
if (valueRegex != null)
{
gitArgs += $" {QuoteCmdArg(valueRegex)}";
}
using (ChildProcess git = _git.CreateProcess(gitArgs))
{
git.Start(Trace2ProcessClass.Git);
git.WaitForExit();
switch (git.ExitCode)
{
case 0: // OK
case 5: // Trying to unset a value that does not exist
InvalidateCache();
break;
default:
_trace.WriteLine($"Failed to unset all multivar '{name}' with value regex '{valueRegex}' (exit={git.ExitCode}, level={level})");
throw GitProcess.CreateGitException(git, $"Failed to unset all Git configuration multi-valued entries '{name}'");
}
}
}
private static void EnsureSpecificLevel(GitConfigurationLevel level)
{
if (level == GitConfigurationLevel.All)
{
throw new InvalidOperationException("Must have a specific configuration level filter to modify values.");
}
}
private static string GetLevelFilterArg(GitConfigurationLevel level)
{
switch (level)
{
case GitConfigurationLevel.System:
return "--system";
case GitConfigurationLevel.Global:
return "--global";
case GitConfigurationLevel.Local:
return "--local";
case GitConfigurationLevel.Unknown:
default:
return null;
}
}
private string GetCanonicalizeTypeArg(GitConfigurationType type)
{
if (_git.Version >= TypeConfigMinVersion)
{
return type switch
{
GitConfigurationType.Bool => "--type=bool",
GitConfigurationType.Path => "--type=path",
_ => null
};
}
else
{
return type switch
{
GitConfigurationType.Bool => "--bool",
GitConfigurationType.Path => "--path",
_ => null
};
}
}
public static string QuoteCmdArg(string str)
{
bool needsQuotes = string.IsNullOrEmpty(str);
var result = new StringBuilder();
for (int i = 0; i < (str?.Length ?? 0); i++)
{
switch (str![i])
{
case '"':
result.Append("\\\"");
needsQuotes = true;
break;
case ' ':
case '{':
case '*':
case '?':
case '\r':
case '\n':
case '\t':
case '\'':
result.Append(str[i]);
needsQuotes = true;
break;
case '\\':
int end = i;
// Copy all the '\'s in this run.
while (end < str.Length && str[end] == '\\')
{
result.Append('\\');
end++;
}
// If we ended the run of '\'s with a '"' then we need to double up the number of '\'s.
// The '"' will be escaped on the next pass of the loop.
// Also if we have reached the end of the string, and we need to book-end the result
// with double quotes ('"') we should escape all the '\'s to prevent ending on an
// escaped '"' in the result.
if (end < str.Length && str[end] == '"' ||
end == str.Length && needsQuotes)
{
result.Append('\\', end - i);
}
// Back-off one character
if (end > i)
{
end--;
}
i = end;
break;
default:
result.Append(str[i]);
break;
}
}
if (needsQuotes)
{
result.Insert(0, '"');
result.Append('"');
}
return result.ToString();
}
}
public static class GitConfigurationExtensions
{
/// <summary>
/// Enumerate all configuration entries invoking the specified callback for each entry.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="cb">Callback to invoke for each matching configuration entry.</param>
public static void Enumerate(this IGitConfiguration config, GitConfigurationEnumerationCallback cb)
{
config.Enumerate(GitConfigurationLevel.All, cb);
}
/// <summary>
/// Enumerate all configuration entries invoking the specified callback for each entry.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="section">Optional section name to filter; use null for any.</param>
/// <param name="property">Optional property name to filter; use null for any.</param>
/// <param name="cb">Callback to invoke for each matching configuration entry.</param>
public static void Enumerate(this IGitConfiguration config,
GitConfigurationLevel level, string section, string property, GitConfigurationEnumerationCallback cb)
{
config.Enumerate(level, entry =>
{
if (GitConfigurationKeyComparer.TrySplit(entry.Key, out string entrySection, out _, out string entryProperty) &&
(section is null || GitConfigurationKeyComparer.SectionComparer.Equals(section, entrySection)) &&
(property is null || GitConfigurationKeyComparer.PropertyComparer.Equals(property, entryProperty)))
{
return cb(entry);
}
return true;
});
}
/// <summary>
/// Enumerate all configuration entries invoking the specified callback for each entry.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="section">Optional section name to filter; use null for any.</param>
/// <param name="property">Optional property name to filter; use null for any.</param>
/// <param name="cb">Callback to invoke for each matching configuration entry.</param>
public static void Enumerate(this IGitConfiguration config, string section, string property, GitConfigurationEnumerationCallback cb)
{
Enumerate(config, GitConfigurationLevel.All, section, property, cb);
}
/// <summary>
/// Get the value of a configuration entry as a string.
/// </summary>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">A configuration entry with the specified key was not found.</exception>
/// <param name="config">Configuration object.</param>
/// <param name="level">Filter to the specific configuration level.</param>
/// <param name="name">Configuration entry name.</param>
/// <returns>Configuration entry value.</returns>
public static string Get(this IGitConfiguration config, GitConfigurationLevel level, string name)
{
if (!config.TryGet(level, GitConfigurationType.Raw, name, out string value))
{
throw new KeyNotFoundException($"Git configuration entry with the name '{name}' was not found.");
}
return value;
}
/// <summary>
/// Get the value of a configuration entry as a string.
/// </summary>
/// <exception cref="System.Collections.Generic.KeyNotFoundException">A configuration entry with the specified key was not found.</exception>
/// <param name="config">Configuration object.</param>
/// <param name="name">Configuration entry name.</param>
/// <returns>Configuration entry value.</returns>
public static string Get(this IGitConfiguration config, string name)
{
return Get(config, GitConfigurationLevel.All, name);
}
/// <summary>
/// Try and get the value of a configuration entry as a string.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="name">Configuration entry name.</param>
/// <param name="isPath">Whether the entry should be canonicalized as a path.</param>
/// <param name="value">Configuration entry value.</param>
/// <returns>True if the value was found, false otherwise.</returns>
public static bool TryGet(this IGitConfiguration config, string name, bool isPath, out string value)
{
return config.TryGet(GitConfigurationLevel.All,
isPath ? GitConfigurationType.Path : GitConfigurationType.Raw,
name, out value);
}
/// <summary>
/// Get all value of a multivar configuration entry.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="name">Configuration entry name.</param>
/// <returns>All values of the multivar configuration entry.</returns>
public static IEnumerable<string> GetAll(this IGitConfiguration config, string name)
{
return config.GetAll(GitConfigurationLevel.All, GitConfigurationType.Raw, name);
}
/// <summary>
/// Get all values of a multivar configuration entry.
/// </summary>
/// <param name="config">Configuration object.</param>
/// <param name="nameRegex">Configuration entry name regular expression.</param>
/// <param name="valueRegex">Regular expression to filter which variables we're interested in. Use null to indicate all.</param>
/// <returns>All values of the multivar configuration entry.</returns>
public static IEnumerable<string> GetRegex(this IGitConfiguration config, string nameRegex, string valueRegex)
{
return config.GetRegex(GitConfigurationLevel.All, GitConfigurationType.Raw, nameRegex, valueRegex);
}
}
}