Exemple #1
0
def main(argv):
  """Main program.

  Arguments:
    argv: (Positional arguments) A list of files to reformat.

  Returns:
    0 if there were no errors, non-zero otherwise.
  """
  parser = argparse.ArgumentParser(description='Formatter for Python code.')
  parser.add_argument(
      '--style', action='store', default=None,
      help=('specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings'))
  diff_inplace_group = parser.add_mutually_exclusive_group()
  diff_inplace_group.add_argument(
      '-d', '--diff', action='store_true',
      help='print the diff for the fixed source')
  diff_inplace_group.add_argument(
      '-i', '--in-place', action='store_true',
      help='make changes to files in place')

  lines_recursive_group = parser.add_mutually_exclusive_group()
  lines_recursive_group.add_argument(
      '-l', '--lines', metavar='START-END', action='append', default=None,
      help='range of lines to reformat, one-based')
  lines_recursive_group.add_argument(
      '-r', '--recursive', action='store_true',
      help='run recursively over directories')

  parser.add_argument('files', nargs=argparse.REMAINDER)
  args = parser.parse_args()

  if args.lines and len(args.files) > 1:
    parser.error('cannot use -l/--lines with more than one file')

  lines = _GetLines(args.lines) if args.lines is not None else None
  files = file_resources.GetCommandLineFiles(argv[1:], args.recursive)
  if not files:
    # No arguments specified. Read code from stdin.
    if args.in_place or args.diff:
      parser.error('cannot use --in_place or --diff flags when reading '
                   'from stdin')

    original_source = []
    while True:
      try:
        # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
        # user will need to hit 'Ctrl-D' more than once if they're inputting
        # the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break
    sys.stdout.write(yapf_api.FormatCode(
        py3compat.unicode('\n'.join(original_source) + '\n'),
        filename='<stdin>',
        style_config=args.style,
        lines=lines))
    return 0

  FormatFiles(files, lines, style_config=args.style, in_place=args.in_place,
              print_diff=args.diff)
  return 0
