B
    )`8                 @   s4  d Z ddlmZ ddlmZ ddlmZ ddlZddlZddlZddlZddl	Z	ddl
ZddlZddlmZ ddlmZ dZd	Zd
ZdZdZG dd deZG dd deZd&ddZd'ddZG dd deZdd Zdd ZG dd deZG dd deZ G d d! d!eZ!G d"d# d#eZ"G d$d% d%eZ#dS )(z>Building Blocks of TensorFlow Debugger Command-Line Interface.    )absolute_import)division)print_functionN)pywrap_tf_session)gfilez  Zexplicit_user_exitregex_match_linesZinit_scroll_poszmm:c               @   s"   e Zd ZdddZedd ZdS )CommandLineExitNc             C   s   t |  || _d S )N)	Exception__init___exit_token)self
exit_token r   ^/home/dcms/DCMS/lib/python3.7/site-packages/tensorflow/python/debug/cli/debugger_cli_common.pyr
   +   s    
zCommandLineExit.__init__c             C   s   | j S )N)r   )r   r   r   r   r   /   s    zCommandLineExit.exit_token)N)__name__
__module____qualname__r
   propertyr   r   r   r   r   r   )   s   
r   c               @   s*   e Zd ZdZd
ddZdd Zdd	 ZdS )RichLinea  Rich single-line text.

  Attributes:
    text: A plain string, the raw text represented by this object.  Should not
      contain newlines.
    font_attr_segs: A list of (start, end, font attribute) triples, representing
      richness information applied to substrings of text.
   Nc             C   s(   || _ |rdt||fg| _ng | _dS )a2  Construct a RichLine with no rich attributes or a single attribute.

    Args:
      text: Raw text string
      font_attr: If specified, a single font attribute to be applied to the
        entire text.  Extending this object via concatenation allows creation
        of text with varying attributes.
    r   N)textlenfont_attr_segs)r   r   	font_attrr   r   r   r
   >   s    zRichLine.__init__c             C   s   t  }t|tjr2| j| |_| jdd |_|S t|t r| j|j |_| jdd |_t| j}x.|jD ]$\}}}|j|| || |f qlW |S td| dS )a  Concatenate two chunks of maybe rich text to make a longer rich line.

    Does not modify self.

    Args:
      other: Another piece of text to concatenate with this one.
        If it is a plain str, it will be appended to this string with no
        attributes.  If it is a RichLine, it will be appended to this string
        with its attributes preserved.

    Returns:
      A new RichLine comprising both chunks of text, with appropriate
        attributes applied to the corresponding substrings.
    Nz)%r cannot be concatenated with a RichLine)	r   
isinstancesixstring_typesr   r   r   append	TypeError)r   otherretZold_lenstartendr   r   r   r   __add__O   s    

zRichLine.__add__c             C   s
   t | jS )N)r   r   )r   r   r   r   __len__m   s    zRichLine.__len__)r   N)r   r   r   __doc__r
   r#   r$   r   r   r   r   r   4   s   
r   c             C   s^   g }i }xFt | D ]:\}}t|trB||j |jrL|j||< q|| qW t|||dS )a	  Convert a list of RichLine objects or strings to a RichTextLines object.

  Args:
    rich_text_list: a list of RichLine objects or strings
    annotations: annotations for the resultant RichTextLines object.

  Returns:
    A corresponding RichTextLines object.
  )annotations)	enumerater   r   r   r   r   RichTextLines)Zrich_text_listr&   linesr   iZrlr   r   r   #rich_text_lines_from_rich_line_listq   s    

r+   Fc             C   sF   dt j g}|d | r>|d |dtj  |d t|S )zGenerate RichTextLines with TensorFlow version info.

  Args:
    include_dependency_versions: Include the version of TensorFlow's key
      dependencies, such as numpy.

  Returns:
    A formatted, multi-line `RichTextLines` object.
  zTensorFlow version: %sr   zDependency version(s):z  numpy: %s)r   __version__r   npr(   )include_dependency_versionsr)   r   r   r   get_tensorflow_version_lines   s    



r/   c               @   s   e Zd ZdZdddZedd Zedd Zed	d
 Zdd Z	dd Z
dd Zdd ZdddZdd ZdddZdd ZdS )r(   a]  Rich multi-line text.

  Line-by-line text output, with font attributes (e.g., color) and annotations
  (e.g., indices in a multi-dimensional tensor). Used as the text output of CLI
  commands. Can be rendered on terminal environments such as curses.

  This is not to be confused with Rich Text Format (RTF). This class is for text
  lines only.
  Nc             C   s`   t |tr|| _n&t |tjr(|g| _ntdt| || _| jsJi | _|| _| js\i | _dS )a   Constructor of RichTextLines.

    Args:
      lines: A list of str or a single str, representing text output to
        screen. The latter case is for convenience when the text output is
        single-line.
      font_attr_segs: A map from 0-based row index to a list of 3-tuples.
        It lists segments in each row that have special font attributes, such
        as colors, that are not the default attribute. For example:
        {1: [(0, 3, "red"), (4, 7, "green")], 2: [(10, 20, "yellow")]}

        In each tuple, the 1st element is the start index of the segment. The
        2nd element is the end index, in an "open interval" fashion. The 3rd
        element is an object or a list of objects that represents the font
        attribute. Colors are represented as strings as in the examples above.
      annotations: A map from 0-based row index to any object for annotating
        the row. A typical use example is annotating rows of the output as
        indices in a multi-dimensional tensor. For example, consider the
        following text representation of a 3x2x2 tensor:
          [[[0, 0], [0, 0]],
           [[0, 0], [0, 0]],
           [[0, 0], [0, 0]]]
        The annotation can indicate the indices of the first element shown in
        each row, i.e.,
          {0: [0, 0, 0], 1: [1, 0, 0], 2: [2, 0, 0]}
        This information can make display of tensors on screen clearer and can
        help the user navigate (scroll) to the desired location in a large
        tensor.

    Raises:
      ValueError: If lines is of invalid type.
    zUnexpected type in lines: %sN)	r   list_linesr   r   
