Skip to content

Instantly share code, notes, and snippets.

@sigmaSd
Last active March 25, 2022 10:46
Show Gist options
  • Save sigmaSd/a30b01189acac1b53051611a48be33c4 to your computer and use it in GitHub Desktop.
Save sigmaSd/a30b01189acac1b53051611a48be33c4 to your computer and use it in GitHub Desktop.
Show deno scripts
const homeDir = () => {
switch (Deno.build.os) {
case "linux":
case "darwin":
return Deno.env.get("HOME");
case "windows":
return Deno.env.get("USERPROFILE");
}
};
const binaryPathFromName = (name: string) => `${homeDir()}/.deno/bin/${name}`;
const denoFile = async (name: string) =>
await Deno.readTextFile(binaryPathFromName(name));
const isFileLocal = (file: string) => file.includes("file://");
const filePath = (file: string) => file.match(/file:\/\/(.*)'/)![1];
const httpsPath = (file: string) => {
// there can be multiple https links if there is an import map for example
// we'll just pick the last one using this separator " '"
const matches = file.match(/(https:\/\/.*)'/)![1].split(" '");
return matches[matches.length - 1];
};
const downloadRemoteFileAndReturnPath = async (path: string) => {
const code = await fetch(path).then((r) => r.text());
const codePath = await Deno.makeTempFile({ suffix: ".ts" });
await Deno.writeFile(codePath, new TextEncoder().encode(code));
return codePath;
};
const cmd = () => Deno.env.get("CMD") || "bat";
const exec = async (file: string, cmd: string) => {
const cmdIter = cmd.split(" ");
return await Deno.run({
cmd: [cmdIter[0], ...cmdIter.slice(1), file],
}).status();
};
const listAll = async () => {
const files = Deno.readDir(`${homeDir()}/.deno/bin`);
for await (const file of files) {
if (file.name === "deno") continue;
console.log(
`- ${file.name} (${
isFileLocal(await denoFile(file.name)) ? "local" : "remote"
})`,
);
}
};
if (import.meta.main) {
const args = Deno.args;
if (args.length !== 0) {
const file = await denoFile(args[0]);
let codePath;
if (isFileLocal(file)) {
codePath = filePath(file);
} else {
codePath = await downloadRemoteFileAndReturnPath(httpsPath(file));
}
await exec(codePath, cmd());
} else {
await listAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment