[toolingLog] when indent block is synchronous, dedent synchronously (#129269)

Co-authored-by: kibanamachine <42973632+kibanamachine@users.noreply.github.com>
This commit is contained in:
Spencer 2022-04-04 10:53:08 -05:00 committed by GitHub
parent 3fd4621716
commit 513c81b803
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 51 additions and 16 deletions

View file

@ -95,6 +95,24 @@ describe('#indent()', () => {
]
`);
});
it('resets the indent synchrounsly if the block does not return a promise', () => {
const log = new ToolingLog();
const writer = new ToolingLogCollectingWriter();
log.setWriters([writer]);
log.info('foo');
log.indent(4, () => log.error('bar'));
log.info('baz');
expect(writer.messages).toMatchInlineSnapshot(`
Array [
" info foo",
" │ERROR bar",
" info baz",
]
`);
});
});
(['verbose', 'debug', 'info', 'success', 'warning', 'error', 'write'] as const).forEach(

View file

@ -62,23 +62,33 @@ export class ToolingLog {
* @param delta the number of spaces to increase/decrease the indentation
* @param block a function to run and reset any indentation changes after
*/
public indent(delta: number): undefined;
public indent(delta: number): void;
public indent<T>(delta: number, block: () => Promise<T>): Promise<T>;
public indent<T>(delta: number, block: () => T): T;
public indent<T>(delta = 0, block?: () => T | Promise<T>) {
public indent<T>(delta = 0, block?: () => T | Promise<T>): void | T | Promise<T> {
const originalWidth = this.indentWidth$.getValue();
this.indentWidth$.next(Math.max(originalWidth + delta, 0));
if (!block) {
return;
}
return (async () => {
try {
return await block();
} finally {
this.indentWidth$.next(originalWidth);
}
})();
const maybePromise: any = block();
if (
typeof maybePromise === 'object' &&
maybePromise &&
typeof maybePromise.then === 'function'
) {
return (async () => {
try {
return await maybePromise;
} finally {
this.indentWidth$.next(originalWidth);
}
})();
}
this.indentWidth$.next(originalWidth);
return maybePromise;
}
public verbose(...args: any[]) {

View file

@ -649,13 +649,20 @@ class ToolingLog {
return;
}
return (async () => {
try {
return await block();
} finally {
this.indentWidth$.next(originalWidth);
}
})();
const maybePromise = block();
if (typeof maybePromise === 'object' && maybePromise && typeof maybePromise.then === 'function') {
return (async () => {
try {
return await maybePromise;
} finally {
this.indentWidth$.next(originalWidth);
}
})();
}
this.indentWidth$.next(originalWidth);
return maybePromise;
}
verbose(...args) {