Exemple #2
0
def main(argv):
    """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    Zero on successful program termination, non-zero otherwise.
    With --diff: zero if there were no changes, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
    args = _ParseArguments(argv)
    if args.version:
        print('yapf {}'.format(__version__))
        return 0

    style_config = args.style

    if args.style_help:
        print_help(args)
        return 0

    if args.lines and len(args.files) > 1:
        parser.error('cannot use -l/--lines with more than one file')

    lines = _GetLines(args.lines) if args.lines is not None else None
    if not args.files:
        # No arguments specified. Read code from stdin.
        if args.in_place or args.diff:
            parser.error('cannot use --in-place or --diff flags when reading '
                         'from stdin')

        original_source = []
        while True:
            if sys.stdin.closed:
                break
            try:
                # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
                # user will need to hit 'Ctrl-D' more than once if they're inputting
                # the program by hand. 'raw_input' throws an EOFError exception if
                # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
                original_source.append(py3compat.raw_input())
            except EOFError:
                break
            except KeyboardInterrupt:
                return 1

        if style_config is None and not args.no_local_style:
            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='<stdin>',
                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('<stdout>', 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)
    return 1 if changed and (args.diff or args.quiet) else 0
Exemple #3
0
def main(argv):
  """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    0 if there were no changes, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
  parser = argparse.ArgumentParser(description='Formatter for Python code.')
  parser.add_argument(
      '-v',
      '--version',
      action='store_true',
      help='show version number and exit')

  diff_inplace_group = parser.add_mutually_exclusive_group()
  diff_inplace_group.add_argument(
      '-d',
      '--diff',
      action='store_true',
      help='print the diff for the fixed source')
  diff_inplace_group.add_argument(
      '-i',
      '--in-place',
      action='store_true',
      help='make changes to files in place')

  lines_recursive_group = parser.add_mutually_exclusive_group()
  lines_recursive_group.add_argument(
      '-r',
      '--recursive',
      action='store_true',
      help='run recursively over directories')
  lines_recursive_group.add_argument(
      '-l',
      '--lines',
      metavar='START-END',
      action='append',
      default=None,
      help='range of lines to reformat, one-based')

  parser.add_argument(
      '-e',
      '--exclude',
      metavar='PATTERN',
      action='append',
      default=None,
      help='patterns for files to exclude from formatting')
  parser.add_argument(
      '--style',
      action='store',
      help=('specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. The '
            'default is pep8 unless a %s or %s file located in one of the '
            'parent directories of the source file (or current directory for '
            'stdin)' % (style.LOCAL_STYLE, style.SETUP_CONFIG)))
  parser.add_argument(
      '--style-help',
      action='store_true',
      help=('show style settings and exit; this output can be '
            'saved to .style.yapf to make your settings '
            'permanent'))
  parser.add_argument(
      '--no-local-style',
      action='store_true',
      help="don't search for local style definition")
  parser.add_argument('--verify', action='store_true', help=argparse.SUPPRESS)
  parser.add_argument(
      '-p',
      '--parallel',
      action='store_true',
      help=('Run yapf in parallel when formatting multiple files. Requires '
            'concurrent.futures in Python 2.X'))

  parser.add_argument('files', nargs='*')
  args = parser.parse_args(argv[1:])

  if args.version:
    print('yapf {}'.format(__version__))
    return 0

  if args.style_help:
    style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
    print('[style]')
    for option, docstring in sorted(style.Help().items()):
      for line in docstring.splitlines():
        print('#', line and ' ' or '', line, sep='')
      print(option.lower(), '=', style.Get(option), sep='')
      print()
    return 0

  if args.lines and len(args.files) > 1:
    parser.error('cannot use -l/--lines with more than one file')

  lines = _GetLines(args.lines) if args.lines is not None else None
  if not args.files:
    # No arguments specified. Read code from stdin.
    if args.in_place or args.diff:
      parser.error('cannot use --in-place or --diff flags when reading '
                   'from stdin')

    original_source = []
    while True:
      try:
        # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
        # user will need to hit 'Ctrl-D' more than once if they're inputting
        # the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break

    style_config = args.style
    if style_config is None and not args.no_local_style:
      style_config = file_resources.GetDefaultStyleForDir(os.getcwd())

    source = [line.rstrip() for line in original_source]
    reformatted_source, _ = yapf_api.FormatCode(
        py3compat.unicode('\n'.join(source) + '\n'),
        filename='<stdin>',
        style_config=style_config,
        lines=lines,
        verify=args.verify)
    file_resources.WriteReformattedCode('<stdout>', reformatted_source)
    return 0

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

  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)
  return 0
