Exemple #1
0
def ParseAndUnwrap(code, dumptree=False):
  """Produces logical lines from the given code.

  Parses the code into a tree, performs comment splicing and runs the
  unwrapper.

  Arguments:
    code: code to parse as a string
    dumptree: if True, the parsed pytree (after comment splicing) is dumped
              to stderr. Useful for debugging.

  Returns:
    List of logical lines.
  """
  tree = pytree_utils.ParseCodeToTree(code)
  comment_splicer.SpliceComments(tree)
  continuation_splicer.SpliceContinuations(tree)
  subtype_assigner.AssignSubtypes(tree)
  identify_container.IdentifyContainers(tree)
  split_penalty.ComputeSplitPenalties(tree)
  blank_line_calculator.CalculateBlankLines(tree)

  if dumptree:
    pytree_visitor.DumpPyTree(tree, target_stream=sys.stderr)

  llines = pytree_unwrapper.UnwrapPyTree(tree)
  for lline in llines:
    lline.CalculateFormattingInformation()

  return llines
Exemple #2
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=False):
    """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    remaining arguments: see comment at the top of this module.

  Returns:
    Tuple of (reformatted_source, changed). reformatted_source conforms to the
    desired formatting style. changed is True if the source changed.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
    if not unformatted_source.endswith('\n'):
        unformatted_source += '\n'

    try:
        tree = pytree_utils.ParseCodeToTree(unformatted_source)
    except parse.ParseError as e:
        e.msg = filename + ': ' + e.msg
        raise

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    identify_container.IdentifyContainers(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    lines = _LineRangesToSet(lines)
    _MarkLinesToFormat(uwlines, lines)
    reformatted_source = reformatter.Reformat(_SplitSemicolons(uwlines),
                                              verify, lines)

    if unformatted_source == reformatted_source:
        return '' if print_diff else reformatted_source, False

    code_diff = _GetUnifiedDiff(unformatted_source,
                                reformatted_source,
                                filename=filename)

    if print_diff:
        return code_diff, code_diff.strip() != ''  # pylint: disable=g-explicit-bool-comparison

    return reformatted_source, True
Exemple #3
0
def FormatTree(tree, style_config=None, lines=None, verify=False):
    """Format a parsed lib2to3 pytree.

  This provides an alternative entry point to YAPF.

  Arguments:
    tree: (pytree.Node) The root of the pytree to format.
    style_config: (string) Either a style name or a path to a file that contains
      formatting style settings. If None is specified, use the default style
      as set in style.DEFAULT_STYLE_FACTORY
    lines: (list of tuples of integers) A list of tuples of lines, [start, end],
      that we want to format. The lines are 1-based indexed. It can be used by
      third-party code (e.g., IDEs) when reformatting a snippet of code rather
      than a whole file.
    verify: (bool) True if reformatted code should be verified for syntax.

  Returns:
    The source formatted according to the given formatting style.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    identify_container.IdentifyContainers(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    llines = pytree_unwrapper.UnwrapPyTree(tree)
    for lline in llines:
        lline.CalculateFormattingInformation()

    lines = _LineRangesToSet(lines)
    _MarkLinesToFormat(llines, lines)
    return reformatter.Reformat(_SplitSemicolons(llines), verify, lines)
Exemple #4
0
def FormatCode(unformatted_source,
               filename='<unknown>',
               style_config=None,
               lines=None,
               print_diff=False,
               verify=False):
    """Format a string of Python code.

  This provides an alternative entry point to YAPF.

  Arguments:
    unformatted_source: (unicode) The code to format.
    filename: (unicode) The name of the file being reformatted.
    style_config: (string) Either a style name or a path to a file that contains
      formatting style settings. If None is specified, use the default style
      as set in style.DEFAULT_STYLE_FACTORY
    lines: (list of tuples of integers) A list of tuples of lines, [start, end],
      that we want to format. The lines are 1-based indexed. It can be used by
      third-party code (e.g., IDEs) when reformatting a snippet of code rather
      than a whole file.
    print_diff: (bool) Instead of returning the reformatted source, return a
      diff that turns the formatted source into reformatter source.
    verify: (bool) True if reformatted code should be verified for syntax.

  Returns:
    Tuple of (reformatted_source, changed). reformatted_source conforms to the
    desired formatting style. changed is True if the source changed.
  """
    _CheckPythonVersion()
    style.SetGlobalStyle(style.CreateStyleFromConfig(style_config))
    if not unformatted_source.endswith('\n'):
        unformatted_source += '\n'

    try:
        tree = pytree_utils.ParseCodeToTree(unformatted_source)
    except parse.ParseError as e:
        e.msg = filename + ': ' + e.msg
        raise

    # Run passes on the tree, modifying it in place.
    comment_splicer.SpliceComments(tree)
    continuation_splicer.SpliceContinuations(tree)
    subtype_assigner.AssignSubtypes(tree)
    identify_container.IdentifyContainers(tree)
    split_penalty.ComputeSplitPenalties(tree)
    blank_line_calculator.CalculateBlankLines(tree)

    uwlines = pytree_unwrapper.UnwrapPyTree(tree)
    for uwl in uwlines:
        uwl.CalculateFormattingInformation()

    lines = _LineRangesToSet(lines)
    _MarkLinesToFormat(uwlines, lines)
    reformatted_source = reformatter.Reformat(_SplitSemicolons(uwlines),
                                              verify, lines)

    if unformatted_source == reformatted_source:
        return '' if print_diff else reformatted_source, False

    code_diff = _GetUnifiedDiff(unformatted_source,
                                reformatted_source,
                                filename=filename)

    if print_diff:
        return code_diff, code_diff.strip() != ''  # pylint: disable=g-explicit-bool-comparison

    return reformatted_source, True