Skip to content

Commit 402a20b

Browse files
committed
Add well-known environment variables to culture directive parsing
1 parent b7429cf commit 402a20b

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

src/System.CommandLine/Builder/CommandLineBuilderExtensions.cs

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -235,6 +235,9 @@ public static CommandLineBuilder UseCultureDirective(
235235
builder.AddMiddleware(async (context, next) =>
236236
{
237237
var directives = context.ParseResult.Directives;
238+
239+
ApplyCultureFromWellKnownEnvironmentVariables();
240+
238241
if (directives.Contains("invariantculture"))
239242
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
240243
if (directives.Contains("invariantuiculture"))
@@ -250,6 +253,50 @@ public static CommandLineBuilder UseCultureDirective(
250253
CultureInfo.CurrentUICulture = CultureInfo.GetCultureInfo(cultureName);
251254
}
252255
await next(context);
256+
257+
static void ApplyCultureFromWellKnownEnvironmentVariables()
258+
{
259+
const string invariant_name = "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT";
260+
const string uiinvariant_name = "DOTNET_SYSTEM_GLOBALIZATION_UIINVARIANT";
261+
const string culture_name = "DOTNET_SYSTEM_GLOBALIZATION_CULTURE";
262+
const string uiculture_name = "DOTNET_SYSTEM_GLOBALIZATION_UICULTURE";
263+
264+
if (GetEnvironmentVariable(invariant_name) is string invariant &&
265+
ParseBooleanEnvironmentVariableValue(invariant))
266+
{
267+
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
268+
}
269+
if (GetEnvironmentVariable(uiinvariant_name) is string uiinvariant &&
270+
ParseBooleanEnvironmentVariableValue(uiinvariant))
271+
{
272+
CultureInfo.CurrentCulture = CultureInfo.InvariantCulture;
273+
}
274+
if (GetEnvironmentVariable(culture_name) is string culture)
275+
{
276+
CultureInfo? c = null;
277+
try { c = CultureInfo.GetCultureInfo(culture); }
278+
catch (CultureNotFoundException) { }
279+
if (!(c is null))
280+
CultureInfo.CurrentCulture = c;
281+
}
282+
if (GetEnvironmentVariable(uiculture_name) is string uiculture)
283+
{
284+
CultureInfo? c = null;
285+
try { c = CultureInfo.GetCultureInfo(uiculture); }
286+
catch (CultureNotFoundException) { }
287+
if (!(c is null))
288+
CultureInfo.CurrentUICulture = c;
289+
}
290+
}
291+
292+
static bool ParseBooleanEnvironmentVariableValue(string value)
293+
{
294+
if (bool.TryParse(value, out bool boolResult))
295+
return boolResult;
296+
if (int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int numResult))
297+
return numResult != 0;
298+
return false;
299+
}
253300
}, MiddlewareOrderInternal.CultureDirective);
254301

255302
return builder;

0 commit comments

Comments
 (0)