Skip to content

Commit

Permalink
style: format python files with black
Browse files Browse the repository at this point in the history
  • Loading branch information
jooola committed Jun 23, 2023
1 parent b9978da commit 7601220
Show file tree
Hide file tree
Showing 36 changed files with 776 additions and 909 deletions.
25 changes: 13 additions & 12 deletions .azure-pipelines/scripts/combine-coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
It is up to pipeline authors to avoid name collisions when deviating from the recommended format.
"""

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type

import os
Expand All @@ -20,12 +21,12 @@ def main():
"""Main program entry point."""
source_directory = sys.argv[1]

if '/ansible_collections/' in os.getcwd():
if "/ansible_collections/" in os.getcwd():
output_path = "tests/output"
else:
output_path = "test/results"

destination_directory = os.path.join(output_path, 'coverage')
destination_directory = os.path.join(output_path, "coverage")

if not os.path.exists(destination_directory):
os.makedirs(destination_directory)
Expand All @@ -34,27 +35,27 @@ def main():
count = 0

for name in os.listdir(source_directory):
match = re.search('^Coverage (?P<attempt>[0-9]+) (?P<label>.+)$', name)
label = match.group('label')
attempt = int(match.group('attempt'))
match = re.search("^Coverage (?P<attempt>[0-9]+) (?P<label>.+)$", name)
label = match.group("label")
attempt = int(match.group("attempt"))
jobs[label] = max(attempt, jobs.get(label, 0))

for label, attempt in jobs.items():
name = 'Coverage {attempt} {label}'.format(label=label, attempt=attempt)
name = "Coverage {attempt} {label}".format(label=label, attempt=attempt)
source = os.path.join(source_directory, name)
source_files = os.listdir(source)

for source_file in source_files:
source_path = os.path.join(source, source_file)
destination_path = os.path.join(destination_directory, source_file + '.' + label)
destination_path = os.path.join(destination_directory, source_file + "." + label)
print('"%s" -> "%s"' % (source_path, destination_path))
shutil.copyfile(source_path, destination_path)
count += 1

print('Coverage file count: %d' % count)
print('##vso[task.setVariable variable=coverageFileCount]%d' % count)
print('##vso[task.setVariable variable=outputPath]%s' % output_path)
print("Coverage file count: %d" % count)
print("##vso[task.setVariable variable=coverageFileCount]%d" % count)
print("##vso[task.setVariable variable=outputPath]%s" % output_path)


if __name__ == '__main__':
if __name__ == "__main__":
main()
11 changes: 6 additions & 5 deletions .azure-pipelines/scripts/time-command.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
#!/usr/bin/env python
"""Prepends a relative timestamp to each input line from stdin and writes it to stdout."""

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type

import sys
Expand All @@ -12,14 +13,14 @@ def main():
"""Main program entry point."""
start = time.time()

sys.stdin.reconfigure(errors='surrogateescape')
sys.stdout.reconfigure(errors='surrogateescape')
sys.stdin.reconfigure(errors="surrogateescape")
sys.stdout.reconfigure(errors="surrogateescape")

for line in sys.stdin:
seconds = time.time() - start
sys.stdout.write('%02d:%02d %s' % (seconds // 60, seconds % 60, line))
sys.stdout.write("%02d:%02d %s" % (seconds // 60, seconds % 60, line))
sys.stdout.flush()


if __name__ == '__main__':
if __name__ == "__main__":
main()
4 changes: 2 additions & 2 deletions plugins/doc_fragments/hcloud.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


class ModuleDocFragment(object):
DOCUMENTATION = '''
DOCUMENTATION = """
options:
api_token:
description:
Expand All @@ -26,4 +26,4 @@ class ModuleDocFragment(object):
- name: Documentation for Hetzner Cloud API
description: Complete reference for the Hetzner Cloud API.
link: https://docs.hetzner.cloud/
'''
"""
61 changes: 33 additions & 28 deletions plugins/inventory/hcloud.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
# Copyright (c) 2019 Hetzner Cloud GmbH <[email protected]>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)

from __future__ import (absolute_import, division, print_function)
from __future__ import absolute_import, division, print_function

__metaclass__ = type

DOCUMENTATION = r'''
DOCUMENTATION = r"""
name: hcloud
author:
- Lukas Kaemmerling (@lkaemmerling)
Expand Down Expand Up @@ -84,7 +84,7 @@
type: list
elements: str
required: false
'''
"""

