Skip to content

Commit e12bc03

Browse files
committed
Reorganise all imports with ruff check --fix ., move utils/ to tests/utils/
1 parent 150b1f3 commit e12bc03

Some content is hidden

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

65 files changed

+409
-899
lines changed

docs/conf.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# All configuration values have a default; values that are commented out
1212
# serve to show the default.
1313

14+
1415
from datetime import datetime
1516

1617
import splunklib

pyproject.toml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,8 +57,10 @@ packages = ["splunklib", "splunklib.modularinput", "splunklib.searchcommands"]
5757
version = { attr = "splunklib.__version__" }
5858

5959
# https://docs.astral.sh/ruff/configuration/
60+
[tool.ruff]
61+
line-length = 100
62+
6063
[tool.ruff.lint]
61-
fixable = ["ALL"]
6264
select = [
6365
"F", # pyflakes
6466
"E", # pycodestyle

splunklib/__init__.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,7 @@
2626
# To set the logging level of splunklib
2727
# ex. To enable debug logs, call this method with parameter 'logging.DEBUG'
2828
# default logging level is set to 'WARNING'
29-
def setup_logging(
30-
level, log_format=DEFAULT_LOG_FORMAT, date_format=DEFAULT_DATE_FORMAT
31-
):
29+
def setup_logging(level, log_format=DEFAULT_LOG_FORMAT, date_format=DEFAULT_DATE_FORMAT):
3230
logging.basicConfig(level=level, format=log_format, datefmt=date_format)
3331

3432

splunklib/binding.py

Lines changed: 41 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -34,27 +34,27 @@
3434
from contextlib import contextmanager
3535
from datetime import datetime
3636
from functools import wraps
37-
from io import BytesIO
38-
from urllib import parse
3937
from http import client
4038
from http.cookies import SimpleCookie
39+
from io import BytesIO
40+
from urllib import parse
4141
from xml.etree.ElementTree import XML, ParseError
42-
from .data import record
43-
from . import __version__
4442

43+
from . import __version__
44+
from .data import record
4545

4646
logger = logging.getLogger(__name__)
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
@@ -251,7 +251,7 @@ def __mod__(self, fields):
251251
raise TypeError("Cannot interpolate into a UrlEncoded object.")
252252

253253
def __repr__(self):
254-
return f"UrlEncoded({repr(parse.unquote(str(self)))})"
254+
return f"UrlEncoded({parse.unquote(str(self))!r})"
255255

256256

257257
@contextmanager
@@ -345,9 +345,7 @@ def wrapper(self, *args, **kwargs):
345345
):
346346
return request_fun(self, *args, **kwargs)
347347
elif he.status == 401 and not self.autologin:
348-
raise AuthenticationError(
349-
"Request failed: Session is not logged in.", he
350-
)
348+
raise AuthenticationError("Request failed: Session is not logged in.", he)
351349
else:
352350
raise
353351

@@ -612,9 +610,7 @@ def _auth_headers(self):
612610
if token:
613611
header.append(("Authorization", token))
614612
if self.get_cookies():
615-
header.append(
616-
("Cookie", _make_cookie_header(list(self.get_cookies().items())))
617-
)
613+
header.append(("Cookie", _make_cookie_header(list(self.get_cookies().items()))))
618614

619615
return header
620616