Exemple #4
0
def main(argv):
  """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    Zero on successful program termination, non-zero otherwise.
    With --diff: zero if there were no changes, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
  parser = argparse.ArgumentParser(description='Formatter for Python code.')
  parser.add_argument(
      '-v',
      '--version',
      action='store_true',
      help='show version number and exit')

  diff_inplace_quiet_group = parser.add_mutually_exclusive_group()
  diff_inplace_quiet_group.add_argument(
      '-d',
      '--diff',
      action='store_true',
      help='print the diff for the fixed source')
  diff_inplace_quiet_group.add_argument(
      '-i',
      '--in-place',
      action='store_true',
      help='make changes to files in place')
  diff_inplace_quiet_group.add_argument(
      '-q',
      '--quiet',
      action='store_true',
      help='output nothing and set return value')

  lines_recursive_group = parser.add_mutually_exclusive_group()
  lines_recursive_group.add_argument(
      '-r',
      '--recursive',
      action='store_true',
      help='run recursively over directories')
  lines_recursive_group.add_argument(
      '-l',
      '--lines',
      metavar='START-END',
      action='append',
      default=None,
      help='range of lines to reformat, one-based')

  parser.add_argument(
      '-e',
      '--exclude',
      metavar='PATTERN',
      action='append',
      default=None,
      help='patterns for files to exclude from formatting')
  parser.add_argument(
      '--style',
      action='store',
      help=('specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. The '
            'default is pep8 unless a %s or %s file located in the same '
            'directory as the source or one of its parent directories '
            '(for stdin, the current directory is used).' %
            (style.LOCAL_STYLE, style.SETUP_CONFIG)))
  parser.add_argument(
      '--style-help',
      action='store_true',
      help=('show style settings and exit; this output can be '
            'saved to .style.yapf to make your settings '
            'permanent'))
  parser.add_argument(
      '--no-local-style',
      action='store_true',
      help="don't search for local style definition")
  parser.add_argument('--verify', action='store_true', help=argparse.SUPPRESS)
  parser.add_argument(
      '-p',
      '--parallel',
      action='store_true',
      help=('run yapf in parallel when formatting multiple files. Requires '
            'concurrent.futures in Python 2.X'))
  parser.add_argument(
      '-vv',
      '--verbose',
      action='store_true',
      help='print out file names while processing')

  parser.add_argument(
      'files', nargs='*', help='reads from stdin when no files are specified.')
  args = parser.parse_args(argv[1:])

  if args.version:
    print('yapf {}'.format(__version__))
    return 0

  style_config = args.style

  if args.style_help:
    print_help(args)
    return 0

  if args.lines and len(args.files) > 1:
    parser.error('cannot use -l/--lines with more than one file')

  lines = _GetLines(args.lines) if args.lines is not None else None
  if not args.files:
    # No arguments specified. Read code from stdin.
    if args.in_place or args.diff:
      parser.error('cannot use --in-place or --diff flags when reading '
                   'from stdin')

    original_source = []
    while True:
      if sys.stdin.closed:
        break
      try:
        # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
        # user will need to hit 'Ctrl-D' more than once if they're inputting
        # the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break
      except KeyboardInterrupt:
        return 1

    if style_config is None and not args.no_local_style:
      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='<stdin>',
          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('<stdout>', 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)
  return 1 if changed and (args.diff or args.quiet) else 0
Exemple #5
0
def main(argv):
  """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    0 if there were no changes, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
  parser = argparse.ArgumentParser(description='Formatter for Python code.')
  parser.add_argument(
      '-v',
      '--version',
      action='store_true',
      help='show version number and exit')

  diff_inplace_group = parser.add_mutually_exclusive_group()
  diff_inplace_group.add_argument(
      '-d',
      '--diff',
      action='store_true',
      help='print the diff for the fixed source')
  diff_inplace_group.add_argument(
      '-i',
      '--in-place',
      action='store_true',
      help='make changes to files in place')

  lines_recursive_group = parser.add_mutually_exclusive_group()
  lines_recursive_group.add_argument(
      '-r',
      '--recursive',
      action='store_true',
      help='run recursively over directories')
  lines_recursive_group.add_argument(
      '-l',
      '--lines',
      metavar='START-END',
      action='append',
      default=None,
      help='range of lines to reformat, one-based')

  parser.add_argument(
      '-e',
      '--exclude',
      metavar='PATTERN',
      action='append',
      default=None,
      help='patterns for files to exclude from formatting')
  parser.add_argument(
      '--style',
      action='store',
      help=('specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. The '
            'default is pep8 unless a %s or %s file located in one of the '
            'parent directories of the source file (or current directory for '
            'stdin)' % (style.LOCAL_STYLE, style.SETUP_CONFIG)))
  parser.add_argument(
      '--style-help',
      action='store_true',
      help=('show style settings and exit; this output can be '
            'saved to .style.yapf to make your settings '
            'permanent'))
  parser.add_argument(
      '--no-local-style',
      action='store_true',
      help="don't search for local style definition")
  parser.add_argument('--verify', action='store_true', help=argparse.SUPPRESS)
  parser.add_argument(
      '-p',
      '--parallel',
      action='store_true',
      help=('Run yapf in parallel when formatting multiple files. Requires '
            'concurrent.futures in Python 2.X'))

  parser.add_argument('files', nargs='*')
  args = parser.parse_args(argv[1:])

  if args.version:
    print('yapf {}'.format(__version__))
    return 0

  if args.style_help:
    style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
    print('[style]')
    for option, docstring in sorted(style.Help().items()):
      for line in docstring.splitlines():
        print('#', line and ' ' or '', line, sep='')
      print(option.lower(), '=', style.Get(option), sep='')
      print()
    return 0

  if args.lines and len(args.files) > 1:
    parser.error('cannot use -l/--lines with more than one file')

  lines = _GetLines(args.lines) if args.lines is not None else None
  if not args.files:
    # No arguments specified. Read code from stdin.
    if args.in_place or args.diff:
      parser.error('cannot use --in-place or --diff flags when reading '
                   'from stdin')

    original_source = []
    while True:
      try:
        # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
        # user will need to hit 'Ctrl-D' more than once if they're inputting
        # the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break

    style_config = args.style
    if style_config is None and not args.no_local_style:
      style_config = file_resources.GetDefaultStyleForDir(os.getcwd())

    source = [line.rstrip() for line in original_source]
    reformatted_source, _ = yapf_api.FormatCode(
        py3compat.unicode('\n'.join(source) + '\n'),
        filename='<stdin>',
        style_config=style_config,
        lines=lines,
        verify=args.verify)
    file_resources.WriteReformattedCode('<stdout>', reformatted_source)
    return 0

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

  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)
  return 0
