Skip to content

Commit ef615f2

Browse files
authored
Ruff Linting (#1314)
* Disable all linters for now and slowly add them back * Disable more unneeded linter rules * Enabled linters with 0 issues * Fixes for flake8-async linter * Add ignored variable names * Fixes for refurb linter * Fixes for flake8-implicit-str-concat * Fixes for flake8-import-conventions * Fixes for flake8-future-annotations * Fixes for flake8-pyi * Remove blanket noqa statements to fix (pygrep-hooks) * Remove large batch of unused noqa F401 * Fixes for flake8-builtins * Misc rule fixes * Fixes for flake8-logging-format * Fixes for flake8-raise * Fixes for Perflint * Sort imports with isort * Format with ruff * Reorganize disabled rules list * Update megalinter in CI (to update ruff) * Update MegaLinter workflow
1 parent 9429694 commit ef615f2

File tree

448 files changed

+903
-1382
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

448 files changed

+903
-1382
lines changed

.github/workflows/mega-linter.yml

+31-41
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,14 @@
11
---
2-
# Mega-Linter GitHub Action configuration file
3-
# More info at https://oxsecurity.github.io/megalinter
4-
name: Mega-Linter
2+
# MegaLinter GitHub Action configuration file
3+
# More info at https://megalinter.io
4+
name: MegaLinter
55

66
on:
77
# Trigger mega-linter at every push. Action will also be visible from Pull Requests to main
88
# push: # Comment this line to trigger action only on pull-requests (not recommended if you don't pay for GH Actions)
99
pull_request:
1010

11-
env: # Comment env block if you do not want to apply fixes
11+
env: # Comment env block if you don't want to apply fixes
1212
# Apply linter fixes configuration
1313
APPLY_FIXES: all # When active, APPLY_FIXES must also be defined as environment variable (in github/workflows/mega-linter.yml or other CI tool)
1414
APPLY_FIXES_EVENT: pull_request # Decide which event triggers application of fixes in a commit or a PR (pull_request, push, all)
@@ -19,66 +19,56 @@ concurrency:
1919
cancel-in-progress: true
2020

2121
jobs:
22-
build:
23-
name: Mega-Linter
22+
megalinter:
23+
name: MegaLinter
2424
runs-on: ubuntu-22.04
25+
permissions:
26+
# Give the default GITHUB_TOKEN write permission to commit and push, comment issues & post new PR
27+
# Remove the ones you do not need
28+
contents: write
29+
issues: write
30+
pull-requests: write
2531
steps:
2632
# Git Checkout
2733
- name: Checkout Code
28-
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # 4.1.1
34+
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # 4.2.2
2935
with:
3036
token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
31-
fetch-depth: 0
3237

33-
# Mega-Linter
34-
- name: Mega-Linter
38+
# MegaLinter
39+
- name: MegaLinter
3540
id: ml
36-
# You can override Mega-Linter flavor used to have faster performances
37-
# More info at https://oxsecurity.github.io/megalinter/flavors/
38-
uses: oxsecurity/megalinter/flavors/python@a7a0163b6c8ff7474a283d99a706e27483ddd80f # 7.10.0
41+
# You can override MegaLinter flavor used to have faster performances
42+
# More info at https://megalinter.io/flavors/
43+
uses: oxsecurity/megalinter/flavors/python@ec124f7998718d79379a3c5b39f5359952baf21d # 8.4.2
3944
env:
4045
# All available variables are described in documentation
41-
# https://oxsecurity.github.io/megalinter/configuration/
42-
VALIDATE_ALL_CODEBASE: ${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }} # Validates all source when push on main, else just the git diff with main. Set 'true' if you always want to lint all sources
43-
DEFAULT_BRANCH: ${{ github.event_name == 'pull_request' && github.base_ref || 'main' }}
46+
# https://megalinter.io/configuration/
47+
VALIDATE_ALL_CODEBASE: "true"
4448
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
45-
# ADD YOUR CUSTOM ENV VARIABLES HERE TO OVERRIDE VALUES OF .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
46-
PYTHON_RUFF_ARGUMENTS: '--config=''output-format="github"'''
47-
PYTHON_RUFF_FORMAT_ARGUMENTS: '--config=''output-format="github"'''
49+
# ADD YOUR CUSTOM ENV VARIABLES HERE OR DEFINE THEM IN A FILE .mega-linter.yml AT THE ROOT OF YOUR REPOSITORY
50+
PYTHON_RUFF_ARGUMENTS: --config pyproject.toml --config 'output-format="github"'
51+
PYTHON_RUFF_FORMAT_ARGUMENTS: --config pyproject.toml --config 'output-format="github"'
4852

