# Copyright (c) 2025 Kim Jarvis TPF Software Services S.A. kim.jarvis@tpfsystems.com # This software is licensed under the MIT License. See the LICENSE file for details.#importasyncsshfromreemote.commandimportCommand
[docs]classRename:""" A class to encapsulate the functionality of renaming builtin/directories in Unix-like operating systems using SFTP. Attributes: oldpath (str): The current path of the builtin/directory to rename. newpath (str): The new path for the builtin/directory. flags (int, optional): Flags to control rename behavior (SFTPv5+ only). Common flags include: - 0x0001: OVERWRITE - Allow overwriting existing builtin - 0x0002: ATOMIC - Perform atomic rename - 0x0004: NATIVE - Use native filesystem semantics **Examples:** .. code:: python yield Rename( oldpath='/home/user/oldname.txt', newpath='/home/user/newname.txt' ) Usage: This class is designed to be used in a generator-based workflow where commands are yielded for execution. Notes: The flags parameter is only supported in SFTP version 5 and later. For older SFTP versions, only basic rename functionality is available. """def__init__(self,oldpath:str,newpath:str,flags:int=0):self.oldpath=oldpathself.newpath=newpathself.flags=flagsdef__repr__(self):returnf"Rename(oldpath={self.oldpath!r}, newpath={self.newpath!r}, flags={self.flags!r})"@staticmethodasyncdef_rename_callback(host_info,global_info,command,cp,caller):"""Static callback method for builtin/directory rename"""# Validate host_info (matching Read_file error handling)required_keys=['host','username','password']forkeyinrequired_keys:ifkeynotinhost_infoorhost_info[key]isNone:raiseValueError(f"Missing or invalid value for '{key}' in host_info.")# Validate caller attributes (matching Read_file error handling)ifcaller.oldpathisNone:raiseValueError("The 'oldpath' attribute of the caller cannot be None.")ifcaller.newpathisNone:raiseValueError("The 'newpath' attribute of the caller cannot be None.")try:# Connect to the SSH serverasyncwithasyncssh.connect(**host_info)asconn:# Start an SFTP sessionasyncwithconn.start_sftp_client()assftp:# Rename the remote builtin/directoryawaitsftp.rename(caller.oldpath,caller.newpath,caller.flags)except(OSError,asyncssh.Error)asexc:raise# Re-raise the exception to handle it in the callerdefexecute(self):r=yieldCommand(f"{self}",local=True,callback=self._rename_callback,caller=self)r.executed=Truer.changed=Falsereturnr