Last active
April 23, 2021 18:51
-
-
Save crazy4groovy/52670e7a1c4be6537628b9bfb7b02d32 to your computer and use it in GitHub Desktop.
Runs a given command for each file in a folder, recursively; replaces #FILE_PATH, #FILE_NAME, #FILE_SIZE_KB in command (Deno)
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
import * as fs from "https://deno.land/std@0.93.0/fs/mod.ts"; | |
import * as path from "https://deno.land/std@0.93.0/path/mod.ts"; | |
export default () => { | |
let [execCmdTemplate, basedir = ".", fileExt = ""] = Deno.args; | |
if (!execCmdTemplate) throw new Error("No command was given"); | |
if (!basedir || !fs.existsSync(basedir)) throw new Error("DIR doesn't exist"); | |
basedir = path.resolve(".", basedir); | |
return { execCmdTemplate, basedir, fileExt }; | |
} |
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
#!/usr/bin/env -S deno run --allow-all --unstable | |
// Runs a given command for each file in a folder, recursively | |
// Replaces #FILE_PATH, #FILE_NAME, #FILE_SIZE_KB in command | |
//$ deno run --allow-all --unstable https://gist.githubusercontent.com/crazy4groovy/52670e7a1c4be6537628b9bfb7b02d32/raw/index.ts 'echo #FILE_PATH::#FILE_NAME' ~ .jpg | |
import * as fs from "https://deno.land/std@0.93.0/fs/mod.ts"; | |
import { exec } from "https://deno.land/x/exec@0.0.5/mod.ts"; | |
import args from "./args.ts"; | |
const { execCmdTemplate, basedir, fileExt } = args(); | |
const validators = [ | |
(f: any) => Boolean(f.isFile), | |
(f: any) => f.path?.endsWith(fileExt), | |
]; | |
const replacers = { | |
'#FILE_PATH': (f: any) => String(f.path), | |
'#FILE_NAME': (f: any) => String(f.name), | |
// check execCmdTemplate for calculating the "expensive" replacements: | |
'#FILE_SIZE_KB': ( | |
execCmdTemplate.indexOf('#FILE_SIZE_KB') === -1 | |
? (f: any) => '#FILE_SIZE_KB' // not found | |
: (f: any) => String(Math.round(Deno.statSync(f.path).size / 1024))), | |
} as Record<string, (f: any) => string>; | |
(async () => { | |
for await (const f of fs.walkSync(basedir)) { | |
const isValid = validators.find(v => !v(f)) === undefined; // i.e. check if found no falsies, then it's valid | |
if (!isValid) continue; | |
const cmd = Object.keys(replacers).reduce( | |
(cmd: string, key: string) => cmd.replace(key, replacers[key](f)), | |
execCmdTemplate | |
); | |
await exec(cmd).catch(console.error); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment