Skip to content

Commit

Permalink
feat: substitute environment variables (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
usernamehw committed Nov 1, 2021
1 parent 2fca7eb commit 84d6223
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions src/substituteVariables.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ const enum VariableNames {
pathSeparator = '${pathSeparator}', // `/` on macOS or linux, `\` on Windows
lineNumber = '${lineNumber}', // the current selected line number in the active file
selectedText = '${selectedText}', // the current selected text in the active file
environmentVariable = '${env}',
// ────────────────────────────────────────────────────────────
// relativeFile = '${relativeFile}', // the current opened file relative to `workspaceFolder`
// relativeFileDirname = '${relativeFileDirname}', // the current opened file's dirname relative to `workspaceFolder`
Expand All @@ -34,6 +35,7 @@ const variableRegexps = {
[VariableNames.pathSeparator]: new RegExp(escapeRegExp(VariableNames.pathSeparator), 'ig'),
[VariableNames.lineNumber]: new RegExp(escapeRegExp(VariableNames.lineNumber), 'ig'),
[VariableNames.selectedText]: new RegExp(escapeRegExp(VariableNames.selectedText), 'ig'),
[VariableNames.environmentVariable]: /\${env:([a-zA-Z_]+[a-zA-Z0-9_]*)}/i,
// [VariableNames.relativeFile]: new RegExp(escapeRegExp(VariableNames.relativeFile), 'ig'),
// [VariableNames.relativeFileDirname]: new RegExp(escapeRegExp(VariableNames.relativeFileDirname), 'ig'),
// [VariableNames.cwd]: new RegExp(escapeRegExp(VariableNames.cwd), 'ig'),
Expand Down Expand Up @@ -87,5 +89,13 @@ export function substituteVariables(str: string) {
str = str.replace(variableRegexps[VariableNames.fileWorkspaceFolder], fileWorkspaceFolder);
}
}
if (variableRegexps[VariableNames.environmentVariable].test(str)) {
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = str.match(variableRegexps[VariableNames.environmentVariable]);
const envName = match?.[1];
if (envName) {
str = str.replace(variableRegexps[VariableNames.environmentVariable], process.env[envName] || '');
}
}
return str;
}

1 comment on commit 84d6223

@depascalis
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Awesome, thank you!

Please sign in to comment.