Skip to content

Commit

Permalink
refactor: run pyupgrade
Browse files Browse the repository at this point in the history
This PR is a result of using [pyupgrade](https://github.com/asottile/pyupgrade) with `--py3-plus` option.
  • Loading branch information
artemrys authored and rfaircloth-splunk committed Jul 9, 2021
1 parent 785791e commit bd088ee
Show file tree
Hide file tree
Showing 43 changed files with 78 additions and 84 deletions.
1 change: 0 additions & 1 deletion docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
#
# solnlib documentation build configuration file, created by
# sphinx-quickstart on Sat Feb 27 15:17:42 2016.
Expand Down
3 changes: 1 addition & 2 deletions examples/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#
# SPDX-License-Identifier: Apache-2.0

from __future__ import print_function
import sys
import os
import os.path as op
Expand All @@ -24,7 +23,7 @@

def setup_environment():
print("Setup solnlib demo environment...")
print("Copying %s to %s" % (source_dir, target_dir))
print("Copying {} to {}".format(source_dir, target_dir))
shutil.copytree(source_dir, target_dir)
shutil.copytree(solnlib_lib_dir, solnlib_lib_target_dir)
os.system(splunk_bin + " start")
Expand Down
1 change: 0 additions & 1 deletion examples/test__kvstore.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#
# SPDX-License-Identifier: Apache-2.0

from builtins import range
import json
import os.path as op
import sys
Expand Down
1 change: 0 additions & 1 deletion examples/test_credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#
# SPDX-License-Identifier: Apache-2.0

from builtins import range
import sys
import os.path as op
import pytest
Expand Down
1 change: 0 additions & 1 deletion examples/test_hec_event_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#
# SPDX-License-Identifier: Apache-2.0

from builtins import range
import sys
import os.path as op

Expand Down
2 changes: 1 addition & 1 deletion examples/test_metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ def test_metadata_reader():
mr = metadata.MetadataReader(context.app)

modtime = mr.get("collections", "sessions", "modtime")
assert isinstance(modtime, six.text_type)
assert isinstance(modtime, str)

modtime = mr.get_float("collections", "sessions", "modtime")
assert type(modtime) == float
1 change: 0 additions & 1 deletion examples/test_server_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@
#
# SPDX-License-Identifier: Apache-2.0

from __future__ import print_function
import os.path as op
import sys

Expand Down
2 changes: 1 addition & 1 deletion examples/test_user_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ def test_object_acl_manager():
replace_existing=False,
)
obj_acl = oaclm.get_acl(obj_collection, obj_id1)
assert set((obj_acl.obj_perms["read"])) == set(["admin", "user1"])
assert set(obj_acl.obj_perms["read"]) == {"admin", "user1"}

oaclm.update_acls(
obj_collection,
Expand Down
2 changes: 1 addition & 1 deletion solnlib/acl.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class ACLException(Exception):
pass


class ACLManager(object):
class ACLManager:
"""ACL manager.
:param session_key: Splunk access token.
Expand Down
10 changes: 5 additions & 5 deletions solnlib/api_documenter.py
Original file line number Diff line number Diff line change
Expand Up @@ -401,7 +401,7 @@ def _generate_documentation(context, method_list):
generator.update_spec()


class _SwaggerSpecGenerator(object):
class _SwaggerSpecGenerator:
"""Private class to generate the swagger spec file."""

def __init__(self, swagger_api):
Expand Down Expand Up @@ -451,15 +451,15 @@ def update_spec(self):
)


class _SwaggerApi(object):
class _SwaggerApi:
"""
Private class to generate the swagger
documentation and default params values.
"""

def __init__(self):
if op.isfile(tempfile.gettempdir() + op.sep + "temp.yaml"):
with open(tempfile.gettempdir() + op.sep + "temp.yaml", "r") as stream:
with open(tempfile.gettempdir() + op.sep + "temp.yaml") as stream:
try:
spec = yaml.safe_load(stream)
self.swagger = spec["swagger"]
Expand Down Expand Up @@ -606,10 +606,10 @@ def create_model(self, params, name, req):
definition["requirements"] = req
for param in params:
# get type of property
type_info = re.findall("\((.*?)\)\s", str(params.get(param)), re.DOTALL)
type_info = re.findall(r"\((.*?)\)\s", str(params.get(param)), re.DOTALL)
if type_info and len(type_info) > 0:
type_info = type_info[0]
prop_type = re.findall("\<(.*?)\(", str(params.get(param)), re.DOTALL)
prop_type = re.findall(r"\<(.*?)\(", str(params.get(param)), re.DOTALL)
if prop_type and len(prop_type) > 0:
prop_type = prop_type[0]
if prop_type in self.type_converter:
Expand Down
4 changes: 2 additions & 2 deletions solnlib/compression.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
__all__ = ["GzipHandler", "ZipHandler"]


class GzipHandler(object):
class GzipHandler:
"""
Class for handling gzip-formatted string content.
"""
Expand Down Expand Up @@ -57,7 +57,7 @@ def decompress(cls, data):
return gzip.GzipFile(fileobj=BytesIO(data), mode="rb").read()


class ZipHandler(object):
class ZipHandler:
"""
Class for handling zip files.
"""
Expand Down
10 changes: 5 additions & 5 deletions solnlib/conf_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class ConfStanzaNotExistException(Exception):
pass


class ConfFile(object):
class ConfFile:
"""Configuration file.
:param name: Configuration file name.
Expand Down Expand Up @@ -211,12 +211,12 @@ def get(self, stanza_name, only_current_app=False):
raise

raise ConfStanzaNotExistException(
"Stanza: %s does not exist in %s.conf" % (stanza_name, self._name)
"Stanza: {} does not exist in {}.conf".format(stanza_name, self._name)
)

if len(stanza_mgrs) == 0:
raise ConfStanzaNotExistException(
"Stanza: %s does not exist in %s.conf" % (stanza_name, self._name)
"Stanza: {} does not exist in {}.conf".format(stanza_name, self._name)
)

stanza = self._decrypt_stanza(stanza_mgrs[0].name, stanza_mgrs[0].content)
Expand Down Expand Up @@ -326,7 +326,7 @@ def delete(self, stanza_name):
"Delete stanza: %s error: %s.", stanza_name, traceback.format_exc()
)
raise ConfStanzaNotExistException(
"Stanza: %s does not exist in %s.conf" % (stanza_name, self._name)
"Stanza: {} does not exist in {}.conf".format(stanza_name, self._name)
)

@retry(exceptions=[binding.HTTPError])
Expand All @@ -349,7 +349,7 @@ class ConfManagerException(Exception):
pass


class ConfManager(object):
class ConfManager:
"""Configuration file manager.
:param session_key: Splunk access token.
Expand Down
8 changes: 4 additions & 4 deletions solnlib/credentials.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class CredentialNotExistException(Exception):
pass


class CredentialManager(object):
class CredentialManager:
"""Credential manager.
:param session_key: Splunk access token.
Expand Down Expand Up @@ -125,7 +125,7 @@ def get_password(self, user):
return password["clear_password"]

raise CredentialNotExistException(
"Failed to get password of realm=%s, user=%s." % (self._realm, user)
"Failed to get password of realm={}, user={}.".format(self._realm, user)
)

@retry(exceptions=[binding.HTTPError])
Expand Down Expand Up @@ -211,7 +211,7 @@ def delete_password(self, user):
"""
all_passwords = self._get_all_passwords_in_realm()
deleted = False
ent_pattern = re.compile("(%s%s\d+)" % (user.replace("\\", "\\\\"), self.SEP))
ent_pattern = re.compile(r"({}{}\d+)".format(user.replace("\\", "\\\\"), self.SEP))
for password in list(all_passwords):
match = (user == password.username) or ent_pattern.match(password.username)
if match and password.realm == self._realm:
Expand All @@ -220,7 +220,7 @@ def delete_password(self, user):

if not deleted:
raise CredentialNotExistException(
"Failed to delete password of realm=%s, user=%s" % (self._realm, user)
"Failed to delete password of realm={}, user={}".format(self._realm, user)
)

def _get_all_passwords_in_realm(self):
Expand Down
4 changes: 2 additions & 2 deletions solnlib/file_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
__all__ = ["FileChangesChecker", "FileMonitor"]


class FileChangesChecker(object):
class FileChangesChecker:
"""Files change checker.
:param callback: Callback function for files change.
Expand Down Expand Up @@ -67,7 +67,7 @@ def check_changes(self):
return False


class FileMonitor(object):
class FileMonitor:
"""Files change monitor.
Monitor files change in a separated thread and call callback
Expand Down
2 changes: 1 addition & 1 deletion solnlib/hec_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
__all__ = ["HECConfig"]


class HECConfig(object):
class HECConfig:
"""HTTP Event Collector configuration.
:param session_key: Splunk access token.
Expand Down
2 changes: 1 addition & 1 deletion solnlib/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ class LogException(Exception):
pass


