Created
May 7, 2021 09:44
-
-
Save clo4/af4b737541b34911ca8cc6973e3d5c7c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Copyright 2021 SeparateRecords | |
| // | |
| // Permission to use, copy, modify, and/or distribute this software for any purpose | |
| // with or without fee is hereby granted, provided that the above copyright notice | |
| // and this permission notice appear in all copies. | |
| // | |
| // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH | |
| // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND | |
| // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, | |
| // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS | |
| // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER | |
| // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF | |
| // THIS SOFTWARE. | |
| /** | |
| * Tagged template literal to replace expressions using `Deno.env`. | |
| * | |
| * Requires `--allow-env`. | |
| * | |
| * @example | |
| * ``` | |
| * expand`${"XDG_CONFIG_DIR"}/app/config.json` | |
| * //=> /home/username/.config/app/config.json | |
| * ``` | |
| */ | |
| export function expand(strings: TemplateStringsArray, ...keys: string[]) { | |
| let output = ""; | |
| let stringIndex = 0; | |
| let keyIndex = 0; | |
| while (keyIndex < keys.length) { | |
| output += strings[stringIndex]; | |
| const key = keys[keyIndex]; | |
| stringIndex++; | |
| keyIndex++; | |
| // Deno.env may throw if given an invalid character, | |
| // like "", "\0", or "=". Instead of throwing, this | |
| // follows the Bash/ZSH behaviour of returning the key. | |
| try { | |
| output += Deno.env.get(key) ?? ""; | |
| } catch { | |
| output += key; | |
| } | |
| } | |
| // stringIndex won't have been increased if there were no keys, | |
| // and since there must always be at least one string, this is | |
| // guaranteed to work. | |
| output += strings[stringIndex]; | |
| return output; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment