Skip to content

Commit fc77c7f

Browse files
committed
run ruff format on some files
This is the result of running ruff format on all files currently not touched by any open PR. Signed-off-by: Jan Luebbe <jlu@pengutronix.de>
1 parent 81d768e commit fc77c7f

113 files changed

Lines changed: 1174 additions & 1147 deletions

File tree

Some content is hidden

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

contrib/coordinator-statsd.py

Lines changed: 2 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -72,11 +72,7 @@ async def report_reservations(session, tags, gauges):
7272
for group_name, group in groups.items():
7373
inc_gauge(
7474
gauges,
75-
".".join(
76-
["reservations", group_name]
77-
+ [group.get(t, "") for t in tags]
78-
+ [reservation.state.name]
79-
),
75+
".".join(["reservations", group_name] + [group.get(t, "") for t in tags] + [reservation.state.name]),
8076
)
8177

8278

@@ -92,9 +88,7 @@ async def report_places(session, tags, gauges):
9288

9389

9490
def main():
95-
parser = argparse.ArgumentParser(
96-
description="Report Labgrid usage metrics to statsd"
97-
)
91+
parser = argparse.ArgumentParser(description="Report Labgrid usage metrics to statsd")
9892
parser.add_argument(
9993
"-x",
10094
"--coordinator",

contrib/sync-places.py

Lines changed: 7 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -112,21 +112,21 @@ async def do_sync(session, args):
112112
print(f"Adding match '{match}' for place {name}")
113113

114114
if not args.dry_run:
115-
request = labgrid_coordinator_pb2.AddPlaceMatchRequest(placename=name, pattern=match, rename=rename)
115+
request = labgrid_coordinator_pb2.AddPlaceMatchRequest(
116+
placename=name, pattern=match, rename=rename
117+
)
116118
await session.stub.AddPlaceMatch(request)
117119
await session.sync_with_coordinator()
118120
changed = True
119121

120-
tags = { str(k): str(v) for k, v in config["places"][name].get("tags", {}).items() }
122+
tags = {str(k): str(v) for k, v in config["places"][name].get("tags", {}).items()}
121123

122124
if place_tags != tags:
123125
print(
124126
"Setting tags for place %s to %s"
125127
% (
126128
name,
127-
", ".join(
128-
"%s=%s" % (key, value) for (key, value) in tags.items()
129-
),
129+
", ".join("%s=%s" % (key, value) for (key, value) in tags.items()),
130130
)
131131
)
132132

@@ -146,10 +146,7 @@ async def do_dump(session, args):
146146
config = {"places": {}}
147147
for name, place in session.places.items():
148148
config["places"][name] = {
149-
"matches": [
150-
{repr(m): m.rename} if m.rename else repr(m)
151-
for m in place.matches
152-
],
149+
"matches": [{repr(m): m.rename} if m.rename else repr(m) for m in place.matches],
153150
"tags": {k: v for k, v in place.tags.items()},
154151
}
155152

@@ -191,9 +188,7 @@ async def do_dump(session, args):
191188
subparsers = parser.add_subparsers()
192189
subparsers.required = True
193190

194-
sync_parser = subparsers.add_parser(
195-
"sync", help="Synchronize coordinator places with file"
196-
)
191+
sync_parser = subparsers.add_parser("sync", help="Synchronize coordinator places with file")
197192
sync_parser.add_argument(
198193
"places",
199194
metavar="FILE",
Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
def test_shell(target):
2-
ssh_driver = target.get_driver('SSHDriver')
2+
ssh_driver = target.get_driver("SSHDriver")
33
target.activate(ssh_driver)
44

5-
stdout, stderr, returncode = ssh_driver.run('uname -r')
5+
stdout, stderr, returncode = ssh_driver.run("uname -r")
66

77
assert stdout
8-
print(f'Kernel {stdout}')
8+
print(f"Kernel {stdout}")

labgrid/autoinstall/main.py

Lines changed: 30 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
"""The autoinstall.main module runs an installation script automatically on multiple targets."""
2+
23
import ast
34
import argparse
45
import logging
@@ -20,44 +21,46 @@ def __init__(self, env, args, name):
2021
self.name = name
2122

2223
self.context = {
23-
'name': self.name,
24-
'env': self.env,
25-
'config': self.config,
24+
"name": self.name,
25+
"env": self.env,
26+
"config": self.config,
2627
}
2728
self.context.update(target_factory.resources)
2829
self.context.update(target_factory.drivers)
2930

3031
def _get_function(self, name, context):
31-
snippet = self.config.data['autoinstall'].get(name)
32+
snippet = self.config.data["autoinstall"].get(name)
3233
if not snippet:
3334
return None
3435

3536
code = f"def {name}():\n{textwrap.indent(snippet, ' ')}"
3637
tree = ast.parse(code, filename=self.env.config_file)
3738
ast.increment_lineno(tree, snippet.start_mark.line)
38-
co = compile(tree, filename=self.env.config_file, mode='exec')
39+
co = compile(tree, filename=self.env.config_file, mode="exec")
3940

4041
stage = {}
4142
exec(co, context, stage) # pylint: disable=exec-used
4243
return stage[name]
4344

4445
def _get_setup_function(self):
4546
context = self.context
46-
context['log'] = self.log.getChild('setup')
47-
setup = self._get_function('setup', self.context)
47+
context["log"] = self.log.getChild("setup")
48+
setup = self._get_function("setup", self.context)
4849
if setup is None:
50+
4951
def setup():
5052
pass
53+
5154
return setup
5255

5356
def _get_handler_function(self):
5457
context = self.context.copy()
55-
context['log'] = self.log.getChild('handler')
56-
handler = self._get_function('handler', context)
58+
context["log"] = self.log.getChild("handler")
59+
handler = self._get_function("handler", context)
5760
return handler
5861

5962
def _get_initial_resource(self):
60-
cls = self.config.data['autoinstall'].get('initial-resource')
63+
cls = self.config.data["autoinstall"].get("initial-resource")
6164
if not cls:
6265
return None
6366

@@ -69,7 +72,7 @@ def run(self):
6972

7073
try:
7174
self.target = self.env.get_target(self.name)
72-
self.context['target'] = self.target
75+
self.context["target"] = self.target
7376
if self.target is None:
7477
raise KeyError
7578
except Exception: # pylint: disable=broad-except
@@ -88,8 +91,7 @@ def run(self):
8891
def run_once(self):
8992
try:
9093
if self.initial_resource:
91-
self.log.info("waiting until %s is available",
92-
self.initial_resource.display_name)
94+
self.log.info("waiting until %s is available", self.initial_resource.display_name)
9395
while True:
9496
self.target.update_resources()
9597
if self.initial_resource.avail:
@@ -100,13 +102,11 @@ def run_once(self):
100102
self.target.update_resources()
101103
result = self.handler()
102104
if result is not None:
103-
self.log.warning("unexpected return value from handler: %s",
104-
repr(result))
105+
self.log.warning("unexpected return value from handler: %s", repr(result))
105106
self.log.info("completed handler")
106107

107108
if self.initial_resource:
108-
self.log.info("waiting until %s is unavailable",
109-
self.initial_resource.display_name)
109+
self.log.info("waiting until %s is unavailable", self.initial_resource.display_name)
110110
while True:
111111
self.target.update_resources()
112112
if not self.initial_resource.avail:
@@ -115,11 +115,9 @@ def run_once(self):
115115

116116
except NoResourceFoundError as e:
117117
if e.filter and len(e.filter) > 1:
118-
self.log.warning("resources %s not found, restarting",
119-
e.filter)
118+
self.log.warning("resources %s not found, restarting", e.filter)
120119
elif e.filter:
121-
self.log.warning("resource %s not found, restarting",
122-
next(iter(e.filter)))
120+
self.log.warning("resource %s not found, restarting", next(iter(e.filter)))
123121
else:
124122
self.log.warning("resource not found, restarting")
125123
except Exception: # pylint: disable=broad-except
@@ -141,24 +139,20 @@ def __init__(self, env, args):
141139
self.log = logging.getLogger("manager")
142140

143141
def configure(self):
144-
if not 'autoinstall' in self.env.config.data:
145-
self.log.error("no 'autoinstall' section found in '%s'",
146-
self.env.config_file)
142+
if not "autoinstall" in self.env.config.data:
143+
self.log.error("no 'autoinstall' section found in '%s'", self.env.config_file)
147144
return False
148145

149-
if not 'handler' in self.env.config.data['autoinstall']:
150-
self.log.error("no 'handler' definition found in '%s'",
151-
self.env.config_file)
146+
if not "handler" in self.env.config.data["autoinstall"]:
147+
self.log.error("no 'handler' definition found in '%s'", self.env.config_file)
152148
return False
153149

154150
self.handlers = {}
155-
for target_name in self.config.data.get('targets', {}).keys():
156-
self.handlers[target_name] = Handler(self.env, self.args,
157-
target_name)
151+
for target_name in self.config.data.get("targets", {}).keys():
152+
self.handlers[target_name] = Handler(self.env, self.args, target_name)
158153

159154
if not self.handlers:
160-
self.log.error("no targets found in '%s'",
161-
self.env.config_file)
155+
self.log.error("no targets found in '%s'", self.env.config_file)
162156
return False
163157

164158
return True
@@ -175,28 +169,14 @@ def join(self):
175169
for handler in self.handlers.values():
176170
handler.join()
177171

172+
178173
def main():
179174
basicConfig(level=logging.INFO)
180175

181176
parser = argparse.ArgumentParser()
182-
parser.add_argument(
183-
'-d',
184-
'--debug',
185-
action='store_true',
186-
default=False,
187-
help="enable debug mode"
188-
)
189-
parser.add_argument(
190-
'--once',
191-
action='store_true',
192-
default=False,
193-
help="handle each target only once"
194-
)
195-
parser.add_argument(
196-
'config',
197-
type=str,
198-
help="config file"
199-
)
177+
parser.add_argument("-d", "--debug", action="store_true", default=False, help="enable debug mode")
178+
parser.add_argument("--once", action="store_true", default=False, help="handle each target only once")
179+
parser.add_argument("config", type=str, help="config file")
200180

201181
args = parser.parse_args()
202182

labgrid/binding.py

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,7 @@ class BindingMixin:
4141

4242
# these are controlled by the Target
4343
target = attr.ib()
44-
name = attr.ib(
45-
validator=attr.validators.optional(attr.validators.instance_of(str)))
44+
name = attr.ib(validator=attr.validators.optional(attr.validators.instance_of(str)))
4645
state = attr.ib(default=BindingState.idle, init=False)
4746

4847
def __attrs_post_init__(self):
@@ -108,9 +107,7 @@ def check_bound(cls, func):
108107
@wraps(func)
109108
def wrapper(self, *_args, **_kwargs):
110109
if self.state is BindingState.active:
111-
raise StateError(
112-
f'{self} is active, but must be deactivated to call {func.__qualname__}'
113-
)
110+
raise StateError(f"{self} is active, but must be deactivated to call {func.__qualname__}")
114111
elif self.state is not BindingState.bound:
115112
raise StateError(
116113
f'{self} has not been bound, {func.__qualname__} cannot be called in state "{self.state.name}"' # pylint: disable=line-too-long
@@ -123,6 +120,7 @@ class NamedBinding:
123120
"""
124121
Marks a binding (or binding set) as requiring an explicit name.
125122
"""
123+
126124
def __init__(self, value):
127125
self.value = value
128126

labgrid/consoleloggingreporter.py

Lines changed: 11 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ class ConsoleLoggingReporter:
1111
Args:
1212
logpath (str): path to store the logfiles in
1313
"""
14+
1415
instance = None
1516

1617
@classmethod
@@ -49,42 +50,33 @@ def get_logfile(self, event):
4950
log = self._logcache[source]
5051
except KeyError:
5152
if source.name:
52-
name = f'console_{source.target.name}_{source.name}'
53+
name = f"console_{source.target.name}_{source.name}"
5354
else:
54-
name = f'console_{source.target.name}'
55+
name = f"console_{source.target.name}"
5556
name = os.path.join(self.logpath, name)
5657
try:
57-
log = self._logcache[source] = open(name, mode='ab',
58-
buffering=0)
58+
log = self._logcache[source] = open(name, mode="ab", buffering=0)
5959
except OSError as e:
6060
print(f"failed to open log file {name}: {e}", file=sys.stderr)
6161
log = self._logcache[source] = None
6262
if not log:
6363
return None
6464

6565
if source.name:
66-
log.write(
67-
f"Labgrid Console Logfile for {source.target.name} {source.name}\n"
68-
.encode("utf-8")
69-
)
66+
log.write(f"Labgrid Console Logfile for {source.target.name} {source.name}\n".encode("utf-8"))
7067
else:
71-
log.write(
72-
f"Labgrid Console Logfile for {source.target.name}\n"
73-
.encode("utf-8")
74-
)
75-
log.write(
76-
f"Logfile started at {datetime.now()}\n".encode("utf-8")
77-
)
78-
log.write("=== Log starts here ===\n".encode('utf-8'))
68+
log.write(f"Labgrid Console Logfile for {source.target.name}\n".encode("utf-8"))
69+
log.write(f"Logfile started at {datetime.now()}\n".encode("utf-8"))
70+
log.write("=== Log starts here ===\n".encode("utf-8"))
7971

8072
return log
8173

8274
def notify(self, event):
8375
"""This is the callback function for steps"""
8476
step = event.step
85-
if step.tag == 'console':
86-
if step.title == 'read':
87-
if event.data.get('state') == 'stop':
77+
if step.tag == "console":
78+
if step.title == "read":
79+
if event.data.get("state") == "stop":
8880
if step.result and step.source:
8981
log = self.get_logfile(event)
9082
if not log:

labgrid/driver/commandmixin.py

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ def __attrs_post_init__(self):
1515
super().__attrs_post_init__()
1616

1717
@Driver.check_active
18-
@step(args=['cmd', 'pattern'])
18+
@step(args=["cmd", "pattern"])
1919
def wait_for(self, cmd, pattern, timeout=30.0, sleepduration=1):
2020
"""
2121
Wait until the pattern is detected in the output of cmd. Raises
@@ -34,7 +34,7 @@ def wait_for(self, cmd, pattern, timeout=30.0, sleepduration=1):
3434
raise ExecutionError("Wait timeout expired")
3535

3636
@Driver.check_active
37-
@step(args=['cmd', 'expected', 'tries', 'timeout', 'sleepduration'])
37+
@step(args=["cmd", "expected", "tries", "timeout", "sleepduration"])
3838
def poll_until_success(self, cmd, *, expected=0, tries=None, timeout=30.0, sleepduration=1):
3939
"""
4040
Poll a command until a specific exit code is detected.
@@ -63,8 +63,7 @@ def poll_until_success(self, cmd, *, expected=0, tries=None, timeout=30.0, sleep
6363
break
6464
return False
6565

66-
def _run_check(self, cmd: str, *, timeout=30, codec: str = "utf-8",
67-
decodeerrors: str = "strict"):
66+
def _run_check(self, cmd: str, *, timeout=30, codec: str = "utf-8", decodeerrors: str = "strict"):
6867
"""
6968
Internal function which runs the specified command on the shell and
7069
returns the output if successful, raises ExecutionError otherwise.
@@ -75,14 +74,13 @@ def _run_check(self, cmd: str, *, timeout=30, codec: str = "utf-8",
7574
Returns:
7675
List[str]: stdout of the executed command
7776
"""
78-
stdout, stderr, exitcode = self._run(cmd, timeout=timeout, codec=codec,
79-
decodeerrors=decodeerrors)
77+
stdout, stderr, exitcode = self._run(cmd, timeout=timeout, codec=codec, decodeerrors=decodeerrors)
8078
if exitcode != 0:
8179
raise ExecutionError(cmd, stdout, stderr)
8280
return stdout
8381

8482
@Driver.check_active
85-
@step(args=['cmd'], result=True)
83+
@step(args=["cmd"], result=True)
8684
def run_check(self, cmd: str, *, timeout=30, codec="utf-8", decodeerrors="strict"):
8785
"""
8886
External run_check function, only available if the driver is active.

0 commit comments

Comments
 (0)