MireaBackend/Endpoint/Configuration/ApplicationConfiguration/EnvironmentConfiguration.cs

79 lines
2.5 KiB
C#
Raw Normal View History

using Microsoft.Extensions.Configuration;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Mirea.Api.Endpoint.Configuration.ApplicationConfiguration;
public static class EnvironmentConfiguration
{
private static Dictionary<string, string> LoadEnvironment(string envFile)
{
Dictionary<string, string> environment = [];
if (!File.Exists(envFile)) return environment;
foreach (var line in File.ReadAllLines(envFile))
{
if (string.IsNullOrEmpty(line)) continue;
var commentIndex = line.IndexOf('#', StringComparison.Ordinal);
string arg = line;
if (commentIndex != -1)
arg = arg.Remove(commentIndex, arg.Length - commentIndex);
var parts = arg.Split(
'=',
StringSplitOptions.RemoveEmptyEntries);
if (parts.Length > 2)
parts = [parts[0], string.Join("=", parts[1..])];
if (parts.Length != 2)
continue;
environment.Add(parts[0].Trim(), parts[1].Trim());
}
return environment;
}
public static IConfigurationRoot GetEnvironment()
{
var variablesFromFile = LoadEnvironment(".env");
2024-07-05 01:22:21 +03:00
#if DEBUG
LoadEnvironment(".env.develop").ToList().ForEach(x => variablesFromFile.Add(x.Key, x.Value));
#endif
var environmentVariables = Environment.GetEnvironmentVariables()
.OfType<DictionaryEntry>()
.ToDictionary(
entry => entry.Key.ToString() ?? string.Empty,
entry => entry.Value?.ToString() ?? string.Empty
);
var result = new ConfigurationBuilder()
.AddInMemoryCollection(environmentVariables!)
.AddInMemoryCollection(variablesFromFile!);
2024-07-05 01:35:19 +03:00
if (variablesFromFile.TryGetValue("PATH_TO_SAVE", out var pathToSave))
{
Environment.SetEnvironmentVariable("PATH_TO_SAVE", pathToSave);
if (!Directory.Exists(pathToSave))
Directory.CreateDirectory(pathToSave);
}
2024-07-05 01:22:21 +03:00
2024-07-05 01:35:19 +03:00
if (variablesFromFile.TryGetValue("ACTUAL_SUB_PATH", out var actualSubPath))
Environment.SetEnvironmentVariable("ACTUAL_SUB_PATH", actualSubPath);
2024-07-05 01:22:21 +03:00
2024-07-05 01:35:19 +03:00
if (variablesFromFile.TryGetValue("SWAGGER_SUB_PATH", out var swaggerSubPath))
Environment.SetEnvironmentVariable("SWAGGER_SUB_PATH", swaggerSubPath);
return result.Build();
}
}