Skip to content

Commit

Permalink
fixing R rules
Browse files Browse the repository at this point in the history
  • Loading branch information
Borda committed Sep 23, 2024
1 parent 27190ff commit dca6c8f
Show file tree
Hide file tree
Showing 14 changed files with 56 additions and 66 deletions.
2 changes: 1 addition & 1 deletion .github/scripts/build.sh
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ python setup.py develop
python -m pytest # Run the tests without IPython.
pip install ipython
python -m pytest # Now run the tests with IPython.
pre-commit run --all-files
pre-commit run --all-files --show-diff-on-failure --
if [[ ${PYTHON_VERSION} == 3.7 ]]; then
# Run type-checking.
pip install pytype;
Expand Down
5 changes: 2 additions & 3 deletions fire/completion.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,7 @@ def _BashScript(name, commands, default_options=None):
def _GetOptsAssignmentTemplate(command):
if command == name:
return opts_assignment_main_command_template
else:
return opts_assignment_subcommand_template
return opts_assignment_subcommand_template

lines = []
commands_set = set()
Expand Down Expand Up @@ -281,7 +280,7 @@ def _FishScript(name, commands, default_options=None):
)


def MemberVisible(component, name, member, class_attrs=None, verbose=False):
def MemberVisible(component, name, member, class_attrs=None, verbose=False): # noqa: C901
"""Returns whether a member should be included in auto-completion or help.
Determines whether a member of an object with the specified name should be
Expand Down
11 changes: 5 additions & 6 deletions fire/console/console_attr.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,7 +314,7 @@ def _GetConsoleEncoding(self):
console_encoding = console_encoding.lower()
if 'utf-8' in console_encoding:
return 'utf8'
elif 'cp437' in console_encoding:
if 'cp437' in console_encoding:
return 'cp437'
return None

Expand Down Expand Up @@ -700,15 +700,14 @@ def GetCharacterDisplayWidth(char):
if unicodedata.combining(char) != 0:
# Modifies the previous character and does not move the cursor.
return 0
elif unicodedata.category(char) == 'Cf':
if unicodedata.category(char) == 'Cf':
# Unprintable formatting char.
return 0
elif unicodedata.east_asian_width(char) in 'FW':
if unicodedata.east_asian_width(char) in 'FW':
# Fullwidth or Wide chars take 2 character positions.
return 2
else:
# Don't use this function on control chars.
return 1
# Don't use this function on control chars.
return 1


def SafeText(data, encoding=None, escape=True):
Expand Down
4 changes: 2 additions & 2 deletions fire/console/console_pager.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def _Help(self):
self._attr.GetRawKey()
self._Write('\n')

def Run(self):
def Run(self): # noqa: C901
"""Run the pager."""
# No paging if the contents are small enough.
if len(self._lines) <= self._height:
Expand Down Expand Up @@ -215,7 +215,7 @@ def Run(self):
):
# Quit.
return
elif c in ('/', '?'):
if c in ('/', '?'):
c = self._GetSearchCommand(c)
elif c.isdigit():
# Collect digits for operation count.
Expand Down
3 changes: 1 addition & 2 deletions fire/console/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,8 +66,7 @@ def _FindExecutableOnPath(executable, path, pathext):
def _PlatformExecutableExtensions(platform):
if platform == platforms.OperatingSystem.WINDOWS:
return ('.exe', '.cmd', '.bat', '.com', '.ps1')
else:
return ('', '.sh')
return ('', '.sh')


def FindExecutableOnPath(executable, path=None, pathext=None,
Expand Down
22 changes: 10 additions & 12 deletions fire/console/platforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,13 @@ def Current():
"""
if os.name == 'nt':
return OperatingSystem.WINDOWS
elif 'linux' in sys.platform:
if 'linux' in sys.platform:
return OperatingSystem.LINUX
elif 'darwin' in sys.platform:
if 'darwin' in sys.platform:
return OperatingSystem.MACOSX
elif 'cygwin' in sys.platform:
if 'cygwin' in sys.platform:
return OperatingSystem.CYGWIN
elif 'msys' in sys.platform:
if 'msys' in sys.platform:
return OperatingSystem.MSYS
return None