ValueErrortype_font_attr_segs_annotations)r   r)   r   r&   r   r   r   r
      s    !

zRichTextLines.__init__c             C   s   | j S )N)r1   )r   r   r   r   r)      s    zRichTextLines.linesc             C   s   | j S )N)r4   )r   r   r   r   r      s    zRichTextLines.font_attr_segsc             C   s   | j S )N)r5   )r   r   r   r   r&      s    zRichTextLines.annotationsc             C   s
   t | jS )N)r   r1   )r   r   r   r   	num_lines   s    zRichTextLines.num_linesc             C   s   |dk s|dk rt d| j|| }i }x0| jD ]&}||kr2||k r2| j| ||| < q2W i }xJ| jD ]@}t|ts| j| ||< qh||krh||k rh| j| ||| < qhW t|||dS )a}  Slice a RichTextLines object.

    The object itself is not changed. A sliced instance is returned.

    Args:
      begin: (int) Beginning line index (inclusive). Must be >= 0.
      end: (int) Ending line index (exclusive). Must be >= 0.

    Returns:
      (RichTextLines) Sliced output instance of RichTextLines.

    Raises:
      ValueError: If begin or end is negative.
    r   zEncountered negative index.)r   r&   )r2   r)   r   r&   r   intr(   )r   beginr"   r)   r   keyr&   r   r   r   slice   s    
zRichTextLines.slicec             C   s~   |   }| j|j x"|jD ]}|j| | j|| < qW x>|jD ]4}t|trf|j| | j	|| < qB|j| | j	|< qBW dS )aC  Extend this instance of RichTextLines with another instance.

    The extension takes effect on the text lines, the font attribute segments,
    as well as the annotations. The line indices in the font attribute
    segments and the annotations are adjusted to account for the existing
    lines. If there are duplicate, non-line-index fields in the annotations,
    the value from the input argument "other" will override that in this
    instance.

    Args:
      other: (RichTextLines) The other RichTextLines instance to be appended at
        the end of this instance.
    N)
r6   r1   extendr)   r   r4   r&   r   r7   r5   )r   r   Zorig_num_lines
line_indexr9   r   r   r   r;     s    
zRichTextLines.extendc             C   s   |  }|j| j | _i }x | jD ]}| j| ||| < q"W ||j || _i }x:| jD ]0}t|tr|| j	| ||| < qZ|j	| ||< qZW ||j	 || _dS )zAdd another RichTextLines object to the front.

    Args:
      other: (RichTextLines) The other object to add to the front to this
        object.
    N)