49-
# Upload Mega-Linter artifacts
53+
# Upload MegaLinter artifacts
5054
- name: Archive production artifacts
51-
if: ${{ success() }} || ${{ failure() }}
52-
uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # 4.3.1
55+
if: success() || failure()
56+
uses: actions/upload-artifact@4cec3d8aa04e39d1a68397de0c4cd6fb9dce8ec1 # 4.6.1
5357
with:
54-
name: Mega-Linter reports
58+
name: MegaLinter reports
5559
path: |
5660
megalinter-reports
5761
mega-linter.log
5862
59-
# Create pull request if applicable (for now works only on PR from same repository, not from forks)
60-
- name: Create Pull Request with applied fixes
61-
id: cpr
62-
if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'pull_request' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
63-
uses: peter-evans/create-pull-request@c55203cfde3e5c11a452d352b4393e68b85b4533 # 6.0.3
64-
with:
65-
token: ${{ secrets.PAT || secrets.GITHUB_TOKEN }}
66-
commit-message: "[Mega-Linter] Apply linters automatic fixes"
67-
title: "[Mega-Linter] Apply linters automatic fixes"
68-
labels: bot
69-
- name: Create PR output
70-
if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'pull_request' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
71-
run: |
72-
echo "Pull Request Number - ${{ steps.cpr.outputs.pull-request-number }}"
73-
echo "Pull Request URL - ${{ steps.cpr.outputs.pull-request-url }}"
74-
7563
# Push new commit if applicable (for now works only on PR from same repository, not from forks)
7664
- name: Prepare commit
7765
if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'commit' && github.ref != 'refs/heads/main' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
7866
run: sudo chown -Rc $UID .git/
7967
- name: Commit and push applied linter fixes
8068
if: steps.ml.outputs.has_updated_sources == 1 && (env.APPLY_FIXES_EVENT == 'all' || env.APPLY_FIXES_EVENT == github.event_name) && env.APPLY_FIXES_MODE == 'commit' && github.ref != 'refs/heads/main' && (github.event_name == 'push' || github.event.pull_request.head.repo.full_name == github.repository) && !contains(github.event.head_commit.message, 'skip fix')
81-
uses: stefanzweifel/git-auto-commit-action@8621497c8c39c72f3e2a999a26b4ca1b5058a842 # 5.0.1
69+
uses: stefanzweifel/git-auto-commit-action@e348103e9026cc0eee72ae06630dbe30c8bf7a79 # 5.1.0
8270
with:
8371
branch: ${{ github.event.pull_request.head.ref || github.head_ref || github.ref }}
84-
commit_message: "[Mega-Linter] Apply linters fixes"
72+
commit_message: "[MegaLinter] Apply linters fixes"
73+
commit_user_name: newrelic-python-agent-team
74+
commit_user_email: [email protected]

.mega-linter.yml

+3-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ DEFAULT_BRANCH: main # Usually master or main
66
SHOW_ELAPSED_TIME: true
77
FILEIO_REPORTER: false
88
PRINT_ALPACA: false
9-
VALIDATE_ALL_CODEBASE: false # only lint new and edited files
9+
VALIDATE_ALL_CODEBASE: true
1010
IGNORE_GITIGNORED_FILES: true
1111
FILTER_REGEX_EXCLUDE: "(.*/?packages/.*)" # Ignore packages directories
1212

@@ -23,4 +23,6 @@ ENABLE_LINTERS: # If you use ENABLE_LINTERS variable, all other linters will be
2323
- YAML_YAMLLINT
2424

2525
PYTHON_RUFF_CONFIG_FILE: pyproject.toml
26+
PYTHON_RUFF_CLI_LINT_MODE: project
2627
PYTHON_RUFF_FORMAT_CONFIG_FILE: pyproject.toml
28+
PYTHON_RUFF_FORMAT_CLI_LINT_MODE: project

newrelic/admin/__init__.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,7 @@ def usage(name):
5353

5454

5555
@command("help", "[command]", hidden=True)
56-
def help(args):
56+
def help_(args):
5757
if not args:
5858
print("Usage: newrelic-admin command [options]")
5959
print()
@@ -125,7 +125,7 @@ def load_external_plugins():
125125
if sys.version_info >= (3, 10):
126126
from importlib.metadata import entry_points
127127
# Introduced in Python 3.8
128-
elif sys.version_info >= (3, 8) and sys.version_info <= (3, 9):
128+
elif sys.version_info >= (3, 8) and sys.version_info < (3, 9):
129129
from importlib_metadata import entry_points
130130
# Removed in Python 3.12
131131
else:

