Skip to content

Commit

Permalink
Change: Enable string normalization with black
Browse files Browse the repository at this point in the history
Normalize all strings with black
  • Loading branch information
bjoernricks committed Aug 16, 2022
1 parent 5435ce0 commit ec17b3e
Show file tree
Hide file tree
Showing 18 changed files with 650 additions and 651 deletions.
22 changes: 11 additions & 11 deletions gvmtools/cli.py
Expand Up @@ -56,32 +56,32 @@ def _load_infile(filename=None):
if not filename:
return None

with open(filename, encoding='utf-8') as f:
with open(filename, encoding="utf-8") as f:
return f.read()


def main():
do_not_run_as_root()

parser = create_parser(description=HELP_TEXT, logfilename='gvm-cli.log')
parser = create_parser(description=HELP_TEXT, logfilename="gvm-cli.log")

parser.add_protocol_argument()

parser.add_argument('-X', '--xml', help='XML request to send')
parser.add_argument("-X", "--xml", help="XML request to send")
parser.add_argument(
'-r', '--raw', help='Return raw XML', action='store_true', default=False
"-r", "--raw", help="Return raw XML", action="store_true", default=False
)
parser.add_argument(
'--pretty',
help='Pretty format the returned xml',
action='store_true',
"--pretty",
help="Pretty format the returned xml",
action="store_true",
default=False,
)
parser.add_argument(
'--duration', action='store_true', help='Measure command execution time'
"--duration", action="store_true", help="Measure command execution time"
)
parser.add_argument(
'infile', nargs='?', help='File to read XML commands from.'
"infile", nargs="?", help="File to read XML commands from."
)

args = parser.parse_args()
Expand Down Expand Up @@ -135,7 +135,7 @@ def main():

if args.duration:
duration = time.time() - starttime
print(f'Elapsed time: {duration} seconds')
print(f"Elapsed time: {duration} seconds")
elif args.pretty:
pretty_print(result)
else:
Expand All @@ -147,5 +147,5 @@ def main():
sys.exit(0)


if __name__ == '__main__':
if __name__ == "__main__":
main()
28 changes: 14 additions & 14 deletions gvmtools/config.py
Expand Up @@ -34,19 +34,19 @@

class Config:
def __init__(self):
self._config = configparser.ConfigParser(default_section='main')
self._config = configparser.ConfigParser(default_section="main")

self._config = {}

