Last active
April 30, 2020 13:54
-
-
Save drmats/a9d9e13fe4d2c8790c16546c7c289f36 to your computer and use it in GitHub Desktop.
renders renamer
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
#!/bin/node | |
/* MIT License, (c) 2020 xcmats */ | |
/** | |
* usage: | |
* $ renamer.js [directory] | |
* | |
* set env. variable in windows 7+: | |
* > setx NODE_PATH C:\Windows\npm | |
* | |
* > node -r renamer | |
* | |
*/ | |
// ... | |
var | |
{ | |
readdirSync, | |
renameSync, | |
} = require("fs"), | |
{ | |
extname, | |
resolve, | |
} = require("path"), | |
print = console.info, | |
// ... | |
suffixes = [ | |
"7016-1003", // 0001 | |
"7016-5015", // 0002 | |
"7016-6018", // 0003 | |
"7035-5015", // 0004 | |
"7035-7016", // 0005 | |
"7035-7035", // 0006 | |
], | |
// ... | |
matchingRegex = /(.*-)(000[1-6])(\.png)/, | |
// ... | |
comp3 = f => g => h => x => f(g(h(x))), | |
waitForKey = (prompt = "hit some key...") => new Promise(r => { | |
print(prompt); | |
process.stdin.setRawMode(true); | |
process.stdin.resume(); | |
process.stdin.on("data", comp3(r) (x => x[0]) (Array.from)); | |
}), | |
// ... | |
findEntries = dir => { | |
let files = []; | |
readdirSync(dir, { withFileTypes: true }) | |
.forEach(entry => { | |
if (entry.isDirectory()) { | |
files.push.apply( | |
files, | |
findEntries(resolve(dir, entry.name)) | |
); | |
} else if (entry.isFile() && extname(entry.name) === ".png") { | |
let match = entry.name.match(matchingRegex); | |
if (match && match[2]) { | |
files.push([ | |
resolve(dir), | |
entry.name, | |
[ | |
match[1], | |
suffixes[parseInt(match[2], 10) - 1], | |
match[3], | |
].join(""), | |
]); | |
} | |
} | |
}); | |
return files; | |
}; | |
// main | |
(async () => { | |
let dir = resolve(process.argv[2] || "./"); | |
print(`Finding candidates to rename at '${dir}'...`); | |
try { | |
let entries = findEntries(dir); | |
if (entries.length) { | |
print("Rename proposal:"); | |
entries.forEach(entry => | |
print(`\t'${entry[0]}': '${entry[1]}' -> '${entry[2]}'`) | |
); | |
let choice = await waitForKey("Make changes on disk? - [y/n]"); | |
if (String.fromCharCode(choice) === "y") { | |
print("Renaming..."); | |
entries.forEach(entry => { | |
renameSync( | |
resolve(entry[0], entry[1]), | |
resolve(entry[0], entry[2]) | |
) | |
}); | |
print("Done!"); | |
} else { | |
print("Cancelled."); | |
} | |
} else { | |
print(`No matches found at '${dir}'.`); | |
} | |
} catch (ex) { | |
print(ex.toString()); | |
} finally { | |
process.exit(0); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment