diff --git a/changelog.md b/changelog.md index b38646e..eeff392 100644 --- a/changelog.md +++ b/changelog.md @@ -1,5 +1,11 @@ # Changelog +## 2025-01-07 - 11.1.0 - feat(SmartFile) +Add rename functionality to SmartFile class + +- Implemented a new method to rename a file within the SmartFile class. +- The rename method updates the file path and optionally writes the renamed file to the disk. + ## 2024-12-15 - 11.0.23 - fix(fs) Handle errors in toObjectSync method diff --git a/ts/00_commitinfo_data.ts b/ts/00_commitinfo_data.ts index ad419a2..1da2daa 100644 --- a/ts/00_commitinfo_data.ts +++ b/ts/00_commitinfo_data.ts @@ -3,6 +3,6 @@ */ export const commitinfo = { name: '@push.rocks/smartfile', - version: '11.0.23', + version: '11.1.0', description: 'Provides comprehensive tools for efficient file management in Node.js using TypeScript, including handling streams, virtual directories, and various file operations.' } diff --git a/ts/classes.smartfile.ts b/ts/classes.smartfile.ts index f84cc8e..cb55242 100644 --- a/ts/classes.smartfile.ts +++ b/ts/classes.smartfile.ts @@ -91,7 +91,7 @@ export class SmartFile extends plugins.smartjson.Smartjson { }); } - public static async fromUrl (urlArg: string) { + public static async fromUrl(urlArg: string) { const response = await plugins.smartrequest.getBinary(urlArg); const smartfile = await SmartFile.fromBuffer(urlArg, response.body); return smartfile; @@ -212,6 +212,43 @@ export class SmartFile extends plugins.smartjson.Smartjson { await fs.remove(plugins.path.join(this.base, this.path)); } + /** + * Renames the file to the specified new name. + * - Updates the `path` property with the new name. + * - Writes the file to the new location if it exists on disk. + * @param newName The new name of the file (including extension if applicable). + * @param writeToDisk (optional) If true, also renames the file on the disk. + * @returns The updated file path after renaming. + */ + public async rename(newName: string, writeToDisk: boolean = false): Promise { + // Validate the new name + if (!newName || typeof newName !== 'string') { + throw new Error('Invalid new name provided.'); + } + + // Extract the directory path + const oldFilePath = this.path; + const dirPath = plugins.path.dirname(this.path); + + // Create the new file path + const newFilePath = plugins.path.join(dirPath, newName); + + // Update the `path` property + this.path = newFilePath; + + // Optionally write the renamed file to disk + if (writeToDisk) { + const oldAbsolutePath = plugins.smartpath.transform.makeAbsolute(oldFilePath, this.base); + const newAbsolutePath = plugins.smartpath.transform.makeAbsolute(newFilePath, this.base); + + // Rename the file on disk + await plugins.fsExtra.rename(oldAbsolutePath, newAbsolutePath); + } + + // Return the new path + return this.path; + } + // ----------------------------------------------- // vinyl compatibility // -----------------------------------------------