Expand Down Expand Up @@ -323,12 +323,12 @@ def UserAgentFragment(self):
# '#1 SMP Tue May 21 02:35:06 PDT 2013', 'x86_64', 'x86_64')
return '({name} {version})'.format(
name=self.operating_system.name, version=platform.release())
elif self.operating_system == OperatingSystem.WINDOWS:
if self.operating_system == OperatingSystem.WINDOWS:
# ('Windows', '<hostname goes here>', '7', '6.1.7601', 'AMD64',
# 'Intel64 Family 6 Model 45 Stepping 7, GenuineIntel')
return '({name} NT {version})'.format(
name=self.operating_system.name, version=platform.version())
elif self.operating_system == OperatingSystem.MACOSX:
if self.operating_system == OperatingSystem.MACOSX:
# ('Darwin', '<hostname goes here>', '12.4.0',
# 'Darwin Kernel Version 12.4.0: Wed May 1 17:57:12 PDT 2013;
# root:xnu-2050.24.15~1/RELEASE_X86_64', 'x86_64', 'i386')
Expand All @@ -337,8 +337,7 @@ def UserAgentFragment(self):
if self.architecture == Architecture.ppc else 'Intel')
return format_string.format(
name=arch_string, version=platform.release())
else:
return '()'
return '()'

def AsyncPopenArgs(self):
"""Returns the args for spawning an async process using Popen on this OS.
Expand Down Expand Up @@ -413,10 +412,9 @@ def SupportedVersionMessage(self, allow_py3):
PythonVersion.MIN_SUPPORTED_PY2_VERSION[1],
PythonVersion.MIN_SUPPORTED_PY3_VERSION[0],
PythonVersion.MIN_SUPPORTED_PY3_VERSION[1])
else:
return 'Please use Python version {0}.{1}.x.'.format(
PythonVersion.MIN_SUPPORTED_PY2_VERSION[0],
PythonVersion.MIN_SUPPORTED_PY2_VERSION[1])
return 'Please use Python version {0}.{1}.x.'.format(
PythonVersion.MIN_SUPPORTED_PY2_VERSION[0],
PythonVersion.MIN_SUPPORTED_PY2_VERSION[1])

def IsCompatible(self, allow_py3=False, raise_exception=False):
"""Ensure that the Python version we are using is compatible.
Expand Down
9 changes: 4 additions & 5 deletions fire/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ def Fire(component=None, command=None, name=None, serialize=None):
# The command succeeded normally; print the result.
_PrintResult(
component_trace, verbose=component_trace.verbose, serialize=serialize)
result = component_trace.GetResult()
return result
return component_trace.GetResult()


def Display(lines, out):
Expand Down Expand Up @@ -236,7 +235,7 @@ def _IsHelpShortcut(component_trace, remaining_args):
return show_help


def _PrintResult(component_trace, verbose=False, serialize=None):
def _PrintResult(component_trace, verbose=False, serialize=None): # noqa: C901
"""Prints the result of the Fire call to stdout in a human readable way."""
# TODO(dbieber): Design human readable deserializable serialization method
# and move serialization to its own module.
Expand Down Expand Up @@ -358,7 +357,7 @@ def _OneLineResult(result):
return str(result).replace('\n', ' ')


def _Fire(component, args, parsed_flag_args, context, name=None):
def _Fire(component, args, parsed_flag_args, context, name=None): # noqa: C901
"""Execute a Fire command on a target component using the args supplied.
Arguments that come after a final isolated '--' are treated as Flags, eg for
Expand Down Expand Up @@ -813,7 +812,7 @@ def _ParseArgs(fn_args, fn_defaults, num_required_args, kwargs,
return parsed_args, kwargs, remaining_args, capacity


def _ParseKeywordArgs(args, fn_spec):
def _ParseKeywordArgs(args, fn_spec): # noqa: C901
"""Parses the supplied arguments for keyword arguments.
Given a list of arguments, finds occurrences of --name value, and uses 'name'
Expand Down
3 changes: 1 addition & 2 deletions fire/decorators.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,8 +98,7 @@ def GetMetadata(fn) -> Dict[str, Any]:
metadata = getattr(fn, FIRE_METADATA, default)
if ACCEPTS_POSITIONAL_ARGS in metadata:
return metadata
else:
return default
return default
except: # noqa: E722
return default

Expand Down
20 changes: 7 additions & 13 deletions fire/docstrings.py
Original file line number Diff line number Diff line change
Expand Up @@ -338,8 +338,7 @@ def _as_arg_name_and_type(text):
type_token = ' '.join(tokens[1:])
type_token = type_token.lstrip('{([').rstrip('])}')
return tokens[0], type_token
else:
return None
return None


def _as_arg_names(names_str):
Expand Down Expand Up @@ -408,7 +407,7 @@ def _consume_google_args_line(line_info, state):
state.current_arg.description.lines.append(split_line[0])


