|
| 1 | +/* |
| 2 | + * Copyright 2022-2025 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.grails.plugins.databasemigration.generator |
| 17 | + |
| 18 | +import java.time.ZonedDateTime |
| 19 | +import java.time.ZoneId |
| 20 | +import java.time.format.DateTimeFormatter |
| 21 | + |
| 22 | +import groovy.transform.CompileStatic |
| 23 | + |
| 24 | +import grails.cli.generator.AbstractGenerator |
| 25 | + |
| 26 | +/** |
| 27 | + * @author Michael Yan |
| 28 | + * @since 6.3.0 |
| 29 | + */ |
| 30 | +@CompileStatic |
| 31 | +class MigrationGenerator extends AbstractGenerator { |
| 32 | + |
| 33 | + @Override |
| 34 | + boolean generate() { |
| 35 | + String[] args = commandLine.remainingArgs.toArray(new String[0]) |
| 36 | + if (args.size() < 2) { |
| 37 | + return |
| 38 | + } |
| 39 | + |
| 40 | + boolean overwrite = commandLine.hasOption('force') || commandLine.hasOption('f') |
| 41 | + |
| 42 | + ZonedDateTime now = ZonedDateTime.now(ZoneId.of('UTC')) |
| 43 | + String migrationNumber = now.format(DateTimeFormatter.ofPattern('yyyyMMddHHmmss')) |
| 44 | + String migrationName = args[1].uncapitalize() |
| 45 | + String migrationFileName = [migrationNumber, migrationName].join('_') + '.groovy' |
| 46 | + |
| 47 | + File changelogFile = new File(baseDir, 'db/migrations/changelog.groovy') |
| 48 | + Map<String, Object> model = new HashMap<>() |
| 49 | + model.put('id', System.currentTimeMillis().toString()) |
| 50 | + |
| 51 | + String migrationFile = 'db/migrations/' + migrationFileName |
| 52 | + createFile('Migration.groovy.tpl', migrationFile, model, overwrite) |
| 53 | + |
| 54 | + if (changelogFile.exists()) { |
| 55 | + String content = changelogFile.text |
| 56 | + changelogFile.text = content.substring(0, content.length() - 3) + |
| 57 | + "\n include file: '${migrationFileName}'\n}\n" |
| 58 | + } |
| 59 | + |
| 60 | + true |
| 61 | + } |
| 62 | + |
| 63 | +} |
0 commit comments