-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathmigrate.groovy
More file actions
executable file
·289 lines (240 loc) · 10.9 KB
/
migrate.groovy
File metadata and controls
executable file
·289 lines (240 loc) · 10.9 KB
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
#!/usr/bin/env groovy
/*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* Migration script for migrating legacy content using an AEM Content Package
* See: https://github.com/PerficientDigital/AEM-Migration-Script
*/
@Grab('com.xlson.groovycsv:groovycsv:1.3')
import static com.xlson.groovycsv.CsvParser.parseCsv
@Grab('org.apache.tika:tika-core:1.14')
import org.apache.tika.Tika;
import groovy.io.FileType
import groovy.xml.MarkupBuilder
import groovy.json.JsonSlurper
import groovy.time.TimeCategory
import groovy.time.TimeDuration
import groovy.transform.Field
import groovy.ant.AntBuilder
import groovy.xml.XmlSlurper
import java.nio.file.Files
import java.nio.file.StandardCopyOption
// configure settings here
@Field
final SEPARATOR = ","
@Field
final ENCODING = "UTF-8"
start = new Date()
if(args.length < 1) {
println 'groovy migrate.groovy [configdir] [batch (Optional)]'
System.exit(1)
}
batch = ""
if(args.length == 2) {
batch = args[1]
println "Using batch ${batch}"
}
Map loadReplacements() {
def count = 0
def cf = new File("work${File.separator}config${File.separator}replacement-config.json")
assert cf.exists()
def slurper = new JsonSlurper()
def config = slurper.parseText(cf.text)
def replacements = [:]
config.each{file,cfgs->
println "Processing replacements for ${file}..."
def sf = new File("work${File.separator}config${File.separator}${file}")
assert sf.exists()
cfgs.each{cfg ->
println "Processing configuration: ${cfg}"
def source = parseCsv(sf.getText(ENCODING), separator: SEPARATOR)
for (line in source) {
if(cfg.mode == 'mapping'){
replacements[line[cfg.sourceKey]] = line[cfg.targetKey]
} else {
def key = line[cfg.sourceKey]
if(cfg.targetKey){
replacements[key.replaceAll(cfg.extractionPattern, cfg.sourceReplacement)] = line[cfg.targetKey]
} else {
replacements[key.replaceAll(cfg.extractionPattern, cfg.sourceReplacement)] = key.replaceAll(cfg.extractionPattern, cfg.targetReplacement)
}
}
count++
}
}
}
println "Generated ${count} replacements in ${TimeCategory.minus(new Date(), start)}"
return replacements
}
Map loadTemplates() {
println 'Loading templates...'
def count = 0
def templates = [:]
GroovyShell shell = new GroovyShell()
new File('templates').eachFile (FileType.FILES) { template ->
if(!template.getName().startsWith('.') && template.getName().endsWith('groovy')){
def name = template.getName().replace('.groovy','')
println "Loading template $template as $name"
templates[name] = shell.parse(template)
count++
}
}
println "Loaded ${count} templates in ${TimeCategory.minus(new Date(), start)}"
return templates
}
void processPages(File source, File jcrRoot) {
def templates = loadTemplates()
def replacements = loadReplacements()
def pageFile = new File("work${File.separator}config${File.separator}page-mappings.csv")
def count = 0
def migrated = 0
println 'Processing pages...'
for (pageData in parseCsv(pageFile.getText(ENCODING), separator: SEPARATOR)) {
println "Processing page ${count + 1}"
def process = true
if(batch?.trim() && !batch.equals(pageData['Batch'])){
process = false
}
if('Remove' == pageData[0] || 'Missing' == pageData[0]) {
process = false
}
if(process){
def template = templates[pageData['Template']]
assert template : "Template ${pageData['Template']} not found!"
def sourceFile = new File(pageData['Source Path'],source)
assert sourceFile.exists() : "Source file ${sourceFile} not found!"
println "Using template ${pageData['Template']} for ${sourceFile}"
def inXml = new XmlSlurper().parseText(sourceFile.getText(ENCODING))
def writer = new StringWriter()
def outXml = new MarkupBuilder(writer)
println 'Rendering page...'
template.renderPage(pageData, inXml, outXml, replacements)
println 'Creating parent folder...'
def targetFile = new File("${pageData['New Path']}${File.separator}.content.xml",jcrRoot)
targetFile.getParentFile().mkdirs()
println "Writing results to $targetFile"
targetFile.write(writer.toString(),ENCODING)
migrated++
} else {
println 'No action required...'
}
count++
}
println "${count} pages processed and ${migrated} migrated in ${TimeCategory.minus(new Date(), start)}"
}
void processFiles(File source, File jcrRoot){
def contentXml = '''<?xml version="1.0" encoding="UTF-8"?>
<jcr:root xmlns:exif="http://ns.adobe.com/exif/1.0/" xmlns:photoshop="http://ns.adobe.com/photoshop/1.0/" xmlns:tiff="http://ns.adobe.com/tiff/1.0/" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmlns:xmpMM="http://ns.adobe.com/xap/1.0/mm/" xmlns:stEvt="http://ns.adobe.com/xap/1.0/sType/ResourceEvent#" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:dam="http://www.day.com/dam/1.0" xmlns:cq="http://www.day.com/jcr/cq/1.0" xmlns:jcr="http://www.jcp.org/jcr/1.0" xmlns:mix="http://www.jcp.org/jcr/mix/1.0" xmlns:nt="http://www.jcp.org/jcr/nt/1.0"
jcr:primaryType="dam:Asset">
<jcr:content
jcr:primaryType="dam:AssetContent">
<metadata
jcr:primaryType="nt:unstructured"/>
<related jcr:primaryType="nt:unstructured"/>
</jcr:content>
</jcr:root>
'''
def tika = new Tika()
def files = new File("work${File.separator}config${File.separator}file-mappings.csv")
def count = 0
def migrated = 0
println 'Processing files...'
for (fileData in parseCsv(files.getText(ENCODING), separator: SEPARATOR)) {
def assetRoot = new File(fileData['Target'], jcrRoot)
def sourceFile = new File(fileData['Source'], source)
def mimeType = tika.detect(sourceFile)
println "Processing Source: ${sourceFile} Target: ${assetRoot}"
println 'Creating original.dir XML...'
def writer = new StringWriter()
def originalDirXml = new MarkupBuilder(writer)
originalDirXml.'jcr:root'('xmlns:jcr':'http://www.jcp.org/jcr/1.0','xmlns:nt':'http://www.jcp.org/jcr/nt/1.0','jcr:primaryType':'nt:file'){
'jcr:content'('jcr:mimeType': mimeType, 'jcr:primaryType': 'nt:resource')
}
def originalDir = new File("_jcr_content${File.separator}renditions${File.separator}original.dir${File.separator}.content.xml",assetRoot)
originalDir.getParentFile().mkdirs()
originalDir.newWriter().withWriter { w ->
w << writer.toString()
}
println 'Copying original file...'
Files.copy(sourceFile.toPath(), new File("_jcr_content${File.separator}renditions${File.separator}original",assetRoot).toPath(),StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES)
println 'Writing .content.xml...'
new File('.content.xml',assetRoot).newWriter().withWriter { w ->
w << contentXml
}
}
}
def configDir = new File(args[0])
assert configDir.exists()
println 'Copying configuration to work dir...'
def workConfig = new File("work${File.separator}config")
if(!workConfig.exists()){
workConfig.mkdirs()
}
configDir.eachFile (FileType.FILES) { file ->
Files.copy(file.toPath(), new File(workConfig.getAbsolutePath()+File.separator+file.getName()).toPath(),StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES)
}
def base = new File('work')
def source = new File('source',base)
println "Using source: ${source}"
def target = new File('target',base)
def jcrRoot = new File('jcr_root',target)
println "Using target: ${target}"
println 'Clearing target...'
target.deleteDir();
target.mkdir();
processPages(source,jcrRoot)
processFiles(source,jcrRoot)
println 'Updating filter.xml...'
def vlt = new File("META-INF${File.separator}vault",target)
vlt.mkdirs()
if(batch?.trim()){
def writer = new StringWriter()
def filterXml = new MarkupBuilder(writer)
def pageFile = new File("work${File.separator}config${File.separator}page-mappings.csv")
filterXml.'workspaceFilter'('version':'1.0'){
for (pageData in parseCsv(pageFile.getText(ENCODING), separator: SEPARATOR)) {
if(batch.equals(pageData['Batch']) && 'Remove' != pageData[0] && 'Missing' != pageData[0]){
'filter'('root':pageData['New Path']){
'include'('pattern':pageData['New Path'])
'include'('pattern':"${pageData['New Path']}/jcr:content.*")
}
}
}
for (fileData in parseCsv(new File("work${File.separator}config${File.separator}file-mappings.csv").getText(ENCODING), separator: SEPARATOR)) {
if(batch.equals(fileData['Batch']) && 'Remove' != fileData[0] && 'Missing' != fileData[0]){
'filter'('root':fileData['Target']){
'include'('pattern':fileData['Target'])
'include'('pattern':"${fileData['Target']}/jcr:content.*")
}
}
}
}
new File('filter.xml',vlt) << writer.toString()
} else {
def filter = new File('filter.xml',workConfig)
assert filter.exists()
Files.copy(filter.toPath(), new File('filter.xml',vlt).toPath(),StandardCopyOption.REPLACE_EXISTING,StandardCopyOption.COPY_ATTRIBUTES)
}
def now = new Date().format("yyyy-MM-dd-HH-mm-ss")
println 'Updating properties.xml...'
def propertiesXml = new File('properties.xml',workConfig)
assert propertiesXml.exists()
new File('properties.xml',vlt) << propertiesXml.getText().replace('${version}',now).replace('${name}',"migrated-content-${configDir.getName()}")
println 'Creating package...'
def ant = new AntBuilder()
ant.zip(destfile: "${base.getAbsolutePath()}${File.separator}migrated-content-${configDir.getName()}-${now}.zip", basedir: target)
println "Package saved to: work${File.separator}migrated-content-${configDir.getName()}-${now}.zip"
println "Content migrated in ${TimeCategory.minus(new Date(), start)}"
println "Package created successfully!!!"