def _consume_line(line_info, state):
def _consume_line(line_info, state): # noqa: C901
"""Consumes one line of text, updating the state accordingly.
When _consume_line is called, part of the line may already have been processed
Expand Down Expand Up @@ -689,17 +688,15 @@ def _get_directive(line_info):
"""
if line_info.stripped.startswith(':'):
return line_info.stripped.split(':', 2)[1]
else:
return None
return None


def _get_after_directive(line_info):
"""Gets the remainder of the line, after a directive."""
sections = line_info.stripped.split(':', 2)
if len(sections) > 2:
return sections[-1]
else:
return ''
return ''


def _rst_section(line_info):
Expand All @@ -717,8 +714,7 @@ def _rst_section(line_info):
if directive:
possible_title = directive.split()[0]
return _section_from_possible_title(possible_title)
else:
return None
return None


def _line_is_hyphens(line):
Expand All @@ -744,8 +740,7 @@ def _numpy_section(line_info):
if next_line_is_hyphens:
possible_title = line_info.remaining
return _section_from_possible_title(possible_title)
else:
return None
return None


def _line_is_numpy_parameter_type(line_info):
Expand All @@ -769,6 +764,5 @@ def _line_is_numpy_parameter_type(line_info):
if ':' in line_info.previous.line and current_indent > previous_indent:
# The parameter type was the previous line; this is the description.
return False
else:
return True
return True
return False
5 changes: 2 additions & 3 deletions fire/helptext.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,8 +160,7 @@ def _DescriptionSection(component, info):
text = description or summary or None
if text:
return ('DESCRIPTION', text)
else:
return None
return None


def _CreateKeywordOnlyFlagItem(flag, docstring_info, spec, short_arg):
Expand All @@ -185,7 +184,7 @@ def _GetShortFlags(flags):
return [v for v in short_flags if short_flag_counts[v] == 1]


def _ArgsAndFlagsSections(info, spec, metadata):
def _ArgsAndFlagsSections(info, spec, metadata): # noqa: C901
"""The "Args and Flags" sections of the help string."""
args_with_no_defaults = spec.args[:len(spec.args) - len(spec.defaults)]
args_with_defaults = spec.args[len(spec.args) - len(spec.defaults):]
Expand Down
5 changes: 2 additions & 3 deletions fire/inspectutils.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class with an __init__ method.
return fn, skip_arg


def Py3GetFullArgSpec(fn):
def Py3GetFullArgSpec(fn): # noqa: C901
"""A alternative to the builtin getfullargspec.
The builtin inspect.getfullargspec uses:
Expand Down Expand Up @@ -326,8 +326,7 @@ def IsNamedTuple(component):
if not isinstance(component, tuple):
return False

has_fields = bool(getattr(component, '_fields', None))
return has_fields
return bool(getattr(component, '_fields', None)) # whether it has files


def GetClassAttrsDict(component):
Expand Down
2 changes: 1 addition & 1 deletion fire/interact_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@


try:
import IPython # noqa: F401
import IPython
INTERACT_METHOD = 'IPython.start_ipython'
except ImportError:
INTERACT_METHOD = 'code.InteractiveConsole'
Expand Down
23 changes: 11 additions & 12 deletions fire/trace.py
Original file line number Diff line number Diff line change
Expand Up @@ -294,15 +294,14 @@ def ErrorAsStr(self):
def __str__(self):
if self.HasError():
return self.ErrorAsStr()
else:
# Format is: {action} "{target}" ({filename}:{lineno})
string = self._action
if self._target is not None:
string += f' "{self._target}"'
if self._filename is not None:
path = self._filename
if self._lineno is not None:
path += f':{self._lineno}'

string += f' ({path})'
return string
# Format is: {action} "{target}" ({filename}:{lineno})
string = self._action
if self._target is not None:
string += f' "{self._target}"'
if self._filename is not None:
path = self._filename
if self._lineno is not None:
path += f':{self._lineno}'

string += f' ({path})'
return string
8 changes: 7 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,13 @@ output = ".pytype"
line-length = 80

# Enable specific rule categories
lint.select = ["E", "F", "W", "RUF100"]
lint.select = [
"E", # Errors
"W", # Warnings
"C", # Conventions
"R", # Refactors
"RUF100", # Remove unused noqas
]

# Exclude specific files and directories
lint.exclude = ["build", "dist", ".venv"]
Expand Down

0 comments on commit dca6c8f

Please sign in to comment.