Browse Source

Style everything with yapf

skullY 6 năm trước cách đây
mục cha
commit
7c5a16d427

+ 0 - 1
bin/qmk

@@ -42,6 +42,5 @@ else:
 os.environ['ORIG_CWD'] = os.getcwd()
 os.chdir(qmk_dir)
 
-
 if __name__ == '__main__':
     cli()

+ 66 - 58
lib/python/milc.py

@@ -36,7 +36,6 @@ except ImportError:
 import argcomplete
 import colorama
 
-
 # Log Level Representations
 EMOJI_LOGLEVELS = {
     'CRITICAL': '{bg_red}{fg_white}¬_¬{style_reset_all}',
@@ -49,7 +48,6 @@ EMOJI_LOGLEVELS = {
 EMOJI_LOGLEVELS['FATAL'] = EMOJI_LOGLEVELS['CRITICAL']
 EMOJI_LOGLEVELS['WARN'] = EMOJI_LOGLEVELS['WARNING']
 
-
 # ANSI Color setup
 # Regex was gratefully borrowed from kfir on stackoverflow:
 # https://stackoverflow.com/a/45448194
@@ -68,10 +66,14 @@ ansi_regex = r'\x1b(' \
              r'(\[\?\d;\d0c)|' \
              r'(\d;\dR))'
 ansi_escape = re.compile(ansi_regex, flags=re.IGNORECASE)
+ansi_styles = (
+    ('fg', colorama.ansi.AnsiFore()),
+    ('bg', colorama.ansi.AnsiBack()),
+    ('style', colorama.ansi.AnsiStyle()),
+)
 ansi_colors = {}
-for prefix, obj in (('fg', colorama.ansi.AnsiFore()),
-                    ('bg', colorama.ansi.AnsiBack()),
-                    ('style', colorama.ansi.AnsiStyle())):
+
+for prefix, obj in ansi_styles:
     for color in [x for x in obj.__dict__ if not x.startswith('_')]:
         ansi_colors[prefix + '_' + color.lower()] = getattr(obj, color)
 
@@ -88,6 +90,7 @@ def format_ansi(text):
 class ANSIFormatter(logging.Formatter):
     """A log formatter that inserts ANSI color.
     """
+
     def format(self, record):
         msg = super(ANSIFormatter, self).format(record)
         return format_ansi(msg)
@@ -96,6 +99,7 @@ class ANSIFormatter(logging.Formatter):
 class ANSIEmojiLoglevelFormatter(ANSIFormatter):
     """A log formatter that makes the loglevel an emoji.
     """
+
     def format(self, record):
         record.levelname = EMOJI_LOGLEVELS[record.levelname].format(**ansi_colors)
         return super(ANSIEmojiLoglevelFormatter, self).format(record)
@@ -104,6 +108,7 @@ class ANSIEmojiLoglevelFormatter(ANSIFormatter):
 class ANSIStrippingFormatter(ANSIFormatter):
     """A log formatter that strips ANSI.
     """
+
     def format(self, record):
         msg = super(ANSIStrippingFormatter, self).format(record)
         return ansi_escape.sub('', msg)
@@ -115,6 +120,7 @@ class Configuration(object):
     This class never raises IndexError, instead it will return None if a
     section or option does not yet exist.
     """
+
     def __contains__(self, key):
         return self._config.__contains__(key)
 
@@ -154,8 +160,8 @@ class Configuration(object):
 
     def __delitem__(self, key):
         if key in self.__dict__ and key[0] != '_':
-            del(self.__dict__[key])
-        del(self._config[key])
+            del self.__dict__[key]
+        del self._config[key]
 
 
 class ConfigurationOption(Configuration):
@@ -197,6 +203,7 @@ def handle_store_boolean(self, *args, **kwargs):
 class SubparserWrapper(object):
     """Wrap subparsers so we can populate the normal and the shadow parser.
     """
+
     def __init__(self, cli, submodule, subparser):
         self.cli = cli
         self.submodule = submodule
@@ -215,7 +222,7 @@ class SubparserWrapper(object):
         if kwargs.get('add_dest', True):
             kwargs['dest'] = self.submodule + '_' + self.cli.get_argument_name(*args, **kwargs)
         if 'add_dest' in kwargs:
-            del(kwargs['add_dest'])
+            del kwargs['add_dest']
 
         if 'action' in kwargs and kwargs['action'] == 'store_boolean':
             return handle_store_boolean(self, *args, **kwargs)
@@ -224,7 +231,7 @@ class SubparserWrapper(object):
         self.subparser.add_argument(*args, **kwargs)
 
         if 'default' in kwargs:
-            del(kwargs['default'])
+            del kwargs['default']
         if 'action' in kwargs and kwargs['action'] == 'store_false':
             kwargs['action'] == 'store_true'
         self.cli.subcommands_default[self.submodule].add_argument(*args, **kwargs)
@@ -234,6 +241,7 @@ class SubparserWrapper(object):
 class MILC(object):
     """MILC - An Opinionated Batteries Included Framework
     """
+
     def __init__(self):
         """Initialize the MILC object.
         """
@@ -286,7 +294,7 @@ class MILC(object):
         """
         kwargs = {
             'fromfile_prefix_chars': '@',
-            'conflict_handler': 'resolve'
+            'conflict_handler': 'resolve',
         }
 
         self.acquire_lock()
@@ -314,7 +322,7 @@ class MILC(object):
         if kwargs.get('add_dest', True):
             kwargs['dest'] = 'general_' + self.get_argument_name(*args, **kwargs)
         if 'add_dest' in kwargs:
-            del(kwargs['add_dest'])
+            del kwargs['add_dest']
 
         if 'action' in kwargs and kwargs['action'] == 'store_boolean':
             return handle_store_boolean(self, *args, **kwargs)
@@ -324,7 +332,7 @@ class MILC(object):
 
         # Populate the shadow parser
         if 'default' in kwargs:
-            del(kwargs['default'])
+            del kwargs['default']
         if 'action' in kwargs and kwargs['action'] == 'store_false':
             kwargs['action'] == 'store_true'
         self._arg_defaults.add_argument(*args, **kwargs)
@@ -581,6 +589,7 @@ class MILC(object):
     def subcommand(self, description, **kwargs):
         """Decorator to register a subcommand.
         """
+
         def subcommand_function(handler):
             return self.add_subcommand(handler, description, **kwargs)
 
@@ -654,50 +663,49 @@ class MILC(object):
 cli = MILC()
 
 if __name__ == '__main__':
-        @cli.argument('-c', '--comma', help='comma in output', default=True, action='store_boolean')
-        @cli.entrypoint('My useful CLI tool with subcommands.')
-        def main(cli):
-            comma = ',' if cli.config.general.comma else ''
-            cli.log.info('{bg_green}{fg_red}Hello%s World!', comma)
-
-        @cli.argument('-n', '--name', help='Name to greet', default='World')
-        @cli.subcommand('Description of hello subcommand here.')
-        def hello(cli):
-            comma = ',' if cli.config.general.comma else ''
-            cli.log.info('{fg_blue}Hello%s %s!', comma, cli.config.hello.name)
-
-        def goodbye(cli):
-            comma = ',' if cli.config.general.comma else ''
-            cli.log.info('{bg_red}Goodbye%s %s!', comma, cli.config.goodbye.name)
-
-        @cli.argument('-n', '--name', help='Name to greet', default='World')
-        @cli.subcommand('Think a bit before greeting the user.')
-        def thinking(cli):
-            comma = ',' if cli.config.general.comma else ''
-            spinner = cli.spinner(text='Just a moment...', spinner='earth')
-            spinner.start()
+
+    @cli.argument('-c', '--comma', help='comma in output', default=True, action='store_boolean')
+    @cli.entrypoint('My useful CLI tool with subcommands.')
+    def main(cli):
+        comma = ',' if cli.config.general.comma else ''
+        cli.log.info('{bg_green}{fg_red}Hello%s World!', comma)
+
+    @cli.argument('-n', '--name', help='Name to greet', default='World')
+    @cli.subcommand('Description of hello subcommand here.')
+    def hello(cli):
+        comma = ',' if cli.config.general.comma else ''
+        cli.log.info('{fg_blue}Hello%s %s!', comma, cli.config.hello.name)
+
+    def goodbye(cli):
+        comma = ',' if cli.config.general.comma else ''
+        cli.log.info('{bg_red}Goodbye%s %s!', comma, cli.config.goodbye.name)
+
+    @cli.argument('-n', '--name', help='Name to greet', default='World')
+    @cli.subcommand('Think a bit before greeting the user.')
+    def thinking(cli):
+        comma = ',' if cli.config.general.comma else ''
+        spinner = cli.spinner(text='Just a moment...', spinner='earth')
+        spinner.start()
+        sleep(2)
+        spinner.stop()
+
+        with cli.spinner(text='Almost there!', spinner='moon'):
             sleep(2)
-            spinner.stop()
-
-            with cli.spinner(text='Almost there!', spinner='moon'):
-                sleep(2)
-
-            cli.log.info('{fg_cyan}Hello%s %s!', comma, cli.config.thinking.name)
-
-        @cli.subcommand('Show off our ANSI colors.')
-        def pride(cli):
-            cli.echo('{bg_red}                    ')
-            cli.echo('{bg_lightred_ex}                    ')
-            cli.echo('{bg_lightyellow_ex}                    ')
-            cli.echo('{bg_green}                    ')
-            cli.echo('{bg_blue}                    ')
-            cli.echo('{bg_magenta}                    ')
-
-        if __name__ == '__main__':
-            # You can register subcommands using decorators as seen above,
-            # or using functions like like this:
-            cli.add_subcommand(goodbye, 'This will show up in --help output.')
-            cli.goodbye.add_argument('-n', '--name', help='Name to bid farewell to', default='World')
-
-            cli()  # Automatically picks between main(), hello() and goodbye()
-            print(sorted(ansi_colors.keys()))
+
+        cli.log.info('{fg_cyan}Hello%s %s!', comma, cli.config.thinking.name)
+
+    @cli.subcommand('Show off our ANSI colors.')
+    def pride(cli):
+        cli.echo('{bg_red}                    ')
+        cli.echo('{bg_lightred_ex}                    ')
+        cli.echo('{bg_lightyellow_ex}                    ')
+        cli.echo('{bg_green}                    ')
+        cli.echo('{bg_blue}                    ')
+        cli.echo('{bg_magenta}                    ')
+
+    # You can register subcommands using decorators as seen above, or using functions like like this:
+    cli.add_subcommand(goodbye, 'This will show up in --help output.')
+    cli.goodbye.add_argument('-n', '--name', help='Name to bid farewell to', default='World')
+
+    cli()  # Automatically picks between main(), hello() and goodbye()
+    print(sorted(ansi_colors.keys()))

+ 1 - 0
lib/python/qmk/compile/json.py

@@ -8,6 +8,7 @@ import subprocess
 import qmk.keymap
 from milc import cli
 
+
 @cli.argument('-f', '--filename', help='Configurator JSON export', required=True)  # FIXME: This should be positional
 @cli.entrypoint('Generate a keymap.c from a QMK Configurator export.')
 def main(cli):

+ 1 - 0
lib/python/qmk/errors.py

@@ -5,5 +5,6 @@ class Error(Exception):
 class NoSuchKeyboardError(Error):
     """Raised when we can't find a keyboard/keymap directory.
     """
+
     def __init__(self, message):
         self.message = message

+ 1 - 0
lib/python/qmk/json/keymap.py

@@ -7,6 +7,7 @@ import sys
 import qmk.keymap
 from milc import cli
 
+
 @cli.argument('-f', '--filename', help='Configurator JSON export', required=True)  # FIXME: This should be positional
 @cli.argument('-o', '--output', help='File to write to')
 @cli.entrypoint('Generate a keymap.c from a QMK Configurator export.')

+ 6 - 4
lib/python/qmk/keymap.py

@@ -47,7 +47,7 @@ def template(keyboard, keymap):
 
     return DEFAULT_KEYMAP_C.replace('__KEYMAP_GOES_HERE__', keymap)
 
-    
+
 def generate(keyboard, layout, layers):
     """Generate the keymap source code.
     """
@@ -93,7 +93,7 @@ def compile_firmware(keyboard, keymap, layout, layers):
         'returncode': -2,
         'output': '',
         'firmware': None,
-        'firmware_filename': ''
+        'firmware_filename': '',
     }
 
     try:
@@ -106,8 +106,10 @@ def compile_firmware(keyboard, keymap, layout, layers):
             logging.error('Unknown keyboard: %s', keyboard)
             return {'returncode': -1, 'command': '', 'output': 'Unknown keyboard!', 'firmware': None}
 
-        for pathname in ('qmk_firmware/keyboards/%s/keymaps/%s' % (keyboard, keymap),
-                         'qmk_firmware/keyboards/%s/../keymaps/%s' % (keyboard, keymap)):
+        for pathname in (
+            'qmk_firmware/keyboards/%s/keymaps/%s' % (keyboard, keymap),
+            'qmk_firmware/keyboards/%s/../keymaps/%s' % (keyboard, keymap),
+        ):
             if os.path.exists(pathname):
                 logging.error('Name collision! %s already exists! This should not happen!', pathname)
                 return {'returncode': -1, 'command': '', 'output': 'Keymap name collision! %s already exists!' % (pathname), 'firmware': None}

+ 330 - 0
setup.cfg

@@ -0,0 +1,330 @@
+# Python settings for QMK
+
+[yapf]
+# Align closing bracket with visual indentation.
+align_closing_bracket_with_visual_indent=True
+
+# Allow dictionary keys to exist on multiple lines. For example:
+#
+#   x = {
+#       ('this is the first element of a tuple',
+#        'this is the second element of a tuple'):
+#            value,
+#   }
+allow_multiline_dictionary_keys=False
+
+# Allow lambdas to be formatted on more than one line.
+allow_multiline_lambdas=False
+
+# Allow splitting before a default / named assignment in an argument list.
+allow_split_before_default_or_named_assigns=True
+
+# Allow splits before the dictionary value.
+allow_split_before_dict_value=True
+
+#   Let spacing indicate operator precedence. For example:
+#
+#     a = 1 * 2 + 3 / 4
+#     b = 1 / 2 - 3 * 4
+#     c = (1 + 2) * (3 - 4)
+#     d = (1 - 2) / (3 + 4)
+#     e = 1 * 2 - 3
+#     f = 1 + 2 + 3 + 4
+#
+# will be formatted as follows to indicate precedence:
+#
+#     a = 1*2 + 3/4
+#     b = 1/2 - 3*4
+#     c = (1+2) * (3-4)
+#     d = (1-2) / (3+4)
+#     e = 1*2 - 3
+#     f = 1 + 2 + 3 + 4
+#
+arithmetic_precedence_indication=True
+
+# Number of blank lines surrounding top-level function and class
+# definitions.
+blank_lines_around_top_level_definition=2
+
+# Insert a blank line before a class-level docstring.
+blank_line_before_class_docstring=False
+
+# Insert a blank line before a module docstring.
+blank_line_before_module_docstring=False
+
+# Insert a blank line before a 'def' or 'class' immediately nested
+# within another 'def' or 'class'. For example:
+#
+#   class Foo:
+#                      # <------ this blank line
+#     def method():
+#       ...
+blank_line_before_nested_class_or_def=False
+
+# Do not split consecutive brackets. Only relevant when
+# dedent_closing_brackets is set. For example:
+#
+#    call_func_that_takes_a_dict(
+#        {
+#            'key1': 'value1',
+#            'key2': 'value2',
+#        }
+#    )
+#
+# would reformat to:
+#
+#    call_func_that_takes_a_dict({
+#        'key1': 'value1',
+#        'key2': 'value2',
+#    })
+coalesce_brackets=True
+
+# The column limit.
+column_limit=256
+
+# The style for continuation alignment. Possible values are:
+#
+# - SPACE: Use spaces for continuation alignment. This is default behavior.
+# - FIXED: Use fixed number (CONTINUATION_INDENT_WIDTH) of columns
+#   (ie: CONTINUATION_INDENT_WIDTH/INDENT_WIDTH tabs) for continuation
+#   alignment.
+# - VALIGN-RIGHT: Vertically align continuation lines with indent
+#   characters. Slightly right (one more indent character) if cannot
+#   vertically align continuation lines with indent characters.
+#
+# For options FIXED, and VALIGN-RIGHT are only available when USE_TABS is
+# enabled.
+continuation_align_style=SPACE
+
+# Indent width used for line continuations.
+continuation_indent_width=4
+
+# Put closing brackets on a separate line, dedented, if the bracketed
+# expression can't fit in a single line. Applies to all kinds of brackets,
+# including function definitions and calls. For example:
+#
+#   config = {
+#       'key1': 'value1',
+#       'key2': 'value2',
+#   }        # <--- this bracket is dedented and on a separate line
+#
+#   time_series = self.remote_client.query_entity_counters(
+#       entity='dev3246.region1',
+#       key='dns.query_latency_tcp',
+#       transform=Transformation.AVERAGE(window=timedelta(seconds=60)),
+#       start_ts=now()-timedelta(days=3),
+#       end_ts=now(),
+#   )        # <--- this bracket is dedented and on a separate line
+dedent_closing_brackets=True
+
+# Disable the heuristic which places each list element on a separate line
+# if the list is comma-terminated.
+disable_ending_comma_heuristic=False
+
+# Place each dictionary entry onto its own line.
+each_dict_entry_on_separate_line=True
+
+# The regex for an i18n comment. The presence of this comment stops
+# reformatting of that line, because the comments are required to be
+# next to the string they translate.
+i18n_comment=
+
+# The i18n function call names. The presence of this function stops
+# reformattting on that line, because the string it has cannot be moved
+# away from the i18n comment.
+i18n_function_call=
+
+# Indent blank lines.
+indent_blank_lines=False
+
+# Indent the dictionary value if it cannot fit on the same line as the
+# dictionary key. For example:
+#
+#   config = {
+#       'key1':
+#           'value1',
+#       'key2': value1 +
+#               value2,
+#   }
+indent_dictionary_value=True
+
+# The number of columns to use for indentation.
+indent_width=4
+
+# Join short lines into one line. E.g., single line 'if' statements.
+join_multiple_lines=False
+
+# Do not include spaces around selected binary operators. For example:
+#
+#   1 + 2 * 3 - 4 / 5
+#
+# will be formatted as follows when configured with "*,/":
+#
+#   1 + 2*3 - 4/5
+no_spaces_around_selected_binary_operators=
+
+# Use spaces around default or named assigns.
+spaces_around_default_or_named_assign=False
+
+# Use spaces around the power operator.
+spaces_around_power_operator=False
+
+# The number of spaces required before a trailing comment.
+# This can be a single value (representing the number of spaces
+# before each trailing comment) or list of values (representing
+# alignment column values; trailing comments within a block will
+# be aligned to the first column value that is greater than the maximum
+# line length within the block). For example:
+#
+# With spaces_before_comment=5:
+#
+#   1 + 1 # Adding values
+#
+# will be formatted as:
+#
+#   1 + 1     # Adding values <-- 5 spaces between the end of the statement and comment
+#
+# With spaces_before_comment=15, 20:
+#
+#   1 + 1 # Adding values
+#   two + two # More adding
+#
+#   longer_statement # This is a longer statement
+#   short # This is a shorter statement
+#
+#   a_very_long_statement_that_extends_beyond_the_final_column # Comment
+#   short # This is a shorter statement
+#
+# will be formatted as:
+#
+#   1 + 1          # Adding values <-- end of line comments in block aligned to col 15
+#   two + two      # More adding
+#
+#   longer_statement    # This is a longer statement <-- end of line comments in block aligned to col 20
+#   short               # This is a shorter statement
+#
+#   a_very_long_statement_that_extends_beyond_the_final_column  # Comment <-- the end of line comments are aligned based on the line length
+#   short                                                       # This is a shorter statement
+#
+spaces_before_comment=2
+
+# Insert a space between the ending comma and closing bracket of a list,
+# etc.
+space_between_ending_comma_and_closing_bracket=False
+
+# Split before arguments
+split_all_comma_separated_values=False
+
+# Split before arguments if the argument list is terminated by a
+# comma.
+split_arguments_when_comma_terminated=True
+
+# Set to True to prefer splitting before '+', '-', '*', '/', '//', or '@'
+# rather than after.
+split_before_arithmetic_operator=False
+
+# Set to True to prefer splitting before '&', '|' or '^' rather than
+# after.
+split_before_bitwise_operator=True
+
+# Split before the closing bracket if a list or dict literal doesn't fit on
+# a single line.
+split_before_closing_bracket=True
+
+# Split before a dictionary or set generator (comp_for). For example, note
+# the split before the 'for':
+#
+#   foo = {
+#       variable: 'Hello world, have a nice day!'
+#       for variable in bar if variable != 42
+#   }
+split_before_dict_set_generator=True
+
+# Split before the '.' if we need to split a longer expression:
+#
+#   foo = ('This is a really long string: {}, {}, {}, {}'.format(a, b, c, d))
+#
+# would reformat to something like:
+#
+#   foo = ('This is a really long string: {}, {}, {}, {}'
+#          .format(a, b, c, d))
+split_before_dot=False
+
+# Split after the opening paren which surrounds an expression if it doesn't
+# fit on a single line.
+split_before_expression_after_opening_paren=False
+
+# If an argument / parameter list is going to be split, then split before
+# the first argument.
+split_before_first_argument=False
+
+# Set to True to prefer splitting before 'and' or 'or' rather than
+# after.
+split_before_logical_operator=False
+
+# Split named assignments onto individual lines.
+split_before_named_assigns=True
+
+# Set to True to split list comprehensions and generators that have
+# non-trivial expressions and multiple clauses before each of these
+# clauses. For example:
+#
+#   result = [
+#       a_long_var + 100 for a_long_var in xrange(1000)
+#       if a_long_var % 10]
+#
+# would reformat to something like:
+#
+#   result = [
+#       a_long_var + 100
+#       for a_long_var in xrange(1000)
+#       if a_long_var % 10]
+split_complex_comprehension=True
+
+# The penalty for splitting right after the opening bracket.
+split_penalty_after_opening_bracket=300
+
+# The penalty for splitting the line after a unary operator.
+split_penalty_after_unary_operator=10000
+
+# The penalty of splitting the line around the '+', '-', '*', '/', '//',
+# ``%``, and '@' operators.
+split_penalty_arithmetic_operator=300
+
+# The penalty for splitting right before an if expression.
+split_penalty_before_if_expr=0
+
+# The penalty of splitting the line around the '&', '|', and '^'
+# operators.
+split_penalty_bitwise_operator=300
+
+# The penalty for splitting a list comprehension or generator
+# expression.
+split_penalty_comprehension=80
+
+# The penalty for characters over the column limit.
+split_penalty_excess_character=7000
+
+# The penalty incurred by adding a line split to the unwrapped line. The
+# more line splits added the higher the penalty.
+split_penalty_for_added_line_split=30
+
+# The penalty of splitting a list of "import as" names. For example:
+#
+#   from a_very_long_or_indented_module_name_yada_yad import (long_argument_1,
+#                                                             long_argument_2,
+#                                                             long_argument_3)
+#
+# would reformat to something like:
+#
+#   from a_very_long_or_indented_module_name_yada_yad import (
+#       long_argument_1, long_argument_2, long_argument_3)
+split_penalty_import_names=0
+
+# The penalty of splitting the line around the 'and' and 'or'
+# operators.
+split_penalty_logical_operator=300
+
+# Use the Tab character for indentation.
+use_tabs=False
+