blob: 4844eb88783491dd759ae1da6301e4f8ee66ed53 [file] [log] [blame]
Shawn O. Pearce68194f42009-04-10 16:48:52 -07001# Copyright (C) 2009 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
Shawn O. Pearcef4f04d92010-05-27 16:48:36 -070015import os
Shawn O. Pearce68194f42009-04-10 16:48:52 -070016import sys
Gavin Makedcaa942023-04-27 05:58:57 +000017import time
18
19try:
20 import threading as _threading
21except ImportError:
22 import dummy_threading as _threading
23
LaMont Jones47020ba2022-11-10 00:11:51 +000024from repo_trace import IsTraceToStderr
Shawn O. Pearce68194f42009-04-10 16:48:52 -070025
Shawn O. Pearcef4f04d92010-05-27 16:48:36 -070026_NOT_TTY = not os.isatty(2)
27
Mike Frysinger70d861f2019-08-26 15:22:36 -040028# This will erase all content in the current line (wherever the cursor is).
29# It does not move the cursor, so this is usually followed by \r to move to
30# column 0.
Gavin Makea2e3302023-03-11 06:46:20 +000031CSI_ERASE_LINE = "\x1b[2K"
Mike Frysinger70d861f2019-08-26 15:22:36 -040032
Mike Frysinger4c11aeb2022-04-19 02:30:09 -040033# This will erase all content in the current line after the cursor. This is
34# useful for partial updates & progress messages as the terminal can display
35# it better.
Gavin Makea2e3302023-03-11 06:46:20 +000036CSI_ERASE_LINE_AFTER = "\x1b[K"
Mike Frysinger4c11aeb2022-04-19 02:30:09 -040037
David Pursehouse819827a2020-02-12 15:20:19 +090038
Gavin Makedcaa942023-04-27 05:58:57 +000039def convert_to_hms(total):
40 """Converts a period of seconds to hours, minutes, and seconds."""
41 hours, rem = divmod(total, 3600)
42 mins, secs = divmod(rem, 60)
43 return int(hours), int(mins), secs
44
45
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050046def duration_str(total):
Gavin Makea2e3302023-03-11 06:46:20 +000047 """A less noisy timedelta.__str__.
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050048
Gavin Makea2e3302023-03-11 06:46:20 +000049 The default timedelta stringification contains a lot of leading zeros and
50 uses microsecond resolution. This makes for noisy output.
51 """
Gavin Makedcaa942023-04-27 05:58:57 +000052 hours, mins, secs = convert_to_hms(total)
Gavin Makea2e3302023-03-11 06:46:20 +000053 ret = "%.3fs" % (secs,)
54 if mins:
55 ret = "%im%s" % (mins, ret)
56 if hours:
57 ret = "%ih%s" % (hours, ret)
58 return ret
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050059
60
Gavin Makedcaa942023-04-27 05:58:57 +000061def elapsed_str(total):
62 """Returns seconds in the format [H:]MM:SS.
63
64 Does not display a leading zero for minutes if under 10 minutes. This should
65 be used when displaying elapsed time in a progress indicator.
66 """
67 hours, mins, secs = convert_to_hms(total)
68 ret = f"{int(secs):>02d}"
69 if total >= 3600:
70 # Show leading zeroes if over an hour.
71 ret = f"{mins:>02d}:{ret}"
72 else:
73 ret = f"{mins}:{ret}"
74 if hours:
75 ret = f"{hours}:{ret}"
76 return ret
77
78
Shawn O. Pearce68194f42009-04-10 16:48:52 -070079class Progress(object):
Gavin Makea2e3302023-03-11 06:46:20 +000080 def __init__(
81 self,
82 title,
83 total=0,
84 units="",
85 print_newline=False,
86 delay=True,
87 quiet=False,
Gavin Makedcaa942023-04-27 05:58:57 +000088 show_elapsed=False,
Gavin Makea2e3302023-03-11 06:46:20 +000089 ):
90 self._title = title
91 self._total = total
92 self._done = 0
Gavin Makedcaa942023-04-27 05:58:57 +000093 self._start = time.time()
Gavin Makea2e3302023-03-11 06:46:20 +000094 self._show = not delay
95 self._units = units
96 self._print_newline = print_newline
97 # Only show the active jobs section if we run more than one in parallel.
98 self._show_jobs = False
99 self._active = 0
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500100
Gavin Makedcaa942023-04-27 05:58:57 +0000101 # Save the last message for displaying on refresh.
102 self._last_msg = None
103 self._show_elapsed = show_elapsed
104 self._update_event = _threading.Event()
105 self._update_thread = _threading.Thread(
106 target=self._update_loop,
107 )
108 self._update_thread.daemon = True
109
Gavin Makea2e3302023-03-11 06:46:20 +0000110 # When quiet, never show any output. It's a bit hacky, but reusing the
111 # existing logic that delays initial output keeps the rest of the class
112 # clean. Basically we set the start time to years in the future.
113 if quiet:
114 self._show = False
115 self._start += 2**32
Gavin Makedcaa942023-04-27 05:58:57 +0000116 elif show_elapsed:
117 self._update_thread.start()
118
119 def _update_loop(self):
120 while True:
121 if self._update_event.is_set():
122 return
123 self.update(inc=0, msg=self._last_msg)
124 time.sleep(1)
Mike Frysinger151701e2021-04-13 15:07:21 -0400125
Gavin Makea2e3302023-03-11 06:46:20 +0000126 def start(self, name):
127 self._active += 1
128 if not self._show_jobs:
129 self._show_jobs = self._active > 1
130 self.update(inc=0, msg="started " + name)
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500131
Gavin Makea2e3302023-03-11 06:46:20 +0000132 def finish(self, name):
133 self.update(msg="finished " + name)
134 self._active -= 1
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700135
Gavin Makea2e3302023-03-11 06:46:20 +0000136 def update(self, inc=1, msg=""):
137 self._done += inc
Gavin Makedcaa942023-04-27 05:58:57 +0000138 self._last_msg = msg
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700139
Gavin Makea2e3302023-03-11 06:46:20 +0000140 if _NOT_TTY or IsTraceToStderr():
141 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700142
Gavin Makedcaa942023-04-27 05:58:57 +0000143 elapsed_sec = time.time() - self._start
Gavin Makea2e3302023-03-11 06:46:20 +0000144 if not self._show:
Gavin Makedcaa942023-04-27 05:58:57 +0000145 if 0.5 <= elapsed_sec:
Gavin Makea2e3302023-03-11 06:46:20 +0000146 self._show = True
147 else:
148 return
Shawn O. Pearce2810cbc2009-04-18 10:09:16 -0700149
Gavin Makea2e3302023-03-11 06:46:20 +0000150 if self._total <= 0:
151 sys.stderr.write(
152 "\r%s: %d,%s" % (self._title, self._done, CSI_ERASE_LINE_AFTER)
153 )
154 sys.stderr.flush()
155 else:
156 p = (100 * self._done) / self._total
157 if self._show_jobs:
158 jobs = "[%d job%s] " % (
159 self._active,
160 "s" if self._active > 1 else "",
161 )
162 else:
163 jobs = ""
Gavin Makedcaa942023-04-27 05:58:57 +0000164 if self._show_elapsed:
165 elapsed = f" {elapsed_str(elapsed_sec)} |"
166 else:
167 elapsed = ""
Gavin Makea2e3302023-03-11 06:46:20 +0000168 sys.stderr.write(
Gavin Makedcaa942023-04-27 05:58:57 +0000169 "\r%s: %2d%% %s(%d%s/%d%s)%s %s%s%s"
Gavin Makea2e3302023-03-11 06:46:20 +0000170 % (
171 self._title,
172 p,
173 jobs,
174 self._done,
175 self._units,
176 self._total,
177 self._units,
Gavin Makedcaa942023-04-27 05:58:57 +0000178 elapsed,
Gavin Makea2e3302023-03-11 06:46:20 +0000179 msg,
180 CSI_ERASE_LINE_AFTER,
181 "\n" if self._print_newline else "",
182 )
183 )
184 sys.stderr.flush()
Shawn O. Pearceb1168ff2009-04-16 08:00:42 -0700185
Gavin Makea2e3302023-03-11 06:46:20 +0000186 def end(self):
Gavin Makedcaa942023-04-27 05:58:57 +0000187 self._update_event.set()
Gavin Makea2e3302023-03-11 06:46:20 +0000188 if _NOT_TTY or IsTraceToStderr() or not self._show:
189 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700190
Gavin Makedcaa942023-04-27 05:58:57 +0000191 duration = duration_str(time.time() - self._start)
Gavin Makea2e3302023-03-11 06:46:20 +0000192 if self._total <= 0:
193 sys.stderr.write(
194 "\r%s: %d, done in %s%s\n"
195 % (self._title, self._done, duration, CSI_ERASE_LINE_AFTER)
196 )
197 sys.stderr.flush()
198 else:
199 p = (100 * self._done) / self._total
200 sys.stderr.write(
201 "\r%s: %3d%% (%d%s/%d%s), done in %s%s\n"
202 % (
203 self._title,
204 p,
205 self._done,
206 self._units,
207 self._total,
208 self._units,
209 duration,
210 CSI_ERASE_LINE_AFTER,
211 )
212 )
213 sys.stderr.flush()