Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: scaffold tsconfig is none is present #77

Merged
merged 1 commit into from
Nov 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"globby": "^10",
"jest": "^24.9.0",
"prettier": "^1.18.2",
"strip-ansi": "^6.0.0",
"ts-jest": "^24.1.0"
},
"engines": {
Expand Down
12 changes: 7 additions & 5 deletions src/cli/commands/build.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,17 @@
import * as fs from 'fs-jetpack'
import { BUILD_FOLDER_NAME } from '../../constants'
import { scan } from '../../framework/layout'
import { runPrismaGenerators } from '../../framework/plugins'
import { createStartModuleContent } from '../../framework/start'
import {
compile,
findOrScaffoldTsConfig,
generateArtifacts,
pog,
readTsConfig,
transpileModule,
pog,
} from '../../utils'
import { createStartModuleContent } from '../../framework/start'
import { Command } from '../helpers'
import { BUILD_FOLDER_NAME } from '../../constants'

const log = pog.sub('cli:build')

Expand All @@ -22,10 +23,11 @@ export class Build implements Command {
async parse(argv: string[]) {
// Handle Prisma integration
// TODO pluggable CLI
await runPrismaGenerators()

const layout = await scan()

await findOrScaffoldTsConfig(layout)
await runPrismaGenerators()

log('running typegen')
console.log('🎃 Generating Nexus artifacts ...')
await generateArtifacts(
Expand Down
9 changes: 6 additions & 3 deletions src/cli/commands/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ import { Box, Instance, render } from 'ink'
import React from 'react'
import * as readline from 'readline'
import { Layout, scan } from '../../framework/layout'
import { runPrismaGenerators } from '../../framework/plugins'
import { createStartModuleContent } from '../../framework/start'
import { pog } from '../../utils'
import { findOrScaffoldTsConfig, pog } from '../../utils'
import { createWatcher } from '../../watcher'
import { Command } from '../helpers'
import { runPrismaGenerators } from '../../framework/plugins'

const log = pog.sub('cli:dev')

Expand All @@ -23,7 +23,10 @@ export class Dev implements Command {
process.exit(0)
}

const [layout] = await Promise.all([scan(), runPrismaGenerators()])
const layout = await scan()

await findOrScaffoldTsConfig(layout)
await runPrismaGenerators()

// Setup ui/log toggling system
let state:
Expand Down
23 changes: 21 additions & 2 deletions src/cli/commands/doctor.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import Git from 'simple-git/promise'
import { scan } from '../../framework/layout'
import { findOrScaffoldTsConfig } from '../../utils'
import { Command } from '../helpers'
import chalk from 'chalk'

export class Doctor implements Command {
public static new(): Doctor {
Expand All @@ -10,12 +13,28 @@ export class Doctor implements Command {
const frameworkDotFolder = '.pumpkins'
const git = Git(process.cwd())

console.log(chalk.bold('-- .gitignore --'))
if (await git.checkIsRepo()) {
if ((await git.checkIgnore([frameworkDotFolder])).length === 0) {
console.log(`please add ${frameworkDotFolder} to your gitignore file`)
console.log(
chalk`{yellow Warning:} Please add ${frameworkDotFolder} to your gitignore file`
)
} else {
console.log(`ok ${frameworkDotFolder} is git-ignored correctly`)
console.log(
chalk`{green OK:} ${frameworkDotFolder} is git-ignored correctly`
)
}
}

console.log(chalk.bold('-- tsconfig.json --'))
const layout = await scan()
const result = await findOrScaffoldTsConfig(layout, {
exitAfterError: false,
})
if (result === 'success') {
console.log(
chalk`{green OK:} "tsconfig.json" is present and in the right directory`
)
}
}
}
2 changes: 0 additions & 2 deletions src/framework/nexus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ import * as nexus from 'nexus'
import { generateSchema } from 'nexus/dist/core'
import * as fs from 'fs-jetpack'
import * as Nexus from 'nexus'
import * as path from 'path'
import { findProjectDir } from '../utils'

export function createNexusSingleton() {
const __types: any[] = []
Expand Down
14 changes: 4 additions & 10 deletions src/utils/path.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,19 +49,13 @@ export const writeCachedFile = async (
}

export function findProjectDir() {
let filePath = findConfigFile('package.json', { required: false })
let packageJsonPath = findConfigFile('package.json', { required: false })

if (!filePath) {
filePath = findConfigFile('tsconfig.json', { required: false })
if (packageJsonPath) {
return path.dirname(packageJsonPath)
}

if (!filePath) {
throw new Error(
'Could not find the project directory. A "package.json" or "tsconfig.json" file is required.'
)
}

return path.dirname(filePath)
return process.cwd()
}

// build/index.js => index.ts
Expand Down
64 changes: 63 additions & 1 deletion src/utils/tsc.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import * as ts from 'typescript'
import * as fs from 'fs-jetpack'
import * as path from 'path'
import * as ts from 'typescript'
import { BUILD_FOLDER_NAME } from '../constants'
import { Layout } from '../framework/layout'
import { findProjectDir } from './path'
import chalk = require('chalk')

const diagnosticHost: ts.FormatDiagnosticsHost = {
getNewLine: () => ts.sys.newLine,
Expand Down Expand Up @@ -112,3 +116,61 @@ export function transpileModule(
): string {
return ts.transpileModule(input, { compilerOptions }).outputText
}

/**
* Find or scaffold a tsconfig.json file
* Process will exit if package.json is not in the projectDir**
*/
export async function findOrScaffoldTsConfig(
layout: Layout,
options: { exitAfterError: boolean } = { exitAfterError: true }
): Promise<'success' | 'warning' | 'error'> {
const tsConfigPath = findConfigFile('tsconfig.json', { required: false })
const projectDir = findProjectDir()

if (tsConfigPath) {
if (path.dirname(tsConfigPath) !== projectDir) {
console.error(
chalk`{red ERROR:} Your tsconfig.json file needs to be in your project root directory`
)
console.error(
chalk`{red ERROR:} Found ${tsConfigPath}, expected ${path.join(
projectDir,
'tsconfig.json'
)}`
)
if (options.exitAfterError) {
process.exit(1)
} else {
return 'error'
}
}
}

if (!tsConfigPath) {
console.log(`
${chalk.yellow('Warning:')} We could not find a "tsconfig.json" file.
${chalk.yellow('Warning:')} We scaffolded one for you at ${path.join(
projectDir,
'tsconfig.json'
)}.
`)

const tsConfigContent = `\
{
"target": "es2016",
"module": "commonjs",
"lib": ["esnext"],
"rootDir": "${path.relative(projectDir, layout.sourceRoot)}",
"outDir": "${BUILD_FOLDER_NAME}",
"skipLibCheck": true,
"strict": true,
}
`
const tsConfigPath = path.join(projectDir, 'tsconfig.json')
await fs.writeAsync(tsConfigPath, tsConfigContent)
return 'warning'
}

return 'success'
}
9 changes: 7 additions & 2 deletions test/__helpers/run.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,12 @@
import { spawnSync, SpawnSyncOptions } from 'child_process'
import * as path from 'path'
import { withoutColors } from './utils'

type RunResult = { stderr: string; stdout: string; status: null | number }
export type RunResult = {
stderr: string
stdout: string
status: null | number
}
type RunOptions = Omit<SpawnSyncOptions, 'encoding'> & {
require?: boolean
}
Expand All @@ -26,7 +31,7 @@ export const run = (command: string, options?: RunOptions): RunResult => {
`)
}

return { stderr, stdout, status }
return withoutColors({ stderr, stdout, status })
}

export const createRunner = (cwd: string): typeof run => {
Expand Down
10 changes: 10 additions & 0 deletions test/__helpers/utils.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { SimpleGit } from 'simple-git/promise'
import stripAnsi from 'strip-ansi'
import { RunResult } from './run'

export async function gitReset(git: SimpleGit) {
await Promise.all([
Expand All @@ -12,3 +14,11 @@ export async function gitRepo(git: SimpleGit) {
await git.raw(['add', '-A'])
await git.raw(['commit', '--allow-empty', '--message', 'initial commit'])
}

export function withoutColors(result: RunResult): RunResult {
return {
status: result.status,
stdout: stripAnsi(result.stdout),
stderr: stripAnsi(result.stderr),
}
}
26 changes: 13 additions & 13 deletions test/integration/__snapshots__/build.spec.ts.snap
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ Object {
"children": Array [
Object {
"name": "app.js",
"size": 319,
"size": 370,
"type": "file",
},
Object {
Expand All @@ -26,17 +26,17 @@ Object {
},
Object {
"name": "schema.js",
"size": 366,
"size": 499,
"type": "file",
},
Object {
"name": "start.js",
"size": 625,
"size": 480,
"type": "file",
},
],
"name": "dist",
"size": 1578,
"name": ".build",
"size": 1617,
"type": "dir",
}
`;
Expand All @@ -57,17 +57,17 @@ Object {
"children": Array [
Object {
"name": "a.js",
"size": 95,
"size": 213,
"type": "file",
},
Object {
"name": "start.js",
"size": 472,
"size": 509,
"type": "file",
},
],
"name": "build",
"size": 567,
"name": ".build",
"size": 722,
"type": "dir",
}
`;
Expand All @@ -88,17 +88,17 @@ Object {
"children": Array [
Object {
"name": "schema.js",
"size": 95,
"size": 213,
"type": "file",
},
Object {
"name": "start.js",
"size": 470,
"size": 507,
"type": "file",
},
],
"name": "build",
"size": 565,
"name": ".build",
"size": 720,
"type": "dir",
}
`;
Expand Down
Loading