This repository has been archived by the owner on Jan 12, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 58
/
EnvironmentProvider.cs
60 lines (55 loc) · 2.12 KB
/
EnvironmentProvider.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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#nullable enable
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Microsoft.Extensions.Configuration;
namespace Microsoft.Quantum.IQSharp
{
public class NormalizedEnvironmentVariableConfigurationSource : IConfigurationSource
{
public IDictionary<string, string>? Aliases { get; set; }
public string? Prefix { get; set; }
public IConfigurationProvider Build(IConfigurationBuilder builder) =>
new NormalizedEnvironmentVariableConfigurationProvider(
Prefix, Aliases
);
}
public class NormalizedEnvironmentVariableConfigurationProvider : ConfigurationProvider
{
private readonly IImmutableDictionary<string, string> Aliases;
private readonly string Prefix;
public NormalizedEnvironmentVariableConfigurationProvider(
string? prefix = null,
IDictionary<string, string>? aliases = null
)
{
Aliases = aliases?.ToImmutableDictionary(StringComparer.OrdinalIgnoreCase)
?? ImmutableDictionary<string, string>.Empty;
Prefix = prefix ?? "";
}
public override void Load() =>
Data = System.Environment
.GetEnvironmentVariables()
.Cast<DictionaryEntry>()
.Where(variable =>
((string)variable.Key).StartsWith(Prefix)
)
.ToDictionary(
variable => {
var keyWithoutPrefix = ((string)variable.Key)
.Substring(Prefix.Length);
if (Aliases.TryGetValue(keyWithoutPrefix, out var newKey))
{
return newKey;
}
return keyWithoutPrefix;
},
variable => ((string)variable.Value!),
StringComparer.OrdinalIgnoreCase
);
}
}