blob: b21e1bc6f0dedf5a5ec8981aa14d8349729c98c4 [file] [log] [blame]
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +00001#
2# Copyright (C) 2009 The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16import sys
17from time import time
18
19class Progress(object):
20 def __init__(self, title, total=0):
21 self._title = title
22 self._total = total
23 self._done = 0
24 self._lastp = -1
25 self._start = time()
26 self._show = False
maruel@chromium.org55a2eb82010-10-06 23:35:18 +000027 self._width = 0
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000028
maruel@chromium.org55a2eb82010-10-06 23:35:18 +000029 def update(self, inc=1, extra=''):
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000030 self._done += inc
31
32 if not self._show:
33 if 0.5 <= time() - self._start:
34 self._show = True
35 else:
36 return
37
maruel@chromium.org55a2eb82010-10-06 23:35:18 +000038 text = None
39
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000040 if self._total <= 0:
maruel@chromium.org55a2eb82010-10-06 23:35:18 +000041 text = '%s: %3d' % (self._title, self._done)
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000042 else:
43 p = (100 * self._done) / self._total
44
45 if self._lastp != p:
46 self._lastp = p
maruel@chromium.org55a2eb82010-10-06 23:35:18 +000047 text = '%s: %3d%% (%2d/%2d)' % (self._title, p,
48 self._done, self._total)
49
50 if text:
51 text += ' ' + extra
52 spaces = max(self._width - len(text), 0)
53 sys.stdout.write('%s%*s\r' % (text, spaces, ''))
54 sys.stdout.flush()
55 self._width = len(text)
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000056
57 def end(self):
58 if not self._show:
59 return
60
61 if self._total <= 0:
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000062 text = '%s: %d, done.' % (
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000063 self._title,
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000064 self._done)
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000065 else:
66 p = (100 * self._done) / self._total
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000067 text = '%s: %3d%% (%d/%d), done.' % (
nasser@codeaurora.org1f7a3d12010-02-04 15:11:50 +000068 self._title,
69 p,
70 self._done,
szager@chromium.orgfe0d1902014-04-08 20:50:44 +000071 self._total)
72
73 spaces = max(self._width - len(text), 0)
74 sys.stdout.write('%s%*s\n' % (text, spaces, ''))
75 sys.stdout.flush()