-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.js
386 lines (327 loc) · 9.92 KB
/
main.js
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
378
379
380
381
382
383
384
385
386
const fs = require('fs')
const path = require('path')
const { noCase, pascalCase } = require('change-case')
const baseEnum = require('./base-enum')
const CodeWriter = require('./code-writer')
const columnTypes = require('./column-types')
/**
* Generate a database compatible table name for UML class.
*
* @param {string} name
* @returns {string}
*/
function sanitizeTableName (name) {
return noCase(name, {
transform: (part, index, parts) =>
`${part}${parts.length - 1 === index ? '' : '_'}`.toLowerCase()
})
.split(' ')
.join('')
}
/**
* Get model views from diagram.
*
* @param {type.UMLClassDiagram} diagram
* @param {type.UMLView} type
* @returns {type.UMLObject[]}
*/
function getViews (diagram, type) {
return diagram.ownedViews
.filter(view => view instanceof type)
.map(typeView => typeView.model)
}
/**
* Get associated classes.
*
* @param {type.UMLClass} umlClass
* @returns {type.UMLAssociation[]}
*/
function getClassAssociations (umlClass) {
return umlClass.ownedElements.filter(
element => element instanceof type.UMLAssociation
)
}
/**
* Pad Value.
*
* @param {any} value
* @returns {string}
*/
function padValue (value) {
return value.toString().padStart(2, '0')
}
function generateMigrations (diagram, folder) {
const tables = getViews(diagram, type.UMLClassView).filter(
umlClass => (umlClass.stereotype || '').toLowerCase() === 'table'
)
const enumerations = getViews(diagram, type.UMLEnumerationView)
if (!tables.length) {
return app.toast.error('There is no migrations to generate!')
}
tables
.sort((a, b) => {
if (getClassAssociations(b).some(dep => dep.end2.reference === a)) {
return -1
}
if (getClassAssociations(a).some(dep => dep.end2.reference === b)) {
return 1
}
return 0
})
.forEach((table, tableIndex) => {
const date = new Date()
const writer = new CodeWriter()
const ids = table.attributes
.filter(attribute => attribute.isID)
.map(attribute => `'${attribute.name}'`)
const usedEnums = table.attributes
.filter(attribute => attribute.type instanceof type.UMLEnumeration)
.map(attribute => attribute.type.name)
const timestampColumns = ['created_at', 'updated_at']
const typesWithMultiplicity = [
'set',
'char',
'time',
'float',
'double',
'timeTz',
'string',
'decimal',
'dateTime',
'dateTimeTz',
'softDeletes',
'softDeletesTz',
'unsignedDecimal'
]
const databaseTableName = sanitizeTableName(table.name)
writer.writeLines(
['<?php', ''].concat(
usedEnums
.map(usedEnum => `use App\\Enums\\${usedEnum};`)
.sort((a, b) => a.length - b.length),
[
'use Illuminate\\Support\\Facades\\Schema;',
'use Illuminate\\Database\\Schema\\Blueprint;',
'use Illuminate\\Database\\Migrations\\Migration;',
'',
`class Create${pascalCase(table.name)}Table extends Migration`,
'{'
]
)
)
writer.indent()
writer.writeLines([
'/**',
' * Run the migrations.',
' *',
' * @return void',
' */',
'public function up()',
'{'
])
writer.indent()
writer.writeLine(
`Schema::create('${databaseTableName}', function (Blueprint $table) {`
)
writer.indent()
table.attributes
.filter(attribute => timestampColumns.indexOf(attribute.name) === -1)
.forEach(
({
name,
isID,
isUnique,
stereotype,
multiplicity,
defaultValue,
documentation,
type: dataType
}) => {
writer.writeLine('$table->')
if (
typeof dataType === 'string' &&
columnTypes.indexOf(dataType) !== -1
) {
writer.write(`${dataType}('${name}'`)
if (
typesWithMultiplicity.indexOf(dataType) !== -1 &&
multiplicity !== ''
) {
writer.write(', ' + multiplicity.split('..').join(', '))
}
} else if (dataType instanceof type.UMLEnumeration) {
writer.write(`enum('${name}', ${dataType.name}::values()`)
} else {
// I don't know what this person is thinking, let's just do `text` abeg...
writer.write(`text('${name}'`)
}
writer.write(')')
if (isUnique) {
writer.write('->unique()')
}
if (defaultValue !== '') {
if (defaultValue.toLowerCase() === 'null') {
writer.write('->nullable()')
} else {
writer.write(
`->default(${
dataType instanceof type.UMLEnumeration
? `${dataType.name}::${defaultValue}`
: defaultValue
})`
)
}
}
// if we have multiple ids, we will handle it later...
if (isID && ids.length <= 1) {
writer.write('->primary()')
}
if (documentation !== '') {
writer.write(`->comment('${documentation.replace("'", "\\'")}')`)
}
writer.write(';')
if ((stereotype = (stereotype || '').toLowerCase())) {
if (stereotype === 'in' || stereotype === 'index') {
return writer.writeLine(`$table->index('${name}');`)
}
}
}
)
// handle composite keys
if (ids.length > 1) {
writer.writeLine(`$table->primary([${ids.join(', ')}]);`)
}
// handle timestamps
if (
table.attributes.some(
attribute => timestampColumns.indexOf(attribute.name) !== -1
)
) {
writer.writeLine('$table->timestamps();')
}
getClassAssociations(table).forEach(({ end1, end2 }, index, arr) => {
writer.writeLine(`$table->foreign('${end1.name}')`)
writer.indent()
writer.writeLines([
`->references('${end2.name}')`,
`->on('${sanitizeTableName(end2.reference.name)}')`,
`->onDelete('${
end1.defaultValue.length ? end1.defaultValue : 'cascade'
}');`
])
writer.outdent()
})
writer.outdent()
writer.writeLine('});')
writer.outdent()
writer.writeLines([
'}',
'',
'/**',
' * Reverse the migrations.',
' *',
' * @return void',
' */',
'public function down()',
'{'
])
writer.indent()
writer.writeLine(`Schema::dropIfExists('${databaseTableName}');`)
writer.outdent()
writer.writeLine('}')
writer.outdent()
writer.writeLines(['}', ''])
// Laravel Migrations file format: <year>_<month>_<day>_<hour><minute><second>_create_<table>_table.php
fs.writeFileSync(
path.join(
folder,
`${date.getFullYear()}_${padValue(date.getMonth() + 1)}_${padValue(
date.getDate()
)}_${padValue(date.getHours())}${padValue(
date.getMinutes()
)}${padValue(
date.getSeconds() + tableIndex
)}_create_${databaseTableName}_table.php`
),
writer.getData()
)
})
if (enumerations.length > 0) {
const enumsDir = path.join(folder, 'Enums')
fs.mkdirSync(enumsDir)
fs.writeFileSync(path.join(enumsDir, 'BaseEnum.php'), baseEnum)
enumerations.forEach(({ name, literals }) => {
const writer = new CodeWriter()
const enumerationName = pascalCase(name)
writer.writeLines([
'<?php',
'',
'namespace App\\Enums;',
'',
`abstract class ${enumerationName} extends BaseEnum`,
'{'
])
writer.indent()
literals.forEach(({ name, documentation }, index) => {
if (documentation !== '') {
writer.writeLine('/**')
writer.writeLines(documentation.split('\n').map(line => ` * ${line}`))
writer.writeLine(' */')
}
writer.writeLine(`public const ${name} = '${name}';`)
// if not last item, add a blank line after definition...
if (index !== literals.length - 1) {
writer.writeLine('')
}
})
writer.outdent()
writer.writeLines(['}', ''])
fs.writeFileSync(
path.join(enumsDir, `${enumerationName}.php`),
writer.getData()
)
})
}
app.toast.info(
`${tables.length} migrations and ${enumerations.length} enums generated successfully.`
)
}
function getOutputFolderAndGenerateMigrations (diagram) {
const files = app.dialogs.showOpenDialog(
'Select a folder where generated migrations will be located',
null,
null,
{ properties: ['openDirectory'] }
)
if (files && files.length > 0) {
generateMigrations(diagram, files[0])
}
}
exports.init = function () {
app.commands.register(
'laravel:generate',
function (diagram, folder) {
if (!diagram || !diagram instanceof type.UMLClassDiagram) {
app.elementListPickerDialog
.showDialog(
'Select a class diagram to generate the migrations from',
app.repository.select('@UMLClassDiagram')
)
.then(function ({ buttonId, returnValue }) {
if (buttonId === 'ok') {
if (!folder) {
getOutputFolderAndGenerateMigrations(returnValue)
} else {
generateMigrations(returnValue, folder)
}
}
})
} else if (!folder) {
getOutputFolderAndGenerateMigrations(diagram)
} else {
generateMigrations(diagram, folder)
}
},
'Generate Laravel Migrations'
)
}