1
0
Fork 0
mirror of https://github.com/denoland/deno.git synced 2025-01-18 03:44:05 -05:00

BREAKING: Map-like interface for Deno.env (#4942)

This commit is contained in:
Valentin Anger 2020-04-29 20:48:19 +02:00 committed by GitHub
parent 17cf2ecdac
commit 721a4ad59d
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 53 additions and 58 deletions

View file

@ -116,29 +116,35 @@ declare namespace Deno {
*/ */
export function exit(code?: number): never; export function exit(code?: number): never;
/** Returns a snapshot of the environment variables at invocation. Changing a export const env: {
* property in the object will set that variable in the environment for the /** Retrieve the value of an environment variable. Returns undefined if that
* process. The environment object will only accept `string`s as values. * key doesn't exist.
* *
* const myEnv = Deno.env(); * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice"
* console.log(myEnv.SHELL); * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined"
* myEnv.TEST_VAR = "HELLO"; *
* const newEnv = Deno.env(); * Requires `allow-env` permission. */
* console.log(myEnv.TEST_VAR === newEnv.TEST_VAR); // outputs "true" get(key: string): string | undefined;
*
* Requires `allow-env` permission. */
export function env(): {
[index: string]: string;
};
/** Retrieve the value of an environment variable. Returns undefined if that /** Set the value of an environment variable.
* key doesn't exist. *
* * Deno.env.set("SOME_VAR", "Value"));
* console.log(Deno.env("HOME")); // e.g. outputs "/home/alice" * Deno.env.get("SOME_VAR"); // outputs "Value"
* console.log(Deno.env("MADE_UP_VAR")); // outputs "Undefined" *
* * Requires `allow-env` permission. */
* Requires `allow-env` permission. */ set(key: string, value: string): void;
export function env(key: string): string | undefined;
/** Returns a snapshot of the environment variables at invocation.
*
* Deno.env.set("TEST_VAR", "A");
* const myEnv = Deno.env.toObject();
* console.log(myEnv.SHELL);
* Deno.env.set("TEST_VAR", "B");
* console.log(myEnv.TEST_VAR); // outputs "A"
*
* Requires `allow-env` permission. */
toObject(): { [index: string]: string };
};
/** **UNSTABLE** */ /** **UNSTABLE** */
export type DirKind = export type DirKind =

View file

@ -27,22 +27,13 @@ function getEnv(key: string): string | undefined {
return sendSync("op_get_env", { key })[0]; return sendSync("op_get_env", { key })[0];
} }
export function env(): { [index: string]: string }; export const env = {
export function env(key: string): string | undefined; get: getEnv,
export function env( toObject(): { [key: string]: string } {
key?: string return sendSync("op_env");
): { [index: string]: string } | string | undefined { },
if (key) { set: setEnv,
return getEnv(key); };
}
const env = sendSync("op_env");
return new Proxy(env, {
set(obj, prop: string, value: string): boolean {
setEnv(prop, value);
return Reflect.set(obj, prop, value);
},
});
}
type DirKind = type DirKind =
| "home" | "home"

View file

