-
Notifications
You must be signed in to change notification settings - Fork 1
/
contentful-cli-migrations.js
executable file
·604 lines (540 loc) · 22.8 KB
/
contentful-cli-migrations.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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
#! /usr/bin/env node
const PLACEHOLDER_MANAGEMENT_TOKEN = 'placeholder-management-token'
const PLACEHOLDER_SPACE_ID = 'placeholder-space-id'
const DEFAULT_MIGRATIONS_DIR = 'migrations/scripts/'
const DEFAULT_LOCALE = 'en-US'
const DEFAULT_FIRST_MIGRATION = '0001-create-counter-content-type.cjs'
;(async function main() {
try {
const localWorkingDir = process.cwd()
const scriptDirectory = await getDirNamePath()
const envValues = await getEnvValues(localWorkingDir, scriptDirectory)
const parsedArguments = await parseArguments(localWorkingDir, envValues)
const environmentSingleton = await getEnvironment(parsedArguments)
console.log(
'##/INFO: Applying migrations to environment-id: ' +
environmentSingleton?.sys?.id
)
let migrationArray
let latestMigrationNumber = 0
if (parsedArguments?.shouldInitialise) {
await createFirstMigration(parsedArguments)
migrationArray = [DEFAULT_FIRST_MIGRATION]
console.log(
'##/INFO: This is the fist run of the script. We will create the Counter content-type.'
)
} else {
latestMigrationNumber = await getCounter(
environmentSingleton,
parsedArguments
)
console.log(
'##/INFO: Latest migration successfully run # ' + latestMigrationNumber
)
migrationArray = await parseMigrationsToRun(
parsedArguments,
latestMigrationNumber
)
}
await performMigrations(
environmentSingleton,
parsedArguments,
latestMigrationNumber,
migrationArray
)
} catch (error) {
console.error('@@/ERROR:', error)
}
})()
/**
* Reads environment values from .env files.
*
* @param {string} localWorkingDir - The directory path where the library is located.
* @param {string} scriptDirectory - The directory path where the script is running.
* @return {Promise<object>} The environment values.
* @property {string} CMS_MANAGEMENT_TOKEN - The CMA token for Contentful.
* @property {string} CMS_SPACE_ID - The Space ID.
* @property {string} CMS_MIGRATIONS_DIR - The folder where the migration scripts are.
* @property {string} CMS_MIGRATIONS_COUNTER_ID - The entry-id used for the counter
* @property {string} CMS_MIGRATIONS_COUNTER_FIELD - The field in that entry that will store the actual counter
* @property {string} CMS_MIGRATIONS_COUNTER_LOCALE - The locale to look for in that field
*/
async function getEnvValues(localWorkingDir, scriptDirectory) {
const fileSystem = await import('fs')
const { config } = await import('dotenv')
const envDataFromPath = path =>
fileSystem.existsSync(path) ? config({ path }).parsed : {}
const paths = [
`${scriptDirectory}/../../.env`,
`${scriptDirectory}/../../.env.local`,
`${localWorkingDir}/.env`,
`${localWorkingDir}/.env.local`
]
const envValues = paths.map(envDataFromPath)
return Object.assign({}, ...envValues)
}
/**
* Parses command line arguments and sets default values.
*
* @param {string} rootFolder - The directory path where the .env files are located.
* @param {Object} envValues - The .env values loaded.
* @property {string} envValues.CMS_MANAGEMENT_TOKEN - The CMA token for Contentful.
* @property {string} envValues.CMS_SPACE_ID - The Space ID.
* @property {string} envValues.CMS_MIGRATIONS_DIR - The folder where the migration scripts are.
* @property {string} envValues.CMS_MIGRATIONS_COUNTER_ID - The entry-id used for the counter
* @property {string} envValues.CMS_MIGRATIONS_COUNTER_FIELD - The field in that entry that will store the actual counter
* @property {string} envValues.CMS_MIGRATIONS_COUNTER_LOCALE - The locale to look for in that field
* @returns {Promise<object>} The initial settings.
* @property {string} managementToken - The CMS Management Token.
* @property {string} spaceId - The CMS Space ID.
* @property {string} environmentId - The CMS Environment ID.
* @property {string} rootDestinationFolder - The folder containing the migrations
* @property {string} counterEntryId - The entry ID storing the counter.
* @property {string} counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} counterLocale - The locale of the field to look for.
* @property {boolean} forceYes - If it should run all the migrations.
* @property {boolean} shouldInitialise - If it should create the content-type and entry for the Counter.
*
* @throws {Error} If '--environment-id' or '--to' are not provided or if '--management-token' or '--mt' are duplicated.
*/
async function parseArguments(rootFolder, envValues) {
const minimist = (await import('minimist')).default
const parsedArguments = minimist(process.argv.slice(2))
await checkArgs(parsedArguments)
const {
'space-id': spaceId = envValues?.CMS_SPACE_ID ?? PLACEHOLDER_SPACE_ID,
'management-token': managementToken = parsedArguments['mt'] ??
envValues?.CMS_MANAGEMENT_TOKEN ??
PLACEHOLDER_MANAGEMENT_TOKEN,
'counter-id': counterEntryId = envValues?.CMS_MIGRATIONS_COUNTER_ID,
'counter-field': counterFieldId = envValues?.CMS_MIGRATIONS_COUNTER_FIELD,
'counter-locale':
counterLocale = envValues?.CMS_MIGRATIONS_COUNTER_LOCALE ??
DEFAULT_LOCALE,
'migrations-dir': migrationsDir = envValues?.CMS_MIGRATIONS_DIR ??
DEFAULT_MIGRATIONS_DIR
} = parsedArguments
const rootDestinationFolder = await getDestinationFolder(
rootFolder,
migrationsDir,
parsedArguments
)
const environmentId = parsedArguments?.to || parsedArguments['environment-id']
if (!environmentId) {
console.error('@@/ERROR: An environment-id should be specified')
process.exit(1)
}
return {
managementToken,
spaceId,
environmentId,
rootDestinationFolder,
counterEntryId,
counterFieldId,
counterLocale,
forceYes: parsedArguments.hasOwnProperty('force-yes'),
shouldInitialise: parsedArguments.hasOwnProperty('initialise')
}
}
/**
* This function checks the arguments passed in the command line.
*
* @param {Object} parsedArguments - The object that contains the parsed command line arguments.
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
* @returns {Promise<object>} An object containing the evaluated command line arguments.
*
* @throws {Error} If both 'to' and 'environment-id' options are specified or if neither is specified.
* @throws {Error} If both 'management-token' and 'mt' options are specified.
*/
async function checkArgs(parsedArguments) {
if (
!(Boolean(parsedArguments.to) ^ Boolean(parsedArguments['environment-id']))
) {
console.error(
"@@/ERROR: Only one of the two options '--environment-id' or '--to' should be specified"
)
process.exit(1)
}
if (
Boolean(parsedArguments['management-token']) &&
Boolean(parsedArguments.mt)
) {
console.error(
"@@/ERROR: Only one of the two options '--management-token' or '--mt' can be specified"
)
process.exit(1)
}
}
/**
* This function gets the destination folder based on whether a custom folder is provided or not.
*
* @param {string} rootFolder - The directory path where the script is being executed.
* @param {string} cmsMigrationsDir - The CMS Default Migrations Directory.
* @param {Object} parsedArguments - The object that contains the parsed command line arguments.
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
*
* @returns {Promise<string>} The path of the evaluated destination folder.
* @property {string} destinationFolder - The destination folder for the export.
*
* @throws {Error} If the destination folder does not exist or is not accessible.
*/
async function getDestinationFolder(
rootFolder,
cmsMigrationsDir,
parsedArguments
) {
const fileSystem = await import('fs')
const path = await import('path')
const defaultExportDirectory = path.join(rootFolder, cmsMigrationsDir)
let destinationFolder =
path.resolve(parsedArguments['migrations-dir'] || defaultExportDirectory) +
'/'
// Create destination folder if not present
if (!fileSystem.existsSync(destinationFolder)) {
fileSystem.mkdirSync(destinationFolder, { recursive: true })
}
if (
!fileSystem.existsSync(destinationFolder) ||
destinationFolder === path.sep
) {
console.error(
'@@/ERROR: Destination folder does not exist or is not accessible!'
)
process.exit(1)
}
return destinationFolder
}
/**
* Gets the current directory's path.
*
* @return {Promise<string>} The path of the current directory.
*/
async function getDirNamePath() {
const { fileURLToPath } = await import('url')
const { dirname } = await import('path')
const __filename = fileURLToPath(import.meta.url)
return dirname(__filename)
}
/**
* Create a First Migration if empty Environment
*
* @param {Object} parsedArguments
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
* @return {Promise<void>}
*/
async function createFirstMigration(parsedArguments) {
const fileSystem = await import('fs')
const firstMigrationName =
parsedArguments?.rootDestinationFolder + DEFAULT_FIRST_MIGRATION
const data =
'module.exports = async function (migration, context) {\n' +
" const keyValueStore = migration.createContentType('keyValue', {\n" +
" name: 'Key-Value',\n" +
" displayField: 'key'\n" +
' })\n' +
'\n' +
' keyValueStore\n' +
" .createField('key')\n" +
" .name('key')\n" +
" .type('Symbol')\n" +
' .localized(false)\n' +
' .required(true)\n' +
' .validations([\n' +
' {\n' +
' "unique": true\n' +
' }\n' +
' ])\n' +
' .disabled(false)\n' +
' .omitted(false)\n' +
'\n' +
' keyValueStore\n' +
" .createField('value')\n" +
" .name('value')\n" +
" .type('Symbol')\n" +
' .localized(true)\n' +
' .required(false)\n' +
' .validations([])\n' +
' .disabled(false)\n' +
' .omitted(false)\n' +
'}'
fileSystem.writeFileSync(firstMigrationName, data)
}
/**
* Create a Counter entry if missing
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environmentSingleton - The Contentful environment object.
* @return {Promise<void>}
*/
async function createCounterEntry(environmentSingleton) {
try {
const lib = await import('contentful-lib-helpers')
const defaultLocale = await lib.getDefaultLocale(environmentSingleton)
const counterEntry = await environmentSingleton.createEntry('keyValue', {
fields: {
key: {
[defaultLocale.code]: 'Counter-DO-NOT-DELETE'
},
value: {
[defaultLocale.code]: '1'
}
}
})
console.log('##/INFO: We created the Counter entry for you.')
console.log(
'##/INFO: Please write these values in your .env/.env.local file.'
)
console.log('CMS_MIGRATIONS_COUNTER_ID=' + counterEntry?.sys?.id)
console.log('CMS_MIGRATIONS_COUNTER_FIELD=value')
console.log('CMS_MIGRATIONS_COUNTER_LOCALE=' + defaultLocale.code)
} catch (error) {
console.error('@@/ERROR:', error)
process.exit(1)
}
}
/**
* Check if the destination environment exists before running the migration(s)
*
* @param {Object} parsedArguments
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @returns {Promise<import("contentful-management/dist/typings/entities/environment").Environment|null>} - A Promise that resolves with the environment object, or `null` if not found.
*/
async function getEnvironment(parsedArguments) {
const contentfulManagement = (await import('contentful-management')).default
const lib = await import('contentful-lib-helpers')
const environmentSingleton = await lib.getEnvironment(
contentfulManagement,
parsedArguments?.managementToken,
parsedArguments?.spaceId,
parsedArguments?.environmentId,
0
)
if (!environmentSingleton) {
console.error(
`Unable to retrieve Destination environment-id '${parsedArguments?.environmentId}' for space-id '${parsedArguments?.spaceId}'!`
)
console.error(
`Could also be that the management token or space-id are invalid.`
)
process.exit(1)
}
return environmentSingleton
}
/**
* Get the value of the latest successful migration from the Counter Entry
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environmentSingleton - The Contentful environment object.
* @param {Object} parsedArguments
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
* @return {Promise<number>}
*/
async function getCounter(environmentSingleton, parsedArguments) {
try {
const fieldId = parsedArguments?.counterFieldId
const fieldLocale = parsedArguments?.counterLocale
const counterEntry = await environmentSingleton.getEntry(
parsedArguments?.counterEntryId
)
if (!counterEntry?.fields?.[fieldId]) {
throw new Error(
'Impossible to retrieve the Counter entry! Please check entry-id, field-id and locale in your configuration'
)
}
if (counterEntry.fields[fieldId][fieldLocale] === undefined) {
counterEntry.fields[fieldId][fieldLocale] = '0'
try {
await counterEntry.update()
console.log('##/INFO: Counter entry is being initialised...')
} catch (e) {
throw new Error(
'Counter entry is invalid! Please check entry-id, field-id and locale in your configuration'
)
}
}
return parseInt(counterEntry.fields[fieldId]?.[fieldLocale], 10) || 0
} catch (error) {
console.error('@@/ERROR:', error)
process.exit(1)
}
}
/**
* Parses the migrations to run based on the latest migration number.
*
* @param {Object} parsedArguments - The script arguments.
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
* @param {number} latestMigrationNumber - The latest migration number.
* @returns {Promise<string[]>} An array of migrations to run.
*/
async function parseMigrationsToRun(parsedArguments, latestMigrationNumber) {
const fileSystem = await import('fs')
const folderMigrationScript = parsedArguments?.rootDestinationFolder
const allFiles = fileSystem.readdirSync(folderMigrationScript)
const files = allFiles.filter(item => !/(^|\/)\.[^/.]/g.test(item))
let migrationArray = []
let indexObject = []
let arrayLength = files.length
if (arrayLength === 0) {
console.log('%%/DEBUG: The migration folder is empty')
process.exit(1)
}
indexObject[0] = 'unused'
for (let i = 0; i < arrayLength; i++) {
const fileIndexValue = parseInt(files[i].split('-')[0])
if (fileIndexValue === undefined || !Number.isInteger(fileIndexValue)) {
console.error('@@/ERROR: There is an invalid migration:')
console.error('@@/ERROR: ' + folderMigrationScript + files[i])
process.exit(1)
}
if (indexObject[fileIndexValue]) {
console.error('@@/ERROR: There are duplicated migrations!')
console.error('@@/ERROR: ' + folderMigrationScript + files[i])
process.exit(1)
}
indexObject[fileIndexValue] = files[i]
}
for (let i = 1; i < indexObject.length; i++) {
if (i > latestMigrationNumber) {
migrationArray.push(indexObject[i])
}
}
return migrationArray
}
/**
* Performs the Contentful migrations.
*
* @param {import("contentful-management/dist/typings/entities/environment").Environment} environmentSingleton - The Contentful environment object.
* @param {Object} parsedArguments - The script arguments.
* @property {string} parsedArguments.managementToken - The CMS Management Token.
* @property {string} parsedArguments.spaceId - The CMS Space ID.
* @property {string} parsedArguments.environmentId - The CMS Environment ID.
* @property {string} parsedArguments.rootDestinationFolder - The folder containing the migrations
* @property {string} parsedArguments.counterEntryId - The entry ID storing the counter.
* @property {string} parsedArguments.counterFieldId - The field ID to retrieve the latest ran migration.
* @property {string} parsedArguments.counterLocale - The locale of the field to look for.
* @property {boolean} parsedArguments.forceYes - If it should run all the migrations.
* @property {boolean} parsedArguments.shouldInitialise - If it should create the content-type and entry for the Counter.
* @param {number} latestMigrationNumber - The latest migration number.
* @param {string[]} migrationArray - An array of migrations to run.
* @returns {Promise<void>}
*/
async function performMigrations(
environmentSingleton,
parsedArguments,
latestMigrationNumber,
migrationArray
) {
const fileSystem = await import('fs')
const path = await import('path')
const customAsync = await import('async')
const { runMigration } = await import('contentful-migration')
const folderMigrationScript =
parsedArguments?.rootDestinationFolder ?? DEFAULT_MIGRATIONS_DIR
if (migrationArray.length === 0) {
console.log(
'##/INFO: Your environment is already up to date to the latest migration'
)
return
}
// Loop and run migrations
await customAsync.eachSeries(
migrationArray,
function (migrationScript, callback) {
let options = {
spaceId: parsedArguments?.spaceId,
environmentId: environmentSingleton?.sys?.id,
accessToken: parsedArguments?.managementToken,
yes: parsedArguments?.forceYes
}
process.stdin.on('keypress', function (ch, key) {
if (key && key.name === 'n') {
process.exit(1)
}
})
if (
fileSystem.readFileSync(folderMigrationScript + migrationScript)
.length === 0
) {
console.error('@@/ERROR: The following migration is empty')
console.error('@@/ERROR: ' + folderMigrationScript + migrationScript)
process.exit(1)
}
runMigration({
...options,
...{
filePath: path.resolve(folderMigrationScript + migrationScript)
}
})
.then(async () => {
console.log('##/INFO: Migration ' + migrationScript + ' Done!')
if (!parsedArguments?.shouldInitialise) {
// Update counter value
latestMigrationNumber++
// Write new Count into Entry
const fieldId = parsedArguments?.counterFieldId
const fieldLocale = parsedArguments?.counterLocale
const entrySavingCounter = await environmentSingleton.getEntry(
parsedArguments?.counterEntryId
)
entrySavingCounter.fields[fieldId][fieldLocale] =
`${latestMigrationNumber}`
entrySavingCounter
.update()
.then(callback())
.catch(e => console.error('@@/ERROR: ' + e))
} else {
await createCounterEntry(environmentSingleton)
}
})
.catch(e =>
console.error(
'@@/ERROR ' +
e +
' - while running the migration: ' +
folderMigrationScript +
migrationScript
)
)
}
)
}