How to use indent method in stryker-parent

Best JavaScript code snippet using stryker-parent

token_renderer.py

Source:token_renderer.py Github

copy

Full Screen

1# -*- coding: utf-8 -*- #2# Copyright 2017 Google Inc. All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Cloud SDK markdown document token renderer.16This is different from the other renderers:17(1) The output is a list of (token, text) tuples returned by18 TokenRenderer.Finish().19(2) A token is an empty object that conveys font style and embellishment by20 convention using the token name. Callers set up a style sheet indexed by21 tokens to control how the embellishments are rendered, e.g. color.22(3) The rendering is constrained by width and height.23Tokens generated by this module:24 Token.Markdown.Bold: bold text25 Token.Markdown.BoldItalic: bold+italic text26 Token.Markdown.Code: code text for command line examples27 Token.Markdown.Definition: definition list item (flag or subcommand or choice)28 Token.Markdown.Italic: italic text29 Token.Markdown.Normal: normal text30 Token.Markdown.Section: section header31 Token.Markdown.Truncated: the last token => indicates truncation32 Token.Markdown.Value: definition list item value (flag value)33The Token objects self-define on first usage. Don't champion this pattern in the34Cloud SDK.35Usage:36 from six.moves import StringIO37 from googlecloudsdk.core.document_renderers import token_renderer38 from googlecloudsdk.core.document_renderers import render_document39 markdown = <markdown document string>40 tokens = render_document.MarkdownRenderer(41 token_renderer.TokenRenderer(width=W, height=H),42 StringIO(markdown)).Run()43"""44from __future__ import absolute_import45from __future__ import division46from __future__ import unicode_literals47import re48from googlecloudsdk.core.console import console_attr49from googlecloudsdk.core.document_renderers import renderer50from prompt_toolkit.token import Token51from six.moves import range # pylint: disable=redefined-builtin52class TokenRenderer(renderer.Renderer):53 """Renders markdown to a list of lines where each line is a list of Tokens.54 Attributes:55 _attr: console_attr.ConsoleAttr object.56 _bullet: List of bullet characters indexed by list level modulo #bullets.57 _blank: True if the output already contains a blank line. Used to avoid58 sequences of 2 or more blank lines in the output.59 _compact: Compact representation if True. Saves rendering real estate.60 _csi: The control sequence indicator character. Token does not61 have control sequences. This renderer uses them internally to manage62 font styles and attributes (bold, code, italic).63 _current_token_type: current default Token.Markdown.* type64 _fill: The number of characters in the current output line.65 _height: The height of the output window, 0 to disable height checks.66 _ignore_paragraph: Ignore paragraph markdown until the next non-space67 _AddToken.68 _ignore_width: True if the next output word should ignore _width.69 _indent: List of left indentations in characters indexed by _level.70 _level: The section or list level counting from 0.71 _table: True if currently rendering a table.72 _tokens: The list of output tokens73 _truncated: The number of output lines exceeded the output height.74 _rows: current rows in table75 """76 # Internal inline embellishments are 2 character sequences77 # <CSI><EMBELLISHMENT>. The embellishment must be an alpha character78 # to make the display width helpers work properly.79 CSI = '\0' # Won't clash with markdown text input.80 EMBELLISHMENTS = {81 'B': Token.Markdown.Bold,82 'C': Token.Markdown.Code,83 'I': Token.Markdown.Italic,84 'N': Token.Markdown.Normal,85 'Z': Token.Markdown.BoldItalic,86 }87 INDENT = 488 SPLIT_INDENT = 289 TOKEN_TYPE_INDEX = 090 TOKEN_TEXT_INDEX = 191 class Indent(object):92 """Hanging indent stack."""93 def __init__(self, compact=True):94 self.indent = 0 if compact else TokenRenderer.INDENT95 self.hanging_indent = self.indent96 def __init__(self, height=0, encoding='utf8', compact=True, *args, **kwargs):97 super(TokenRenderer, self).__init__(*args, **kwargs)98 self._attr = console_attr.GetConsoleAttr(encoding=encoding)99 self._csi = self.CSI100 self._attr._csi = self._csi # pylint: disable=protected-access101 self._blank = True102 self._bullet = self._attr.GetBullets()103 self._compact = compact104 self._fill = 0105 self._current_token_type = Token.Markdown.Normal106 self._height = height107 self._ignore_paragraph = False108 self._ignore_width = False109 self._indent = [self.Indent(compact)]110 self._level = 0111 self._lines = []112 self._table = False113 self._tokens = []114 self._truncated = False115 self._rows = []116 def _Truncate(self, tokens, overflow):117 """Injects a truncation indicator token and rejects subsequent tokens.118 Args:119 tokens: The last line of tokens at the output height. The part of the120 line within the output width will be visible, modulo the trailing121 truncation marker token added here.122 overflow: If not None then this is a (word, available) tuple from Fill()123 where word caused the line width overflow and available is the number of124 characters available in the current line before ' '+word would be125 appended.126 Returns:127 A possibly altered list of tokens that form the last output line.128 """129 self._truncated = True130 marker_string = '...'131 marker_width = len(marker_string)132 marker_token = (Token.Markdown.Truncated, marker_string)133 if tokens and overflow:134 word, available = overflow # pylint: disable=unpacking-non-sequence135 if marker_width == available:136 # Exactly enough space for the marker.137 pass138 elif (marker_width + 1) <= available:139 # The marker can replace the trailing characters in the overflow word.140 word = ' ' + self._UnFormat(word)[:available-marker_width-1]141 tokens.append((self._current_token_type, word))142 else:143 # Truncate the token list so the marker token can fit.144 truncated_tokens = []145 available = self._width146 for token in tokens:147 word = token[self.TOKEN_TEXT_INDEX]148 width = self._attr.DisplayWidth(word)149 available -= width150 if available <= marker_width:151 trim = marker_width - available152 if trim:153 word = word[:-trim]154 truncated_tokens.append((token[self.TOKEN_TYPE_INDEX], word))155 break156 truncated_tokens.append(token)157 tokens = truncated_tokens158 tokens.append(marker_token)159 return tokens160 def _NewLine(self, overflow=None):161 """Adds the current token list to the line list.162 Args:163 overflow: If not None then this is a (word, available) tuple from Fill()164 where word caused the line width overflow and available is the number of165 characters available in the current line before ' '+word would be166 appended.167 """168 tokens = self._tokens169 self._tokens = []170 if self._truncated or not tokens and self._compact:171 return172 if self._lines:173 # Delete trailing space.174 while (self._lines[-1] and175 self._lines[-1][-1][self.TOKEN_TEXT_INDEX].isspace()):176 self._lines[-1] = self._lines[-1][:-1]177 if self._height and (len(self._lines) + int(bool(tokens))) >= self._height:178 tokens = self._Truncate(tokens, overflow)179 self._lines.append(tokens)180 def _MergeOrAddToken(self, text, token_type):181 """Merges text if the previous token_type matches or appends a new token."""182 if not text:183 return184 if (not self._tokens or185 self._tokens[-1][self.TOKEN_TYPE_INDEX] != token_type):186 self._tokens.append((token_type, text))187 elif self._tokens[-1][self.TOKEN_TYPE_INDEX] == Token.Markdown.Section:188 # A section header with no content.189 prv_text = self._tokens[-1][self.TOKEN_TEXT_INDEX]190 prv_indent = re.match('( *)', prv_text).group(1)191 new_indent = re.match('( *)', text).group(1)192 if prv_indent == new_indent:193 # Same indentation => discard the previous empty section.194 self._tokens[-1] = (token_type, text)195 else:196 # Insert newline to separate previous header from the new one.197 self._NewLine()198 self._tokens.append((token_type, text))199 else:200 self._tokens[-1] = (token_type,201 self._tokens[-1][self.TOKEN_TEXT_INDEX] + text)202 def _AddToken(self, text, token_type=None):203 """Appends a (token_type, text) tuple to the current line."""204 if text and not text.isspace():205 self._ignore_paragraph = False206 if not token_type:207 token_type = self._current_token_type208 if self._csi not in text:209 self._MergeOrAddToken(text, token_type)210 else:211 i = 0212 while True:213 j = text.find(self._csi, i)214 if j < 0:215 self._MergeOrAddToken(text[i:], token_type)216 break217 self._MergeOrAddToken(text[i:j], token_type)218 token_type = self.EMBELLISHMENTS[text[j + 1]]219 self._current_token_type = token_type220 i = j + 2221 def _UnFormat(self, text):222 """Returns text with all inline formatting stripped."""223 if self._csi not in text:224 return text225 stripped = []226 i = 0227 while i < len(text):228 j = text.find(self._csi, i)229 if j < 0:230 stripped.append(text[i:])231 break232 stripped.append(text[i:j])233 i = j + 2234 return ''.join(stripped)235 def _AddDefinition(self, text):236 """Appends a definition list definition item to the current line."""237 text = self._UnFormat(text)238 parts = text.split('=', 1)239 self._AddToken(parts[0], Token.Markdown.Definition)240 if len(parts) > 1:241 self._AddToken('=', Token.Markdown.Normal)242 self._AddToken(parts[1], Token.Markdown.Value)243 self._NewLine()244 def _Flush(self):245 """Flushes the current collection of Fill() lines."""246 self._ignore_width = False247 if self._fill:248 self._NewLine()249 self._blank = False250 self._fill = 0251 def _SetIndent(self, level, indent=None, hanging_indent=None):252 """Sets the markdown list level and indentations.253 Args:254 level: int, The desired markdown list level.255 indent: int, The new indentation.256 hanging_indent: int, The hanging indentation. This is subtracted from the257 prevailing indent to decrease the indentation of the next input line258 for this effect:259 HANGING INDENT ON THE NEXT LINE260 PREVAILING INDENT261 ON SUBSEQUENT LINES262 """263 if self._level < level:264 # The level can increase by 1 or more. Loop through each so that265 # intervening levels are handled the same.266 while self._level < level:267 prev_level = self._level268 self._level += 1269 if self._level >= len(self._indent):270 self._indent.append(self.Indent())271 self._indent[self._level].indent = (272 self._indent[prev_level].indent + indent) # pytype: disable=wrong-arg-types273 if (self._level > 1 and274 self._indent[prev_level].hanging_indent ==275 self._indent[prev_level].indent):276 # Bump the indent by 1 char for nested indentation. Top level looks277 # fine (aesthetically) without it.278 self._indent[self._level].indent += 1279 self._indent[self._level].hanging_indent = (280 self._indent[self._level].indent)281 if hanging_indent is not None:282 # Adjust the hanging indent if specified.283 self._indent[self._level].hanging_indent -= hanging_indent284 else:285 # Decreasing level just sets the indent stack level, no state to clean up.286 self._level = level287 if hanging_indent is not None:288 # Change hanging indent on existing level.289 self._indent[self._level].indent = (290 self._indent[self._level].hanging_indent + hanging_indent)291 def Example(self, line):292 """Displays line as an indented example.293 Args:294 line: The example line text.295 """296 self._fill = self._indent[self._level].indent + self.INDENT297 self._AddToken(' ' * self._fill + line, Token.Markdown.Normal)298 self._NewLine()299 self._blank = False300 self._fill = 0301 def Fill(self, line):302 """Adds a line to the output, splitting to stay within the output width.303 This is close to textwrap.wrap() except that control sequence characters304 don't count in the width computation.305 Args:306 line: The text line.307 """308 self._blank = True309 for word in line.split():310 if not self._fill:311 if self._level or not self._compact:312 self._fill = self._indent[self._level].indent - 1313 else:314 self._level = 0315 self._AddToken(' ' * self._fill)316 width = self._attr.DisplayWidth(word)317 available = self._width - self._fill318 if (width + 1) >= available and not self._ignore_width:319 self._NewLine(overflow=(word, available))320 self._fill = self._indent[self._level].indent321 self._AddToken(' ' * self._fill)322 else:323 self._ignore_width = False324 if self._fill:325 self._fill += 1326 self._AddToken(' ')327 self._fill += width328 self._AddToken(word)329 def Finish(self):330 """Finishes all output document rendering."""331 self._Flush()332 self.Font()333 return self._lines334 def Font(self, attr=None):335 """Returns the font embellishment control sequence for attr.336 Args:337 attr: None to reset to the default font, otherwise one of renderer.BOLD,338 renderer.ITALIC, or renderer.CODE.339 Returns:340 The font embellishment control sequence.341 """342 if attr is None:343 self._font = 0344 else:345 mask = 1 << attr346 self._font ^= mask347 font = self._font & ((1 << renderer.BOLD) |348 (1 << renderer.CODE) |349 (1 << renderer.ITALIC))350 if font & (1 << renderer.CODE):351 embellishment = 'C'352 elif font == ((1 << renderer.BOLD) | (1 << renderer.ITALIC)):353 embellishment = 'Z'354 elif font == (1 << renderer.BOLD):355 embellishment = 'B'356 elif font == (1 << renderer.ITALIC):357 embellishment = 'I'358 else:359 embellishment = 'N'360 return self._csi + embellishment361 def Heading(self, level, heading):362 """Renders a heading.363 Args:364 level: The heading level counting from 1.365 heading: The heading text.366 """367 if level == 1 and heading.endswith('(1)'):368 # Ignore man page TH.369 return370 self._Flush()371 self.Line()372 self.Font()373 if level > 2:374 indent = ' ' * (level - 2)375 self._AddToken(indent)376 if self._compact:377 self._ignore_paragraph = True378 self._fill += len(indent)379 self._AddToken(heading, Token.Markdown.Section)380 if self._compact:381 self._ignore_paragraph = True382 self._fill += self._attr.DisplayWidth(heading)383 else:384 self._NewLine()385 self._blank = True386 self._level = 0387 self._rows = []388 def Line(self):389 """Renders a paragraph separating line."""390 if self._ignore_paragraph:391 return392 self._Flush()393 if not self._blank:394 self._blank = True395 self._NewLine()396 def List(self, level, definition=None, end=False):397 """Renders a bullet or definition list item.398 Args:399 level: The list nesting level, 0 if not currently in a list.400 definition: Bullet list if None, definition list item otherwise.401 end: End of list if True.402 """403 self._Flush()404 if not level:405 self._level = level406 elif end:407 # End of list.408 self._SetIndent(level)409 elif definition is not None:410 # Definition list item.411 if definition:412 self._SetIndent(level, indent=4, hanging_indent=3)413 self._AddToken(' ' * self._indent[level].hanging_indent)414 self._AddDefinition(definition)415 else:416 self._SetIndent(level, indent=1, hanging_indent=0)417 self.Line()418 else:419 # Bullet list item.420 indent = 2 if level > 1 else 4421 self._SetIndent(level, indent=indent, hanging_indent=2)422 self._AddToken(' ' * self._indent[level].hanging_indent +423 self._bullet[(level - 1) % len(self._bullet)])424 self._fill = self._indent[level].indent + 1425 self._ignore_width = True426 def _SkipSpace(self, line, index):427 """Skip space characters starting at line[index].428 Args:429 line: The string.430 index: The starting index in string.431 Returns:432 The index in line after spaces or len(line) at end of string.433 """434 while index < len(line):435 c = line[index]436 if c != ' ':437 break438 index += 1439 return index440 def _SkipControlSequence(self, line, index):441 """Skip the control sequence at line[index].442 Args:443 line: The string.444 index: The starting index in string.445 Returns:446 The index in line after the control sequence or len(line) at end of447 string.448 """449 n = self._attr.GetControlSequenceLen(line[index:])450 if not n:451 n = 1452 return index + n453 def _SkipNest(self, line, index, open_chars='[(', close_chars=')]'):454 """Skip a [...] nested bracket group starting at line[index].455 Args:456 line: The string.457 index: The starting index in string.458 open_chars: The open nesting characters.459 close_chars: The close nesting characters.460 Returns:461 The index in line after the nesting group or len(line) at end of string.462 """463 nest = 0464 while index < len(line):465 c = line[index]466 index += 1467 if c in open_chars:468 nest += 1469 elif c in close_chars:470 nest -= 1471 if nest <= 0:472 break473 elif c == self._csi:474 index = self._SkipControlSequence(line, index)475 return index476 def _SplitWideSynopsisGroup(self, group, indent, running_width):477 """Splits a wide SYNOPSIS section group string._out.478 Args:479 group: The wide group string to split.480 indent: The prevailing left indent.481 running_width: The width of the line in progress.482 Returns:483 The running_width after the group has been split and written.484 """485 prev_delimiter = ' '486 while group:487 # Check split delimiters in order for visual emphasis.488 for delimiter in (' | ', ' : ', ' ', ','):489 part, _, remainder = group.partition(delimiter)490 w = self._attr.DisplayWidth(part)491 if ((running_width + len(prev_delimiter) + w) >= self._width or492 prev_delimiter != ',' and delimiter == ','):493 if delimiter != ',' and (indent +494 self.SPLIT_INDENT +495 len(prev_delimiter) +496 w) >= self._width:497 # The next delimiter may produce a smaller first part.498 continue499 if prev_delimiter == ',':500 self._AddToken(prev_delimiter)501 prev_delimiter = ' '502 if running_width != indent:503 running_width = indent + self.SPLIT_INDENT504 self._NewLine()505 self._AddToken(' ' * running_width)506 self._AddToken(prev_delimiter + part)507 running_width += len(prev_delimiter) + w508 prev_delimiter = delimiter509 group = remainder510 break511 return running_width512 def Synopsis(self, line):513 """Renders NAME and SYNOPSIS lines as a hanging indent.514 Collapses adjacent spaces to one space, deletes trailing space, and doesn't515 split top-level nested [...] or (...) groups. Also detects and does not516 count terminal control sequences.517 Args:518 line: The NAME or SYNOPSIS text.519 """520 # Split the line into token, token | token, and [...] groups.521 groups = []522 i = self._SkipSpace(line, 0)523 beg = i524 while i < len(line):525 c = line[i]526 if c == ' ':527 end = i528 i = self._SkipSpace(line, i)529 if i <= (len(line) - 1) and line[i] == '|' and line[i + 1] == ' ':530 i = self._SkipSpace(line, i + 1)531 else:532 groups.append(line[beg:end])533 beg = i534 elif c in '[(':535 i = self._SkipNest(line, i)536 elif c == self._csi:537 i = self._SkipControlSequence(line, i)538 else:539 i += 1540 if beg < len(line):541 groups.append(line[beg:])542 # Output the groups.543 indent = self._indent[0].indent - 1544 running_width = indent545 self._AddToken(' ' * running_width)546 indent += self.INDENT547 for group in groups:548 w = self._attr.DisplayWidth(group) + 1549 if (running_width + w) >= self._width:550 running_width = indent551 self._NewLine()552 self._AddToken(' ' * running_width)553 if (running_width + w) >= self._width:554 # The group is wider than the available width and must be split.555 running_width = self._SplitWideSynopsisGroup(556 group, indent, running_width)557 continue558 self._AddToken(' ' + group)559 running_width += w560 self._NewLine()561 self._NewLine()562 def Table(self, line):563 """Renders a table line.564 Nested tables are not supported. The first call on a new table is:565 Table(attributes)566 the intermediate calls add the heading and data lines and the last call is:567 Table(None)568 Args:569 line: A CSV table data line.570 """571 if line is None:572 # TODO(b/31628974): Use resource_printer.TablePrinter().573 if self._rows:574 cols = len(self._rows[0])575 width = [0 for _ in range(cols)]576 for row in self._rows:577 for i in range(min(len(row), cols) - 1):578 w = len(row[i])579 if width[i] <= w:580 width[i] = w + 1581 for row in self._rows:582 self._AddToken(' ' * (self._indent[self._level].indent + 2))583 for i in range(min(len(row), cols) - 1):584 self._AddToken(row[i].ljust(width[i]))585 self._AddToken(row[-1])586 self._NewLine()587 self._rows = []588 self._table = False589 self._NewLine()590 elif not self._table:591 self._table = True592 self.Line()593 else:...

Full Screen

Full Screen

data.py

Source:data.py Github

copy

Full Screen

...38 return39 yield match.start(), token_class, text40 context.pos = match.end()41 return callback42 def reset_indent(token_class):43 """Reset the indentation levels."""44 def callback(lexer, match, context):45 text = match.group()46 context.indent_stack = []47 context.indent = -148 context.next_indent = 049 context.block_scalar_indent = None50 yield match.start(), token_class, text51 context.pos = match.end()52 return callback53 def save_indent(token_class, start=False):54 """Save a possible indentation level."""55 def callback(lexer, match, context):56 text = match.group()57 extra = ''58 if start:59 context.next_indent = len(text)60 if context.next_indent < context.indent:61 while context.next_indent < context.indent:62 context.indent = context.indent_stack.pop()63 if context.next_indent > context.indent:64 extra = text[context.indent:]65 text = text[:context.indent]66 else:67 context.next_indent += len(text)68 if text:69 yield match.start(), token_class, text70 if extra:71 yield match.start()+len(text), token_class.Error, extra72 context.pos = match.end()73 return callback74 def set_indent(token_class, implicit=False):75 """Set the previously saved indentation level."""76 def callback(lexer, match, context):77 text = match.group()78 if context.indent < context.next_indent:79 context.indent_stack.append(context.indent)80 context.indent = context.next_indent81 if not implicit:82 context.next_indent += len(text)83 yield match.start(), token_class, text84 context.pos = match.end()85 return callback86 def set_block_scalar_indent(token_class):87 """Set an explicit indentation level for a block scalar."""88 def callback(lexer, match, context):89 text = match.group()90 context.block_scalar_indent = None91 if not text:92 return93 increment = match.group(1)94 if increment:95 current_indent = max(context.indent, 0)96 increment = int(increment)97 context.block_scalar_indent = current_indent + increment98 if text:99 yield match.start(), token_class, text100 context.pos = match.end()101 return callback102 def parse_block_scalar_empty_line(indent_token_class, content_token_class):103 """Process an empty line in a block scalar."""104 def callback(lexer, match, context):105 text = match.group()106 if (context.block_scalar_indent is None or107 len(text) <= context.block_scalar_indent):108 if text:109 yield match.start(), indent_token_class, text110 else:111 indentation = text[:context.block_scalar_indent]112 content = text[context.block_scalar_indent:]113 yield match.start(), indent_token_class, indentation114 yield (match.start()+context.block_scalar_indent,115 content_token_class, content)116 context.pos = match.end()117 return callback118 def parse_block_scalar_indent(token_class):119 """Process indentation spaces in a block scalar."""120 def callback(lexer, match, context):121 text = match.group()122 if context.block_scalar_indent is None:123 if len(text) <= max(context.indent, 0):124 context.stack.pop()125 context.stack.pop()126 return127 context.block_scalar_indent = len(text)128 else:129 if len(text) < context.block_scalar_indent:130 context.stack.pop()131 context.stack.pop()132 return133 if text:134 yield match.start(), token_class, text135 context.pos = match.end()136 return callback137 def parse_plain_scalar_indent(token_class):138 """Process indentation spaces in a plain scalar."""139 def callback(lexer, match, context):140 text = match.group()141 if len(text) <= context.indent:142 context.stack.pop()143 context.stack.pop()144 return145 if text:146 yield match.start(), token_class, text147 context.pos = match.end()148 return callback149 tokens = {150 # the root rules151 'root': [152 # ignored whitespaces153 (r'[ ]+(?=#|$)', Text),154 # line breaks155 (r'\n+', Text),156 # a comment157 (r'#[^\n]*', Comment.Single),158 # the '%YAML' directive159 (r'^%YAML(?=[ ]|$)', reset_indent(Name.Tag), 'yaml-directive'),160 # the %TAG directive161 (r'^%TAG(?=[ ]|$)', reset_indent(Name.Tag), 'tag-directive'),162 # document start and document end indicators163 (r'^(?:---|\.\.\.)(?=[ ]|$)', reset_indent(Name.Namespace),164 'block-line'),165 # indentation spaces166 (r'[ ]*(?!\s|$)', save_indent(Text, start=True),167 ('block-line', 'indentation')),168 ],169 # trailing whitespaces after directives or a block scalar indicator170 'ignored-line': [171 # ignored whitespaces172 (r'[ ]+(?=#|$)', Text),173 # a comment174 (r'#[^\n]*', Comment.Single),175 # line break176 (r'\n', Text, '#pop:2'),177 ],178 # the %YAML directive179 'yaml-directive': [180 # the version number181 (r'([ ]+)([0-9]+\.[0-9]+)',182 bygroups(Text, Number), 'ignored-line'),183 ],184 # the %YAG directive185 'tag-directive': [186 # a tag handle and the corresponding prefix187 (r'([ ]+)(!|![\w-]*!)'188 r'([ ]+)(!|!?[\w;/?:@&=+$,.!~*\'()\[\]%-]+)',189 bygroups(Text, Keyword.Type, Text, Keyword.Type),190 'ignored-line'),191 ],192 # block scalar indicators and indentation spaces193 'indentation': [194 # trailing whitespaces are ignored195 (r'[ ]*$', something(Text), '#pop:2'),196 # whitespaces preceeding block collection indicators197 (r'[ ]+(?=[?:-](?:[ ]|$))', save_indent(Text)),198 # block collection indicators199 (r'[?:-](?=[ ]|$)', set_indent(Punctuation.Indicator)),200 # the beginning a block line201 (r'[ ]*', save_indent(Text), '#pop'),202 ],203 # an indented line in the block context204 'block-line': [205 # the line end206 (r'[ ]*(?=#|$)', something(Text), '#pop'),207 # whitespaces separating tokens208 (r'[ ]+', Text),209 # tags, anchors and aliases,210 include('descriptors'),211 # block collections and scalars212 include('block-nodes'),213 # flow collections and quoted scalars214 include('flow-nodes'),215 # a plain scalar216 (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`-]|[?:-]\S)',217 something(Name.Variable),218 'plain-scalar-in-block-context'),219 ],220 # tags, anchors, aliases221 'descriptors': [222 # a full-form tag223 (r'!<[\w#;/?:@&=+$,.!~*\'()\[\]%-]+>', Keyword.Type),224 # a tag in the form '!', '!suffix' or '!handle!suffix'225 (r'!(?:[\w-]+!)?'226 r'[\w#;/?:@&=+$,.!~*\'()\[\]%-]+', Keyword.Type),227 # an anchor228 (r'&[\w-]+', Name.Label),229 # an alias230 (r'\*[\w-]+', Name.Variable),231 ],232 # block collections and scalars233 'block-nodes': [234 # implicit key235 (r':(?=[ ]|$)', set_indent(Punctuation.Indicator, implicit=True)),236 # literal and folded scalars237 (r'[|>]', Punctuation.Indicator,238 ('block-scalar-content', 'block-scalar-header')),239 ],240 # flow collections and quoted scalars241 'flow-nodes': [242 # a flow sequence243 (r'\[', Punctuation.Indicator, 'flow-sequence'),244 # a flow mapping245 (r'\{', Punctuation.Indicator, 'flow-mapping'),246 # a single-quoted scalar247 (r'\'', String, 'single-quoted-scalar'),248 # a double-quoted scalar249 (r'\"', String, 'double-quoted-scalar'),250 ],251 # the content of a flow collection252 'flow-collection': [253 # whitespaces254 (r'[ ]+', Text),255 # line breaks256 (r'\n+', Text),257 # a comment258 (r'#[^\n]*', Comment.Single),259 # simple indicators260 (r'[?:,]', Punctuation.Indicator),261 # tags, anchors and aliases262 include('descriptors'),263 # nested collections and quoted scalars264 include('flow-nodes'),265 # a plain scalar266 (r'(?=[^\s?:,\[\]{}#&*!|>\'"%@`])',267 something(Name.Variable),268 'plain-scalar-in-flow-context'),269 ],270 # a flow sequence indicated by '[' and ']'271 'flow-sequence': [272 # include flow collection rules273 include('flow-collection'),274 # the closing indicator275 (r'\]', Punctuation.Indicator, '#pop'),276 ],277 # a flow mapping indicated by '{' and '}'278 'flow-mapping': [279 # include flow collection rules280 include('flow-collection'),281 # the closing indicator282 (r'\}', Punctuation.Indicator, '#pop'),283 ],284 # block scalar lines285 'block-scalar-content': [286 # line break287 (r'\n', Text),288 # empty line289 (r'^[ ]+$',290 parse_block_scalar_empty_line(Text, Name.Constant)),291 # indentation spaces (we may leave the state here)292 (r'^[ ]*', parse_block_scalar_indent(Text)),293 # line content294 (r'[\S\t ]+', Name.Constant),295 ],296 # the content of a literal or folded scalar297 'block-scalar-header': [298 # indentation indicator followed by chomping flag299 (r'([1-9])?[+-]?(?=[ ]|$)',300 set_block_scalar_indent(Punctuation.Indicator),301 'ignored-line'),302 # chomping flag followed by indentation indicator303 (r'[+-]?([1-9])?(?=[ ]|$)',304 set_block_scalar_indent(Punctuation.Indicator),305 'ignored-line'),306 ],307 # ignored and regular whitespaces in quoted scalars308 'quoted-scalar-whitespaces': [309 # leading and trailing whitespaces are ignored310 (r'^[ ]+', Text),311 (r'[ ]+$', Text),312 # line breaks are ignored313 (r'\n+', Text),314 # other whitespaces are a part of the value315 (r'[ ]+', Name.Variable),316 ],317 # single-quoted scalars318 'single-quoted-scalar': [319 # include whitespace and line break rules320 include('quoted-scalar-whitespaces'),321 # escaping of the quote character322 (r'\'\'', String.Escape),323 # regular non-whitespace characters324 (r'[^\s\']+', String),325 # the closing quote326 (r'\'', String, '#pop'),327 ],328 # double-quoted scalars329 'double-quoted-scalar': [330 # include whitespace and line break rules331 include('quoted-scalar-whitespaces'),332 # escaping of special characters333 (r'\\[0abt\tn\nvfre "\\N_LP]', String),334 # escape codes335 (r'\\(?:x[0-9A-Fa-f]{2}|u[0-9A-Fa-f]{4}|U[0-9A-Fa-f]{8})',336 String.Escape),337 # regular non-whitespace characters338 (r'[^\s"\\]+', String),339 # the closing quote340 (r'"', String, '#pop'),341 ],342 # the beginning of a new line while scanning a plain scalar343 'plain-scalar-in-block-context-new-line': [344 # empty lines345 (r'^[ ]+$', Text),346 # line breaks347 (r'\n+', Text),348 # document start and document end indicators349 (r'^(?=---|\.\.\.)', something(Name.Namespace), '#pop:3'),350 # indentation spaces (we may leave the block line state here)351 (r'^[ ]*', parse_plain_scalar_indent(Text), '#pop'),352 ],353 # a plain scalar in the block context354 'plain-scalar-in-block-context': [355 # the scalar ends with the ':' indicator356 (r'[ ]*(?=:[ ]|:$)', something(Text), '#pop'),357 # the scalar ends with whitespaces followed by a comment358 (r'[ ]+(?=#)', Text, '#pop'),359 # trailing whitespaces are ignored360 (r'[ ]+$', Text),361 # line breaks are ignored362 (r'\n+', Text, 'plain-scalar-in-block-context-new-line'),363 # other whitespaces are a part of the value364 (r'[ ]+', Literal.Scalar.Plain),365 # regular non-whitespace characters...

Full Screen

Full Screen

text_renderer.py

Source:text_renderer.py Github

copy

Full Screen

1# -*- coding: utf-8 -*- #2# Copyright 2015 Google Inc. All Rights Reserved.3#4# Licensed under the Apache License, Version 2.0 (the "License");5# you may not use this file except in compliance with the License.6# You may obtain a copy of the License at7#8# http://www.apache.org/licenses/LICENSE-2.09#10# Unless required by applicable law or agreed to in writing, software11# distributed under the License is distributed on an "AS IS" BASIS,12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.13# See the License for the specific language governing permissions and14# limitations under the License.15"""Cloud SDK markdown document text renderer."""16from __future__ import absolute_import17from __future__ import division18from __future__ import unicode_literals19from googlecloudsdk.core.console import console_attr20from googlecloudsdk.core.document_renderers import renderer21from six.moves import range # pylint: disable=redefined-builtin22class TextRenderer(renderer.Renderer):23 """Renders markdown to text.24 Attributes:25 _attr: console_attr.ConsoleAttr object.26 _bullet: List of bullet characters indexed by list level modulo #bullets.27 _blank: True if the output already contains a blank line. Used to avoid28 sequences of 2 or more blank lines in the output.29 _csi_char: The first control sequence indicator character or None if control30 sequences are not supported.31 _fill: The number of characters in the current output line.32 _ignore_width: True if the next output word should ignore _width.33 _indent: List of left indentations in characters indexed by _level.34 _level: The section or list level counting from 0.35 _table: True if currently rendering a table.36 """37 INDENT = 438 SPLIT_INDENT = 239 class Indent(object):40 """Hanging indent stack."""41 def __init__(self):42 self.indent = TextRenderer.INDENT43 self.hanging_indent = self.indent44 def __init__(self, *args, **kwargs):45 super(TextRenderer, self).__init__(*args, **kwargs)46 self._attr = console_attr.GetConsoleAttr()47 self._blank = True48 self._bullet = self._attr.GetBullets()49 self._csi_char = self._attr.GetControlSequenceIndicator()50 if self._csi_char:51 self._csi_char = self._csi_char[0]52 self._fill = 053 self._ignore_width = False54 self._indent = [self.Indent()]55 self._level = 056 self._table = False57 def _Flush(self):58 """Flushes the current collection of Fill() lines."""59 self._ignore_width = False60 if self._fill:61 self._out.write('\n')62 self._blank = False63 self._fill = 064 def _SetIndent(self, level, indent=None, hanging_indent=None):65 """Sets the markdown list level and indentations.66 Args:67 level: int, The desired markdown list level.68 indent: int, The new indentation.69 hanging_indent: int, The hanging indentation. This is subtracted from the70 prevailing indent to decrease the indentation of the next input line71 for this effect:72 HANGING INDENT ON THE NEXT LINE73 PREVAILING INDENT74 ON SUBSEQUENT LINES75 """76 if self._level < level:77 # The level can increase by 1 or more. Loop through each so that78 # intervening levels are handled the same.79 while self._level < level:80 prev_level = self._level81 self._level += 182 if self._level >= len(self._indent):83 self._indent.append(self.Indent())84 self._indent[self._level].indent = (85 self._indent[prev_level].indent + indent) # pytype: disable=wrong-arg-types86 if (self._level > 1 and87 self._indent[prev_level].hanging_indent ==88 self._indent[prev_level].indent):89 # Bump the indent by 1 char for nested indentation. Top level looks90 # fine (aesthetically) without it.91 self._indent[self._level].indent += 192 self._indent[self._level].hanging_indent = (93 self._indent[self._level].indent)94 if hanging_indent is not None:95 # Adjust the hanging indent if specified.96 self._indent[self._level].hanging_indent -= hanging_indent97 else:98 # Decreasing level just sets the indent stack level, no state to clean up.99 self._level = level100 if hanging_indent is not None:101 # Change hanging indent on existing level.102 self._indent[self._level].indent = (103 self._indent[self._level].hanging_indent + hanging_indent)104 def Example(self, line):105 """Displays line as an indented example.106 Args:107 line: The example line text.108 """109 self._fill = self._indent[self._level].indent + self.INDENT110 self._out.write(' ' * self._fill + line + '\n')111 self._blank = False112 self._fill = 0113 def Fill(self, line):114 """Adds a line to the output, splitting to stay within the output width.115 This is close to textwrap.wrap() except that control sequence characters116 don't count in the width computation.117 Args:118 line: The text line.119 """120 self._blank = True121 for word in line.split():122 if not self._fill:123 self._fill = self._indent[self._level].indent - 1124 self._out.write(' ' * self._fill)125 width = self._attr.DisplayWidth(word)126 if self._fill + width + 1 >= self._width and not self._ignore_width:127 self._out.write('\n')128 self._fill = self._indent[self._level].indent129 self._out.write(' ' * self._fill)130 else:131 self._ignore_width = False132 if self._fill:133 self._fill += 1134 self._out.write(' ')135 self._fill += width136 self._out.write(word)137 def Finish(self):138 """Finishes all output document rendering."""139 self._Flush()140 self.Font(out=self._out)141 def Font(self, attr=None, out=None):142 """Returns the font embellishment string for attr.143 Args:144 attr: None to reset to the default font, otherwise one of renderer.BOLD,145 renderer.ITALIC, or renderer.CODE.146 out: Writes tags to this stream if not None.147 Returns:148 The font embellishment string.149 """150 if attr is None:151 self._font = 0152 else:153 mask = 1 << attr154 self._font ^= mask155 bold = self._font & ((1 << renderer.BOLD) | (1 << renderer.CODE))156 italic = self._font & (1 << renderer.ITALIC)157 code = self._attr.GetFontCode(bold=bold, italic=italic)158 if out:159 out.write(code)160 return code161 def Heading(self, level, heading):162 """Renders a heading.163 Args:164 level: The heading level counting from 1.165 heading: The heading text.166 """167 if level == 1 and heading.endswith('(1)'):168 # Ignore man page TH.169 return170 self._Flush()171 self.Line()172 self.Font(out=self._out)173 if level > 2:174 self._out.write(' ' * (level - 2))175 self._out.write(self.Font(renderer.BOLD) + heading +176 self.Font(renderer.BOLD) + '\n')177 if level == 1:178 self._out.write('\n')179 self._blank = True180 self._level = 0181 self._rows = []182 def Line(self):183 """Renders a paragraph separating line."""184 self._Flush()185 if not self._blank:186 self._blank = True187 self._out.write('\n')188 def List(self, level, definition=None, end=False):189 """Renders a bullet or definition list item.190 Args:191 level: The list nesting level, 0 if not currently in a list.192 definition: Bullet list if None, definition list item otherwise.193 end: End of list if True.194 """195 self._Flush()196 if not level:197 self._level = level198 elif end:199 # End of list.200 self._SetIndent(level)201 elif definition is not None:202 # Definition list item.203 if definition:204 self._SetIndent(level, indent=4, hanging_indent=3)205 self._out.write(206 ' ' * self._indent[level].hanging_indent + definition + '\n')207 else:208 self._SetIndent(level, indent=1, hanging_indent=0)209 self.Line()210 else:211 # Bullet list item.212 indent = 2 if level > 1 else 4213 self._SetIndent(level, indent=indent, hanging_indent=2)214 self._out.write(' ' * self._indent[level].hanging_indent +215 self._bullet[(level - 1) % len(self._bullet)])216 self._fill = self._indent[level].indent + 1217 self._ignore_width = True218 def _SkipSpace(self, line, index):219 """Skip space characters starting at line[index].220 Args:221 line: The string.222 index: The starting index in string.223 Returns:224 The index in line after spaces or len(line) at end of string.225 """226 while index < len(line):227 c = line[index]228 if c != ' ':229 break230 index += 1231 return index232 def _SkipControlSequence(self, line, index):233 """Skip the control sequence at line[index].234 Args:235 line: The string.236 index: The starting index in string.237 Returns:238 The index in line after the control sequence or len(line) at end of239 string.240 """241 n = self._attr.GetControlSequenceLen(line[index:])242 if not n:243 n = 1244 return index + n245 def _SkipNest(self, line, index, open_chars='[(', close_chars=')]'):246 """Skip a [...] nested bracket group starting at line[index].247 Args:248 line: The string.249 index: The starting index in string.250 open_chars: The open nesting characters.251 close_chars: The close nesting characters.252 Returns:253 The index in line after the nesting group or len(line) at end of string.254 """255 nest = 0256 while index < len(line):257 c = line[index]258 index += 1259 if c in open_chars:260 nest += 1261 elif c in close_chars:262 nest -= 1263 if nest <= 0:264 break265 elif c == self._csi_char:266 index = self._SkipControlSequence(line, index)267 return index268 def _SplitWideSynopsisGroup(self, group, indent, running_width):269 """Splits a wide SYNOPSIS section group string to self._out.270 Args:271 group: The wide group string to split.272 indent: The prevailing left indent.273 running_width: The width of the self._out line in progress.274 Returns:275 The running_width after the group has been split and written to self._out.276 """277 prev_delimiter = ' '278 while group:279 # Check split delimiters in order for visual emphasis.280 for delimiter in (' | ', ' : ', ' ', ','):281 part, _, remainder = group.partition(delimiter)282 w = self._attr.DisplayWidth(part)283 if ((running_width + len(prev_delimiter) + w) >= self._width or284 prev_delimiter != ',' and delimiter == ','):285 if delimiter != ',' and (indent +286 self.SPLIT_INDENT +287 len(prev_delimiter) +288 w) >= self._width:289 # The next delimiter may produce a smaller first part.290 continue291 if prev_delimiter == ',':292 self._out.write(prev_delimiter)293 prev_delimiter = ' '294 if running_width != indent:295 running_width = indent + self.SPLIT_INDENT296 self._out.write('\n' + ' ' * running_width)297 self._out.write(prev_delimiter + part)298 running_width += len(prev_delimiter) + w299 prev_delimiter = delimiter300 group = remainder301 break302 return running_width303 def Synopsis(self, line):304 """Renders NAME and SYNOPSIS lines as a hanging indent.305 Collapses adjacent spaces to one space, deletes trailing space, and doesn't306 split top-level nested [...] or (...) groups. Also detects and does not307 count terminal control sequences.308 Args:309 line: The NAME or SYNOPSIS text.310 """311 # Split the line into token, token | token, and [...] groups.312 groups = []313 i = self._SkipSpace(line, 0)314 beg = i315 while i < len(line):316 c = line[i]317 if c == ' ':318 end = i319 i = self._SkipSpace(line, i)320 if i <= (len(line) - 1) and line[i] == '|' and line[i + 1] == ' ':321 i = self._SkipSpace(line, i + 1)322 else:323 groups.append(line[beg:end])324 beg = i325 elif c in '[(':326 i = self._SkipNest(line, i)327 elif c == self._csi_char:328 i = self._SkipControlSequence(line, i)329 else:330 i += 1331 if beg < len(line):332 groups.append(line[beg:])333 # Output the groups.334 indent = self._indent[0].indent - 1335 running_width = indent336 self._out.write(' ' * running_width)337 indent += self.INDENT338 for group in groups:339 w = self._attr.DisplayWidth(group) + 1340 if (running_width + w) >= self._width:341 running_width = indent342 self._out.write('\n' + ' ' * running_width)343 if (running_width + w) >= self._width:344 # The group is wider than the available width and must be split.345 running_width = self._SplitWideSynopsisGroup(346 group, indent, running_width)347 continue348 self._out.write(' ' + group)349 running_width += w350 self._out.write('\n\n')351 def Table(self, line):352 """Renders a table line.353 Nested tables are not supported. The first call on a new table is:354 Table(attributes)355 the intermediate calls add the heading and data lines and the last call is:356 Table(None)357 Args:358 line: A CSV table data line.359 """360 if line is None:361 # TODO(b/31628974): Use resource_printer.TablePrinter().362 if self._rows:363 cols = len(self._rows[0])364 width = [0 for _ in range(cols)]365 for row in self._rows:366 for i in range(cols - 1):367 w = len(row[i])368 if width[i] <= w:369 width[i] = w + 1370 for row in self._rows:371 self._out.write(' ' * (self._indent[self._level].indent + 2))372 for i in range(cols - 1):373 self._out.write(row[i].ljust(width[i]))374 self._out.write(row[-1] + '\n')375 self._rows = []376 self._table = False377 self._out.write('\n')378 elif not self._table:379 self._table = True380 self.Line()381 else:...

Full Screen

Full Screen

formatting.py

Source:formatting.py Github

copy

Full Screen

...62 buf.append(line)63 _flush_par()64 rv = []65 for indent, raw, text in p:66 with wrapper.extra_indent(' ' * indent):67 if raw:68 rv.append(wrapper.indent_only(text))69 else:70 rv.append(wrapper.fill(text))71 return '\n\n'.join(rv)72class HelpFormatter(object):73 """This class helps with formatting text-based help pages. It's74 usually just needed for very special internal cases, but it's also75 exposed so that developers can write their own fancy outputs.76 At present, it always writes into memory.77 :param indent_increment: the additional increment for each level.78 :param width: the width for the text. This defaults to the terminal79 width clamped to a maximum of 78.80 """81 def __init__(self, indent_increment=2, width=None, max_width=None):82 self.indent_increment = indent_increment83 if max_width is None:84 max_width = 8085 if width is None:86 width = FORCED_WIDTH87 if width is None:88 width = max(min(get_terminal_size()[0], max_width) - 2, 50)89 self.width = width90 self.current_indent = 091 self.buffer = []92 def write(self, string):93 """Writes a unicode string into the internal buffer."""94 self.buffer.append(string)95 def indent(self):96 """Increases the indentation."""97 self.current_indent += self.indent_increment98 def dedent(self):99 """Decreases the indentation."""100 self.current_indent -= self.indent_increment101 def write_usage(self, prog, args='', prefix='Usage: '):102 """Writes a usage line into the buffer.103 :param prog: the program name.104 :param args: whitespace separated list of arguments.105 :param prefix: the prefix for the first line.106 """107 usage_prefix = '%*s%s ' % (self.current_indent, prefix, prog)108 text_width = self.width - self.current_indent109 if text_width >= (term_len(usage_prefix) + 20):110 # The arguments will fit to the right of the prefix.111 indent = ' ' * term_len(usage_prefix)112 self.write(wrap_text(args, text_width,113 initial_indent=usage_prefix,114 subsequent_indent=indent))115 else:116 # The prefix is too long, put the arguments on the next line.117 self.write(usage_prefix)118 self.write('\n')119 indent = ' ' * (max(self.current_indent, term_len(prefix)) + 4)120 self.write(wrap_text(args, text_width,121 initial_indent=indent,122 subsequent_indent=indent))123 self.write('\n')124 def write_heading(self, heading):125 """Writes a heading into the buffer."""126 self.write('%*s%s:\n' % (self.current_indent, '', heading))127 def write_paragraph(self):128 """Writes a paragraph into the buffer."""129 if self.buffer:130 self.write('\n')131 def write_text(self, text):132 """Writes re-indented text into the buffer. This rewraps and133 preserves paragraphs.134 """135 text_width = max(self.width - self.current_indent, 11)136 indent = ' ' * self.current_indent137 self.write(wrap_text(text, text_width,138 initial_indent=indent,139 subsequent_indent=indent,140 preserve_paragraphs=True))141 self.write('\n')142 def write_dl(self, rows, col_max=30, col_spacing=2):143 """Writes a definition list into the buffer. This is how options144 and commands are usually formatted.145 :param rows: a list of two item tuples for the terms and values.146 :param col_max: the maximum width of the first column.147 :param col_spacing: the number of spaces between the first and148 second column.149 """150 rows = list(rows)151 widths = measure_table(rows)152 if len(widths) != 2:153 raise TypeError('Expected two columns for definition list')154 first_col = min(widths[0], col_max) + col_spacing155 for first, second in iter_rows(rows, len(widths)):156 self.write('%*s%s' % (self.current_indent, '', first))157 if not second:158 self.write('\n')159 continue160 if term_len(first) <= first_col - col_spacing:161 self.write(' ' * (first_col - term_len(first)))162 else:163 self.write('\n')164 self.write(' ' * (first_col + self.current_indent))165 text_width = max(self.width - first_col - 2, 10)166 lines = iter(wrap_text(second, text_width).splitlines())167 if lines:168 self.write(next(lines) + '\n')169 for line in lines:170 self.write('%*s%s\n' % (171 first_col + self.current_indent, '', line))172 else:173 self.write('\n')174 @contextmanager175 def section(self, name):176 """Helpful context manager that writes a paragraph, a heading,177 and the indents.178 :param name: the section name that is written as heading.179 """180 self.write_paragraph()181 self.write_heading(name)182 self.indent()183 try:184 yield185 finally:186 self.dedent()187 @contextmanager188 def indentation(self):189 """A context manager that increases the indentation."""190 self.indent()191 try:192 yield193 finally:194 self.dedent()195 def getvalue(self):196 """Returns the buffer contents."""197 return ''.join(self.buffer)198def join_options(options):199 """Given a list of option strings this joins them in the most appropriate200 way and returns them in the form ``(formatted_string,201 any_prefix_is_slash)`` where the second item in the tuple is a flag that202 indicates if any of the option prefixes was a slash.203 """204 rv = []...

Full Screen

Full Screen

_json.py

Source:_json.py Github

copy

Full Screen

1import json2from .. import constants3ROUND = constants.DEFAULT_PRECISION4## THREE override function5def _json_floatstr(o):6 if ROUND is not None:7 o = round(o, ROUND)8 9 return '%g' % o10def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,11 _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,12 ## HACK: hand-optimized bytecode; turn globals into locals13 ValueError=ValueError,14 dict=dict,15 float=float,16 id=id,17 int=int,18 isinstance=isinstance,19 list=list,20 str=str,21 tuple=tuple,22 ):23 '''24 Overwrite json.encoder for Python 2.7 and above to not25 assign each index of a list or tuple to its own row as26 this is completely asinine behaviour 27 '''28 ## @THREE29 # Override the function30 _floatstr = _json_floatstr31 if _indent is not None and not isinstance(_indent, str):32 _indent = ' ' * _indent33 def _iterencode_list(lst, _current_indent_level):34 if not lst:35 yield '[]'36 return37 if markers is not None:38 markerid = id(lst)39 if markerid in markers:40 raise ValueError("Circular reference detected")41 markers[markerid] = lst42 buf = '['43 ## @THREEJS44 # - block the moronic functionality that puts each45 # index on its own line causing insane row counts46 #if _indent is not None:47 # _current_indent_level += 148 # newline_indent = '\n' + _indent * _current_indent_level49 # separator = _item_separator + newline_indent50 # buf += newline_indent51 #else:52 newline_indent = None53 separator = _item_separator54 first = True55 for value in lst:56 if first:57 first = False58 else:59 buf = separator60 if isinstance(value, str):61 yield buf + _encoder(value)62 elif value is None:63 yield buf + 'null'64 elif value is True:65 yield buf + 'true'66 elif value is False:67 yield buf + 'false'68 elif isinstance(value, int):69 yield buf + str(value)70 elif isinstance(value, float):71 yield buf + _floatstr(value)72 else:73 yield buf74 if isinstance(value, (list, tuple)):75 chunks = _iterencode_list(value, _current_indent_level)76 elif isinstance(value, dict):77 chunks = _iterencode_dict(value, _current_indent_level)78 else:79 chunks = _iterencode(value, _current_indent_level)80 for chunk in chunks:81 yield chunk82 if newline_indent is not None:83 _current_indent_level -= 184 yield '\n' + _indent * _current_indent_level85 yield ']'86 if markers is not None:87 del markers[markerid]88 def _iterencode_dict(dct, _current_indent_level):89 if not dct:90 yield '{}'91 return92 if markers is not None:93 markerid = id(dct)94 if markerid in markers:95 raise ValueError("Circular reference detected")96 markers[markerid] = dct97 yield '{'98 if _indent is not None:99 _current_indent_level += 1100 newline_indent = '\n' + _indent * _current_indent_level101 item_separator = _item_separator + newline_indent102 yield newline_indent103 else:104 newline_indent = None105 item_separator = _item_separator106 first = True107 if _sort_keys:108 items = sorted(dct.items(), key=lambda kv: kv[0])109 else:110 items = dct.items()111 for key, value in items:112 if isinstance(key, str):113 pass114 # JavaScript is weakly typed for these, so it makes sense to115 # also allow them. Many encoders seem to do something like this.116 elif isinstance(key, float):117 key = _floatstr(key)118 elif key is True:119 key = 'true'120 elif key is False:121 key = 'false'122 elif key is None:123 key = 'null'124 elif isinstance(key, int):125 key = str(key)126 elif _skipkeys:127 continue128 else:129 raise TypeError("key " + repr(key) + " is not a string")130 if first:131 first = False132 else:133 yield item_separator134 yield _encoder(key)135 yield _key_separator136 if isinstance(value, str):137 yield _encoder(value)138 elif value is None:139 yield 'null'140 elif value is True:141 yield 'true'142 elif value is False:143 yield 'false'144 elif isinstance(value, int):145 yield str(value)146 elif isinstance(value, float):147 yield _floatstr(value)148 else:149 if isinstance(value, (list, tuple)):150 chunks = _iterencode_list(value, _current_indent_level)151 elif isinstance(value, dict):152 chunks = _iterencode_dict(value, _current_indent_level)153 else:154 chunks = _iterencode(value, _current_indent_level)155 for chunk in chunks:156 yield chunk157 if newline_indent is not None:158 _current_indent_level -= 1159 yield '\n' + _indent * _current_indent_level160 yield '}'161 if markers is not None:162 del markers[markerid]163 def _iterencode(o, _current_indent_level):164 if isinstance(o, str):165 yield _encoder(o)166 elif o is None:167 yield 'null'168 elif o is True:169 yield 'true'170 elif o is False:171 yield 'false'172 elif isinstance(o, int):173 yield str(o)174 elif isinstance(o, float):175 yield _floatstr(o)176 elif isinstance(o, (list, tuple)):177 for chunk in _iterencode_list(o, _current_indent_level):178 yield chunk179 elif isinstance(o, dict):180 for chunk in _iterencode_dict(o, _current_indent_level):181 yield chunk182 else:183 if markers is not None:184 markerid = id(o)185 if markerid in markers:186 raise ValueError("Circular reference detected")187 markers[markerid] = o188 o = _default(o)189 for chunk in _iterencode(o, _current_indent_level):190 yield chunk191 if markers is not None:192 del markers[markerid]193 return _iterencode194# override the encoder...

Full Screen

Full Screen

util.py

Source:util.py Github

copy

Full Screen

...36# https://github.com/pre-commit/pre-commit/pull/211#issuecomment-18646660537# if you use this in your code, I suggest adding a test in your test suite38# that check this routines output against a known piece of your YAML39# before upgrades to this code break your round-tripped YAML40def load_yaml_guess_indent(stream, **kw):41 # type: (StreamTextType, Any) -> Any42 """guess the indent and block sequence indent of yaml stream/string43 returns round_trip_loaded stream, indent level, block sequence indent44 - block sequence indent is the number of spaces before a dash relative to previous indent45 - if there are no block sequences, indent is taken from nested mappings, block sequence46 indent is unset (None) in that case47 """48 from .main import round_trip_load49 # load a yaml file guess the indentation, if you use TABs ...50 def leading_spaces(l):51 # type: (Any) -> int52 idx = 053 while idx < len(l) and l[idx] == ' ':54 idx += 1...

Full Screen

Full Screen

PyAbcEcho.py

Source:PyAbcEcho.py Github

copy

Full Screen

1#-******************************************************************************2#3# Copyright (c) 2012,4# Sony Pictures Imageworks Inc. and5# Industrial Light & Magic, a division of Lucasfilm Entertainment Company Ltd.6#7# All rights reserved.8#9# Redistribution and use in source and binary forms, with or without10# modification, are permitted provided that the following conditions are11# met:12# * Redistributions of source code must retain the above copyright13# notice, this list of conditions and the following disclaimer.14# * Redistributions in binary form must reproduce the above15# copyright notice, this list of conditions and the following disclaimer16# in the documentation and/or other materials provided with the17# distribution.18# * Neither the name of Sony Pictures Imageworks, nor19# Industrial Light & Magic, nor the names of their contributors may be used20# to endorse or promote products derived from this software without specific21# prior written permission.22#23# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS24# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT25# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR26# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT27# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,28# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT29# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,30# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY31# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT32# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE33# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.34#35#-******************************************************************************3637import sys38from alembic.AbcCoreAbstract import *39from alembic.Abc import *40from alembic.Util import *4142def visitSmallArraySamples( iProp, iIndent ):43 indent = " " * iIndent4445 for i, s in enumerate( iProp.arraySamples ):46 print "%ssample %d:" % ( indent, i )47 if s is None:48 print indent, "********** Got nothing **********"49 else:50 print indent,51 for j in s:52 print j,53 print5455def visitScalarSamples( iProp, iIndent ):56 indent = " " * iIndent5758 for i, s in enumerate( iProp.scalarSamples ):59 print "%ssample %d:" % ( indent, i )60 if s is None:61 print indent, "********** Got nothing **********"62 else:63 print "%s%s" % ( indent, s )6465def visitArraySamples( iProp, iIndent ):66 indent = " " * iIndent6768 for i, s in enumerate( iProp.samples ):69 print "%ssample %d:" % ( indent, i )70 if s is None:71 print indent, "********** Got nothing **********"72 else:73 print indent,74 for j in s:75 print j,76 print 7778def visitCompoundProperty( iProp, iIndent ):79 indent = " " * iIndent80 ptype = "CompoundProperty"81 name = "name=%s" % iProp.getName()82 interp = "schema=%s" % iProp.getMetaData().get( "schema" )8384 print "%s%s %s; %s" % ( indent, ptype, name, interp )8586 visitProperties( iProp, iIndent+2 )8788def visitSimpleProperty( iProp, iIndent ):89 indent = " " * iIndent90 ptype = "ScalarProperty" if iProp.isScalar() else "ArrayProperty"91 name = "name=%s" % iProp.getName()92 md = "interpretation=%s" % iProp.getMetaData().get( "interpretation" )93 dtype = "datatype=%s" % iProp.getDataType()94 numsamps = "numsamps=%s" %iProp.getNumSamples()9596 print "%s%s %s; %s; %s; %s" % ( indent, ptype, name, md, dtype, numsamps )9798 if iProp.isScalar():99 if iProp.getDataType().getExtent() == 1:100 visitScalarSamples( iProp, iIndent+2 )101 elif len( iProp.getMetaData().get( "interpretation" ) ) > 0:102 visitScalarSamples( iProp, iIndent+2 )103 else:104 visitSmallArraySamples( iProp, iIndent+2 )105 else:106 visitArraySamples( iProp, iIndent+2 )107108109def visitProperties( iParent, iIndent ):110 for header in iParent.propertyheaders:111 prop = iParent.getProperty( header.getName() )112113 if header.isCompound():114 visitCompoundProperty( prop, iIndent+2 )115 elif header.isScalar() or header.isArray():116 visitSimpleProperty( prop, iIndent+2 )117118def visitObject( iObj, iIndent = 0 ):119120 path = iObj;121 indent = " " * iIndent122 ptype = "Object"123 name = "name=%s" % path124125 if path != "/":126 iIndent += 2127 print "%s%s %s" % ( indent, ptype, name )128129 visitProperties( iObj.getProperties(), iIndent )130131 for child in iObj.children:132 visitObject( child, iIndent )133134def visitArchive( iArg ):135 iArchive = IArchive( iArg )136137 print "AbcEcho for %s" % GetLibraryVersion()138139 info = GetArchiveInfo ( iArchive )140141 if len( info['appName'] ) > 0:142 print " file written by : %s" % info['appName']143 print " using Alembic : %s" % info['libraryVersionString']144 print " written on : %s" % info['whenWritten']145 print " user description by: %s" % info['userDescription']146 print147 else:148 print iArg149 print " (file doesn't have any ArchiveInfo)"150 print151152 visitObject( iArchive.getTop() )153154 ...

Full Screen

Full Screen

_textwrap.py

Source:_textwrap.py Github

copy

Full Screen

...11 reversed_chunks[-1] = res12 elif not cur_line:13 cur_line.append(reversed_chunks.pop())14 @contextmanager15 def extra_indent(self, indent):16 old_initial_indent = self.initial_indent17 old_subsequent_indent = self.subsequent_indent18 self.initial_indent += indent19 self.subsequent_indent += indent20 try:21 yield22 finally:23 self.initial_indent = old_initial_indent24 self.subsequent_indent = old_subsequent_indent25 def indent_only(self, text):26 rv = []27 for idx, line in enumerate(text.splitlines()):28 indent = self.initial_indent29 if idx > 0:...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1var indent = require('stryker-parent').indent;2console.log(indent('foo'));3var indent = require('stryker-parent').indent;4console.log(indent('foo'));5var indent = require('stryker-parent').indent;6console.log(indent('foo'));7var indent = require('stryker-parent').indent;8console.log(indent('foo'));9var indent = require('stryker-parent').indent;10console.log(indent('foo'));11var indent = require('stryker-parent').indent;12console.log(indent('foo'));13var indent = require('stryker-parent').indent;14console.log(indent('foo'));15var indent = require('stryker-parent').indent;16console.log(indent('foo'));17var indent = require('stryker-parent').indent;18console.log(indent('foo'));19var indent = require('stryker-parent').indent;20console.log(indent('foo'));21var indent = require('stryker-parent').indent;22console.log(indent('foo'));23var indent = require('stryker-parent').indent;24console.log(indent('foo'));25var indent = require('stryker-parent').indent;26console.log(indent('foo'));27var indent = require('stryker-parent').indent;28console.log(indent('foo'));

Full Screen

Using AI Code Generation

copy

Full Screen

1const strykerParent = require('stryker-parent');2console.log(strykerParent.indent('hello world'));3const strykerParent = require('stryker-parent');4console.log(strykerParent.indent('hello world'));5const strykerParent = require('stryker-parent');6console.log(strykerParent.indent('hello world'));7const strykerParent = require('stryker-parent');8console.log(strykerParent.indent('hello world'));9const strykerParent = require('stryker-parent');10console.log(strykerParent.indent('hello world'));11const strykerParent = require('stryker-parent');12console.log(strykerParent.indent('hello world'));13const strykerParent = require('stryker-parent');14console.log(strykerParent.indent('hello world'));15const strykerParent = require('stryker-parent');16console.log(strykerParent.indent('hello world'));17const strykerParent = require('stryker-parent');18console.log(strykerParent.indent('hello world'));19const strykerParent = require('stryker-parent');20console.log(strykerParent.indent('hello world'));21const strykerParent = require('stryker-parent');22console.log(strykerParent.indent('hello world'));23const strykerParent = require('stryker-parent');24console.log(strykerParent.indent('hello world'));

Full Screen

Using AI Code Generation

copy

Full Screen

1var indent = require('stryker-parent').indent;2var indent = require('stryker-parent').indent;3var indent = require('stryker-parent').indent;4var indent = require('stryker-parent').indent;5var indent = require('stryker-parent').indent;6var indent = require('stryker-parent').indent;7var indent = require('stryker-parent').indent;8var indent = require('stryker-parent').indent;9var indent = require('stryker-parent').indent;10var indent = require('stryker-parent').indent;11var indent = require('stryker-parent').indent;12var indent = require('stryker-parent').indent;13var indent = require('stryker

Full Screen

Using AI Code Generation

copy

Full Screen

1const { indent } = require('stryker-parent');2console.log(indent('foo'));3const { indent } = require('stryker-parent');4console.log(indent('foo'));5const { indent } = require('stryker-parent');6console.log(indent('foo'));7const { indent } = require('stryker-parent');8console.log(indent('foo'));9const { indent } = require('stryker-parent');10console.log(indent('foo'));11const { indent } = require('stryker-parent');12console.log(indent('foo'));13const { indent } = require('stryker-parent');14console.log(indent('foo'));15const { indent } = require('stryker-parent');16console.log(indent('foo'));17const { indent } = require('stryker-parent');18console.log(indent('foo'));19const { indent } = require('stryker-parent');20console.log(indent('foo'));21const { indent } = require('stryker-parent');22console.log(indent('foo'));23const { indent } = require('stryker-parent');24console.log(indent('foo'));25const { indent } = require('stryker-parent');26console.log(indent('foo'));27const { indent } = require('stryker-parent');28console.log(indent('foo'));29const { indent } = require('stryker-parent');30console.log(indent('foo'));31const { indent } = require('stryker-parent');32console.log(indent('foo'));

Full Screen

Using AI Code Generation

copy

Full Screen

1var fs = require('fs');2var indent = require('stryker-parent').indent;3var contents = fs.readFileSync(__dirname + '/test.js');4console.log(indent(contents.toString()));5var fs = require('fs');6var indent = require('stryker-parent').indent;7var contents = fs.readFileSync(__dirname + '/test.js');8console.log(indent(contents.toString()));9var fs = require('fs');10var indent = require('stryker-parent').indent;11var contents = fs.readFileSync(__dirname + '/test.js');12console.log(indent(contents.toString()));13var fs = require('fs');14var indent = require('stryker-parent').indent;15var contents = fs.readFileSync(__dirname + '/test.js');16console.log(indent(contents.toString()));17var fs = require('fs');18var indent = require('stryker-parent').indent;19var contents = fs.readFileSync(__dirname + '/test.js');20console.log(indent(contents.toString()));21var fs = require('fs');22var indent = require('stryker-parent').indent;23var contents = fs.readFileSync(__dirname + '/test.js');24console.log(indent(contents.toString()));25var fs = require('fs');26var indent = require('stryker-parent').indent;27var contents = fs.readFileSync(__dirname + '/test.js');28console.log(indent(contents.toString()));29var fs = require('fs');30var indent = require('stry

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run stryker-parent automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful