Skip to content

Commit

Permalink
refactor: Update log system
Browse files Browse the repository at this point in the history
  • Loading branch information
spring-raining committed Jan 1, 2025
1 parent 02508ff commit 5ffbb5c
Show file tree
Hide file tree
Showing 20 changed files with 431 additions and 453 deletions.
7 changes: 3 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
"ajv-formats": "^2.1.1",
"archiver": "^5.3.1",
"bcp-47-match": "^2.0.3",
"chalk": "^4.1.2",
"command-exists": "1.2.9",
"commander": "^12.1.0",
"debug": "^4.3.2",
Expand All @@ -43,10 +42,8 @@
"github-slugger": "^2.0.0",
"hast-util-to-html": "^9.0.1",
"hastscript": "^9.0.0",
"is-interactive": "1.0.0",
"mime-types": "^2.1.32",
"node-stream-zip": "^1.14.0",
"ora": "^5.4.1",
"pdf-lib": "^1.16.0",
"playwright-core": "1.49.0",
"press-ready": "^4.0.3",
Expand All @@ -62,7 +59,9 @@
"vfile": "^4.2.1",
"vite": "6.0.3",
"w3c-xmlserializer": "^4.0.0",
"whatwg-mimetype": "^3.0.0"
"whatwg-mimetype": "^3.0.0",
"yocto-spinner": "^0.1.2",
"yoctocolors": "^2.1.1"
},
"devDependencies": {
"@release-it/conventional-changelog": "^5.1.1",
Expand Down
30 changes: 12 additions & 18 deletions src/browser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,8 @@ import * as playwright from 'playwright-core';
import { registry } from 'playwright-core/lib/server';
import { ResolvedTaskConfig } from './config/resolve.js';
import type { BrowserType } from './config/schema.js';
import {
beforeExitHandlers,
debug,
isInContainer,
logInfo,
logSuccess,
pathEquals,
suspendLogging,
} from './util.js';
import { Logger } from './logger.js';
import { beforeExitHandlers, isInContainer, pathEquals } from './util.js';

export async function launchBrowser({
browserType,
Expand Down Expand Up @@ -51,9 +44,9 @@ export async function launchBrowser({
headless && '--force-device-scale-factor=1',
// set Chromium language to English to avoid locale-dependent issues (e.g. minimum font size)
'--lang=en',
...(!headless && process.platform === 'darwin'
? ['-AppleLanguages', '(en)']
: []),
// ...(!headless && process.platform === 'darwin'
// ? ['-AppleLanguages', '(en)']
// : []),
].filter((value): value is string => Boolean(value)),
env: { ...process.env, LANG: 'en.UTF-8' },
proxy: proxy,
Expand Down Expand Up @@ -93,11 +86,12 @@ export async function downloadBrowser(
browserType: BrowserType,
): Promise<string> {
const executable = registry.findExecutable(browserType);
logInfo('Rendering browser is not installed yet. Downloading now...');
const restartLogging = suspendLogging();
await registry.install([executable], false);
logSuccess(`Successfully downloaded browser`);
restartLogging();
{
using _ = Logger.suspendLogging(
'Rendering browser is not installed yet. Downloading now.',
);
await registry.install([executable], false);
}
return executable.executablePath()!;
}

Expand All @@ -121,7 +115,7 @@ export async function launchPreview({
| 'ignoreHttpsErrors'
>;
}) {
debug(`Executing browser path: ${executableBrowser}`);
Logger.debug(`Executing browser path: ${executableBrowser}`);
if (!checkBrowserAvailability(executableBrowser)) {
if (isPlaywrightExecutable(executableBrowser)) {
// The browser isn't downloaded first time starting CLI so try to download it
Expand Down
8 changes: 6 additions & 2 deletions src/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import process from 'node:process';
import { build } from '../core/build.js';
import { debug, gracefulError, isInContainer } from '../util.js';
import { Logger } from '../logger.js';
import { gracefulError, isInContainer } from '../util.js';
import { setupBuildParserProgram } from './build.parser.js';
import { parseFlagsToInlineConfig } from './cli-flags.js';

Expand All @@ -11,7 +12,10 @@ try {
);
if (isInContainer()) {
inlineConfig = JSON.parse(process.env.VS_CLI_BUILD_PDF_OPTIONS!);
debug('bypassedPdfBuilderOption', JSON.stringify(inlineConfig, null, 2));
Logger.debug(
'bypassedPdfBuilderOption',
JSON.stringify(inlineConfig, null, 2),
);
}
await build(inlineConfig);
} catch (err) {
Expand Down
27 changes: 9 additions & 18 deletions src/commands/cli-flags.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import chalk from 'chalk';
import { Command, OptionValues } from 'commander';
import upath from 'upath';
import * as v from 'valibot';
Expand All @@ -10,7 +9,7 @@ import {
VivliostyleInlineConfig,
} from '../config/schema.js';
import { EMPTY_DATA_URI } from '../const.js';
import { logWarn } from '../util.js';
import { Logger } from '../logger.js';

export interface CliFlags {
input?: string;
Expand Down Expand Up @@ -98,36 +97,28 @@ function warnDeprecatedFlags(options: OptionValues): OptionValues {
const modifiedOptions = { ...options };

if (options.executableChromium) {
logWarn(
chalk.yellowBright(
"'--executable-chromium' option was deprecated and will be removed in a future release. Please replace with '--executable-browser' option.",
),
Logger.logWarn(
"'--executable-chromium' option was deprecated and will be removed in a future release. Please replace with '--executable-browser' option.",
);
modifiedOptions.executableBrowser = options.executableChromium;
}

if (options.verbose) {
logWarn(
chalk.yellowBright(
"'--verbose' option was deprecated and will be removed in a future release. Please replace with '--log-level verbose' option.",
),
Logger.logWarn(
"'--verbose' option was deprecated and will be removed in a future release. Please replace with '--log-level verbose' option.",
);
modifiedOptions.logLevel = 'verbose';
}

if (options.sandbox === false) {
logWarn(
chalk.yellowBright(
"'--no-sandbox' option was deprecated and will be removed in a future release. It is no longer necessary because the sandbox is disabled by default.",
),
Logger.logWarn(
"'--no-sandbox' option was deprecated and will be removed in a future release. It is no longer necessary because the sandbox is disabled by default.",
);
}

if (options.http) {
logWarn(
chalk.yellowBright(
"'--http' option was deprecated and will be removed in a future release. It is unnecessary because the HTTP server starts automatically.",
),
Logger.logWarn(
"'--http' option was deprecated and will be removed in a future release. It is unnecessary because the HTTP server starts automatically.",
);
}

Expand Down
21 changes: 7 additions & 14 deletions src/config/load.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import chalk from 'chalk';
import fs from 'node:fs';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
import upath from 'upath';
import * as v from 'valibot';
import { Logger } from '../logger.js';
import {
cwd as defaultRoot,
DetailError,
logWarn,
parseJsonc,
prettifySchemaError,
} from '../util.js';
Expand Down Expand Up @@ -84,26 +83,20 @@ export async function loadVivliostyleConfig({

export function warnDeprecatedConfig(config: ParsedVivliostyleConfigSchema) {
if (config.tasks.some((task) => task.includeAssets)) {
logWarn(
chalk.yellowBright(
"'includeAssets' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'copyAsset.includes' property instead.",
),
Logger.logWarn(
"'includeAssets' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'copyAsset.includes' property instead.",
);
}

if (config.tasks.some((task) => task.tocTitle)) {
logWarn(
chalk.yellowBright(
"'tocTitle' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'toc.title' property instead.",
),
Logger.logWarn(
"'tocTitle' property of Vivliostyle config was deprecated and will be removed in a future release. Please use 'toc.title' property instead.",
);
}

if (config.tasks.some((task) => task.http)) {
logWarn(
chalk.yellowBright(
"'http' property of Vivliostyle config was deprecated and will be removed in a future release. This option is enabled by default, and the file protocol is no longer supported.",
),
Logger.logWarn(
"'http' property of Vivliostyle config was deprecated and will be removed in a future release. This option is enabled by default, and the file protocol is no longer supported.",
);
}
}
24 changes: 10 additions & 14 deletions src/config/resolve.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Metadata, StringifyMarkdownOptions, VFM } from '@vivliostyle/vfm';
import chalk from 'chalk';
import { lookup as mime } from 'mime-types';
import fs from 'node:fs';
import { pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -27,15 +26,14 @@ import {
TOC_TITLE,
} from '../const.js';
import { CONTAINER_IMAGE, CONTAINER_LOCAL_HOSTNAME } from '../container.js';
import { Logger } from '../logger.js';
import { readMarkdownMetadata } from '../processor/markdown.js';
import { parsePackageName } from '../processor/theme.js';
import {
debug,
cwd as defaultCwd,
getEpubRootDir,
isInContainer,
isValidUri,
logWarn,
pathEquals,
readJSON,
statFileSync,
Expand Down Expand Up @@ -428,9 +426,9 @@ export function resolveTaskConfig(
options: InlineOptions,
): ResolvedTaskConfig {
const context = options.cwd ?? defaultCwd;
debug('context directory', context);
debug('inlineOptions', options);
debug('vivliostyle.config.js', config);
Logger.debug('context directory', context);
Logger.debug('inlineOptions', options);
Logger.debug('vivliostyle.config.js', config);

const entryContextDir = config.entryContext
? upath.resolve(context, config.entryContext)
Expand Down Expand Up @@ -643,7 +641,7 @@ export function resolveTaskConfig(
viteConfig,
viteConfigFile,
} satisfies ResolvedTaskConfig;
debug('resolvedConfig', JSON.stringify(resolvedConfig, null, 2));
Logger.debug('resolvedConfig', JSON.stringify(resolvedConfig, null, 2));
return resolvedConfig;
}

Expand Down Expand Up @@ -672,7 +670,7 @@ function resolveSingleInputConfig({
config: ParsedBuildTask;
input: NonNullable<InlineOptions['input']>;
}): ProjectConfig {
debug('entering single entry config mode');
Logger.debug('entering single entry config mode');

let sourcePath: string;
let workspaceDir: string;
Expand Down Expand Up @@ -854,7 +852,7 @@ function resolveComposedProjectConfig({
| 'rootUrl'
| 'cover'
> & { config: ParsedBuildTask }): ProjectConfig {
debug('entering composed project config mode');
Logger.debug('entering composed project config mode');

const workspaceDir = upath.resolve(
context,
Expand All @@ -866,7 +864,7 @@ function resolveComposedProjectConfig({
? readJSON(pkgJsonPath)
: undefined;
if (pkgJson) {
debug('located package.json path', pkgJsonPath);
Logger.debug('located package.json path', pkgJsonPath);
}
const exportAliases: { source: string; target: string }[] = [];

Expand Down Expand Up @@ -987,10 +985,8 @@ function resolveComposedProjectConfig({
/* v8 ignore next 10 */
} catch (error) {
// For backward compatibility, we allow missing files then assume that option as `output` field.
logWarn(
chalk.yellowBright(
`The "path" option is set but the file does not exist: ${source}\nMaybe you want to set the "output" field instead.`,
),
Logger.logWarn(
`The "path" option is set but the file does not exist: ${source}\nMaybe you want to set the "output" field instead.`,
);
entry.output = entry.path;
entry.path = undefined;
Expand Down
45 changes: 20 additions & 25 deletions src/container.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
import chalk from 'chalk';
import commandExists from 'command-exists';
import { execa } from 'execa';
import isInteractive from 'is-interactive';
import { execFile } from 'node:child_process';
import process from 'node:process';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand All @@ -10,8 +8,9 @@ import upath from 'upath';
import { PdfOutput, ResolvedTaskConfig } from './config/resolve.js';
import { ParsedVivliostyleInlineConfig } from './config/schema.js';
import { cliVersion } from './const.js';
import { Logger } from './logger.js';
import { getSourceUrl } from './server.js';
import { debug, isValidUri, log, pathEquals, suspendLogging } from './util.js';
import { isValidUri, pathEquals } from './util.js';

const execFileAsync = promisify(execFile);

Expand Down Expand Up @@ -93,35 +92,31 @@ export async function runContainer({
);
}

const restartLogging = suspendLogging('Launching docker container', '📦');
const args = [
'run',
...(isInteractive() ? ['-it'] : []),
'--rm',
...(entrypoint ? ['--entrypoint', entrypoint] : []),
...(env ? env.flatMap(([k, v]) => ['-e', `${k}=${v}`]) : []),
...(process.env.DEBUG
? ['-e', `DEBUG=${process.env.DEBUG}`] // escape seems to work well
: []),
...userVolumeArgs.flatMap((arg) => ['-v', arg]),
...(workdir ? ['-w', workdir] : []),
image,
...commandArgs,
];
debug(`docker ${args.join(' ')}`);
try {
using _ = Logger.suspendLogging('Launching docker container');
const args = [
'run',
...(Logger.isInteractive ? ['-it'] : []),
'--rm',
...(entrypoint ? ['--entrypoint', entrypoint] : []),
...(env ? env.flatMap(([k, v]) => ['-e', `${k}=${v}`]) : []),
...(process.env.DEBUG
? ['-e', `DEBUG=${process.env.DEBUG}`] // escape seems to work well
: []),
...userVolumeArgs.flatMap((arg) => ['-v', arg]),
...(workdir ? ['-w', workdir] : []),
image,
...commandArgs,
];
Logger.debug(`docker ${args.join(' ')}`);
const proc = execa('docker', args, {
stdio: 'inherit',
});
await proc;
restartLogging();
} catch (error) {
log(
`\n${chalk.red.bold(
'Error:',
)} An error occurred on the running container. Please see logs above.`,
throw new Error(
'An error occurred on the running container. Please see logs above.',
);
process.exit(1);
}
}

Expand Down
Loading

0 comments on commit 5ffbb5c

Please sign in to comment.