Skip to content

Instantly share code, notes, and snippets.

@sigmaSd
Last active September 6, 2022 01:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sigmaSd/e3231a191323629b1c97643f8f260978 to your computer and use it in GitHub Desktop.
Save sigmaSd/e3231a191323629b1c97643f8f260978 to your computer and use it in GitHub Desktop.
Install a javascript function as an executable
import cache_dir from "https://deno.land/x/dir@1.5.1/cache_dir/mod.ts";
import { ensureDirSync } from "https://deno.land/std@0.152.0/fs/ensure_dir.ts";
export interface Options {
prelude?: string;
permissions?: string[];
}
// deno-lint-ignore no-explicit-any
export default function installFn(fn: any, options?: Options) {
const name = fn.name;
if (!name) {
throw "fn name is required";
}
const body: string = fn.toString();
let content;
if (body.includes("=>")) {
content = `
const ${name} = ${body}
const output = ${name}(...Deno.args)
console.log(output)
`;
} else {
// TODO
throw "unrecognized function type";
}
if (options?.prelude) {
content = options.prelude + "\n" + content;
}
const installDir = `${cache_dir()}/deno-install-fn/`;
ensureDirSync(installDir);
const fnPath = `${installDir}/${name}.ts`;
Deno.writeTextFileSync(fnPath, content);
Deno.spawnSync("deno", {
args: ["fmt", fnPath],
});
Deno.spawnSync("deno", {
args: options?.permissions
? ["install", "-f", ...options.permissions, fnPath]
: ["install", "-f", fnPath],
stdout: "inherit",
stderr: "inherit",
});
console.log(`%c${name}%c was succefully installed!`, "color:blue", "");
}
@sigmaSd
Copy link
Author

sigmaSd commented Aug 22, 2022

install

@sigmaSd
Copy link
Author

sigmaSd commented Aug 22, 2022

How it works

1- create a script with the name of the function
2- Write the script content (to $cache/deno-install-fn/script): Evaluate Deno.args as input to the function body and write it to stdout
3- deno install scriptPath i you have ~/.deno/bin in your path , this make it very convenient as the function will become immediately available

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment