From c7dca80ac9edc49aaff5c190c9303ee4cfbf6720 Mon Sep 17 00:00:00 2001 From: Bradley Grainger Date: Fri, 12 Jul 2024 13:19:02 -0700 Subject: [PATCH] Allow additional environment variables to be set when running an app. (#67) This is typed as a non-null get-only property so users can use collection initialization syntax: new AppRunnerSettings { EnvironmentVariables = { { "name", "value" }, }, } --- src/Faithlife.Build/AppRunner.cs | 29 ++++++++++++++++-------- src/Faithlife.Build/AppRunnerSettings.cs | 6 +++++ 2 files changed, 25 insertions(+), 10 deletions(-) diff --git a/src/Faithlife.Build/AppRunner.cs b/src/Faithlife.Build/AppRunner.cs index e31f322..1d74297 100644 --- a/src/Faithlife.Build/AppRunner.cs +++ b/src/Faithlife.Build/AppRunner.cs @@ -127,18 +127,27 @@ private static int DoRunApp(string path, AppRunnerSettings settings) var handleOutputLine = settings.HandleOutputLine; var handleErrorLine = settings.HandleErrorLine; + var startInfo = new ProcessStartInfo + { + FileName = commandPath, + Arguments = argsString, + WorkingDirectory = settings.WorkingDirectory, + UseShellExecute = false, + RedirectStandardOutput = handleOutputLine is not null, + RedirectStandardError = handleErrorLine is not null, + CreateNoWindow = false, + }; + + // add environment variables only if they're specified (to avoid touching the lazy ProcessStartInfo.Environment property) + if (settings.EnvironmentVariables.Count != 0) + { + foreach (var (name, value) in settings.EnvironmentVariables) + startInfo.Environment.Add(name, value); + } + using var process = new Process { - StartInfo = new ProcessStartInfo - { - FileName = commandPath, - Arguments = argsString, - WorkingDirectory = settings.WorkingDirectory, - UseShellExecute = false, - RedirectStandardOutput = handleOutputLine is not null, - RedirectStandardError = handleErrorLine is not null, - CreateNoWindow = false, - }, + StartInfo = startInfo, }; if (!settings.NoEcho) diff --git a/src/Faithlife.Build/AppRunnerSettings.cs b/src/Faithlife.Build/AppRunnerSettings.cs index db29cda..d7d576e 100644 --- a/src/Faithlife.Build/AppRunnerSettings.cs +++ b/src/Faithlife.Build/AppRunnerSettings.cs @@ -15,6 +15,11 @@ public sealed class AppRunnerSettings /// public string? WorkingDirectory { get; set; } + /// + /// Additional environment variables to set when running the app. + /// + public IDictionary EnvironmentVariables { get; private set; } = new Dictionary(StringComparer.OrdinalIgnoreCase); + /// /// True if the process information should not be written to standard error. /// @@ -52,6 +57,7 @@ public AppRunnerSettings Clone() { var clone = (AppRunnerSettings) MemberwiseClone(); clone.Arguments = clone.Arguments?.ToList(); + clone.EnvironmentVariables = new Dictionary(clone.EnvironmentVariables, StringComparer.OrdinalIgnoreCase); return clone; } }