@ -8,24 +8,22 @@ import {
} from "./test_util.ts"; } from "./test_util.ts";
unitTest({ perms: { env: true } }, function envSuccess(): void { unitTest({ perms: { env: true } }, function envSuccess(): void {
const env = Deno.env(); Deno.env.set("TEST_VAR", "A");
assert(env !== null); const env = Deno.env.toObject();
// eslint-disable-next-line @typescript-eslint/camelcase Deno.env.set("TEST_VAR", "B");
env.test_var = "Hello World"; assertEquals(env["TEST_VAR"], "A");
const newEnv = Deno.env(); assertNotEquals(Deno.env.get("TEST_VAR"), env["TEST_VAR"]);
assertEquals(env.test_var, newEnv.test_var);
assertEquals(Deno.env("test_var"), env.test_var);
}); });
unitTest({ perms: { env: true } }, function envNotFound(): void { unitTest({ perms: { env: true } }, function envNotFound(): void {
const r = Deno.env("env_var_does_not_exist!"); const r = Deno.env.get("env_var_does_not_exist!");
assertEquals(r, undefined); assertEquals(r, undefined);
}); });
unitTest(function envPermissionDenied1(): void { unitTest(function envPermissionDenied1(): void {
let err; let err;
try { try {
Deno.env(); Deno.env.toObject();
} catch (e) { } catch (e) {
err = e; err = e;
} }
@ -37,7 +35,7 @@ unitTest(function envPermissionDenied1(): void {
unitTest(function envPermissionDenied2(): void { unitTest(function envPermissionDenied2(): void {
let err; let err;
try { try {
Deno.env("PATH"); Deno.env.get("PATH");
} catch (e) { } catch (e) {
err = e; err = e;
} }
@ -62,7 +60,7 @@ unitTest(
): Promise<void> => { ): Promise<void> => {
const src = ` const src = `
console.log( console.log(
${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env(k)) ${JSON.stringify(Object.keys(expectedEnv))}.map(k => Deno.env.get(k))
)`; )`;
const proc = Deno.run({ const proc = Deno.run({
cmd: [Deno.execPath(), "eval", src], cmd: [Deno.execPath(), "eval", src],
@ -79,8 +77,8 @@ unitTest(
proc.close(); proc.close();
}; };
assertEquals(Deno.env("path"), Deno.env("PATH")); assertEquals(Deno.env.get("path"), Deno.env.get("PATH"));
assertEquals(Deno.env("Path"), Deno.env("PATH")); assertEquals(Deno.env.get("Path"), Deno.env.get("PATH"));
// Check 'foo', 'Foo' and 'Foo' are case folded. // Check 'foo', 'Foo' and 'Foo' are case folded.
await checkChildEnv({ foo: "X" }, { foo: "X", Foo: "X", FOO: "X" }); await checkChildEnv({ foo: "X" }, { foo: "X", Foo: "X", FOO: "X" });

View file

@ -11,7 +11,7 @@ const test: { [key: string]: Function } = {
makeTempDirSync(); makeTempDirSync();
}, },
envRequired(): void { envRequired(): void {
env().home; env.get("home");
}, },
netRequired(): void { netRequired(): void {
listen({ transport: "tcp", port: 4541 }); listen({ transport: "tcp", port: 4541 });

View file

@ -7,7 +7,7 @@ function pathBase(p: string): string {
return parts[parts.length - 1]; return parts[parts.length - 1];
} }
const token = Deno.env()["GIST_TOKEN"]; const token = Deno.env.get("GIST_TOKEN");
if (!token) { if (!token) {
console.error("GIST_TOKEN environmental variable not set."); console.error("GIST_TOKEN environmental variable not set.");
console.error("Get a token here: https://github.com/settings/tokens"); console.error("Get a token here: https://github.com/settings/tokens");

View file

@ -534,8 +534,8 @@ class Module {
} }
static _initPaths(): void { static _initPaths(): void {
const homeDir = Deno.env("HOME"); const homeDir = Deno.env.get("HOME");
const nodePath = Deno.env("NODE_PATH"); const nodePath = Deno.env.get("NODE_PATH");
// Removed $PREFIX/bin/node case // Removed $PREFIX/bin/node case

View file

@ -30,7 +30,7 @@ export const process = {
on, on,
get env(): { [index: string]: string } { get env(): { [index: string]: string } {
// using getter to avoid --allow-env unless it's used // using getter to avoid --allow-env unless it's used
return Deno.env(); return Deno.env.toObject();
}, },
get argv(): string[] { get argv(): string[] {
// Deno.execPath() also requires --allow-env // Deno.execPath() also requires --allow-env

View file

@ -3,7 +3,7 @@ import { assert, assertThrows, assertEquals } from "../testing/asserts.ts";
import { process } from "./process.ts"; import { process } from "./process.ts";
// NOTE: Deno.execPath() (and thus process.argv) currently requires --allow-env // NOTE: Deno.execPath() (and thus process.argv) currently requires --allow-env
// (Also Deno.env() (and process.env) requires --allow-env but it's more obvious) // (Also Deno.env.toObject() (and process.env) requires --allow-env but it's more obvious)
test({ test({
name: "process.cwd and process.chdir success", name: "process.cwd and process.chdir success",

View file

@ -39,7 +39,7 @@ export function resolve(...pathSegments: string[]): string {
// absolute path, get cwd for that drive, or the process cwd if // absolute path, get cwd for that drive, or the process cwd if
// the drive cwd is not available. We're sure the device is not // the drive cwd is not available. We're sure the device is not
// a UNC path at this points, because UNC paths are always absolute. // a UNC path at this points, because UNC paths are always absolute.
path = env()[`=${resolvedDevice}`] || cwd(); path = env.get(`=${resolvedDevice}`) || cwd();
// Verify that a cwd was found and that it actually points // Verify that a cwd was found and that it actually points
// to our drive. If not, default to the drive's root. // to our drive. If not, default to the drive's root.