@swell/cli
Version:
Swell's command line interface/utility
64 lines (63 loc) • 2.77 kB
JavaScript
import { confirm } from '@inquirer/prompts';
import * as path from 'node:path';
import { AppCommand } from './app-command.js';
import { AllConfigPaths, filePathExists, writeFile, writeJsonFile, } from './lib/apps/index.js';
/**
* A base class for Swell CLI Create commands for file and input handling.
*
* This class extends the `AppCommand` class and adds:
*
* - createType: Type of Config to generate file path
* - createFile: File creation, including general prompts
*/
export class CreateConfigCommand extends AppCommand {
createType = '';
async createFile({ extension = 'json', fileBody, fileName }, overwrite, shouldConfirm = true) {
const isJson = extension === 'json';
const filePath = path.join(this.appPath, AllConfigPaths[this.createType.toUpperCase()], `${fileName}.${extension}`);
if (shouldConfirm) {
this.log(`\nCreating app ${this.createType} in ${filePath}`);
this.log(`\n${isJson ? JSON.stringify(fileBody, null, 4) : fileBody}\n`);
if (filePathExists(filePath) && !overwrite) {
const continueWrite = await confirm({
message: `This will overwrite an existing ${this.createType} file. Ok to continue?`,
});
if (!continueWrite) {
return;
}
}
else {
const confirmCreate = await confirm({
message: 'Ok to continue?',
});
if (!confirmCreate) {
return;
}
}
}
else if (filePathExists(filePath) && !overwrite) {
// Non-interactive mode: never prompt; fail fast on potential overwrite
this.error(`A ${this.createType} file already exists at ${filePath}.\n\nUse --overwrite to replace the existing file in non-interactive mode.`, { exit: 1 });
}
typeof fileBody === 'string'
? await writeFile(filePath, fileBody)
: await writeJsonFile(filePath, fileBody);
this.log(`${filePath} created.`);
return true;
}
async getCollectionOptions() {
const models = await this.api.post({ adminPath: `/data/$get/:models` }, {
body: {
abstract: { $ne: true },
app_id: null,
client_id: null,
deprecated: { $ne: true },
fields: 'name, namespace',
limit: 1000,
name: { $nin: ['events', 'notifications', 'settings'] },
sort: 'namespace asc, name asc',
},
});
return (models?.results?.map((model) => model.namespace ? `${model.namespace}/${model.name}` : model.name) || []);
}
}