r6   r)   r1   r   updater4   r5   r   r7   r&   )r   r   Zother_num_linesZnew_font_attr_segsr<   Znew_annotationsr9   r   r   r   _extend_before.  s    
zRichTextLines._extend_beforec             C   s(   | j | |r$|| jt| j d < dS )zAppend a single line of text.

    Args:
      line: (str) The text to be added to the end.
      font_attr_segs: (list of tuples) Font attribute segments of the appended
        line.
       N)r1   r   r4   r   )r   liner   r   r   r   r   N  s    	zRichTextLines.appendc             C   s   |  |j|j d S )N)r   r   r   )r   Z	rich_liner   r   r   append_rich_line[  s    zRichTextLines.append_rich_linec             C   s$   t |}|r||jd< | | dS )zPrepend (i.e., add to the front) a single line of text.

    Args:
      line: (str) The text to be added to the front.
      font_attr_segs: (list of tuples) Font attribute segments of the appended
        line.
    r   N)r(   r   r>   )r   r@   r   r   r   r   r   prepend^  s    	
zRichTextLines.prependc          	   C   s:   t |d$}x| jD ]}||d  qW W dQ R X dS )zWrite the object itself to file, in a plain format.

    The font_attr_segs and annotations are ignored.

    Args:
      file_path: (str) path of the file to write to.
    w
N)r   ZOpenr1   write)r   	file_pathfr@   r   r   r   write_to_filel  s    	zRichTextLines.write_to_file)NN)N)N)r   r   r   r%   r
   r   r)   r   r&   r6   r:   r;   r>   r   rA   rB   rH   r   r   r   r   r(      s   	
2(  

r(   c             C   s   t | jt| j| jd}yt|}W n" tj	k
rJ   t
d| Y nX g }xt|jD ]\}}||}g }	x$|D ]}
|	|
 |
 |f qxW |	r\||jkr|	|j|< n,|j| |	 t|j| dd d|j|< || q\W ||jt< |S )a  Perform regex match in rich text lines.

  Produces a new RichTextLines object with font_attr_segs containing highlighted
  regex matches.

  Example use cases include:
  1) search for specific items in a large list of items, and
  2) search for specific numerical values in a large tensor.

  Args:
    orig_screen_output: The original RichTextLines, in which the regex find
      is to be performed.
    regex: The regex used for matching.
    font_attr: Font attribute used for highlighting the found result.

  Returns:
    A modified copy of orig_screen_output.

  Raises:
    ValueError: If input str regex is not a valid regular expression.
  )r   r&   z Invalid regular expression: "%s"c             S   s   | d S )Nr   r   )xr   r   r   <lambda>      zregex_find.<locals>.<lambda>)r9   )r(   r)   copydeepcopyr   r&   recompilesre_constantserrorr2   r'   finditerr   r!   r"   r;   sortedREGEX_MATCH_LINES_KEY)Zorig_screen_outputregexr   Znew_screen_outputZre_progr   r*   r@   Zfind_itZ
match_segsmatchr   r   r   
regex_find}  s.    





rW   c             C   s"  g }t | tstdt |ts(tdtg }d}xt| jD ]\}}||  || jkrt| j| |j|< t	||kr|j| || j
kr| j
| |j
|< |d7 }qBg }g }|| j
kr| j
| }d}	x|	t	|k r|	| t	|krt	|}
n|	| }
|||	|
  x|D ]}|d |
k r|d |	kr|d |	krX|d |	 }nd}|d |
k rx|d |	 }n|
|	 }||kr|||d f}||j
kr|g|j
|< n|j
| | qW |	|7 }	|d7 }qW |j| qBW x,| jD ]"}t |ts| j| |j|< qW ||fS )ab  Wrap RichTextLines according to maximum number of columns.

  Produces a new RichTextLines object with the text lines, font_attr_segs and
  annotations properly wrapped. This ought to be used sparingly, as in most
  cases, command handlers producing RichTextLines outputs should know the
  screen/panel width via the screen_info kwarg and should produce properly
  length-limited lines in the output accordingly.

  Args:
    inp: Input RichTextLines object.
    cols: Number of columns, as an int.

  Returns:
    1) A new instance of RichTextLines, with line lengths limited to cols.
    2) A list of new (wrapped) line index. For example, if the original input
      consists of three lines and only the second line is wrapped, and it's
      wrapped into two lines, this return value will be: [0, 1, 3].
  Raises:
    ValueError: If inputs have invalid types.
  z#Invalid type of input screen_outputzInvalid type of input colsr   r?      )r   r(   r2   r7   r'   r)   r   r6   r&   r   r   r;   )inpcolsZnew_line_indicesoutZrow_counterr*   r@   ZwlinesZosegsidxZrlimsegZlbrbZwsegr9   r   r   r   wrap_rich_text_lines  s\    









