Skip to content

Commit 2447f4e

Browse files
committed
feat(cli): use logger
1 parent 6493eae commit 2447f4e

File tree

7 files changed

+66
-22
lines changed

7 files changed

+66
-22
lines changed

packages/cli/src/app.ts

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { makeLogger } from '@ocap/utils';
12
import path from 'node:path';
23
import yargs from 'yargs';
34
import { hideBin } from 'yargs/helpers';
@@ -9,6 +10,8 @@ import { defaultConfig } from './config.ts';
910
import type { Config } from './config.ts';
1011
import { withTimeout } from './utils.ts';
1112

13+
const logger = makeLogger('[cli]');
14+
1215
await yargs(hideBin(process.argv))
1316
.usage('$0 <command> [options]')
1417
.demandCommand(1)
@@ -55,7 +58,7 @@ await yargs(hideBin(process.argv))
5558
},
5659
dir: resolvedDir,
5760
};
58-
console.info(`starting ${appName} in ${resolvedDir} on ${url}`);
61+
logger.info(`starting ${appName} in ${resolvedDir} on ${url}`);
5962
const server = getServer(config);
6063
await server.listen();
6164
},
@@ -77,13 +80,13 @@ await yargs(hideBin(process.argv))
7780
ready
7881
.then((close) => {
7982
handleClose = close;
80-
console.info(`Watching ${args.dir}...`);
83+
logger.info(`Watching ${args.dir}...`);
8184
return undefined;
8285
})
83-
.catch(console.error);
86+
.catch((reason) => logger.error(reason));
8487

8588
error.catch(async (reason) => {
86-
console.error(reason);
89+
logger.error(reason);
8790
// If watching started, close the watcher.
8891
return handleClose ? withTimeout(handleClose(), 400) : undefined;
8992
});
@@ -120,7 +123,7 @@ await yargs(hideBin(process.argv))
120123
const { ready: watchReady, error: watchError } = watchDir(resolvedDir);
121124

122125
watchError.catch(async (reason) => {
123-
console.error(reason);
126+
logger.error(reason);
124127
await handleClose();
125128
});
126129

@@ -136,7 +139,7 @@ await yargs(hideBin(process.argv))
136139
const { close: closeServer, port } = await server.listen();
137140
closeHandlers.push(closeServer);
138141

139-
console.info(`bundling and serving ${resolvedDir} on localhost:${port}`);
142+
logger.info(`bundling and serving ${resolvedDir} on localhost:${port}`);
140143
},
141144
)
142145
.help('help')

packages/cli/src/commands/bundle.test.ts

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,13 @@ import { fileExists } from '../file.ts';
1111

1212
const mocks = vi.hoisted(() => ({
1313
bundleSource: vi.fn(),
14+
logger: {
15+
log: vi.fn(),
16+
error: vi.fn(),
17+
info: vi.fn(),
18+
warn: vi.fn(),
19+
debug: vi.fn(),
20+
},
1421
}));
1522

