Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 32 additions & 0 deletions src/download/progress.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createProgressBar } from './progress.js';

describe('download progress display', () => {
afterEach(() => {
vi.restoreAllMocks();
});

it('clamps percentages above 100 to keep the progress bar renderable', () => {
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const progress = createProgressBar('file.bin', 0, 1);

expect(() => progress.update(150, 100)).not.toThrow();
expect(write).toHaveBeenCalledWith(expect.stringContaining('100%'));
});

it('clamps negative percentages to zero', () => {
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const progress = createProgressBar('file.bin', 0, 1);

expect(() => progress.update(-10, 100)).not.toThrow();
expect(write).toHaveBeenCalledWith(expect.stringContaining('0%'));
});

it('renders zero percent when the total size is unknown', () => {
const write = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);
const progress = createProgressBar('file.bin', 0, 1);

expect(() => progress.update(50, 0)).not.toThrow();
expect(write).toHaveBeenCalledWith(expect.stringContaining('0%'));
});
});
7 changes: 6 additions & 1 deletion src/download/progress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ export function createProgressBar(filename: string, index: number, total: number

return {
update(current: number, totalBytes: number, label?: string) {
const percent = totalBytes > 0 ? Math.round((current / totalBytes) * 100) : 0;
const percent = clampPercent(totalBytes > 0 ? Math.round((current / totalBytes) * 100) : 0);
const bar = createBar(percent);
const size = totalBytes > 0 ? formatBytes(totalBytes) : '';
const extra = label ? ` ${label}` : '';
Expand All @@ -64,6 +64,11 @@ export function createProgressBar(filename: string, index: number, total: number
};
}

function clampPercent(percent: number): number {
if (!Number.isFinite(percent)) return 0;
return Math.max(0, Math.min(100, percent));
}

/**
* Create a progress bar string.
*/
Expand Down
Loading