meerschaum.actions
Default actions available to the mrsm CLI.
Every standard action runs in the native dispatcher (mrsm, from the wheel's extension or the standalone binary).
The functions in actions are thin façades over it: actions['sync'](['pipes'], **kw) runs
sync pipes natively and returns its SuccessTuple. Actions added by plugins (@make_action)
are the plugins' own functions.
1#! /usr/bin/env python 2# -*- coding: utf-8 -*- 3# vim:fenc=utf-8 4 5""" 6Default actions available to the mrsm CLI. 7 8Every standard action runs in the native dispatcher (`mrsm`, from the wheel's extension or the standalone binary). 9The functions in `actions` are thin façades over it: `actions['sync'](['pipes'], **kw)` runs 10`sync pipes` natively and returns its `SuccessTuple`. Actions added by plugins (`@make_action`) 11are the plugins' own functions. 12""" 13 14from __future__ import annotations 15from meerschaum.utils.typing import Callable, Any, Optional, Union, List, Dict, SuccessTuple 16from meerschaum.utils.packages import get_modules_from_package 17from inspect import getmembers, isfunction # kept: importable from here in v4 18 19__all__ = ( 20 'get_action', 21 'get_subactions', 22 'make_action', 23 'pre_sync_hook', 24 'post_sync_hook', 25 'get_main_action_name', 26 'get_completer', 27) 28 29### The core registry: `{name: {'doc', 'accepts_executor_keys', 'subactions': {name: function}}}`, 30### read once from the native dispatcher (`_core.core_actions()`). 31_core_registry: Dict[str, Dict[str, Any]] = {} 32 33 34def _make_function( 35 function_name: str, 36 prefix: List[str], 37 doc: str, 38 accepts_executor_keys: bool, 39) -> Callable[[Any], SuccessTuple]: 40 """ 41 Build the façade of one core action (or subaction). 42 `function_name` is v4's function name (`sync`, `_sync_pipes`), `prefix` the words that 43 select it in the native dispatcher. 44 """ 45 import inspect 46 47 def _function(action: Optional[List[str]] = None, **kw: Any) -> SuccessTuple: 48 from meerschaum import _core 49 from meerschaum._internal.entry import adhoc_context 50 return _core.run_action([*prefix, *(action or [])], kw, adhoc_context()) 51 52 _function.__name__ = function_name 53 _function.__qualname__ = function_name 54 _function.__module__ = __name__ 55 _function.__doc__ = doc or None 56 parameters = [ 57 inspect.Parameter( 58 'action', 59 inspect.Parameter.POSITIONAL_OR_KEYWORD, 60 default=None, 61 annotation=Optional[List[str]], 62 ), 63 ] 64 if accepts_executor_keys: 65 parameters.append( 66 inspect.Parameter( 67 'executor_keys', 68 inspect.Parameter.KEYWORD_ONLY, 69 default=None, 70 annotation=Optional[str], 71 ) 72 ) 73 parameters.append(inspect.Parameter('kw', inspect.Parameter.VAR_KEYWORD, annotation=Any)) 74 _function.__signature__ = inspect.Signature(parameters, return_annotation=SuccessTuple) 75 _function._mrsm_core_action = True 76 return _function 77 78 79def _load_core_registry() -> Dict[str, Dict[str, Any]]: 80 """Read the registry of the native actions once.""" 81 if _core_registry: 82 return _core_registry 83 from meerschaum import _core 84 for name, doc, accepts_executor_keys, subs in _core.core_actions(): 85 function = _make_function(name, [name], doc, accepts_executor_keys) 86 subactions = { 87 sub_name: _make_function( 88 function_name, 89 [name, sub_name], 90 sub_doc, 91 sub_accepts_executor_keys, 92 ) 93 for sub_name, function_name, sub_doc, sub_accepts_executor_keys in subs 94 } 95 _core_registry[name] = { 96 'function': function, 97 'doc': doc, 98 'subactions': subactions, 99 } 100 return _core_registry 101 102 103def get_subactions( 104 action: Union[str, List[str]], 105 _actions: Optional[Dict[str, Callable[[Any], Any]]] = None, 106) -> Dict[str, Callable[[Any], Any]]: 107 """ 108 Return a dictionary of an action's sub-action functions. 109 110 Examples 111 -------- 112 >>> get_subactions('install').keys() 113 dict_keys(['packages', 'plugins', 'required']) 114 >>> 115 """ 116 import importlib, inspect 117 subactions = {} 118 if isinstance(action, str): 119 action = [action] 120 action_function = get_action(action[0], _actions=_actions) 121 if action_function is None: 122 return subactions 123 124 ### The standard actions: the native registry knows their subactions. 125 if getattr(action_function, '_mrsm_core_action', False): 126 registry = _load_core_registry().get(action[0], None) 127 if registry is None: 128 registry = _load_core_registry().get(action_function.__name__, None) 129 return dict(registry['subactions']) if registry is not None else subactions 130 131 try: 132 action_module = importlib.import_module(action_function.__module__) 133 except ImportError: 134 action_module = None 135 if action_module is None: 136 return subactions 137 for name, f in inspect.getmembers(action_module): 138 if not inspect.isfunction(f): 139 continue 140 141 ### Detect subactions which may contain an underscore prefix. 142 if ( 143 name.lstrip('_').startswith(action_function.__name__.lstrip('_') + '_') 144 ): 145 _name = name.replace(action_function.__name__, '') 146 _name = _name.lstrip('_') 147 subactions[_name] = f 148 return subactions 149 150 151def get_action( 152 action: Union[str, List[str]], 153 _actions: Optional[Dict[str, Callable[[Any], Any]]] = None, 154) -> Union[Callable[[Any], Any], None]: 155 """ 156 Return a function corresponding to the given action list. 157 This may be a custom action with an underscore, in which case, allow for underscores. 158 This may also be a subaction, which is handled by `get_subactions()` 159 """ 160 if _actions is None: 161 _actions = actions 162 if isinstance(action, str): 163 action = [action] 164 165 if not any(action): 166 return None 167 168 ### Simple case, e.g. ['show'] 169 if len(action) == 1: 170 if action[0] in _actions: 171 return _actions[action[0]] 172 173 ### e.g. ['foo'] (and no custom action available) 174 return None 175 176 ### Last case: it could be a custom action with an underscore in the name. 177 action_name_with_underscores = '_'.join(action) 178 candidates = [] 179 for action_key, action_function in _actions.items(): 180 if not '_' in action_key: 181 continue 182 if action_name_with_underscores.startswith(action_key): 183 leftovers = action_name_with_underscores.replace(action_key, '') 184 candidates.append((len(leftovers), action_function)) 185 if len(candidates) > 0: 186 return sorted(candidates)[0][1] 187 188 ### Might be dealing with a subaction. 189 if action[0] in _actions: 190 subactions = get_subactions([action[0]], _actions=_actions) 191 if action[1] not in subactions: 192 if (action[1] + 's') in subactions: 193 return subactions[action[1] + 's'] 194 return _actions[action[0]] 195 return subactions[action[1]] 196 197 return None 198 199 200def get_main_action_name( 201 action: Union[List[str], str], 202 _actions: Optional[Dict[str, Callable[[Any], SuccessTuple]]] = None, 203) -> Union[str, None]: 204 """ 205 Given an action list, return the name of the main function. 206 For subactions, this will return the root function. 207 If no action function can be found, return `None`. 208 209 Parameters 210 ---------- 211 action: Union[List[str], str] 212 The standard action list. 213 214 Examples 215 -------- 216 >>> get_main_action_name(['show', 'pipes']) 217 'show' 218 >>> 219 """ 220 if _actions is None: 221 _actions = actions 222 action_function = get_action(action, _actions=_actions) 223 if action_function is None: 224 return None 225 clean_name = action_function.__name__.lstrip('_') 226 if clean_name in _actions: 227 return clean_name 228 words = clean_name.split('_') 229 first_word = words[0] 230 if first_word in _actions: 231 return first_word 232 ### We might be dealing with shell `do_` functions. 233 second_word = words[1] if len(words) > 1 else None 234 if second_word and second_word in _actions: 235 return second_word 236 return None 237 238 239def get_completer( 240 action: Union[List[str], str], 241 _actions: Optional[Dict[str, Callable[[Any], SuccessTuple]]] = None, 242) -> Union[ 243 Callable[['meerschaum._internal.shell.Shell', str, str, int, int], List[str]], None 244 ]: 245 """ 246 Search for a custom completer function for an action. 247 The standard actions complete in the native shell, so only plugin actions have one. 248 """ 249 import importlib, inspect 250 if isinstance(action, str): 251 action = [action] 252 action_function = get_action(action) 253 if action_function is None or getattr(action_function, '_mrsm_core_action', False): 254 return None 255 try: 256 action_module = importlib.import_module(action_function.__module__) 257 except ImportError: 258 action_module = None 259 if action_module is None: 260 return None 261 candidates = [] 262 for name, f in inspect.getmembers(action_module): 263 if not inspect.isfunction(f): 264 continue 265 name_lstrip = name.lstrip('_') 266 if not name_lstrip.startswith('complete_'): 267 continue 268 if name_lstrip == 'complete_' + action_function.__name__: 269 candidates.append((name_lstrip, f)) 270 continue 271 if name_lstrip == 'complete_' + action_function.__name__.split('_')[0]: 272 candidates.append((name_lstrip, f)) 273 if len(candidates) == 1: 274 return candidates[0][1] 275 if len(candidates) > 1: 276 return sorted(candidates)[-1][1] 277 278 return None 279 280 281def choose_subaction( 282 action: Optional[List[str]] = None, 283 options: Optional[Dict[str, Any]] = None, 284 **kw 285) -> SuccessTuple: 286 """ 287 Given a dictionary of options and the standard Meerschaum actions list, 288 check if choice is valid and execute chosen function, else show available 289 options and return False 290 291 Parameters 292 ---------- 293 action: Optional[List[str]], default None 294 A list of subactions (e.g. `show pipes` -> ['pipes']). 295 296 options: Optional[Dict[str, Any]], default None 297 Available options to execute. 298 option (key) -> function (value) 299 Functions must accept **kw keyword arguments 300 and return a tuple of success bool and message. 301 302 Returns 303 ------- 304 The return value of the chosen subaction (assumed to be a `SuccessTuple`). 305 306 """ 307 from meerschaum.utils.warnings import warn, info 308 import inspect 309 if action is None: 310 action = [] 311 if options is None: 312 options = {} 313 parent_action = inspect.stack()[1][3] 314 if len(action) == 0: 315 action = [''] 316 choice = action[0] 317 318 def valid_choice(_choice : str, _options : dict): 319 if _choice in _options: 320 return _choice 321 if (_choice + 's') in options: 322 return _choice + 's' 323 return None 324 325 parsed_choice = valid_choice(choice, options) 326 if parsed_choice is None: 327 warn(f"Cannot {parent_action} '{choice}'. Choose one:", stack=False) 328 for option in sorted(options): 329 print(f" - {parent_action} {option}") 330 return (False, f"Invalid choice '{choice}'.") 331 ### remove parent sub-action 332 kw['action'] = list(action) 333 del kw['action'][0] 334 return options[parsed_choice](**kw) 335 336 337def _get_subaction_names(action: str, globs: dict = None) -> List[str]: 338 """Use `meerschaum.actions.get_subactions()` instead.""" 339 if globs is None: 340 import importlib 341 module = importlib.import_module(f'meerschaum.actions.{action}') 342 globs = vars(module) 343 subactions = [] 344 for item in globs: 345 if f'_{action}' in item and 'complete' not in item.lstrip('_'): 346 subactions.append(globs[item]) 347 return subactions 348 349 350def choices_docstring(action: str, globs: Optional[Dict[str, Any]] = None) -> str: 351 """ 352 Append the an action's available options to the module docstring. 353 This function is to be placed at the bottom of each action module. 354 355 Parameters 356 ---------- 357 action: str 358 The name of the action module (e.g. 'install'). 359 360 globs: Optional[Dict[str, Any]], default None 361 An optional dictionary of global variables. 362 363 Returns 364 ------- 365 The generated docstring for the module. 366 367 Examples 368 -------- 369 >>> from meerschaum.utils.misc import choices_docstring as _choices_docstring 370 >>> install.__doc__ += _choices_docstring('install') 371 372 """ 373 options_str = f"\n Options:\n `{action} " 374 subactions = _get_subaction_names(action, globs=globs) 375 options_str += "[" 376 sa_names = [] 377 for sa in subactions: 378 try: 379 sa_names.append(sa.__name__[len(f"_{action}") + 1:]) 380 except Exception as e: 381 print(e) 382 return "" 383 for sa_name in sorted(sa_names): 384 options_str += f"{sa_name}, " 385 options_str = options_str[:-2] + "]`" 386 return options_str 387 388 389### The action modules of plugins (`load_plugins()` keeps this list current). 390modules: List[Any] = [] 391 392### The standard actions, in v4's order, then the plugins' (`make_action()` adds to this). 393actions: Dict[str, Callable[[Any], SuccessTuple]] = { 394 _name: _entry['function'] 395 for _name, _entry in _load_core_registry().items() 396} 397_custom_actions_plugins: Dict[str, str] = {} 398_plugins_actions: Dict[str, List[str]] = {} 399 400original_actions = actions.copy() 401from meerschaum._internal.entry import entry, get_shell 402import meerschaum.plugins 403make_action = meerschaum.plugins.make_action 404pre_sync_hook = meerschaum.plugins.pre_sync_hook 405post_sync_hook = meerschaum.plugins.post_sync_hook 406 407__all__ = ['actions', 'get_subactions', 'get_action', 'get_main_action_name', 'get_completer'] 408 409### Instruct pdoc to skip the `meerschaum.actions.plugins` subdirectory. 410__pdoc__ = { 411 'plugins': False, 412 'arguments': True, 413 'shell': False, 414 'actions': ( 415 "Access functions of the standard Meerschaum actions.\n\n" 416 + "Visit the [actions reference page](https://meerschaum.io/reference/actions/) " 417 + "for documentation about each action.\n\n" 418 + """\n\nExamples 419-------- 420>>> actions['show'](['pipes']) 421 422""" 423 + "Keys\n----\n" 424 + ', '.join(sorted([f'`{a}`' for a in actions])) 425 ) 426} 427for a in actions: 428 __pdoc__[a] = False 429 430meerschaum.plugins.load_plugins(skip_if_loaded=True)
104def get_subactions( 105 action: Union[str, List[str]], 106 _actions: Optional[Dict[str, Callable[[Any], Any]]] = None, 107) -> Dict[str, Callable[[Any], Any]]: 108 """ 109 Return a dictionary of an action's sub-action functions. 110 111 Examples 112 -------- 113 >>> get_subactions('install').keys() 114 dict_keys(['packages', 'plugins', 'required']) 115 >>> 116 """ 117 import importlib, inspect 118 subactions = {} 119 if isinstance(action, str): 120 action = [action] 121 action_function = get_action(action[0], _actions=_actions) 122 if action_function is None: 123 return subactions 124 125 ### The standard actions: the native registry knows their subactions. 126 if getattr(action_function, '_mrsm_core_action', False): 127 registry = _load_core_registry().get(action[0], None) 128 if registry is None: 129 registry = _load_core_registry().get(action_function.__name__, None) 130 return dict(registry['subactions']) if registry is not None else subactions 131 132 try: 133 action_module = importlib.import_module(action_function.__module__) 134 except ImportError: 135 action_module = None 136 if action_module is None: 137 return subactions 138 for name, f in inspect.getmembers(action_module): 139 if not inspect.isfunction(f): 140 continue 141 142 ### Detect subactions which may contain an underscore prefix. 143 if ( 144 name.lstrip('_').startswith(action_function.__name__.lstrip('_') + '_') 145 ): 146 _name = name.replace(action_function.__name__, '') 147 _name = _name.lstrip('_') 148 subactions[_name] = f 149 return subactions
Return a dictionary of an action's sub-action functions.
Examples
>>> get_subactions('install').keys()
dict_keys(['packages', 'plugins', 'required'])
>>>
152def get_action( 153 action: Union[str, List[str]], 154 _actions: Optional[Dict[str, Callable[[Any], Any]]] = None, 155) -> Union[Callable[[Any], Any], None]: 156 """ 157 Return a function corresponding to the given action list. 158 This may be a custom action with an underscore, in which case, allow for underscores. 159 This may also be a subaction, which is handled by `get_subactions()` 160 """ 161 if _actions is None: 162 _actions = actions 163 if isinstance(action, str): 164 action = [action] 165 166 if not any(action): 167 return None 168 169 ### Simple case, e.g. ['show'] 170 if len(action) == 1: 171 if action[0] in _actions: 172 return _actions[action[0]] 173 174 ### e.g. ['foo'] (and no custom action available) 175 return None 176 177 ### Last case: it could be a custom action with an underscore in the name. 178 action_name_with_underscores = '_'.join(action) 179 candidates = [] 180 for action_key, action_function in _actions.items(): 181 if not '_' in action_key: 182 continue 183 if action_name_with_underscores.startswith(action_key): 184 leftovers = action_name_with_underscores.replace(action_key, '') 185 candidates.append((len(leftovers), action_function)) 186 if len(candidates) > 0: 187 return sorted(candidates)[0][1] 188 189 ### Might be dealing with a subaction. 190 if action[0] in _actions: 191 subactions = get_subactions([action[0]], _actions=_actions) 192 if action[1] not in subactions: 193 if (action[1] + 's') in subactions: 194 return subactions[action[1] + 's'] 195 return _actions[action[0]] 196 return subactions[action[1]] 197 198 return None
Return a function corresponding to the given action list.
This may be a custom action with an underscore, in which case, allow for underscores.
This may also be a subaction, which is handled by get_subactions()
201def get_main_action_name( 202 action: Union[List[str], str], 203 _actions: Optional[Dict[str, Callable[[Any], SuccessTuple]]] = None, 204) -> Union[str, None]: 205 """ 206 Given an action list, return the name of the main function. 207 For subactions, this will return the root function. 208 If no action function can be found, return `None`. 209 210 Parameters 211 ---------- 212 action: Union[List[str], str] 213 The standard action list. 214 215 Examples 216 -------- 217 >>> get_main_action_name(['show', 'pipes']) 218 'show' 219 >>> 220 """ 221 if _actions is None: 222 _actions = actions 223 action_function = get_action(action, _actions=_actions) 224 if action_function is None: 225 return None 226 clean_name = action_function.__name__.lstrip('_') 227 if clean_name in _actions: 228 return clean_name 229 words = clean_name.split('_') 230 first_word = words[0] 231 if first_word in _actions: 232 return first_word 233 ### We might be dealing with shell `do_` functions. 234 second_word = words[1] if len(words) > 1 else None 235 if second_word and second_word in _actions: 236 return second_word 237 return None
Given an action list, return the name of the main function.
For subactions, this will return the root function.
If no action function can be found, return None.
Parameters
- action (Union[List[str], str]): The standard action list.
Examples
>>> get_main_action_name(['show', 'pipes'])
'show'
>>>
240def get_completer( 241 action: Union[List[str], str], 242 _actions: Optional[Dict[str, Callable[[Any], SuccessTuple]]] = None, 243) -> Union[ 244 Callable[['meerschaum._internal.shell.Shell', str, str, int, int], List[str]], None 245 ]: 246 """ 247 Search for a custom completer function for an action. 248 The standard actions complete in the native shell, so only plugin actions have one. 249 """ 250 import importlib, inspect 251 if isinstance(action, str): 252 action = [action] 253 action_function = get_action(action) 254 if action_function is None or getattr(action_function, '_mrsm_core_action', False): 255 return None 256 try: 257 action_module = importlib.import_module(action_function.__module__) 258 except ImportError: 259 action_module = None 260 if action_module is None: 261 return None 262 candidates = [] 263 for name, f in inspect.getmembers(action_module): 264 if not inspect.isfunction(f): 265 continue 266 name_lstrip = name.lstrip('_') 267 if not name_lstrip.startswith('complete_'): 268 continue 269 if name_lstrip == 'complete_' + action_function.__name__: 270 candidates.append((name_lstrip, f)) 271 continue 272 if name_lstrip == 'complete_' + action_function.__name__.split('_')[0]: 273 candidates.append((name_lstrip, f)) 274 if len(candidates) == 1: 275 return candidates[0][1] 276 if len(candidates) > 1: 277 return sorted(candidates)[-1][1] 278 279 return None
Search for a custom completer function for an action. The standard actions complete in the native shell, so only plugin actions have one.