-
Notifications
You must be signed in to change notification settings - Fork 892
/
Copy pathConfiguration.cs
849 lines (764 loc) · 36.9 KB
/
Configuration.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
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using LibGit2Sharp.Core;
using LibGit2Sharp.Core.Handles;
namespace LibGit2Sharp
{
/// <summary>
/// Provides access to configuration variables for a repository.
/// </summary>
public class Configuration : IDisposable,
IEnumerable<ConfigurationEntry<string>>
{
private readonly FilePath repoConfigPath;
private readonly FilePath globalConfigPath;
private readonly FilePath xdgConfigPath;
private readonly FilePath systemConfigPath;
private readonly FilePath programDataConfigPath;
private ConfigurationHandle configHandle;
/// <summary>
/// Needed for mocking purposes.
/// </summary>
protected Configuration()
{ }
internal Configuration(
Repository repository,
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
if (repositoryConfigurationFileLocation != null)
{
repoConfigPath = NormalizeConfigPath(repositoryConfigurationFileLocation);
}
globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global();
xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg();
systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system();
programDataConfigPath = Proxy.git_config_find_programdata();
Init(repository);
}
private void Init(Repository repository)
{
configHandle = Proxy.git_config_new();
RepositoryHandle repoHandle = (repository != null) ? repository.Handle : null;
if (repoHandle != null)
{
//TODO: push back this logic into libgit2.
// As stated by @carlosmn "having a helper function to load the defaults and then allowing you
// to modify it before giving it to git_repository_open_ext() would be a good addition, I think."
// -- Agreed :)
string repoConfigLocation = Path.Combine(repository.Info.Path, "config");
Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local, repoHandle);
Proxy.git_repository_set_config(repoHandle, configHandle);
}
else if (repoConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, repoConfigPath, ConfigurationLevel.Local, repoHandle);
}
if (globalConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global, repoHandle);
}
if (xdgConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg, repoHandle);
}
if (systemConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System, repoHandle);
}
if (programDataConfigPath != null)
{
Proxy.git_config_add_file_ondisk(configHandle, programDataConfigPath, ConfigurationLevel.ProgramData, repoHandle);
}
}
private FilePath NormalizeConfigPath(FilePath path)
{
if (File.Exists(path.Native))
{
return path;
}
if (!Directory.Exists(path.Native))
{
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
var configPath = Path.Combine(path.Native, "config");
if (File.Exists(configPath))
{
return configPath;
}
var gitConfigPath = Path.Combine(path.Native, ".git", "config");
if (File.Exists(gitConfigPath))
{
return gitConfigPath;
}
throw new FileNotFoundException("Cannot find repository configuration file", path.Native);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(string repositoryConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, null, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, null, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation)
{
return BuildFrom(repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, null);
}
/// <summary>
/// Access configuration values without a repository.
/// <para>
/// Generally you want to access configuration via an instance of <see cref="Repository"/> instead.
/// </para>
/// <para>
/// <paramref name="repositoryConfigurationFileLocation"/> can either contains a path to a file or a directory. In the latter case,
/// this can be the working directory, the .git directory or the directory containing a bare repository.
/// </para>
/// </summary>
/// <param name="repositoryConfigurationFileLocation">Path to an existing Repository configuration file.</param>
/// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a Global configuration file will be probed.</param>
/// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param>
/// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a System configuration file will be probed.</param>
/// <returns>An instance of <see cref="Configuration"/>.</returns>
public static Configuration BuildFrom(
string repositoryConfigurationFileLocation,
string globalConfigurationFileLocation,
string xdgConfigurationFileLocation,
string systemConfigurationFileLocation)
{
return new Configuration(null, repositoryConfigurationFileLocation, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation);
}
/// <summary>
/// Determines which configuration file has been found.
/// </summary>
public virtual bool HasConfig(ConfigurationLevel level)
{
using (ConfigurationHandle snapshot = Snapshot())
using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
return handle != null;
}
}
#region IDisposable Members
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// Saves any open configuration files.
/// </summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
#endregion
/// <summary>
/// Unset a configuration variable (key and value) in the local configuration.
/// </summary>
/// <param name="key">The key to unset.</param>
public virtual bool Unset(string key)
{
return Unset(key, ConfigurationLevel.Local);
}
/// <summary>
/// Unset a configuration variable (key and value).
/// </summary>
/// <param name="key">The key to unset.</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual bool Unset(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
return Proxy.git_config_delete(h, key);
}
}
/// <summary>
/// Unset all configuration values in a multivar variable (key and value) in the local configuration.
/// </summary>
/// <param name="key">The key to unset.</param>
public virtual bool UnsetAll(string key)
{
return UnsetAll(key, ConfigurationLevel.Local);
}
/// <summary>
/// Unset all configuration values in a multivar variable (key and value).
/// </summary>
/// <param name="key">The key to unset.</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual bool UnsetAll(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
return Proxy.git_config_delete_multivar(h, key);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
protected virtual void Dispose(bool disposing)
{
configHandle.SafeDispose();
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>(new []{ "core", "bare" }).Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="keyParts">The key parts</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string[] keyParts)
{
Ensure.ArgumentNotNull(keyParts, "keyParts");
return Get<T>(string.Join(".", keyParts));
}
/// <summary>
/// Get a configuration value for the given key parts.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [difftool "kdiff3"]
/// path = c:/Program Files/KDiff3/kdiff3.exe
/// </code>
///
/// You would call:
///
/// <code>
/// string where = repo.Config.Get<string>("difftool", "kdiff3", "path").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="firstKeyPart">The first key part</param>
/// <param name="secondKeyPart">The second key part</param>
/// <param name="thirdKeyPart">The third key part</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
Ensure.ArgumentNotNullOrEmptyString(firstKeyPart, "firstKeyPart");
Ensure.ArgumentNotNullOrEmptyString(secondKeyPart, "secondKeyPart");
Ensure.ArgumentNotNullOrEmptyString(thirdKeyPart, "thirdKeyPart");
return Get<T>(new[] { firstKeyPart, secondKeyPart, thirdKeyPart });
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
///
/// The first occurence of the key will be returned.
/// </para>
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle snapshot = Snapshot())
{
return Proxy.git_config_get_entry<T>(snapshot, key);
}
}
/// <summary>
/// Get a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to get the value for this in a .git\config file:
///
/// <code>
/// [core]
/// bare = true
/// </code>
///
/// You would call:
///
/// <code>
/// bool isBare = repo.Config.Get<bool>("core.bare").Value;
/// </code>
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key</param>
/// <param name="level">The configuration file into which the key should be searched for</param>
/// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns>
public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle snapshot = Snapshot())
using (ConfigurationHandle handle = RetrieveConfigurationHandle(level, false, snapshot))
{
if (handle == null)
{
return null;
}
return Proxy.git_config_get_entry<T>(handle, key);
}
}
/// <summary>
/// Get a configuration value for the given key.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/>if not found</returns>
public virtual T GetValueOrDefault<T>(string key)
{
return ValueOrDefault(Get<T>(key), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value</returns>
public virtual T GetValueOrDefault<T>(string key, T defaultValue)
{
return ValueOrDefault(Get<T>(key), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>The configuration value, or the default value for <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level)
{
return ValueOrDefault(Get<T>(key, level), default(T));
}
/// <summary>
/// Get a configuration value for the given key,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValue">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, T defaultValue)
{
return ValueOrDefault(Get<T>(key, level), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <returns>The configuration value, or the default value for<see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts)
{
return ValueOrDefault(Get<T>(keyParts), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default value.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, T defaultValue)
{
return ValueOrDefault(Get<T>(keyParts), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key parts.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <returns>The configuration value, or the default value for the selected <see typeparamref="T"/> if not found</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), default(T));
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or <paramref name="defaultValue" /> if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValue">The default value if the key is not set.</param>
/// <returns>The configuration value, or the default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, T defaultValue)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValue);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="key">The key.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string key, ConfigurationLevel level, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(key, level), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="keyParts">The key parts.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string[] keyParts, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(keyParts), defaultValueSelector);
}
/// <summary>
/// Get a configuration value for the given key parts,
/// or a value generated by <paramref name="defaultValueSelector" />
/// if the key is not set.
/// </summary>
/// <typeparam name="T">The configuration value type.</typeparam>
/// <param name="firstKeyPart">The first key part.</param>
/// <param name="secondKeyPart">The second key part.</param>
/// <param name="thirdKeyPart">The third key part.</param>
/// <param name="defaultValueSelector">The selector used to generate a default value if the key is not set.</param>
/// <returns>The configuration value, or a generated default.</returns>
public virtual T GetValueOrDefault<T>(string firstKeyPart, string secondKeyPart, string thirdKeyPart, Func<T> defaultValueSelector)
{
return ValueOrDefault(Get<T>(firstKeyPart, secondKeyPart, thirdKeyPart), defaultValueSelector);
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, T defaultValue)
{
return value == null ? defaultValue : value.Value;
}
private static T ValueOrDefault<T>(ConfigurationEntry<T> value, Func<T> defaultValueSelector)
{
Ensure.ArgumentNotNull(defaultValueSelector, "defaultValueSelector");
return value == null
? defaultValueSelector()
: value.Value;
}
/// <summary>
/// Set a configuration value for a key in the local configuration. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
public virtual void Set<T>(string key, T value)
{
Set(key, value, ConfigurationLevel.Local);
}
/// <summary>
/// Set a configuration value for a key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to set the value for this in a .git\config file:
///
/// [test]
/// boolsetting = true
///
/// You would call:
///
/// repo.Config.Set("test.boolsetting", true);
/// </para>
/// </summary>
/// <typeparam name="T">The configuration value type</typeparam>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Set<T>(string key, T value, ConfigurationLevel level)
{
Ensure.ArgumentNotNull(value, "value");
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
if (!configurationTypedUpdater.ContainsKey(typeof(T)))
{
throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName));
}
configurationTypedUpdater[typeof(T)](key, value, h);
}
}
/// <summary>
/// Adds a configuration value for a multivalue key in the local configuration. Keys are in the form 'section.name'.
/// <para>
/// For example in order to add the value for this in a .git\config file:
///
/// [test]
/// plugin = first
///
/// You would call:
///
/// repo.Config.Add("test.plugin", "first");
/// </para>
/// </summary>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
public virtual void Add(string key, string value)
{
Add(key, value, ConfigurationLevel.Local);
}
/// <summary>
/// Adds a configuration value for a multivalue key. Keys are in the form 'section.name'.
/// <para>
/// For example in order to add the value for this in a .git\config file:
///
/// [test]
/// plugin = first
///
/// You would call:
///
/// repo.Config.Add("test.plugin", "first");
/// </para>
/// </summary>
/// <param name="key">The key parts</param>
/// <param name="value">The value</param>
/// <param name="level">The configuration file which should be considered as the target of this operation</param>
public virtual void Add(string key, string value, ConfigurationLevel level)
{
Ensure.ArgumentNotNull(value, "value");
Ensure.ArgumentNotNullOrEmptyString(key, "key");
using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, configHandle))
{
Proxy.git_config_add_string(h, key, value);
}
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp)
{
return Find(regexp, ConfigurationLevel.Local);
}
/// <summary>
/// Find configuration entries matching <paramref name="regexp"/>.
/// </summary>
/// <param name="regexp">A regular expression.</param>
/// <param name="level">The configuration file into which the key should be searched for.</param>
/// <returns>Matching entries.</returns>
public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level)
{
Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp");
using (ConfigurationHandle snapshot = Snapshot())
using (ConfigurationHandle h = RetrieveConfigurationHandle(level, true, snapshot))
{
return Proxy.git_config_iterator_glob(h, regexp).ToList();
}
}
private ConfigurationHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationHandle fromHandle)
{
ConfigurationHandle handle = null;
if (fromHandle != null)
{
handle = Proxy.git_config_open_level(fromHandle, level);
}
if (handle == null && throwIfStoreHasNotBeenFound)
{
throw new LibGit2SharpException("No {0} configuration file has been found.",
Enum.GetName(typeof(ConfigurationLevel), level));
}
return handle;
}
private static Action<string, object, ConfigurationHandle> GetUpdater<T>(Action<ConfigurationHandle, string, T> setter)
{
return (key, val, handle) => setter(handle, key, (T)val);
}
private readonly static IDictionary<Type, Action<string, object, ConfigurationHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationHandle>>
{
{ typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) },
{ typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) },
{ typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) },
{ typeof(string), GetUpdater<string>(Proxy.git_config_set_string) },
};
/// <summary>
/// Returns an enumerator that iterates through the configuration entries.
/// </summary>
/// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns>
public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator()
{
return BuildConfigEntries().GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator();
}
private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries()
{
return Proxy.git_config_foreach(configHandle, BuildConfigEntry);
}
internal static unsafe ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr)
{
var entry = (GitConfigEntry*)entryPtr.ToPointer();
return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry->namePtr),
LaxUtf8Marshaler.FromNative(entry->valuePtr),
(ConfigurationLevel)entry->level);
}
/// <summary>
/// Builds a <see cref="Signature"/> based on current configuration. If it is not found or
/// some configuration is missing, <code>null</code> is returned.
/// <para>
/// The same escalation logic than in git.git will be used when looking for the key in the config files:
/// - local: the Git file in the current repository
/// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`)
/// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`)
/// - system: the system-wide Git file
/// </para>
/// </summary>
/// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param>
/// <returns>The signature or null if no user identity can be found in the configuration.</returns>
public virtual Signature BuildSignature(DateTimeOffset now)
{
var name = this.GetValueOrDefault<string>("user.name");
var email = this.GetValueOrDefault<string>("user.email");
if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(email))
{
return null;
}
return new Signature(name, email, now);
}
internal Signature BuildSignatureOrThrow(DateTimeOffset now)
{
var signature = BuildSignature(now);
if (signature == null)
{
throw new LibGit2SharpException("This overload requires 'user.name' and 'user.email' to be set. " +
"Use a different overload or set those variables in the configuation");
}
return signature;
}
private ConfigurationHandle Snapshot()
{
return Proxy.git_config_snapshot(configHandle);
}
/// <summary>
/// Perform a series of actions within a transaction.
///
/// The configuration will be locked during this function and the changes will be committed at the end. These
/// changes will not be visible in the configuration until the end of this method.
///
/// If the action throws an exception, the changes will be rolled back.
/// </summary>
/// <param name="action">The code to run under the transaction</param>
public virtual unsafe void WithinTransaction(Action action)
{
IntPtr txn = IntPtr.Zero;
try
{
txn = Proxy.git_config_lock(configHandle);
action();
Proxy.git_transaction_commit(txn);
}
finally
{
Proxy.git_transaction_free(txn);
}
}
}
}