add config element to load environment variables from a file

pull/880/head
Sebastian Bäumlisberger 2021-10-31 00:33:58 +02:00
parent d31c2a6a0a
commit eef1d5841e
2 changed files with 46 additions and 0 deletions

View File

@ -219,6 +219,14 @@ This optional element can be specified multiple times if necessary to specify en
<env name="HOME" value="c:\abc" />
```
### Environment File
This optional element can be specified one time to specify a file to load environment variables from. Each variable definition must be on a separate line and in the format "key=value". Empty lines and lines starting with "#" are ignored. The syntax is:
```xml
<envFile>%BASE%/env.txt</env-file>
```
### interactive
If this optional element is specified, the service will be allowed to interact with the desktop, such as by showing a new window and dialog boxes.

View File

@ -78,6 +78,8 @@ namespace WinSW
// Also inject system environment variables
Environment.SetEnvironmentVariable(WinSWSystem.EnvVarNameServiceId, this.Name);
this.LoadEnvironmentVariablesFromFile();
this.environmentVariables = this.LoadEnvironmentVariables();
}
@ -449,6 +451,11 @@ namespace WinSW
/// </summary>
public override Dictionary<string, string> EnvironmentVariables => this.environmentVariables;
/// <summary>
/// File from which environment variables are loaded.
/// </summary>
public string? EnvironmentVariablesFile => this.SingleElementOrNull("envFile");
/// <summary>
/// List of downloads to be performed by the wrapper before starting
/// a service.
@ -623,6 +630,37 @@ namespace WinSW
return environment;
}
private void LoadEnvironmentVariablesFromFile()
{
var envFile = this.SingleElementOrNull("envFile");
if (envFile is null)
{
return;
}
foreach (string line in File.ReadAllLines(envFile))
{
if (line.Length == 0 || line.StartsWith("#"))
{
// ignore empty lines and comments
continue;
}
int equalsSignIndex = line.IndexOf("=");
if (equalsSignIndex == -1)
{
throw new WinSWException("The environment variables file contains one or more invalid entries. Each variable definition must be on a separate line and in the format \"key=value\".");
}
string key = line.Substring(0, equalsSignIndex);
string value = line.Substring(equalsSignIndex + 1);
Environment.SetEnvironmentVariable(key, value);
}
}
private ProcessCommand GetProcessCommand(string name)
{
var node = this.root.SelectSingleNode(name);