/
bin.ts
executable file
·256 lines (236 loc) · 7.01 KB
/
bin.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
#!/usr/bin/env ts-node
import fs from 'fs'
import { promisify } from 'util'
import path from 'path'
import dotenv from 'dotenv'
import chalk from 'chalk'
import { arg, drawBox, getCLIPathHash, getProjectHash } from '@prisma/sdk'
const packageJson = require('../package.json') // eslint-disable-line @typescript-eslint/no-var-requires
export { byline } from '@prisma/migrate'
// do this before facebook's yoga
import debugLib from 'debug'
const debug = debugLib('prisma')
process.on('uncaughtException', (e) => {
debug(e)
})
process.on('unhandledRejection', (e) => {
debug(e)
})
// warnings: no tanks
// hides ExperimentalWarning: The fs.promises API is experimental
process.env.NODE_NO_WARNINGS = '1'
// react: psst 🙊
process.env.NODE_ENV = 'production'
if (process.argv.length > 1 && process.argv[1].endsWith('prisma2')) {
console.log(
chalk.yellow('deprecated') +
` The ${chalk.redBright(
'prisma2',
)} command is deprecated and has been renamed to ${chalk.greenBright(
'prisma',
)}.\nPlease execute ${chalk.bold.greenBright(
'prisma' +
(process.argv.length > 2
? ' ' + process.argv.slice(2).join(' ')
: ''),
)} instead.\n`,
)
}
//
// Read .env file only if next to schema.prisma
//
// if the CLI is called witout any comand like `prisma` we can ignore .env loading
if (process.argv.length > 2) {
let dotenvResult
// Parse CLI arguments and look for --schema
const args = arg(process.argv.slice(3), { '--schema': String })
// Check --schema directory
if (args && args['--schema']) {
const dotenvFilepath = path.join(path.dirname(args['--schema']), '.env')
if (fs.existsSync(args['--schema']) && fs.existsSync(dotenvFilepath)) {
dotenvResult = dotenv.config({ path: dotenvFilepath })
console.log(
chalk.dim(
'Environment variables loaded from provided --schema directory',
),
)
} else {
debug('Environment variables not loaded (--schema was provided)')
}
} // Check current directory
else if (fs.existsSync('schema.prisma') && fs.existsSync('.env')) {
dotenvResult = dotenv.config()
console.log(
chalk.dim('Environment variables loaded from current directory'),
)
} // Check ./prisma directory
else if (
fs.existsSync('prisma/schema.prisma') &&
fs.existsSync('prisma/.env')
) {
dotenvResult = dotenv.config({ path: 'prisma/.env' })
console.log(chalk.dim('Environment variables loaded from ./prisma/.env'))
} // We didn't find a .env file next to the prisma.schema file.
else {
debug('Environment variables not loaded')
}
// Print the error if any (if internal dotenv readFileSync throws)
if (dotenvResult && dotenvResult.error) {
console.error(chalk.redBright.bold('Error: ') + dotenvResult.error)
}
}
/**
* Dependencies
*/
import { isError, HelpError } from '@prisma/sdk'
import {
MigrateCommand,
MigrateSave,
MigrateUp,
MigrateDown,
MigrateTmpPrepare,
StudioCommand,
handlePanic,
} from '@prisma/migrate'
import { CLI } from './CLI'
import { Introspect, Init } from '@prisma/introspection'
import { Dev } from './Dev'
import { Version } from './Version'
import { Generate } from './Generate'
import { ProviderAliases } from '@prisma/sdk'
import { Validate } from './Validate'
import * as checkpoint from 'checkpoint-client'
import ci from '@prisma/ci-info'
import { Format } from './Format'
// aliases are only used by @prisma/studio, but not for users anymore,
// as they have to ship their own version of @prisma/client
const aliases: ProviderAliases = {
'prisma-client-js': {
generatorPath: eval(
`require('path').join(__dirname, '../prisma-client/generator-build/index.js')`,
), // all evals are here for ncc
outputPath: eval(`require('path').join(__dirname, '../prisma-client/')`),
},
}
// because chalk ...
if (process.env.NO_COLOR) {
chalk.level = 0
}
/**
* Main function
*/
async function main(): Promise<number> {
// create a new CLI with our subcommands
const cli = CLI.new(
{
init: Init.new(),
migrate: MigrateCommand.new({
save: MigrateSave.new(),
up: MigrateUp.new(),
down: MigrateDown.new(),
}),
'tmp-prepare': MigrateTmpPrepare.new(),
introspect: Introspect.new(),
dev: Dev.new(),
studio: StudioCommand.new(aliases),
generate: Generate.new(),
version: Version.new(),
validate: Validate.new(),
format: Format.new(),
},
[
'version',
'init',
'migrate',
'tmp-prepare',
'introspect',
'dev',
'studio',
'generate',
'validate',
'format',
],
)
// parse the arguments
const result = await cli.parse(process.argv.slice(2))
if (result instanceof HelpError) {
console.error(result.message)
return 1
} else if (isError(result)) {
console.error(result)
return 1
}
console.log(result)
// SHA256 identifier for the project based on the prisma schema path
const projectPathHash = await getProjectHash()
// SHA256 of the cli path
const cliPathHash = getCLIPathHash()
// check prisma for updates
const checkResult = await checkpoint.check({
product: 'prisma',
cli_path_hash: cliPathHash,
project_hash: projectPathHash,
version: packageJson.version,
disable: ci.isCI,
})
// if the result is cached and we're outdated, show this prompte
if (checkResult.status === 'ok' && checkResult.data.outdated) {
console.error(
drawBox({
height: 4,
width: 59,
str: `\n${chalk.blue('Update available')} ${packageJson.version} -> ${
checkResult.data.current_version
}\nRun ${chalk.bold(checkResult.data.install_command)} to update`,
horizontalPadding: 2,
}),
)
}
return 0
}
process.on('SIGINT', () => {
process.exit(0) // now the "exit" event will fire
})
/**
* Run our program
*/
if (require.main === module) {
main()
.then((code) => {
if (code !== 0) {
process.exit(code)
}
})
.catch((err) => {
function handleIndividualError(error): void {
if (error.rustStack) {
handlePanic(
error,
packageJson.version,
packageJson.prisma.version,
).catch((e) => {
if (debugLib.enabled('prisma')) {
console.error(chalk.redBright.bold('Error: ') + e.stack)
} else {
console.error(chalk.redBright.bold('Error: ') + e.message)
}
})
} else {
if (debugLib.enabled('prisma')) {
console.error(chalk.redBright.bold('Error: ') + error.stack)
} else {
console.error(chalk.redBright.bold('Error: ') + error.message)
}
process.exit(1)
}
}
// Sindre's pkg p-map & co are using AggregateError, it is an iterator.
if (typeof err[Symbol.iterator] === 'function') {
for (const individualError of err) {
handleIndividualError(individualError)
}
} else {
handleIndividualError(err)
}
})
}