Skip to content

Commit 80d27dd

Browse files
committed
add progress bar
1 parent 659aa00 commit 80d27dd

File tree

1 file changed

+20
-0
lines changed

1 file changed

+20
-0
lines changed

zigup.zig

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,7 @@ fn download(allocator: Allocator, url: []const u8, writer: anytype) DownloadResu
103103
// TODO: we take advantage of request.response.content_length
104104

105105
var buf: [4096]u8 = undefined;
106+
var current: usize = 0;
106107
while (true) {
107108
const len = request.reader().read(&buf) catch |err| return .{ .err = std.fmt.allocPrint(
108109
allocator,
@@ -111,6 +112,13 @@ fn download(allocator: Allocator, url: []const u8, writer: anytype) DownloadResu
111112
) catch |e| oom(e) };
112113
if (len == 0)
113114
return .ok;
115+
progressBar(current, request.response.content_length.?) catch |err| return .{ .err = std.fmt.allocPrint(
116+
allocator,
117+
"failed to write the progress bar with {s}'",
118+
.{@errorName(err)},
119+
) catch |e| oom(e) };
120+
current += len;
121+
114122
writer.writeAll(buf[0..len]) catch |err| return .{ .err = std.fmt.allocPrint(
115123
allocator,
116124
"failed to write the HTTP response body with {s}'",
@@ -119,6 +127,17 @@ fn download(allocator: Allocator, url: []const u8, writer: anytype) DownloadResu
119127
}
120128
}
121129

130+
fn progressBar(downloaded: usize, total: u64) !void {
131+
const stdout = std.io.getStdOut().writer();
132+
const width = 20;
133+
const percent: f64 = (@as(f64, @floatFromInt(downloaded)) / @as(f64, @floatFromInt(total))) * 100.0;
134+
const filled: u64 = @intFromFloat(@round((percent / 100.0) * @as(f64, @floatFromInt(width))));
135+
try stdout.print("\r[", .{});
136+
for (0..filled) |_| try stdout.print("#", .{});
137+
for (filled..width) |_| try stdout.print(" ", .{});
138+
try stdout.print("] {d:.0}%", .{percent});
139+
}
140+
122141
const DownloadStringResult = union(enum) {
123142
ok: []u8,
124143
err: []u8,
@@ -1287,6 +1306,7 @@ fn installCompiler(allocator: Allocator, compiler_dir: []const u8, url: []const
12871306
return error.AlreadyReported;
12881307
},
12891308
}
1309+
loginfo("", .{}); // add new line
12901310

12911311
if (std.mem.endsWith(u8, archive_basename, ".tar.xz")) {
12921312
archive_root_dir = archive_basename[0 .. archive_basename.len - ".tar.xz".len];

0 commit comments

Comments
 (0)