From d5004b6e23bf1e4745ddd345228e71d06d87fcef Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 08:17:14 +0100 Subject: [PATCH 1/7] Add verbose logging to create-astro --- packages/create-astro/src/index.ts | 15 ++- packages/create-astro/src/logger.ts | 141 ++++++++++++++++++++++++++++ 2 files changed, 153 insertions(+), 3 deletions(-) create mode 100644 packages/create-astro/src/logger.ts diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index 898d6b2486eb..4e44d26edfac 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -8,6 +8,7 @@ import yargs from 'yargs-parser'; import { FRAMEWORKS, COUNTER_COMPONENTS } from './frameworks.js'; import { TEMPLATES } from './templates.js'; import { createConfig } from './config.js'; +import { logger, defaultLogLevel } from './logger.js'; // NOTE: In the v7.x version of npm, the default behavior of `npm init` was changed // to no longer require `--` to pass args and instead pass `--` directly to us. This @@ -31,6 +32,7 @@ const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import const POSTPROCESS_FILES = ['package.json', 'astro.config.mjs', 'CHANGELOG.md']; // some files need processing after copying. export async function main() { + logger.debug("Verbose logging turned on") console.log(`\n${bold('Welcome to Astro!')} ${gray(`(create-astro v${version})`)}`); console.log(`If you encounter a problem, visit ${cyan('https://github.com/withastro/astro/issues')} to search or file a new issue.\n`); @@ -75,9 +77,15 @@ export async function main() { const emitter = degit(`${templateTarget}${hash}`, { cache: false, force: true, - verbose: false, + verbose: defaultLogLevel === 'debug' ? true : false, }); + logger.debug('Initialized degit with following config:',`${templateTarget}${hash}`, { + cache: false, + force: true, + verbose: defaultLogLevel === 'debug' ? true : false, + }) + const selectedTemplate = TEMPLATES.find((template) => template.value === options.template); let renderers: string[] = []; @@ -99,11 +107,12 @@ export async function main() { // Copy try { - // emitter.on('info', info => { console.log(info.message) }); + emitter.on('info', info => { logger.debug(info.message) }); console.log(`${green(`>`)} ${gray(`Copying project files...`)}`); await emitter.clone(cwd); } catch (err: any) { - // degit is compiled, so the stacktrace is pretty noisy. Just report the message. + // degit is compiled, so the stacktrace is pretty noisy. Only report the stacktrace when using verbose mode. + logger.debug(err) console.error(red(err.message)); // Warning for issue #655 diff --git a/packages/create-astro/src/logger.ts b/packages/create-astro/src/logger.ts new file mode 100644 index 000000000000..6c5aac5590e1 --- /dev/null +++ b/packages/create-astro/src/logger.ts @@ -0,0 +1,141 @@ +import { bold, blue, dim, red, yellow } from 'kleur/colors'; +import { Writable } from 'stream'; +import { format as utilFormat } from 'util'; + +type ConsoleStream = Writable & { + fd: 1 | 2; +}; + +function getLoggerLocale(): string { + const defaultLocale = 'en-US'; + if (process.env.LANG) { + const extractedLocale = process.env.LANG.split('.')[0].replace(/_/g, '-'); + // Check if language code is atleast two characters long (ie. en, es). + // NOTE: if "c" locale is encountered, the default locale will be returned. + if (extractedLocale.length < 2) return defaultLocale; + else return extractedLocale; + } else return defaultLocale; +} + +const dt = new Intl.DateTimeFormat(getLoggerLocale(), { + hour: '2-digit', + minute: '2-digit', +}); + +export const defaultLogDestination = new Writable({ + objectMode: true, + write(event: LogMessage, _, callback) { + let dest: ConsoleStream = process.stderr; + if (levels[event.level] < levels['error']) { + dest = process.stdout; + } + + dest.write(dim(dt.format(new Date()) + ' ')); + + let type = event.type; + if (type) { + if (event.level === 'info') { + type = bold(blue(type)); + } else if (event.level === 'warn') { + type = bold(yellow(type)); + } else if (event.level === 'error') { + type = bold(red(type)); + } + + dest.write(`[${type}] `); + } + + dest.write(utilFormat(...event.args)); + dest.write('\n'); + + callback(); + }, +}); + +interface LogWritable extends Writable { + write: (chunk: T) => boolean; +} + +export type LoggerLevel = 'debug' | 'info' | 'warn' | 'error' | 'silent'; // same as Pino +export type LoggerEvent = 'debug' | 'info' | 'warn' | 'error'; + +export let defaultLogLevel: LoggerLevel; +if (process.argv.includes('--verbose')) { + defaultLogLevel = 'debug'; +} else if (process.argv.includes('--silent')) { + defaultLogLevel = 'silent'; +} else { + defaultLogLevel = 'info'; +} + +export interface LogOptions { + dest?: LogWritable; + level?: LoggerLevel; +} + +export const defaultLogOptions: Required = { + dest: defaultLogDestination, + level: defaultLogLevel, +}; + +export interface LogMessage { + type: string | null; + level: LoggerLevel; + message: string; + args: Array; +} + +export const levels: Record = { + debug: 20, + info: 30, + warn: 40, + error: 50, + silent: 90, +}; + +/** Full logging API */ +export function log(opts: LogOptions = {}, level: LoggerLevel, type: string | null, ...args: Array) { + const logLevel = opts.level ?? defaultLogOptions.level; + const dest = opts.dest ?? defaultLogOptions.dest; + const event: LogMessage = { + type, + level, + args, + message: '', + }; + + // test if this level is enabled or not + if (levels[logLevel] > levels[level]) { + return; // do nothing + } + + dest.write(event); +} + +/** Emit a message only shown in debug mode */ +export function debug(opts: LogOptions, type: string | null, ...messages: Array) { + return log(opts, 'debug', type, ...messages); +} + +/** Emit a general info message (be careful using this too much!) */ +export function info(opts: LogOptions, type: string | null, ...messages: Array) { + return log(opts, 'info', type, ...messages); +} + +/** Emit a warning a user should be aware of */ +export function warn(opts: LogOptions, type: string | null, ...messages: Array) { + return log(opts, 'warn', type, ...messages); +} + +/** Emit a fatal error message the user should address. */ +export function error(opts: LogOptions, type: string | null, ...messages: Array) { + return log(opts, 'error', type, ...messages); +} + +// A default logger for when too lazy to pass LogOptions around. +export const logger = { + debug: debug.bind(null, defaultLogOptions, 'debug'), + info: info.bind(null, defaultLogOptions, 'info'), + warn: warn.bind(null, defaultLogOptions, 'warn'), + error: error.bind(null, defaultLogOptions, 'error'), +}; \ No newline at end of file From 964bc5fc941a6ccc6ea830b9b72e5c013475bcd0 Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 09:26:30 +0100 Subject: [PATCH 2/7] Tell user to use the verbose flag when encountering the MISSING_REF error --- packages/create-astro/src/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index 4e44d26edfac..e1d89edd860e 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -124,7 +124,7 @@ export async function main() { // Helpful message when encountering the "could not find commit hash for ..." error if (err.code === 'MISSING_REF') { console.log(yellow("This seems to be an issue with degit. Please check if you have 'git' installed on your system, and install it if you don't have (https://git-scm.com).")); - console.log(yellow("If you do have 'git' installed, please file a new issue here: https://github.com/withastro/astro/issues")); + console.log(yellow("If you do have 'git' installed, please run this command with the --verbose flag and file a new issue with the command output here: https://github.com/withastro/astro/issues")); } process.exit(1); } From fcc9b0392f242248f2e4c2e9fce28ab7a542b6e8 Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 09:29:03 +0100 Subject: [PATCH 3/7] Create changeset --- .changeset/gentle-cats-guess.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/gentle-cats-guess.md diff --git a/.changeset/gentle-cats-guess.md b/.changeset/gentle-cats-guess.md new file mode 100644 index 000000000000..a6f7d3aa6339 --- /dev/null +++ b/.changeset/gentle-cats-guess.md @@ -0,0 +1,5 @@ +--- +'create-astro': patch +--- + +Added an option to create-astro to use verbose logging which should help debug degit issues From f5ffea2ff2e56b255eb1eded088e640a524e70a5 Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 15:31:56 +0100 Subject: [PATCH 4/7] Add information in README --- packages/create-astro/README.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/create-astro/README.md b/packages/create-astro/README.md index 5709fa426801..80a0da093ed9 100644 --- a/packages/create-astro/README.md +++ b/packages/create-astro/README.md @@ -43,4 +43,19 @@ May be provided in place of prompts | `--template` | Specify the template name ([list][examples]) | | `--commit` | Specify a specific Git commit or branch to use from this repo (by default, `main` branch of this repo will be used) | +### Debugging + +To debug `create-astro`, you can use the `--verbose` flag which will log the output of degit and some more information about the command, this can be useful when you encounter an error and want to report it. + +```bash +# npm 6.x +npm init astro my-astro-project --verbose + +# npm 7+, extra double-dash is needed: +npm init astro my-astro-project -- --verbose + +# yarn +yarn create astro my-astro-project --verbose +``` + [examples]: https://github.com/withastro/astro/tree/main/examples From 5e98dc107196dbaa52819df2e427be992a6f32a3 Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 15:36:47 +0100 Subject: [PATCH 5/7] Format --- packages/create-astro/src/index.ts | 18 ++++++++++++------ packages/create-astro/src/logger.ts | 8 ++++---- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/packages/create-astro/src/index.ts b/packages/create-astro/src/index.ts index e1d89edd860e..06f8f5b1fb6e 100644 --- a/packages/create-astro/src/index.ts +++ b/packages/create-astro/src/index.ts @@ -32,7 +32,7 @@ const { version } = JSON.parse(fs.readFileSync(new URL('../package.json', import const POSTPROCESS_FILES = ['package.json', 'astro.config.mjs', 'CHANGELOG.md']; // some files need processing after copying. export async function main() { - logger.debug("Verbose logging turned on") + logger.debug('Verbose logging turned on'); console.log(`\n${bold('Welcome to Astro!')} ${gray(`(create-astro v${version})`)}`); console.log(`If you encounter a problem, visit ${cyan('https://github.com/withastro/astro/issues')} to search or file a new issue.\n`); @@ -80,11 +80,11 @@ export async function main() { verbose: defaultLogLevel === 'debug' ? true : false, }); - logger.debug('Initialized degit with following config:',`${templateTarget}${hash}`, { + logger.debug('Initialized degit with following config:', `${templateTarget}${hash}`, { cache: false, force: true, verbose: defaultLogLevel === 'debug' ? true : false, - }) + }); const selectedTemplate = TEMPLATES.find((template) => template.value === options.template); let renderers: string[] = []; @@ -107,12 +107,14 @@ export async function main() { // Copy try { - emitter.on('info', info => { logger.debug(info.message) }); + emitter.on('info', (info) => { + logger.debug(info.message); + }); console.log(`${green(`>`)} ${gray(`Copying project files...`)}`); await emitter.clone(cwd); } catch (err: any) { // degit is compiled, so the stacktrace is pretty noisy. Only report the stacktrace when using verbose mode. - logger.debug(err) + logger.debug(err); console.error(red(err.message)); // Warning for issue #655 @@ -124,7 +126,11 @@ export async function main() { // Helpful message when encountering the "could not find commit hash for ..." error if (err.code === 'MISSING_REF') { console.log(yellow("This seems to be an issue with degit. Please check if you have 'git' installed on your system, and install it if you don't have (https://git-scm.com).")); - console.log(yellow("If you do have 'git' installed, please run this command with the --verbose flag and file a new issue with the command output here: https://github.com/withastro/astro/issues")); + console.log( + yellow( + "If you do have 'git' installed, please run this command with the --verbose flag and file a new issue with the command output here: https://github.com/withastro/astro/issues" + ) + ); } process.exit(1); } diff --git a/packages/create-astro/src/logger.ts b/packages/create-astro/src/logger.ts index 6c5aac5590e1..f52cdb1ac13a 100644 --- a/packages/create-astro/src/logger.ts +++ b/packages/create-astro/src/logger.ts @@ -61,11 +61,11 @@ export type LoggerEvent = 'debug' | 'info' | 'warn' | 'error'; export let defaultLogLevel: LoggerLevel; if (process.argv.includes('--verbose')) { - defaultLogLevel = 'debug'; + defaultLogLevel = 'debug'; } else if (process.argv.includes('--silent')) { - defaultLogLevel = 'silent'; + defaultLogLevel = 'silent'; } else { - defaultLogLevel = 'info'; + defaultLogLevel = 'info'; } export interface LogOptions { @@ -138,4 +138,4 @@ export const logger = { info: info.bind(null, defaultLogOptions, 'info'), warn: warn.bind(null, defaultLogOptions, 'warn'), error: error.bind(null, defaultLogOptions, 'error'), -}; \ No newline at end of file +}; From ce088226513c04cb6f432fc83bda050775f2c323 Mon Sep 17 00:00:00 2001 From: Mikkel-T Date: Thu, 20 Jan 2022 20:25:53 +0100 Subject: [PATCH 6/7] Use switch statement instead of if and if else blocks --- packages/create-astro/src/logger.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/create-astro/src/logger.ts b/packages/create-astro/src/logger.ts index f52cdb1ac13a..acb79b636608 100644 --- a/packages/create-astro/src/logger.ts +++ b/packages/create-astro/src/logger.ts @@ -34,12 +34,16 @@ export const defaultLogDestination = new Writable({ let type = event.type; if (type) { - if (event.level === 'info') { - type = bold(blue(type)); - } else if (event.level === 'warn') { - type = bold(yellow(type)); - } else if (event.level === 'error') { - type = bold(red(type)); + switch (event.level) { + case 'info': + type = bold(blue(type)); + break; + case 'warn': + type = bold(yellow(type)); + break; + case 'error': + type = bold(red(type)); + break; } dest.write(`[${type}] `); From d1053fd2e2e622aa208d36fbbecb153d6b75dd25 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mikkel=20T=C3=B8nder?= <71938724+Mikkel-T@users.noreply.github.com> Date: Thu, 20 Jan 2022 20:29:36 +0100 Subject: [PATCH 7/7] Update packages/create-astro/src/logger.ts Make if statement easier to read Co-authored-by: Evan Boehs --- packages/create-astro/src/logger.ts | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/create-astro/src/logger.ts b/packages/create-astro/src/logger.ts index acb79b636608..97be7af0a220 100644 --- a/packages/create-astro/src/logger.ts +++ b/packages/create-astro/src/logger.ts @@ -26,9 +26,7 @@ export const defaultLogDestination = new Writable({ objectMode: true, write(event: LogMessage, _, callback) { let dest: ConsoleStream = process.stderr; - if (levels[event.level] < levels['error']) { - dest = process.stdout; - } + if (levels[event.level] < levels['error']) dest = process.stdout; dest.write(dim(dt.format(new Date()) + ' '));