blob: fe246c74409ee4d30f0a5ec1dc6e32252a411b12 [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
Mike Frysinger64477332023-08-21 21:20:32 -040019
Gavin Makedcaa942023-04-27 05:58:57 +000020try:
21 import threading as _threading
22except ImportError:
23 import dummy_threading as _threading
24
LaMont Jones47020ba2022-11-10 00:11:51 +000025from repo_trace import IsTraceToStderr
Shawn O. Pearce68194f42009-04-10 16:48:52 -070026
Mike Frysinger64477332023-08-21 21:20:32 -040027
Gavin Makb2263ba2023-06-07 21:59:17 +000028_TTY = sys.stderr.isatty()
Shawn O. Pearcef4f04d92010-05-27 16:48:36 -070029
Mike Frysinger70d861f2019-08-26 15:22:36 -040030# This will erase all content in the current line (wherever the cursor is).
31# It does not move the cursor, so this is usually followed by \r to move to
32# column 0.
Gavin Makea2e3302023-03-11 06:46:20 +000033CSI_ERASE_LINE = "\x1b[2K"
Mike Frysinger70d861f2019-08-26 15:22:36 -040034
Mike Frysinger4c11aeb2022-04-19 02:30:09 -040035# This will erase all content in the current line after the cursor. This is
36# useful for partial updates & progress messages as the terminal can display
37# it better.
Gavin Makea2e3302023-03-11 06:46:20 +000038CSI_ERASE_LINE_AFTER = "\x1b[K"
Mike Frysinger4c11aeb2022-04-19 02:30:09 -040039
David Pursehouse819827a2020-02-12 15:20:19 +090040
Gavin Makedcaa942023-04-27 05:58:57 +000041def convert_to_hms(total):
42 """Converts a period of seconds to hours, minutes, and seconds."""
43 hours, rem = divmod(total, 3600)
44 mins, secs = divmod(rem, 60)
45 return int(hours), int(mins), secs
46
47
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050048def duration_str(total):
Gavin Makea2e3302023-03-11 06:46:20 +000049 """A less noisy timedelta.__str__.
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050050
Gavin Makea2e3302023-03-11 06:46:20 +000051 The default timedelta stringification contains a lot of leading zeros and
52 uses microsecond resolution. This makes for noisy output.
53 """
Gavin Makedcaa942023-04-27 05:58:57 +000054 hours, mins, secs = convert_to_hms(total)
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -040055 ret = f"{secs:.3f}s"
Gavin Makea2e3302023-03-11 06:46:20 +000056 if mins:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -040057 ret = f"{mins}m{ret}"
Gavin Makea2e3302023-03-11 06:46:20 +000058 if hours:
Jason R. Coombsb32ccbb2023-09-29 11:04:49 -040059 ret = f"{hours}h{ret}"
Gavin Makea2e3302023-03-11 06:46:20 +000060 return ret
Mike Frysinger8d2a6df2021-02-26 03:55:44 -050061
62
Gavin Makedcaa942023-04-27 05:58:57 +000063def elapsed_str(total):
64 """Returns seconds in the format [H:]MM:SS.
65
66 Does not display a leading zero for minutes if under 10 minutes. This should
67 be used when displaying elapsed time in a progress indicator.
68 """
69 hours, mins, secs = convert_to_hms(total)
70 ret = f"{int(secs):>02d}"
71 if total >= 3600:
72 # Show leading zeroes if over an hour.
73 ret = f"{mins:>02d}:{ret}"
74 else:
75 ret = f"{mins}:{ret}"
76 if hours:
77 ret = f"{hours}:{ret}"
78 return ret
79
80
Gavin Mak04cba4a2023-05-24 21:28:28 +000081def jobs_str(total):
82 return f"{total} job{'s' if total > 1 else ''}"
83
84
Mike Frysingerd4aee652023-10-19 05:13:32 -040085class Progress:
Gavin Makea2e3302023-03-11 06:46:20 +000086 def __init__(
87 self,
88 title,
89 total=0,
90 units="",
Gavin Makea2e3302023-03-11 06:46:20 +000091 delay=True,
92 quiet=False,
Gavin Makedcaa942023-04-27 05:58:57 +000093 show_elapsed=False,
Gavin Mak551285f2023-05-04 04:48:43 +000094 elide=False,
Gavin Makea2e3302023-03-11 06:46:20 +000095 ):
96 self._title = title
97 self._total = total
98 self._done = 0
Gavin Makedcaa942023-04-27 05:58:57 +000099 self._start = time.time()
Gavin Makea2e3302023-03-11 06:46:20 +0000100 self._show = not delay
101 self._units = units
Gavin Makb2263ba2023-06-07 21:59:17 +0000102 self._elide = elide and _TTY
Kuang-che Wu70a4e642024-10-24 10:12:39 +0800103 self._quiet = quiet
Gavin Makb2263ba2023-06-07 21:59:17 +0000104
Gavin Makea2e3302023-03-11 06:46:20 +0000105 # Only show the active jobs section if we run more than one in parallel.
106 self._show_jobs = False
107 self._active = 0
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500108
Gavin Makedcaa942023-04-27 05:58:57 +0000109 # Save the last message for displaying on refresh.
110 self._last_msg = None
111 self._show_elapsed = show_elapsed
112 self._update_event = _threading.Event()
113 self._update_thread = _threading.Thread(
114 target=self._update_loop,
115 )
116 self._update_thread.daemon = True
117
Kuang-che Wu70a4e642024-10-24 10:12:39 +0800118 if not quiet and show_elapsed:
Gavin Makedcaa942023-04-27 05:58:57 +0000119 self._update_thread.start()
120
121 def _update_loop(self):
122 while True:
Gavin Mak551285f2023-05-04 04:48:43 +0000123 self.update(inc=0)
124 if self._update_event.wait(timeout=1):
Gavin Makedcaa942023-04-27 05:58:57 +0000125 return
Gavin Mak551285f2023-05-04 04:48:43 +0000126
127 def _write(self, s):
128 s = "\r" + s
129 if self._elide:
Gavin Makb2263ba2023-06-07 21:59:17 +0000130 col = os.get_terminal_size(sys.stderr.fileno()).columns
Gavin Mak551285f2023-05-04 04:48:43 +0000131 if len(s) > col:
132 s = s[: col - 1] + ".."
133 sys.stderr.write(s)
134 sys.stderr.flush()
Mike Frysinger151701e2021-04-13 15:07:21 -0400135
Gavin Makea2e3302023-03-11 06:46:20 +0000136 def start(self, name):
137 self._active += 1
138 if not self._show_jobs:
139 self._show_jobs = self._active > 1
140 self.update(inc=0, msg="started " + name)
Mike Frysingerfbb95a42021-02-23 17:34:35 -0500141
Gavin Makea2e3302023-03-11 06:46:20 +0000142 def finish(self, name):
143 self.update(msg="finished " + name)
144 self._active -= 1
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700145
Gavin Mak551285f2023-05-04 04:48:43 +0000146 def update(self, inc=1, msg=None):
147 """Updates the progress indicator.
148
149 Args:
150 inc: The number of items completed.
151 msg: The message to display. If None, use the last message.
152 """
Gavin Makea2e3302023-03-11 06:46:20 +0000153 self._done += inc
Gavin Mak551285f2023-05-04 04:48:43 +0000154 if msg is None:
155 msg = self._last_msg
Gavin Makedcaa942023-04-27 05:58:57 +0000156 self._last_msg = msg
Shawn O. Pearce68194f42009-04-10 16:48:52 -0700157
Kuang-che Wu70a4e642024-10-24 10:12:39 +0800158 if not _TTY or IsTraceToStderr() or self._quiet:
Gavin Makea2e3302023-03-11 06:46:20 +0000159 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700160
Gavin Makedcaa942023-04-27 05:58:57 +0000161 elapsed_sec = time.time() - self._start
Gavin Makea2e3302023-03-11 06:46:20 +0000162 if not self._show:
Gavin Makedcaa942023-04-27 05:58:57 +0000163 if 0.5 <= elapsed_sec:
Gavin Makea2e3302023-03-11 06:46:20 +0000164 self._show = True
165 else:
166 return
Shawn O. Pearce2810cbc2009-04-18 10:09:16 -0700167
Gavin Makea2e3302023-03-11 06:46:20 +0000168 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000169 self._write(
170 "%s: %d,%s" % (self._title, self._done, CSI_ERASE_LINE_AFTER)
Gavin Makea2e3302023-03-11 06:46:20 +0000171 )
Gavin Makea2e3302023-03-11 06:46:20 +0000172 else:
173 p = (100 * self._done) / self._total
174 if self._show_jobs:
Gavin Mak04cba4a2023-05-24 21:28:28 +0000175 jobs = f"[{jobs_str(self._active)}] "
Gavin Makea2e3302023-03-11 06:46:20 +0000176 else:
177 jobs = ""
Gavin Makedcaa942023-04-27 05:58:57 +0000178 if self._show_elapsed:
179 elapsed = f" {elapsed_str(elapsed_sec)} |"
180 else:
181 elapsed = ""
Gavin Mak551285f2023-05-04 04:48:43 +0000182 self._write(
183 "%s: %2d%% %s(%d%s/%d%s)%s %s%s"
Gavin Makea2e3302023-03-11 06:46:20 +0000184 % (
185 self._title,
186 p,
187 jobs,
188 self._done,
189 self._units,
190 self._total,
191 self._units,
Gavin Makedcaa942023-04-27 05:58:57 +0000192 elapsed,
Gavin Makea2e3302023-03-11 06:46:20 +0000193 msg,
194 CSI_ERASE_LINE_AFTER,
Gavin Makea2e3302023-03-11 06:46:20 +0000195 )
196 )
Shawn O. Pearceb1168ff2009-04-16 08:00:42 -0700197
Gavin Makea2e3302023-03-11 06:46:20 +0000198 def end(self):
Gavin Makedcaa942023-04-27 05:58:57 +0000199 self._update_event.set()
Kuang-che Wu70a4e642024-10-24 10:12:39 +0800200 if not _TTY or IsTraceToStderr() or self._quiet:
Gavin Makea2e3302023-03-11 06:46:20 +0000201 return
Shawn O. Pearce6ed4e282009-04-18 09:59:18 -0700202
Gavin Makedcaa942023-04-27 05:58:57 +0000203 duration = duration_str(time.time() - self._start)
Gavin Makea2e3302023-03-11 06:46:20 +0000204 if self._total <= 0:
Gavin Mak551285f2023-05-04 04:48:43 +0000205 self._write(
206 "%s: %d, done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000207 % (self._title, self._done, duration, CSI_ERASE_LINE_AFTER)
208 )
Gavin Makea2e3302023-03-11 06:46:20 +0000209 else:
210 p = (100 * self._done) / self._total
Gavin Mak551285f2023-05-04 04:48:43 +0000211 self._write(
212 "%s: %3d%% (%d%s/%d%s), done in %s%s\n"
Gavin Makea2e3302023-03-11 06:46:20 +0000213 % (
214 self._title,
215 p,
216 self._done,
217 self._units,
218 self._total,
219 self._units,
220 duration,
221 CSI_ERASE_LINE_AFTER,
222 )
223 )