Exemple #6
0
 def _MakeTempFileWithContents(self, filename, contents):
     path = os.path.join(self.test_tmpdir, filename)
     with py3compat.open_with_encoding(path, mode='w',
                                       encoding='utf-8') as f:
         f.write(py3compat.unicode(contents))
     return path
Exemple #7
0
def main(argv):
  """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    0 if there were no errors, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
  parser = argparse.ArgumentParser(description='Formatter for Python code.')
  parser.add_argument('--version',
                      action='store_true',
                      help='show version number and exit')
  parser.add_argument('--style-help',
                      action='store_true',
                      help='show style settings and exit')
  parser.add_argument(
      '--style',
      action='store',
      default='pep8',
      help=('specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. pep8 is '
            'the default.'))
  parser.add_argument('--verify',
                      action='store_true',
                      help='try to verify reformatted code for syntax errors')
  diff_inplace_group = parser.add_mutually_exclusive_group()
  diff_inplace_group.add_argument('-d', '--diff',
                                  action='store_true',
                                  help='print the diff for the fixed source')
  diff_inplace_group.add_argument('-i', '--in-place',
                                  action='store_true',
                                  help='make changes to files in place')

  lines_recursive_group = parser.add_mutually_exclusive_group()
  lines_recursive_group.add_argument(
      '-l', '--lines',
      metavar='START-END',
      action='append',
      default=None,
      help='range of lines to reformat, one-based')
  lines_recursive_group.add_argument('-r', '--recursive',
                                     action='store_true',
                                     help='run recursively over directories')

  parser.add_argument('files', nargs='*')
  args = parser.parse_args(argv[1:])

  if args.version:
    print('yapf {}'.format(__version__))
    return 0

  if args.style_help:
    style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
    for option, docstring in sorted(style.Help().items()):
      print(option, '=', style.Get(option), sep='')
      for line in docstring.splitlines():
        print('  ', line)
      print()
    return 0

  if args.lines and len(args.files) > 1:
    parser.error('cannot use -l/--lines with more than one file')

  lines = _GetLines(args.lines) if args.lines is not None else None
  if not args.files:
    # No arguments specified. Read code from stdin.
    if args.in_place or args.diff:
      parser.error('cannot use --in_place or --diff flags when reading '
                   'from stdin')

    original_source = []
    while True:
      try:
        # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
        # user will need to hit 'Ctrl-D' more than once if they're inputting
        # the program by hand. 'raw_input' throws an EOFError exception if
        # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
        original_source.append(py3compat.raw_input())
      except EOFError:
        break
    sys.stdout.write(yapf_api.FormatCode(
        py3compat.unicode('\n'.join(original_source) + '\n'),
        filename='<stdin>',
        style_config=args.style,
        lines=lines,
        verify=args.verify))
    return 0

  files = file_resources.GetCommandLineFiles(args.files, args.recursive)
  if not files:
    raise YapfError('Input filenames did not match any python files')
  FormatFiles(files, lines,
              style_config=args.style,
              in_place=args.in_place,
              print_diff=args.diff,
              verify=args.verify)
  return 0
Exemple #8
0
def main(argv):
    """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    0 if there were no errors, non-zero otherwise.
  """
    parser = argparse.ArgumentParser(description='Formatter for Python code.')
    parser.add_argument('--version',
                        action='store_true',
                        help='show version number and exit')
    parser.add_argument('--style-help',
                        action='store_true',
                        help='show style settings and exit')
    parser.add_argument(
        '--style',
        action='store',
        default='pep8',
        help=(
            'specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. pep8 is '
            'the default.'))
    parser.add_argument('--verify',
                        action='store_true',
                        help='try to verify refomatted code for syntax errors')
    diff_inplace_group = parser.add_mutually_exclusive_group()
    diff_inplace_group.add_argument('-d',
                                    '--diff',
                                    action='store_true',
                                    help='print the diff for the fixed source')
    diff_inplace_group.add_argument('-i',
                                    '--in-place',
                                    action='store_true',
                                    help='make changes to files in place')

    lines_recursive_group = parser.add_mutually_exclusive_group()
    lines_recursive_group.add_argument(
        '-l',
        '--lines',
        metavar='START-END',
        action='append',
        default=None,
        help='range of lines to reformat, one-based')
    lines_recursive_group.add_argument('-r',
                                       '--recursive',
                                       action='store_true',
                                       help='run recursively over directories')

    parser.add_argument('files', nargs='*')
    args = parser.parse_args(argv[1:])

    if args.version:
        print('yapf {}'.format(__version__))
        return 0

    if args.style_help:
        style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
        for option, docstring in sorted(style.Help().items()):
            print(option, "=", style.Get(option), sep='')
            for line in docstring.splitlines():
                print('  ', line)
            print()
        return 0

    if args.lines and len(args.files) > 1:
        parser.error('cannot use -l/--lines with more than one file')

    lines = _GetLines(args.lines) if args.lines is not None else None
    if not args.files:
        # No arguments specified. Read code from stdin.
        if args.in_place or args.diff:
            parser.error('cannot use --in_place or --diff flags when reading '
                         'from stdin')

        original_source = []
        while True:
            try:
                # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
                # user will need to hit 'Ctrl-D' more than once if they're inputting
                # the program by hand. 'raw_input' throws an EOFError exception if
                # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
                original_source.append(py3compat.raw_input())
            except EOFError:
                break
        sys.stdout.write(
            yapf_api.FormatCode(py3compat.unicode('\n'.join(original_source) +
                                                  '\n'),
                                filename='<stdin>',
                                style_config=args.style,
                                lines=lines,
                                verify=args.verify))
        return 0

    files = file_resources.GetCommandLineFiles(args.files, args.recursive)
    if not files:
        raise YapfError('Input filenames did not match any python files')
    FormatFiles(files,
                lines,
                style_config=args.style,
                in_place=args.in_place,
                print_diff=args.diff,
                verify=args.verify)
    return 0
Exemple #9
0
def main(argv):
    """Main program.

  Arguments:
    argv: command-line arguments, such as sys.argv (including the program name
      in argv[0]).

  Returns:
    0 if there were no errors, non-zero otherwise.

  Raises:
    YapfError: if none of the supplied files were Python files.
  """
    parser = argparse.ArgumentParser(description="Formatter for Python code.")
    parser.add_argument("--version", action="store_true", help="show version number and exit")
    parser.add_argument("--style-help", action="store_true", help="show style settings and exit")
    parser.add_argument(
        "--style",
        action="store",
        help=(
            'specify formatting style: either a style name (for example "pep8" '
            'or "google"), or the name of a file with style settings. The '
            "default is pep8 unless a %s file located in one of the parent "
            "directories of the source file (or current directory for "
            "stdin)" % style.LOCAL_STYLE
        ),
    )
    parser.add_argument(
        "--no-local-style",
        action="store_true",
        help=("Do not search for local style defintion (%s)" % style.LOCAL_STYLE),
    )
    parser.add_argument("--verify", action="store_true", help="try to verify reformatted code for syntax errors")
    diff_inplace_group = parser.add_mutually_exclusive_group()
    diff_inplace_group.add_argument("-d", "--diff", action="store_true", help="print the diff for the fixed source")
    diff_inplace_group.add_argument("-i", "--in-place", action="store_true", help="make changes to files in place")

    lines_recursive_group = parser.add_mutually_exclusive_group()
    lines_recursive_group.add_argument(
        "-l",
        "--lines",
        metavar="START-END",
        action="append",
        default=None,
        help="range of lines to reformat, one-based",
    )
    lines_recursive_group.add_argument(
        "-r", "--recursive", action="store_true", help="run recursively over directories"
    )

    parser.add_argument("files", nargs="*")
    args = parser.parse_args(argv[1:])

    if args.version:
        print("yapf {}".format(__version__))
        return 0

    if args.style_help:
        style.SetGlobalStyle(style.CreateStyleFromConfig(args.style))
        for option, docstring in sorted(style.Help().items()):
            print(option, "=", style.Get(option), sep="")
            for line in docstring.splitlines():
                print("  ", line)
            print()
        return 0

    if args.lines and len(args.files) > 1:
        parser.error("cannot use -l/--lines with more than one file")

    lines = _GetLines(args.lines) if args.lines is not None else None
    if not args.files:
        # No arguments specified. Read code from stdin.
        if args.in_place or args.diff:
            parser.error("cannot use --in_place or --diff flags when reading " "from stdin")

        original_source = []
        while True:
            try:
                # Use 'raw_input' instead of 'sys.stdin.read', because otherwise the
                # user will need to hit 'Ctrl-D' more than once if they're inputting
                # the program by hand. 'raw_input' throws an EOFError exception if
                # 'Ctrl-D' is pressed, which makes it easy to bail out of this loop.
                original_source.append(py3compat.raw_input())
            except EOFError:
                break
        style_config = args.style
        if style_config is None and not args.no_local_style:
            style_config = file_resources.GetDefaultStyleForDir(os.getcwd())
        sys.stdout.write(
            yapf_api.FormatCode(
                py3compat.unicode("\n".join(original_source) + "\n"),
                filename="<stdin>",
                style_config=style_config,
                lines=lines,
                verify=args.verify,
            )
        )
        return 0

    files = file_resources.GetCommandLineFiles(args.files, args.recursive)
    if not files:
        raise errors.YapfError("Input filenames did not match any python files")
    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,
    )
    return 0
Exemple #10
0
 def _MakeTempFileWithContents(self, filename, contents):
   path = os.path.join(self.test_tmpdir, filename)
   with py3compat.open_with_encoding(path, mode='w', encoding='utf-8') as f:
     f.write(py3compat.unicode(contents))
   return path