-
-
Notifications
You must be signed in to change notification settings - Fork 864
Expand file tree
/
Copy pathutil.py
More file actions
215 lines (160 loc) · 6.06 KB
/
util.py
File metadata and controls
215 lines (160 loc) · 6.06 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
# Copyright (c) 2014-present PlatformIO <contact@platformio.org>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import datetime
import functools
import os
import platform
import re
import shutil
import time
import click
from platformio import __version__
# pylint: disable=unused-import
from platformio.device.list.util import list_serial_ports as get_serial_ports
from platformio.fs import cd, load_json
from platformio.proc import exec_command
# pylint: enable=unused-import
# also export list_serial_ports as get_serialports to be
# backward compatibility with arduinosam versions 3.9.0 to 3.5.0 (and possibly others)
get_serialports = get_serial_ports
class memoized:
def __init__(self, expire=0):
expire = str(expire)
if expire.isdigit():
expire = "%ss" % int((int(expire) / 1000))
tdmap = {"s": 1, "m": 60, "h": 3600, "d": 86400}
assert expire.endswith(tuple(tdmap))
self.expire = int(tdmap[expire[-1]] * int(expire[:-1]))
self.cache = {}
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
key = str(args) + str(kwargs)
if key not in self.cache or (
self.expire > 0 and self.cache[key][0] < time.time() - self.expire
):
self.cache[key] = (time.time(), func(*args, **kwargs))
return self.cache[key][1]
wrapper.reset = self._reset
return wrapper
def _reset(self):
self.cache.clear()
class throttle:
def __init__(self, threshold):
self.threshold = threshold # milliseconds
self.last = 0
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
diff = int(round((time.time() - self.last) * 1000))
if diff < self.threshold:
time.sleep((self.threshold - diff) * 0.001)
self.last = time.time()
return func(*args, **kwargs)
return wrapper
# Retry: Begin
class RetryException(Exception):
pass
class RetryNextException(RetryException):
pass
class RetryStopException(RetryException):
pass
class retry:
RetryNextException = RetryNextException
RetryStopException = RetryStopException
def __init__(self, timeout=0, step=0.25):
self.timeout = timeout
self.step = step
def __call__(self, func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
elapsed = 0
while True:
try:
return func(*args, **kwargs)
except self.RetryNextException:
pass
if elapsed >= self.timeout:
raise self.RetryStopException()
elapsed += self.step
time.sleep(self.step)
return wrapper
# Retry: End
def singleton(cls):
"""From PEP-318 http://www.python.org/dev/peps/pep-0318/#examples"""
_instances = {}
def get_instance(*args, **kwargs):
if cls not in _instances:
_instances[cls] = cls(*args, **kwargs)
return _instances[cls]
return get_instance
def get_systype():
# allow manual override, eg. for
# windows on arm64 systems with emulated x86
if "PLATFORMIO_SYSTEM_TYPE" in os.environ:
return os.environ.get("PLATFORMIO_SYSTEM_TYPE")
system = platform.system().lower()
arch = platform.machine().lower()
if system == "windows":
if not arch: # issue #4353
arch = "x86_" + platform.architecture()[0]
if "x86" in arch:
arch = "amd64" if "64" in arch else "x86"
if arch == "aarch64" and platform.architecture()[0] == "32bit":
arch = "armv7l"
return "%s_%s" % (system, arch) if arch else system
def pioversion_to_intstr():
"""Legacy for framework-zephyr/scripts/platformio/platformio-build-pre.py"""
vermatch = re.match(r"^([\d\.]+)", __version__)
assert vermatch
return [int(i) for i in vermatch.group(1).split(".")[:3]]
def items_to_list(items):
if isinstance(items, list):
return items
return [i.strip() for i in items.split(",") if i.strip()]
def items_in_list(needle, haystack):
needle = items_to_list(needle)
haystack = items_to_list(haystack)
if "*" in needle or "*" in haystack:
return True
return set(needle) & set(haystack)
def parse_datetime(datestr):
assert "T" in datestr and "Z" in datestr
return datetime.datetime.strptime(datestr, "%Y-%m-%dT%H:%M:%SZ")
def merge_dicts(d1, d2, path=None):
if path is None:
path = []
for key in d2:
if key in d1 and isinstance(d1[key], dict) and isinstance(d2[key], dict):
merge_dicts(d1[key], d2[key], path + [str(key)])
else:
d1[key] = d2[key]
return d1
def print_labeled_bar(label, is_error=False, fg=None, sep="="):
terminal_width = shutil.get_terminal_size().columns
width = len(click.unstyle(label))
half_line = sep * int((terminal_width - width - 2) / 2)
click.secho("%s %s %s" % (half_line, label, half_line), fg=fg, err=is_error)
def humanize_duration_time(duration):
if duration is None:
return duration
milliseconds = int(round(duration * 1000))
# Extract components using divmod (returns quotient and remainder)
hours, remainder = divmod(milliseconds, 3600000)
minutes, remainder = divmod(remainder, 60000)
seconds, millis = divmod(remainder, 1000)
return "{:02d}:{:02d}:{:02d}.{:03d}".format(hours, minutes, seconds, millis)
def strip_ansi_codes(text):
# pylint: disable=protected-access
return click._compat.strip_ansi(text)