blob: f2edf14407d2045758cf68afa750d0bb3ff4760b [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
Gavin Makb2263ba2023-06-07 21:59:17 +000026_TTY = sys.stderr.isatty()
Shawn O. Pearcef4f04d92010-05-27 16:48:36 -070027
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
Gavin Mak04cba4a2023-05-24 21:28:28 +000079def jobs_str(total):
80 return f"{total} job{'s' if total > 1 else ''}"
81
82
Shawn O. Pearce68194f42009-04-10 16:48:52 -070083class Progress(object):
Gavin Makea2e3302023-03-11 06:46:20 +000084 def __init__(
85 self,
86 title,
87 total=0,
88 units="",
Gavin Makea2e3302023-03-11 06:46:20 +000089 delay=True,
90 quiet=False,
Gavin Makedcaa942023-04-27 05:58:57 +000091 show_elapsed=False,
Gavin Mak551285f2023-05-04 04:48:43 +000092 elide=False,
Gavin Makea2e3302023-03-11 06:46:20 +000093 ):
94 self._title = title
95 self._total = total
96 self._done = 0
Gavin Makedcaa942023-04-27 05:58:57 +000097 self._start = time.time()
Gavin Makea2e3302023-03-11 06:46:20 +000098 self._show = not delay
99 self._units = units
Gavin Makb2263ba2023-06-07 21:59:17 +0000100 self._elide = elide and _TTY
101
Gavin Makea2e3302023-03-11 06:46:20 +0000102 # Only show the active jobs section if we run more than one in parallel.
103 self._show_jobs = False
104 self._active = 0
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500105
Gavin Makedcaa942023-04-27 05:58:57 +0000106 # Save the last message for displaying on refresh.
107 self._last_msg = None
108 self._show_elapsed = show_elapsed
109 self._update_event = _threading.Event()
110 self._update_thread = _threading.Thread(
111 target=self._update_loop,
112 )
113 self._update_thread.daemon = True
114
Gavin Makea2e3302023-03-11 06:46:20 +0000115 # When quiet, never show any output. It's a bit hacky, but reusing the
116 # existing logic that delays initial output keeps the rest of the class
117 # clean. Basically we set the start time to years in the future.
118 if quiet:
119 self._show = False
120 self._start += 2**32
Gavin Makedcaa942023-04-27 05:58:57 +0000121 elif show_elapsed:
122 self._update_thread.start()
123
124 def _update_loop(self):
125 while True:
Gavin Mak551285f2023-05-04 04:48:43 +0000126 self.update(inc=0)
127 if self._update_event.wait(timeout=1):
Gavin Makedcaa942023-04-27 05:58:57 +0000128 return
Gavin Mak551285f2023-05-04 04:48:43 +0000129
130 def _write(self, s):
131 s = "\r" + s
132 if self._elide:
Gavin Makb2263ba2023-06-07 21:59:17 +0000133 col = os.get_terminal_size(sys.stderr.fileno()).columns
Gavin Mak551285f2023-05-04 04:48:43 +0000134 if len(s) > col:
135 s = s[: col - 1] + ".."
136 sys.stderr.write(s)
137 sys.stderr.flush()
Mike Frysinger151701e2021-04-13 15:07:21 -0400138
Gavin Makea2e3302023-03-11 06:46:20 +0000139 def start(self, name):
140 self._active += 1
141 if not self._show_jobs:
142 self._show_jobs = self._active > 1
143 self.update(inc=0, msg="started " + name)
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500144
Gavin Makea2e3302023-03-11 06:46:20 +0000145 def finish(self, name):
146 self.update(msg="finished " + name)
147 self._active -= 1
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700148
Gavin Mak551285f2023-05-04 04:48:43 +0000149 def update(self, inc=1, msg=None):
150 """Updates the progress indicator.
151
152 Args:
153 inc: The number of items completed.
154 msg: The message to display. If None, use the last message.
155 """
Gavin Makea2e3302023-03-11 06:46:20 +0000156 self._done += inc
Gavin Mak551285f2023-05-04 04:48:43 +0000157 if msg is None:
158 msg = self._last_msg
Gavin Makedcaa942023-04-27 05:58:57 +0000159 self._last_msg = msg
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700160
Gavin Makb2263ba2023-06-07 21:59:17 +0000161 if not _TTY or IsTraceToStderr():
Gavin Makea2e3302023-03-11 06:46:20 +0000162 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700163
Gavin Makedcaa942023-04-27 05:58:57 +0000164 elapsed_sec = time.time() - self._start
Gavin Makea2e3302023-03-11 06:46:20 +0000165 if not self._show:
Gavin Makedcaa942023-04-27 05:58:57 +0000166 if 0.5 <= elapsed_sec:
Gavin Makea2e3302023-03-11 06:46:20 +0000167 self._show = True
168 else:
169 return
Shawn O. Pearce2810cbc2009-04-18 10:09:16 -0700170
Gavin Makea2e3302023-03-11 06:46:20 +0000171 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000172 self._write(
173 "%s: %d,%s" % (self._title, self._done, CSI_ERASE_LINE_AFTER)
Gavin Makea2e3302023-03-11 06:46:20 +0000174 )
Gavin Makea2e3302023-03-11 06:46:20 +0000175 else:
176 p = (100 * self._done) / self._total
177 if self._show_jobs:
Gavin Mak04cba4a2023-05-24 21:28:28 +0000178 jobs = f"[{jobs_str(self._active)}] "
Gavin Makea2e3302023-03-11 06:46:20 +0000179 else:
180 jobs = ""
Gavin Makedcaa942023-04-27 05:58:57 +0000181 if self._show_elapsed:
182 elapsed = f" {elapsed_str(elapsed_sec)} |"
183 else:
184 elapsed = ""
Gavin Mak551285f2023-05-04 04:48:43 +0000185 self._write(
186 "%s: %2d%% %s(%d%s/%d%s)%s %s%s"
Gavin Makea2e3302023-03-11 06:46:20 +0000187 % (
188 self._title,
189 p,
190 jobs,
191 self._done,
192 self._units,
193 self._total,
194 self._units,
Gavin Makedcaa942023-04-27 05:58:57 +0000195 elapsed,
Gavin Makea2e3302023-03-11 06:46:20 +0000196 msg,
197 CSI_ERASE_LINE_AFTER,
Gavin Makea2e3302023-03-11 06:46:20 +0000198 )
199 )
Shawn O. Pearceb1168ff2009-04-16 08:00:42 -0700200
Gavin Makea2e3302023-03-11 06:46:20 +0000201 def end(self):
Gavin Makedcaa942023-04-27 05:58:57 +0000202 self._update_event.set()
Gavin Makb2263ba2023-06-07 21:59:17 +0000203 if not _TTY or IsTraceToStderr() or not self._show:
Gavin Makea2e3302023-03-11 06:46:20 +0000204 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700205
Gavin Makedcaa942023-04-27 05:58:57 +0000206 duration = duration_str(time.time() - self._start)
Gavin Makea2e3302023-03-11 06:46:20 +0000207 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000208 self._write(
209 "%s: %d, done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000210 % (self._title, self._done, duration, CSI_ERASE_LINE_AFTER)
211 )
Gavin Makea2e3302023-03-11 06:46:20 +0000212 else:
213 p = (100 * self._done) / self._total
Gavin Mak551285f2023-05-04 04:48:43 +0000214 self._write(
215 "%s: %3d%% (%d%s/%d%s), done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000216 % (
217 self._title,
218 p,
219 self._done,
220 self._units,
221 self._total,
222 self._units,
223 duration,
224 CSI_ERASE_LINE_AFTER,
225 )
226 )