This repository was archived by the owner on Dec 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 197
Expand file tree
/
Copy pathKeyPerFileConfigurationProvider.cs
More file actions
72 lines (63 loc) · 2.47 KB
/
KeyPerFileConfigurationProvider.cs
File metadata and controls
72 lines (63 loc) · 2.47 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
using System;
using System.Collections.Generic;
using System.IO;
namespace Microsoft.Extensions.Configuration.KeyPerFile
{
/// <summary>
/// A <see cref="ConfigurationProvider"/> that uses a directory's files as configuration key/values.
/// </summary>
public class KeyPerFileConfigurationProvider : ConfigurationProvider
{
KeyPerFileConfigurationSource Source { get; set; }
/// <summary>
/// Initializes a new instance.
/// </summary>
/// <param name="source">The settings.</param>
public KeyPerFileConfigurationProvider(KeyPerFileConfigurationSource source)
=> Source = source ?? throw new ArgumentNullException(nameof(source));
private static string NormalizeKey(string key)
=> key.Replace("__", ConfigurationPath.KeyDelimiter);
private static string TrimNewLine(string value)
=> value.EndsWith(Environment.NewLine)
? value.Substring(0, value.Length - Environment.NewLine.Length)
: value;
/// <summary>
/// Loads the docker secrets.
/// </summary>
public override void Load()
{
Data = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
if (Source.FileProvider == null)
{
if (Source.Optional)
{
return;
}
else
{
throw new DirectoryNotFoundException("A non-null file provider for the directory is required when this source is not optional.");
}
}
var directory = Source.FileProvider.GetDirectoryContents("/");
if (!directory.Exists && !Source.Optional)
{
throw new DirectoryNotFoundException("The root directory for the FileProvider doesn't exist and is not optional.");
}
foreach (var file in directory)
{
if (file.IsDirectory)
{
continue;
}
using (var stream = file.CreateReadStream())
using (var streamReader = new StreamReader(stream))
{
if (Source.IgnoreCondition == null || !Source.IgnoreCondition(file.Name))
{
Data.Add(NormalizeKey(file.Name), TrimNewLine(streamReader.ReadToEnd()));
}
}
}
}
}
}