self._config['gmp'] = dict(username='', password='')
self._config['ssh'] = dict(
username='gmp',
password='gmp',
self._config["gmp"] = dict(username="", password="")
self._config["ssh"] = dict(
username="gmp",
password="gmp",
port=DEFAULT_SSH_PORT,
hostname=DEFAULT_HOSTNAME,
)
self._config['unixsocket'] = dict(socketpath=DEFAULT_UNIX_SOCKET_PATH)
self._config['tls'] = dict(
self._config["unixsocket"] = dict(socketpath=DEFAULT_UNIX_SOCKET_PATH)
self._config["tls"] = dict(
port=DEFAULT_GVM_PORT, hostname=DEFAULT_HOSTNAME
)

Expand All @@ -55,26 +55,26 @@ def __init__(self):
def load(self, filepath):
path = filepath.expanduser()

config = configparser.ConfigParser(default_section='main')
config = configparser.ConfigParser(default_section="main")

with path.open() as f:
config.read_file(f)

if 'Auth' in config:
if "Auth" in config:
logger.warning(
"Warning: Loaded config file %s contains deprecated 'Auth' "
"section. This section will be ignored in future.",
str(filepath),
)
gmp_username = config.get('Auth', 'gmp_username', fallback='')
gmp_password = config.get('Auth', 'gmp_password', fallback='')
self._config['gmp']['username'] = gmp_username
self._config['gmp']['password'] = gmp_password
gmp_username = config.get("Auth", "gmp_username", fallback="")
gmp_password = config.get("Auth", "gmp_password", fallback="")
self._config["gmp"]["username"] = gmp_username
self._config["gmp"]["password"] = gmp_password

self._defaults.update(config.defaults())

for section in config.sections():
if section == 'Auth':
if section == "Auth":
continue

for key, value in config.items(section):
Expand Down
32 changes: 16 additions & 16 deletions gvmtools/helper.py
Expand Up @@ -27,11 +27,11 @@
from gvm.xml import pretty_print
from lxml import etree

__all__ = ['authenticate', 'pretty_print', 'run_script']
__all__ = ["authenticate", "pretty_print", "run_script"]


class Table:
def __init__(self, heading=None, rows=None, divider=' | '):
def __init__(self, heading=None, rows=None, divider=" | "):
self.heading = heading or []
self.rows = rows or []
self.divider = divider
Expand Down Expand Up @@ -71,7 +71,7 @@ def __str__(self):

heading_columns.append(self._create_column(column, column_size))
heading_divider_columns.append(
self._create_column('-' * column_size, column_size)
self._create_column("-" * column_size, column_size)
)

row_strings.append(self._create_row(heading_columns))
Expand All @@ -95,10 +95,10 @@ def yes_or_no(question):
Arguments:
question (str): The condition the user should answer
"""
reply = str(input(question + ' (y/n): ')).lower().strip()
if reply[0] == ('y'):
reply = str(input(question + " (y/n): ")).lower().strip()
if reply[0] == ("y"):
return True
if reply[0] == ('n'):
if reply[0] == ("n"):
return False
else:
return yes_or_no("Please enter 'y' or 'n'")
Expand All @@ -119,8 +119,8 @@ def generate_random_ips(count: int):
exclude_127 = [i for i in range(1, 256)]
exclude_127.remove(127)
return [
f'{choice(exclude_127)}.{randrange(0, 256)}.'
f'{randrange(0, 256)}.{randrange(1, 256)}'
f"{choice(exclude_127)}.{randrange(0, 256)}."
f"{randrange(0, 256)}.{randrange(1, 256)}"
for i in range(count)
]

Expand All @@ -129,7 +129,7 @@ def generate_id(
size: int = 12, chars: str = string.ascii_uppercase + string.digits
):
"""Generate a random ID"""
return ''.join(choice(chars) for _ in range(size))
return "".join(choice(chars) for _ in range(size))


def generate_uuid():
Expand Down Expand Up @@ -158,8 +158,8 @@ def create_xml_tree(xml_doc):


def do_not_run_as_root():
if hasattr(os, 'geteuid') and os.geteuid() == 0:
raise RuntimeError('This tool MUST NOT be run as root user.')
if hasattr(os, "geteuid") and os.geteuid() == 0:
raise RuntimeError("This tool MUST NOT be run as root user.")


def authenticate(gmp, username=None, password=None):
Expand Down Expand Up @@ -187,16 +187,16 @@ def authenticate(gmp, username=None, password=None):
# Ask for login credentials if none are given.
if not username:
while username is None or len(username) == 0:
username = input('Enter username: ')
username = input("Enter username: ")

if not password:
password = getpass.getpass(f'Enter password for {username}: ')
password = getpass.getpass(f"Enter password for {username}: ")

try:
gmp.authenticate(username, password)
return (username, password)
except GvmError as e:
print('Could not authenticate. Please check your credentials.')
print("Could not authenticate. Please check your credentials.")
raise e


Expand All @@ -208,9 +208,9 @@ def run_script(path, global_vars):
vars (dict): Variables passed as globals to the script
"""
try:
file = open(path, 'r', encoding='utf-8', newline='').read()
file = open(path, "r", encoding="utf-8", newline="").read()
except FileNotFoundError:
print(f'Script {path} does not exist', file=sys.stderr)
print(f"Script {path} does not exist", file=sys.stderr)
sys.exit(2)

exec(file, global_vars) # pylint: disable=exec-used

0 comments on commit ec17b3e

Please sign in to comment.