All files / cli / unstable_progress_bar.ts

100.00% Branches 10/10
100.00% Lines 102/102
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x15
x24
x24
x24
x25
x15
 
x4
x16
x16
x16
x16
x12
x4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x4
x15
x15
x15
x15
x15
x15
 
x15
x15
x15
x15
x15
x15
x15
x4
 
 
 
 
 
 
x4
x4
x4
x4
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
x15
 
x15
x15
 
x15
x15
x45
x15
x15
x15
x15
x15
x15
x15
 
x4
x27
 
x27
x27
x27
 
x27
x27
x49
x49
x49
x27
x27
x49
x49
x49
x27
x27
x27
x27
x27
x27
x27
x27
x27
x27
x27
x27
x27
 
 
 
 
 
 
 
 
 
 
 
 
 
x4
x54
x54
 
 
 
 
 
 
 
 
 
 
 
 
x4
x15
x15
x15
x15
x15
x15
x4


























































































































































































































































































// Copyright 2018-2025 the Deno authors. MIT license.
// This module is browser compatible.

/**
 * The properties provided to the fmt function upon every visual update.
 */
export interface ProgressBarFormatter {
  /**
   * A function that returns a formatted version of the duration.
   * `[mm:ss]`
   */
  styledTime: () => string;
  /**
   * A function that returns a formatted version of the data received.
   * `[0.40/97.66 KiB]`
   * @param fractions The number of decimal places the values should have.
   */
  styledData: (fractions?: number) => string;
  /**
   * The progress bar string.
   * Default Style: `[###-------]`
   */
  progressBar: string;
  /**
   * The duration of the progress bar.
   */
  time: number;
  /**
   * The duration passed to the last call.
   */
  previousTime: number;
  /**
   * The current value the progress bar is sitting at.
   */
  value: number;
  /**
   * The value passed to the last call.
   */
  previousValue: number;
  /**
   * The max value expected to receive.
   */
  max: number;
}

/**
 * The options that are provided to a {@link createProgressBar} or
 * {@link ProgressBarStream}.
 */
export interface ProgressBarOptions {
  /**
   * The offset size of the input if progress is resuming part way through.
   * @default {0}
   */
  value?: number;
  /**
   * The total size expected to receive.
   */
  max: number;
  /**
   * The length that the progress bar should be, in characters.
   * @default {50}
   */
  barLength?: number;
  /**
   * The character to fill the progress bar up with as it makes progress.
   * @default {'#'}
   */
  fillChar?: string;
  /**
   * The character the progress bar starts out with.
   * @default {'-'}
   */
  emptyChar?: string;
  /**
   * Whether the progress bar should be removed after completion.
   * @default {false}
   */
  clear?: boolean;
  /**
   * A function that creates the style of the progress bar.
   * Default Style: `[mm:ss] [###-------] [0.24/97.6 KiB]`.
   */
  fmt?: (fmt: ProgressBarFormatter) => string;
  /**
   * Whether the writable should be kept open when progress bar stops.
   * @default {true}
   */
  keepOpen?: boolean;
}

type Unit = "KiB" | "MiB" | "GiB" | "TiB" | "PiB";

function getUnit(max: number): Unit {
  if (max < 2 ** 20) return "KiB";
  if (max < 2 ** 30) return "MiB";
  if (max < 2 ** 40) return "GiB";
  if (max < 2 ** 50) return "TiB";
  return "PiB";
}

const UNIT_RATE_MAP = new Map<Unit, number>([
  ["KiB", 2 ** 10],
  ["MiB", 2 ** 20],
  ["GiB", 2 ** 30],
  ["TiB", 2 ** 40],
  ["PiB", 2 ** 50],
]);

/**
 * `ProgressBar` is a customisable class that reports updates to a
 * {@link WritableStream} on a 1s interval. Progress is communicated by calling
 * the `ProgressBar.add(x: number)` method.
 *
 * @experimental **UNSTABLE**: New API, yet to be vetted.
 *
 * @example Basic Usage
 * ```ts ignore
 * import { delay } from "@std/async";
 * import { ProgressBar } from "@std/cli/unstable-progress-bar";
 *
 * const gen = async function* () {
 *   for (let i = 0; i < 100; ++i) {
 *     yield new Uint8Array(1000).fill(97);
 *     await delay(Math.random() * 200 | 0);
 *   }
 * }();
 * const writer = (await Deno.create("./_tmp/output.txt")).writable.getWriter();
 *
 * const bar = new ProgressBar(Deno.stdout.writable, { max: 100_000 });
 *
 * for await (const buffer of gen) {
 *   bar.add(buffer.length);
 *   await writer.write(buffer);
 * }
 *
 * await bar.end();
 * await writer.close();
 * ```
 *
 * @example Custom Formatting
 * ```ts ignore
 * import { delay } from "@std/async";
 * import { ProgressBar } from "@std/cli/unstable-progress-bar";
 *
 * const bar = new ProgressBar(Deno.stdout.writable, {
 *   max: 100,
 *   fmt(x) {
 *     return `${x.styledTime()}${x.progressBar}[${x.value}/${x.max} files]`;
 *   },
 * });
 *
 * for (const x of Array(100)) {
 *   bar.add(1);
 *   await delay(Math.random() * 500);
 * }
 *
 * bar.end();
 */