class Logs(with_metaclass(Singleton, object)):
class Logs(metaclass=Singleton):
"""A singleton class that manage all kinds of logger.
Usage::
Expand Down
4 changes: 2 additions & 2 deletions solnlib/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
__all__ = ["MetadataReader"]


class MetadataReader(object):
class MetadataReader:
"""Metadata reader for `app`.
:param app: App name.
Expand All @@ -46,7 +46,7 @@ def __init__(self, app):
# May raise ConfigParser.ParsingError
self._cfg.read(local_meta)
else:
raise IOError("No such file: %s." % local_meta)
raise OSError("No such file: %s." % local_meta)

def get(self, conf, stanza, option):
"""Return the metadata value of option in [conf/stanza] section.
Expand Down
8 changes: 4 additions & 4 deletions solnlib/modular_input/checkpointer.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class CheckpointerException(Exception):
pass


class Checkpointer(with_metaclass(ABCMeta, object)):
class Checkpointer(metaclass=ABCMeta):
"""Base class of checkpointer."""

@abstractmethod
Expand Down Expand Up @@ -264,7 +264,7 @@ def update(self, key, state):
if op.exists(file_name):
try:
os.remove(file_name)
except IOError:
except OSError:
pass

os.rename(file_name + "_new", file_name)
Expand All @@ -276,9 +276,9 @@ def batch_update(self, states):
def get(self, key):
file_name = op.join(self._checkpoint_dir, self.encode_key(key))
try:
with open(file_name, "r") as fp:
with open(file_name) as fp:
return json.load(fp)
except (IOError, ValueError):
except (OSError, ValueError):
return None

def delete(self, key):
Expand Down
4 changes: 2 additions & 2 deletions solnlib/modular_input/event.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
import json

try:
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET

Expand All @@ -32,7 +32,7 @@ class EventException(Exception):
pass


class Event(object):
class Event:
"""Base class of modular input event."""

def __init__(
Expand Down
4 changes: 2 additions & 2 deletions solnlib/modular_input/event_writer.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@
__all__ = ["ClassicEventWriter", "HECEventWriter"]


class EventWriter(with_metaclass(ABCMeta, object)):
class EventWriter(metaclass=ABCMeta):
"""Base class of event writer."""

description = "EventWriter"
Expand Down Expand Up @@ -221,7 +221,7 @@ def __init__(
logger=None,
**context
):
super(HECEventWriter, self).__init__()
super().__init__()
self._session_key = session_key
if logger:
self.logger = logger
Expand Down
4 changes: 2 additions & 2 deletions solnlib/modular_input/modular_input.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
from six import with_metaclass

try:
import xml.etree.cElementTree as ET
import xml.etree.ElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET

Expand All @@ -51,7 +51,7 @@ class ModularInputException(Exception):
pass


class ModularInput(with_metaclass(ABCMeta, object)):
class ModularInput(metaclass=ABCMeta):
"""Base class of Splunk modular input.
It's a base modular input, it should be inherited by sub modular input. For
Expand Down
2 changes: 1 addition & 1 deletion solnlib/net_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def is_valid_hostname(hostname):
return False
if hostname[-1:] == ".":
hostname = hostname[:-1]
allowed = re.compile("(?!-)(::)?[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
allowed = re.compile(r"(?!-)(::)?[A-Z\d-]{1,63}(?<!-)$", re.IGNORECASE)
return all(allowed.match(x) for x in hostname.split("."))


Expand Down
4 changes: 2 additions & 2 deletions solnlib/orphan_process_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
__all__ = ["OrphanProcessChecker", "OrphanProcessMonitor"]


class OrphanProcessChecker(object):
class OrphanProcessChecker:
"""Orphan process checker.
Only work for Linux platform. On Windows platform, is_orphan
Expand Down Expand Up @@ -61,7 +61,7 @@ def check_orphan(self):
return res


class OrphanProcessMonitor(object):
class OrphanProcessMonitor:
"""Orpan process monitor.
Check if process become orphan in background thread per
Expand Down
4 changes: 2 additions & 2 deletions solnlib/pattern.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,10 @@ class Singleton(type):
"""

def __init__(cls, name, bases, attrs):
super(Singleton, cls).__init__(name, bases, attrs)
super().__init__(name, bases, attrs)
cls._instance = None

def __call__(cls, *args, **kwargs):
if cls._instance is None:
cls._instance = super(Singleton, cls).__call__(*args, **kwargs)
cls._instance = super().__call__(*args, **kwargs)
return cls._instance
Loading

0 comments on commit bd088ee

Please sign in to comment.