Skip to content

Commit

Permalink
feat: use @astrojs/check
Browse files Browse the repository at this point in the history
  • Loading branch information
Princesseuh committed Aug 1, 2023
1 parent 1b7dd11 commit 3f15fbf
Show file tree
Hide file tree
Showing 7 changed files with 538 additions and 351 deletions.
5 changes: 5 additions & 0 deletions .changeset/three-onions-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'astro': major
---

The `astro check` command now requires an external package `@astrojs/check` and an install of `typescript` in your project. This was done in order to make the main `astro` package smaller and give more flexibility to users in regard to the version of TypeScript they use.
8 changes: 7 additions & 1 deletion packages/astro/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -116,10 +116,16 @@
},
"dependencies": {
"@astrojs/compiler": "^1.6.3",
<<<<<<< Updated upstream
"@astrojs/internal-helpers": "workspace:*",
"@astrojs/language-server": "^1.0.0",
"@astrojs/markdown-remark": "workspace:*",
"@astrojs/telemetry": "workspace:*",
=======
"@astrojs/internal-helpers": "^0.1.1",
"@astrojs/markdown-remark": "^2.2.1",
"@astrojs/telemetry": "^2.1.1",
>>>>>>> Stashed changes
"@babel/core": "^7.22.5",
"@babel/generator": "^7.22.5",
"@babel/parser": "^7.22.5",
Expand Down Expand Up @@ -164,7 +170,6 @@
"string-width": "^5.1.2",
"strip-ansi": "^7.1.0",
"tsconfig-resolver": "^3.0.1",
"typescript": "*",
"unist-util-visit": "^4.1.2",
"vfile": "^5.3.7",
"vite": "^4.4.6",
Expand Down Expand Up @@ -196,6 +201,7 @@
"@types/send": "^0.17.1",
"@types/server-destroy": "^1.0.1",
"@types/unist": "^2.0.6",
"@astrojs/check": "^0.1.0",
"astro-scripts": "workspace:*",
"chai": "^4.3.7",
"cheerio": "1.0.0-rc.12",
Expand Down
53 changes: 41 additions & 12 deletions packages/astro/src/cli/check/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
<<<<<<< Updated upstream
import {
AstroCheck,
DiagnosticSeverity,
Expand Down Expand Up @@ -36,16 +37,32 @@ export type CheckPayload = {
* Flags passed via CLI
*/
flags: Flags;
};

type CheckFlags = {
=======
import path from 'node:path';
import type { Arguments } from 'yargs-parser';
import { error, info, type LogOptions } from '../../core/logger/core.js';
import { getPackage } from '../install-package.js';

type CheckOptions = {
flags: Arguments;
/**
* Whether the `check` command should watch for `.astro` and report errors
* @default {false}
* Logging options
*/
watch: boolean;
logging: LogOptions;
>>>>>>> Stashed changes
};

export async function check({ flags, logging }: CheckOptions) {
const getPackageOpts = { skipAsk: flags.yes || flags.y, cwd: flags.root };
const checkPackage = await getPackage<typeof import('@astrojs/check')>(
'@astrojs/check',
logging,
getPackageOpts,
['typescript']
);
const typescript = await getPackage('typescript', logging, getPackageOpts);

<<<<<<< Updated upstream
/**
*
* Types of response emitted by the checker
Expand Down Expand Up @@ -100,14 +117,22 @@ export async function check({ flags }: CheckPayload): Promise<AstroChecker | und
const { userConfig, astroConfig } = await resolveConfig(inlineConfig, 'check');
telemetry.record(eventCliSession('check', userConfig, flags));
const settings = createSettings(astroConfig, fileURLToPath(astroConfig.root));

const checkFlags = parseFlags(flags);
if (checkFlags.watch) {
info(logging, 'check', 'Checking files in watch mode');
} else {
info(logging, 'check', 'Checking files');
=======
if (!checkPackage || !typescript) {
error(
logging,
'check',
'The `@astrojs/check` and `typescript` packages are required for this command to work. Please install them into your project and try again.'
);
return;
}

const { check: checker, parseArgsAsCheckConfig } = checkPackage;
>>>>>>> Stashed changes

const config = parseArgsAsCheckConfig(process.argv);

<<<<<<< Updated upstream
const { syncInternal } = await import('../../core/sync/index.js');
const root = settings.config.root;
const require = createRequire(import.meta.url);
Expand Down Expand Up @@ -393,4 +418,8 @@ function parseFlags(flags: Flags): CheckFlags {
return {
watch: flags.watch ?? false,
};
=======
info(logging, 'check', `Getting diagnostics for Astro files in ${path.resolve(config.root)}...`);
return await checker(config);
>>>>>>> Stashed changes
}
119 changes: 0 additions & 119 deletions packages/astro/src/cli/check/print.ts

This file was deleted.

9 changes: 8 additions & 1 deletion packages/astro/src/cli/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
}
case 'check': {
const { check } = await import('./check/index.js');
<<<<<<< Updated upstream
// We create a server to start doing our operations
const checkServer = await check({ flags });
if (checkServer) {
Expand All @@ -164,8 +165,14 @@ async function runCommand(cmd: string, flags: yargs.Arguments) {
const checkResult = await checkServer.check();
return process.exit(checkResult);
}
=======
const checkServer = await check({ flags, logging });
if (flags.watch) {
return await new Promise(() => {}); // lives forever
} else {
return process.exit(checkServer ? 1 : 0);
>>>>>>> Stashed changes
}
return;
}
case 'sync': {
const { sync } = await import('./sync/index.js');
Expand Down
124 changes: 124 additions & 0 deletions packages/astro/src/cli/install-package.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
import boxen from 'boxen';
import { execa } from 'execa';
import { bold, cyan, dim, magenta } from 'kleur/colors';
import { createRequire } from 'node:module';
import ora from 'ora';
import prompts from 'prompts';
import whichPm from 'which-pm';
import { debug, info, type LogOptions } from '../core/logger/core.js';

type GetPackageOptions = {
skipAsk?: boolean;
cwd?: string;
};

export async function getPackage<T>(
packageName: string,
logging: LogOptions,
options: GetPackageOptions,
otherDeps: string[] = []
): Promise<T | undefined> {
const require = createRequire(options.cwd ?? process.cwd());

let packageImport;
try {
require.resolve(packageName);

// The `require.resolve` is required as to avoid Node caching the failed `import`
packageImport = await import(packageName);
} catch (e) {
info(
logging,
'',
`To continue, Astro requires the following dependency to be installed: ${bold(packageName)}.`
);
const result = await installPackage([packageName, ...otherDeps], options, logging);

if (result) {
packageImport = await import(packageName);
} else {
return undefined;
}
}

return packageImport as T;
}

function getInstallCommand(packages: string[], packageManager: string) {
switch (packageManager) {
case 'npm':
return { pm: 'npm', command: 'install', flags: [], dependencies: packages };
case 'yarn':
return { pm: 'yarn', command: 'add', flags: [], dependencies: packages };
case 'pnpm':
return { pm: 'pnpm', command: 'add', flags: [], dependencies: packages };
default:
return null;
}
}

async function installPackage(
packageNames: string[],
options: GetPackageOptions,
logging: LogOptions
): Promise<boolean> {
const cwd = options.cwd ?? process.cwd();
const packageManager = (await whichPm(cwd)).name ?? 'npm';
const installCommand = getInstallCommand(packageNames, packageManager);

if (!installCommand) {
return false;
}

const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
'',
...installCommand.flags,
].join(' ')} ${cyan(installCommand.dependencies.join(' '))}`;
const message = `\n${boxen(coloredOutput, {
margin: 0.5,
padding: 0.5,
borderStyle: 'round',
})}\n`;
info(
logging,
null,
`\n ${magenta('Astro will run the following command:')}\n ${dim(
'If you skip this step, you can always run it yourself later'
)}\n${message}`
);

let response;
if (options.skipAsk) {
response = true;
} else {
response = (
await prompts({
type: 'confirm',
name: 'askToContinue',
message: 'Continue?',
initial: true,
})
).askToContinue;
}

if (Boolean(response)) {
const spinner = ora('Installing dependencies...').start();
try {
await execa(
installCommand.pm,
[installCommand.command, ...installCommand.flags, ...installCommand.dependencies],
{ cwd: cwd }
);
spinner.succeed();

return true;
} catch (err) {
debug('add', 'Error installing dependencies', err);
spinner.fail();

return false;
}
} else {
return false;
}
}
Loading

0 comments on commit 3f15fbf

Please sign in to comment.