blob: 6686ad4ae440c56b8a2c77af4ff70c11660d5386 [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="",
Gavin Makea2e3302023-03-11 06:46:20 +000085 delay=True,
86 quiet=False,
Gavin Makedcaa942023-04-27 05:58:57 +000087 show_elapsed=False,
Gavin Mak551285f2023-05-04 04:48:43 +000088 elide=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
Gavin Mak551285f2023-05-04 04:48:43 +000096 self._elide = elide
Gavin Makea2e3302023-03-11 06:46:20 +000097 # 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:
Gavin Mak551285f2023-05-04 04:48:43 +0000121 self.update(inc=0)
122 if self._update_event.wait(timeout=1):
Gavin Makedcaa942023-04-27 05:58:57 +0000123 return
Gavin Mak551285f2023-05-04 04:48:43 +0000124
125 def _write(self, s):
126 s = "\r" + s
127 if self._elide:
128 col = os.get_terminal_size().columns
129 if len(s) > col:
130 s = s[: col - 1] + ".."
131 sys.stderr.write(s)
132 sys.stderr.flush()
Mike Frysinger151701e2021-04-13 15:07:21 -0400133
Gavin Makea2e3302023-03-11 06:46:20 +0000134 def start(self, name):
135 self._active += 1
136 if not self._show_jobs:
137 self._show_jobs = self._active > 1
138 self.update(inc=0, msg="started " + name)
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500139
Gavin Makea2e3302023-03-11 06:46:20 +0000140 def finish(self, name):
141 self.update(msg="finished " + name)
142 self._active -= 1
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700143
Gavin Mak551285f2023-05-04 04:48:43 +0000144 def update(self, inc=1, msg=None):
145 """Updates the progress indicator.
146
147 Args:
148 inc: The number of items completed.
149 msg: The message to display. If None, use the last message.
150 """
Gavin Makea2e3302023-03-11 06:46:20 +0000151 self._done += inc
Gavin Mak551285f2023-05-04 04:48:43 +0000152 if msg is None:
153 msg = self._last_msg
Gavin Makedcaa942023-04-27 05:58:57 +0000154 self._last_msg = msg
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700155
Gavin Makea2e3302023-03-11 06:46:20 +0000156 if _NOT_TTY or IsTraceToStderr():
157 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700158
Gavin Makedcaa942023-04-27 05:58:57 +0000159 elapsed_sec = time.time() - self._start
Gavin Makea2e3302023-03-11 06:46:20 +0000160 if not self._show:
Gavin Makedcaa942023-04-27 05:58:57 +0000161 if 0.5 <= elapsed_sec:
Gavin Makea2e3302023-03-11 06:46:20 +0000162 self._show = True
163 else:
164 return
Shawn O. Pearce2810cbc2009-04-18 10:09:16 -0700165
Gavin Makea2e3302023-03-11 06:46:20 +0000166 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000167 self._write(
168 "%s: %d,%s" % (self._title, self._done, CSI_ERASE_LINE_AFTER)
Gavin Makea2e3302023-03-11 06:46:20 +0000169 )
Gavin Makea2e3302023-03-11 06:46:20 +0000170 else:
171 p = (100 * self._done) / self._total
172 if self._show_jobs:
173 jobs = "[%d job%s] " % (
174 self._active,
175 "s" if self._active > 1 else "",
176 )
177 else:
178 jobs = ""
Gavin Makedcaa942023-04-27 05:58:57 +0000179 if self._show_elapsed:
180 elapsed = f" {elapsed_str(elapsed_sec)} |"
181 else:
182 elapsed = ""
Gavin Mak551285f2023-05-04 04:48:43 +0000183 self._write(
184 "%s: %2d%% %s(%d%s/%d%s)%s %s%s"
Gavin Makea2e3302023-03-11 06:46:20 +0000185 % (
186 self._title,
187 p,
188 jobs,
189 self._done,
190 self._units,
191 self._total,
192 self._units,
Gavin Makedcaa942023-04-27 05:58:57 +0000193 elapsed,
Gavin Makea2e3302023-03-11 06:46:20 +0000194 msg,
195 CSI_ERASE_LINE_AFTER,
Gavin Makea2e3302023-03-11 06:46:20 +0000196 )
197 )
Shawn O. Pearceb1168ff2009-04-16 08:00:42 -0700198
Gavin Makea2e3302023-03-11 06:46:20 +0000199 def end(self):
Gavin Makedcaa942023-04-27 05:58:57 +0000200 self._update_event.set()
Gavin Makea2e3302023-03-11 06:46:20 +0000201 if _NOT_TTY or IsTraceToStderr() or not self._show:
202 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700203
Gavin Makedcaa942023-04-27 05:58:57 +0000204 duration = duration_str(time.time() - self._start)
Gavin Makea2e3302023-03-11 06:46:20 +0000205 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000206 self._write(
207 "%s: %d, done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000208 % (self._title, self._done, duration, CSI_ERASE_LINE_AFTER)
209 )
Gavin Makea2e3302023-03-11 06:46:20 +0000210 else:
211 p = (100 * self._done) / self._total
Gavin Mak551285f2023-05-04 04:48:43 +0000212 self._write(
213 "%s: %3d%% (%d%s/%d%s), done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000214 % (
215 self._title,
216 p,
217 self._done,
218 self._units,
219 self._total,
220 self._units,
221 duration,
222 CSI_ERASE_LINE_AFTER,
223 )
224 )