All files / cli / unstable_progress_bar.ts

100.00% Branches 7/7
100.00% Lines 104/104
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
 
 
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
 
x59
x59
x59
 
x61
x61
x61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
x24
 
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x6
 
 
 
 
 
x6
x6
x6
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
x24
 
x24
x24
x72
x24
x24
x24
x24
x24
 
x24
x24
x24
x6
x61
 
x61
x61
x61
x61
 
x61
x61
x114
x114
x114
x61
x61
x114
x61
x61
x61
x61
x61
x61
x61
x61
x61
x6
x61
x61
x61
x61
x61
 
x67
x61
x61
x61
 
 
 
 
 
 
 
 
 
 
 
 
x6
x24
x24
x24
x25
x24
x41
x41
x52
x36
x36
x24
 
x30
x24
x6















































































































































































































































































































// Copyright 2018-2025 the Deno authors. MIT license.

import { formatUnitFraction } from "./_unit.ts";

/**
 * The properties provided to the fmt function upon every visual update.
 */
export interface ProgressBarFormatter {
  /**
   * 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 {@link WritableStream} that will receive the progress bar reports.
   * @default {Deno.stderr.writable}
   */
  writable?: WritableStream<Uint8Array>;
  /**
   * 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;
}

const LINE_CLEAR = "\r\u001b[K";

function defaultFormatter(x: ProgressBarFormatter) {
  return `[${x.styledTime}] [${x.progressBar}] [${x.styledData()}]`;
}

function clamp(value: number, min: number, max: number) {
  return Math.min(Math.max(value, min), max);
}

/**
 * `ProgressBar` is a customisable class that reports updates to a
 * {@link WritableStream} on a 1s interval. Progress is communicated by using
 * the `ProgressBar.value` property.
 *
 * @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({ max: 100_000 });
 *
 * for await (const buffer of gen) {
 *   bar.value += buffer.length;
 *   await writer.write(buffer);
 * }
 *
 * await bar.stop();
 * 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({
 *   max: 100,
 *   fmt(x) {
 *     return `[${x.styledTime()}] [${x.progressBar}] [${x.value}/${x.max} files]`;
 *   },
 * });
 *
 * for (const x of Array(100)) {
 *   bar.value += 1;
 *   await delay(Math.random() * 500);
 * }
 *
 * await bar.stop();
 */
export class ProgressBar {
  /**
   * The current progress that has been completed.
   * @example Usage
   * ```ts no-assert
   * import { ProgressBar } from "@std/cli/unstable-progress-bar";
   *
   * const progressBar = new ProgressBar({ max : 10 });
   * progressBar.value += 1;
   *
   * // do stuff
   *
   * await progressBar.stop();
   * ```
   */
  value: number;
  /**
   * The maximum progress that is expected.
   * @example Usage
   * ```ts no-assert
   * import { ProgressBar } from "@std/cli/unstable-progress-bar";
   *
   * const progressBar = new ProgressBar({ max : 1 });
   * progressBar.max = 100;
   *
   * // do stuff
   *
   * await progressBar.stop();
   * ```
   */
  max: number;

  #writer: WritableStreamDefaultWriter;
  #id: number;
  #startTime: number;
  #previousTime: number;
  #previousValue: number;
  #barLength: number;
  #fillChar: string;
  #emptyChar: string;
  #clear: boolean;
  #fmt: (fmt: ProgressBarFormatter) => string;
  #keepOpen: boolean;
  #pipePromise: Promise<void>;
  /**
   * Constructs a new instance.
   *
   * @param options The options to configure various settings of the progress bar.
   */
  constructor(
    options: ProgressBarOptions,
  ) {
    const {
      writable = Deno.stderr.writable,
      value = 0,
      max,
      barLength = 50,
      fillChar = "#",
      emptyChar = "-",
      clear = false,
      fmt = defaultFormatter,
      keepOpen = true,
    } = options;
    this.value = value;
    this.max = max;
    this.#barLength = barLength;
    this.#fillChar = fillChar;
    this.#emptyChar = emptyChar;
    this.#clear = clear;
    this.#fmt = fmt;
    this.#keepOpen = keepOpen;

    const stream = new TextEncoderStream();
    this.#pipePromise = stream.readable
      .pipeTo(writable, { preventClose: this.#keepOpen })
      .catch(() => clearInterval(this.#id));
    this.#writer = stream.writable.getWriter();
    this.#startTime = Date.now();
    this.#previousTime = 0;
    this.#previousValue = this.value;

    this.#id = setInterval(() => this.#print(), 1000);
    this.#print();
  }
  #createFormatterObject() {
    const time = Date.now() - this.#startTime;

    const ratio = clamp(this.value / this.max, 0, 1);
    const size = Math.trunc(ratio * this.#barLength);
    const fillChars = this.#fillChar.repeat(size);
    const emptyChars = this.#emptyChar.repeat(this.#barLength - size);

    return {
      get 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() {
        return formatUnitFraction(this.value, this.max);
      },
      progressBar: `${fillChars}${emptyChars}`,
      time,
      previousTime: this.#previousTime,
      value: this.value,
      previousValue: this.#previousValue,
      max: this.max,
    };
  }
  async #print(): Promise<void> {
    const formatter = this.#createFormatterObject();
    const output = this.#fmt(formatter);
    try {
      await this.#writer.write(LINE_CLEAR + output);
    } catch {
      // ignore
    }
    this.#previousTime = formatter.time;
    this.#previousValue = formatter.value;
  }

  /**
   * 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({ max: 100 });
   * await progressBar.stop()
   * ```
   */
  async stop(): Promise<void> {
    clearInterval(this.#id);
    try {
      if (this.#clear) {
        await this.#writer.write(LINE_CLEAR);
      } else {
        await this.#print();
        await this.#writer.write("\n");
      }
      await this.#writer.close();
      await this.#pipePromise;
    } catch {
      // ignore
    }
  }
}