r_   c               @   s~   e Zd ZdZdZdgZdZdgZdd Zdd	d
Z	dddZ
dd ZdddZdd ZdddZdddZdd Zdd ZdS ) CommandHandlerRegistrya  Registry of command handlers for CLI.

  Handler methods (callables) for user commands can be registered with this
  class, which then is able to dispatch commands to the correct handlers and
  retrieve the RichTextLines output.

  For example, suppose you have the following handler defined:
    def echo(argv, screen_info=None):
      return RichTextLines(["arguments = %s" % " ".join(argv),
                            "screen_info = " + repr(screen_info)])

  you can register the handler with the command prefix "echo" and alias "e":
    registry = CommandHandlerRegistry()
    registry.register_command_handler("echo", echo,
        "Echo arguments, along with screen info", prefix_aliases=["e"])

  then to invoke this command handler with some arguments and screen_info, do:
    registry.dispatch_command("echo", ["foo", "bar"], screen_info={"cols": 80})

  or with the prefix alias:
    registry.dispatch_command("e", ["foo", "bar"], screen_info={"cols": 80})

  The call will return a RichTextLines object which can be rendered by a CLI.
  helphversionverc             C   sR   i | _ i | _i | _i | _d | _| j| j| jd| jd | j| j	| j
d| jd d S )NzPrint this help message.)prefix_aliasesz:Print the versions of TensorFlow and its key dependencies.)	_handlers_alias_to_prefix_prefix_to_aliases_prefix_to_help_help_introregister_command_handlerHELP_COMMAND_help_handlerHELP_COMMAND_ALIASESVERSION_COMMAND_version_handlerVERSION_COMMAND_ALIASES)r   r   r   r   r
   1  s    
zCommandHandlerRegistry.__init__Nc             C   s   |st d|| jkr"t d| t|s2t dt|tjsFt d|rx,|D ]$}| |rjt d| || j|< qPW || j|< || j|< || j	|< dS )a  Register a callable as a command handler.

    Args:
      prefix: Command prefix, i.e., the first word in a command, e.g.,
        "print" as in "print tensor_1".
      handler: A callable of the following signature:
          foo_handler(argv, screen_info=None),
        where argv is the argument vector (excluding the command prefix) and
          screen_info is a dictionary containing information about the screen,
          such as number of columns, e.g., {"cols": 100}.
        The callable should return:
          1) a RichTextLines object representing the screen output.

        The callable can also raise an exception of the type CommandLineExit,
        which if caught by the command-line interface, will lead to its exit.
        The exception can optionally carry an exit token of arbitrary type.
      help_info: A help string.
      prefix_aliases: Aliases for the command prefix, as a list of str. E.g.,
        shorthands for the command prefix: ["p", "pr"]

    Raises:
      ValueError: If
        1) the prefix is empty, or
        2) handler is not callable, or
        3) a handler is already registered for the prefix, or
        4) elements in prefix_aliases clash with existing aliases.
        5) help_info is not a str.
    zEmpty command prefixz7A handler is already registered for command prefix "%s"zhandler is not callablezhelp_info is not a strz@The prefix alias "%s" clashes with existing prefixes or aliases.N)
r2   rf   callabler   r   r   _resolve_prefixrg   rh   ri   )r   prefixhandler	help_infore   aliasr   r   r   rk   O  s&    "





z/CommandHandlerRegistry.register_command_handlerc       	   
   C   s8  |st d| |}|s&t d| | j| }y|||d}W n tk
