Skip to content

Commit

Permalink
chore(cli): support stderr on spinner
Browse files Browse the repository at this point in the history
  • Loading branch information
andrewthauer committed Jan 18, 2025
1 parent 5d41054 commit 6c03bf3
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
14 changes: 11 additions & 3 deletions cli/unstable_spinner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,12 @@ export interface SpinnerOptions {
* This can be changed while the spinner is active.
*/
color?: Color;
/*
* The stream to write the spinner to.
*
* @default {Deno.stdout}
*/
stream?: typeof Deno.stderr | typeof Deno.stdout;
}

/**
Expand Down Expand Up @@ -126,6 +132,7 @@ export class Spinner {
#color: Color | undefined;
#intervalId: number | undefined;
#active = false;
#stream: typeof Deno.stdout | typeof Deno.stderr;

/**
* Creates a new spinner.
Expand All @@ -142,6 +149,7 @@ export class Spinner {
this.#spinner = spinner;
this.message = message;
this.#interval = interval;
this.#stream = options?.stream ?? Deno.stdout;
this.color = color;
}

Expand Down Expand Up @@ -199,7 +207,7 @@ export class Spinner {
* ```
*/
start() {
if (this.#active || Deno.stdout.writable.locked) {
if (this.#active || this.#stream.writable.locked) {
return;
}

Expand All @@ -219,7 +227,7 @@ export class Spinner {
const writeData = new Uint8Array(LINE_CLEAR.length + frame.length);
writeData.set(LINE_CLEAR);
writeData.set(frame, LINE_CLEAR.length);
Deno.stdout.writeSync(writeData);
this.#stream.writeSync(writeData);
i = (i + 1) % this.#spinner.length;
};

Expand All @@ -245,7 +253,7 @@ export class Spinner {
stop() {
if (this.#intervalId && this.#active) {
clearInterval(this.#intervalId);
Deno.stdout.writeSync(LINE_CLEAR); // Clear the current line
this.#stream.writeSync(LINE_CLEAR); // Clear the current line
this.#active = false;
}
}
Expand Down
33 changes: 33 additions & 0 deletions cli/unstable_spinner_test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,39 @@ Deno.test("Spinner constructor accepts interval", async () => {
}
});

Deno.test("Spinner constructor accepts stream", async () => {
try {
stub(Deno.stdin, "setRaw");

const expectedOutput = [
"\r\x1b[K⠋\x1b[0m ",
"\r\x1b[K⠙\x1b[0m ",
"\r\x1b[K⠹\x1b[0m ",
"\r\x1b[K",
];

const actualOutput: string[] = [];

stub(
Deno.stderr,
"writeSync",
(data: Uint8Array) => {
const output = decoder.decode(data);
actualOutput.push(output);
return data.length;
},
);

const spinner = new Spinner({ interval: 300, stream: Deno.stderr });
spinner.start();
await delay(1000); // 100ms buffer
spinner.stop();
assertEquals(actualOutput, expectedOutput);
} finally {
restore();
}
});

Deno.test("Spinner constructor accepts each color", async (t) => {
await t.step("black", async () => {
try {
Expand Down

0 comments on commit 6c03bf3

Please sign in to comment.