Skip to content

Commit bc07ecf

Browse files
authored
Run linter with uv run ruff check --fix (#773)
No human-made changes here, only `ruff` linting
1 parent 205f565 commit bc07ecf

33 files changed

Lines changed: 264 additions & 438 deletions

.basedpyright/baseline.json

Lines changed: 66 additions & 234 deletions
Large diffs are not rendered by default.

Makefile

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -15,30 +15,29 @@ upgrade:
1515
$(UV_SYNC_CMD) --dev --upgrade
1616

1717
# Workaround for make being unable to pass arguments to underlying cmd
18-
# $ SDK_DEPS_GROUP="build" make uv-sync-ci
18+
# $ SDK_DEPS_GROUP="build" make ci-install
1919
.PHONY: ci-install
2020
ci-install:
21-
$(UV_SYNC_CMD) --group $(SDK_DEPS_GROUP)
21+
$(UV_SYNC_CMD) --frozen --group $(SDK_DEPS_GROUP)
2222

23-
UV_RUN_CMD := uv run --frozen --no-config
23+
UV_RUN_CMD := uv run
2424
.PHONY: lint
2525
lint: lint-python # TODO: Add mbake
2626

2727
.PHONY: lint-python
2828
lint-python:
29-
$(UV_RUN_CMD) basedpyright
30-
# $(UV_RUN_CMD) ruff check --fix-only
29+
$(UV_RUN_CMD) ruff check --fix-only
3130
$(UV_RUN_CMD) ruff format
31+
$(UV_RUN_CMD) basedpyright
3232

33-
UV_RUN_CMD := uv run --frozen --no-config
3433
.PHONY: ci-lint
3534
ci-lint: ci-lint-python # TODO: Add mbake
3635

3736
.PHONY: ci-lint-python
3837
ci-lint-python:
39-
$(UV_RUN_CMD) basedpyright
40-
# $(UV_RUN_CMD) ruff check
38+
$(UV_RUN_CMD) ruff check --fix-only --exit-non-zero-on-fix
4139
$(UV_RUN_CMD) ruff format --check
40+
$(UV_RUN_CMD) basedpyright
4241

4342
.PHONY: clean
4443
clean:

splunklib/ai/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,8 +28,8 @@
2828
__all__ = [
2929
"Agent",
3030
"AnthropicModel",
31-
"OpenAIModel",
3231
"GoogleModel",
32+
"OpenAIModel",
3333
"create_structured_prompt",
3434
"detect_injection",
3535
"truncate_input",

splunklib/ai/engines/langchain.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,12 +16,12 @@
1616
import logging
1717
import os
1818
import string
19-
from time import monotonic
2019
import uuid
2120
from collections.abc import Awaitable, Callable, Sequence
2221
from dataclasses import asdict, dataclass
2322
from enum import Enum
2423
from functools import partial
24+
from time import monotonic
2525
from typing import Any, cast, final, override
2626

2727
from langchain.agents import create_agent # pyright: ignore[reportUnknownVariableType]
@@ -1909,9 +1909,7 @@ def check_tool_name(type: str, name: str) -> None:
19091909

19101910
last_ai_message: AIMessage | None = None
19111911
for message in messages:
1912-
if type(message) is HumanMessage:
1913-
check_no_pending_calls()
1914-
elif type(message) is SystemMessage:
1912+
if type(message) is HumanMessage or type(message) is SystemMessage:
19151913
check_no_pending_calls()
19161914
elif type(message) is AIMessage:
19171915
last_ai_message = message

splunklib/ai/tools.py

Lines changed: 18 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -296,22 +296,24 @@ async def connect_remote_mcp(
296296
mcp_url = f"{management_url}/services/mcp"
297297
mcp_token = await asyncio.to_thread(lambda: _get_mcp_token(splunk_username, service))
298298
if mcp_token is not None:
299-
async with streamable_http_client(
300-
url=mcp_url,
301-
http_client=httpx.AsyncClient(
302-
headers={
303-
"x-splunk-trace-id": trace_id,
304-
"x-splunk-app-id": app_id,
305-
},
306-
auth=_MCPAuth(f"Bearer {mcp_token}"),
307-
verify=False,
308-
follow_redirects=True,
309-
timeout=httpx.Timeout(_MCP_DEFAULT_TIMEOUT, read=_MCP_DEFAULT_SSE_READ_TIMEOUT),
310-
),
311-
) as (read, write, _):
312-
async with ClientSession(read, write) as session:
313-
await session.initialize()
314-
yield session
299+
async with (
300+
streamable_http_client(
301+
url=mcp_url,
302+
http_client=httpx.AsyncClient(
303+
headers={
304+
"x-splunk-trace-id": trace_id,
305+
"x-splunk-app-id": app_id,
306+
},
307+
auth=_MCPAuth(f"Bearer {mcp_token}"),
308+
verify=False,
309+
follow_redirects=True,
310+
timeout=httpx.Timeout(_MCP_DEFAULT_TIMEOUT, read=_MCP_DEFAULT_SSE_READ_TIMEOUT),
311+
),
312+
) as (read, write, _),
313+
ClientSession(read, write) as session,
314+
):
315+
await session.initialize()
316+
yield session
315317
else:
316318
yield None
317319

splunklib/binding.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -47,14 +47,14 @@
4747

4848
__all__ = [
4949
"AuthenticationError",
50-
"connect",
5150
"Context",
52-
"handler",
5351
"HTTPError",
5452
"UrlEncoded",
53+
"_NoAuthenticationToken",
5554
"_encode",
5655
"_make_cookie_header",
57-
"_NoAuthenticationToken",
56+
"connect",
57+
"handler",
5858
"namespace",
5959
]
6060

@@ -102,7 +102,7 @@ def mask_sensitive_data(data):
102102
if not isinstance(data, dict):
103103
try:
104104
data = json.loads(data)
105-
except Exception as ex:
105+
except Exception:
106106
return data
107107

108108
# json.loads will return "123"(str) as 123(int), so return the data if it's not 'dict' type
@@ -252,7 +252,7 @@ def __mod__(self, fields):
252252
raise TypeError("Cannot interpolate into a UrlEncoded object.")
253253

254254
def __repr__(self):
255-
return f"UrlEncoded({repr(parse.unquote(str(self)))})"
255+
return f"UrlEncoded({parse.unquote(str(self))!r})"
256256

257257

258258
@contextmanager
@@ -1619,7 +1619,7 @@ def request(self, url, message, **kwargs):
16191619
time.sleep(self.retryDelay)
16201620
self.retries -= 1
16211621
response = record(response)
1622-
if 400 <= response.status:
1622+
if response.status >= 400:
16231623
raise HTTPError(response)
16241624

16251625
# Update the cookie with any HTTP request

splunklib/client.py

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -641,7 +641,7 @@ def restart(self, timeout=None):
641641
continue
642642
else:
643643
return result
644-
except Exception as e:
644+
except Exception:
645645
sleep(1)
646646
raise Exception("Operation time out.")
647647

@@ -1053,7 +1053,7 @@ def __init__(self, service, path, **kwargs):
10531053
Endpoint.__init__(self, service, path)
10541054
self._state = None
10551055
if not kwargs.get("skip_refresh", False):
1056-
self.refresh(kwargs.get("state", None)) # "Prefresh"
1056+
self.refresh(kwargs.get("state")) # "Prefresh"
10571057

10581058
def __contains__(self, item):
10591059
try:
@@ -1645,7 +1645,7 @@ def iter(self, offset=0, count=None, pagesize=None, **kwargs):
16451645
fetched += N
16461646
for item in items:
16471647
yield item
1648-
if pagesize is None or N < pagesize:
1648+
if pagesize is None or pagesize > N:
16491649
break
16501650
offset += N
16511651
logger.debug(
@@ -1945,7 +1945,7 @@ def create(self, name):
19451945
# a ConfigurationFile (which is a Collection) instead of some
19461946
# Entity.
19471947
if not isinstance(name, str):
1948-
raise ValueError(f"Invalid name: {repr(name)}")
1948+
raise ValueError(f"Invalid name: {name!r}")
19491949
response = self.post(__conf=name)
19501950
if response.status == 303:
19511951
return self[name]
@@ -1996,7 +1996,7 @@ class StoragePassword(Entity):
19961996
"""This class contains a storage password."""
19971997

19981998
def __init__(self, service, path, **kwargs):
1999-
state = kwargs.get("state", None)
1999+
state = kwargs.get("state")
20002000
kwargs["skip_refresh"] = kwargs.get("skip_refresh", state is not None)
20012001
super().__init__(service, path, **kwargs)
20022002
self._state = state
@@ -2047,7 +2047,7 @@ def create(self, password, username, realm=None):
20472047
:return: The :class:`StoragePassword` object created.
20482048
"""
20492049
if not isinstance(username, str):
2050-
raise ValueError(f"Invalid name: {repr(username)}")
2050+
raise ValueError(f"Invalid name: {username!r}")
20512051

20522052
if realm is None:
20532053
response = self.post(password=password, name=username)
@@ -2202,8 +2202,8 @@ def attach(self, host=None, source=None, sourcetype=None):
22022202
# the input mode
22032203
sock = self.service.connect()
22042204
headers = [
2205-
f"POST {str(self.service._abspath(path))} HTTP/1.1\r\n".encode("utf-8"),
2206-
f"Host: {self.service.host}:{int(self.service.port)}\r\n".encode("utf-8"),
2205+
f"POST {self.service._abspath(path)!s} HTTP/1.1\r\n".encode(),
2206+
f"Host: {self.service.host}:{int(self.service.port)}\r\n".encode(),
22072207
b"Accept-Encoding: identity\r\n",
22082208
cookie_or_auth_header.encode("utf-8"),
22092209
b"X-Splunk-Input-Mode: Streaming\r\n",
@@ -2806,14 +2806,14 @@ def list(self, *kinds, **kwargs):
28062806
entities = entities[kwargs["offset"] :]
28072807
if "count" in kwargs:
28082808
entities = entities[: kwargs["count"]]
2809-
if kwargs.get("sort_mode", None) == "alpha":
2809+
if kwargs.get("sort_mode") == "alpha":
28102810
sort_field = kwargs.get("sort_field", "name")
28112811
if sort_field == "name":
28122812
f = lambda x: x.name.lower()
28132813
else:
28142814
f = lambda x: x[sort_field].lower()
28152815
entities = sorted(entities, key=f)
2816-
if kwargs.get("sort_mode", None) == "alpha_case":
2816+
if kwargs.get("sort_mode") == "alpha_case":
28172817
sort_field = kwargs.get("sort_field", "name")
28182818
if sort_field == "name":
28192819
f = lambda x: x.name
@@ -3199,10 +3199,10 @@ def create(self, query, **kwargs):
31993199
32003200
:return: The :class:`Job`.
32013201
"""
3202-
if kwargs.get("exec_mode", None) == "oneshot":
3202+
if kwargs.get("exec_mode") == "oneshot":
32033203
raise TypeError("Cannot specify exec_mode=oneshot; use the oneshot method instead.")
32043204
response = self.post(search=query, **kwargs)
3205-
sid = _load_sid(response, kwargs.get("output_mode", None))
3205+
sid = _load_sid(response, kwargs.get("output_mode"))
32063206
return Job(self.service, sid)
32073207

32083208
def export(self, query, **params):
@@ -3421,7 +3421,7 @@ def dispatch(self, **kwargs):
34213421
:return: The :class:`Job`.
34223422
"""
34233423
response = self.post("dispatch", **kwargs)
3424-
sid = _load_sid(response, kwargs.get("output_mode", None))
3424+
sid = _load_sid(response, kwargs.get("output_mode"))
34253425
return Job(self.service, sid)
34263426

34273427
@property
@@ -3737,7 +3737,7 @@ def create(self, username, password, roles, **params):
37373737
hilda = users.create("hilda", "anotherpassword", roles=["user", "power"])
37383738
"""
37393739
if not isinstance(username, str):
3740-
raise ValueError(f"Invalid username: {str(username)}")
3740+
raise ValueError(f"Invalid username: {username!s}")
37413741
username = username.lower()
37423742
self.post(name=username, password=password, roles=roles, **params)
37433743
# splunkd doesn't return the user in the POST response body,
@@ -3859,7 +3859,7 @@ def create(self, name, **params):
38593859
paltry = roles.create("paltry", imported_roles="user", defaultApp="search")
38603860
"""
38613861
if not isinstance(name, str):
3862-
raise ValueError(f"Invalid role name: {str(name)}")
3862+
raise ValueError(f"Invalid role name: {name!s}")
38633863
name = name.lower()
38643864
self.post(name=name, **params)
38653865
# splunkd doesn't return the user in the POST response body,

splunklib/modularinput/utils.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,6 +73,6 @@ def parse_xml_data(parent_node, child_node_tag):
7373
data[child_name] = {"__app": child.get("app", None)}
7474
for param in child:
7575
data[child_name][param.get("name")] = parse_parameters(param)
76-
elif "item" == parent_node.tag:
76+
elif parent_node.tag == "item":
7777
data[child_name] = parse_parameters(child)
7878
return data

splunklib/searchcommands/decorators.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ def _get_specification(self):
218218
try:
219219
specification = ConfigurationSettingsType.specification_matrix[name]
220220
except KeyError:
221-
raise AttributeError(f"Unknown configuration setting: {name}={repr(self._value)}")
221+
raise AttributeError(f"Unknown configuration setting: {name}={self._value!r}")
222222

223223
return ConfigurationSettingsType.validate_configuration_setting, specification
224224

splunklib/searchcommands/external_search_command.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
class ExternalSearchCommand:
3232
def __init__(self, path, argv=None, environ=None):
3333
if not isinstance(path, (bytes, str)):
34-
raise ValueError(f"Expected a string value for path, not {repr(path)}")
34+
raise ValueError(f"Expected a string value for path, not {path!r}")
3535

3636
self._logger = getLogger(self.__class__.__name__)
3737
self._path = str(path)
@@ -45,22 +45,22 @@ def __init__(self, path, argv=None, environ=None):
4545

4646
@property
4747
def argv(self):
48-
return getattr(self, "_argv")
48+
return self._argv
4949

5050
@argv.setter
5151
def argv(self, value):
5252
if not (value is None or isinstance(value, (list, tuple))):
53-
raise ValueError(f"Expected a list, tuple or value of None for argv, not {repr(value)}")
53+
raise ValueError(f"Expected a list, tuple or value of None for argv, not {value!r}")
5454
self._argv = value
5555

5656
@property
5757
def environ(self):
58-
return getattr(self, "_environ")
58+
return self._environ
5959

6060
@environ.setter
6161
def environ(self, value):
6262
if not (value is None or isinstance(value, dict)):
63-
raise ValueError(f"Expected a dictionary value for environ, not {repr(value)}")
63+
raise ValueError(f"Expected a dictionary value for environ, not {value!r}")
6464
self._environ = value
6565

6666
@property
@@ -83,7 +83,7 @@ def execute(self):
8383
self._execute(self._path, self._argv, self._environ)
8484
except:
8585
error_type, error, tb = sys.exc_info()
86-
message = f"Command execution failed: {str(error)}"
86+
message = f"Command execution failed: {error!s}"
8787
self._logger.error(message + "\nTraceback:\n" + "".join(traceback.format_tb(tb)))
8888
sys.exit(1)
8989

0 commit comments

Comments
 (0)