Skip to content

Commit 16de387

Browse files
committed
debugpy: Format code.
Signed-off-by: Jos Verlinde <[email protected]>
1 parent 26c6e3a commit 16de387

File tree

3 files changed

+94
-61
lines changed

3 files changed

+94
-61
lines changed

python-ecosys/debugpy/debugpy/common/messaging.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -64,7 +64,9 @@ def send_response(self, command, request_seq, success=True, body=None, message=N
6464
if message is not None:
6565
kwargs["message"] = message
6666

67-
self._debug_print(f"[DAP] SEND: response {command} (req_seq={request_seq}, success={success})")
67+
self._debug_print(
68+
f"[DAP] SEND: response {command} (req_seq={request_seq}, success={success})"
69+
)
6870
if body:
6971
self._debug_print(f"[DAP] body: {body}")
7072
if message:
@@ -95,14 +97,14 @@ def recv_message(self):
9597
self._recv_buffer += data
9698
except OSError as e:
9799
# Handle timeout and other socket errors
98-
if hasattr(e, 'errno') and e.errno in (11, 35): # EAGAIN, EWOULDBLOCK
100+
if hasattr(e, "errno") and e.errno in (11, 35): # EAGAIN, EWOULDBLOCK
99101
return None # No data available
100102
self.closed = True
101103
return None
102104

103105
header_end = self._recv_buffer.find(b"\r\n\r\n")
104106
header_str = self._recv_buffer[:header_end].decode("utf-8")
105-
self._recv_buffer = self._recv_buffer[header_end + 4:]
107+
self._recv_buffer = self._recv_buffer[header_end + 4 :]
106108

107109
# Parse Content-Length
108110
content_length = 0
@@ -123,7 +125,7 @@ def recv_message(self):
123125
return None
124126
self._recv_buffer += data
125127
except OSError as e:
126-
if hasattr(e, 'errno') and e.errno in (11, 35): # EAGAIN, EWOULDBLOCK
128+
if hasattr(e, "errno") and e.errno in (11, 35): # EAGAIN, EWOULDBLOCK
127129
return None
128130
self.closed = True
129131
return None
@@ -134,7 +136,9 @@ def recv_message(self):
134136
# Parse JSON
135137
try:
136138
message = json.loads(body.decode("utf-8"))
137-
self._debug_print(f"[DAP] Successfully received message: {message.get('type')} {message.get('command', message.get('event', 'unknown'))}")
139+
self._debug_print(
140+
f"[DAP] Successfully received message: {message.get('type')} {message.get('command', message.get('event', 'unknown'))}"
141+
)
138142
return message
139143
except (ValueError, UnicodeDecodeError) as e:
140144
print(f"[DAP] JSON parse error: {e}")

python-ecosys/debugpy/debugpy/public_api.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,11 @@
1111

1212
def listen(port=DEFAULT_PORT, host=DEFAULT_HOST):
1313
"""Start listening for debugger connections.
14-
14+
1515
Args:
1616
port: Port number to listen on (default: 5678)
1717
host: Host address to bind to (default: "127.0.0.1")
18-
18+
1919
Returns:
2020
(host, port) tuple of the actual listening address
2121
"""
@@ -52,7 +52,7 @@ def listen(port=DEFAULT_PORT, host=DEFAULT_HOST):
5252
# Handle just the initialize request, then return immediately
5353
print("[DAP] Waiting for initialize request...")
5454
init_message = _debug_session.channel.recv_message()
55-
if init_message and init_message.get('command') == 'initialize':
55+
if init_message and init_message.get("command") == "initialize":
5656
_debug_session._handle_message(init_message)
5757
print("[DAP] Initialize request handled - returning control immediately")
5858
else:
@@ -74,14 +74,15 @@ def listen(port=DEFAULT_PORT, host=DEFAULT_HOST):
7474

7575
return (host, port)
7676

77+
7778
def format_client_addr(client_addr):
7879
"""Format client address using socket module methods"""
7980
if isinstance(client_addr, (tuple, list)):
8081
# Already in (ip, port) format
8182
return f"{client_addr[0]}:{client_addr[1]}"
8283
elif isinstance(client_addr, bytes) and len(client_addr) >= 8:
8384
# Extract port (bytes 2-4, network byte order)
84-
port = struct.unpack('!H', client_addr[2:4])[0]
85+
port = struct.unpack("!H", client_addr[2:4])[0]
8586
# Extract IP address (bytes 4-8) using inet_ntoa
8687
ip_packed = client_addr[4:8]
8788
try:
@@ -90,11 +91,12 @@ def format_client_addr(client_addr):
9091
return f"{ip_addr}:{port}"
9192
except:
9293
# Fallback if inet_ntoa not available (MicroPython)
93-
ip_addr = '.'.join(str(b) for b in ip_packed)
94+
ip_addr = ".".join(str(b) for b in ip_packed)
9495
return f"{ip_addr}:{port}"
9596
else:
9697
return str(client_addr)
9798

99+
98100
def wait_for_client():
99101
"""Wait for the debugger client to connect and initialize."""
100102
global _debug_session
@@ -109,7 +111,7 @@ def breakpoint():
109111
_debug_session.trigger_breakpoint()
110112
else:
111113
# Fallback to built-in breakpoint if available
112-
if hasattr(__builtins__, 'breakpoint'):
114+
if hasattr(__builtins__, "breakpoint"):
113115
__builtins__.breakpoint()
114116

115117

@@ -120,7 +122,7 @@ def debug_this_thread():
120122
_debug_session.debug_this_thread()
121123
else:
122124
# Install trace function even if no session yet
123-
if hasattr(sys, 'settrace'):
125+
if hasattr(sys, "settrace"):
124126
sys.settrace(_default_trace_func)
125127
else:
126128
raise RuntimeError("MICROPY_PY_SYS_SETTRACE required")
@@ -132,7 +134,6 @@ def _default_trace_func(frame, event, arg):
132134
return None
133135

134136

135-
136137
def is_client_connected():
137138
"""Check if a debugger client is connected."""
138139
global _debug_session

python-ecosys/debugpy/debugpy/server/debug_session.py

Lines changed: 76 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,34 @@
33
import sys
44
from ..common.messaging import JsonMessageChannel
55
from ..common.constants import (
6-
CMD_INITIALIZE, CMD_LAUNCH, CMD_ATTACH, CMD_SET_BREAKPOINTS,
7-
CMD_CONTINUE, CMD_NEXT, CMD_STEP_IN, CMD_STEP_OUT, CMD_PAUSE,
8-
CMD_STACK_TRACE, CMD_SCOPES, CMD_VARIABLES, CMD_EVALUATE, CMD_DISCONNECT,
9-
CMD_CONFIGURATION_DONE, CMD_THREADS, CMD_SOURCE, EVENT_INITIALIZED, EVENT_STOPPED, EVENT_CONTINUED, EVENT_TERMINATED,
10-
STOP_REASON_BREAKPOINT, STOP_REASON_STEP, STOP_REASON_PAUSE,
11-
TRACE_CALL, TRACE_LINE, TRACE_RETURN, TRACE_EXCEPTION
6+
CMD_INITIALIZE,
7+
CMD_LAUNCH,
8+
CMD_ATTACH,
9+
CMD_SET_BREAKPOINTS,
10+
CMD_CONTINUE,
11+
CMD_NEXT,
12+
CMD_STEP_IN,
13+
CMD_STEP_OUT,
14+
CMD_PAUSE,
15+
CMD_STACK_TRACE,
16+
CMD_SCOPES,
17+
CMD_VARIABLES,
18+
CMD_EVALUATE,
19+
CMD_DISCONNECT,
20+
CMD_CONFIGURATION_DONE,
21+
CMD_THREADS,
22+
CMD_SOURCE,
23+
EVENT_INITIALIZED,
24+
EVENT_STOPPED,
25+
EVENT_CONTINUED,
26+
EVENT_TERMINATED,
27+
STOP_REASON_BREAKPOINT,
28+
STOP_REASON_STEP,
29+
STOP_REASON_PAUSE,
30+
TRACE_CALL,
31+
TRACE_LINE,
32+
TRACE_RETURN,
33+
TRACE_EXCEPTION,
1234
)
1335
from .pdb_adapter import PdbAdapter
1436

@@ -34,7 +56,7 @@ def _debug_print(self, message):
3456

3557
@property
3658
def _baremetal(self) -> bool:
37-
return sys.platform not in ("linux") # to be expanded
59+
return sys.platform not in ("linux") # to be expanded
3860

3961
def start(self):
4062
"""Start the debug session message loop."""
@@ -77,7 +99,7 @@ def initialize_connection(self):
7799
message_count += 1
78100

79101
# Just wait for attach, then we can return control
80-
if message.get('command') == 'attach':
102+
if message.get("command") == "attach":
81103
attached = True
82104
print("[DAP] ✅ Attach received - returning control to main thread")
83105
break
@@ -191,12 +213,12 @@ def _handle_request(self, message):
191213
elif command == CMD_SOURCE:
192214
self._handle_source(seq, args)
193215
else:
194-
self.channel.send_response(command, seq, success=False,
195-
message=f"Unknown command: {command}")
216+
self.channel.send_response(
217+
command, seq, success=False, message=f"Unknown command: {command}"
218+
)
196219

197220
except Exception as e:
198-
self.channel.send_response(command, seq, success=False,
199-
message=str(e))
221+
self.channel.send_response(command, seq, success=False, message=str(e))
200222

201223
def _handle_initialize(self, seq, args):
202224
"""Handle initialize request."""
@@ -251,16 +273,15 @@ def _handle_attach(self, seq, args):
251273
self.debug_logging = args.get("logToFile", False)
252274

253275
self._debug_print(f"[DAP] Processing attach request with args: {args}")
254-
print(f"[DAP] Debug logging {'enabled' if self.debug_logging else 'disabled'} (logToFile={self.debug_logging})")
255-
276+
print(
277+
f"[DAP] Debug logging {'enabled' if self.debug_logging else 'disabled'} (logToFile={self.debug_logging})"
278+
)
279+
256280
# get debugger root and debugee root from pathMappings
257-
for pm in args.get("pathMappings",[]):
281+
for pm in args.get("pathMappings", []):
258282
# debugee - debugger
259-
self.pdb.path_mappings.append(
260-
(pm.get("remoteRoot", "./"),
261-
pm.get("localRoot", "./"))
262-
)
263-
# # TODO: justMyCode, debugOptions ,
283+
self.pdb.path_mappings.append((pm.get("remoteRoot", "./"), pm.get("localRoot", "./")))
284+
# # TODO: justMyCode, debugOptions ,
264285

265286
# Enable trace function
266287
self.pdb.set_trace_function(self._trace_function)
@@ -282,8 +303,9 @@ def _handle_set_breakpoints(self, seq, args):
282303
# Set breakpoints in pdb adapter
283304
actual_breakpoints = self.pdb.set_breakpoints(filename, breakpoints)
284305

285-
self.channel.send_response(CMD_SET_BREAKPOINTS, seq,
286-
body={"breakpoints": actual_breakpoints})
306+
self.channel.send_response(
307+
CMD_SET_BREAKPOINTS, seq, body={"breakpoints": actual_breakpoints}
308+
)
287309

288310
def _handle_continue(self, seq, args):
289311
"""Handle continue request."""
@@ -322,8 +344,11 @@ def _handle_pause(self, seq, args):
322344
def _handle_stack_trace(self, seq, args):
323345
"""Handle stackTrace request."""
324346
stack_frames = self.pdb.get_stack_trace()
325-
self.channel.send_response(CMD_STACK_TRACE, seq,
326-
body={"stackFrames": stack_frames, "totalFrames": len(stack_frames)})
347+
self.channel.send_response(
348+
CMD_STACK_TRACE,
349+
seq,
350+
body={"stackFrames": stack_frames, "totalFrames": len(stack_frames)},
351+
)
327352

328353
def _handle_scopes(self, seq, args):
329354
"""Handle scopes request."""
@@ -345,18 +370,17 @@ def _handle_evaluate(self, seq, args):
345370
frame_id = args.get("frameId")
346371
context = args.get("context", "watch")
347372
if not expression:
348-
self.channel.send_response(CMD_EVALUATE, seq, success=False,
349-
message="No expression provided")
373+
self.channel.send_response(
374+
CMD_EVALUATE, seq, success=False, message="No expression provided"
375+
)
350376
return
351377
try:
352378
result = self.pdb.evaluate_expression(expression, frame_id)
353-
self.channel.send_response(CMD_EVALUATE, seq, body={
354-
"result": str(result),
355-
"variablesReference": 0
356-
})
379+
self.channel.send_response(
380+
CMD_EVALUATE, seq, body={"result": str(result), "variablesReference": 0}
381+
)
357382
except Exception as e:
358-
self.channel.send_response(CMD_EVALUATE, seq, success=False,
359-
message=str(e))
383+
self.channel.send_response(CMD_EVALUATE, seq, success=False, message=str(e))
360384

361385
def _handle_disconnect(self, seq, args):
362386
"""Handle disconnect request."""
@@ -372,10 +396,7 @@ def _handle_configuration_done(self, seq, args):
372396
def _handle_threads(self, seq, args):
373397
"""Handle threads request."""
374398
# MicroPython is single-threaded, so return one thread
375-
threads = [{
376-
"id": self.thread_id,
377-
"name": "main"
378-
}]
399+
threads = [{"id": self.thread_id, "name": "main"}]
379400
self.channel.send_response(CMD_THREADS, seq, body={"threads": threads})
380401

381402
def _handle_source(self, seq, args):
@@ -395,10 +416,13 @@ def _handle_source(self, seq, args):
395416
content = f.read()
396417
self.channel.send_response(CMD_SOURCE, seq, body={"content": content})
397418
except Exception:
398-
self.channel.send_response(CMD_SOURCE, seq, success=False,
399-
message="cancelled"
400-
# message=f"Could not read source: {e}"
401-
)
419+
self.channel.send_response(
420+
CMD_SOURCE,
421+
seq,
422+
success=False,
423+
message="cancelled",
424+
# message=f"Could not read source: {e}"
425+
)
402426

403427
def _trace_function(self, frame, event, arg):
404428
"""Trace function called by sys.settrace."""
@@ -407,19 +431,23 @@ def _trace_function(self, frame, event, arg):
407431

408432
# Handle breakpoints and stepping
409433
if self.pdb.should_stop(frame, event, arg):
410-
self._send_stopped_event(STOP_REASON_BREAKPOINT if self.pdb.hit_breakpoint else
411-
STOP_REASON_STEP if self.stepping else STOP_REASON_PAUSE)
434+
self._send_stopped_event(
435+
STOP_REASON_BREAKPOINT
436+
if self.pdb.hit_breakpoint
437+
else STOP_REASON_STEP
438+
if self.stepping
439+
else STOP_REASON_PAUSE
440+
)
412441
# Wait for continue command
413442
self.pdb.wait_for_continue()
414443

415444
return self._trace_function
416445

417446
def _send_stopped_event(self, reason):
418447
"""Send stopped event to client."""
419-
self.channel.send_event(EVENT_STOPPED,
420-
reason=reason,
421-
threadId=self.thread_id,
422-
allThreadsStopped=True)
448+
self.channel.send_event(
449+
EVENT_STOPPED, reason=reason, threadId=self.thread_id, allThreadsStopped=True
450+
)
423451

424452
def wait_for_client(self):
425453
"""Wait for client to initialize."""
@@ -433,7 +461,7 @@ def trigger_breakpoint(self):
433461

434462
def debug_this_thread(self):
435463
"""Enable debugging for current thread."""
436-
if hasattr(sys, 'settrace'):
464+
if hasattr(sys, "settrace"):
437465
sys.settrace(self._trace_function)
438466

439467
def is_connected(self):
@@ -443,7 +471,7 @@ def is_connected(self):
443471
def disconnect(self):
444472
"""Disconnect from client."""
445473
self.connected = False
446-
if hasattr(sys, 'settrace'):
474+
if hasattr(sys, "settrace"):
447475
sys.settrace(None)
448476
self.pdb.cleanup()
449477
self.channel.close()

0 commit comments

Comments
 (0)