# 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.#importasyncsshimportasyncioimportsysimportposixpathfromreemote.commandimportCommandfromtypingimportcast
[docs]classRmtree:""" A class to encapsulate the functionality of rmtree (recursively remove directory tree). Attributes: path (str): The directory path to remove recursively. ignore_errors (bool): Whether to ignore errors during removal. **Examples:** .. code:: python yield Rmtree(path='/home/user/hfs', ignore_errors=False) Usage: This class is designed to be used in a generator-based workflow where commands are yielded for execution. """def__init__(self,path:str,ignore_errors:bool=False):self.path=pathself.ignore_errors=ignore_errorsdef__repr__(self):return(f"Rmtree(path={self.path!r}, "f"ignore_errors={self.ignore_errors!r})")@staticmethodasyncdef_rmtree_callback(host_info,global_info,command,cp,caller):"""Static callback method for recursive directory removal"""# Validate host_info (matching Rmdir 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 Rmdir error handling)ifcaller.pathisNone:raiseValueError("The 'path' attribute of the caller cannot be None.")try:# Connect to the SSH server and recursively remove the directoryasyncwithasyncssh.connect(**host_info)asconn:asyncwithconn.start_sftp_client()assftp:# Use the rmtree method provided by asyncsshawaitsftp.rmtree(path=caller.path,ignore_errors=caller.ignore_errors)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._rmtree_callback,caller=self)r.executed=Truer.changed=Falsereturnr