0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2025-01-06 22:10:10 -05:00

db: scaffold db files when using astro add db (#10349)

* feat(add): scaffold db files

* refactor: no `recursive` needed
This commit is contained in:
Nate Moore 2024-03-07 13:50:23 -06:00 committed by GitHub
parent 988aad6705
commit 7001ae48db
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
3 changed files with 75 additions and 30 deletions

View file

@ -0,0 +1,5 @@
---
"astro": patch
---
Adds scaffolded files when running `astro add db`

View file

@ -49,26 +49,44 @@ const ALIASES = new Map([
['solid', 'solid-js'], ['solid', 'solid-js'],
['tailwindcss', 'tailwind'], ['tailwindcss', 'tailwind'],
]); ]);
const ASTRO_CONFIG_STUB = `import { defineConfig } from 'astro/config';\n\nexport default defineConfig({});`;
const TAILWIND_CONFIG_STUB = `/** @type {import('tailwindcss').Config} */ const STUBS = {
ASTRO_CONFIG: `import { defineConfig } from 'astro/config';\n// https://astro.build/config\nexport default defineConfig({});`,
TAILWIND_CONFIG: `/** @type {import('tailwindcss').Config} */
export default { export default {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'], content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
theme: { theme: {
extend: {}, extend: {},
}, },
plugins: [], plugins: [],
}\n`; }\n`,
const SVELTE_CONFIG_STUB = `\ SVELTE_CONFIG: `\
import { vitePreprocess } from '@astrojs/svelte'; import { vitePreprocess } from '@astrojs/svelte';
export default { export default {
preprocess: vitePreprocess(), preprocess: vitePreprocess(),
}; }\n`,
`; LIT_NPMRC: `\
const LIT_NPMRC_STUB = `\
# Lit libraries are required to be hoisted due to dependency issues. # Lit libraries are required to be hoisted due to dependency issues.
public-hoist-pattern[]=*lit* public-hoist-pattern[]=*lit*
`; `,
DB_CONFIG: `\
import { defineDB } from 'astro:db';
// https://astro.build/db/config
export default defineDB({
tables: {}
});
`,
DB_SEED: `\
import { db } from 'astro:db';
// https://astro.build/db/seed
export default async function seed() {
// TODO
}
`
}
const OFFICIAL_ADAPTER_TO_IMPORT_MAP: Record<string, string> = { const OFFICIAL_ADAPTER_TO_IMPORT_MAP: Record<string, string> = {
netlify: '@astrojs/netlify', netlify: '@astrojs/netlify',
@ -172,7 +190,7 @@ export async function add(names: string[], { flags }: AddOptions) {
'./tailwind.config.js', './tailwind.config.js',
], ],
defaultConfigFile: './tailwind.config.mjs', defaultConfigFile: './tailwind.config.mjs',
defaultConfigContent: TAILWIND_CONFIG_STUB, defaultConfigContent: STUBS.TAILWIND_CONFIG,
}); });
} }
if (integrations.find((integration) => integration.id === 'svelte')) { if (integrations.find((integration) => integration.id === 'svelte')) {
@ -183,9 +201,32 @@ export async function add(names: string[], { flags }: AddOptions) {
integrationName: 'Svelte', integrationName: 'Svelte',
possibleConfigFiles: ['./svelte.config.js', './svelte.config.cjs', './svelte.config.mjs'], possibleConfigFiles: ['./svelte.config.js', './svelte.config.cjs', './svelte.config.mjs'],
defaultConfigFile: './svelte.config.js', defaultConfigFile: './svelte.config.js',
defaultConfigContent: SVELTE_CONFIG_STUB, defaultConfigContent: STUBS.SVELTE_CONFIG,
}); });
} }
if (integrations.find((integration) => integration.id === 'db')) {
if (!existsSync(new URL('./db/', root))) {
logger.info(
'SKIP_FORMAT',
`\n ${magenta(`Astro will scaffold ${green('./db/config.ts')}${magenta(' and ')}${green('./db/seed.ts')}${magenta(' files.')}`)}\n`
);
if (await askToContinue({ flags })) {
await fs.mkdir(new URL('./db', root));
await Promise.all([
fs.writeFile(new URL('./db/config.ts', root), STUBS.DB_CONFIG, { encoding: 'utf-8' }),
fs.writeFile(new URL('./db/seed.ts', root), STUBS.DB_SEED, { encoding: 'utf-8' }),
])
} else {
logger.info(
'SKIP_FORMAT',
`\n Astro DB requires additional configuration. Please refer to https://astro.build/db/config`
);
}
} else {
logger.debug('add', `Using existing db configuration`);
}
}
// Some lit dependencies needs to be hoisted, so for strict package managers like pnpm, // Some lit dependencies needs to be hoisted, so for strict package managers like pnpm,
// we add an .npmrc to hoist them // we add an .npmrc to hoist them
if ( if (
@ -199,14 +240,14 @@ export async function add(names: string[], { flags }: AddOptions) {
integrationName: 'Lit', integrationName: 'Lit',
possibleConfigFiles: ['./.npmrc'], possibleConfigFiles: ['./.npmrc'],
defaultConfigFile: './.npmrc', defaultConfigFile: './.npmrc',
defaultConfigContent: LIT_NPMRC_STUB, defaultConfigContent: STUBS.LIT_NPMRC,
}); });
} }
break; break;
} }
case UpdateResult.cancelled: { case UpdateResult.cancelled: {
logger.info( logger.info(
null, 'SKIP_FORMAT',
msg.cancelled( msg.cancelled(
`Dependencies ${bold('NOT')} installed.`, `Dependencies ${bold('NOT')} installed.`,
`Be sure to install them manually before continuing!` `Be sure to install them manually before continuing!`
@ -233,7 +274,7 @@ export async function add(names: string[], { flags }: AddOptions) {
} else { } else {
logger.info('add', `Unable to locate a config file, generating one for you.`); logger.info('add', `Unable to locate a config file, generating one for you.`);
configURL = new URL('./astro.config.mjs', root); configURL = new URL('./astro.config.mjs', root);
await fs.writeFile(fileURLToPath(configURL), ASTRO_CONFIG_STUB, { encoding: 'utf-8' }); await fs.writeFile(fileURLToPath(configURL), STUBS.ASTRO_CONFIG, { encoding: 'utf-8' });
} }
let ast: t.File | null = null; let ast: t.File | null = null;
@ -261,7 +302,7 @@ export async function add(names: string[], { flags }: AddOptions) {
await setAdapter(ast, integration, officialExportName); await setAdapter(ast, integration, officialExportName);
} else { } else {
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta( `\n ${magenta(
`Check our deployment docs for ${bold( `Check our deployment docs for ${bold(
integration.packageName integration.packageName
@ -298,7 +339,7 @@ export async function add(names: string[], { flags }: AddOptions) {
switch (configResult) { switch (configResult) {
case UpdateResult.cancelled: { case UpdateResult.cancelled: {
logger.info(null, msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`)); logger.info('SKIP_FORMAT', msg.cancelled(`Your configuration has ${bold('NOT')} been updated.`));
break; break;
} }
case UpdateResult.none: { case UpdateResult.none: {
@ -312,21 +353,20 @@ export async function add(names: string[], { flags }: AddOptions) {
(integration) => !deps.includes(integration.packageName) (integration) => !deps.includes(integration.packageName)
); );
if (missingDeps.length === 0) { if (missingDeps.length === 0) {
logger.info(null, msg.success(`Configuration up-to-date.`)); logger.info('SKIP_FORMAT', msg.success(`Configuration up-to-date.`));
break; break;
} }
} }
logger.info(null, msg.success(`Configuration up-to-date.`)); logger.info('SKIP_FORMAT', msg.success(`Configuration up-to-date.`));
break; break;
} }
default: { default: {
const list = integrations.map((integration) => ` - ${integration.packageName}`).join('\n'); const list = integrations.map((integration) => ` - ${integration.packageName}`).join('\n');
logger.info( logger.info(
null, 'SKIP_FORMAT',
msg.success( msg.success(
`Added the following integration${ `Added the following integration${integrations.length === 1 ? '' : 's'
integrations.length === 1 ? '' : 's'
} to your project:\n${list}` } to your project:\n${list}`
) )
); );
@ -341,7 +381,7 @@ export async function add(names: string[], { flags }: AddOptions) {
} }
case UpdateResult.cancelled: { case UpdateResult.cancelled: {
logger.info( logger.info(
null, 'SKIP_FORMAT',
msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`) msg.cancelled(`Your TypeScript configuration has ${bold('NOT')} been updated.`)
); );
break; break;
@ -352,7 +392,7 @@ export async function add(names: string[], { flags }: AddOptions) {
); );
} }
default: default:
logger.info(null, msg.success(`Successfully updated TypeScript settings`)); logger.info('SKIP_FORMAT', msg.success(`Successfully updated TypeScript settings`));
} }
} }
@ -580,13 +620,13 @@ async function updateAstroConfig({
})}\n`; })}\n`;
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta('Astro will make the following changes to your config file:')}\n${message}` `\n ${magenta('Astro will make the following changes to your config file:')}\n${message}`
); );
if (logAdapterInstructions) { if (logAdapterInstructions) {
logger.info( logger.info(
null, 'SKIP_FORMAT',
magenta( magenta(
` For complete deployment options, visit\n ${bold( ` For complete deployment options, visit\n ${bold(
'https://docs.astro.build/en/guides/deploy/' 'https://docs.astro.build/en/guides/deploy/'
@ -718,7 +758,7 @@ async function tryToInstallIntegrations({
borderStyle: 'round', borderStyle: 'round',
})}\n`; })}\n`;
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta('Astro will run the following command:')}\n ${dim( `\n ${magenta('Astro will run the following command:')}\n ${dim(
'If you skip this step, you can always run it yourself later' 'If you skip this step, you can always run it yourself later'
)}\n${message}` )}\n${message}`
@ -950,7 +990,7 @@ async function updateTSConfig(
})}\n`; })}\n`;
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}` `\n ${magenta(`Astro will make the following changes to your ${configFileName}:`)}\n${message}`
); );
@ -964,7 +1004,7 @@ async function updateTSConfig(
if (hasConflictingIntegrations) { if (hasConflictingIntegrations) {
logger.info( logger.info(
null, 'SKIP_FORMAT',
red( red(
` ${bold( ` ${bold(
'Caution:' 'Caution:'
@ -1063,7 +1103,7 @@ async function setupIntegrationConfig(opts: {
} }
if (!alreadyConfigured) { if (!alreadyConfigured) {
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}\n` `\n ${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}\n`
); );
if (await askToContinue({ flags: opts.flags })) { if (await askToContinue({ flags: opts.flags })) {

View file

@ -38,7 +38,7 @@ export async function getPackage<T>(
return packageImport as T; return packageImport as T;
} catch (e) { } catch (e) {
logger.info( logger.info(
null, 'SKIP_FORMAT',
`To continue, Astro requires the following dependency to be installed: ${bold(packageName)}.` `To continue, Astro requires the following dependency to be installed: ${bold(packageName)}.`
); );
const result = await installPackage([packageName, ...otherDeps], options, logger); const result = await installPackage([packageName, ...otherDeps], options, logger);
@ -108,7 +108,7 @@ async function installPackage(
borderStyle: 'round', borderStyle: 'round',
})}\n`; })}\n`;
logger.info( logger.info(
null, 'SKIP_FORMAT',
`\n ${magenta('Astro will run the following command:')}\n ${dim( `\n ${magenta('Astro will run the following command:')}\n ${dim(
'If you skip this step, you can always run it yourself later' 'If you skip this step, you can always run it yourself later'
)}\n${message}` )}\n${message}`