1623
vi.mock('@endo/bundle-source', () => ({
@@ -19,6 +26,10 @@ vi.mock('@endo/bundle-source', () => ({
1926

2027
vi.mock('@endo/init', () => ({}));
2128

29+
vi.mock('../logger.ts', () => ({
30+
logger: mocks.logger,
31+
}));
32+
2233
describe('bundle', async () => {
2334
const { testBundleRoot, getTestBundleSpecs, globBundles, resolveBundlePath } =
2435
await makeTestBundleStage();
@@ -34,6 +45,7 @@ describe('bundle', async () => {
3445
beforeEach(async () => {
3546
vi.resetModules();
3647
await deleteTestBundles();
48+
vi.resetAllMocks();
3749
});
3850

3951
describe('createBundleFile', () => {
@@ -57,11 +69,10 @@ describe('bundle', async () => {
5769
},
5870
);
5971

60-
it('calls console.error if bundling fails', async () => {
61-
const consoleErrorSpy = vi.spyOn(console, 'error');
72+
it('calls logger.error if bundling fails', async () => {
6273
const badBundle = resolveBundlePath('bad-vat.fails');
6374
await createBundleFile(badBundle);
64-
expect(consoleErrorSpy).toHaveBeenCalledOnce();
75+
expect(mocks.logger.error).toHaveBeenCalledOnce();
6576
});
6677
});
6778

packages/cli/src/commands/bundle.ts

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { writeFile } from 'node:fs/promises';
55
import { resolve, join } from 'node:path';
66

77
import { isDirectory } from '../file.ts';
8+
import { logger } from '../logger.ts';
89
import { resolveBundlePath } from '../path.ts';
910

1011
/**
@@ -25,9 +26,9 @@ export async function createBundleFile(
2526
const bundle = await bundleSource(sourceFullPath);
2627
const bundleString = JSON.stringify(bundle);
2728
await writeFile(bundlePath, bundleString);
28-
console.log(`wrote ${bundlePath}: ${new Blob([bundleString]).size} bytes`);
29+
logger.log(`wrote ${bundlePath}: ${new Blob([bundleString]).size} bytes`);
2930
} catch (problem) {
30-
console.error(problem);
31+
logger.error(problem);
3132
}
3233
}
3334

@@ -38,7 +39,7 @@ export async function createBundleFile(
3839
* @returns A promise that resolves when the bundles have been written.
3940
*/
4041
export async function createBundleDir(sourceDir: string): Promise<void> {
41-
console.log('bundling dir', sourceDir);
42+
logger.log('bundling dir', sourceDir);
4243
await Promise.all(
4344
(await glob(join(sourceDir, '*.js'))).map(
4445
async (source) => await createBundleFile(source),

packages/cli/src/commands/watch.test.ts

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,16 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';
88
import { createBundleFile } from './bundle.ts';
99
import { watchDir, makeWatchEvents } from './watch.ts';
1010

11+
const mocks = vi.hoisted(() => ({
12+
logger: {
13+
log: vi.fn(),
14+
error: vi.fn(),
15+
info: vi.fn(),
16+
warn: vi.fn(),
17+
debug: vi.fn(),
18+
},
19+
}));
20+
1121
vi.mock('fs/promises', () => ({
1222
unlink: vi.fn(async () => new Promise<void>(() => undefined)),
1323
}));
@@ -20,9 +30,13 @@ vi.mock('./bundle.ts', () => ({
2030
createBundleFile: vi.fn(async () => new Promise<void>(() => undefined)),
2131
}));
2232

33+
vi.mock('../logger.ts', () => ({
34+
logger: mocks.logger,
35+
}));
36+
2337
vi.mock('chokidar', () => ({
2438
watch: () => {
25-
console.log('returning watcher...');
39+
mocks.logger.log('returning watcher...');
2640
const watcher = {
2741
on: () => watcher,
2842
close: async (): Promise<void> => undefined,
@@ -99,26 +113,25 @@ describe('makeWatchEvents', () => {
99113
expect(unlink).toHaveBeenLastCalledWith(`resolved:${testPath}`);
100114
});
101115

102-
it('calls console.info on success', async () => {
116+
it('calls logger.info on success', async () => {
103117
const promise = Promise.resolve();
104118
vi.mocked(unlink).mockReturnValue(promise);
105119

106120
const events = makeWatchEvents(watch('.'), vi.fn(), vi.fn());
107121
const testPath = 'test-path';
108-
const infoSpy = vi.spyOn(console, 'info');
109122

110123
events.unlink(testPath);
111124

112125
// wait for next crank turn
113126
await Promise.resolve();
114127

115-
expect(infoSpy).toHaveBeenCalledTimes(2);
116-
expect(infoSpy).toHaveBeenNthCalledWith(
128+
expect(mocks.logger.info).toHaveBeenCalledTimes(2);
129+
expect(mocks.logger.info).toHaveBeenNthCalledWith(
117130
1,
118131
'Source file removed:',
119132
testPath,
120133
);
121-
expect(infoSpy).toHaveBeenNthCalledWith(
134+
expect(mocks.logger.info).toHaveBeenNthCalledWith(
122135
2,
123136
`removed resolved:${testPath}`,
124137
);

packages/cli/src/commands/watch.ts

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { unlink } from 'fs/promises';
55
import { resolve } from 'path';
66

77
import { createBundleFile } from './bundle.ts';
8+
import { logger } from '../logger.ts';
89
import { resolveBundlePath } from '../path.ts';
910

1011
type CloseWatcher = () => Promise<void>;
@@ -27,18 +28,18 @@ export const makeWatchEvents = (
2728
} => ({
2829
ready: () => readyResolve(watcher.close.bind(watcher)),
2930
add: (path) => {
30-
console.info(`Source file added:`, path);
31+
logger.info(`Source file added:`, path);
3132
createBundleFile(path, resolveBundlePath(path)).catch(throwError);
3233
},
3334
change: (path) => {
34-
console.info(`Source file changed:`, path);
35+
logger.info(`Source file changed:`, path);
3536
createBundleFile(path, resolveBundlePath(path)).catch(throwError);
3637
},
3738
unlink: (path) => {
38-
console.info('Source file removed:', path);
39+
logger.info('Source file removed:', path);
3940
const bundlePath = resolveBundlePath(path);
4041
unlink(bundlePath)
41-
.then(() => console.info(`removed ${bundlePath}`))
42+
.then(() => logger.info(`removed ${bundlePath}`))
4243
.catch((reason: unknown) => {
4344
if (reason instanceof Error && reason.message.match(/ENOENT/u)) {
4445
// If associated bundle does not exist, do nothing.

packages/cli/src/logger.test.ts

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import { describe, it, expect } from 'vitest';
2+
3+
describe('logger', () => {
4+
it('exports a logger', async () => {
5+
const { logger } = await import('./logger.ts');
6+
expect(logger).toBeDefined();
7+
expect(logger.label).toMatch(/cli/u);
8+
});
9+
});

packages/cli/src/logger.ts

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
import { makeLogger } from '@ocap/utils';
2+
3+
/**
4+
* The default CLI logger
5+
*/
6+
export const logger = makeLogger('[ocap cli]');

0 commit comments

Comments
 (0)