newrelic/admin/local_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
from <config_file>.""",
2323
)
2424
def local_config(args):
25+
import logging
2526
import os
2627
import sys
27-
import logging
2828

2929
if len(args) == 0:
3030
usage("local-config")

newrelic/admin/network_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,9 @@
2222
from <config_file>.""",
2323
)
2424
def network_config(args):
25+
import logging
2526
import os
2627
import sys
27-
import logging
2828

2929
if len(args) == 0:
3030
usage("network-config")

newrelic/admin/run_python.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,8 @@ def log_message(text, *args):
6161
if name.startswith("NEW_RELIC_") or name.startswith("PYTHON"):
6262
log_message("%s = %r", name, os.environ.get(name))
6363

64-
from newrelic import version, __file__ as root_directory
64+
from newrelic import __file__ as root_directory
65+
from newrelic import version
6566

6667
root_directory = os.path.dirname(root_directory)
6768
boot_directory = os.path.join(root_directory, "bootstrap")

newrelic/admin/server_config.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@
2424
configuration file is used.""",
2525
)
2626
def server_config(args):
27+
import logging
2728
import os
2829
import sys
29-
import logging
3030
import time
3131

3232
if len(args) == 0:

newrelic/api/cat_header_mixin.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@
1313
# limitations under the License.
1414

1515
from newrelic.common.encoding_utils import (
16-
obfuscate,
16+
base64_decode,
17+
base64_encode,
1718
deobfuscate,
18-
json_encode,
1919
json_decode,
20-
base64_encode,
21-
base64_decode,
20+
json_encode,
21+
obfuscate,
2222
)
2323

2424

newrelic/api/generator_trace.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,13 @@
1313
# limitations under the License.
1414

1515
import functools
16-
import types
1716
import sys
17+
import types
1818

19-
from newrelic.api.time_trace import current_trace
2019
from newrelic.api.function_trace import FunctionTrace
21-
from newrelic.common.object_wrapper import FunctionWrapper, wrap_object
20+
from newrelic.api.time_trace import current_trace
2221
from newrelic.common.object_names import callable_name
22+
from newrelic.common.object_wrapper import FunctionWrapper, wrap_object
2323

2424

2525
def GeneratorTraceWrapper(wrapped, name=None, group=None, label=None, params=None):

newrelic/api/html_insertion.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
_head_re = re.compile(b"<head[^>]*>", re.IGNORECASE)
1818

19-
_xua_meta_re = re.compile(b"""<\\s*meta[^>]+http-equiv\\s*=\\s*['"]""" b"""x-ua-compatible['"][^>]*>""", re.IGNORECASE)
19+
_xua_meta_re = re.compile(b"""<\\s*meta[^>]+http-equiv\\s*=\\s*['"]x-ua-compatible['"][^>]*>""", re.IGNORECASE)
2020

2121
_charset_meta_re = re.compile(b"""<\\s*meta[^>]+charset\\s*=[^>]*>""", re.IGNORECASE)
2222

newrelic/api/import_hook.py

+1-3
Original file line numberDiff line numberDiff line change
@@ -14,10 +14,8 @@
1414

1515
import logging
1616
import sys
17-
1817
from importlib.util import find_spec
1918

20-
2119
_logger = logging.getLogger(__name__)
2220

2321

@@ -57,7 +55,7 @@
5755
_uninstrumented_modules = set()
5856

5957

60-
def register_import_hook(name, callable): # pylint: disable=redefined-builtin
58+
def register_import_hook(name, callable): # noqa: A002
6159
hooks = _import_hooks.get(name, None)
6260

6361
if name not in _import_hooks or hooks is None:

newrelic/api/in_function.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@
1414

1515
# Use of these from this module will be deprecated.
1616

17-
from newrelic.common.object_wrapper import in_function, InFunctionWrapper, wrap_in_function
17+
from newrelic.common.object_wrapper import InFunctionWrapper, in_function, wrap_in_function

newrelic/api/lambda_handler.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -14,14 +14,14 @@
1414

1515
import functools
1616
import warnings
17-
from newrelic.common.object_wrapper import FunctionWrapper
17+
18+
from newrelic.api.application import application_instance
1819
from newrelic.api.transaction import current_transaction
1920
from newrelic.api.web_transaction import WebTransaction
20-
from newrelic.api.application import application_instance
21+
from newrelic.common.object_wrapper import FunctionWrapper
2122
from newrelic.core.attribute import truncate
2223
from newrelic.core.config import global_settings
2324

24-
2525
COLD_START_RECORDED = False
2626
MEGABYTE_IN_BYTES = 2**20
2727

newrelic/api/ml_model.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,8 @@ def _wrap_callback(model, content):
116116

117117
if not isinstance(token_count_val, int) or token_count_val < 0:
118118
_logger.warning(
119-
f"llm_token_count_callback returned an invalid value of {token_count_val}. This value must be a positive integer and will not be recorded for the token_count."
119+
"llm_token_count_callback returned an invalid value of %s. This value must be a positive integer and will not be recorded for the token_count.",
120+
token_count_val,
120121
)
121122
return None
122123

