Skip to content

Commit acfc19a

Browse files
committed
Run linter with uv run ruff check --fix
1 parent 425a903 commit acfc19a

32 files changed

Lines changed: 191 additions & 197 deletions

‎Makefile‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ lint: lint-python # TODO: Add mbake
2727
.PHONY: lint-python
2828
lint-python:
2929
$(UV_RUN_CMD) basedpyright
30-
# $(UV_RUN_CMD) ruff check --fix-only
30+
$(UV_RUN_CMD) ruff check --fix-only
3131
$(UV_RUN_CMD) ruff format
3232

3333
UV_RUN_CMD := uv run --frozen --no-config
@@ -37,7 +37,7 @@ ci-lint: ci-lint-python # TODO: Add mbake
3737
.PHONY: ci-lint-python
3838
ci-lint-python:
3939
$(UV_RUN_CMD) basedpyright
40-
# $(UV_RUN_CMD) ruff check
40+
$(UV_RUN_CMD) ruff check
4141
$(UV_RUN_CMD) ruff format --check
4242

4343
.PHONY: 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: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1859,9 +1859,7 @@ def check_tool_name(type: str, name: str) -> None:
18591859

18601860
last_ai_message: AIMessage | None = None
18611861
for message in messages:
1862-
if type(message) is HumanMessage:
1863-
check_no_pending_calls()
1864-
elif type(message) is SystemMessage:
1862+
if type(message) is HumanMessage or type(message) is SystemMessage:
18651863
check_no_pending_calls()
18661864
elif type(message) is AIMessage:
18671865
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

‎splunklib/searchcommands/internals.py‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -251,11 +251,11 @@ class ConfigurationSettingsType(type):
251251
"""
252252

253253
def __new__(mcs, module, name, bases):
254-
mcs = super(ConfigurationSettingsType, mcs).__new__(mcs, str(name), bases, {})
254+
mcs = super().__new__(mcs, str(name), bases, {})
255255
return mcs
256256

257257
def __init__(cls, module, name, bases):
258-
super(ConfigurationSettingsType, cls).__init__(name, bases, None)
258+
super().__init__(name, bases, None)
259259
cls.__module__ = module
260260

261261
@staticmethod
@@ -265,9 +265,9 @@ def validate_configuration_setting(specification, name, value):
265265
type_names = specification.type.__name__
266266
else:
267267
type_names = ", ".join(map(lambda t: t.__name__, specification.type))
268-
raise ValueError(f"Expected {type_names} value, not {name}={repr(value)}")
268+
raise ValueError(f"Expected {type_names} value, not {name}={value!r}")
269269
if specification.constraint and not specification.constraint(value):
270-
raise ValueError(f"Illegal value: {name}={repr(value)}")
270+
raise ValueError(f"Illegal value: {name}={value!r}")
271271
return value
272272

273273
specification = namedtuple(
@@ -549,7 +549,7 @@ def _write_record(self, record):
549549
if fieldnames is None:
550550
self._fieldnames = fieldnames = list(record.keys())
551551
self._fieldnames.extend([i for i in self.custom_fields if i not in self._fieldnames])
552-
value_list = map(lambda fn: (str(fn), str("__mv_") + str(fn)), fieldnames)
552+
value_list = map(lambda fn: (str(fn), "__mv_" + str(fn)), fieldnames)
553553
self._writerow(list(chain.from_iterable(value_list)))
554554

555555
get_value = record.get

0 commit comments

Comments
 (0)