Skip to content

Commit 38febbe

Browse files
committed
Add .env integration
closes #105
1 parent 1116dc7 commit 38febbe

File tree

3 files changed

+66
-0
lines changed

3 files changed

+66
-0
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -366,3 +366,9 @@ FodyWeavers.xsd
366366

367367
# Rider config directory
368368
.idea/
369+
370+
# Environment files
371+
*.env
372+
*.env.*
373+
!*.env.template
374+
!*.env.*.template

ThunderstoreCLI/Configuration/Config.cs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,11 @@ private Config()
3232
}
3333
public static Config FromCLI(IConfigProvider cliConfig)
3434
{
35+
var environment = Environment.GetEnvironmentVariable("DOTNET_ENVIRONMENT")
36+
?? Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")
37+
?? Environment.GetEnvironmentVariable("ENVIRONMENT");
38+
DotEnv.LoadAll(environment);
39+
3540
List<IConfigProvider> providers = new();
3641
providers.Add(cliConfig);
3742
providers.Add(new EnvironmentConfig());
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
namespace ThunderstoreCLI.Configuration;
2+
3+
public static class DotEnv
4+
{
5+
public static void Load(string filePath)
6+
{
7+
if (!File.Exists(filePath))
8+
return;
9+
10+
foreach (var line in File.ReadAllLines(filePath))
11+
{
12+
if (string.IsNullOrWhiteSpace(line) || line.TrimStart().StartsWith('#'))
13+
continue;
14+
15+
var parts = line.Split('=', 2);
16+
if (parts.Length != 2)
17+
continue;
18+
19+
var key = parts[0].Trim();
20+
var value = parts[1].Trim();
21+
22+
if (value.Length >= 2)
23+
{
24+
if ((value.StartsWith('"') && value.EndsWith('"')) ||
25+
(value.StartsWith('\'') && value.EndsWith('\'')))
26+
{
27+
value = value.Substring(1, value.Length - 2);
28+
}
29+
}
30+
31+
Environment.SetEnvironmentVariable(key, value);
32+
}
33+
}
34+
35+
public static void LoadAll(string? environment = null)
36+
{
37+
var filesToLoad = new List<string> { ".env" };
38+
39+
if (!string.IsNullOrEmpty(environment))
40+
{
41+
filesToLoad.Add($".env.{environment}");
42+
filesToLoad.Add($".env.{environment.ToLowerInvariant()}");
43+
filesToLoad.Add($".{environment}.env");
44+
filesToLoad.Add($".{environment.ToLowerInvariant()}.env");
45+
}
46+
47+
filesToLoad.Add(".env.local");
48+
filesToLoad.Add(".local.env");
49+
50+
foreach (var file in filesToLoad)
51+
{
52+
Load(file);
53+
}
54+
}
55+
}

0 commit comments

Comments
 (0)