#1084 Fix dupe char suffix

This commit is contained in:
Cohee 2023-09-03 15:18:23 +03:00
parent ce2c2b0dac
commit a26e8ef455
1 changed files with 21 additions and 7 deletions

View File

@ -2289,17 +2289,31 @@ app.post("/dupecharacter", jsonParser, async function (request, response) {
} }
let suffix = 1; let suffix = 1;
let newFilename = filename; let newFilename = filename;
// If filename ends with a _number, increment the number
const nameParts = path.basename(filename, path.extname(filename)).split('_');
const lastPart = nameParts[nameParts.length - 1];
let baseName;
if (!isNaN(Number(lastPart)) && nameParts.length > 1) {
suffix = parseInt(lastPart) + 1;
baseName = nameParts.slice(0, -1).join("_"); // construct baseName without suffix
} else {
baseName = nameParts.join("_"); // original filename is completely the baseName
}
newFilename = path.join(directories.characters, `${baseName}_${suffix}${path.extname(filename)}`);
while (fs.existsSync(newFilename)) { while (fs.existsSync(newFilename)) {
let suffixStr = "_" + suffix; let suffixStr = "_" + suffix;
let ext = path.extname(filename); newFilename = path.join(directories.characters, `${baseName}${suffixStr}${path.extname(filename)}`);
newFilename = filename.slice(0, -ext.length) + suffixStr + ext;
suffix++; suffix++;
} }
fs.copyFile(filename, newFilename, (err) => {
if (err) throw err; fs.copyFileSync(filename, newFilename);
console.log(`${filename} was copied to ${newFilename}`); console.log(`${filename} was copied to ${newFilename}`);
response.sendStatus(200); response.sendStatus(200);
});
} }
catch (error) { catch (error) {
console.error(error); console.error(error);