rf } z|W dd}~X Y n tk
r } zd| d| g}t|}W dd}~X Y np tk
r } zPd|d|f d	t|t	|f g}|
d
 |t d t|}W dd}~X Y nX t|ts4|dk	r4t dt	| |S )a  Handles a command by dispatching it to a registered command handler.

    Args:
      prefix: Command prefix, as a str, e.g., "print".
      argv: Command argument vector, excluding the command prefix, represented
        as a list of str, e.g.,
        ["tensor_1"]
      screen_info: A dictionary containing screen info, e.g., {"cols": 100}.

    Returns:
      An instance of RichTextLines or None. If any exception is caught during
      the invocation of the command handler, the RichTextLines will wrap the
      error type and message.

    Raises:
      ValueError: If
        1) prefix is empty, or
        2) no command handler is registered for the command prefix, or
        3) the handler is found for the prefix, but it fails to return a
          RichTextLines or raise any exception.
      CommandLineExit:
        If the command handler raises this type of exception, this method will
        simply pass it along.
    zPrefix is emptyz0No handler is registered for command prefix "%s")screen_infoNzSyntax error for command: %szFor help, do "help %s"z1Error occurred during handling of command: %s %s: z%s: %sr   rD   zLReturn value from command handler %s is not None or a RichTextLines instance)r2   rs   rf   r   
SystemExitr(   BaseExceptionjoinr3   strr   r;   	traceback
format_excsplitr   )	r   rt   argvrx   resolved_prefixru   outputer)   r   r   r   dispatch_command  s4    


$
z'CommandHandlerRegistry.dispatch_commandc             C   s   |  |dk	S )zTest if a command prefix or its alias is has a registered handler.

    Args:
      prefix: A prefix or its alias, as a str.

    Returns:
      True iff a handler is registered for prefix.
    N)rs   )r   rt   r   r   r   is_registered  s    	z$CommandHandlerRegistry.is_registeredc             C   sx   |sft g }| jr|| j t| j}x8|D ]0}| |}|d |d |t | q.W |S t | |S dS )a  Compile help information into a RichTextLines object.

    Args:
      cmd_prefix: Optional command prefix. As the prefix itself or one of its
        aliases.

    Returns:
      A RichTextLines object containing the help information. If cmd_prefix
      is None, the return value will be the full command-line help. Otherwise,
      it will be the help information for the specified command.
    r   N)r(   rj   r;   rS   rf   _get_help_for_command_prefixr   )r   
cmd_prefixrv   Zsorted_prefixesr)   r   r   r   get_help  s    




zCommandHandlerRegistry.get_helpc             C   s
   || _ dS )zSet an introductory message to help output.

    Args:
      help_intro: (RichTextLines) Rich text lines appended to the
        beginning of the output of the command "help", as introductory
        information.
    N)rj   )r   Z
help_intror   r   r   set_help_intro  s    z%CommandHandlerRegistry.set_help_introc             C   s8   |}|s|   S t|dkr*|  |d S tdgS dS )at  Command handler for "help".

    "help" is a common command that merits built-in support from this class.

    Args:
      args: Command line arguments to "help" (not including "help" itself).
      screen_info: (dict) Information regarding the screen, e.g., the screen
        width in characters: {"cols": 80}

    Returns:
      (RichTextLines) Screen text output.
    r?   r   z-ERROR: help takes only 0 or 1 input argument.N)r   r   r(   )r   argsrx   _r   r   r   rm     s    z$CommandHandlerRegistry._help_handlerc             C   s   ~~t ddS )NT)r.   )r/   )r   r   rx   r   r   r   rp     s    z'CommandHandlerRegistry._version_handlerc             C   s*   || j kr|S || jkr"| j| S dS dS )zResolve command prefix from the prefix itself or its alias.

    Args:
      token: a str to be resolved.

    Returns:
      If resolvable, the resolved command prefix.
      If not resolvable, None.
    N)rf   rg   )r   tokenr   r   r   rs     s
    



z&CommandHandlerRegistry._resolve_prefixc             C   s   g }|  |}|s$|d|  |S || || jkrV|td d| j|   |d | j| d}x|D ]}|t|  qvW |S )a>  Compile the help information for a given command prefix.

    Args:
      cmd_prefix: Command prefix, as the prefix itself or one of its
        aliases.

    Returns:
      A list of str as the help information fo cmd_prefix. If the cmd_prefix
        does not exist, the returned list of str will indicate that.
    zInvalid command prefix: "%s"z	Aliases: z, r   rD   )rs   r   rh   HELP_INDENTr|   ri   r   )r   r   r)   r   
