Skip to content

Instantly share code, notes, and snippets.

@rkmax
Created March 18, 2025 23:29
Show Gist options
  • Save rkmax/e72fee0e0f1af52752f40a44917d1ed8 to your computer and use it in GitHub Desktop.
Save rkmax/e72fee0e0f1af52752f40a44917d1ed8 to your computer and use it in GitHub Desktop.
#!/usr/bin/env -S deno run --allow-env --allow-run --allow-read --allow-write
import { parseArgs } from "jsr:@std/cli/parse-args";
export async function copy(text: string): Promise<void> {
const cmd = new Deno.Command("wl-copy", {
stdin: "piped",
});
const process = cmd.spawn();
const writer = process.stdin.getWriter();
await writer.write(new TextEncoder().encode(text));
await writer.close();
const status = await process.status;
if (!status.success) {
throw new Error("Failed to copy to clipboard");
}
}
export async function paste(): Promise<string> {
const cmd = new Deno.Command("wl-paste", {
args: ["-n"],
stdout: "piped",
});
const process = cmd.spawn();
const output = await process.output();
const status = await process.status;
if (!status.success) {
throw new Error("Failed to paste from clipboard");
}
return new TextDecoder().decode(output.stdout);
}
export async function encodeJSONAsString(): Promise<void> {
try {
const clipboardText = await paste();
const jsonString = JSON.stringify(clipboardText);
await copy(jsonString);
} catch (error) {
console.error("Error:", error);
}
}
export async function decodeStringAsJSON(): Promise<void> {
try {
const clipboardText = await paste();
const jsonString = JSON.parse(clipboardText);
await copy(jsonString);
} catch (error) {
console.error("Error:", error);
}
}
async function main() {
const flags = parseArgs(Deno.args, {
string: ["action"],
});
switch (flags.action) {
case "decode":
await decodeStringAsJSON();
break;
case "encode":
await encodeJSONAsString();
break;
default:
throw new Error("Not implemented");
}
}
main()
.catch((e) => {
console.error(e);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment