renameFileOrDirectory method

  1. @override
Future<void> renameFileOrDirectory(
  1. String oldPath,
  2. String newPath
)
override

Renames a file or directory from the old path to the new path. Both paths are relative to the current working directory. Implementations must handle path resolution and ensure the operation stays within allowed boundaries.

Implementation

@override
Future<void> renameFileOrDirectory(String oldPath, String newPath) async {
  final oldFullPath = resolvePath(oldPath);
  final newFullPath = resolvePath(newPath);

  // Prevent renaming the root directory
  if (oldFullPath == rootDirectory) {
    throw FileSystemException("Cannot rename root directory", oldPath);
  }

  // Check if source exists
  final sourceEntity = FileSystemEntity.typeSync(oldFullPath);
  if (sourceEntity == FileSystemEntityType.notFound) {
    throw FileSystemException(
        "Source not found for rename: $oldPath (resolved to $oldFullPath)");
  }

  // Check if destination already exists
  if (FileSystemEntity.typeSync(newFullPath) !=
      FileSystemEntityType.notFound) {
    throw FileSystemException(
        "Destination already exists: $newPath (resolved to $newFullPath)");
  }

  try {
    if (sourceEntity == FileSystemEntityType.file) {
      final file = File(oldFullPath);
      await file.rename(newFullPath);
    } else if (sourceEntity == FileSystemEntityType.directory) {
      final directory = Directory(oldFullPath);
      await directory.rename(newFullPath);
    } else {
      throw FileSystemException(
          "Unsupported file system entity type for rename", oldPath);
    }
  } catch (e) {
    throw FileSystemException("Failed to rename $oldPath to $newPath: $e");
  }
}