forked from microsoft/debugpy
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
73 lines (54 loc) · 2.07 KB
/
Copy pathcode.py
File metadata and controls
73 lines (54 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root
# for license information.
"""Helpers to work with Python code.
"""
import py.path
import re
_marked_line_numbers_cache = {}
def get_marked_line_numbers(path):
"""Given a path to a Python source file, extracts line numbers for all lines
that are marked with #@. For example, given this file::
print(1) # @foo
print(2)
print(3) # @bar,baz
the function will return::
{"foo": 1, "bar": 3, "baz": 3}
"""
if isinstance(path, py.path.local):
path = path.strpath
try:
return _marked_line_numbers_cache[path]
except KeyError:
pass
# Read as bytes to avoid decoding errors.
with open(path, "rb") as f:
lines = {}
for i, line in enumerate(f):
match = re.search(rb"#\s*@(.+?)\s*$", line)
if match:
markers = match.group(1).decode("ascii")
for marker in markers.split(","):
lines[marker] = i + 1
_marked_line_numbers_cache[path] = lines
return lines
def get_index_of_first_non_whitespace_char(path, lineNum):
"""Given a path to a Python source file and a line number,
get the index of the first non whitespace char on that line.
If the line is empty or contains only whitespace, return 0
"""
if isinstance(path, py.path.local):
path = path.strpath
# Read as bytes to avoid decoding errors.
with open(path, "rb") as f:
# enumerate the lines in the file, using 1-indexing
for i, line in enumerate(f, 1):
# keep going until we hit the specified line
if i < lineNum:
continue
# we hit the specified line, decode it and parse the whitespace
decodedLine = line.decode("ascii")
index = len(decodedLine) - len(decodedLine.lstrip())
return index
# if we get here, the line num was out of bounds
raise "File does not contain lineNum = " + lineNum