How to use the yapf.yapflib.file_resources function in yapf

To help you get started, we’ve selected a few yapf examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github palantir / python-language-server / pyls / plugins / yapf_format.py View on Github external
def _format(document, lines=None):
    new_source, changed = FormatCode(
        document.source,
        lines=lines,
        filename=document.filename,
        style_config=file_resources.GetDefaultStyleForDir(
            os.path.dirname(document.path)
        )
    )

    if not changed:
        return []

    # I'm too lazy at the moment to parse diffs into TextEdit items
    # So let's just return the entire file...
    return [{
        'range': {
            'start': {'line': 0, 'character': 0},
            # End char 0 of the line after our document
            'end': {'line': len(document.lines), 'character': 0}
        },
        'newText': new_source
github baohaojun / system-config / elpy-20170701.1412 / elpy / yapfutil.py View on Github external
def fix_code(code):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not yapf_api:
        raise Fault('yapf not installed', code=400)
    style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
    try:
        reformatted_source, _ = yapf_api.FormatCode(code,
                                                    filename='',
                                                    style_config=style_config,
                                                    verify=False)
        return reformatted_source
    except Exception as e:
            raise Fault("Error during formatting: {}".format(e),
                        code=400)
github mikadosoftware / workstation / .build / rcassets / .emacs.d / elpa / elpy-20180613.1353 / elpy / yapfutil.py View on Github external
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not yapf_api:
        raise Fault('yapf not installed', code=400)
    style_config = file_resources.GetDefaultStyleForDir(directory or os.getcwd())
    try:
        reformatted_source, _ = yapf_api.FormatCode(code,
                                                    filename='',
                                                    style_config=style_config,
                                                    verify=False)
        return reformatted_source
    except Exception as e:
            raise Fault("Error during formatting: {}".format(e),
                        code=400)
github baohaojun / system-config / elpy-20200329.1830 / elpy / yapfutil.py View on Github external
def fix_code(code, directory):
    """Formats Python code to conform to the PEP 8 style guide.

    """
    if not yapf_api:
        raise Fault('yapf not installed', code=400)
    style_config = file_resources.GetDefaultStyleForDir(directory or os.getcwd())
    try:
        reformatted_source, _ = yapf_api.FormatCode(code,
                                                    filename='',
                                                    style_config=style_config,
                                                    verify=False)
        return reformatted_source
    except Exception as e:
            raise Fault("Error during formatting: {}".format(e),
                        code=400)
github google / yapf / yapf / __init__.py View on Github external
style_config = file_resources.GetDefaultStyleForDir(os.getcwd())

    source = [line.rstrip() for line in original_source]
    source[0] = py3compat.removeBOM(source[0])

    try:
      reformatted_source, _ = yapf_api.FormatCode(
          py3compat.unicode('\n'.join(source) + '\n'),
          filename='',
          style_config=style_config,
          lines=lines,
          verify=args.verify)
    except tokenize.TokenError as e:
      raise errors.YapfError('%s:%s' % (e.args[1][0], e.args[0]))

    file_resources.WriteReformattedCode('', reformatted_source)
    return 0

  # Get additional exclude patterns from ignorefile
  exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
      os.getcwd())

  files = file_resources.GetCommandLineFiles(args.files, args.recursive,
                                             (args.exclude or []) +
                                             exclude_patterns_from_ignore_file)
  if not files:
    raise errors.YapfError('Input filenames did not match any python files')

  changed = FormatFiles(
      files,
      lines,
      style_config=args.style,
github google / yapf / yapf / yapflib / yapf_api.py View on Github external
An optional logger can be specified to emit messages to your favorite logging
  stream. If specified, then no exception is raised. This is external so that it
  can be used by third-party applications.

  Arguments:
    filename: (unicode) The name of the file.
    logger: (function) A function or lambda that takes a string and emits it.

  Returns:
    The contents of filename.

  Raises:
    IOError: raised if there was an error reading the file.
  """
  try:
    encoding = file_resources.FileEncoding(filename)

    # Preserves line endings.
    with py3compat.open_with_encoding(
        filename, mode='r', encoding=encoding, newline='') as fd:
      lines = fd.readlines()

    line_ending = file_resources.LineEnding(lines)
    source = '\n'.join(line.rstrip('\r\n') for line in lines) + '\n'
    return source, line_ending, encoding
  except IOError as err:  # pragma: no cover
    if logger:
      logger(err)
    raise
github google / yapf / yapf / __init__.py View on Github external
if verbose and not quiet:
    print('Reformatting %s' % filename)
  if style_config is None and not no_local_style:
    style_config = file_resources.GetDefaultStyleForDir(
        os.path.dirname(filename))
  try:
    reformatted_code, encoding, has_change = yapf_api.FormatFile(
        filename,
        in_place=in_place,
        style_config=style_config,
        lines=lines,
        print_diff=print_diff,
        verify=verify,
        logger=logging.warning)
    if not in_place and not quiet and reformatted_code:
      file_resources.WriteReformattedCode(filename, reformatted_code, encoding,
                                          in_place)
    return has_change
  except tokenize.TokenError as e:
    raise errors.YapfError('%s:%s:%s' % (filename, e.args[1][0], e.args[0]))
  except SyntaxError as e:
    e.filename = filename
    raise
github google / yapf / yapf / yapflib / yapf_api.py View on Github external
Returns:
    The contents of filename.

  Raises:
    IOError: raised if there was an error reading the file.
  """
  try:
    encoding = file_resources.FileEncoding(filename)

    # Preserves line endings.
    with py3compat.open_with_encoding(
        filename, mode='r', encoding=encoding, newline='') as fd:
      lines = fd.readlines()

    line_ending = file_resources.LineEnding(lines)
    source = '\n'.join(line.rstrip('\r\n') for line in lines) + '\n'
    return source, line_ending, encoding
  except IOError as err:  # pragma: no cover
    if logger:
      logger(err)
    raise
github google / yapf / yapf / __init__.py View on Github external
py3compat.unicode('\n'.join(source) + '\n'),
          filename='',
          style_config=style_config,
          lines=lines,
          verify=args.verify)
    except tokenize.TokenError as e:
      raise errors.YapfError('%s:%s' % (e.args[1][0], e.args[0]))

    file_resources.WriteReformattedCode('', reformatted_source)
    return 0

  # Get additional exclude patterns from ignorefile
  exclude_patterns_from_ignore_file = file_resources.GetExcludePatternsForDir(
      os.getcwd())

  files = file_resources.GetCommandLineFiles(args.files, args.recursive,
                                             (args.exclude or []) +
                                             exclude_patterns_from_ignore_file)
  if not files:
    raise errors.YapfError('Input filenames did not match any python files')

  changed = FormatFiles(
      files,
      lines,
      style_config=args.style,
      no_local_style=args.no_local_style,
      in_place=args.in_place,
      print_diff=args.diff,
      verify=args.verify,
      parallel=args.parallel,
      quiet=args.quiet,
      verbose=args.verbose)