From ff7fb5a5d696256b232f8435c53087d5b12848ab Mon Sep 17 00:00:00 2001 From: Evgeniy Karagodin Date: Mon, 24 Jun 2019 22:08:06 +0700 Subject: [PATCH] Add userHomeDir (#521) --- os/README.md | 16 ++++++++++++++++ os/mod.ts | 26 ++++++++++++++++++++++++++ os/test.ts | 8 ++++++++ test.ts | 1 + 4 files changed, 51 insertions(+) create mode 100644 os/README.md create mode 100644 os/mod.ts create mode 100644 os/test.ts diff --git a/os/README.md b/os/README.md new file mode 100644 index 000000000000..0f2ea810b4f5 --- /dev/null +++ b/os/README.md @@ -0,0 +1,16 @@ +# os + +Module provide platform-independent interface to operating system functionality. + +## Usage + +### userHomeDir + +Returns the current user's home directory. On Unix, including macOS, it returns the \$HOME environment variable. On Windows, it returns %USERPROFILE%. +Needs permissions to access env (--allow-env). + +```ts +import { userHomeDir } from "https://deno.land/std/os/mod.ts"; + +userHomeDir(); +``` diff --git a/os/mod.ts b/os/mod.ts new file mode 100644 index 000000000000..a2bb0457b61e --- /dev/null +++ b/os/mod.ts @@ -0,0 +1,26 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. + +/** + * Returns the current user's home directory. + * On Unix, including macOS, it returns the $HOME environment variable. + * On Windows, it returns %USERPROFILE%. + * Needs permissions to access env (--allow-env). + * + * Ported from Go: https://github.com/golang/go/blob/go1.12.5/src/os/file.go#L389 + */ +export function userHomeDir(): string { + let env = "HOME"; + let envErr = "$HOME"; + + if (Deno.platform.os === "win") { + env = "USERPROFILE"; + envErr = "%USERPROFILE%"; + } + + const value = Deno.env()[env]; + if (value !== "") { + return value; + } + + throw new Error(`Environment variable '${envErr}' is not defined.`); +} diff --git a/os/test.ts b/os/test.ts new file mode 100644 index 000000000000..f1993f22bafc --- /dev/null +++ b/os/test.ts @@ -0,0 +1,8 @@ +// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license. +import { test } from "../testing/mod.ts"; +import { assertNotEquals } from "../testing/asserts.ts"; +import { userHomeDir } from "./mod.ts"; + +test(function testUserHomeDir(): void { + assertNotEquals(userHomeDir(), ""); +}); diff --git a/test.ts b/test.ts index 5747be1c5e7b..1f41003f3d6f 100755 --- a/test.ts +++ b/test.ts @@ -23,6 +23,7 @@ import "./textproto/test.ts"; import "./util/test.ts"; import "./ws/test.ts"; import "./encoding/test.ts"; +import "./os/test.ts"; import { xrun } from "./prettier/util.ts"; import { red, green } from "./colors/mod.ts";