Skip to content

Commit b1b6615

Browse files
authored
Improve progress bar (ETA and Unicode-based rendering) (#4)
* Use ProgressMeter to draw progress bars * Fix test failures in Julia 1.0 * Use infix operator to improve @-test failure output * Fix test failures in Windows * Vendor ProgressMeter.jl * Fix test/TerminalLogger.jl * More tests * Fix Windows test
1 parent cabd0d0 commit b1b6615

File tree

6 files changed

+229
-26
lines changed

6 files changed

+229
-26
lines changed

Project.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ version = "0.1.0"
55

66
[deps]
77
Logging = "56ddb016-857b-54e1-b83d-db4d58db5568"
8+
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
89

910
[compat]
1011
julia = "1"

src/ProgressMeter/LICENSE.txt

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
The MIT License (MIT)
2+
Copyright (c) 2013 Timothy E. Holy
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
5+
6+
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
7+
8+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

src/ProgressMeter/ProgressMeter.jl

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
module ProgressMeter
2+
3+
using Printf: @printf, @sprintf
4+
5+
"""
6+
Holds the five characters that will be used to generate the progress bar.
7+
"""
8+
mutable struct BarGlyphs
9+
leftend::Char
10+
fill::Char
11+
front::Union{Vector{Char}, Char}
12+
empty::Char
13+
rightend::Char
14+
end
15+
16+
BarGlyphs() = BarGlyphs(
17+
'|',
18+
'',
19+
Sys.iswindows() ? '' : ['', '', '', '', '', '', ''],
20+
' ',
21+
'|',
22+
)
23+
24+
struct ProgressBar
25+
barglyphs::BarGlyphs
26+
tfirst::Float64
27+
end
28+
29+
ProgressBar(barglyphs = BarGlyphs()) = ProgressBar(barglyphs, time())
30+
31+
"""
32+
printprogress(io::IO, p::ProgressBar, desc, progress::Real)
33+
34+
Print progress bar to `io` with setting `p`.
35+
36+
# Arguments
37+
- `io::IO`
38+
- `p::ProgressBar`
39+
- `desc`: description to be printed at left side of progress bar.
40+
- `progress::Real`: a number between 0 and 1 or a `NaN`.
41+
"""
42+
function printprogress(io::IO, p::ProgressBar, desc, progress::Real)
43+
t = time()
44+
percentage_complete = 100.0 * (isnan(progress) ? 0.0 : progress)
45+
46+
#...length of percentage and ETA string with days is 29 characters
47+
barlen = max(0, displaysize(io)[2] - (length(desc) + 29))
48+
49+
if progress >= 1
50+
bar = barstring(barlen, percentage_complete, barglyphs=p.barglyphs)
51+
dur = durationstring(t - p.tfirst)
52+
@printf io "%s%3u%%%s Time: %s" desc round(Int, percentage_complete) bar dur
53+
return
54+
end
55+
56+
bar = barstring(barlen, percentage_complete, barglyphs=p.barglyphs)
57+
elapsed_time = t - p.tfirst
58+
est_total_time = 100 * elapsed_time / percentage_complete
59+
if 0 <= est_total_time <= typemax(Int)
60+
eta_sec = round(Int, est_total_time - elapsed_time)
61+
eta = durationstring(eta_sec)
62+
else
63+
eta = "N/A"
64+
end
65+
@printf io "%s%3u%%%s ETA: %s" desc round(Int, percentage_complete) bar eta
66+
return
67+
end
68+
69+
function compute_front(barglyphs::BarGlyphs, frac_solid::AbstractFloat)
70+
barglyphs.front isa Char && return barglyphs.front
71+
idx = round(Int, frac_solid * (length(barglyphs.front) + 1))
72+
return idx > length(barglyphs.front) ? barglyphs.fill :
73+
idx == 0 ? barglyphs.empty :
74+
barglyphs.front[idx]
75+
end
76+
77+
function barstring(barlen, percentage_complete; barglyphs)
78+
bar = ""
79+
if barlen>0
80+
if percentage_complete == 100 # if we're done, don't use the "front" character
81+
bar = string(barglyphs.leftend, repeat(string(barglyphs.fill), barlen), barglyphs.rightend)
82+
else
83+
n_bars = barlen * percentage_complete / 100
84+
nsolid = trunc(Int, n_bars)
85+
frac_solid = n_bars - nsolid
86+
nempty = barlen - nsolid - 1
87+
bar = string(barglyphs.leftend,
88+
repeat(string(barglyphs.fill), max(0,nsolid)),
89+
compute_front(barglyphs, frac_solid),
90+
repeat(string(barglyphs.empty), max(0, nempty)),
91+
barglyphs.rightend)
92+
end
93+
end
94+
bar
95+
end
96+
97+
function durationstring(nsec)
98+
days = div(nsec, 60*60*24)
99+
r = nsec - 60*60*24*days
100+
hours = div(r,60*60)
101+
r = r - 60*60*hours
102+
minutes = div(r, 60)
103+
seconds = floor(r - 60*minutes)
104+
105+
hhmmss = @sprintf "%u:%02u:%02u" hours minutes seconds
106+
if days>9
107+
return @sprintf "%.2f days" nsec/(60*60*24)
108+
elseif days>0
109+
return @sprintf "%u days, %s" days hhmmss
110+
end
111+
hhmmss
112+
end
113+
114+
end

src/TerminalLogger.jl

Lines changed: 58 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
"""
2-
TerminalLogger(stream=stderr, min_level=Info; meta_formatter=default_metafmt,
2+
TerminalLogger(stream=stderr, min_level=$ProgressLevel; meta_formatter=default_metafmt,
33
show_limited=true, right_justify=0)
44
55
Logger with formatting optimized for readability in a text console, for example
@@ -28,12 +28,21 @@ struct TerminalLogger <: AbstractLogger
2828
right_justify::Int
2929
message_limits::Dict{Any,Int}
3030
sticky_messages::StickyMessages
31+
bars::Dict{Any,ProgressBar}
3132
end
32-
function TerminalLogger(stream::IO=stderr, min_level=Info;
33+
function TerminalLogger(stream::IO=stderr, min_level=ProgressLevel;
3334
meta_formatter=default_metafmt, show_limited=true,
3435
right_justify=0)
35-
TerminalLogger(stream, min_level, meta_formatter,
36-
show_limited, right_justify, Dict{Any,Int}(), StickyMessages(stream))
36+
TerminalLogger(
37+
stream,
38+
min_level,
39+
meta_formatter,
40+
show_limited,
41+
right_justify,
42+
Dict{Any,Int}(),
43+
StickyMessages(stream),
44+
Dict{Any,ProgressBar}(),
45+
)
3746
end
3847

3948
shouldlog(logger::TerminalLogger, level, _module, group, id) =
@@ -94,6 +103,46 @@ function termlength(str)
94103
return N
95104
end
96105

106+
function handle_progress(logger, message, id, progress)
107+
# Don't do anything when it's already done:
108+
if (progress == "done" || progress >= 1) && !haskey(logger.bars, id)
109+
return
110+
end
111+
112+
try
113+
bar = get!(ProgressBar, logger.bars, id)
114+
115+
if message == ""
116+
message = "Progress: "
117+
else
118+
message = string(message)
119+
if !endswith(message, " ")
120+
message *= " "
121+
end
122+
end
123+
124+
bartxt = sprint(
125+
printprogress,
126+
bar,
127+
message,
128+
progress == "done" ? 1.0 : progress;
129+
context = :displaysize => displaysize(logger.stream),
130+
)
131+
132+
if progress == "done" || progress >= 1
133+
pop!(logger.sticky_messages, id)
134+
println(logger.stream, bartxt)
135+
else
136+
push!(logger.sticky_messages, id => bartxt)
137+
end
138+
finally
139+
if progress == "done" || progress >= 1
140+
pop!(logger.sticky_messages, id) # redundant (but safe) if no error
141+
pop!(logger.bars, id, nothing)
142+
end
143+
end
144+
end
145+
97146
function handle_message(logger::TerminalLogger, level, message, _module, group, id,
98147
filepath, line; maxlog=nothing, progress=nothing,
99148
sticky=nothing, kwargs...)
@@ -103,6 +152,11 @@ function handle_message(logger::TerminalLogger, level, message, _module, group,
103152
remaining > 0 || return
104153
end
105154

155+
if progress == "done" || progress isa Real
156+
handle_progress(logger, message, id, progress)
157+
return
158+
end
159+
106160
substr(s) = SubString(s, 1, length(s)) # julia 0.6 compat
107161

108162
# Generate a text representation of the message and all key value pairs,
@@ -129,14 +183,6 @@ function handle_message(logger::TerminalLogger, level, message, _module, group,
129183
end
130184
end
131185

132-
if progress !== nothing
133-
if (progress isa Symbol && progress == :done) || progress == 1
134-
sticky = :done
135-
else
136-
sticky = true
137-
end
138-
end
139-
140186
# Format lines as text with appropriate indentation and with a box
141187
# decoration on the left.
142188
color,prefix,suffix = logger.meta_formatter(level, _module, group, id, filepath, line)
@@ -162,12 +208,6 @@ function handle_message(logger::TerminalLogger, level, message, _module, group,
162208
printstyled(iob, prefix, " ", bold=true, color=color)
163209
end
164210
print(iob, " "^indent, msg)
165-
if i == 1 && progress !== nothing
166-
progress = clamp(convert(Float64, progress), 0.0, 1.0)
167-
barfulllen = dsize[2] - length(boxstr) - length(prefix) - indent - length(msg) - 2
168-
barlen = round(Int, barfulllen*progress)
169-
print(iob, ' ', '='^barlen, ' '^(barfulllen-barlen))
170-
end
171211
if i == length(msglines) && !isempty(suffix)
172212
npad = max(0, justify_width - nonpadwidth) + minsuffixpad
173213
print(iob, " "^npad)

src/TerminalLoggers.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ import Logging:
99

1010
export TerminalLogger
1111

12+
const ProgressLevel = LogLevel(-1)
13+
14+
include("ProgressMeter/ProgressMeter.jl")
15+
using .ProgressMeter:
16+
ProgressBar, printprogress
17+
1218
include("StickyMessages.jl")
1319
include("TerminalLogger.jl")
1420

test/TerminalLogger.jl

Lines changed: 42 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,20 +42,40 @@ import TerminalLoggers.default_metafmt
4242
end
4343

4444
# Log formatting
45-
function genmsg(message; level=Info, _module=Main,
46-
file="some/path.jl", line=101, color=false, width=75,
47-
meta_formatter=dummy_metafmt, show_limited=true,
48-
right_justify=0, kws...)
45+
function genmsgs(events; level=Info, _module=Main,
46+
file="some/path.jl", line=101, color=false, width=75,
47+
meta_formatter=dummy_metafmt, show_limited=true,
48+
right_justify=0)
4949
buf = IOBuffer()
5050
io = IOContext(buf, :displaysize=>(30,width), :color=>color)
5151
logger = TerminalLogger(io, Debug,
5252
meta_formatter=meta_formatter,
5353
show_limited=show_limited,
5454
right_justify=right_justify)
5555
prev_have_color = Base.have_color
56-
handle_message(logger, level, message, _module, :a_group, :an_id,
57-
file, line; kws...)
58-
String(take!(buf))
56+
return map(events) do (message, kws)
57+
handle_message(logger, level, message, _module, :a_group, :an_id,
58+
file, line; kws...)
59+
String(take!(buf))
60+
end
61+
end
62+
function genmsg(message; kwargs...)
63+
kws = Dict(kwargs)
64+
logconfig = Dict(
65+
k => pop!(kws, k)
66+
for k in [
67+
:level,
68+
:_module,
69+
:file,
70+
:line,
71+
:color,
72+
:width,
73+
:meta_formatter,
74+
:show_limited,
75+
:right_justify,
76+
] if haskey(kws, k)
77+
)
78+
return genmsgs([(message, kws)]; logconfig...)[1]
5979
end
6080

6181
# Basic tests for the default setup
@@ -196,7 +216,7 @@ import TerminalLoggers.default_metafmt
196216
""",
197217
# EOL hack to work around git whitespace errors
198218
# VERSION dependence due to JuliaLang/julia#33339
199-
(VERSION <= v"1.3" ? "EOL" : " EOL")=>""
219+
(VERSION < v"1.4-" ? "EOL" : " EOL")=>""
200220
)
201221
# Limiting the amount which is printed
202222
@test genmsg("msg", a=fill(1.00001, 10,10), show_limited=false) ==
@@ -225,4 +245,18 @@ import TerminalLoggers.default_metafmt
225245
\e[36m\e[1m│ \e[22m\e[39mline2
226246
\e[36m\e[1m└ \e[22m\e[39m\e[90mSUFFIX\e[39m
227247
"""
248+
249+
# Using infix operator so that `@test` prints lhs and rhs when failed:
250+
(s, re) = match(re, s) !== nothing
251+
252+
@test genmsg("", progress=0.1, width=60)
253+
r"Progress: 10%\|██. \| ETA: 0:00:[0-9][0-9]"
254+
@test genmsg("", progress=NaN, width=60)
255+
r"Progress: 0%|. | ETA: N/A"
256+
@test genmsg("", progress=1.0, width=60) == ""
257+
@test genmsg("", progress="done", width=60) == ""
258+
@test genmsgs([("", (progress = 0.1,)), ("", (progress = 1.0,))], width = 60)[end]
259+
r"Progress: 100%|█████████████████████| Time: 0:00:[0-9][0-9]"
260+
@test genmsgs([("", (progress = 0.1,)), ("", (progress = "done",))], width = 60)[end]
261+
r"Progress: 100%|█████████████████████| Time: 0:00:[0-9][0-9]"
228262
end

0 commit comments

Comments
 (0)