help_linesr@   r   r   r   r   .  s    




z3CommandHandlerRegistry._get_help_for_command_prefix)N)N)N)N)N)r   r   r   r%   rl   rn   ro   rq   r
   rk   r   r   r   r   rm   rp   rs   r   r   r   r   r   r`     s   "
>
=



r`   c               @   sH   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dd Z
dS )TabCompletionRegistryz&Registry for tab completion responses.c             C   s
   i | _ d S )N)
_comp_dict)r   r   r   r   r
   Q  s    zTabCompletionRegistry.__init__c             C   sX   t |tstdt| t |ts4tdt| t|}x|D ]}|| j|< qBW dS )aO  Register a tab-completion context.

    Register that, for each word in context_words, the potential tab-completions
    are the words in comp_items.

    A context word is a pre-existing, completed word in the command line that
    determines how tab-completion works for another, incomplete word in the same
    command line.
    Completion items consist of potential candidates for the incomplete word.

    To give a general example, a context word can be "drink", and the completion
    items can be ["coffee", "tea", "water"]

    Note: A context word can be empty, in which case the context is for the
     top-level commands.

    Args:
      context_words: A list of context words belonging to the context being
        registered. It is a list of str, instead of a single string, to support
        synonym words triggering the same tab-completion context, e.g.,
        both "drink" and the short-hand "dr" can trigger the same context.
      comp_items: A list of completion items, as a list of str.

    Raises:
      TypeError: if the input arguments are not all of the correct types.
    z5Incorrect type in context_list: Expected list, got %sz3Incorrect type in comp_items: Expected list, got %sN)r   r0   r   r3   rS   r   )r   context_words
comp_itemsZsorted_comp_itemscontext_wordr   r   r   register_tab_comp_contextW  s    


z/TabCompletionRegistry.register_tab_comp_contextc             C   s>   x"|D ]}|| j krtd| qW x|D ]}| j |= q*W dS )zDeregister a list of context words.

    Args:
      context_words: A list of context words to deregister, as a list of str.

    Raises:
      KeyError: if there are word(s) in context_words that do not correspond
        to any registered contexts.
    z0Cannot deregister unregistered context word "%s"N)r   KeyError)r   r   r   r   r   r   deregister_context  s    


z(TabCompletionRegistry.deregister_contextc             C   s>   || j krtd| | j | | t| j | | j |< dS )ab  Add a list of completion items to a completion context.

    Args:
      context_word: A single completion word as a string. The extension will
        also apply to all other context words of the same context.
      new_comp_items: (list of str) New completion items to add.

    Raises:
      KeyError: if the context word has not been registered.
    z)Context word "%s" has not been registeredN)r   r   r;   rS   )r   r   Znew_comp_itemsr   r   r   extend_comp_items  s
    
z'TabCompletionRegistry.extend_comp_itemsc             C   s8   || j krtd| x|D ]}| j | | qW dS )aR  Remove a list of completion items from a completion context.

    Args:
      context_word: A single completion word as a string. The removal will
        also apply to all other context words of the same context.
      comp_items: Completion items to remove.

    Raises:
      KeyError: if the context word has not been registered.
    z)Context word "%s" has not been registeredN)r   r   remove)r   r   r   itemr   r   r   remove_comp_items  s
    

z'TabCompletionRegistry.remove_comp_itemsc                s<   || j krdS | j | }t fdd|D }|| |fS )a  Get the tab completions given a context word and a prefix.

    Args:
      context_word: The context word.
      prefix: The prefix of the incomplete word.

    Returns:
      (1) None if no registered context matches the context_word.
          A list of str for the matching completion items. Can be an empty list
          of a matching context exists, but no completion item matches the
          prefix.
      (2) Common prefix of all the words in the first return value. If the
          first return value is None, this return value will be None, too. If
          the first return value is not None, i.e., a list, this return value
          will be a str, which can be an empty str if there is no common
          prefix among the items of the list.
    )NNc                s   g | ]}|  r|qS r   )
