Skip to content

Commit

Permalink
feat: 🎸 implement basic rename() method, only for files
Browse files Browse the repository at this point in the history
  • Loading branch information
streamich committed Jun 20, 2023
1 parent b68ea2a commit 169662a
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/fsa-to-node/FsaNodeFs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,19 @@ export class FsaNodeFs implements FsCallbackApi, FsCommonObjects {
public readonly rename: FsCallbackApi['rename'] = (oldPath: misc.PathLike, newPath: misc.PathLike, callback: misc.TCallback<void>): void => {
const oldPathFilename = pathToFilename(oldPath);
const newPathFilename = pathToFilename(newPath);
const [oldFolder, oldName] = pathToLocation(oldPathFilename);
const [newFolder, newName] = pathToLocation(newPathFilename);
(async () => {
const oldFile = await this.getFile(oldFolder, oldName, 'rename');
const newDir = await this.getDir(newFolder, false, 'rename');
const newFile = await newDir.getFileHandle(newName, { create: true });
const writable = await newFile.createWritable({ keepExistingData: false });
const oldData = await oldFile.getFile();
await writable.write(await oldData.arrayBuffer());
await writable.close();
const oldDir = await this.getDir(oldFolder, false, 'rename');
await oldDir.removeEntry(oldName);
})().then(() => callback(null), error => callback(error));
};

public readonly exists: FsCallbackApi['exists'] = (
Expand Down
12 changes: 12 additions & 0 deletions src/fsa-to-node/__tests__/FsaNodeFs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -451,3 +451,15 @@ describe('.access()', () => {
});
});
});

describe('.rename()', () => {
test('can rename a file', async () => {
const { fs, mfs } = setup({ folder: { file: 'test' }, 'empty-folder': null, 'f.html': 'test' });
await fs.promises.rename('/folder/file', '/folder/file2');
expect(mfs.__vol.toJSON()).toStrictEqual({
'/mountpoint/folder/file2': 'test',
'/mountpoint/empty-folder': null,
'/mountpoint/f.html': 'test',
});
});
});

0 comments on commit 169662a

Please sign in to comment.