export class ProgressBar {
  #unit: Unit;
  #rate: number;
  #writer: WritableStreamDefaultWriter;
  #id: number;
  #startTime: number;
  #lastTime: number;
  #lastValue: number;

  #value: number;
  #max: number;
  #barLength: number;
  #fillChar: string;
  #emptyChar: string;
  #clear: boolean;
  #fmt: (fmt: ProgressBarFormatter) => string;
  #keepOpen: boolean;
  /**
   * Constructs a new instance.
   *
   * @param writable The {@link WritableStream} that will receive the progress bar reports.
   * @param options The options to configure various settings of the progress bar.
   */
  constructor(
    writable: WritableStream<Uint8Array>,
    options: ProgressBarOptions,
  ) {
    const {
      value = 0,
      barLength = 50,
      fillChar = "#",
      emptyChar = "-",
      clear = false,
      fmt = (x) => `${x.styledTime()} ${x.progressBar} ${x.styledData()} `,
      keepOpen = true,
    } = options;
    this.#value = value;
    this.#max = options.max;
    this.#barLength = barLength;
    this.#fillChar = fillChar;
    this.#emptyChar = emptyChar;
    this.#clear = clear;
    this.#fmt = fmt;
    this.#keepOpen = keepOpen;

    this.#unit = getUnit(options.max);
    this.#rate = UNIT_RATE_MAP.get(this.#unit)!;

    const stream = new TextEncoderStream();
    stream.readable
      .pipeTo(writable, { preventClose: this.#keepOpen })
      .catch(() => clearInterval(this.#id));
    this.#writer = stream.writable.getWriter();
    this.#id = setInterval(() => this.#print(), 1000);
    this.#startTime = performance.now();
    this.#lastTime = this.#startTime;
    this.#lastValue = this.#value;
  }

  async #print(): Promise<void> {
    const currentTime = performance.now();

    const size = this.#value / this.#max * this.#barLength | 0;
    const fillChars = this.#fillChar.repeat(size);
    const emptyChars = this.#emptyChar.repeat(this.#barLength - size);

    const formatter: ProgressBarFormatter = {
      styledTime() {
        const minutes = (this.time / 1000 / 60 | 0).toString().padStart(2, "0");
        const seconds = (this.time / 1000 % 60 | 0).toString().padStart(2, "0");
        return `[${minutes}:${seconds}]`;
      },
      styledData: (fractions = 2): string => {
        const currentValue = (this.#value / this.#rate).toFixed(fractions);
        const maxValue = (this.#max / this.#rate).toFixed(fractions);
        return `[${currentValue}/${maxValue} ${this.#unit}]`;
      },
      progressBar: `[${fillChars}${emptyChars}]`,
      time: currentTime - this.#startTime,
      previousTime: this.#lastTime - this.#startTime,
      value: this.#value,
      previousValue: this.#lastValue,
      max: this.#max,
    };
    this.#lastTime = currentTime;
    this.#lastValue = this.#value;
    await this.#writer.write("\r\u001b[K" + this.#fmt(formatter))
      .catch(() => {});
  }

  /**
   * Increments the progress by `x`.
   *
   * @example Usage
   * ```ts ignore
   * import { ProgressBar } from "@std/cli/unstable-progress-bar";
   *
   * const progressBar = new ProgressBar(Deno.stdout.writable, { max: 100 });
   * progressBar.add(10);
   * ```
   * @param x The amount of progress that has been made.
   */
  add(x: number): void {
    this.#value += x;
  }

  /**
   * Ends the progress bar and cleans up any lose ends.
   *
   * @example Usage
   * ```ts ignore
   * import { ProgressBar } from "@std/cli/unstable-progress-bar";
   *
   * const progressBar = new ProgressBar(Deno.stdout.writable, { max: 100 });
   * await progressBar.end()
   * ```
   */
  async end(): Promise<void> {
    clearInterval(this.#id);
    await this.#print()
      .then(() => this.#writer.write(this.#clear ? "\r\u001b[K" : "\n"))
      .then(() => this.#writer.close())
      .catch(() => {});
  }
}