[ci] format

This commit is contained in:
matthewp 2022-11-03 12:07:39 +00:00 committed by fredkbot
parent 126cd8e83f
commit 50e5e576bc
7 changed files with 60 additions and 76 deletions

View file

@ -1,7 +1,6 @@
/* eslint-disable no-console */ /* eslint-disable no-console */
import * as colors from 'kleur/colors'; import * as colors from 'kleur/colors';
import { pathToFileURL } from 'url'; import { pathToFileURL } from 'url';
import { normalizePath } from 'vite';
import type { Arguments as Flags } from 'yargs-parser'; import type { Arguments as Flags } from 'yargs-parser';
import yargs from 'yargs-parser'; import yargs from 'yargs-parser';
import { z } from 'zod'; import { z } from 'zod';
@ -12,7 +11,6 @@ import {
openConfig, openConfig,
resolveConfigPath, resolveConfigPath,
resolveFlags, resolveFlags,
resolveRoot,
} from '../core/config/index.js'; } from '../core/config/index.js';
import { ASTRO_VERSION } from '../core/constants.js'; import { ASTRO_VERSION } from '../core/constants.js';
import devServer from '../core/dev/index.js'; import devServer from '../core/dev/index.js';
@ -21,7 +19,6 @@ import { createSafeError } from '../core/errors/index.js';
import { debug, error, info, LogOptions } from '../core/logger/core.js'; import { debug, error, info, LogOptions } from '../core/logger/core.js';
import { enableVerboseLogging, nodeLogDestination } from '../core/logger/node.js'; import { enableVerboseLogging, nodeLogDestination } from '../core/logger/node.js';
import { formatConfigErrorMessage, formatErrorMessage, printHelp } from '../core/messages.js'; import { formatConfigErrorMessage, formatErrorMessage, printHelp } from '../core/messages.js';
import { appendForwardSlash } from '../core/path.js';
import preview from '../core/preview/index.js'; import preview from '../core/preview/index.js';
import * as event from '../events/index.js'; import * as event from '../events/index.js';
import { eventConfigError, eventError, telemetry } from '../events/index.js'; import { eventConfigError, eventError, telemetry } from '../events/index.js';
@ -178,9 +175,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
switch (cmd) { switch (cmd) {
case 'dev': { case 'dev': {
const configFlag = resolveFlags(flags).config; const configFlag = resolveFlags(flags).config;
const configFlagPath = configFlag const configFlagPath = configFlag ? await resolveConfigPath({ cwd: root, flags }) : undefined;
? await resolveConfigPath({ cwd: root, flags })
: undefined;
await devServer(settings, { await devServer(settings, {
configFlag, configFlag,
@ -190,7 +185,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
handleConfigError(e) { handleConfigError(e) {
handleConfigError(e, { cwd: root, flags, logging }); handleConfigError(e, { cwd: root, flags, logging });
info(logging, 'astro', 'Continuing with previous valid configuration\n'); info(logging, 'astro', 'Continuing with previous valid configuration\n');
} },
}); });
return await new Promise(() => {}); // lives forever return await new Promise(() => {}); // lives forever
} }

View file

@ -106,7 +106,7 @@ export function resolveFlags(flags: Partial<Flags>): CLIFlags {
} }
export function resolveRoot(cwd?: string | URL): string { export function resolveRoot(cwd?: string | URL): string {
if(cwd instanceof URL) { if (cwd instanceof URL) {
cwd = fileURLToPath(cwd); cwd = fileURLToPath(cwd);
} }
return cwd ? path.resolve(cwd) : process.cwd(); return cwd ? path.resolve(cwd) : process.cwd();

View file

@ -7,15 +7,15 @@ import * as vite from 'vite';
import { import {
runHookConfigDone, runHookConfigDone,
runHookConfigSetup, runHookConfigSetup,
runHookServerDone,
runHookServerSetup, runHookServerSetup,
runHookServerStart, runHookServerStart,
runHookServerDone
} from '../../integrations/index.js'; } from '../../integrations/index.js';
import { createDefaultDevSettings, resolveRoot } from '../config/index.js'; import { createDefaultDevSettings, resolveRoot } from '../config/index.js';
import { createVite } from '../create-vite.js'; import { createVite } from '../create-vite.js';
import { LogOptions } from '../logger/core.js'; import { LogOptions } from '../logger/core.js';
import { appendForwardSlash } from '../path.js';
import { nodeLogDestination } from '../logger/node.js'; import { nodeLogDestination } from '../logger/node.js';
import { appendForwardSlash } from '../path.js';
import { apply as applyPolyfill } from '../polyfill.js'; import { apply as applyPolyfill } from '../polyfill.js';
const defaultLogging: LogOptions = { const defaultLogging: LogOptions = {
@ -108,17 +108,13 @@ export async function createContainer(params: CreateContainerParams = {}): Promi
// TODO deprecate and remove // TODO deprecate and remove
close() { close() {
return closeContainer(container); return closeContainer(container);
} },
}; };
return container; return container;
} }
async function closeContainer({ async function closeContainer({ viteServer, settings, logging }: Container) {
viteServer,
settings,
logging
}: Container) {
await viteServer.close(); await viteServer.close();
await runHookServerDone({ await runHookServerDone({
config: settings.config, config: settings.config,

View file

@ -1,6 +1,6 @@
import type { AstroTelemetry } from '@astrojs/telemetry'; import type { AstroTelemetry } from '@astrojs/telemetry';
import type { AddressInfo } from 'net';
import type http from 'http'; import type http from 'http';
import type { AddressInfo } from 'net';
import { performance } from 'perf_hooks'; import { performance } from 'perf_hooks';
import * as vite from 'vite'; import * as vite from 'vite';
import type { AstroSettings } from '../../@types/astro'; import type { AstroSettings } from '../../@types/astro';
@ -43,7 +43,7 @@ export default async function dev(
settings, settings,
logging: options.logging, logging: options.logging,
isRestart: options.isRestart, isRestart: options.isRestart,
} },
}); });
// Start listening to the port // Start listening to the port

View file

@ -1,9 +1,3 @@
export { export { createContainer, runInContainer, startContainer } from './container.js';
createContainer,
runInContainer,
startContainer
} from './container.js';
export {
createContainerWithAutomaticRestart
} from './restart.js';
export { default } from './dev.js'; export { default } from './dev.js';
export { createContainerWithAutomaticRestart } from './restart.js';

View file

@ -1,19 +1,16 @@
import type { AstroSettings } from '../../@types/astro';
import type { Container, CreateContainerParams } from './container';
import * as vite from 'vite'; import * as vite from 'vite';
import type { AstroSettings } from '../../@types/astro';
import { createSettings, openConfig } from '../config/index.js'; import { createSettings, openConfig } from '../config/index.js';
import { info } from '../logger/core.js';
import { createContainer, isStarted, startContainer } from './container.js';
import { createSafeError } from '../errors/index.js'; import { createSafeError } from '../errors/index.js';
import { info } from '../logger/core.js';
import type { Container, CreateContainerParams } from './container';
import { createContainer, isStarted, startContainer } from './container.js';
async function createRestartedContainer(container: Container, settings: AstroSettings): Promise<Container> { async function createRestartedContainer(
const { container: Container,
logging, settings: AstroSettings
fs, ): Promise<Container> {
resolvedRoot, const { logging, fs, resolvedRoot, configFlag, configFlagPath } = container;
configFlag,
configFlagPath
} = container;
const needsStart = isStarted(container); const needsStart = isStarted(container);
const newContainer = await createContainer({ const newContainer = await createContainer({
isRestart: true, isRestart: true,
@ -25,26 +22,24 @@ async function createRestartedContainer(container: Container, settings: AstroSet
configFlagPath, configFlagPath,
}); });
if(needsStart) { if (needsStart) {
await startContainer(newContainer); await startContainer(newContainer);
} }
return newContainer; return newContainer;
} }
export function shouldRestartContainer({ export function shouldRestartContainer(
settings, { settings, configFlag, configFlagPath, restartInFlight }: Container,
configFlag, changedFile: string
configFlagPath, ): boolean {
restartInFlight if (restartInFlight) return false;
}: Container, changedFile: string): boolean {
if(restartInFlight) return false;
let shouldRestart = false; let shouldRestart = false;
// If the config file changed, reload the config and restart the server. // If the config file changed, reload the config and restart the server.
if(configFlag) { if (configFlag) {
if(!!configFlagPath) { if (!!configFlagPath) {
shouldRestart = vite.normalizePath(configFlagPath) === vite.normalizePath(changedFile); shouldRestart = vite.normalizePath(configFlagPath) === vite.normalizePath(changedFile);
} }
} }
@ -78,19 +73,14 @@ export async function restartContainer({
flags, flags,
logMsg, logMsg,
handleConfigError, handleConfigError,
beforeRestart beforeRestart,
}: RestartContainerParams): Promise<{ container: Container, error: Error | null }> { }: RestartContainerParams): Promise<{ container: Container; error: Error | null }> {
const { const { logging, close, resolvedRoot, settings: existingSettings } = container;
logging,
close,
resolvedRoot,
settings: existingSettings
} = container;
container.restartInFlight = true; container.restartInFlight = true;
//console.clear(); // TODO move this //console.clear(); // TODO move this
if(beforeRestart) { if (beforeRestart) {
beforeRestart() beforeRestart();
} }
try { try {
const newConfig = await openConfig({ const newConfig = await openConfig({
@ -107,7 +97,7 @@ export async function restartContainer({
await close(); await close();
return { return {
container: await createRestartedContainer(container, settings), container: await createRestartedContainer(container, settings),
error: null error: null,
}; };
} catch (_err) { } catch (_err) {
const error = createSafeError(_err); const error = createSafeError(_err);
@ -116,7 +106,7 @@ export async function restartContainer({
info(logging, 'astro', 'Continuing with previous valid configuration\n'); info(logging, 'astro', 'Continuing with previous valid configuration\n');
return { return {
container: await createRestartedContainer(container, existingSettings), container: await createRestartedContainer(container, existingSettings),
error error,
}; };
} }
} }
@ -137,11 +127,11 @@ export async function createContainerWithAutomaticRestart({
flags, flags,
handleConfigError = (_e: Error) => {}, handleConfigError = (_e: Error) => {},
beforeRestart, beforeRestart,
params params,
}: CreateContainerWithAutomaticRestart): Promise<Restart> { }: CreateContainerWithAutomaticRestart): Promise<Restart> {
const initialContainer = await createContainer(params); const initialContainer = await createContainer(params);
let resolveRestart: (value: Error | null) => void; let resolveRestart: (value: Error | null) => void;
let restartComplete = new Promise<Error | null>(resolve => { let restartComplete = new Promise<Error | null>((resolve) => {
resolveRestart = resolve; resolveRestart = resolve;
}); });
@ -149,14 +139,14 @@ export async function createContainerWithAutomaticRestart({
container: initialContainer, container: initialContainer,
restarted() { restarted() {
return restartComplete; return restartComplete;
} },
}; };
function handleServerRestart(logMsg: string) { function handleServerRestart(logMsg: string) {
// eslint-disable-next-line @typescript-eslint/no-shadow // eslint-disable-next-line @typescript-eslint/no-shadow
const container = restart.container; const container = restart.container;
return async function(changedFile: string) { return async function (changedFile: string) {
if(shouldRestartContainer(container, changedFile)) { if (shouldRestartContainer(container, changedFile)) {
const { container: newContainer, error } = await restartContainer({ const { container: newContainer, error } = await restartContainer({
beforeRestart, beforeRestart,
container, container,
@ -169,20 +159,20 @@ export async function createContainerWithAutomaticRestart({
type: 'error', type: 'error',
err: { err: {
message: err.message, message: err.message,
stack: err.stack || '' stack: err.stack || '',
} },
}); });
} },
}); });
restart.container = newContainer; restart.container = newContainer;
// Add new watches because this is a new container with a new Vite server // Add new watches because this is a new container with a new Vite server
addWatches(); addWatches();
resolveRestart(error); resolveRestart(error);
restartComplete = new Promise<Error | null>(resolve => { restartComplete = new Promise<Error | null>((resolve) => {
resolveRestart = resolve; resolveRestart = resolve;
}); });
} }
} };
} }
// Set up watches // Set up watches

View file

@ -1,7 +1,10 @@
import { expect } from 'chai'; import { expect } from 'chai';
import * as cheerio from 'cheerio'; import * as cheerio from 'cheerio';
import { createContainerWithAutomaticRestart, runInContainer } from '../../../dist/core/dev/index.js'; import {
createContainerWithAutomaticRestart,
runInContainer,
} from '../../../dist/core/dev/index.js';
import { createFs, createRequestAndResponse } from '../test-utils.js'; import { createFs, createRequestAndResponse } from '../test-utils.js';
const root = new URL('../../fixtures/alias/', import.meta.url); const root = new URL('../../fixtures/alias/', import.meta.url);
@ -20,13 +23,13 @@ describe('dev container restarts', () => {
`, `,
'/astro.config.mjs': ` '/astro.config.mjs': `
` `,
}, },
root root
); );
let restart = await createContainerWithAutomaticRestart({ let restart = await createContainerWithAutomaticRestart({
params: { fs, root } params: { fs, root },
}); });
try { try {
@ -39,13 +42,16 @@ describe('dev container restarts', () => {
const $ = cheerio.load(html); const $ = cheerio.load(html);
expect(r.res.statusCode).to.equal(200); expect(r.res.statusCode).to.equal(200);
expect($('h1')).to.have.a.lengthOf(1); expect($('h1')).to.have.a.lengthOf(1);
// Create an error // Create an error
let restartComplete = restart.restarted(); let restartComplete = restart.restarted();
fs.writeFileFromRootSync('/astro.config.mjs', 'const foo = bar'); fs.writeFileFromRootSync('/astro.config.mjs', 'const foo = bar');
// Vite watches the real filesystem, so we have to mock this part. It's not so bad. // Vite watches the real filesystem, so we have to mock this part. It's not so bad.
restart.container.viteServer.watcher.emit('change', fs.getFullyResolvedPath('/astro.config.mjs')); restart.container.viteServer.watcher.emit(
'change',
fs.getFullyResolvedPath('/astro.config.mjs')
);
// Wait for the restart to finish // Wait for the restart to finish
let hmrError = await restartComplete; let hmrError = await restartComplete;
@ -57,7 +63,10 @@ describe('dev container restarts', () => {
fs.writeFileFromRootSync('/astro.config.mjs', 'const foo = bar2'); fs.writeFileFromRootSync('/astro.config.mjs', 'const foo = bar2');
// Vite watches the real filesystem, so we have to mock this part. It's not so bad. // Vite watches the real filesystem, so we have to mock this part. It's not so bad.
restart.container.viteServer.watcher.emit('change', fs.getFullyResolvedPath('/astro.config.mjs')); restart.container.viteServer.watcher.emit(
'change',
fs.getFullyResolvedPath('/astro.config.mjs')
);
hmrError = await restartComplete; hmrError = await restartComplete;
expect(hmrError).to.not.be.a('undefined'); expect(hmrError).to.not.be.a('undefined');