Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Installer: supports windows #499

Merged
merged 28 commits into from
Jun 18, 2019
Merged
Show file tree
Hide file tree
Changes from 21 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
160 changes: 99 additions & 61 deletions installer/mod.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env deno --allow-all

// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const {
args,
env,
Expand All @@ -9,14 +9,15 @@ const {
exit,
stdin,
stat,
readAll,
run,
remove
chmod,
remove,
run
} = Deno;
import * as path from "../fs/path.ts";

const encoder = new TextEncoder();
const decoder = new TextDecoder("utf-8");
const isWindows = Deno.platform.os === "win";

enum Permission {
Read,
Expand Down Expand Up @@ -86,69 +87,104 @@ function createDirIfNotExists(path: string): void {
}
}

function checkIfExistsInPath(path: string): boolean {
const { PATH } = env();

const paths = (PATH as string).split(":");
function checkIfExistsInPath(filePath: string): boolean {
// In Windows's Powershell. $PATH not exist. use $Path instead.
// $HOMEDRIVE is only use in Windows.
const { PATH, Path, HOMEDRIVE } = env();
axetroy marked this conversation as resolved.
Show resolved Hide resolved

return paths.includes(path);
}
let envPath = (PATH as string) || (Path as string) || "";

function getInstallerDir(): string {
const { HOME } = env();

if (!HOME) {
throw new Error("$HOME is not defined.");
}
const paths = envPath.split(isWindows ? ";" : ":");

return path.join(HOME, ".deno", "bin");
}
let fileAbsolutePath = filePath;

// TODO: fetch doesn't handle redirects yet - once it does this function
// can be removed
async function fetchWithRedirects(
url: string,
redirectLimit: number = 10
// eslint-disable-next-line @typescript-eslint/no-explicit-any
): Promise<any> {
// TODO: `Response` is not exposed in global so 'any'
const response = await fetch(url);

if (response.status === 301 || response.status === 302) {
if (redirectLimit > 0) {
const redirectUrl = response.headers.get("location")!;
return await fetchWithRedirects(redirectUrl, redirectLimit - 1);
for (const p of paths) {
let pathInEnv = path.normalize(p);
axetroy marked this conversation as resolved.
Show resolved Hide resolved
// In Windows. We can get the path from env. eg. C:\Users\username\.deno\bin
// But in the path of Deno, there is no drive letter. eg \Users\username\.deno\bin in deno
axetroy marked this conversation as resolved.
Show resolved Hide resolved
if (isWindows) {
const driverLetterReg = /^[c-z]:/i;
axetroy marked this conversation as resolved.
Show resolved Hide resolved
if (driverLetterReg.test(pathInEnv)) {
fileAbsolutePath = HOMEDRIVE + "\\" + fileAbsolutePath;
}
}
if (pathInEnv === fileAbsolutePath) {
return true;
}
fileAbsolutePath = filePath;
}

return response;
return false;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
async function fetchModule(url: string): Promise<any> {
const response = await fetchWithRedirects(url);
function getInstallerDir(): string {
// In Windows's Powershell. $HOME environmental variable maybe null. use $HOMEPATH instead.
axetroy marked this conversation as resolved.
Show resolved Hide resolved
let { HOME, HOMEPATH } = env();

const HOME_PATH = HOME || HOMEPATH;

if (response.status !== 200) {
// TODO: show more debug information like status and maybe body
throw new Error(`Failed to get remote script ${url}.`);
if (!HOME_PATH) {
throw new Error("$HOME is not defined.");
axetroy marked this conversation as resolved.
Show resolved Hide resolved
}

const body = await readAll(response.body);
return decoder.decode(body);
return path.join(HOME_PATH, ".deno", "bin");
}

function showHelp(): void {
console.log(`deno installer
Install remote or local script as executables.

USAGE:
deno https://deno.land/std/installer/mod.ts EXE_NAME SCRIPT_URL [FLAGS...]
deno https://deno.land/std/installer/mod.ts EXE_NAME SCRIPT_URL [FLAGS...]

ARGS:
EXE_NAME Name for executable
EXE_NAME Name for executable
SCRIPT_URL Local or remote URL of script to install
[FLAGS...] List of flags for script, both Deno permission and script specific flag can be used.
`);
`);
}

async function generateExecutable(
filePath: string,
commands: string[]
): Promise<void> {
// In Windows. if use Powershell to run the installed module. It will look up .cmd file.
axetroy marked this conversation as resolved.
Show resolved Hide resolved
// genereate Batch script
axetroy marked this conversation as resolved.
Show resolved Hide resolved
if (isWindows) {
const template = `% This executable is generated by Deno. Please don't modify it unless you know what it means. %
@IF EXIST "%~dp0\deno.exe" (
"%~dp0\deno.exe" ${commands.slice(1).join(" ")} %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.TS;=;%
${commands.join(" ")} %*
)
`;
const cmdFile = filePath + ".cmd";
axetroy marked this conversation as resolved.
Show resolved Hide resolved
await writeFile(cmdFile, encoder.encode(template));
await chmod(cmdFile, 0o755);
axetroy marked this conversation as resolved.
Show resolved Hide resolved
}

// generate Shell script
const template = `#/bin/sh
# This executable is generated by Deno. Please don't modify it unless you know what it means.
basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")

case \`uname\` in
*CYGWIN*) basedir=\`cygpath -w "$basedir"\`;;
esac

if [ -x "$basedir/deno" ]; then
"$basedir/deno" ${commands.slice(1).join(" ")} "$@"
ret=$?
else
${commands.join(" ")} "$@"
ret=$?
fi
exit $ret
`;
await writeFile(filePath, encoder.encode(template));
await chmod(filePath, 0o755);
axetroy marked this conversation as resolved.
Show resolved Hide resolved
}

export async function install(
Expand Down Expand Up @@ -176,10 +212,20 @@ export async function install(
}

// ensure script that is being installed exists
if (moduleUrl.startsWith("http")) {
if (/^https?:\/\/.{3,}/.test(moduleUrl)) {
axetroy marked this conversation as resolved.
Show resolved Hide resolved
// remote module
console.log(`Downloading: ${moduleUrl}\n`);
await fetchModule(moduleUrl);
const ps = run({
args: ["deno", "fetch", moduleUrl],
stdout: "inherit",
stderr: "inherit"
});

const { code } = await ps.status();

if (code !== 0) {
throw new Error("Fail to fetch remote module.");
axetroy marked this conversation as resolved.
Show resolved Hide resolved
}
} else {
// assume that it's local file
moduleUrl = path.resolve(moduleUrl);
Expand All @@ -201,28 +247,17 @@ export async function install(

const commands = [
"deno",
"run",
...grantedPermissions.map(getFlagFromPermission),
moduleUrl,
...scriptArgs,
"$@"
...scriptArgs
];

// TODO: add windows Version
const template = `#/bin/sh\n${commands.join(" ")}`;
await writeFile(filePath, encoder.encode(template));

const makeExecutable = run({ args: ["chmod", "+x", filePath] });
const { code } = await makeExecutable.status();
makeExecutable.close();

if (code !== 0) {
throw new Error("Failed to make file executable");
}
await generateExecutable(filePath, commands);

console.log(`✅ Successfully installed ${moduleName}`);
console.log(filePath);

// TODO: add Windows version
if (!checkIfExistsInPath(installerDir)) {
console.log("\nℹ️ Add ~/.deno/bin to PATH");
console.log(
Expand All @@ -244,6 +279,9 @@ export async function uninstall(moduleName: string): Promise<void> {
}

await remove(filePath);
axetroy marked this conversation as resolved.
Show resolved Hide resolved
if (isWindows) {
await remove(filePath + ".cmd");
}
console.log(`ℹ️ Uninstalled ${moduleName}`);
}

Expand Down
88 changes: 79 additions & 9 deletions installer/test.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
// Copyright 2018-2019 the Deno authors. All rights reserved. MIT license.
const { readFile, run, stat, makeTempDir, remove, env } = Deno;
const { run, stat, makeTempDir, remove, env } = Deno;

import { test, runIfMain, TestFunction } from "../testing/mod.ts";
import { assert, assertEquals, assertThrowsAsync } from "../testing/asserts.ts";
import { BufReader, EOF } from "../io/bufio.ts";
import { TextProtoReader } from "../textproto/mod.ts";
import { install, uninstall } from "./mod.ts";
import * as path from "../fs/path.ts";
import * as fs from "../fs/mod.ts";

let fileServer: Deno.Process;
const isWindows = Deno.platform.os === "win";

// copied from `http/file_server_test.ts`
async function startFileServer(): Promise<void> {
Expand Down Expand Up @@ -63,11 +65,40 @@ installerTest(async function installBasic(): Promise<void> {
const fileInfo = await stat(filePath);
assert(fileInfo.isFile());

const fileBytes = await readFile(filePath);
const fileContents = new TextDecoder().decode(fileBytes);
if (isWindows) {
assertEquals(
await fs.readFileStr(filePath + ".cmd"),
`% This executable is generated by Deno. Please don't modify it unless you know what it means. %
@IF EXIST "%~dp0\deno.exe" (
"%~dp0\deno.exe" run http://localhost:4500/http/file_server.ts %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.TS;=;%
deno run http://localhost:4500/http/file_server.ts %*
)
`
);
}

assertEquals(
fileContents,
"#/bin/sh\ndeno http://localhost:4500/http/file_server.ts $@"
await fs.readFileStr(filePath),
`#/bin/sh
# This executable is generated by Deno. Please don't modify it unless you know what it means.
basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")

case \`uname\` in
*CYGWIN*) basedir=\`cygpath -w "$basedir"\`;;
esac

if [ -x "$basedir/deno" ]; then
"$basedir/deno" run http://localhost:4500/http/file_server.ts "$@"
ret=$?
else
deno run http://localhost:4500/http/file_server.ts "$@"
ret=$?
fi
exit $ret
`
);
});

Expand All @@ -81,11 +112,40 @@ installerTest(async function installWithFlags(): Promise<void> {
const { HOME } = env();
const filePath = path.resolve(HOME, ".deno/bin/file_server");

const fileBytes = await readFile(filePath);
const fileContents = new TextDecoder().decode(fileBytes);
if (isWindows) {
assertEquals(
await fs.readFileStr(filePath + ".cmd"),
`% This executable is generated by Deno. Please don't modify it unless you know what it means. %
@IF EXIST "%~dp0\deno.exe" (
"%~dp0\deno.exe" run --allow-net --allow-read http://localhost:4500/http/file_server.ts --foobar %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.TS;=;%
deno run --allow-net --allow-read http://localhost:4500/http/file_server.ts --foobar %*
)
`
);
}

assertEquals(
fileContents,
"#/bin/sh\ndeno --allow-net --allow-read http://localhost:4500/http/file_server.ts --foobar $@"
await fs.readFileStr(filePath),
`#/bin/sh
# This executable is generated by Deno. Please don't modify it unless you know what it means.
basedir=$(dirname "$(echo "$0" | sed -e 's,\\\\,/,g')")

case \`uname\` in
*CYGWIN*) basedir=\`cygpath -w "$basedir"\`;;
esac

if [ -x "$basedir/deno" ]; then
"$basedir/deno" run --allow-net --allow-read http://localhost:4500/http/file_server.ts --foobar "$@"
ret=$?
else
deno run --allow-net --allow-read http://localhost:4500/http/file_server.ts --foobar "$@"
ret=$?
fi
exit $ret
`
);
});

Expand All @@ -106,6 +166,16 @@ installerTest(async function uninstallBasic(): Promise<void> {
assertEquals(e.kind, Deno.ErrorKind.NotFound);
}

if (isWindows) {
try {
await stat(filePath + ".cmd");
axetroy marked this conversation as resolved.
Show resolved Hide resolved
} catch (e) {
thrown = true;
assert(e instanceof Deno.DenoError);
assertEquals(e.kind, Deno.ErrorKind.NotFound);
}
}

assert(thrown);
});

Expand Down