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

feat: add cross-platform which command #252

Merged
merged 5 commits into from
Apr 6, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# dax

[![deno doc](https://doc.deno.land/badge.svg)](https://doc.deno.land/https/deno.land/x/dax/mod.ts)
[![NPM Version](https://img.shields.io/npm/v/dax-sh.svg?style=flat)](http://www.npmjs.com/package/dax-sh)
[![npm Version](https://img.shields.io/npm/v/dax-sh.svg?style=flat)](http://www.npmjs.com/package/dax-sh)

<img src="src/assets/logo.svg" height="150px" alt="dax logo">

Expand Down Expand Up @@ -852,6 +852,7 @@ Currently implemented (though not every option is supported):
- [`unset`](https://man7.org/linux/man-pages/man1/unset.1p.html) - Unsets an environment variable.
- [`cat`](https://man7.org/linux/man-pages/man1/cat.1.html) - Concatenate files and print on the standard output
- [`printenv`](https://man7.org/linux/man-pages/man1/printenv.1.html) - Print all or part of environment
- `which` - Resolves the path to an executable (`-a` flag is not supported at this time)
- More to come. Will try to get a similar list as https://deno.land/manual/tools/task_runner#built-in-commands

You can also register your own commands with the shell parser (see below).
Expand Down
43 changes: 43 additions & 0 deletions mod.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2169,6 +2169,49 @@ Deno.test("nice error message when not awaiting a CommandBuilder", async () => {
);
});

Deno.test("which uses same as $.which", async () => {
{
const whichFnOutput = await $.which("deno");
const whichShellOutput = await $`which deno`.text();
if (Deno.build.os === "windows") {
// windows is case insensitive
assertEquals(whichFnOutput?.toLowerCase(), whichShellOutput.toLowerCase());
} else {
assertEquals(whichFnOutput, whichShellOutput);
}
}
// arg not found
{
const whichShellOutput = await $`which non-existent-command-that-not-exists`
.noThrow()
.stderr("piped")
.stdout("piped");
assertEquals(whichShellOutput.stderr, "");
assertEquals(whichShellOutput.stdout, "");
assertEquals(whichShellOutput.code, 1);
}
// invalid args
{
const whichShellOutput = await $`which deno test`
.noThrow()
.stderr("piped")
.stdout("piped");
assertEquals(whichShellOutput.stderr, "which: unsupported too many arguments\n");
assertEquals(whichShellOutput.stdout, "");
assertEquals(whichShellOutput.code, 2);
}
// invalid arg kind
{
const whichShellOutput = await $`which -h`
.noThrow()
.stderr("piped")
.stdout("piped");
assertEquals(whichShellOutput.stderr, "which: unsupported flag: -h\n");
assertEquals(whichShellOutput.stdout, "");
assertEquals(whichShellOutput.code, 2);
}
});

function ensurePromiseNotResolved(promise: Promise<unknown>) {
return new Promise<void>((resolve, reject) => {
promise.then(() => reject(new Error("Promise was resolved")));
Expand Down
2 changes: 2 additions & 0 deletions src/command.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { Path } from "./path.ts";
import { RequestBuilder } from "./request.ts";
import { StreamFds } from "./shell.ts";
import { symbols } from "./common.ts";
import { whichCommand } from "./commands/which.ts";

type BufferStdio = "inherit" | "null" | "streamed" | Buffer;
type StreamKind = "stdout" | "stderr" | "combined";
Expand Down Expand Up @@ -99,6 +100,7 @@ const builtInCommands = {
pwd: pwdCommand,
touch: touchCommand,
unset: unsetCommand,
which: whichCommand,
};

/** @internal */
Expand Down
71 changes: 71 additions & 0 deletions src/commands/which.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { CommandContext } from "../command_handler.ts";
import { errorToString } from "../common.ts";
import { ExecuteResult } from "../result.ts";
import { whichFromContext } from "../shell.ts";
import { ArgKind, parseArgKinds } from "./args.ts";

export async function whichCommand(
context: CommandContext,
): Promise<ExecuteResult> {
try {
return await executeWhich(context);
} catch (err) {
return context.error(`which: ${errorToString(err)}`);
}
}

interface WhichFlags {
commandName: string | undefined;
}

async function executeWhich(context: CommandContext): Promise<ExecuteResult> {
let flags: WhichFlags;
try {
flags = parseArgs(context.args);
} catch (err) {
return await context.error(2, `which: ${errorToString(err)}`);
}
if (flags.commandName == null) {
return { code: 1 };
}
const path = await whichFromContext(flags.commandName, {
getVar(key) {
return context.env[key];
},
});
if (path != null) {
await context.stdout.writeLine(path);
return { code: 0 };
} else {
return { code: 1 };
}
}

export function parseArgs(args: string[]) {
let commandName: string | undefined;

for (const arg of parseArgKinds(args)) {
if (arg.kind === "Arg") {
if (commandName != null) {
throw Error("unsupported too many arguments");
}
commandName = arg.arg;
} else {
bailUnsupported(arg);
}
}
return {
commandName,
};
}

function bailUnsupported(arg: ArgKind): never {
switch (arg.kind) {
case "Arg":
throw Error(`unsupported argument: ${arg.arg}`);
case "ShortFlag":
throw Error(`unsupported flag: -${arg.arg}`);
case "LongFlag":
throw Error(`unsupported flag: --${arg.arg}`);
}
}
33 changes: 18 additions & 15 deletions src/shell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1167,29 +1167,32 @@ async function resolveCommand(unresolvedCommand: UnresolvedCommand, context: Con
}
}

// always use the current executable for "deno"
if (unresolvedCommand.name.toUpperCase() === "DENO") {
return {
kind: "path",
path: Deno.execPath(),
};
const commandPath = await whichFromContext(unresolvedCommand.name, context);
if (commandPath == null) {
return false;
}
return {
kind: "path",
path: commandPath,
};
}

const realEnvironment = new DenoWhichRealEnvironment();
const commandPath = await which(unresolvedCommand.name, {
const realEnvironment = new DenoWhichRealEnvironment();

export async function whichFromContext(commandName: string, context: {
getVar(key: string): string | undefined;
}) {
// always use the current executable for "deno"
if (commandName.toUpperCase() === "DENO") {
return Deno.execPath();
}
return await which(commandName, {
os: Deno.build.os,
stat: realEnvironment.stat,
env(key) {
return context.getVar(key);
},
});
if (commandPath == null) {
return false;
}
return {
kind: "path",
path: commandPath,
};
}

async function executePipeSequence(sequence: PipeSequence, context: Context): Promise<ExecuteResult> {
Expand Down