@@ -666,10 +662,8 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
666662
default :class:`Context` namespace. All other keyword arguments are
667663
included in the URL as query parameters.
668664
669-
:raises AuthenticationError: Raised when the ``Context`` object is not
670-
logged in.
671-
:raises HTTPError: Raised when an error occurred in a GET operation from
672-
*path_segment*.
665+
:raises AuthenticationError: Raised when the ``Context`` object is not logged in.
666+
:raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
673667
:param path_segment: A REST path segment.
674668
:type path_segment: ``string``
675669
:param owner: The owner context of the namespace (optional).
@@ -678,12 +672,10 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
678672
:type app: ``string``
679673
:param sharing: The sharing mode of the namespace (optional).
680674
:type sharing: ``string``
681-
:param query: All other keyword arguments, which are used as query
682-
parameters.
675+
:param query: All other keyword arguments, which are used as query parameters.
683676
:type query: ``string``
684677
:return: The response from the server.
685-
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
686-
and ``status``
678+
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
687679
688680
**Example**::
689681
@@ -699,24 +691,18 @@ def delete(self, path_segment, owner=None, app=None, sharing=None, **query):
699691
('content-type', 'text/xml; charset=utf-8')],
700692
'reason': 'OK',
701693
'status': 200}
702-
c.delete('nonexistant/path') # raises HTTPError
694+
c.delete('nonexistent/path') # raises HTTPError
703695
c.logout()
704696
c.delete('apps/local') # raises AuthenticationError
705697
"""
706-
path = self.authority + self._abspath(
707-
path_segment, owner=owner, app=app, sharing=sharing
708-
)
709-
logger.debug(
710-
"DELETE request to %s (body: %s)", path, mask_sensitive_data(query)
711-
)
698+
path = self.authority + self._abspath(path_segment, owner=owner, app=app, sharing=sharing)
699+
logger.debug("DELETE request to %s (body: %s)", path, mask_sensitive_data(query))
712700
response = self.http.delete(path, self._auth_headers, **query)
713701
return response
714702

715703
@_authentication
716704
@_log_duration
717-
def get(
718-
self, path_segment, owner=None, app=None, headers=None, sharing=None, **query
719-
):
705+
def get(self, path_segment, owner=None, app=None, headers=None, sharing=None, **query):
720706
"""Performs a GET operation from the REST path segment with the given
721707
namespace and query.
722708
@@ -729,10 +715,8 @@ def get(
729715
default :class:`Context` namespace. All other keyword arguments are
730716
included in the URL as query parameters.
731717
732-
:raises AuthenticationError: Raised when the ``Context`` object is not
733-
logged in.
734-
:raises HTTPError: Raised when an error occurred in a GET operation from
735-
*path_segment*.
718+
:raises AuthenticationError: Raised when the ``Context`` object is not logged in.
719+
:raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
736720
:param path_segment: A REST path segment.
737721
:type path_segment: ``string``
738722
:param owner: The owner context of the namespace (optional).
@@ -743,12 +727,10 @@ def get(
743727
:type headers: ``list`` of 2-tuples.
744728
:param sharing: The sharing mode of the namespace (optional).
745729
:type sharing: ``string``
746-
:param query: All other keyword arguments, which are used as query
747-
parameters.
730+
:param query: All other keyword arguments, which are used as query parameters.
748731
:type query: ``string``
749732
:return: The response from the server.
750-
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
751-
and ``status``
733+
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
752734
753735
**Example**::
754736
@@ -764,26 +746,22 @@ def get(
764746
('content-type', 'text/xml; charset=utf-8')],
765747
'reason': 'OK',
766748
'status': 200}
767-
c.get('nonexistant/path') # raises HTTPError
749+
c.get('nonexistent/path') # raises HTTPError
768750
c.logout()
769751
c.get('apps/local') # raises AuthenticationError
770752
"""
771753
if headers is None:
772754
headers = []
773755

774-
path = self.authority + self._abspath(
775-
path_segment, owner=owner, app=app, sharing=sharing
776-
)
756+
path = self.authority + self._abspath(path_segment, owner=owner, app=app, sharing=sharing)
777757
logger.debug("GET request to %s (body: %s)", path, mask_sensitive_data(query))
778758
all_headers = headers + self.additional_headers + self._auth_headers
779759
response = self.http.get(path, all_headers, **query)
780760
return response
781761

782762
@_authentication
783763
@_log_duration
784-
def post(
785-
self, path_segment, owner=None, app=None, sharing=None, headers=None, **query
786-
):
764+
def post(self, path_segment, owner=None, app=None, sharing=None, headers=None, **query):
787765
"""Performs a POST operation from the REST path segment with the given
788766
namespace and query.
789767
@@ -803,10 +781,8 @@ def post(
803781
body, and all other keyword arguments will be passed as
804782
GET-style arguments in the URL.
805783
806-
:raises AuthenticationError: Raised when the ``Context`` object is not
807-
logged in.
808-
:raises HTTPError: Raised when an error occurred in a GET operation from
809-
*path_segment*.
784+
:raises AuthenticationError: Raised when the ``Context`` object is not logged in.
785+
:raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
810786
:param path_segment: A REST path segment.
811787
:type path_segment: ``string``
812788
:param owner: The owner context of the namespace (optional).
@@ -817,17 +793,15 @@ def post(
817793
:type sharing: ``string``
818794
:param headers: List of extra HTTP headers to send (optional).
819795
:type headers: ``list`` of 2-tuples.
820-
:param query: All other keyword arguments, which are used as query
821-
parameters.
796+
:param query: All other keyword arguments, which are used as query parameters.
822797
:param body: Parameters to be used in the post body. If specified,
823798
any parameters in the query will be applied to the URL instead of
824799
the body. If a dict is supplied, the key-value pairs will be form
825800
encoded. If a string is supplied, the body will be passed through
826801
in the request unchanged.
827802
:type body: ``dict`` or ``str``
828803
:return: The response from the server.
829-
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
830-
and ``status``
804+
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
831805
832806
**Example**::
833807
@@ -844,7 +818,7 @@ def post(
844818
('content-type', 'text/xml; charset=utf-8')],
845819
'reason': 'Created',
846820
'status': 201}
847-
c.post('nonexistant/path') # raises HTTPError
821+
c.post('nonexistent/path') # raises HTTPError
848822
c.logout()
849823
# raises AuthenticationError:
850824
c.post('saved/searches', name='boris',
@@ -853,9 +827,7 @@ def post(
853827
if headers is None:
854828
headers = []
855829

856-
path = self.authority + self._abspath(
857-
path_segment, owner=owner, app=app, sharing=sharing
858-
)
830+
path = self.authority + self._abspath(path_segment, owner=owner, app=app, sharing=sharing)
859831

860832
logger.debug("POST request to %s (body: %s)", path, mask_sensitive_data(query))
861833
all_headers = headers + self.additional_headers + self._auth_headers
@@ -883,10 +855,8 @@ def request(
883855
default :class:`Context` namespace. All other keyword arguments are
884856
included in the URL as query parameters.
885857
886-
:raises AuthenticationError: Raised when the ``Context`` object is not
887-
logged in.
888-
:raises HTTPError: Raised when an error occurred in a GET operation from
889-
*path_segment*.
858+
:raises AuthenticationError: Raised when the ``Context`` object is not logged in.
859+
:raises HTTPError: Raised when an error occurred in a GET operation from *path_segment*.
890860
:param path_segment: A REST path segment.
891861
:type path_segment: ``string``
892862
:param method: The HTTP method to use (optional).
@@ -902,8 +872,7 @@ def request(
902872
:param sharing: The sharing mode of the namespace (optional).
903873
:type sharing: ``string``
904874
:return: The response from the server.
905-
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``,
906-
and ``status``
875+
:rtype: ``dict`` with keys ``body``, ``headers``, ``reason``, and ``status``
907876
908877
**Example**::
909878
@@ -919,16 +888,14 @@ def request(
919888
('content-type', 'text/xml; charset=utf-8')],
920889
'reason': 'OK',
921890
'status': 200}
922-
c.request('nonexistant/path', method='GET') # raises HTTPError
891+
c.request('nonexistent/path', method='GET') # raises HTTPError
923892
c.logout()
924893
c.get('apps/local') # raises AuthenticationError
925894
"""
926895
if headers is None:
927896
headers = []
928897

929-
path = self.authority + self._abspath(
930-
path_segment, owner=owner, app=app, sharing=sharing
931-
)
898+
path = self.authority + self._abspath(path_segment, owner=owner, app=app, sharing=sharing)
932899

933900
all_headers = headers + self.additional_headers + self._auth_headers
934901
logger.debug(
@@ -979,9 +946,7 @@ def login(self):
979946
# logged in.
980947
return
981948

982-
if self.token is not _NoAuthenticationToken and (
983-
not self.username and not self.password
984-
):
949+
if self.token is not _NoAuthenticationToken and (not self.username and not self.password):
985950
# If we were passed a session token, but no username or
986951
# password, then login is a nop, since we're automatically
987952
# logged in.
@@ -1078,9 +1043,7 @@ def _abspath(self, path_segment, owner=None, app=None, sharing=None):
10781043

10791044
oname = "nobody" if ns.owner is None else ns.owner
10801045
aname = "system" if ns.app is None else ns.app
1081-
path = UrlEncoded(
1082-
f"/servicesNS/{oname}/{aname}/{path_segment}", skip_encode=skip_encode
1083-
)
1046+
path = UrlEncoded(f"/servicesNS/{oname}/{aname}/{path_segment}", skip_encode=skip_encode)
10841047
return path
10851048

10861049

@@ -1223,11 +1186,7 @@ def _spliturl(url):
12231186
parsed_url = parse.urlparse(url)
12241187
host = parsed_url.hostname
12251188
port = parsed_url.port
1226-
path = (
1227-
"?".join((parsed_url.path, parsed_url.query))
1228-
if parsed_url.query
1229-
else parsed_url.path
1230-
)
1189+
path = "?".join((parsed_url.path, parsed_url.query)) if parsed_url.query else parsed_url.path
12311190
# Strip brackets if its an IPv6 address
12321191
if host.startswith("[") and host.endswith("]"):
12331192
host = host[1:-1]
@@ -1574,10 +1533,7 @@ def request(url, message, **kwargs):
15741533
if timeout is not None:
15751534
connection.sock.settimeout(timeout)
15761535
response = connection.getresponse()
1577-
is_keepalive = (
1578-
"keep-alive"
1579-
in response.getheader("connection", default="close").lower()
1580-
)
1536+
is_keepalive = "keep-alive" in response.getheader("connection", default="close").lower()
15811537
finally:
15821538
if not is_keepalive:
15831539
connection.close()

0 commit comments

Comments
 (0)