-
Notifications
You must be signed in to change notification settings - Fork 2
/
generate.ts
225 lines (211 loc) · 6.68 KB
/
generate.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
import {
ClassDeclaration,
Directory,
IndentationText,
Logger,
Project,
ResolutionHosts,
SourceFile,
StructureKind
} from './deps.ts';
const logger = new Logger('Danet-CLI');
export async function generateProject(options: GenerateOption, name: string) {
try {
await overwriteIfPossibleOrQuit(name);
await cloneRepositoryAndDeleteGitFolder(name);
await setupDatabaseCode(options, name);
logger.log(`Danet's project creation done !
You can run it with the following commands: cd ${name} && danet develop
Tests can be run with: deno task test`);
// deno-lint-ignore no-explicit-any
} catch (e: any) {
logger.error(e.toString());
}
}
interface GenerateOption {
mongodb?: boolean;
postgres?: boolean;
inMemory?: boolean;
}
const capitalize = (myString: string) => {
return myString.charAt(0).toUpperCase() + myString.slice(1);
};
const possibleDatabases = ['mongodb', 'postgres', 'in-memory'];
async function setupDatabaseCode(
options: GenerateOption,
projectDirectory: string,
) {
const databaseName: string = getDatabaseFromOptionOrAskUser(options);
await deleteOtherDatabaseCode(databaseName, projectDirectory);
if (databaseName !== 'in-memory') {
await modifyModulesWithDatabaseService(databaseName, projectDirectory);
} else {
logger.log('Keeping code as is due to in-memory being selected');
// await Deno.remove(toPathString(`${projectDirectory}/src/database`), {
// recursive: true,
// });
logger.log('Deleting database folder');
}
}
function getDatabaseFromOptionOrAskUser(options: GenerateOption) {
let database = '';
if (!options.mongodb && !options.postgres && !options.inMemory) {
database = askWhichDBUserWants();
} else if (options.mongodb) {
database = 'mongodb';
} else if (options.postgres) {
database = 'postgres';
} else {
database = 'in-memory';
}
return database;
}
function modifyDatabaseModule(baseDirectory: Directory, databaseName: string) {
const dbDirectory: Directory = baseDirectory?.getDirectory('src/database')!;
const dbModuleFile: SourceFile = dbDirectory?.getSourceFile('module.ts')!;
const importDeclaration = dbModuleFile.getImportDeclarations()[1];
importDeclaration.remove();
dbModuleFile.addImportDeclaration({
defaultImport: `{ ${capitalize(databaseName)}Service }`,
moduleSpecifier: `./${databaseName}.service.ts`,
});
const DatabaseClass: ClassDeclaration = dbModuleFile?.getClassOrThrow(
'DatabaseModule',
);
const ModuleDeclaration = DatabaseClass.getDecorators().find((d) =>
d.getName() === 'Module'
)!;
const moduleDeclarationArgument = ModuleDeclaration.getArguments()[0];
// deno-lint-ignore no-explicit-any
const argumentProperties = (moduleDeclarationArgument as any).getProperties();
// deno-lint-ignore no-explicit-any
const moduleInjectables = argumentProperties.find((p: any) =>
p.getName() === 'injectables'
);
moduleInjectables.set(
{
name: 'injectables',
kind: StructureKind.PropertyAssignment,
initializer: `[new TokenInjector(${
capitalize(databaseName)
}Service, DATABASE)]`,
},
);
logger.log(
`Declaration and export of ${
capitalize(databaseName)
}Service from DatabaseModule`,
);
}
function modifyTodoModule(baseDirectory: Directory, databaseName: string) {
const dbDirectory: Directory = baseDirectory?.getDirectory('src/todo')!;
const todoModule: SourceFile = dbDirectory?.getSourceFile('module.ts')!;
const importDeclaration = todoModule.getImportDeclarations()[4];
importDeclaration.remove();
todoModule.addImportDeclaration({
defaultImport: `{ ${capitalize(databaseName)}Repository }`,
moduleSpecifier: `./${databaseName}-repository.ts`,
});
todoModule.addImportDeclaration({
defaultImport: `{ DatabaseModule }`,
moduleSpecifier: `../database/module.ts`,
});
const DatabaseClass: ClassDeclaration = todoModule?.getClassOrThrow(
'TodoModule',
);
const ModuleDeclaration = DatabaseClass.getDecorators().find((d) =>
d.getName() === 'Module'
)!;
const moduleDeclarationArgument = ModuleDeclaration.getArguments()[0];
// deno-lint-ignore no-explicit-any
const argumentProperties = (moduleDeclarationArgument as any).getProperties();
// deno-lint-ignore no-explicit-any
(moduleDeclarationArgument as any).addProperty({
name: 'imports',
kind: StructureKind.PropertyAssignment,
initializer: `[DatabaseModule]`,
});
// deno-lint-ignore no-explicit-any
const moduleInjectables = argumentProperties.find((p: any) =>
p.getName() === 'injectables'
);
moduleInjectables.set(
{
name: 'injectables',
kind: 32,
initializer: `[new TokenInjector(${
capitalize(databaseName)
}Repository, USER_REPOSITORY), TodoService]`,
},
);
logger.log(
`Declaration and injection of ${
capitalize(databaseName)
}Repository in TodoModule`,
);
}
async function modifyModulesWithDatabaseService(
databaseName: string,
projectDirectory: string,
) {
const project = new Project({
resolutionHost: ResolutionHosts.deno,
indentationText: IndentationText.TwoSpaces,
// deno-lint-ignore no-explicit-any
} as any);
project.addSourceFilesAtPaths(`${projectDirectory}/**/*.ts`);
const baseDirectory = project.getDirectory(`${projectDirectory}`)!;
modifyDatabaseModule(baseDirectory, databaseName);
modifyTodoModule(baseDirectory, databaseName);
await project.save();
}
async function deleteOtherDatabaseCode(
databaseName: string,
projectDirectory: string,
) {
for (const dbName of possibleDatabases) {
if (dbName !== databaseName) {
if (dbName !== 'in-memory') {
await Deno.remove(`${projectDirectory}/src/database/${dbName}.service.ts`);
}
await Deno.remove(`${projectDirectory}/src/todo/${dbName}-repository.ts`);
}
}
}
function askWhichDBUserWants() {
let database = '';
while (!possibleDatabases.includes(database)) {
database = prompt(
`What database provider do you want to use ? (mongodb/postgres/in-memory)`,
'mongodb',
) as string;
}
return database;
}
async function overwriteIfPossibleOrQuit(name: string) {
const overwrite: string | null = prompt(
`${name} folder may already exists, do you want to completely overwrite its content ? (y/N)`,
'N',
);
if (overwrite?.toLowerCase() === 'y') {
try {
await Deno.remove(name, {recursive: true});
// deno-lint-ignore no-explicit-any
} catch (e: any) {
if (e.name !== 'NotFound')
console.log(e);
}
}
}
async function cloneRepositoryAndDeleteGitFolder(name: string) {
const repository = `https://github.com/Savory/Danet-Starter.git`;
logger.log(`Cloning starter project from ${repository} into ${name}`);
const cloneCommand = new Deno.Command("git", {
args: [ 'clone', repository, `${name}`]
});
const { success, stdout } = await cloneCommand.output();
if (!success) {
throw new Error('Clone Failed');
}
await Deno.remove(`./${name}/.git`, { recursive: true });
}