Skip to content

Commit

Permalink
[ci] format
Browse files Browse the repository at this point in the history
  • Loading branch information
natemoo-re authored and astrobot-houston committed Feb 6, 2023
1 parent 8d2187d commit 6a59531
Show file tree
Hide file tree
Showing 20 changed files with 412 additions and 301 deletions.
54 changes: 29 additions & 25 deletions packages/create-astro/src/actions/context.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os from 'node:os';
import { prompt } from '@astrojs/cli-kit';
import arg from 'arg';
import os from 'node:os';
import detectPackageManager from 'which-pm-runs';
import { prompt } from '@astrojs/cli-kit';

import { getName, getVersion } from '../messages.js';

Expand All @@ -26,27 +26,29 @@ export interface Context {
exit(code: number): never;
}


export async function getContext(argv: string[]): Promise<Context> {
const flags = arg({
'--template': String,
'--ref': String,
'--yes': Boolean,
'--no': Boolean,
'--install': Boolean,
'--no-install': Boolean,
'--git': Boolean,
'--no-git': Boolean,
'--typescript': String,
'--skip-houston': Boolean,
'--dry-run': Boolean,
'--help': Boolean,
'--fancy': Boolean,
const flags = arg(
{
'--template': String,
'--ref': String,
'--yes': Boolean,
'--no': Boolean,
'--install': Boolean,
'--no-install': Boolean,
'--git': Boolean,
'--no-git': Boolean,
'--typescript': String,
'--skip-houston': Boolean,
'--dry-run': Boolean,
'--help': Boolean,
'--fancy': Boolean,

'-y': '--yes',
'-n': '--no',
'-h': '--help',
}, { argv, permissive: true });
'-y': '--yes',
'-n': '--no',
'-h': '--help',
},
{ argv, permissive: true }
);

const pkgManager = detectPackageManager()?.name ?? 'npm';
const [username, version] = await Promise.all([getName(), getVersion()]);
Expand Down Expand Up @@ -75,8 +77,10 @@ export async function getContext(argv: string[]): Promise<Context> {
if (typescript == undefined) typescript = 'strict';
}

skipHouston = ((os.platform() === 'win32' && !fancy) || skipHouston) ?? [yes, no, install, git, typescript].some((v) => v !== undefined);

skipHouston =
((os.platform() === 'win32' && !fancy) || skipHouston) ??
[yes, no, install, git, typescript].some((v) => v !== undefined);

const context: Context = {
help,
prompt,
Expand All @@ -95,7 +99,7 @@ export async function getContext(argv: string[]): Promise<Context> {
cwd,
exit(code) {
process.exit(code);
}
}
},
};
return context;
}
21 changes: 11 additions & 10 deletions packages/create-astro/src/actions/dependencies.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { Context } from "./context";
import type { Context } from './context';

import { title, info, spinner } from '../messages.js';
import { execa } from 'execa';
import { info, spinner, title } from '../messages.js';

