Skip to content

Commit 7b0cb85

Browse files
ascorbicdelucis
andauthored
fix: better logs for invalid content config (#12798)
Co-authored-by: Chris Swithinbank <[email protected]>
1 parent 5f4c543 commit 7b0cb85

File tree

6 files changed

+69
-4
lines changed

6 files changed

+69
-4
lines changed

.changeset/afraid-sloths-shake.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'astro': patch
3+
---
4+
5+
Improves warning logs for invalid content collection configuration

packages/astro/src/content/content-layer.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,15 @@ export class ContentLayer {
138138
async #doSync(options: RefreshContentOptions) {
139139
const contentConfig = globalContentConfigObserver.get();
140140
const logger = this.#logger.forkIntegrationLogger('content');
141+
142+
if (contentConfig?.status === 'error') {
143+
logger.error(`Error loading content config. Skipping sync.\n${contentConfig.error.message}`);
144+
return;
145+
}
146+
147+
// It shows as loaded with no collections even if there's no config
141148
if (contentConfig?.status !== 'loaded') {
142-
logger.debug('Content config not loaded, skipping sync');
149+
logger.error('Content config not loaded, skipping sync');
143150
return;
144151
}
145152

packages/astro/src/content/loaders/glob.ts

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { promises as fs } from 'node:fs';
1+
import { promises as fs, existsSync } from 'node:fs';
2+
import { relative } from 'node:path';
23
import { fileURLToPath, pathToFileURL } from 'node:url';
34
import fastGlob from 'fast-glob';
45
import { bold, green } from 'kleur/colors';
@@ -215,10 +216,27 @@ export function glob(globOptions: GlobOptions): Loader {
215216
baseDir.pathname = `${baseDir.pathname}/`;
216217
}
217218

219+
const filePath = fileURLToPath(baseDir);
220+
const relativePath = relative(fileURLToPath(config.root), filePath);
221+
222+
const exists = existsSync(baseDir);
223+
224+
if (!exists) {
225+
// We warn and don't return because we will still set up the watcher in case the directory is created later
226+
logger.warn(`The base directory "${fileURLToPath(baseDir)}" does not exist.`);
227+
}
228+
218229
const files = await fastGlob(globOptions.pattern, {
219230
cwd: fileURLToPath(baseDir),
220231
});
221232

233+
if (exists && files.length === 0) {
234+
logger.warn(
235+
`No files found matching "${globOptions.pattern}" in directory "${relativePath}"`,
236+
);
237+
return;
238+
}
239+
222240
function configForFile(file: string) {
223241
const ext = file.split('.').at(-1);
224242
if (!ext) {

packages/astro/src/content/runtime.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@ export function createGetCollection({
111111
console.warn(
112112
`The collection ${JSON.stringify(
113113
collection,
114-
)} does not exist or is empty. Ensure a collection directory with this name exists.`,
114+
)} does not exist or is empty. Please check your content config file for errors.`,
115115
);
116116
return [];
117117
}

packages/astro/test/content-layer.test.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,11 @@ import assert from 'node:assert/strict';
22
import { promises as fs, existsSync } from 'node:fs';
33
import { sep } from 'node:path';
44
import { sep as posixSep } from 'node:path/posix';
5+
import { Writable } from 'node:stream';
56
import { after, before, describe, it } from 'node:test';
67
import * as cheerio from 'cheerio';
78
import * as devalue from 'devalue';
9+
import { Logger } from '../dist/core/logger/core.js';
810

911
import { loadFixture } from './test-utils.js';
1012
describe('Content Layer', () => {
@@ -316,8 +318,21 @@ describe('Content Layer', () => {
316318
describe('Dev', () => {
317319
let devServer;
318320
let json;
321+
const logs = [];
319322
before(async () => {
320-
devServer = await fixture.startDevServer({ force: true });
323+
devServer = await fixture.startDevServer({
324+
force: true,
325+
logger: new Logger({
326+
level: 'warn',
327+
dest: new Writable({
328+
objectMode: true,
329+
write(event, _, callback) {
330+
logs.push(event);
331+
callback();
332+
},
333+
}),
334+
}),
335+
});
321336
// Vite may not have noticed the saved data store yet. Wait a little just in case.
322337
await fixture.onNextDataStoreChange(1000).catch(() => {
323338
// Ignore timeout, because it may have saved before we get here.
@@ -331,6 +346,16 @@ describe('Content Layer', () => {
331346
devServer?.stop();
332347
});
333348

349+
it("warns about missing directory in glob() loader's path", async () => {
350+
assert.ok(logs.find((log) => log.level === 'warn' && log.message.includes('does not exist')));
351+
});
352+
353+
it("warns about missing files in glob() loader's path", async () => {
354+
assert.ok(
355+
logs.find((log) => log.level === 'warn' && log.message.includes('No files found matching')),
356+
);
357+
});
358+
334359
it('Generates content types files', async () => {
335360
assert.ok(existsSync(new URL('./.astro/content.d.ts', fixture.config.root)));
336361
const data = await fs.readFile(new URL('./.astro/types.d.ts', fixture.config.root), 'utf-8');

packages/astro/test/fixtures/content-layer/src/content.config.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,13 @@ const numbers = defineCollection({
177177
loader: glob({ pattern: 'src/data/glob-data/*', base: '.' }),
178178
});
179179

180+
const notADirectory = defineCollection({
181+
loader: glob({ pattern: '*', base: 'src/nonexistent' }),
182+
});
183+
184+
const nothingMatches = defineCollection({
185+
loader: glob({ pattern: 'nothingmatches/*', base: 'src/data' }),
186+
});
180187
const images = defineCollection({
181188
loader: () => [
182189
{
@@ -259,4 +266,7 @@ export const collections = {
259266
songs,
260267
probes,
261268
rodents,
269+
notADirectory,
270+
nothingMatches
262271
};
272+

0 commit comments

Comments
 (0)