def _create_application(self): """ Create CommandLineInterface instance. """ # Create Vi command buffer. def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. self.leave_command_mode(append_to_history=True) # Execute command. handle_command(self, text) # Create history and search buffers. commands_history = FileHistory( os.path.join(self.config_directory, 'commands_history')) command_buffer = Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=Always(), completer=create_command_completer(self), history=commands_history) search_buffer_history = FileHistory( os.path.join(self.config_directory, 'search_history')) search_buffer = Buffer(history=search_buffer_history, enable_history_search=Always(), accept_action=AcceptAction.IGNORE) # Create app. # Create CLI. application = Application( layout=self.editor_layout.layout, key_bindings_registry=self.key_bindings_manager.registry, buffers={ COMMAND_BUFFER: command_buffer, SEARCH_BUFFER: search_buffer, }, get_style=lambda: self.current_style, paste_mode=Condition(lambda cli: self.paste_mode), ignore_case=Condition(lambda cli: self.ignore_case), use_alternate_screen=True, on_abort=AbortAction.IGNORE, on_exit=AbortAction.IGNORE, on_buffer_changed=Callback(self._current_buffer_changed)) # Handle command line previews. # (e.g. when typing ':colorscheme blue', it should already show the # preview before pressing enter.) def preview(): if self.cli.current_buffer == command_buffer: self.previewer.preview(command_buffer.text) command_buffer.on_text_changed += preview return application
def __init__(self, registry=None, enable_vi_mode=Never(), enable_system_bindings=Never(), enable_search=Always(), enable_open_in_editor=Never(), enable_all=Always()): # Accept both Filters and booleans as input. enable_vi_mode = to_cli_filter(enable_vi_mode) enable_system_bindings = to_cli_filter(enable_system_bindings) enable_open_in_editor = to_cli_filter(enable_open_in_editor) enable_all = to_cli_filter(enable_all) # Create registry. assert registry is None or isinstance(registry, Registry) self.registry = registry or Registry() # Emacs mode filter is the opposite of Vi mode. enable_emacs_mode = ~enable_vi_mode # Vi state. (Object to keep track of in which Vi mode we are.) self.vi_state = ViState() # Load basic bindings. load_basic_bindings(self.registry, enable_all) load_basic_system_bindings(self.registry, enable_system_bindings & enable_all) # Load emacs bindings. load_emacs_bindings(self.registry, enable_emacs_mode & enable_all) load_emacs_open_in_editor_bindings( self.registry, enable_emacs_mode & enable_open_in_editor & enable_all) load_emacs_search_bindings( self.registry, enable_emacs_mode & enable_search & enable_all) load_emacs_system_bindings( self.registry, enable_emacs_mode & enable_system_bindings & enable_all) # Load Vi bindings. load_vi_bindings(self.registry, self.vi_state, enable_visual_key=~enable_open_in_editor, filter=enable_vi_mode & enable_all) load_vi_open_in_editor_bindings( self.registry, self.vi_state, enable_vi_mode & enable_open_in_editor & enable_all) load_vi_search_bindings(self.registry, self.vi_state, enable_vi_mode & enable_search & enable_all) load_vi_system_bindings( self.registry, self.vi_state, enable_vi_mode & enable_system_bindings & enable_all)
def create_python_input_window(): def menu_position(cli): """ When there is no autocompletion menu to be shown, and we have a signature, set the pop-up position at `bracket_start`. """ b = cli.buffers['default'] if b.complete_state is None and settings.signatures: row, col = settings.signatures[0].bracket_start index = b.document.translate_row_col_to_index(row - 1, col) return index return Window( BufferControl( buffer_name=DEFAULT_BUFFER, lexer=lexer, show_line_numbers=ShowLineNumbersFilter(settings, 'default'), input_processors=[ # Show matching parentheses, but only while editing. ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()), HighlightSearchProcessor(preview_search=Always()), HighlightSelectionProcessor()] + extra_buffer_processors, menu_position=menu_position, # Make sure that we always see the result of an reverse-i-search: preview_search=Always(), ), # As long as we're editing, prefer a minimal height of 6. get_height=(lambda cli: (None if cli.is_done else D(min=6))), )
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.""" from prompt_toolkit.filters import Always # this forces the main window to stay as small as possible, avoiding empty lines in selections ps.layout.current_window.dont_extend_height = Always() # disables the cursor, it is not used actively on the quiz example ps.layout.current_window.always_hide_cursor = Always()
def create_python_input_window(): def menu_position(cli): """ When there is no autocompletion menu to be shown, and we have a signature, set the pop-up position at `bracket_start`. """ b = cli.buffers[DEFAULT_BUFFER] if b.complete_state is None and python_input.signatures: row, col = python_input.signatures[0].bracket_start index = b.document.translate_row_col_to_index(row - 1, col) return index return Window( BufferControl( buffer_name=DEFAULT_BUFFER, lexer=lexer, highlighters=[ # Show matching parentheses, but only while editing. ConditionalHighlighter( highlighter=MatchingBracketHighlighter(chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone() & Condition(lambda cli: python_input. highlight_matching_parenthesis)), ConditionalHighlighter( highlighter=SearchHighlighter(preview_search=Always()), filter=HasFocus(SEARCH_BUFFER)), SelectionHighlighter(), ], input_processors=[ ConditionalProcessor(processor=AppendAutoSuggestion(), filter=~IsDone()) ] + extra_buffer_processors, menu_position=menu_position, wrap_lines=Condition(lambda cli: python_input.wrap_lines), # Make sure that we always see the result of an reverse-i-search: preview_search=Always(), ), left_margins=[PromptMargin(python_input)], # Scroll offsets. The 1 at the bottom is important to make sure the # cursor is never below the "Press [Meta+Enter]" message which is a float. scroll_offsets=ScrollOffsets(bottom=1, left=4, right=4), # As long as we're editing, prefer a minimal height of 6. get_height=(lambda cli: (None if cli.is_done or python_input. show_exit_confirmation else input_buffer_height)), )
def _build_cli(self): layout = create_prompt_layout( message='{0}> '.format(self.args['username']), lexer=PygmentsLexer(SqlLexer), ) buf = Buffer(completer=self.completer, history=self.history, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) key_binding_manager = KeyBindingManager( enable_abort_and_exit_bindings=True, ) application = Application( layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) cli = CommandLineInterface(application=application, eventloop=self.eventloop) return cli
def __init__(self, editor, buffer_name, filename=None, text=None): assert isinstance(buffer_name, string_types) assert filename is None or isinstance(filename, string_types) assert text is None or isinstance(text, string_types) assert not (filename and text) self.buffer_name = buffer_name self.filename = filename self.encoding = 'utf-8' self.is_directory = False # Create buffer if filename: self.is_directory, text = self._read(filename) else: text = text or '' self._file_content = text # Append slash to directory names. if self.is_directory: self.filename += '/' # Create Buffer. self.buffer = Buffer( is_multiline=Always(), completer=DocumentCompleter(editor, self), initial_document=Document(text, 0), accept_action=AcceptAction.IGNORE) # List of reporting errors. self.report_errors = []
def _create_window_frame(self, editor_buffer): """ Create a Window for the buffer, with underneat a status bar. """ window = Window( self._create_buffer_control(editor_buffer), allow_scroll_beyond_bottom=Always(), scroll_offsets=PyvimScrollOffsets(self.editor), left_margins=[ ConditionalMargin( margin=NumberredMargin( buffer_name=editor_buffer.buffer_name, relative=Condition( lambda cli: self.editor.relative_number)), filter=Condition( lambda cli: self.editor.show_line_numbers)) ]) return HSplit([ window, VSplit([ WindowStatusBar(self.editor, editor_buffer, self.manager), WindowStatusBarRuler(self.editor, window, editor_buffer.buffer_name), ]), ])
def _create_window_frame(self, editor_buffer): """ Create a Window for the buffer, with underneat a status bar. """ @Condition def wrap_lines(cli): return self.editor.wrap_lines window = Window( self._create_buffer_control(editor_buffer), allow_scroll_beyond_bottom=Always(), scroll_offsets=ScrollOffsets( left=0, right=0, top=Integer.from_callable(lambda: self.editor.scroll_offset), bottom=Integer.from_callable(lambda: self.editor.scroll_offset)), wrap_lines=wrap_lines, left_margins=[ConditionalMargin( margin=NumberredMargin( display_tildes=True, relative=Condition(lambda cli: self.editor.relative_number)), filter=Condition(lambda cli: self.editor.show_line_numbers))], cursorline=Condition(lambda cli: self.editor.cursorline), cursorcolumn=Condition(lambda cli: self.editor.cursorcolumn), get_colorcolumns=( lambda cli: [ColorColumn(pos) for pos in self.editor.colorcolumn])) return HSplit([ window, VSplit([ WindowStatusBar(self.editor, editor_buffer), WindowStatusBarRuler(self.editor, window, editor_buffer.buffer_name), ]), ])
def initialize(self): history = InMemoryHistory() toolbar_handler = create_toolbar_handler(self.get_long_options) layout = create_prompt_layout( get_prompt_tokens=self.get_prompt_tokens, lexer=create_lexer(), get_bottom_toolbar_tokens=toolbar_handler) buf = Buffer(history=history, completer=CrutchCompleter(self.renv), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) manager = get_key_manager(self.set_long_options, self.get_long_options) application = Application(style=style_factory(), layout=layout, buffer=buf, key_bindings_registry=manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface(application=application, eventloop=eventloop)
def create_handle_decorator(registry, filter=Always()): """ Create a key handle decorator, which is compatible with `Registry.handle` but has a `save_before` option, which will make sure that changes are saved to the undo stack of the `Buffer` object before every key press event. :param save_before: Callable that takes an `Event` and returns True if we should save the current buffer, before handling the event. (That's the default.) """ assert isinstance(filter, CLIFilter) def handle(*keys, **kw): save_before = kw.pop('save_before', lambda e: True) # Chain the given filter to the filter of this specific binding. if 'filter' in kw: kw['filter'] = kw['filter'] & filter else: kw['filter'] = filter def decorator(handler_func): @registry.add_binding(*keys, **kw) @wraps(handler_func) def wrapper(event): if save_before(event): event.cli.current_buffer.save_to_undo_stack() handler_func(event) return handler_func return decorator return handle
def create_tutorial_layout(lex): """ layout for example tutorial """ lexer, _, _ = get_lexers(lex, None, None) layout_full = HSplit([ FloatContainer( Window(BufferControl(input_processors=input_processors, lexer=lexer, preview_search=Always()), get_height=get_height), [ Float(xcursor=True, ycursor=True, content=CompletionsMenu( max_height=MAX_COMPLETION, scroll_offset=1, extra_filter=(HasFocus(DEFAULT_BUFFER)))) ]), ConditionalContainer(HSplit([ get_hline(), get_param(lexer), get_hline(), Window(content=BufferControl(buffer_name='example_line', lexer=lexer), ), Window(TokenListControl(get_tutorial_tokens, default_char=Char(' ', Token.Toolbar)), height=D.exact(1)), ]), filter=~IsDone() & RendererHeightIsKnown()) ]) return layout_full
def __init__(self, editor, buffer_name, location=None, text=None): assert isinstance(buffer_name, string_types) assert location is None or isinstance(location, string_types) assert text is None or isinstance(text, string_types) assert not (location and text) self._editor_ref = weakref.ref(editor) self.buffer_name = buffer_name self.location = location self.encoding = 'utf-8' #: is_new: True when this file does not yet exist in the storage. self.is_new = True # Read text. if location: text = self._read(location) else: text = text or '' self._file_content = text # Create Buffer. self.buffer = Buffer(is_multiline=Always(), completer=DocumentCompleter(editor, self), initial_document=Document(text, 0), accept_action=AcceptAction.IGNORE) # List of reporting errors. self.report_errors = []
def __init__(self, content, width=None, height=None, get_width=None, get_height=None, filter=Always(), dont_extend_width=False, dont_extend_height=False, scroll_offset=0, allow_scroll_beyond_bottom=Never()): assert isinstance(content, UIControl) assert width is None or isinstance(width, LayoutDimension) assert height is None or isinstance(height, LayoutDimension) assert get_width is None or callable(get_width) assert get_height is None or callable(get_height) assert width is None or get_width is None assert height is None or get_height is None assert isinstance(filter, CLIFilter) assert isinstance(scroll_offset, Integer) assert isinstance(allow_scroll_beyond_bottom, CLIFilter) self.content = content self.filter = filter self.dont_extend_width = dont_extend_width self.dont_extend_height = dont_extend_height self.scroll_offset = scroll_offset self.allow_scroll_beyond_bottom = allow_scroll_beyond_bottom self._width = get_width or (lambda cli: width) self._height = get_height or (lambda cli: height) self.reset()
def __init__(self, extra_filter=Always()): self.container = ConditionalContainer( content=Window( _CompletionsToolbarControl(), height=Dimension.exact(1), style='class:completions-toolbar'), filter=has_completions & ~is_done & extra_filter)
def create_application(self, full_layout=True): """ makes the application object and the buffers """ if full_layout: layout = create_layout(self.lexer, ExampleLexer, ToolbarLexer) else: layout = create_tutorial_layout(self.lexer) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'description': Buffer(is_multiline=True, read_only=True), 'parameter': Buffer(is_multiline=True, read_only=True), 'examples': Buffer(is_multiline=True, read_only=True), 'bottom_toolbar': Buffer(is_multiline=True), 'example_line': Buffer(is_multiline=True), 'default_values': Buffer(), 'symbols': Buffer(), 'progress': Buffer(is_multiline=False) } writing_buffer = Buffer(history=self.history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always()) return Application( mouse_support=False, style=self.styles, buffer=writing_buffer, on_input_timeout=self.on_input_timeout, key_bindings_registry=registry, layout=layout, buffers=buffers, )
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.""" default_container = ps.layout.container default_buffer_window = ( default_container.get_children()[0].content.get_children()[1].content) assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections default_buffer_window.dont_extend_height = Always() default_buffer_window.always_hide_cursor = Always()
def _build_cli(self, history): def set_vi_mode(value): self.vi_mode = value key_binding_manager = mssqlcli_bindings( get_vi_mode_enabled=lambda: self.vi_mode, set_vi_mode_enabled=set_vi_mode) def prompt_tokens(_): prompt = self.get_prompt() return [(Token.Prompt, prompt)] def get_continuation_tokens(cli, width): continuation = self.multiline_continuation_char * (width - 1) + ' ' return [(Token.Continuation, continuation)] get_toolbar_tokens = create_toolbar_tokens_func( lambda: self.vi_mode, None, None, None) layout = create_prompt_layout( lexer=PygmentsLexer(PostgresLexer), reserve_space_for_menu=self.min_num_menu_lines, get_prompt_tokens=prompt_tokens, get_continuation_tokens=get_continuation_tokens, get_bottom_toolbar_tokens=get_toolbar_tokens, display_completions_in_columns=self.wider_completion_menu, multiline=True, extra_input_processors=[ # Highlight matching brackets while editing. ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()), ]) with self._completer_lock: buf = MssqlBuffer(auto_suggest=AutoSuggestFromHistory(), always_multiline=self.multi_line, multiline_mode=self.multiline_mode, completer=self.completer, history=history, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) editing_mode = EditingMode.VI if self.vi_mode else EditingMode.EMACS application = Application( style=style_factory(self.syntax_style, self.cli_style), layout=layout, buffer=buf, key_bindings_registry=key_binding_manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True, editing_mode=editing_mode) cli = CommandLineInterface(application=application, eventloop=self.eventloop) return cli
def run_main(tc): """:type tc: ToolContract""" print "Loaded tc {c}".format(c=tc) h = History() if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input('Enter max nproc: ') else: # not quite right nproc = 1 output_dir = get_input('Output Directory: ', enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) input_files.append(in_path) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, '/tmp', int(nproc), tool_options) print rtc print "writing RTC" file_name = tc.task.task_id + "_resolved_tool_contract.json" rtc_path = os.path.join(output_dir, file_name) write_resolved_tool_contract(rtc, rtc_path) return rtc
def create_buffer(self, completer, history): return Buffer(history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT)
def _create_cli(self): """Create the prompt_toolkit's CommandLineInterface.""" history = FileHistory(os.path.expanduser('~/.haxornewshistory')) toolbar = Toolbar(lambda: self.paginate_comments) layout = create_default_layout( message=u'haxor> ', reserve_space_for_menu=8, get_bottom_toolbar_tokens=toolbar.handler, ) cli_buffer = Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) self.key_manager = self._create_key_manager() style_factory = StyleFactory(self.theme) application = Application( mouse_support=False, style=style_factory.style, layout=layout, buffer=cli_buffer, key_bindings_registry=self.key_manager.manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface( application=application, eventloop=eventloop)
def update_multiline(): multiline = self.toggle_multiline() if multiline: event.cli.current_buffer.is_multiline = Always() else: event.cli.current_buffer.is_multiline = Never() print('Set multiline', multiline and 'ON' or 'off')
def add_binding_decorator(*keys, **kw): # Pop default filter keyword argument. filter = kw.pop('filter', Always()) assert not kw return self.key_bindings_registry.add_binding(*keys, filter=filter & ~sidebar_visible)
def __init__(self, max_height=None, extra_filter=Always()): super(CompletionsMenu, self).__init__( content=CompletionsMenuControl(), width=LayoutDimension(min=8), height=LayoutDimension(min=1, max=max_height), # Show when there are completions but not at the point we are # returning the input. filter=HasCompletions() & ~IsDone() & extra_filter)
def create_cli(eventloop, message='', multiline=False, is_password=False, vi_mode=False, lexer=None, enable_system_prompt=False, enable_open_in_editor=False, validator=None, completer=None, style=None, history=None, get_prompt_tokens=None, get_bottom_toolbar_tokens=None, extra_input_processors=None, key_bindings_registry=None, output=None, on_abort=AbortAction.RAISE_EXCEPTION, on_exit=AbortAction.RAISE_EXCEPTION, on_accept=AcceptAction.RETURN_DOCUMENT): """ Create a `CommandLineInterface` instance. """ assert isinstance(eventloop, EventLoop) # Create history instance. if history is None: history = History() # Use default registry from KeyBindingManager if none was given. if key_bindings_registry is None: key_bindings_registry = KeyBindingManager( enable_vi_mode=vi_mode, enable_system_prompt=enable_system_prompt, enable_open_in_editor=enable_open_in_editor).registry # Create interface. return CommandLineInterface( eventloop=eventloop, layout=create_default_layout( message=message, lexer=lexer, is_password=is_password, reserve_space_for_menu=(completer is not None), get_prompt_tokens=get_prompt_tokens, get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, extra_input_processors=extra_input_processors), buffer=Buffer( is_multiline=(Always() if multiline else Never()), history=history, validator=validator, completer=completer, ), key_bindings_registry=key_bindings_registry, style=style, output=output, on_abort=on_abort, on_exit=on_exit)
def _build_cli(self): eventloop = create_eventloop() if self._options.persistent_history: history = FileHistory( os.path.join( os.path.expanduser("~"), ".{}_history".format(self._ctx.binary_name) ) ) else: history = InMemoryHistory() layout = create_prompt_layout( lexer=PygmentsLexer(NubiaLexer), reserve_space_for_menu=5, get_prompt_tokens=self.get_prompt_tokens, get_rprompt_tokens=self._status_bar.get_rprompt_tokens, get_bottom_toolbar_tokens=self._status_bar.get_tokens, display_completions_in_columns=False, multiline=True, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor(chars="[](){}"), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone(), ) ], ) buf = Buffer( completer=self._completer, history=history, auto_suggest=self._suggestor, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT, ) # If EDITOR does not exist, take EMACS # if it does, try fit the EMACS/VI pattern using upper editor = getattr( EditingMode, os.environ.get("EDITOR", EditingMode.EMACS).upper(), EditingMode.EMACS, ) application = Application( style=shell_style, buffer=buf, editing_mode=editor, key_bindings_registry=self._registry, layout=layout, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True, ) cli = CommandLineInterface(application=application, eventloop=eventloop) return cli
def _create_buffer(self): self._create_completer() self.buffer = Buffer( history=FileHistory(os.path.expanduser('./network-history')), auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT, )
def run_main(tc): """:type tc: ToolContract""" print("Loaded tc {c}".format(c=tc)) if tc.task.nproc == SymbolTypes.MAX_NPROC: nproc = get_input('Enter max nproc: ') else: # not quite right nproc = 1 output_dir = get_input('Output Directory: ', enable_system_bindings=Always()) output_dir = os.path.abspath(output_dir) input_files = [] for i, input_type in enumerate(tc.task.input_file_types): in_path = get_input(" {i} file {p} path :".format(i=i, p=input_type)) if not os.path.exists(in_path): warnings.warn("Unable to find {p}".format(p=in_path)) # Make sure all inputs are abspaths p = in_path if os.path.isabs(in_path) else os.path.abspath(in_path) input_files.append(p) tool_options = {} rtc = resolve_tool_contract(tc, input_files, output_dir, '/tmp', int(nproc), tool_options, is_distributable=False) print(rtc) def to_n(ext): return "resolved_tool_contract." + ext def to_f(ext): return "_".join([tc.task.task_id, to_n(ext)]) def to_p(ext): return os.path.join(output_dir, to_f(ext)) rtc_path = to_p("json") print("writing RTC to {f}".format(f=rtc_path)) # Always write the JSON RTC file write_resolved_tool_contract(rtc, rtc_path) if rtc.driver.serialization.lower() == "avro": avro_rtc_path = to_p("avro") print("writing AVRO RTC to {f}".format(f=avro_rtc_path)) write_resolved_tool_contract_avro(rtc, avro_rtc_path) return rtc
def _create_cli(self): """Creates the prompt_toolkit's CommandLineInterface. Args: * None. Returns: None. """ history = FileHistory(os.path.expanduser('~/.saws-history')) toolbar = Toolbar(self.get_color, self.get_fuzzy_match, self.get_shortcut_match) layout = create_default_layout( message='saws> ', reserve_space_for_menu=8, lexer=CommandLexer, get_bottom_toolbar_tokens=toolbar.handler, extra_input_processors=[ ConditionalProcessor( processor=HighlightMatchingBracketProcessor( chars='[](){}'), filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()) ] ) cli_buffer = Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) self.key_manager = KeyManager( self.set_color, self.get_color, self.set_fuzzy_match, self.get_fuzzy_match, self.set_shortcut_match, self.get_shortcut_match, self.refresh_resources_and_options, self.handle_docs) style_factory = StyleFactory(self.theme) application = Application( mouse_support=False, style=style_factory.style, layout=layout, buffer=cli_buffer, key_bindings_registry=self.key_manager.manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.aws_cli = CommandLineInterface( application=application, eventloop=eventloop)
def create_default_layout(message='', lexer=None, is_password=False, reserve_space_for_menu=False, get_bottom_toolbar_tokens=None): """ Generate default layout. """ assert get_bottom_toolbar_tokens is None or callable(get_bottom_toolbar_tokens) # Create processors list. input_processors = [HighlightSearchProcessor(), HighlightSelectionProcessor()] if is_password: input_processors.extend([PasswordProcessor(), DefaultPrompt(message)]) else: input_processors.append(DefaultPrompt(message)) # Create bottom toolbar. if get_bottom_toolbar_tokens: toolbars = [Window(TokenListControl(get_bottom_toolbar_tokens, default_char=Char(' ', Token.Toolbar)), height=LayoutDimension.exact(1), filter=~IsDone())] else: toolbars = [] def get_height(cli): # If there is an autocompletion menu to be shown, make sure that our # layout has at least a minimal height in order to display it. if reserve_space_for_menu and not cli.is_done: return LayoutDimension(min=8) else: return LayoutDimension() # Create and return Layout instance. return HSplit([ FloatContainer( Window( BufferControl( input_processors=input_processors, lexer=lexer, # Enable preview_search, we want to have immediate feedback # in reverse-i-search mode. preview_search=Always()), get_height=get_height, ), [ Float(xcursor=True, ycursor=True, content=CompletionsMenu(max_height=16, extra_filter=HasFocus(DEFAULT_BUFFER))) ] ), ValidationToolbar(), SystemToolbar(), ] + toolbars)