newrelic/api/object_wrapper.py

-1
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,6 @@
1717
# These have been moved. They are retained here until all references to
1818
# them are moved at which point will mark as deprecated to ensure users
1919
# weren't using them directly.
20-
2120
from newrelic.common.object_names import callable_name
2221
from newrelic.common.object_wrapper import ObjectWrapper, wrap_object
2322

newrelic/api/out_function.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@
1414

1515
# Use of these from this module will be deprecated.
1616

17-
from newrelic.common.object_wrapper import out_function, OutFunctionWrapper, wrap_out_function
17+
from newrelic.common.object_wrapper import OutFunctionWrapper, out_function, wrap_out_function

newrelic/api/post_function.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@
1414

1515
# Use of these from this module will be deprecated.
1616

17-
from newrelic.common.object_wrapper import post_function, PostFunctionWrapper, wrap_post_function
17+
from newrelic.common.object_wrapper import PostFunctionWrapper, post_function, wrap_post_function

newrelic/api/pre_function.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,4 +14,4 @@
1414

1515
# Use of these from this module will be deprecated.
1616

17-
from newrelic.common.object_wrapper import pre_function, PreFunctionWrapper, wrap_pre_function
17+
from newrelic.common.object_wrapper import PreFunctionWrapper, pre_function, wrap_pre_function

newrelic/api/profile_trace.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def _callable():
7070
except Exception:
7171
pass
7272

73-
for name, obj in frame.f_globals.items():
73+
for obj in frame.f_globals.values():
7474
try:
7575
if obj.__dict__[func_name].func_code is co:
7676
return obj.__dict__[func_name]

newrelic/api/time_trace.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,9 @@ def add_code_level_metrics(self, source):
211211
node.add_attrs(self._add_agent_attribute)
212212
except Exception as exc:
213213
_logger.debug(
214-
f"Failed to extract source code context from callable {source}. Report this issue to newrelic support. Exception: {exc}"
214+
"Failed to extract source code context from callable %s. Report this issue to newrelic support. Exception: %s",
215+
source,
216+
exc,
215217
)
216218

217219
def _observe_exception(self, exc_info=None, ignore=None, expected=None, status_code=None):

newrelic/api/transaction.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -1871,7 +1871,7 @@ def capture_request_params(flag=True):
18711871
transaction = current_transaction()
18721872
if transaction and transaction.settings:
18731873
if transaction.settings.high_security:
1874-
_logger.warn("Cannot modify capture_params in High Security Mode.")
1874+
_logger.warning("Cannot modify capture_params in High Security Mode.")
18751875
else:
18761876
transaction.capture_params = flag
18771877

newrelic/api/transaction_name.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,8 @@
1515
import functools
1616

1717
from newrelic.api.transaction import current_transaction
18-
from newrelic.common.object_wrapper import FunctionWrapper, wrap_object
1918
from newrelic.common.object_names import callable_name
19+
from newrelic.common.object_wrapper import FunctionWrapper, wrap_object
2020

2121

2222
def TransactionNameWrapper(wrapped, name=None, group=None, priority=None):

newrelic/api/web_transaction.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,8 @@
1515
import functools
1616
import logging
1717
import time
18-
import warnings
19-
2018
import urllib.parse as urlparse
19+
import warnings
2120

2221
from newrelic.api.application import Application, application_instance
2322
from newrelic.api.transaction import Transaction, current_transaction

newrelic/api/wsgi_application.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ def close(self):
9696

9797

9898
class _WSGIInputWrapper:
99-
def __init__(self, transaction, input):
99+
def __init__(self, transaction, input): # noqa: A002
100100
self.__transaction = transaction
101101
self.__input = input
102102

newrelic/common/async_proxy.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@
1515
import logging
1616
import time
1717

18-
from newrelic.common.coroutine import is_coroutine_callable, is_asyncio_coroutine, is_generator_function
18+
from newrelic.common.coroutine import is_asyncio_coroutine, is_coroutine_callable, is_generator_function
1919
from newrelic.common.object_wrapper import ObjectProxy
2020
from newrelic.core.trace_cache import trace_cache
2121

newrelic/common/async_wrapper.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -13,11 +13,12 @@
1313
# limitations under the License.
1414

1515
import functools
16+
1617
from newrelic.common.coroutine import (
17-
is_coroutine_callable,
18+
is_async_generator_function,
1819
is_asyncio_coroutine,
20+
is_coroutine_callable,
1921
is_generator_function,
20-
is_async_generator_function,
2122
)
2223

2324

0 commit comments

Comments
 (0)