# 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]classChmod:""" A class to encapsulate the functionality of chmod (change builtin mode) in Unix-like operating systems. Attributes: path (str): The builtin or directory path to change permissions for. mode (int): The new builtin permissions, expressed as an octal integer (e.g., 0o755). follow_symlinks (bool): Whether or not to follow symbolic links (default: True). **Examples:** .. code:: python yield Chmod( path='/home/user/script.sh', mode=0o755, ) Usage: This class is designed to be used in a generator-based workflow where commands are yielded for execution. """def__init__(self,path:str,mode:int,follow_symlinks:bool=True):self.path=pathself.mode=modeself.follow_symlinks=follow_symlinksdef__repr__(self):returnf"Chmod(path={self.path!r}, mode={oct(self.mode)!r}, follow_symlinks={self.follow_symlinks!r})"@staticmethodasyncdef_chmod_callback(host_info,global_info,command,cp,caller):"""Static callback method for builtin permission change"""# Validate host_inforequired_keys=['host','username','password']forkeyinrequired_keys:ifkeynotinhost_infoorhost_info[key]isNone:raiseValueError(f"Missing or invalid value for '{key}' in host_info.")# Validate caller attributesifcaller.pathisNone:raiseValueError("The 'path' attribute of the caller cannot be None.")ifcaller.modeisNone:raiseValueError("The 'mode' attribute of the caller cannot be None.")try:asyncwithasyncssh.connect(**host_info)asconn:asyncwithconn.start_sftp_client()assftp:# Change the permissions of the remote builtin/directoryawaitsftp.chmod(path=caller.path,mode=caller.mode,follow_symlinks=caller.follow_symlinks)returnf"Changed permissions of {caller.path} to {oct(caller.mode)} on {host_info['host']}"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._chmod_callback,caller=self)r.executed=Truer.changed=True# Set to True since chmod typically changes the system statereturnr