Fix project renumber (#1597)

* fix: generateUniqueFileName

* loadProject should not generate new names

* update comments

* extract and test getProjectNumber

* spell

* finish jsdoc

* use getProjectNumber

* cleanup loadProject

* create a `incrementProjectNumber` function

* spelling

Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com>

---------

Co-authored-by: Carlos Valente <34649812+cpvalente@users.noreply.github.com>
This commit is contained in:
Alex Christoffer Rasmussen
2025-05-07 22:31:18 +02:00
committed by arc-alex
parent 8557f64382
commit c9bf6d9812
3 changed files with 73 additions and 29 deletions
+22 -7
View File
@@ -1,6 +1,6 @@
import { existsSync, mkdirSync, PathLike } from 'fs';
import { readdir, copyFile, unlink } from 'fs/promises';
import { basename, extname, join, parse } from 'path';
import { basename, join, parse } from 'path';
/**
* @description Creates a directory if it doesn't exist
@@ -53,16 +53,11 @@ export function appendToName(filePath: string, append: string): string {
* If a file with the same name already exists, appends a counter to the filename.
*/
export function generateUniqueFileName(directory: string, filename: string): string {
const extension = extname(filename);
const baseName = basename(filename, extension);
let counter = 0;
let uniqueFilename = filename;
while (fileExists(uniqueFilename)) {
counter++;
// Append counter to filename if the file exists.
uniqueFilename = `${baseName} (${counter})${extension}`;
uniqueFilename = incrementProjectNumber(uniqueFilename);
}
return uniqueFilename;
@@ -114,3 +109,23 @@ export async function dockerSafeRename(oldPath: PathLike, newPath: PathLike) {
await copyFile(oldPath, newPath);
await unlink(oldPath);
}
/**
* finds potential file index number in our (*) format and increments
* the number section (*) must be separated from the name by a space
* @example incrementProjectNumber('test(1).json') -> 'test(1).json'
* @example incrementProjectNumber('test (1).json') -> 'test(2).json'
*/
export function incrementProjectNumber(path: string): string {
const { dir, name, ext } = parse(path);
if (!name.endsWith(')')) return join(dir, `${name} (1)${ext}`);
const openingParenIndex = name.lastIndexOf(' (');
if (openingParenIndex === -1) return join(dir, `${name} (1)${ext}`);
const maybeNumber = Number(name.slice(openingParenIndex + 2, -1));
if (isNaN(maybeNumber)) return join(dir, `${name} (1)${ext}`);
return join(dir, `${name.slice(0, openingParenIndex)} (${maybeNumber + 1})${ext}`);
}