EXAMPLES = r"""
# Minimal example. `HCLOUD_TOKEN` is exposed in environment.
Expand Down Expand Up @@ -127,18 +127,21 @@
try:
from hcloud import hcloud
from hcloud import APIException

HAS_HCLOUD = True
except ImportError:
HAS_HCLOUD = False


class InventoryModule(BaseInventoryPlugin, Constructable):
NAME = 'hetzner.hcloud.hcloud'
NAME = "hetzner.hcloud.hcloud"

def _configure_hcloud_client(self):
self.token_env = self.get_option("token_env")
self.templar.available_variables = self._vars
self.api_token = self.templar.template(self.get_option("token"), fail_on_undefined=False) or os.getenv(self.token_env)
self.api_token = self.templar.template(self.get_option("token"), fail_on_undefined=False) or os.getenv(
self.token_env
)
if self.api_token is None:
raise AnsibleError(
"Please specify a token, via the option token, via environment variable HCLOUD_TOKEN "
Expand All @@ -147,10 +150,12 @@ def _configure_hcloud_client(self):

self.endpoint = os.getenv("HCLOUD_ENDPOINT") or "https://api.hetzner.cloud/v1"

self.client = hcloud.Client(token=self.api_token,
api_endpoint=self.endpoint,
application_name="ansible-inventory",
application_version=__version__)
self.client = hcloud.Client(
token=self.api_token,
api_endpoint=self.endpoint,
application_name="ansible-inventory",
application_version=__version__,
)

def _test_hcloud_token(self):
try:
Expand All @@ -168,14 +173,15 @@ def _get_servers(self):

def _filter_servers(self):
if self.get_option("network"):
network = self.templar.template(self.get_option("network"), fail_on_undefined=False) or self.get_option("network")
network = self.templar.template(self.get_option("network"), fail_on_undefined=False) or self.get_option(
"network"
)
try:
self.network = self.client.networks.get_by_name(network)
if self.network is None:
self.network = self.client.networks.get_by_id(network)
except APIException:
raise AnsibleError(
"The given network is not found.")
raise AnsibleError("The given network is not found.")

tmp = []
for server in self.servers:
Expand Down Expand Up @@ -225,16 +231,17 @@ def _set_server_attributes(self, server):

if server.public_net.ipv6:
self.inventory.set_variable(server.name, "ipv6_network", to_native(server.public_net.ipv6.network))
self.inventory.set_variable(server.name, "ipv6_network_mask", to_native(server.public_net.ipv6.network_mask))
self.inventory.set_variable(server.name, "ipv6", to_native(self._first_ipv6_address(server.public_net.ipv6.ip)))
self.inventory.set_variable(
server.name, "ipv6_network_mask", to_native(server.public_net.ipv6.network_mask)
)
self.inventory.set_variable(
server.name, "ipv6", to_native(self._first_ipv6_address(server.public_net.ipv6.ip))
)

self.inventory.set_variable(
server.name,
"private_networks",
[
{"name": n.network.name, "id": n.network.id, "ip": n.ip}
for n in server.private_net
],
[{"name": n.network.name, "id": n.network.id, "ip": n.ip} for n in server.private_net],
)

if self.get_option("network"):
Expand Down Expand Up @@ -306,18 +313,14 @@ def _get_server_ansible_host(self, server):
return to_native(server_private_network.ip)

else:
raise AnsibleError(
"You can only connect via private IPv4 if you specify a network")
raise AnsibleError("You can only connect via private IPv4 if you specify a network")

def _first_ipv6_address(self, network):
return next(IPv6Network(network).hosts())

def verify_file(self, path):
"""Return the possibly of a file being consumable by this plugin."""
return (
super(InventoryModule, self).verify_file(path) and
path.endswith(("hcloud.yaml", "hcloud.yml"))
)
return super(InventoryModule, self).verify_file(path) and path.endswith(("hcloud.yaml", "hcloud.yml"))

def parse(self, inventory, loader, path, cache=True):
super(InventoryModule, self).parse(inventory, loader, path, cache)
Expand All @@ -339,13 +342,15 @@ def parse(self, inventory, loader, path, cache=True):
self._set_server_attributes(server)

# Use constructed if applicable
strict = self.get_option('strict')
strict = self.get_option("strict")

# Composed variables
self._set_composite_vars(self.get_option('compose'), self.inventory.get_host(server.name).get_vars(), server.name, strict=strict)
self._set_composite_vars(
self.get_option("compose"), self.inventory.get_host(server.name).get_vars(), server.name, strict=strict
)

# Complex groups based on jinja2 conditionals, hosts that meet the conditional are added to group
self._add_host_to_composed_groups(self.get_option('groups'), {}, server.name, strict=strict)
self._add_host_to_composed_groups(self.get_option("groups"), {}, server.name, strict=strict)

# Create groups based on variable values and add the corresponding hosts to it
self._add_host_to_keyed_groups(self.get_option('keyed_groups'), {}, server.name, strict=strict)
self._add_host_to_keyed_groups(self.get_option("keyed_groups"), {}, server.name, strict=strict)
38 changes: 13 additions & 25 deletions plugins/modules/hcloud_certificate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

__metaclass__ = type

DOCUMENTATION = '''
DOCUMENTATION = """
---
module: hcloud_certificate
Expand Down Expand Up @@ -68,7 +68,7 @@
extends_documentation_fragment:
- hetzner.hcloud.hcloud
'''
"""

EXAMPLES = """
- name: Create a basic certificate
Expand Down Expand Up @@ -158,36 +158,28 @@ def _prepare_result(self):
"not_valid_before": to_native(self.hcloud_certificate.not_valid_before),
"not_valid_after": to_native(self.hcloud_certificate.not_valid_after),
"domain_names": [to_native(domain) for domain in self.hcloud_certificate.domain_names],
"labels": self.hcloud_certificate.labels
"labels": self.hcloud_certificate.labels,
}

def _get_certificate(self):
try:
if self.module.params.get("id") is not None:
self.hcloud_certificate = self.client.certificates.get_by_id(
self.module.params.get("id")
)
self.hcloud_certificate = self.client.certificates.get_by_id(self.module.params.get("id"))
elif self.module.params.get("name") is not None:
self.hcloud_certificate = self.client.certificates.get_by_name(
self.module.params.get("name")
)
self.hcloud_certificate = self.client.certificates.get_by_name(self.module.params.get("name"))

except Exception as e:
self.module.fail_json(msg=e.message)

def _create_certificate(self):
self.module.fail_on_missing_params(
required_params=["name"]
)
self.module.fail_on_missing_params(required_params=["name"])

params = {
"name": self.module.params.get("name"),
"labels": self.module.params.get("labels")
"labels": self.module.params.get("labels"),
}
if self.module.params.get('type') == 'uploaded':
self.module.fail_on_missing_params(
required_params=["certificate", "private_key"]
)
if self.module.params.get("type") == "uploaded":
self.module.fail_on_missing_params(required_params=["certificate", "private_key"])
params["certificate"] = self.module.params.get("certificate")
params["private_key"] = self.module.params.get("private_key")
if not self.module.check_mode:
Expand All @@ -196,9 +188,7 @@ def _create_certificate(self):
except Exception as e:
self.module.fail_json(msg=e.message)
else:
self.module.fail_on_missing_params(
required_params=["domain_names"]
)
self.module.fail_on_missing_params(required_params=["domain_names"])
params["domain_names"] = self.module.params.get("domain_names")
if not self.module.check_mode:
try:
Expand All @@ -214,9 +204,7 @@ def _update_certificate(self):
try:
name = self.module.params.get("name")
if name is not None and self.hcloud_certificate.name != name:
self.module.fail_on_missing_params(
required_params=["id"]
)
self.module.fail_on_missing_params(required_params=["id"])
if not self.module.check_mode:
self.hcloud_certificate.update(name=name)
self._mark_as_changed()
Expand Down Expand Up @@ -268,8 +256,8 @@ def define_module():
},
**Hcloud.base_module_arguments()
),
required_one_of=[['id', 'name']],
required_if=[['state', 'present', ['name']]],
required_one_of=[["id", "name"]],
required_if=[["state", "present", ["name"]]],
supports_check_mode=True,
)

Expand Down
Loading

0 comments on commit 7601220

Please sign in to comment.