startswith).0r   )rt   r   r   
<listcomp>  s    z9TabCompletionRegistry.get_completions.<locals>.<listcomp>)r   rS   _common_prefix)r   r   rt   r   r   )rt   r   get_completions  s    

z%TabCompletionRegistry.get_completionsc             C   sJ   |sdS t |}t|}x,t|D ] \}}||| kr"|d| S q"W |S )zGiven a list of str, returns the longest common prefix.

    Args:
      m: (list of str) A list of strings.

    Returns:
      (str) The longest common prefix.
    r   N)minmaxr'   )r   ms1s2r*   cr   r   r   r     s    	z$TabCompletionRegistry._common_prefixN)r   r   r   r%   r
   r   r   r   r   r   r   r   r   r   r   r   N  s   +r   c               @   sR   e Zd ZdZdZdddZdd Zd	d
 Zedd Z	dd Z
dd Zdd ZdS )CommandHistoryz*Keeps command history and supports lookup.z.tfdbg_historyd   Nc             C   s&   g | _ || _|p|  | _|   dS )zCommandHistory constructor.

    Args:
      limit: Maximum number of the most recent commands that this instance
        keeps track of, as an int.
      history_file_path: (str) Manually specified path to history file. Used in
        testing.
    N)	_commands_limit_get_default_history_file_path_history_file_path_load_history_from_file)r   limitZhistory_file_pathr   r   r   r
     s    
zCommandHistory.__init__c          	   C   s   t j| jryt| jd}| }W d Q R X dd |D | _t| j| jkr| j| j d  | _t| jd$}x| jD ]}|	|d  qzW W d Q R X W n t
k
r   td Y nX d S )Nrtc             S   s   g | ]}|  r|  qS r   )strip)r   commandr   r   r   r     s    z:CommandHistory._load_history_from_file.<locals>.<listcomp>wtrD   z%WARNING: writing history file failed.)ospathisfiler   open	readlinesr   r   r   rE   IOErrorprint)r   history_filecommandsr   r   r   r   r     s     z&CommandHistory._load_history_from_filec          	   C   sD   y*t | jd}||d  W d Q R X W n tk
r>   Y nX d S )NZatrD   )r   r   rE   r   )r   r   r   r   r   r   _add_command_to_history_file  s
    z+CommandHistory._add_command_to_history_filec             C   s   t jt jd| jS )N~)r   r   r|   
expanduser_HISTORY_FILE_NAME)clsr   r   r   r     s    z-CommandHistory._get_default_history_file_pathc             C   sj   | j r|| j d krdS t|tjs,td| j | t| j | jkr\| j | j d | _ | | dS )zAdd a command to the command history.

    Args:
      command: The history command, as a str.

    Raises:
      TypeError: if command is not a str.
    Nz1Attempt to enter non-str entry to command history)	r   r   r   r   r   r   r   r   r   )r   r   r   r   r   add_command  s    
zCommandHistory.add_commandc             C   s   | j | d S )a  Look up the n most recent commands.

    Args:
      n: Number of most recent commands to look up.

    Returns:
      A list of n most recent commands, or all available most recent commands,
      if n exceeds size of the command history, in chronological order.
    N)r   )r   nr   r   r   most_recent_n5  s    zCommandHistory.most_recent_nc                s"    fdd| j D }|| d S )a}  Look up the n most recent commands that starts with prefix.

    Args:
      prefix: The prefix to lookup.
      n: Number of most recent commands to look up.

    Returns:
      A list of n most recent commands that have the specified prefix, or all
      available most recent commands that have the prefix, if n exceeds the
      number of history commands with the prefix.
    c                s   g | ]}|  r|qS r   )r   )r   cmd)rt   r   r   r   O  s    z0CommandHistory.lookup_prefix.<locals>.<listcomp>N)r   )r   rt   r   r   r   )rt   r   lookup_prefixB  s    zCommandHistory.lookup_prefix)r   N)r   r   r   r%   r   r
   r   r   classmethodr   r   r   r   r   r   r   r   r     s   
r   c               @   sV   e Zd ZdZdddZedd Zedd Zed	d
 Zdd Z	dd Z
