MCPcopy
hub / github.com/jvilk/BrowserFS / renameSync

Method renameSync

src/generic/key_value_filesystem.ts:292–354  ·  view source on GitHub ↗
(oldPath: string, newPath: string)

Source from the content-addressed store, hash-verified

290 }
291
292 public renameSync(oldPath: string, newPath: string): void {
293 const tx = this.store.beginTransaction('readwrite'),
294 oldParent = path.dirname(oldPath), oldName = path.basename(oldPath),
295 newParent = path.dirname(newPath), newName = path.basename(newPath),
296 // Remove oldPath from parent's directory listing.
297 oldDirNode = this.findINode(tx, oldParent),
298 oldDirList = this.getDirListing(tx, oldParent, oldDirNode);
299
300 if (!oldDirList[oldName]) {
301 throw ApiError.ENOENT(oldPath);
302 }
303 const nodeId: string = oldDirList[oldName];
304 delete oldDirList[oldName];
305
306 // Invariant: Can't move a folder inside itself.
307 // This funny little hack ensures that the check passes only if oldPath
308 // is a subpath of newParent. We append '/' to avoid matching folders that
309 // are a substring of the bottom-most folder in the path.
310 if ((newParent + '/').indexOf(oldPath + '/') === 0) {
311 throw new ApiError(ErrorCode.EBUSY, oldParent);
312 }
313
314 // Add newPath to parent's directory listing.
315 let newDirNode: Inode, newDirList: typeof oldDirList;
316 if (newParent === oldParent) {
317 // Prevent us from re-grabbing the same directory listing, which still
318 // contains oldName.
319 newDirNode = oldDirNode;
320 newDirList = oldDirList;
321 } else {
322 newDirNode = this.findINode(tx, newParent);
323 newDirList = this.getDirListing(tx, newParent, newDirNode);
324 }
325
326 if (newDirList[newName]) {
327 // If it's a file, delete it.
328 const newNameNode = this.getINode(tx, newPath, newDirList[newName]);
329 if (newNameNode.isFile()) {
330 try {
331 tx.del(newNameNode.id);
332 tx.del(newDirList[newName]);
333 } catch (e) {
334 tx.abort();
335 throw e;
336 }
337 } else {
338 // If it's a directory, throw a permissions error.
339 throw ApiError.EPERM(newPath);
340 }
341 }
342 newDirList[newName] = nodeId;
343
344 // Commit the two changed directory listings.
345 try {
346 tx.put(oldDirNode.id, Buffer.from(JSON.stringify(oldDirList)), true);
347 tx.put(newDirNode.id, Buffer.from(JSON.stringify(newDirList)), true);
348 } catch (e) {
349 tx.abort();

Callers

nothing calls this directly

Calls 11

findINodeMethod · 0.95
getDirListingMethod · 0.95
getINodeMethod · 0.95
ENOENTMethod · 0.80
EPERMMethod · 0.80
beginTransactionMethod · 0.65
isFileMethod · 0.65
delMethod · 0.65
abortMethod · 0.65
putMethod · 0.65
commitMethod · 0.65

Tested by

no test coverage detected