refactor: code restructuring
This commit is contained in:
@ -0,0 +1,79 @@
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
|
||||
namespace Mirea.Api.Endpoint.Configuration.Core.Startup;
|
||||
|
||||
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");
|
||||
|
||||
#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!);
|
||||
|
||||
if (variablesFromFile.TryGetValue("PATH_TO_SAVE", out var pathToSave))
|
||||
{
|
||||
Environment.SetEnvironmentVariable("PATH_TO_SAVE", pathToSave);
|
||||
if (!Directory.Exists(pathToSave))
|
||||
Directory.CreateDirectory(pathToSave);
|
||||
}
|
||||
|
||||
if (variablesFromFile.TryGetValue("ACTUAL_SUB_PATH", out var actualSubPath))
|
||||
Environment.SetEnvironmentVariable("ACTUAL_SUB_PATH", actualSubPath);
|
||||
|
||||
if (variablesFromFile.TryGetValue("SWAGGER_SUB_PATH", out var swaggerSubPath))
|
||||
Environment.SetEnvironmentVariable("SWAGGER_SUB_PATH", swaggerSubPath);
|
||||
|
||||
return result.Build();
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user