Skip to content

Commit

Permalink
update logging
Browse files Browse the repository at this point in the history
  • Loading branch information
FredKSchott committed Oct 16, 2023
1 parent 7c45851 commit e6d981e
Show file tree
Hide file tree
Showing 36 changed files with 418 additions and 462 deletions.
12 changes: 6 additions & 6 deletions packages/astro/src/cli/telemetry/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,23 @@
/* eslint-disable no-console */
import whichPm from 'which-pm';
import type yargs from 'yargs-parser';
import * as msg from '../../core/messages.js';
import { telemetry } from '../../events/index.js';
import { createLoggerFromFlags } from '../flags.js';

interface TelemetryOptions {
flags: yargs.Arguments;
}

export async function notify() {
const packageManager = (await whichPm(process.cwd()))?.name ?? 'npm';
await telemetry.notify(() => {
console.log(msg.telemetryNotice(packageManager) + '\n');
console.log(msg.telemetryNotice() + '\n');
return true;
});
}

export async function update(subcommand: string, { flags }: TelemetryOptions) {
const isValid = ['enable', 'disable', 'reset'].includes(subcommand);
const logger = createLoggerFromFlags(flags);

if (flags.help || flags.h || !isValid) {
msg.printHelp({
Expand All @@ -37,17 +37,17 @@ export async function update(subcommand: string, { flags }: TelemetryOptions) {
switch (subcommand) {
case 'enable': {
telemetry.setEnabled(true);
console.log(msg.telemetryEnabled());
logger.info('SKIP_FORMAT', msg.telemetryEnabled());
return;
}
case 'disable': {
telemetry.setEnabled(false);
console.log(msg.telemetryDisabled());
logger.info('SKIP_FORMAT', msg.telemetryDisabled());
return;
}
case 'reset': {
telemetry.clear();
console.log(msg.telemetryReset());
logger.info('SKIP_FORMAT', msg.telemetryReset());
return;
}
}
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/cli/throw-and-exit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { collectErrorMetadata } from '../core/errors/dev/index.js';
import { isAstroConfigZodError } from '../core/errors/errors.js';
import { createSafeError } from '../core/errors/index.js';
import { debug } from '../core/logger/core.js';
import { formatErrorMessage } from '../core/messages.js';
import { formatDetailedErrorMessage } from '../core/messages.js';
import { eventError, telemetry } from '../events/index.js';

/** Display error and exit */
Expand All @@ -20,7 +20,7 @@ export async function throwAndExit(cmd: string, err: unknown) {

const errorWithMetadata = collectErrorMetadata(createSafeError(err));
telemetryPromise = telemetry.record(eventError({ cmd, err: errorWithMetadata, isFatal: true }));
errorMessage = formatErrorMessage(errorWithMetadata);
errorMessage = formatDetailedErrorMessage(errorWithMetadata);

// Timeout the error reporter (very short) because the user is waiting.
// NOTE(fks): It is better that we miss some events vs. holding too long.
Expand Down
14 changes: 7 additions & 7 deletions packages/astro/src/content/server-listeners.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { bold, cyan } from 'kleur/colors';
import { bold, cyan, underline } from 'kleur/colors';
import type fsMod from 'node:fs';
import path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -26,7 +26,7 @@ export async function attachContentServerListeners({
const contentPaths = getContentPaths(settings.config, fs);

if (fs.existsSync(contentPaths.contentDir)) {
logger.info(
logger.debug(
'content',
`Watching ${cyan(
contentPaths.contentDir.href.replace(settings.config.root.href, '')
Expand All @@ -39,7 +39,7 @@ export async function attachContentServerListeners({
viteServer.watcher.on('addDir', contentDirListener);
async function contentDirListener(dir: string) {
if (appendForwardSlash(pathToFileURL(dir).href) === contentPaths.contentDir.href) {
logger.info('content', `Content dir found. Watching for changes`);
logger.debug('content', `Content dir found. Watching for changes`);
await attachListeners();
viteServer.watcher.removeListener('addDir', contentDirListener);
}
Expand All @@ -55,7 +55,7 @@ export async function attachContentServerListeners({
contentConfigObserver: globalContentConfigObserver,
});
await contentGenerator.init();
logger.info('content', 'Types generated');
logger.debug('content', 'Types generated');

viteServer.watcher.on('add', (entry) => {
contentGenerator.queueEvent({ name: 'add', entry });
Expand Down Expand Up @@ -90,9 +90,9 @@ function warnAllowJsIsFalse({
'true'
)} in your ${bold(tsConfigFileName)} file to have autocompletion in your ${bold(
contentConfigFileName
)} file.
See ${bold('https://www.typescriptlang.org/tsconfig#allowJs')} for more information.
`
)} file. See ${underline(
cyan('https://www.typescriptlang.org/tsconfig#allowJs')
)} for more information.`
);
}

Expand Down
93 changes: 33 additions & 60 deletions packages/astro/src/content/types-generator.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import glob from 'fast-glob';
import { cyan } from 'kleur/colors';
import { bold, cyan } from 'kleur/colors';
import type fsMod from 'node:fs';
import * as path from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
Expand Down Expand Up @@ -56,13 +56,6 @@ type CreateContentGeneratorParams = {
fs: typeof fsMod;
};

type EventOpts = { logLevel: 'info' | 'warn' };

type EventWithOptions = {
type: ContentEvent;
opts: EventOpts | undefined;
};

class UnsupportedFileTypeError extends Error {}

export async function createContentTypesGenerator({
Expand All @@ -78,7 +71,7 @@ export async function createContentTypesGenerator({
const contentEntryExts = [...contentEntryConfigByExt.keys()];
const dataEntryExts = getDataEntryExts(settings);

let events: EventWithOptions[] = [];
let events: ContentEvent[] = [];
let debounceTimeout: NodeJS.Timeout | undefined;

const typeTemplateContent = await fs.promises.readFile(contentPaths.typesTemplate, 'utf-8');
Expand All @@ -90,10 +83,7 @@ export async function createContentTypesGenerator({
return { typesGenerated: false, reason: 'no-content-dir' };
}

events.push({
type: { name: 'add', entry: contentPaths.config.url },
opts: { logLevel: 'warn' },
});
events.push({ name: 'add', entry: contentPaths.config.url });

const globResult = await glob('**', {
cwd: fileURLToPath(contentPaths.contentDir),
Expand All @@ -110,24 +100,18 @@ export async function createContentTypesGenerator({
const entryURL = pathToFileURL(fullPath);
if (entryURL.href.startsWith(contentPaths.config.url.href)) continue;
if (entry.dirent.isFile()) {
events.push({
type: { name: 'add', entry: entryURL },
opts: { logLevel: 'warn' },
});
events.push({ name: 'add', entry: entryURL });
} else if (entry.dirent.isDirectory()) {
events.push({ type: { name: 'addDir', entry: entryURL }, opts: { logLevel: 'warn' } });
events.push({ name: 'addDir', entry: entryURL });
}
}
await runEvents();
return { typesGenerated: true };
}

async function handleEvent(
event: ContentEvent,
opts?: EventOpts
event: ContentEvent
): Promise<{ shouldGenerateTypes: boolean; error?: Error }> {
const logLevel = opts?.logLevel ?? 'info';

if (event.name === 'addDir' || event.name === 'unlinkDir') {
const collection = normalizePath(
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry))
Expand All @@ -140,9 +124,7 @@ export async function createContentTypesGenerator({
switch (event.name) {
case 'addDir':
collectionEntryMap[JSON.stringify(collection)] = { type: 'unknown', entries: {} };
if (logLevel === 'info') {
logger.info('content', `${cyan(collection)} collection added`);
}
logger.debug('content', `${cyan(collection)} collection added`);
break;
case 'unlinkDir':
if (collectionKey in collectionEntryMap) {
Expand Down Expand Up @@ -186,16 +168,14 @@ export async function createContentTypesGenerator({

const collection = getEntryCollectionName({ entry, contentDir });
if (collection === undefined) {
if (['info', 'warn'].includes(logLevel)) {
logger.warn(
'content',
`${cyan(
normalizePath(
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry))
)
)} must be nested in a collection directory. Skipping.`
);
}
logger.warn(
'content',
`${bold(
normalizePath(
path.relative(fileURLToPath(contentPaths.contentDir), fileURLToPath(event.entry))
)
)} must live in a ${bold('content/...')} collection subdirectory.`
);
return { shouldGenerateTypes: false };
}

Expand Down Expand Up @@ -308,22 +288,19 @@ export async function createContentTypesGenerator({
}
}

function queueEvent(rawEvent: RawContentEvent, opts?: EventOpts) {
function queueEvent(rawEvent: RawContentEvent) {
const event = {
type: {
entry: pathToFileURL(rawEvent.entry),
name: rawEvent.name,
},
opts,
entry: pathToFileURL(rawEvent.entry),
name: rawEvent.name,
};
if (!event.type.entry.pathname.startsWith(contentPaths.contentDir.pathname)) return;
if (!event.entry.pathname.startsWith(contentPaths.contentDir.pathname)) return;

events.push(event);

debounceTimeout && clearTimeout(debounceTimeout);
const runEventsSafe = async () => {
try {
await runEvents(opts);
await runEvents();
} catch {
// Prevent frontmatter errors from crashing the server. The errors
// are still reported on page reflects as desired.
Expand All @@ -333,30 +310,25 @@ export async function createContentTypesGenerator({
debounceTimeout = setTimeout(runEventsSafe, 50 /* debounce to batch chokidar events */);
}

async function runEvents(opts?: EventOpts) {
const logLevel = opts?.logLevel ?? 'info';
async function runEvents() {
const eventResponses = [];

for (const event of events) {
const response = await handleEvent(event.type, event.opts);
const response = await handleEvent(event);
eventResponses.push(response);
}

events = [];
let unsupportedFiles = [];
for (const response of eventResponses) {
if (response.error instanceof UnsupportedFileTypeError) {
unsupportedFiles.push(response.error.message);
logger.warn(
'content',
`Unsupported file type ${bold(
response.error.message
)} found. Prefix filename with an underscore (\`_\`) to ignore.`
);
}
}
if (unsupportedFiles.length > 0 && ['info', 'warn'].includes(logLevel)) {
logger.warn(
'content',
`Unsupported file types found. Prefix with an underscore (\`_\`) to ignore:\n- ${unsupportedFiles.join(
'\n'
)}`
);
}
const observable = contentConfigObserver.get();
if (eventResponses.some((r) => r.shouldGenerateTypes)) {
await writeContentFiles({
Expand All @@ -369,7 +341,7 @@ export async function createContentTypesGenerator({
viteServer,
});
invalidateVirtualMod(viteServer);
if (observable.status === 'loaded' && ['info', 'warn'].includes(logLevel)) {
if (observable.status === 'loaded') {
warnNonexistentCollections({
logger,
contentConfig: observable.config,
Expand Down Expand Up @@ -475,6 +447,7 @@ async function writeContentFiles({
let configPathRelativeToCacheDir = normalizePath(
path.relative(contentPaths.cacheDir.pathname, contentPaths.config.url.pathname)
);

if (!isRelativePath(configPathRelativeToCacheDir))
configPathRelativeToCacheDir = './' + configPathRelativeToCacheDir;

Expand Down Expand Up @@ -514,9 +487,9 @@ function warnNonexistentCollections({
if (!collectionEntryMap[JSON.stringify(configuredCollection)]) {
logger.warn(
'content',
`The ${JSON.stringify(
configuredCollection
)} collection does not have an associated folder in your \`content\` directory. Make sure the folder exists, or check your content config for typos.`
`The ${bold(configuredCollection)} collection is defined but no ${bold(
'content/' + configuredCollection
)} folder exists in the content directory. Create a new folder for the collection, or check your content configuration file for typos.`
);
}
}
Expand Down
Loading

0 comments on commit e6d981e

Please sign in to comment.