export async function dependencies(ctx: Pick<Context, 'install'|'yes'|'prompt'|'pkgManager'|'cwd'|'dryRun'>) {
export async function dependencies(
ctx: Pick<Context, 'install' | 'yes' | 'prompt' | 'pkgManager' | 'cwd' | 'dryRun'>
) {
let deps = ctx.install ?? ctx.yes;
if (deps === undefined) {
({ deps } = await ctx.prompt({
Expand Down Expand Up @@ -33,11 +35,10 @@ export async function dependencies(ctx: Pick<Context, 'install'|'yes'|'prompt'|'
}
}

async function install({ pkgManager, cwd }: { pkgManager: string, cwd: string }) {
const installExec = execa(pkgManager, ['install'], { cwd });
return new Promise<void>((resolve, reject) => {
installExec.on('error', (error) => reject(error));
installExec.on('close', () => resolve());
});
async function install({ pkgManager, cwd }: { pkgManager: string; cwd: string }) {
const installExec = execa(pkgManager, ['install'], { cwd });
return new Promise<void>((resolve, reject) => {
installExec.on('error', (error) => reject(error));
installExec.on('close', () => resolve());
});
}

19 changes: 14 additions & 5 deletions packages/create-astro/src/actions/git.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import type { Context } from "./context";
import fs from 'node:fs';
import path from 'node:path';
import type { Context } from './context';

import { color } from '@astrojs/cli-kit';
import { title, info, spinner } from '../messages.js';
import { execa } from 'execa';
import { info, spinner, title } from '../messages.js';

export async function git(ctx: Pick<Context, 'cwd'|'git'|'yes'|'prompt'|'dryRun'>) {
export async function git(ctx: Pick<Context, 'cwd' | 'git' | 'yes' | 'prompt' | 'dryRun'>) {
if (fs.existsSync(path.join(ctx.cwd, '.git'))) {
await info('Nice!', `Git has already been initialized`);
return
return;
}
let _git = ctx.git ?? ctx.yes;
if (_git === undefined) {
Expand Down Expand Up @@ -43,6 +43,15 @@ async function init({ cwd }: { cwd: string }) {
try {
await execa('git', ['init'], { cwd, stdio: 'ignore' });
await execa('git', ['add', '-A'], { cwd, stdio: 'ignore' });
await execa('git', ['commit', '-m', 'Initial commit from Astro', '--author="houston[bot] <[email protected]>"'], { cwd, stdio: 'ignore' });
await execa(
'git',
[
'commit',
'-m',
'Initial commit from Astro',
'--author="houston[bot] <[email protected]>"',
],
{ cwd, stdio: 'ignore' }
);
} catch (e) {}
}
6 changes: 3 additions & 3 deletions packages/create-astro/src/actions/intro.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { type Context } from './context';

import { banner, welcome, say } from '../messages.js';
import { label, color } from '@astrojs/cli-kit';
import { color, label } from '@astrojs/cli-kit';
import { random } from '@astrojs/cli-kit/utils';
import { banner, say, welcome } from '../messages.js';

export async function intro(ctx: Pick<Context, 'skipHouston'|'version'|'username'>) {
export async function intro(ctx: Pick<Context, 'skipHouston' | 'version' | 'username'>) {
if (!ctx.skipHouston) {
await say([
[
Expand Down
4 changes: 2 additions & 2 deletions packages/create-astro/src/actions/next-steps.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { Context } from "./context";
import path from 'node:path';
import { Context } from './context';

import { nextSteps, say } from '../messages.js';

export async function next(ctx: Pick<Context, 'cwd'|'pkgManager'|'skipHouston'>) {
export async function next(ctx: Pick<Context, 'cwd' | 'pkgManager' | 'skipHouston'>) {
let projectDir = path.relative(process.cwd(), ctx.cwd);
const devCmd = ctx.pkgManager === 'npm' ? 'npm run dev' : `${ctx.pkgManager} dev`;
await nextSteps({ projectDir, devCmd });
Expand Down
6 changes: 3 additions & 3 deletions packages/create-astro/src/actions/project-name.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import type { Context } from "./context";
import type { Context } from './context';

import { color, generateProjectName } from '@astrojs/cli-kit';
import { title, info, log } from '../messages.js';
import path from 'node:path';
import { info, log, title } from '../messages.js';

import { isEmpty, toValidName } from './shared.js';

export async function projectName(ctx: Pick<Context, 'cwd'|'prompt'|'projectName'|'exit'>) {
export async function projectName(ctx: Pick<Context, 'cwd' | 'prompt' | 'projectName' | 'exit'>) {
await checkCwd(ctx.cwd);

if (!ctx.cwd || !isEmpty(ctx.cwd)) {
Expand Down
18 changes: 8 additions & 10 deletions packages/create-astro/src/actions/shared.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,18 @@ export function isEmpty(dirPath: string) {
}

export function isValidName(projectName: string) {
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(
projectName,
)
return /^(?:@[a-z\d\-*~][a-z\d\-*._~]*\/)?[a-z\d\-~][a-z\d\-._~]*$/.test(projectName);
}

export function toValidName(projectName: string) {
if (isValidName(projectName)) return projectName;

return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z\d\-~]+/g, '-')
return projectName
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/^[._]/, '')
.replace(/[^a-z\d\-~]+/g, '-')
.replace(/^-+/, '')
.replace(/-+$/, '')
.replace(/-+$/, '');
}
42 changes: 26 additions & 16 deletions packages/create-astro/src/actions/template.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
/* eslint no-console: 'off' */
import type { Context } from "./context";
import type { Context } from './context';

import { color } from '@astrojs/cli-kit';
import { downloadTemplate } from 'giget';
import fs from 'node:fs';
import path from 'node:path';
import { downloadTemplate } from 'giget';
import { error } from '../messages.js';
import { color } from '@astrojs/cli-kit';
import { title, info, spinner } from '../messages.js';
import { error, info, spinner, title } from '../messages.js';

export async function template(ctx: Pick<Context, 'template'|'prompt'|'dryRun'|'exit'|'exit'>) {
export async function template(
ctx: Pick<Context, 'template' | 'prompt' | 'dryRun' | 'exit' | 'exit'>
) {
if (!ctx.template) {
const { template: tmpl } = await ctx.prompt({
name: 'template',
Expand Down Expand Up @@ -43,18 +44,27 @@ export async function template(ctx: Pick<Context, 'template'|'prompt'|'dryRun'|'
// some files are only needed for online editors when using astro.new. Remove for create-astro installs.
const FILES_TO_REMOVE = ['sandbox.config.json', 'CHANGELOG.md'];
const FILES_TO_UPDATE = {
'package.json': (file: string, overrides: { name: string }) => fs.promises.readFile(file, 'utf-8').then(value => (
fs.promises.writeFile(file, JSON.stringify(Object.assign(JSON.parse(value), Object.assign(overrides, { private: undefined })), null, '\t'), 'utf-8')
))
}
'package.json': (file: string, overrides: { name: string }) =>
fs.promises
.readFile(file, 'utf-8')
.then((value) =>
fs.promises.writeFile(
file,
JSON.stringify(
Object.assign(JSON.parse(value), Object.assign(overrides, { private: undefined })),
null,
'\t'
),
'utf-8'
)
),
};

export default async function copyTemplate(tmpl: string, ctx: Context) {
const ref = ctx.ref || 'latest';
const isThirdParty = tmpl.includes('/');

const templateTarget = isThirdParty
? tmpl
: `github:withastro/astro/examples/${tmpl}#${ref}`;
const templateTarget = isThirdParty ? tmpl : `github:withastro/astro/examples/${tmpl}#${ref}`;

// Copy
if (!ctx.dryRun) {
Expand All @@ -64,7 +74,7 @@ export default async function copyTemplate(tmpl: string, ctx: Context) {
provider: 'github',
cwd: ctx.cwd,
dir: '.',
})
});
} catch (err: any) {
fs.rmdirSync(ctx.cwd);
if (err.message.includes('404')) {
Expand All @@ -85,9 +95,9 @@ export default async function copyTemplate(tmpl: string, ctx: Context) {
const updateFiles = Object.entries(FILES_TO_UPDATE).map(async ([file, update]) => {
const fileLoc = path.resolve(path.join(ctx.cwd, file));
if (fs.existsSync(fileLoc)) {
return update(fileLoc, { name: ctx.projectName! })
return update(fileLoc, { name: ctx.projectName! });
}
})
});

await Promise.all([...removeFiles, ...updateFiles]);
}
Expand Down
20 changes: 12 additions & 8 deletions packages/create-astro/src/actions/typescript.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import type { Context } from "./context";
import type { Context } from './context';

import fs from 'node:fs'
import { readFile } from 'node:fs/promises'
import { color } from '@astrojs/cli-kit';
import fs from 'node:fs';
import { readFile } from 'node:fs/promises';
import path from 'node:path';
import stripJsonComments from 'strip-json-comments';
import { color } from '@astrojs/cli-kit';
import { title, info, error, typescriptByDefault, spinner } from '../messages.js';
import { error, info, spinner, title, typescriptByDefault } from '../messages.js';

export async function typescript(ctx: Pick<Context, 'typescript'|'yes'|'prompt'|'dryRun'|'cwd'|'exit'>) {
export async function typescript(
ctx: Pick<Context, 'typescript' | 'yes' | 'prompt' | 'dryRun' | 'cwd' | 'exit'>
) {
let ts = ctx.typescript ?? (typeof ctx.yes !== 'undefined' ? 'strict' : undefined);
if (ts === undefined) {
const { useTs } = await ctx.prompt({
Expand Down Expand Up @@ -68,7 +70,7 @@ export async function typescript(ctx: Pick<Context, 'typescript'|'yes'|'prompt'|
export async function setupTypeScript(value: string, { cwd }: { cwd: string }) {
const templateTSConfigPath = path.join(cwd, 'tsconfig.json');
try {
const data = await readFile(templateTSConfigPath, { encoding: 'utf-8' })
const data = await readFile(templateTSConfigPath, { encoding: 'utf-8' });
const templateTSConfig = JSON.parse(stripJsonComments(data));
if (templateTSConfig && typeof templateTSConfig === 'object') {
const result = Object.assign(templateTSConfig, {
Expand All @@ -77,7 +79,9 @@ export async function setupTypeScript(value: string, { cwd }: { cwd: string }) {

fs.writeFileSync(templateTSConfigPath, JSON.stringify(result, null, 2));
} else {
throw new Error("There was an error applying the requested TypeScript settings. This could be because the template's tsconfig.json is malformed")
throw new Error(
"There was an error applying the requested TypeScript settings. This could be because the template's tsconfig.json is malformed"
);
}
} catch (err) {
if (err && (err as any).code === 'ENOENT') {
Expand Down
34 changes: 13 additions & 21 deletions packages/create-astro/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import { getContext } from './actions/context.js';

import { setStdout } from './messages.js';
import { help } from './actions/help.js';
import { intro } from './actions/intro.js';
import { projectName } from './actions/project-name.js';
import { template } from './actions/template.js'
import { dependencies } from './actions/dependencies.js';
import { git } from './actions/git.js';
import { typescript, setupTypeScript } from './actions/typescript.js';
import { help } from './actions/help.js';
import { intro } from './actions/intro.js';
import { next } from './actions/next-steps.js';
import { projectName } from './actions/project-name.js';
import { template } from './actions/template.js';
import { setupTypeScript, typescript } from './actions/typescript.js';
import { setStdout } from './messages.js';

const exit = () => process.exit(0)
process.on('SIGINT', exit)
process.on('SIGTERM', exit)
const exit = () => process.exit(0);
process.on('SIGINT', exit);
process.on('SIGTERM', exit);

// Please also update the installation instructions in the docs at
// https://github.com/withastro/docs/blob/main/src/pages/en/install/auto.md
Expand All @@ -29,18 +29,10 @@ export async function main() {
return;
}

const steps = [
intro,
projectName,
template,
dependencies,
git,
typescript,
next
]
const steps = [intro, projectName, template, dependencies, git, typescript, next];

for (const step of steps) {
await step(ctx)
await step(ctx);
}
process.exit(0);
}
Expand All @@ -55,5 +47,5 @@ export {
git,
typescript,
setupTypeScript,
next
}
next,
};
Loading

0 comments on commit 6a59531

Please sign in to comment.