Skip to content

Commit

Permalink
poc new generator architecture
Browse files Browse the repository at this point in the history
  • Loading branch information
timsuchanek committed Oct 9, 2019
1 parent 95c92ff commit ff4a8d1
Show file tree
Hide file tree
Showing 20 changed files with 1,272 additions and 164 deletions.
4 changes: 2 additions & 2 deletions cli/generator-helper/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@prisma/generator-helper",
"version": "0.0.6",
"version": "0.0.8",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"typings": "dist/index.d.ts",
Expand All @@ -13,7 +13,7 @@
},
"scripts": {
"build": "tsc -d",
"prepublishOnly": "yarn build",
"prepublishOnly": "yarn build && yarn test",
"test": "jest"
},
"husky": {
Expand Down
14 changes: 3 additions & 11 deletions cli/generator-helper/src/GeneratorProcess.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,13 +76,7 @@ export class GeneratorProcess {
try {
data = JSON.parse(response)
} catch (e) {
if (!this.exitCode && this.initialized) {
throw new Error(
`Got invalid response from generator at ${
this.executablePath
}:\n${response}\n${e.stack || e.message}`,
)
}
console.error(response)
}
if (data) {
this.handleResponse(data)
Expand Down Expand Up @@ -163,17 +157,15 @@ export class GeneratorProcess {
})
})
}
generate(options: GeneratorOptions): Promise<void> {
generate(options: GeneratorOptions): Promise<any> {
return new Promise((resolve, reject) => {
const messageId = this.getMessageId()

this.registerListener(messageId, (result, error) => {
if (error) {
return reject(error)
}
if (result) {
resolve()
}
resolve(result)
})

this.sendMessage({
Expand Down
8 changes: 5 additions & 3 deletions cli/generator-helper/src/generatorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@ import { GeneratorOptions, GeneratorManifest, JsonRPC } from './types'
import byline from './byline'

export interface Handler {
onGenerate(options: GeneratorOptions): Promise<void>
onGenerate(options: GeneratorOptions): Promise<any>
onManifest?(): GeneratorManifest
}

export function generatorHandler(handler: Handler) {
byline(process.stdin).on('data', async line => {
const json = JSON.parse(String(line))

if (json.method === 'generate' && json.params) {
try {
await handler.onGenerate(json.params)
const result = await handler.onGenerate(json.params)
respond({
jsonrpc: '2.0',
result: {},
result: result,
id: json.id,
})
} catch (e) {
Expand All @@ -29,6 +30,7 @@ export function generatorHandler(handler: Handler) {
})
}
}

if (json.method === 'getManifest') {
if (handler.onManifest) {
try {
Expand Down
11 changes: 0 additions & 11 deletions cli/package.json

This file was deleted.

10 changes: 5 additions & 5 deletions cli/prisma2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,7 @@
"runtime/*.js",
"runtime/*.d.ts",
"runtime/utils",
"runtime/dist",
"nexus_prisma_ncc_build"
"runtime/dist"
],
"bin": {
"prisma2": "build/index.js"
Expand All @@ -24,10 +23,12 @@
},
"devDependencies": {
"@prisma/cli": "^0.1.10",
"@prisma/fetch-engine": "^0.1.14",
"@prisma/fetch-engine": "^0.3.0",
"@prisma/generator-helper": "^0.0.7",
"@prisma/introspection": "0.0.82",
"@prisma/lift": "0.3.24",
"@prisma/lift": "0.3.25",
"@prisma/photon": "^0.2.94",
"@prisma/sdk": "^0.0.4",
"@sentry/node": "5",
"@types/debug": "^4.1.5",
"@types/mocha": "^5.2.7",
Expand All @@ -36,7 +37,6 @@
"jest": "24.8.0",
"mocha": "6.1.4",
"mz": "2.7.0",
"nexus-prisma": "0.0.1-beta.6",
"open": "^6.4.0",
"pkg-up": "3.1.0",
"prisma-test-utils": "^0.2.5",
Expand Down
4 changes: 3 additions & 1 deletion cli/prisma2/scripts/copy-runtime.sh
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
mkdir -p runtime
mkdir -p nexus_prisma_ncc_build
mkdir -p prisma-test-utils_ncc
mkdir -p build/photon-generator
cp -R node_modules/@prisma/photon/runtime/* runtime
cp -R node_modules/@prisma/photon/generator-build/* build/photon-generator

rm -rf runtime/prisma
cp -R node_modules/nexus-prisma/nexus_prisma_ncc_build/* nexus_prisma_ncc_build
# cp -R node_modules/prisma-test-utils/prisma-test-utils_ncc/* prisma-test-utils_ncc
cp node_modules/@prisma/lift/dist/GeneratorWorker.js build/GeneratorWorker.js
cp node_modules/@prisma/studio-transports/build/photon-worker.js build/photon-worker.js
Expand Down
71 changes: 71 additions & 0 deletions cli/prisma2/src/Converter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { arg, Command, format, HelpError, isError } from '@prisma/cli'
import chalk from 'chalk'
import { DatabaseType, DefaultParser } from 'prisma-datamodel'
import { isdlToDatamodel2 } from '@prisma/sdk'

export class Converter implements Command {
public static new(): Converter {
return new Converter()
}

// static help template
private static help = format(`
Convert a datamodel 1.1 to datamodel 2
${chalk.bold('Usage')}
prisma2 convert
${chalk.bold('Options')}
-h, --help Displays this help message
${chalk.bold('Examples')}
${chalk.dim(`$`)} cat old-datamodel.prisma | prisma2 convert > new-datamodel.prisma
`)
private constructor() {}

// parse arguments
public async parse(argv: string[]): Promise<string | Error> {
// parse the arguments according to the spec
const args = arg(argv, {
'--help': Boolean,
'-h': '--help',
})

if (isError(args)) {
return this.help(args.message)
} else if (args['--help']) {
return this.help()
}

const datamodel = await this.readStdin()
const parser = DefaultParser.create(DatabaseType.postgres)
const isdl = parser.parseFromSchemaString(datamodel)
return isdlToDatamodel2(isdl, [])
}

public readStdin(): Promise<string> {
return new Promise(resolve => {
let input = ''

process.stdin.on('data', data => {
input += data.toString()
})
process.stdin.once('end', () => {
resolve(input)
})
process.stdin.setEncoding('utf-8')
process.stdin.resume()
})
}

// help message
public help(error?: string): string | HelpError {
if (error) {
return new HelpError(`\n${chalk.bold.red(`!`)} ${error}\n${Converter.help}`)
}
return Converter.help
}
}
37 changes: 28 additions & 9 deletions cli/prisma2/src/Generate.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,24 @@
import { Command, format, HelpError, Dictionary, GeneratorDefinitionWithPackage, getSchema } from '@prisma/cli'
import {
Command,
format,
HelpError,
Dictionary,
GeneratorDefinitionWithPackage,
getSchema,
getSchemaPath,
} from '@prisma/cli'
import chalk from 'chalk'
import { missingGeneratorMessage } from '@prisma/lift'
import { getCompiledGenerators } from '@prisma/photon'
import { getGenerators } from '@prisma/sdk'
import { formatms } from './utils/formatms'
const pkg = eval(`require('../package.json')`)

/**
* $ prisma migrate new
*/
export class Generate implements Command {
public static new(generators: Dictionary<GeneratorDefinitionWithPackage>): Generate {
return new Generate(generators)
public static new(aliases: Dictionary<string>): Generate {
return new Generate(aliases)
}

// static help template
Expand All @@ -21,21 +30,31 @@ export class Generate implements Command {
prisma2 generate
`)
private constructor(private readonly generators: Dictionary<GeneratorDefinitionWithPackage>) {}
private constructor(private readonly aliases: Dictionary<string>) {}

// parse arguments
public async parse(argv: string[], minimalOutput = false): Promise<string | Error> {
const datamodel = await getSchema()
const generators = await getCompiledGenerators(datamodel, this.generators)
const datamodelPath = await getSchemaPath()
const generators = await getGenerators({
schemaPath: datamodelPath!,
providerAliases: this.aliases,
printDownloadProgress: true,
version: pkg.prisma.version,
})

if (generators.length === 0) {
console.log(missingGeneratorMessage)
}

// CONTINUE HERE

for (const generator of generators) {
const toStr = generator.output ? chalk.dim(` to ${generator.output}`) : ''
console.log(`Generating ${chalk.bold(generator.prettyName!)}${toStr}`)
const toStr = generator.options!.generator.output! ? chalk.dim(` to ${generator.options!.generator.output}`) : ''
const name = generator.manifest ? generator.manifest.prettyName : generator.options!.generator.provider
console.log(`Generating ${chalk.bold(name!)}${toStr}`)
const before = Date.now()
await generator.generate()
generator.stop()
const after = Date.now()
console.log(`Done in ${formatms(after - before)}`)
}
Expand Down
13 changes: 8 additions & 5 deletions cli/prisma2/src/bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,17 +23,20 @@ process.on('unhandledRejection', e => {
*/
import { isError, HelpError } from '@prisma/cli'
import { LiftCommand, LiftSave, LiftUp, LiftDown, LiftWatch, LiftTmpPrepare, handlePanic } from '@prisma/lift'
import { Converter } from '@prisma/photon'
import { CLI } from './CLI'
import { Introspect, Init } from '@prisma/introspection'
import { Version } from './Version'
import { predefinedGenerators } from './generators'
import { Generate } from './Generate'
import chalk from 'chalk'
// import { capture } from './capture'
import { Docs } from './Docs'
import { Converter } from './Converter'
export { Photon } from '@prisma/studio-transports'

const aliases = {
photonjs: eval(`require('path').join(__dirname, './photon-generator/index.js')`), // all evals are here for ncc
}

/**
* Main function
*/
Expand All @@ -50,11 +53,11 @@ async function main(): Promise<number> {
down: LiftDown.new(),
docs: Docs.new('lift', 'https://github.com/prisma/prisma2/tree/master/docs'),
}),
'tmp-prepare': LiftTmpPrepare.new(predefinedGenerators),
'tmp-prepare': LiftTmpPrepare.new(aliases),
introspect: Introspect.new(),
convert: Converter.new(),
dev: LiftWatch.new(predefinedGenerators),
generate: Generate.new(predefinedGenerators),
dev: LiftWatch.new(aliases),
generate: Generate.new(aliases),
version: Version.new(),
})
// parse the arguments
Expand Down
25 changes: 0 additions & 25 deletions cli/prisma2/src/generators.ts

This file was deleted.

0 comments on commit ff4a8d1

Please sign in to comment.