dd ZdS )MenuItemz)A class for an item in a text-based menu.Tc             C   s   || _ || _|| _dS )aT  Menu constructor.

    TODO(cais): Nested menu is currently not supported. Support it.

    Args:
      caption: (str) caption of the menu item.
      content: Content of the menu item. For a menu item that triggers
        a command, for example, content is the command string.
      enabled: (bool) whether this menu item is enabled.
    N)_caption_content_enabled)r   captioncontentZenabledr   r   r   r
   Y  s    zMenuItem.__init__c             C   s   | j S )N)r   )r   r   r   r   r   i  s    zMenuItem.captionc             C   s   | j S )N)Z
_node_type)r   r   r   r   r3   m  s    zMenuItem.typec             C   s   | j S )N)r   )r   r   r   r   r   q  s    zMenuItem.contentc             C   s   | j S )N)r   )r   r   r   r   
is_enabledu  s    zMenuItem.is_enabledc             C   s
   d| _ d S )NF)r   )r   r   r   r   disablex  s    zMenuItem.disablec             C   s
   d| _ d S )NT)r   )r   r   r   r   enable{  s    zMenuItem.enableN)T)r   r   r   r%   r
   r   r   r3   r   r   r   r   r   r   r   r   r   V  s   
r   c               @   sL   e Zd ZdZdddZdd Zdd Zd	d
 Zdd Zdd Z	dddZ
dS )MenuzA class for text-based menu.Nc             C   s   || _ g | _dS )zNMenu constructor.

    Args:
      name: (str or None) name of this menu.
    N)_name_items)r   namer   r   r   r
     s    zMenu.__init__c             C   s   | j | dS )z[Append an item to the Menu.

    Args:
      item: (MenuItem) the item to be appended.
    N)r   r   )r   r   r   r   r   r     s    zMenu.appendc             C   s   | j || d S )N)r   insert)r   indexr   r   r   r   r     s    zMenu.insertc             C   s
   t | jS )N)r   r   )r   r   r   r   	num_items  s    zMenu.num_itemsc             C   s   dd | j D S )Nc             S   s   g | ]
}|j qS r   )r   )r   r   r   r   r   r     s    z!Menu.captions.<locals>.<listcomp>)r   )r   r   r   r   captions  s    zMenu.captionsc             C   s,   |   }||krtd| | j|| S )a   Get a MenuItem from the caption.

    Args:
      caption: (str) The caption to look up.

    Returns:
      (MenuItem) The first-match menu item with the caption, if any.

    Raises:
      LookupError: If a menu item with the caption does not exist.
    z+There is no menu item with the caption "%s")r   LookupErrorr   r   )r   r   r   r   r   r   caption_to_item  s
    zMenu.caption_to_item | c       
      C   s   |dk	rt |ts|g}|dk	r0t |ts0|g}|dk	r<|nd}g }x|| jD ]r}||j7 }t|t|j }| r|g}	|r|	| ||t||	f n|r||t||f ||7 }qLW t|d|idS )a?  Format the menu as a single-line RichTextLines object.

    Args:
      prefix: (str) String added to the beginning of the line.
      divider: (str) The dividing string between the menu items.
      enabled_item_attrs: (list or str) Attributes applied to each enabled
        menu item, e.g., ["bold", "underline"].
      disabled_item_attrs: (list or str) Attributes applied to each
        disabled menu item, e.g., ["red"].

    Returns:
      (RichTextLines) A single-line output representing the menu, with
        font_attr_segs marking the individual menu items.
    Nr   r   )r   )	r   r0   r   r   r   r   r;   r   r(   )
r   rt   dividerZenabled_item_attrsZdisabled_item_attrsZ	menu_lineZ	attr_segsr   Zitem_name_beginZfinal_attrsr   r   r   format_as_single_line  s*    



zMenu.format_as_single_line)N)Nr   NN)r   r   r   r%   r
   r   r   r   r   r   r   r   r   r   r   r     s   

   r   )N)F)$r%   
__future__r   r   r   rL   r   rN   rP   r~   numpyr-   r   Ztensorflow.python.clientr   Ztensorflow.python.platformr   r   ZEXPLICIT_USER_EXITrT   ZINIT_SCROLL_POS_KEYZMAIN_MENU_KEYr	   r   objectr   r+   r/   r(   rW   r_   r`   r   r   r   r   r   r   r   r   <module>   sB   =

 d5`  > j)