-
Notifications
You must be signed in to change notification settings - Fork 22
/
force-meta-backup.groovy
943 lines (740 loc) · 27.7 KB
/
force-meta-backup.groovy
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
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
@Grab(group='com.force.api', module='force-partner-api', version='60.0.0')
@Grab(group='com.force.api', module='force-metadata-api', version='60.0.0')
import com.sforce.soap.metadata.FileProperties
import com.sforce.soap.metadata.ListMetadataQuery
import com.sforce.soap.metadata.MetadataConnection
import com.sforce.soap.partner.Connector
import com.sforce.soap.partner.PartnerConnection
import com.sforce.ws.ConnectorConfig
import com.sforce.ws.SoapFaultException
import groovy.io.FileType
import groovy.xml.MarkupBuilder
import groovy.xml.StreamingMarkupBuilder
import groovy.xml.XmlUtil
import org.apache.tools.ant.Project
import src.StandardValueSetRegistry
import src.BulkRetrieveMetadataTypeRegistry
class ForceServiceConnector {
static final DEFAULT_API_VERSION = determineDefaultApiVersion()
ConnectorConfig config
def apiVersion
PartnerConnection connection
MetadataConnection metadataConnection
ForceServiceConnector(ConnectorConfig config, String apiVersion) {
this.config = config;
this.apiVersion = apiVersion;
}
PartnerConnection getConnection() {
if (connection == null) {
connection = Connector.newConnection(config)
}
connection
}
MetadataConnection getMetadataConnection() {
if (metadataConnection == null) {
def partnerConfig = getConnection().config
def metadataConfig = new ConnectorConfig().with {
it.sessionId = partnerConfig.sessionId
it.serviceEndpoint = metadataEndpoint(partnerConfig.serviceEndpoint, apiVersion)
it
}
metadataConnection = com.sforce.soap.metadata.Connector.newConnection(metadataConfig)
}
metadataConnection
}
public getApiVersion() {
apiVersion
}
private static String metadataEndpoint(url, apiVersion) {
endpoint url, 'm', apiVersion
}
public static String partnerEndpoint(url, apiVersion) {
endpoint url, 'u', apiVersion
}
private static String endpoint(url, apiType, apiVersion) {
def host = new URI(url).host
"https://$host/services/Soap/$apiType/$apiVersion"
}
private static determineDefaultApiVersion() {
// END_POINT is a URI where the last path segment is the API version
Connector.END_POINT.toURI()
.getPath()
.split('/')
.getAt(-1)
}
}
class ForceService {
final ForceServiceConnector connector
def metadata
def metadataTypes
ForceService(ForceServiceConnector connector) {
this.connector = connector
}
def getConnection() {
connector.connection
}
def getMetadataConnection() {
connector.metadataConnection
}
def getOrganizationId() {
connector.connection.userInfo.organizationId
}
Double getApiVersion() {
connector.apiVersion.toDouble()
}
def isValidMetadataType(type) {
if (metadata == null) {
metadata = basicMetadata()
metadataTypes = []
metadataTypes << metadata.keySet()
metadata.each { k, v ->
v.childNames.each {
if (it) {
metadataTypes << it
}
}
}
metadataTypes = metadataTypes.flatten() as Set
}
metadataTypes.contains(type)
}
def withValidMetadataType(type, Closure closure) {
if (isValidMetadataType(type)) {
closure(type)
} else {
System.err.println "WARNING: $type is an invalid metadata type for this Organisation"
null
}
}
def query(soql) {
def result = []
def queryResult = connection.query soql
if (queryResult.size > 0) {
for (;;) {
queryResult.records.each { result << it }
if (queryResult.isDone()) {
break;
}
queryResult = connection.queryMore queryResult.queryLocator
}
}
result
}
def basicMetadata() {
def metadata = [:]
def result = metadataConnection.describeMetadata(apiVersion)
if (result) {
result.metadataObjects.each { obj ->
def name = obj.xmlName
metadata[name] = [
name: name,
childNames: obj.childXmlNames.collect { it } as Set
]
}
}
metadata
}
def listMetadata(String type) {
listMetadata(type, null)
}
def listMetadata(String type, String folder) {
def query = new ListMetadataQuery()
query.type = type
query.folder = folder
listMetadata([query])
}
def listMetadata(List<ListMetadataQuery> queries) {
final MAX_QUERIES_PER_REQUEST = 3
def numQueries = queries.size()
def isLastQuery = false
def index = 0
def fileProperties = []
while (numQueries > 0 && !isLastQuery) {
def start = index * MAX_QUERIES_PER_REQUEST
def end = start + MAX_QUERIES_PER_REQUEST
if (end > numQueries) {
end = numQueries
}
def requestQueries = queries.subList(start, end) as ListMetadataQuery[]
def result = null
try {
result = metadataConnection.listMetadata(requestQueries, apiVersion)
} catch (SoapFaultException e) {
if (e.faultCode.localPart == 'INVALID_TYPE') {
System.err.println "WARNING: ${e.message}"
} else {
throw e
}
}
if (result != null) {
fileProperties.addAll(result.toList())
}
isLastQuery = (numQueries - (++index * MAX_QUERIES_PER_REQUEST)) < 1
}
fileProperties
}
def listMetadataForTypes(types) {
def queries = types.collect { type ->
withValidMetadataType(type) {
def query = new ListMetadataQuery()
query.type = it
query
}
}
queries.removeAll([null])
listMetadata(queries)
}
}
class ForceServiceFactory {
static final USERNAME_PASSWORD_OR_SESSION_ID = 'You must specify the sf.username/sf.password property pair, or the sf.sessionId property but not both.'
static create(ConfigObject config) {
final flatConfig = config.flatten();
def (username, password, sessionId, serverUrl, apiVersion) = [
'sf.username',
'sf.password',
'sf.sessionId',
'sf.serverurl',
'sf.apiVersion'
].collect { flatConfig.get(it)?.toString() }
def connectorConfig = new ConnectorConfig().with {
it.authEndpoint = ForceServiceConnector.partnerEndpoint(serverUrl, apiVersion)
it
}
if (sessionId) {
// Session ID flow
connectorConfig.sessionId = sessionId
connectorConfig.serviceEndpoint = connectorConfig.authEndpoint
} else if (username || password) {
// Username Password flow
if (!username || !password) {
throw new IllegalArgumentException('You must specify values for both sf.username and sf.password properties')
}
connectorConfig.username = username
connectorConfig.password = password
} else {
throw new IllegalArgumentException(USERNAME_PASSWORD_OR_SESSION_ID)
}
new ForceService(new ForceServiceConnector(connectorConfig, apiVersion))
}
}
class Configuration {
static ConfigObject fromAntProject(Project project) {
def properties = project.getProperties()
ConfigObject config = new ConfigObject()
config.buildDir = properties.get('build.dir')
config.excludeTypes = expandExcludeTypes(properties.remove('sf.excludeTypes'))
// We only want the sessionId or username/password but not both
if (properties.get('sf.sessionId') == null) {
properties.remove('sf.sessionId')
} else {
properties.remove('sf.username')
properties.remove('sf.password')
}
// Copy sf properties to config
final prefix = 'sf.'
properties.keySet()
.findAll { it.startsWith(prefix) }
.collect { it.replace(prefix, "") }
.each { property ->
config.sf[property] = properties.get(prefix + property)
}
config
}
private static Set<String> expandExcludeTypes(String commaSeparatedExcludeTypes) {
def excludeTypes = [] as Set
if (commaSeparatedExcludeTypes) {
excludeTypes.addAll(commaSeparatedExcludeTypes.split(',').collect {
it.trim().toLowerCase()
})
}
excludeTypes
}
}
class FileWriterFactory {
static create(filePath) {
def file = new File(filePath)
def parentFile = file.parentFile
if (parentFile) {
parentFile.mkdirs()
}
new FileWriter(file)
}
}
abstract class ManifestBuilder {
protected def forceService
protected def config
protected ManifestBuilder(forceService, config) {
this.forceService = forceService
this.config = config
}
def isExcluded(metadataType) {
config.excludeTypes.contains(metadataType.toLowerCase())
}
abstract void writeManifest()
}
class BulkMetadataManifestBuilder extends ManifestBuilder {
def buildXmlPath
static final BUILD_XML = 'bulk-retrievable-target.xml'
static final TYPES = new BulkRetrieveMetadataTypeRegistry().getTypes()
BulkMetadataManifestBuilder(ForceService forceService, config) {
super(forceService, config)
buildXmlPath = "$config.buildDir/$BUILD_XML"
}
void writeManifest() {
def writer = FileWriterFactory.create(buildXmlPath)
def builder = new MarkupBuilder(writer)
builder.project('xmlns:sf': 'antlib:com.salesforce', 'default': 'bulkRetrievable') {
'import'(file: '../ant-includes/setup-target.xml')
target(name: 'bulkRetrievable', depends: '-setUpMetadataDir') {
parallel(threadCount: 4) {
TYPES.findAll {
!isExcluded(it)
}.each { type ->
forceService.withValidMetadataType(type) {
'sfBulkRetrieve'(metadataType: type)
}
}
}
}
}
}
}
class Folders extends ManifestBuilder {
def packageXmlPath
def buildXmlPath
static final PACKAGE_XML = 'folders-package.xml'
static final BUILD_XML = 'folders-build.xml'
def folderMetaTypeByFolderType = [
Dashboard: 'Dashboard',
Document: 'Document',
Email: 'EmailTemplate',
Report: 'Report',
Insights: 'Report'
]
Folders(ForceService forceService, config) {
super(forceService, config)
packageXmlPath = "$config.buildDir/$PACKAGE_XML"
buildXmlPath = "$config.buildDir/$BUILD_XML"
}
void writeManifest() {
def allFolders = fetchAllFolders()
def foldersAndUnfiled = [:] + allFolders
def unfiledFetchMap = [
Email: 'fetchUnfiledPublicEmailTemplates',
Report: 'fetchUnfiledPublicReports'
]
unfiledFetchMap.each { folderType, fetchMethod ->
def metadataType = folderMetaTypeByFolderType[folderType]
if (!isExcluded(metadataType)) {
foldersAndUnfiled[folderType] = foldersAndUnfiled[folderType] ?: []
foldersAndUnfiled[folderType] += "$fetchMethod"()
}
}
writeFolderBulkRetriveXml(allFolders)
writeFoldersPackageXml(foldersAndUnfiled)
}
private void writeFoldersPackageXml(foldersAndUnfiled) {
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def xml = builder.bind {
mkp.xmlDeclaration()
Package(xmlns: 'http://soap.sforce.com/2006/04/metadata') {
foldersAndUnfiled.each { folderType, folders ->
types {
folders.each { folderName ->
members folderName
}
name folderMetaTypeByFolderType[folderType]
}
}
version forceService.apiVersion
}
}
def writer = FileWriterFactory.create(packageXmlPath)
XmlUtil.serialize(xml, writer)
}
private void writeFolderBulkRetriveXml(allFolders) {
def writer = FileWriterFactory.create(buildXmlPath)
def builder = new MarkupBuilder(writer)
builder.project('xmlns:sf': 'antlib:com.salesforce', 'default': 'bulkRetrieveFolders') {
'import'(file: '../ant-includes/setup-target.xml')
target(name: 'bulkRetrieveFolders', depends: '-setUpMetadataDir') {
parallel(threadCount: 4) {
'sfRetrieve'(unpackaged: packageXmlPath)
allFolders.each { folderType, folders ->
folders.each { folderName ->
def type = folderMetaTypeByFolderType[folderType]
'sfBulkRetrieve'(metadataType: type, containingFolder: folderName)
}
}
}
}
}
}
private fetchAllFolders() {
def folderTypes = folderMetaTypeByFolderType.keySet()
def soql = "SELECT NamespacePrefix, DeveloperName, Type FROM Folder WHERE DeveloperName != '' AND Type IN ('${folderTypes.join("', '")}') ORDER BY Type, NamespacePrefix, DeveloperName"
def sObjects = forceService.query soql
def folders = [:]
sObjects.each {
def prefix = it.getField('NamespacePrefix')
prefix = (prefix == null) ? '' : prefix + '__'
def name = it.getField('DeveloperName')
def type = it.getField('Type')
if (!folders.containsKey(type)) {
folders[type] = []
}
folders[type] << "$prefix$name"
}
folderMetaTypeByFolderType.each { folderType, metadataType ->
if (isExcluded(metadataType)) {
folders.remove(folderType)
}
}
folders
}
private fetchUnfiledPublicEmailTemplates() {
def soql = "SELECT DeveloperName FROM EmailTemplate WHERE FolderId = '$forceService.organizationId'"
fetchUnfiled soql
}
private fetchUnfiledPublicReports() {
def soql = "SELECT DeveloperName FROM Report WHERE OwnerId = '$forceService.organizationId'"
fetchUnfiled soql
}
private fetchUnfiled(soql) {
def sObjects = forceService.query soql
// Unfiled Public folders are not real folders in that there is no
// folder object in the Folders table, instead the OrganisationId is
// used as the Folder/Owner and this is what makes it unfiled.
// There is no direct metadata approach to get this so building this from
// queries to get list of unfiled components.
def folder = 'unfiled$public';
def unfiled = [folder]
sObjects.each {
def name = it.getField('DeveloperName')
unfiled << "$folder/$name"
}
unfiled
}
}
class MiscMetadataManifestBuilder extends ManifestBuilder {
def packageXmlPath
static final PACKAGE_XML = 'misc-package.xml'
static final TYPES = [
'StandardValueSet',
]
static final WILDCARD_TYPES = [
'ApexComponent',
'ApexTrigger',
'AuraDefinitionBundle',
'LightningComponentBundle',
'StandardValueSetTranslation',
]
static final STANDARD_VALUE_SET_NAMES = new StandardValueSetRegistry().getValueSetNames();
MiscMetadataManifestBuilder(ForceService forceService, config) {
super(forceService, config)
packageXmlPath = "$config.buildDir/$PACKAGE_XML"
}
private getGroupedFileProperties() {
def grouped = new GroupedFileProperties(
forceService.listMetadataForTypes(TYPES)
)
// XXX - Hack to always retrieve the CaseComment SObject & Workflow.
//
// For some reason CaseComment is not returned in listMetadata()
// calls for CustomObject and Workflow but if we explicitly put
// these in package.xml for retrieve we can download them.
grouped.addIfMissingStandard('Workflow', 'CaseComment')
// XXX - Salesforce does not return names for type StandardValueSet
// when we call listMetdata(). Adding hardcoded list of names
// as workaround
STANDARD_VALUE_SET_NAMES.each {
grouped.addIfMissingStandard('StandardValueSet', it)
}
grouped.sort()
grouped.filePropertiesByType.findAll {
!isExcluded(it.key)
}
}
void writeManifest() {
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def xml = builder.bind {
mkp.xmlDeclaration()
Package(xmlns: 'http://soap.sforce.com/2006/04/metadata') {
groupedFileProperties.each { type, fileProperties ->
types {
fileProperties.each { fp ->
members fp.fullName
}
name type
}
}
WILDCARD_TYPES.findAll {
!isExcluded(it)
}.each { type ->
types {
members '*'
name type
}
}
version forceService.apiVersion
}
}
def writer = FileWriterFactory.create(packageXmlPath)
XmlUtil.serialize(xml, writer)
}
}
class GroupedFileProperties {
static final String NO_NAMESPACE = null;
static final String STANDARD_NAMESPACE = '';
def filePropertiesByType = [:] as TreeMap
GroupedFileProperties() {
}
GroupedFileProperties(List<FileProperties> fileProperties) {
addAll(fileProperties)
}
GroupedFileProperties addAll(List<FileProperties> fileProperties) {
fileProperties.each { fp ->
add(fp)
}
this
}
GroupedFileProperties add(FileProperties fp) {
if (!containsGroup(fp.type)) {
filePropertiesByType[fp.type] = []
}
filePropertiesByType[fp.type] << fp
this
}
GroupedFileProperties addIfMissingStandard(String type, String fullName) {
addIfMissing(type, fullName, STANDARD_NAMESPACE)
}
GroupedFileProperties addIfMissingCustom(String type, String fullName) {
addIfMissing(type, fullName, NO_NAMESPACE)
}
GroupedFileProperties addIfMissing(String type, String fullName, String namespacePrefix) {
addIfMissing([
type: type,
fullName: fullName,
namespacePrefix: namespacePrefix
] as FileProperties)
}
GroupedFileProperties addIfMissing(FileProperties fp) {
if (!contains(fp.type, fp.fullName, fp.namespacePrefix)) {
add(fp)
}
this
}
Boolean containsGroup(String type) {
filePropertiesByType.containsKey(type)
}
Boolean contains(String type, String fullName, String namespacePrefix) {
containsGroup(type) && filePropertiesByType[type].find {
it.fullName == fullName &&
it.namespacePrefix == namespacePrefix
}
}
void sort() {
filePropertiesByType.each { k, v ->
v.sort { FileProperties a, FileProperties b ->
a.namespacePrefix <=> b.namespacePrefix ?: a.fullName <=> b.fullName
}
}
}
}
class ProfilesMetadataManifestBuilder extends ManifestBuilder {
def groupedFileProps
static final TYPES = [
'ApexClass',
'ApexPage',
'CustomApplication',
'CustomObject',
'CustomObjectTranslation',
'CustomPermission',
'CustomTab',
'ExternalDataSource',
'Layout'
]
ProfilesMetadataManifestBuilder(ForceService forceService, config) {
super(forceService, config)
}
private getGroupedFileProperties() {
if (groupedFileProps == null) {
def listMetadata = forceService.listMetadataForTypes(TYPES)
listMetadata.removeAll { fileProperties ->
// Filter out ApexClasses from managed packages, these are all (hidden) anyway
// and in large Orgs can be more than 10000 components causing LIMIT_EXCEPTION
// on retrieval
fileProperties.type == 'ApexClass' && fileProperties.namespacePrefix != null
}
def grouped = new GroupedFileProperties(listMetadata)
// XXX - Hack to always retrieve the CaseComment SObject & Workflow.
//
// For some reason CaseComment is not returned in listMetadata()
// calls for CustomObject and Workflow but if we explicitly put
// these in package.xml for retrieve we can download them.
grouped.addIfMissingStandard('CustomObject', 'CaseComment')
grouped.sort()
groupedFileProps = grouped.filePropertiesByType.findAll {
!isExcluded(it.key)
}
}
groupedFileProps
}
void writeManifest() {
groupedFileProperties.each { type, fileProperties ->
writePackageXmlForType type, fileProperties
}
writeBuildXml()
}
private void writePackageXmlForType(type, fileProperties) {
def builder = new StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
def resolveName = { FileProperties fp ->
fp.fullName
}
def WILDCARD_TYPES = ['Profile']
if (type == 'Layout') {
// Note: Page Layout assignments require Layouts & RecordType to be retrieved with Profile
WILDCARD_TYPES << 'RecordType'
// Layouts in managed pacakges must have namespace prefix
resolveName = { FileProperties fp ->
if (fp.namespacePrefix) {
def namespace = fp.namespacePrefix + '__'
def seperator = '-'
return fp.fullName.replace(seperator, seperator + namespace)
}
fp.fullName
}
}
def xml = builder.bind {
mkp.xmlDeclaration()
Package(xmlns: 'http://soap.sforce.com/2006/04/metadata') {
types {
fileProperties.each { fp ->
members resolveName(fp)
}
name type
}
WILDCARD_TYPES.each { metadataType ->
types {
members '*'
name metadataType
}
}
version { mkp.yield forceService.apiVersion }
}
}
def writer = FileWriterFactory.create(profilePackageXmlPath(type))
XmlUtil.serialize(xml, writer)
}
private profilePackageXmlPath(type) {
"${config.buildDir}/profile-packages/${type}.xml"
}
private writeBuildXml() {
def writer = FileWriterFactory.create("${config.buildDir}/profile-packages-target.xml")
def builder = new MarkupBuilder(writer)
def targetName = 'profilesPackageRetrieve'
builder.project('xmlns:sf': 'antlib:com.salesforce', 'default': targetName) {
'import'(file: '../ant-includes/setup-target.xml')
target(name: targetName, depends: '-setUpMetadataDir') {
parallel(threadCount: 4) {
groupedFileProperties.each { type, fileProperties ->
def retrieveTarget = "${config.buildDir}/profile-packages-metadata/$type"
forceService.withValidMetadataType(type) {
'sfRetrieveToFolder'(
unpackaged: profilePackageXmlPath(type),
retrieveTarget: retrieveTarget
)
}
}
}
}
}
}
}
class XmlMergeTargetBuilder {
def config
def srcDir
XmlMergeTargetBuilder(config) {
this.config = config
srcDir = "${config.buildDir}/profile-packages-metadata"
}
private getProfiles() {
def profiles = new TreeSet()
def dir = new File(srcDir)
dir.eachFileRecurse (FileType.FILES) { file ->
if (file.name ==~ /.+\.profile$/) {
profiles << file.name
}
}
profiles
}
private writeBuildXml() {
def writer = FileWriterFactory.create("${config.buildDir}/profile-packages-merge-target.xml")
def builder = new MarkupBuilder(writer)
def targetName = 'profilesPackageXmlMerge'
def metadataDir = "${config.buildDir}/metadata"
builder.project('default': targetName) {
'import'(file: '../ant-includes/setup-target.xml')
target(name: targetName) {
def destDir = "$metadataDir/profiles"
mkdir(dir: destDir)
parallel(threadCount: 1) {
profiles.each { filename ->
sequential {
echo "Xml Merging: $filename"
xmlmerge(dest: "$destDir/$filename", conf: 'xmlmerge.properties') {
fileset(dir: srcDir) {
include(name: "**/$filename")
}
}
}
}
}
// TODO maybe we can dynamically build this list of folders/files to be copied
copy(todir: metadataDir) {
fileset(dir: srcDir) {
include(name: '**/classes/*')
include(name: '**/pages/*')
include(name: '**/applications/*')
include(name: '**/objects/*')
include(name: '**/objectTranslations/*')
include(name: '**/customPermissions/*');
include(name: '**/tabs/*')
include(name: '**/layouts/*')
include(name: '**/dataSources/*')
}
cutdirsmapper(dirs: 1)
}
}
}
}
}
////////////////////////////////////////////////////////////////////////////////
class MetadataBackupTool {
final ForceService forceService;
final def config = config;
static MetadataBackupTool forProject(Project p) {
new MetadataBackupTool(Configuration.fromAntProject(p))
}
MetadataBackupTool(config) {
this.config = config
forceService = ForceServiceFactory.create(config)
}
String getSalesforceSessionId() {
"${forceService.connection.config.sessionId}"
}
void generateXmlMergeTarget() {
new XmlMergeTargetBuilder(config).writeBuildXml()
}
void generateMetadataRetrievalManifests() {
[
new BulkMetadataManifestBuilder(forceService, config),
new Folders(forceService, config),
new MiscMetadataManifestBuilder(forceService, config),
new ProfilesMetadataManifestBuilder(forceService, config)
].each { it.writeManifest() }
}
}