execer = self.execer execer.filename = filename ctx = {} # dummy for modules code = execer.compile(src, glbs=ctx, locs=ctx) return code # # Import events # events.doc('on_import_pre_find_spec', """ on_import_pre_find_spec(fullname: str, path: str, target: module or None) -> None Fires before any import find_spec() calls have been executed. The parameters here are the same as importlib.abc.MetaPathFinder.find_spec(). Namely, :``fullname``: The full name of the module to import. :``path``: None if a top-level import, otherwise the ``__path__`` of the parent package. :``target``: Target module used to make a better guess about the package spec. """) events.doc('on_import_post_find_spec', """ on_import_post_find_spec(spec, fullname, path, target) -> None Fires after all import find_spec() calls have been executed. The parameters here the spec and the arguments importlib.abc.MetaPathFinder.find_spec(). Namely, :``spec``: A ModuleSpec object if the spec was found, or None if it was not. :``fullname``: The full name of the module to import. :``path``: None if a top-level import, otherwise the ``__path__`` of the parent
from xonsh.xontribs import update_context, prompt_xontrib_install from xonsh.environ import xonshrc_context from xonsh.execer import Execer from xonsh.platform import (best_shell_type, has_prompt_toolkit, ptk_version_is_supported) from xonsh.tools import XonshError, to_bool_or_int, print_exception from xonsh.events import events import xonsh.history.main as xhm events.doc('on_transform_command', """ on_transform_command(cmd: str) -> str Fired to request xontribs to transform a command line. Return the transformed command, or the same command if no transformaiton occurs. Only done for interactive sessions. This may be fired multiple times per command, with other transformers input or output, so design any handlers for this carefully. """) events.doc('on_precommand', """ on_precommand(cmd: str) -> None Fires just before a command is executed. """) events.doc('on_postcommand', """ on_postcommand(cmd: str, rtn: int, out: str or None, ts: list) -> None Fires just after a command is executed.
import os import random import builtins import warnings from xonsh.xontribs import update_context, prompt_xontrib_install from xonsh.environ import xonshrc_context from xonsh.execer import Execer from xonsh.platform import (best_shell_type, has_prompt_toolkit, ptk_version_is_supported) from xonsh.tools import XonshError, to_bool_or_int from xonsh.events import events events.doc( 'on_precommand', """ on_precommand(cmd: str) -> None Fires just before a command is executed. """) events.doc( 'on_postcommand', """ on_postcommand(cmd: str, rtn: int, out: str or None, ts: list) -> None Fires just after a command is executed. """) class Shell(object): """Main xonsh shell. Initializes execution environment and decides if prompt_toolkit or
import collections.abc import subprocess as sp from xonsh.platform import ON_POSIX, ON_WINDOWS # This is because builtins aren't globally created during testing. # FIXME: Is there a better way? from xonsh.events import events events.doc( "vox_on_create", """ vox_on_create(env: str) -> None Fired after an environment is created. """, ) events.doc( "vox_on_activate", """ vox_on_activate(env: str, path: pathlib.Path) -> None Fired after an environment is activated. """, ) events.doc( "vox_on_deactivate",
def setup_timings(argv): global _timings if "--timings" in argv: events.doc( "on_timingprobe", """ on_timingprobe(name: str) -> None Fired to insert some timings into the startuptime list """, ) @events.on_timingprobe def timing_on_timingprobe(name, **kw): global _timings _timings[name] = clock() @events.on_post_cmdloop def timing_on_post_cmdloop(**kw): global _timings _timings["on_post_cmdloop"] = clock() @events.on_post_init def timing_on_post_init(**kw): global _timings _timings["on_post_init"] = clock() @events.on_post_rc def timing_on_post_rc(**kw): global _timings _timings["on_post_rc"] = clock() @events.on_postcommand def timing_on_postcommand(**kw): global _timings _timings["on_postcommand"] = clock() @events.on_pre_cmdloop def timing_on_pre_cmdloop(**kw): global _timings _timings["on_pre_cmdloop"] = clock() @events.on_pre_rc def timing_on_pre_rc(**kw): global _timings _timings["on_pre_rc"] = clock() @events.on_precommand def timing_on_precommand(**kw): global _timings _timings["on_precommand"] = clock() @events.on_ptk_create def timing_on_ptk_create(**kw): global _timings _timings["on_ptk_create"] = clock() @events.on_chdir def timing_on_chdir(**kw): global _timings _timings["on_chdir"] = clock() @events.on_post_prompt def timing_on_post_prompt(**kw): global _timings _timings = {"on_post_prompt": clock()} @events.on_pre_prompt def timing_on_pre_prompt(**kw): global _timings _timings["on_pre_prompt"] = clock() times = list(_timings.items()) times = sorted(times, key=lambda x: x[1]) width = max(len(s) for s, _ in times) + 2 header_format = "|{{:<{}}}|{{:^11}}|{{:^11}}|".format(width) entry_format = "|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|".format(width) sepline = "|{}|{}|{}|".format("-" * width, "-" * 11, "-" * 11) # Print result table print(" Debug level: {}".format(os.getenv("XONSH_DEBUG", "Off"))) print(sepline) print(header_format.format("Event name", "Time (s)", "Delta (s)")) print(sepline) prevtime = tstart = times[0][1] for name, ts in times: print(entry_format.format(name, ts - tstart, ts - prevtime)) prevtime = ts print(sepline)
import venv import shutil import builtins import collections.abc from xonsh.platform import ON_POSIX, ON_WINDOWS from xonsh.fs import PathLike, fspath # This is because builtins aren't globally created during testing. # FIXME: Is there a better way? from xonsh.events import events events.doc('vox_on_create', """ vox_on_create(env: str) -> None Fired after an environment is created. """) events.doc('vox_on_activate', """ vox_on_activate(env: str) -> None Fired after an environment is activated. """) events.doc('vox_on_deactivate', """ vox_on_deactivate(env: str) -> None Fired after an environment is deactivated. """)
from xonsh.xonfig import print_welcome_screen from xonsh.xontribs import xontribs_load from xonsh.lazyimps import pygments, pyghooks from xonsh.imphooks import install_import_hooks from xonsh.events import events from xonsh.environ import xonshrc_context, make_args_env from xonsh.built_ins import XSH import xonsh.procs.pipelines as xpp events.transmogrify("on_post_init", "LoadEvent") events.doc( "on_post_init", """ on_post_init() -> None Fired after all initialization is finished and we're ready to do work. NOTE: This is fired before the wizard is automatically started. """, ) events.transmogrify("on_exit", "LoadEvent") events.doc( "on_exit", """ on_exit() -> None Fired after all commands have been executed, before tear-down occurs. NOTE: All the caveats of the ``atexit`` module also apply to this event. """,
from prompt_toolkit.shortcuts.prompt import PromptSession from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.styles import merge_styles, Style from prompt_toolkit.styles.pygments import ( style_from_pygments_cls, style_from_pygments_dict, ) Token = _TokenType() events.transmogrify("on_ptk_create", "LoadEvent") events.doc( "on_ptk_create", """ on_ptk_create(prompter: PromptSession, history: PromptToolkitHistory, completer: PromptToolkitCompleter, bindings: KeyBindings) -> Fired after prompt toolkit has been initialized """, ) class PromptToolkit2Shell(BaseShell): """The xonsh shell for prompt_toolkit v2.""" completion_displays_to_styles = { "multi": CompleteStyle.MULTI_COLUMN, "single": CompleteStyle.COLUMN, "readline": CompleteStyle.READLINE_LIKE, "none": None, }
enc = find_source_encoding(src) src = src.decode(encoding=enc) src = src if src.endswith("\n") else src + "\n" return src # # Import events # events.doc( "on_import_pre_find_spec", """ on_import_pre_find_spec(fullname: str, path: str, target: module or None) -> None Fires before any import find_spec() calls have been executed. The parameters here are the same as importlib.abc.MetaPathFinder.find_spec(). Namely, :``fullname``: The full name of the module to import. :``path``: None if a top-level import, otherwise the ``__path__`` of the parent package. :``target``: Target module used to make a better guess about the package spec. """, ) events.doc( "on_import_post_find_spec", """ on_import_post_find_spec(spec, fullname, path, target) -> None Fires after all import find_spec() calls have been executed. The parameters here the spec and the arguments importlib.abc.MetaPathFinder.find_spec(). Namely,
from xonsh.base_shell import BaseShell from xonsh.tools import print_exception from xonsh.pyghooks import (XonshLexer, partial_color_tokenize, xonsh_style_proxy, XonshTerminal256Formatter) from xonsh.ptk.completer import PromptToolkitCompleter from xonsh.ptk.history import PromptToolkitHistory from xonsh.ptk.key_bindings import load_xonsh_bindings from xonsh.ptk.shortcuts import Prompter from xonsh.events import events events.transmogrify('on_ptk_create', 'LoadEvent') events.doc('on_ptk_create', """ on_ptk_create(prompter: Prompter, history: PromptToolkitHistory, completer: PromptToolkitCompleter, bindings: KeyBindingManager) -> Fired after prompt toolkit has been initialized """) class PromptToolkitShell(BaseShell): """The xonsh shell.""" def __init__(self, **kwargs): super().__init__(**kwargs) self.prompter = Prompter() self.history = PromptToolkitHistory() self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx) key_bindings_manager_args = { 'enable_auto_suggest_bindings': True, 'enable_search': True,
to_bool_or_int, bool_or_int_to_str, csv_to_bool_seq, bool_seq_to_csv, DefaultNotGiven, print_exception, setup_win_unicode_console, intensify_colors_on_win_setter, is_dynamic_cwd_width, to_dynamic_cwd_tuple, dynamic_cwd_tuple_to_str, is_logfile_opt, to_logfile_opt, logfile_opt_to_str, executables_in, is_nonstring_seq_of_strings, pathsep_to_upper_seq, seq_to_upper_pathsep, print_color, is_history_backend, to_itself, swap_values, ) import xonsh.prompt.base as prompt events.doc('on_envvar_new', """ on_envvar_new(name: str, value: Any) -> None Fires after a new environment variable is created. Note: Setting envvars inside the handler might cause a recursion until the limit. """) events.doc('on_envvar_change', """ on_envvar_change(name: str, oldvalue: Any, newvalue: Any) -> None Fires after an environment variable is changed. Note: Setting envvars inside the handler might cause a recursion until the limit. """) @lazyobject
import difflib import builtins import warnings from xonsh.platform import (best_shell_type, has_prompt_toolkit, ptk_version_is_supported) from xonsh.tools import XonshError, print_exception from xonsh.events import events import xonsh.history.main as xhm events.doc('on_transform_command', """ on_transform_command(cmd: str) -> str Fired to request xontribs to transform a command line. Return the transformed command, or the same command if no transformation occurs. Only done for interactive sessions. This may be fired multiple times per command, with other transformers input or output, so design any handlers for this carefully. """) events.doc('on_precommand', """ on_precommand(cmd: str) -> None Fires just before a command is executed. """) events.doc('on_postcommand', """ on_postcommand(cmd: str, rtn: int, out: str or None, ts: list) -> None Fires just after a command is executed. The arguments are the same as history.
global _unc_tempDrives if left_drive not in _unc_tempDrives: # if not one we've mapped, don't unmap it return for p in DIRSTACK + [cwd]: # if still in use , don't aunmap it. if p.casefold().startswith(left_drive): return _unc_tempDrives.pop(left_drive) subprocess.check_output(['NET', 'USE', left_drive, '/delete'], universal_newlines=True) events.doc('on_chdir', """ on_chdir(olddir: str, newdir: str) -> None Fires when the current directory is changed for any reason. """) def _get_cwd(): try: return os.getcwd() except (OSError, FileNotFoundError): return None def _change_working_directory(newdir): env = builtins.__xonsh_env__ old = env['PWD'] new = os.path.join(old, newdir)
ptk_above_min_supported, has_prompt_toolkit, minimum_required_ptk_version, ) from xonsh.tools import XonshError, print_exception, simple_random_choice from xonsh.events import events import xonsh.history.main as xhm events.doc( "on_transform_command", """ on_transform_command(cmd: str) -> str Fired to request xontribs to transform a command line. Return the transformed command, or the same command if no transformation occurs. Only done for interactive sessions. This may be fired multiple times per command, with other transformers input or output, so design any handlers for this carefully. """, ) events.doc( "on_precommand", """ on_precommand(cmd: str) -> None Fires just before a command is executed. """, )
from prompt_toolkit.key_binding import KeyBindings from prompt_toolkit.history import ThreadedHistory from prompt_toolkit.shortcuts import print_formatted_text as ptk_print from prompt_toolkit.shortcuts import CompleteStyle from prompt_toolkit.shortcuts.prompt import PromptSession from prompt_toolkit.formatted_text import PygmentsTokens from prompt_toolkit.styles.pygments import (style_from_pygments_cls, style_from_pygments_dict) Token = _TokenType() events.transmogrify('on_ptk_create', 'LoadEvent') events.doc('on_ptk_create', """ on_ptk_create(prompter: PromptSession, history: PromptToolkitHistory, completer: PromptToolkitCompleter, bindings: KeyBindings) -> Fired after prompt toolkit has been initialized """) class PromptToolkit2Shell(BaseShell): """The xonsh shell for prompt_toolkit v2.""" def __init__(self, **kwargs): super().__init__(**kwargs) if ON_WINDOWS: winutils.enable_virtual_terminal_processing() self._first_prompt = True self.history = ThreadedHistory(PromptToolkitHistory()) self.prompter = PromptSession(history=self.history) self.pt_completer = PromptToolkitCompleter(self.completer, self.ctx, self)
def setup_timings(): global _timings if '--timings' in sys.argv: events.doc('on_timingprobe', """ on_timingprobe(name: str) -> None Fired to insert some timings into the startuptime list """) @events.on_timingprobe def timing_on_timingprobe(name, **kw): global _timings _timings[name] = clock() @events.on_post_cmdloop def timing_on_post_cmdloop(**kw): global _timings _timings['on_post_cmdloop'] = clock() @events.on_post_init def timing_on_post_init(**kw): global _timings _timings['on_post_init'] = clock() @events.on_post_rc def timing_on_post_rc(**kw): global _timings _timings['on_post_rc'] = clock() @events.on_postcommand def timing_on_postcommand(**kw): global _timings _timings['on_postcommand'] = clock() @events.on_pre_cmdloop def timing_on_pre_cmdloop(**kw): global _timings _timings['on_pre_cmdloop'] = clock() @events.on_pre_rc def timing_on_pre_rc(**kw): global _timings _timings['on_pre_rc'] = clock() @events.on_precommand def timing_on_precommand(**kw): global _timings _timings['on_precommand'] = clock() @events.on_ptk_create def timing_on_ptk_create(**kw): global _timings _timings['on_ptk_create'] = clock() @events.on_chdir def timing_on_chdir(**kw): global _timings _timings['on_chdir'] = clock() @events.on_post_prompt def timing_on_post_prompt(**kw): global _timings _timings = {'on_post_prompt': clock()} @events.on_pre_prompt def timing_on_pre_prompt(**kw): global _timings _timings['on_pre_prompt'] = clock() times = list(_timings.items()) times = sorted(times, key=lambda x: x[1]) width = max(len(s) for s, _ in times) + 2 header_format = '|{{:<{}}}|{{:^11}}|{{:^11}}|'.format(width) entry_format = '|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|'.format(width) sepline = '|{}|{}|{}|'.format('-'*width, '-'*11, '-'*11) # Print result table print(' Debug level: {}'.format(os.getenv('XONSH_DEBUG', 'Off'))) print(sepline) print(header_format.format('Event name', 'Time (s)', 'Delta (s)')) print(sepline) prevtime = tstart = times[0][1] for name, ts in times: print(entry_format.format(name, ts - tstart, ts - prevtime)) prevtime = ts print(sepline)
import random import builtins import warnings from xonsh.xontribs import update_context, prompt_xontrib_install from xonsh.environ import xonshrc_context from xonsh.execer import Execer from xonsh.platform import (best_shell_type, has_prompt_toolkit, ptk_version_is_supported) from xonsh.tools import XonshError, to_bool_or_int from xonsh.events import events events.doc('on_precommand', """ on_precommand(cmd: str) -> None Fires just before a command is executed. """) events.doc('on_postcommand', """ on_postcommand(cmd: str, rtn: int, out: str or None, ts: list) -> None Fires just after a command is executed. """) class Shell(object): """Main xonsh shell. Initializes execution environment and decides if prompt_toolkit or readline version of shell should be used.
from xonsh.proc import HiddenCommandPipeline from xonsh.jobs import ignore_sigtstp from xonsh.tools import setup_win_unicode_console, print_color from xonsh.platform import HAS_PYGMENTS, ON_WINDOWS from xonsh.codecache import run_script_with_cache, run_code_with_cache from xonsh.xonfig import xonfig_main from xonsh.lazyimps import pygments, pyghooks from xonsh.imphooks import install_hook from xonsh.events import events events.transmogrify('on_post_init', 'LoadEvent') events.doc('on_post_init', """ on_post_init() -> None Fired after all initialization is finished and we're ready to do work. NOTE: This is fired before the wizard is automatically started. """) events.transmogrify('on_exit', 'LoadEvent') events.doc('on_exit', """ on_exit() -> None Fired after all commands have been executed, before tear-down occurs. NOTE: All the caveats of the ``atexit`` module also apply to this event. """) events.transmogrify('on_pre_cmdloop', 'LoadEvent')
if left_drive not in _unc_tempDrives: # if not one we've mapped, don't unmap it return for p in DIRSTACK + [cwd]: # if still in use , don't unmap it. if p.casefold().startswith(left_drive): return _unc_tempDrives.pop(left_drive) subprocess.check_output(["NET", "USE", left_drive, "/delete"], universal_newlines=True) events.doc( "on_chdir", """ on_chdir(olddir: str, newdir: str) -> None Fires when the current directory is changed for any reason. """, ) def _get_cwd(): try: return os.getcwd() except OSError: return None def _change_working_directory(newdir, follow_symlinks=False): env = XSH.env old = env["PWD"]
from xonsh.style_tools import ( partial_color_tokenize, _TokenType, DEFAULT_STYLE_DICT as _DEFAULT_STYLE_DICT, ) from xonsh.lazyimps import pygments, pyghooks, winutils from xonsh.pygments_cache import get_all_styles from xonsh.lazyasd import LazyObject Token = _TokenType() events.transmogrify("on_ptk_create", "LoadEvent") events.doc( "on_ptk_create", """ on_ptk_create(prompter: Prompter, history: PromptToolkitHistory, completer: PromptToolkitCompleter, bindings: KeyBindingManager) -> Fired after prompt toolkit has been initialized """, ) # Convert new ansicolor names to names # understood by PTK1 DEFAULT_STYLE_DICT = LazyObject( lambda: ansicolors_to_ptk1_names(_DEFAULT_STYLE_DICT), globals(), "DEFAULT_STYLE_DICT", ) class PromptToolkitShell(BaseShell): """The xonsh shell."""
def setup_timings(): global _timings if '--timings' in sys.argv: events.doc('on_timingprobe', """ on_timingprobe(name: str) -> None Fired to insert some timings into the startuptime list """) @events.on_timingprobe def timing_on_timingprobe(name, **kw): global _timings _timings[name] = clock() @events.on_post_cmdloop def timing_on_post_cmdloop(**kw): global _timings _timings['on_post_cmdloop'] = clock() @events.on_post_init def timing_on_post_init(**kw): global _timings _timings['on_post_init'] = clock() @events.on_post_rc def timing_on_post_rc(**kw): global _timings _timings['on_post_rc'] = clock() @events.on_postcommand def timing_on_postcommand(**kw): global _timings _timings['on_postcommand'] = clock() @events.on_pre_cmdloop def timing_on_pre_cmdloop(**kw): global _timings _timings['on_pre_cmdloop'] = clock() @events.on_pre_rc def timing_on_pre_rc(**kw): global _timings _timings['on_pre_rc'] = clock() @events.on_precommand def timing_on_precommand(**kw): global _timings _timings['on_precommand'] = clock() @events.on_ptk_create def timing_on_ptk_create(**kw): global _timings _timings['on_ptk_create'] = clock() @events.on_chdir def timing_on_chdir(**kw): global _timings _timings['on_chdir'] = clock() @events.on_post_prompt def timing_on_post_prompt(**kw): global _timings _timings = {'on_post_prompt': clock()} @events.on_pre_prompt def timing_on_pre_prompt(**kw): global _timings _timings['on_pre_prompt'] = clock() times = list(_timings.items()) times = sorted(times, key=lambda x: x[1]) width = max(len(s) for s, _ in times) + 2 header_format = '|{{:<{}}}|{{:^11}}|{{:^11}}|'.format(width) entry_format = '|{{:<{}}}|{{:^11.3f}}|{{:^11.3f}}|'.format(width) sepline = '|{}|{}|{}|'.format('-' * width, '-' * 11, '-' * 11) # Print result table print(' Debug level: {}'.format(os.getenv('XONSH_DEBUG', 'Off'))) print(sepline) print(header_format.format('Event name', 'Time (s)', 'Delta (s)')) print(sepline) prevtime = tstart = times[0][1] for name, ts in times: print(entry_format.format(name, ts - tstart, ts - prevtime)) prevtime = ts print(sepline)
def setup_timings(argv): global _timings if "--timings" in argv: events.doc( "on_timingprobe", """ on_timingprobe(name: str) -> None Fired to insert some timings into the startuptime list """, ) @events.on_timingprobe def timing_on_timingprobe(name, **kw): global _timings _timings[name] = clock() @events.on_post_cmdloop def timing_on_post_cmdloop(**kw): global _timings _timings["on_post_cmdloop"] = clock() @events.on_post_init def timing_on_post_init(**kw): global _timings _timings["on_post_init"] = clock() @events.on_post_rc def timing_on_post_rc(**kw): global _timings _timings["on_post_rc"] = clock() @events.on_postcommand def timing_on_postcommand(**kw): global _timings _timings["on_postcommand"] = clock() @events.on_pre_cmdloop def timing_on_pre_cmdloop(**kw): global _timings _timings["on_pre_cmdloop"] = clock() @events.on_pre_rc def timing_on_pre_rc(**kw): global _timings _timings["on_pre_rc"] = clock() @events.on_precommand def timing_on_precommand(**kw): global _timings _timings["on_precommand"] = clock() @events.on_ptk_create def timing_on_ptk_create(**kw): global _timings _timings["on_ptk_create"] = clock() @events.on_chdir def timing_on_chdir(**kw): global _timings _timings["on_chdir"] = clock() @events.on_pre_prompt_format def timing_on_pre_prompt_format(**kw): global _timings _timings["on_pre_prompt_format"] = clock() @events.on_post_prompt def timing_on_post_prompt(**kw): global _timings _timings = {"on_post_prompt": clock()} @events.on_pre_prompt def timing_on_pre_prompt(**kw): global _timings _timings["on_pre_prompt"] = clock() times = list(_timings.items()) times = sorted(times, key=lambda x: x[1]) width = max(len(s) for s, _ in times) + 2 header_format = f"|{{:<{width}}}|{{:^11}}|{{:^11}}|" entry_format = f"|{{:<{width}}}|{{:^11.3f}}|{{:^11.3f}}|" sepline = "|{}|{}|{}|".format("-" * width, "-" * 11, "-" * 11) # Print result table print(" Debug level: {}".format(os.getenv("XONSH_DEBUG", "Off"))) print(sepline) print(header_format.format("Event name", "Time (s)", "Delta (s)")) print(sepline) prevtime = tstart = times[0][1] for name, ts in times: print(entry_format.format(name, ts - tstart, ts - prevtime)) prevtime = ts print(sepline)
WIZARD_XONTRIB_QUESTION = "Would you like to enable xontribs now, " + wiz.YN WIZARD_TAIL = """ Thanks for using the xonsh configuration wizard!""" _XONFIG_SOURCE_FOREIGN_SHELL_COMMAND: tp.Dict[str, str] = collections.defaultdict( lambda: "source-foreign", bash="source-bash", cmd="source-cmd", zsh="source-zsh") events.doc( "on_xonfig_info_requested", """ on_xonfig_info_requested() -> list[tuple[str, str]] Register a callable that will return extra info when ``xonfig info`` is called. """, ) def _dump_xonfig_foreign_shell(path, value): shell = value["shell"] shell = CANON_SHELL_NAMES.get(shell, shell) cmd = [_XONFIG_SOURCE_FOREIGN_SHELL_COMMAND[shell]] interactive = value.get("interactive", None) if interactive is not None: cmd.extend(["--interactive", str(interactive)]) login = value.get("login", None) if login is not None: cmd.extend(["--login", str(login)])