renovatebot-github/src/input.ts
Jeroen de Bruijn 9c8a784d88
feat: add passing of Renovate environment variables (#534)
Inputs may now be provided using environment variables, as well as the existing inputs. None of the
inputs are required any more, so it is possible to use only environment variables. Nevertheless all
inputs must be provided in some way, either using the input or their corresponding environment
variables.

BREAKING CHANGE: The `configurationFile` input no longer has a default value. This means that a
value for it is now required using the `configurationFile` input or the `RENOVATE_CONFIG_FILE`
environment variable.

Co-authored-by: Michael Kriese <michael.kriese@visualon.de>
2021-03-08 09:42:52 +01:00

98 lines
2.4 KiB
TypeScript

import * as core from '@actions/core';
import path from 'path';
interface EnvironmentVariable {
key: string;
value: string;
}
class Input {
readonly options = {
envRegex: /^(?:RENOVATE_\w+|LOG_LEVEL)$/,
configurationFile: {
input: 'configurationFile',
env: 'RENOVATE_CONFIG_FILE',
optional: true,
},
token: {
input: 'token',
env: 'RENOVATE_TOKEN',
optional: false,
},
} as const;
readonly token: Readonly<EnvironmentVariable>;
private readonly _environmentVariables: Map<string, string>;
private readonly _configurationFile: Readonly<EnvironmentVariable>;
constructor() {
this._environmentVariables = new Map(
Object.entries(process.env).filter(([key]) =>
this.options.envRegex.test(key)
)
);
this.token = this.get(
this.options.token.input,
this.options.token.env,
this.options.token.optional
);
this._configurationFile = this.get(
this.options.configurationFile.input,
this.options.configurationFile.env,
this.options.configurationFile.optional
);
}
configurationFile(): EnvironmentVariable | null {
if (this._configurationFile.value !== '') {
return {
key: this._configurationFile.key,
value: path.resolve(this._configurationFile.value),
};
}
return null;
}
/**
* Convert to environment variables.
*
* @note The environment variables listed below are filtered out.
* - Token, available with the `token` property.
* - Configuration file, available with the `configurationFile()` method.
*/
toEnvironmentVariables(): EnvironmentVariable[] {
return [...this._environmentVariables].map(([key, value]) => ({
key,
value,
}));
}
private get(
input: string,
env: string,
optional: boolean
): EnvironmentVariable {
const fromInput = core.getInput(input);
const fromEnv = this._environmentVariables.get(env);
if (fromInput === '' && fromEnv === undefined && !optional) {
throw new Error(
[
`'${input}' MUST be passed using its input or the '${env}'`,
'environment variable',
].join(' ')
);
}
this._environmentVariables.delete(env);
if (fromInput !== '') {
return { key: env, value: fromInput };
}
return { key: env, value: fromEnv !== undefined ? fromEnv : '' };
}
}
export default Input;
export { EnvironmentVariable, Input };