Last active
March 25, 2022 10:46
-
-
Save sigmaSd/a30b01189acac1b53051611a48be33c4 to your computer and use it in GitHub Desktop.
Show deno scripts
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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