-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcli.ts
More file actions
377 lines (344 loc) · 11.8 KB
/
cli.ts
File metadata and controls
377 lines (344 loc) · 11.8 KB
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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
#!/usr/bin/env node
// SPDX-FileCopyrightText: 2025-2026 Vasyl Zakharchenko
// SPDX-License-Identifier: MIT
import { Command } from "commander";
import dotenv from "dotenv";
import inquirer from "inquirer";
import fs from "node:fs";
import path from "node:path";
import { generateModels, type GenerateModelsOptions } from "./actions/generate-models";
import { createMigration, type CreateMigrationOptions } from "./actions/migrations-create";
import { updateMigration, type UpdateMigrationOptions } from "./actions/migrations-update";
import { dropMigration, type DropMigrationOptions } from "./actions/migrations-drops";
import { createSchema, type CreateSchemaOptions } from "./actions/schema-create";
const ENV_PATH = path.resolve(process.cwd(), ".env");
// 🔄 Load environment variables from `.env` file
dotenv.config({ path: ENV_PATH });
/**
* Resolved configuration shared across all CLI commands.
*/
interface CliConfig {
host?: string;
port?: number;
user?: string;
password?: string;
dbName?: string;
output?: string;
versionField?: string;
entitiesPath?: string;
force?: boolean;
}
/**
* Raw options object provided by Commander to each command action.
* All values arrive as strings (or booleans for flags) from the CLI.
*/
interface CommandOptions {
host?: string;
port?: string;
user?: string;
password?: string;
dbName?: string;
output?: string;
versionField?: string;
entitiesPath?: string;
force?: boolean;
saveEnv?: boolean;
}
/**
* Raw answers returned by Inquirer. Every prompted value is a string,
* including `port`, which is converted to a number before it reaches `CliConfig`.
*/
interface PromptAnswers {
host?: string;
port?: string;
user?: string;
password?: string;
dbName?: string;
output?: string;
versionField?: string;
entitiesPath?: string;
}
const saveEnvFile = (config: CliConfig) => {
let envContent = "";
const envFilePath = ENV_PATH;
if (fs.existsSync(envFilePath)) {
envContent = fs.readFileSync(envFilePath, "utf8");
}
const envVars = envContent
.split("\n")
.filter((line) => line.trim() !== "" && !line.startsWith("#"))
.reduce<Record<string, string>>((acc, line) => {
const [key, ...value] = line.split("=");
acc[key] = value.join("=");
return acc;
}, {});
Object.entries(config).forEach(([key, value]) => {
envVars[`FORGE_SQL_ORM_${key.toUpperCase()}`] = String(value);
});
const updatedEnvContent = Object.entries(envVars)
.map(([key, value]) => `${key}=${value}`)
.join("\n");
fs.writeFileSync(envFilePath, updatedEnvContent, { encoding: "utf8" });
console.log("✅ Configuration saved to .env without overwriting other variables.");
};
/**
* Prompts the user for missing parameters using Inquirer.js.
* @param config - The current configuration object.
* @param defaultOutput - Default output path.
* @param customAskMissingParams - Optional function for additional prompts.
* @returns Updated configuration with user input.
*/
const askMissingParams = async (
config: CliConfig,
defaultOutput: string,
customAskMissingParams?: (cfg: CliConfig, questions: unknown[]) => void,
): Promise<CliConfig> => {
const questions: unknown[] = [];
if (!config.host)
questions.push({
type: "input",
name: "host",
message: "Enter database host:",
default: "localhost",
});
if (!config.port)
questions.push({
type: "input",
name: "port",
message: "Enter database port:",
default: "3306",
validate: (input: string) => !Number.isNaN(Number.parseInt(input, 10)),
});
if (!config.user)
questions.push({
type: "input",
name: "user",
message: "Enter database user:",
default: "root",
});
if (!config.password)
questions.push({
type: "password",
name: "password",
message: "Enter database password:",
mask: "*",
});
if (!config.dbName)
questions.push({
type: "input",
name: "dbName",
message: "Enter database name:",
});
if (!config.output)
questions.push({
type: "input",
name: "output",
message: "Enter output path:",
default: defaultOutput,
});
// Allow additional questions from the caller
if (customAskMissingParams) {
customAskMissingParams(config, questions);
}
// If there are missing parameters, prompt the user
if (questions.length > 0) {
// @ts-ignore - Ignore TypeScript warning for dynamic question type
const answers = (await inquirer.prompt(questions)) as PromptAnswers;
const rawPort = config.port ?? answers.port;
return {
...config,
...answers,
port: rawPort === undefined ? undefined : Number.parseInt(String(rawPort), 10),
};
}
return config;
};
/**
* Retrieves configuration parameters from command-line arguments and environment variables.
* If any required parameters are missing, prompts the user for input.
* @param cmd - The command object containing CLI options.
* @param defaultOutput - Default output directory.
* @param customConfig - Optional function for additional configuration parameters.
* @param customAskMissingParams - Optional function for additional prompts.
* @returns A fully resolved configuration object.
*/
/**
* Resolves the database port from the CLI flag, falling back to the environment.
* @param cmdPort - Raw `--port` value from the command line.
* @returns The parsed port number, or undefined when neither source is set.
*/
function resolvePort(cmdPort?: string): number | undefined {
const raw = cmdPort ?? process.env.FORGE_SQL_ORM_PORT;
return raw === undefined ? undefined : Number.parseInt(raw, 10);
}
const getConfig = async (
cmd: CommandOptions,
defaultOutput: string,
customConfig?: () => Partial<CliConfig>,
customAskMissingParams?: (cfg: CliConfig, questions: unknown[]) => void,
): Promise<CliConfig> => {
let config = {
host: cmd.host || process.env.FORGE_SQL_ORM_HOST,
port: resolvePort(cmd.port),
user: cmd.user || process.env.FORGE_SQL_ORM_USER,
password: cmd.password || process.env.FORGE_SQL_ORM_PASSWORD,
dbName: cmd.dbName || process.env.FORGE_SQL_ORM_DBNAME,
output: cmd.output || process.env.FORGE_SQL_ORM_OUTPUT,
};
// Merge additional configurations if provided
if (customConfig) {
config = { ...config, ...customConfig() };
}
const conf = await askMissingParams(config, defaultOutput, customAskMissingParams);
if (cmd.saveEnv) {
saveEnvFile(conf);
}
return conf;
};
// 📌 Initialize CLI
export const program = new Command();
program.version("1.0.0");
// ✅ Command: Generate database models (Entities)
program
.command("generate:model")
.description("Generate Drizzle models from the database.")
.option("--host <string>", "Database host")
.option("--port <number>", "Database port")
.option("--user <string>", "Database user")
.option("--password <string>", "Database password")
.option("--dbName <string>", "Database name")
.option("--output <string>", "Output path for entities")
.option("--versionField <string>", "Field name for versioning")
.option("--saveEnv", "Save configuration to .env file")
.action(async (cmd) => {
const config = await getConfig(
cmd,
"./database/entities",
() => ({
versionField: cmd.versionField || process.env.FORGE_SQL_ORM_VERSIONFIELD,
}),
(cfg, questions: unknown[]) => {
if (!cfg.versionField) {
questions.push({
type: "input",
name: "versionField",
message: "Enter the field name for versioning (leave empty to skip):",
default: "",
});
}
},
);
await generateModels(config as GenerateModelsOptions);
});
// ✅ Command: Create initial database migration
program
.command("migrations:create")
.description("Generate an initial migration for the entire database.")
.option("--host <string>", "Database host")
.option("--port <number>", "Database port")
.option("--user <string>", "Database user")
.option("--password <string>", "Database password")
.option("--dbName <string>", "Database name")
.option("--output <string>", "Output path for migrations")
.option("--force", "Force creation even if migrations exist")
.option("--saveEnv", "Save configuration to .env file")
.action(async (cmd) => {
const config = await getConfig(cmd, "./database/migration", () => ({
force: cmd.force || false,
}));
await createMigration(config as CreateMigrationOptions);
});
// ✅ Command: Update migration for schema changes
program
.command("migrations:update")
.description("Generate a migration to update the database schema.")
.option("--host <string>", "Database host")
.option("--port <number>", "Database port")
.option("--user <string>", "Database user")
.option("--password <string>", "Database password")
.option("--dbName <string>", "Database name")
.option("--output <string>", "Output path for migrations")
.option("--entitiesPath <string>", "Path to the folder containing entities")
.option("--saveEnv", "Save configuration to .env file")
.action(async (cmd) => {
const config = await getConfig(
cmd,
"./database/migration",
() => ({
entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,
}),
(cfg, questions: unknown[]) => {
if (!cfg.entitiesPath)
questions.push({
type: "input",
name: "entitiesPath",
message: "Enter the path to entities:",
default: "./database/entities",
});
},
);
await updateMigration(config as UpdateMigrationOptions);
});
// ✅ Command: Drop all migrations
program
.command("migrations:drop")
.description("Generate a migration to drop all tables and clear migrations history.")
.option("--host <string>", "Database host")
.option("--port <number>", "Database port")
.option("--user <string>", "Database user")
.option("--password <string>", "Database password")
.option("--dbName <string>", "Database name")
.option("--output <string>", "Output path for migrations")
.option("--entitiesPath <string>", "Path to the folder containing entities")
.option("--saveEnv", "Save configuration to .env file")
.action(async (cmd) => {
const config = await getConfig(
cmd,
"./database/migration",
() => ({
entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,
}),
(cfg, questions: unknown[]) => {
if (!cfg.entitiesPath)
questions.push({
type: "input",
name: "entitiesPath",
message: "Enter the path to entities:",
default: "./database/entities",
});
},
);
await dropMigration(config as DropMigrationOptions);
});
// ✅ Command: Apply DB schema directly from Drizzle models
program
.command("schema:create")
.description("Create/update database schema directly from Drizzle models.")
.option("--host <string>", "Database host")
.option("--port <number>", "Database port")
.option("--user <string>", "Database user")
.option("--password <string>", "Database password")
.option("--dbName <string>", "Database name")
.option("--entitiesPath <string>", "Path to the folder containing entities")
.option("--saveEnv", "Save configuration to .env file")
.action(async (cmd) => {
const config = await getConfig(
cmd,
"./database/entities",
() => ({
entitiesPath: cmd.entitiesPath || process.env.FORGE_SQL_ORM_ENTITIESPATH,
}),
(cfg, questions: unknown[]) => {
if (!cfg.entitiesPath)
questions.push({
type: "input",
name: "entitiesPath",
message: "Enter the path to entities:",
default: "./database/entities",
});
},
);
await createSchema(config as CreateSchemaOptions);
});
// 🔥 Execute CLI
program.parse(process.argv);