-
Notifications
You must be signed in to change notification settings - Fork 204
/
build.gradle
1280 lines (1166 loc) · 67.4 KB
/
build.gradle
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
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* This software is in the public domain under CC0 1.0 Universal plus a
* Grant of Patent License.
*
* To the extent possible under law, the author(s) have dedicated all
* copyright and related and neighboring rights to this software to the
* public domain worldwide. This software is distributed without any
* warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication
* along with this software (see the LICENSE.md file). If not, see
* <http://creativecommons.org/publicdomain/zero/1.0/>.
*/
buildscript {
repositories {
mavenCentral()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies { classpath 'org.ajoberstar.grgit:grgit-gradle:5.0.0' }
}
// Not needed for explicit use, causes problems when not from git repo: plugins { id 'org.ajoberstar.grgit' version 'x.y.z' }
// Run headless so GradleWorkerMain does not steal focus (mostly a macOS annoyance)
allprojects { tasks.withType(JavaForkOptions) { jvmArgs '-Djava.awt.headless=true' } }
import org.ajoberstar.grgit.*
defaultTasks 'build'
def openSearchVersion = '2.4.0'
def elasticSearchVersion = '7.10.2'
def tomcatHome = '../apache-tomcat'
// no longer include version in war file name: def getWarName() { 'moqui-' + childProjects.framework.version + '.war' }
def getWarName() { 'moqui.war' }
def plusRuntimeName = 'moqui-plus-runtime.war'
def execTempDir = 'execwartmp'
def moquiRuntime = 'runtime'
def moquiConfDev = 'conf/MoquiDevConf.xml'
def moquiConfProduction = 'conf/MoquiProductionConf.xml'
def allCleanTasks = getTasksByName('clean', true)
def allBuildTasks = getTasksByName('build', true)
def allTestTasks = getTasksByName('test', true)
allTestTasks.each { it.systemProperties << System.properties.subMap(getDefaultPropertyKeys()) }
// kill the build -> check -> test dependency, only run tests explicitly and not always on build
getTasksByName('check', true).each { it.dependsOn.clear() }
Set<Task> getComponentTestTasks() {
Set<Task> testTasks = new LinkedHashSet()
for (Project subProject in getSubprojects())
if (subProject.getPath().startsWith(':runtime:component:')) testTasks.addAll(subProject.getTasksByName('test', false))
return testTasks
}
def getDefaultPropertyKeys() {
def defaultProperties = []
Node confXml = new XmlParser().parse(file('framework/src/main/resources/MoquiDefaultConf.xml'))
for (Node defaultProperty in confXml.'default-property') { defaultProperties << defaultProperty.'@name' }
defaultProperties
}
// ========== clean tasks ==========
task clean(type: Delete) { delete file(warName); delete file(execTempDir); delete file('wartemp'); cleanVersionDetailFiles() }
task cleanTempDir(type: Delete) { delete file(execTempDir) }
task cleanDb { doLast {
if (!file(moquiRuntime).exists()) return
delete files(file(moquiRuntime+'/db/derby').listFiles()) - files(moquiRuntime+'/db/derby/derby.properties')
delete file(moquiRuntime+'/db/h2')
delete file(moquiRuntime+'/db/orientdb/databases')
delete fileTree(dir: moquiRuntime+'/txlog', include: '*')
cleanElasticSearch(moquiRuntime)
} }
task cleanLog(type: Delete) { delete fileTree(dir: moquiRuntime+'/log', include: '*') }
task cleanSessions(type: Delete) { delete fileTree(dir: moquiRuntime+'/sessions', include: '*') }
task cleanLoadSave(type: Delete) { delete file('SaveH2.zip'); delete file('SaveDEFAULT.zip')
delete file('SaveTransactional.zip'); delete file('SaveAnalytical.zip'); delete file('SaveOrientDb.zip')
delete file('SaveElasticSearch.zip'); delete file('SaveOpenSearch.zip') }
task cleanPlusRuntime(type: Delete) { delete file(plusRuntimeName) }
task cleanOther(type: Delete) { delete fileTree(dir: '.', includes: ['**/.nbattrs', '**/*~', '**/.#*', '**/.DS_Store', '**/*.rej', '**/*.orig']) }
task cleanAll { dependsOn clean, allCleanTasks, cleanDb, cleanLog, cleanSessions, cleanLoadSave, cleanPlusRuntime }
// ========== ElasticSearch tasks (for install in runtime/elasticsearch) ==========
def cleanElasticSearch(String moquiRuntime) {
File osDir = file(moquiRuntime + '/opensearch')
String workDir = moquiRuntime + (osDir.exists() ? '/opensearch' : '/elasticsearch')
if (file(workDir+'/bin').exists()) {
def pidFile = file(workDir+'/pid')
if (pidFile.exists()) {
String pid = pidFile.getText()
logger.lifecycle("${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} running with pid ${pid}, stopping before deleting data then restarting")
exec { workingDir workDir; commandLine 'kill', pid }
exec { workingDir workDir; commandLine 'tail', "--pid=${pid}", '-f', '/dev/null' }
delete file(workDir+'/data')
if (file(workDir+'/logs').exists()) delete files(file(workDir+'/logs').listFiles())
if (pidFile.exists()) delete pidFile
startSearch()
} else {
logger.lifecycle("Found ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} in ${workDir}/bin directory but no pid, deleting data without stop/start; WARNING if ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} is running this will cause problems!")
delete file(workDir+'/data')
if (file(workDir+'/logs').exists()) delete files(file(workDir+'/logs').listFiles())
}
} else {
delete file(workDir+'/data')
if (file(workDir+'/logs').exists()) delete files(file(workDir+'/logs').listFiles())
}
}
task downloadOpenSearch { doLast {
// NOTE: works with Linux and macOS
// TODO: Windows support...
String distType = "tar.gz"
// https://artifacts.opensearch.org/releases/core/opensearch/1.3.1/opensearch-min-1.3.1-linux-x64.tar.gz
String esUrl = "https://artifacts.opensearch.org/releases/core/opensearch/${openSearchVersion}/opensearch-min-${openSearchVersion}-linux-x64.${distType}"
String targetDirPath = moquiRuntime + '/opensearch'
String esExtraDirPath = targetDirPath + '/opensearch-' + openSearchVersion
File targetDir = file(targetDirPath)
if (targetDir.exists()) { logger.lifecycle("Found directory at ${targetDirPath}, deleting"); delete targetDir }
File zipFile = file("${moquiRuntime}/opensearch-min-${openSearchVersion}-linux-x64.${distType}")
if (!zipFile.exists()) {
logger.lifecycle("Downloading OpenSearch from ${esUrl}")
ant.get(src: esUrl, dest: zipFile)
} else {
logger.lifecycle("Found OpenSearch archive at ${zipFile.getPath()}, using that instead of downloading")
}
// the eachFile closure removes the first path from each file, moving everything up a directory, which also requires delete of the extra dirs
copy { from distType == "zip" ? zipTree(zipFile) : tarTree(zipFile); into targetDir; eachFile {
def pathList = it.getRelativePath().getSegments() as List
if (pathList[0] == ".") pathList = pathList.tail()
it.setPath(pathList.tail().join("/"))
return it
} }
// make sure there is a logs directory, OpenSearch (just like ES) has start error without it
File esLogsDir = file(targetDirPath + '/logs')
if (!esLogsDir.exists()) esLogsDir.mkdir()
File extraDir = file(esExtraDirPath)
if (extraDir.exists()) delete extraDir
delete zipFile
}}
task downloadElasticSearch { doLast {
String suffix
String distType
String osName = System.getProperty("os.name").toLowerCase()
if (osName.startsWith("windows")) {
suffix = "windows-x86_64.zip"
distType = "zip"
} else if (osName.startsWith("mac")) {
suffix = "darwin-x86_64.tar.gz"
distType = "tar.gz"
} else {
suffix = "linux-x86_64.tar.gz"
distType = "tar.gz"
}
String esUrl = "https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-oss-${elasticSearchVersion}-no-jdk-${suffix}"
String targetDirPath = moquiRuntime + '/elasticsearch'
String esExtraDirPath = targetDirPath + '/elasticsearch-' + elasticSearchVersion
File targetDir = file(targetDirPath)
if (targetDir.exists()) { logger.lifecycle("Found directory at ${targetDirPath}, deleting"); delete targetDir }
File zipFile = file("${targetDirPath}-${elasticSearchVersion}.${distType}")
if (!zipFile.exists()) {
logger.lifecycle("Downloading ElasticSearch from ${esUrl}")
ant.get(src: esUrl, dest: zipFile)
} else {
logger.lifecycle("Found ElasticSearch archive at ${zipFile.getPath()}, using that instead of downloading")
}
// the eachFile closure removes the first path from each file, moving everything up a directory, which also requires delete of the extra dirs
copy { from distType == "zip"? zipTree(zipFile) : tarTree(zipFile); into targetDir; eachFile {
def pathList = it.getRelativePath().getSegments() as List
if (pathList[0] == ".") pathList = pathList.tail()
it.setPath(pathList.tail().join("/"))
return it
} }
// make sure there is a logs directory, ES start error without it
File esLogsDir = file(targetDirPath + '/logs')
if (!esLogsDir.exists()) esLogsDir.mkdir()
File extraDir = file(esExtraDirPath)
if (extraDir.exists()) delete extraDir
delete zipFile
}}
/* startElasticSearch old approach, with ES 7.10.2 and OpenSearch never exits, gradle just sits there doing nothing (though same command in terminal does exit)
task startElasticSearch(type:Exec) {
File osDir = file(moquiRuntime + '/opensearch')
workingDir moquiRuntime + (osDir.exists() ? '/opensearch' : '/elasticsearch')
commandLine (osDir.exists() ? ['./bin/opensearch', '-d', '-p', 'pid'] : ['./bin/elasticsearch', '-d', '-p', 'pid'])
ignoreExitValue true
onlyIf { (file(moquiRuntime + '/elasticsearch/bin').exists() || file(moquiRuntime + '/opensearch/bin').exists())
&& !file(moquiRuntime + '/elasticsearch/pid').exists() && !file(moquiRuntime + '/opensearch/pid').exists() }
doFirst {
logger.lifecycle("Starting ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} installed in runtime/${osDir.exists() ? 'opensearch' : 'elasticsearch'}")
}
}
*/
void startSearch(String moquiRuntime) {
File osDir = file(moquiRuntime + '/opensearch')
String workDir = moquiRuntime + (osDir.exists() ? '/opensearch' : '/elasticsearch')
def pidFile = file(workDir + '/pid')
def binFile = file(workDir + '/bin')
if (binFile.exists() && !pidFile.exists()) {
logger.lifecycle("Starting ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} installed in ${workDir}")
ProcessBuilder pb = new ProcessBuilder((osDir.exists() ? './bin/opensearch' : './bin/elasticsearch'), '-d', '-p', 'pid')
pb.directory(file(workDir))
pb.redirectOutput()
pb.redirectError()
pb.inheritIO()
logger.lifecycle("Starting process with command ${pb.command()} in ${pb.directory().path}")
try {
Process proc = pb.start()
// logger.lifecycle("ran start waiting...")
int result = proc.waitFor()
logger.lifecycle("Process finished with ${result}")
} catch (Exception e) {
logger.lifecycle("Error starting ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'}", e)
}
} else {
if (pidFile.exists()) logger.lifecycle("Not Starting ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} installed in ${workDir}, pid file already exists")
if (!binFile.exists()) logger.lifecycle("Not Starting ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'}, no ${workDir}/bin directory found")
}
}
task startElasticSearch { doLast {
startSearch(moquiRuntime)
} }
void stopSearch(String moquiRuntime) {
File osDir = file(moquiRuntime + '/opensearch')
String workDir = moquiRuntime + (osDir.exists() ? '/opensearch' : '/elasticsearch')
def pidFile = file(workDir + '/pid')
def binFile = file(workDir + '/bin')
if (pidFile.exists() && binFile.exists()) {
String pid = pidFile.getText()
logger.lifecycle("Stopping ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} installed in ${workDir} with pid ${pid}")
exec { workingDir workDir; commandLine 'kill', pid }
// don't bother waiting in this case: exec { workingDir esDir; commandLine 'tail', "--pid=${pid}", '-f', '/dev/null' }
if (pidFile.exists()) delete pidFile
} else {
if (!pidFile.exists()) logger.lifecycle("Not Stopping ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} installed in ${workDir}, no pid file found")
if (!binFile.exists()) logger.lifecycle("Not Stopping ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'}, no ${workDir}/bin directory found")
}
}
task stopElasticSearch { doLast {
stopSearch(moquiRuntime)
} }
// ========== development tasks ==========
task setupIntellij {
description "Adds all XML catalog items to intellij to enable autocomplete"
doLast {
def ideaDir = "${rootDir}/.idea"
def parser = new XmlSlurper()
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false)
parser.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false)
def catalogEntries = parser.parse(file("${rootDir}/framework/xsd/framework-catalog.xml"))
.system
.list()
.stream()
.map { [url: it.@systemId, location: "\$PROJECT_DIR\$/framework/xsd/${it.@uri}"] }
.collect(java.util.stream.Collectors.toList())
mkdir ideaDir
def rawXml
def miscFile = file("${ideaDir}/misc.xml")
if (!miscFile.exists()) {
def builder = new groovy.xml.StreamingMarkupBuilder()
builder.encoding = 'UTF-8'
rawXml = builder.bind {
project(version: '4') {
component(name: 'ExternalStorageConfigurationManager', enabled: true)
component(name: 'ProjectResources') {
catalogEntries.each { resource(url: it.url, location: it.location) }
}
}
}
} else {
def projectNode = parser.parse(miscFile)
def resourcesNode = projectNode.children().find { it.@name == 'ProjectResources' }
if (resourcesNode.size() == 0) {
projectNode.appendNode {
component(name: 'ProjectResources') {
catalogEntries.each { resource(url: it.url, location: it.location) }
}
}
} else {
catalogEntries.each { cat ->
def existingEntry = resourcesNode.children().find { it.@url == cat.url }
if (existingEntry.size() > 0) {
existingEntry.replaceNode { resource(url: cat.url, location: cat.location) }
} else {
resourcesNode.appendNode { resource(url: cat.url, location: cat.location) }
}
}
}
rawXml = projectNode
}
def misc = groovy.xml.XmlUtil.serialize(rawXml)
miscFile.write(misc)
}
}
// ========== test task ==========
// NOTE1: to run startElasticSearch before the first test task add it as a dependency to all test tasks
// NOTE2: to run stopElasticSearch after the last test task make all test tasks finalizedBy stopElasticSearch
getTasksByName('test', true).each {
if (it.path != ':test') {
// logger.lifecycle("Adding dependencies for test task ${it.getPath()}")
it.dependsOn(startElasticSearch)
it.finalizedBy(stopElasticSearch)
}
}
// ========== check/update tasks ==========
task getRuntime {
description "If the runtime directory does not exist get it using settings in myaddons.xml or addons.xml; also check default components in myaddons.xml (addons.@default) and download any missing"
doLast { checkRuntimeDirAndDefaults(project.hasProperty('locationType') ? locationType : null) }
}
task checkRuntime { doLast {
if (!file('runtime').exists()) throw new GradleException("Required 'runtime' directory not found. Use 'gradle getRuntime' or 'gradle getComponent' or manually clone the moqui-runtime repository. This must be done in a separate Gradle run before a build so Gradle can find and run build tasks.")
} }
task gitPullAll {
description "Do a git pull to update moqui, runtime, and each installed component (for each where a .git directory is found)"
doLast {
// framework and runtime
if (file(".git").exists()) { doGitPullWithStatus(file('.').path) }
if (file("runtime/.git").exists()) { doGitPullWithStatus(file('runtime').path) }
// all directories under runtime/component
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } }) {
doGitPullWithStatus(compDir.path)
}
}
}
def doGitPullWithStatus(def gitDir) {
try {
def curGrgit = Grgit.open(dir: gitDir)
logger.lifecycle("\nPulling ${gitDir} (branch:${curGrgit.branch.current()?.name}, tracking:${curGrgit.branch.current()?.trackingBranch?.name})")
def beforeHead = curGrgit.head()
curGrgit.pull()
def afterHead = curGrgit.head()
if (beforeHead == afterHead) {
logger.lifecycle("Already up-to-date.")
} else {
List<Commit> commits = curGrgit.log { range(beforeHead, afterHead) }
for (Commit commit in commits) logger.lifecycle("- ${commit.getAbbreviatedId(7)} by ${commit.committer?.name}: ${commit.shortMessage}")
}
} catch (Throwable t) {
logger.error(t.message)
}
}
task gitCheckoutAll {
description "Do a git checkout on moqui, runtime, and each installed component (for each where a .git directory is found); use -Pbranch= (required) to specify a branch, use -Pcreate=true to create branches with the given name"
doLast {
if (!project.hasProperty('branch')) throw new InvalidUserDataException("No branch property specified (use -Pbranch=...)")
String curBranch = branch
String curTag = (project.hasProperty('tag') ? tag : null) ?: curBranch
boolean createBranch = false
if (project.hasProperty('create') && create == 'true') createBranch = true
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
for (String gitDir in gitDirectories) {
def curGrgit = Grgit.open(dir: gitDir)
def branchList = curGrgit.branch.list(mode: org.ajoberstar.grgit.operation.BranchListOp.Mode.ALL)
def tagList = curGrgit.tag.list()
def targetBranch = branchList.find({ it.name == curBranch })
def targetTag = tagList.find({ it.name == curTag })
if (targetBranch == null && targetTag == null) {
def originBranch = branchList.find({ it.name == 'origin/' + curBranch })
if (originBranch != null) {
logger.lifecycle("In ${gitDir} branch ${curBranch} not found but found ${originBranch.name}, creating local branch tracking that branch")
targetBranch = curGrgit.branch.add(name: curBranch, startPoint: originBranch, mode: org.ajoberstar.grgit.operation.BranchAddOp.Mode.TRACK)
}
}
if (createBranch || targetBranch != null || targetTag != null) {
if (targetTag != null) {
if (createBranch && curBranch != curTag) {
logger.lifecycle("== Git checkout ${gitDir} tag ${curTag} and create branch ${curBranch}")
try { curGrgit.checkout(branch: curBranch, createBranch: true, startPoint: targetTag) }
catch (Exception e) { logger.lifecycle("Checkout error", e) }
} else {
logger.lifecycle("== Git checkout ${gitDir} tag ${curTag}")
try { curGrgit.checkout(branch: curTag, createBranch: false) }
catch (Exception e) { logger.lifecycle("Checkout error", e) }
}
} else {
logger.lifecycle("== Git checkout ${gitDir} branch ${curBranch} create ${createBranch}")
try { curGrgit.checkout(branch: curBranch, createBranch: createBranch) }
catch (Exception e) { logger.lifecycle("Checkout error", e) }
}
} else {
logger.lifecycle("* No branch or tag '${curBranch}' in ${gitDir}\nBranches: ${branchList.collect({it.name})}\nTags: ${tagList.collect({it.name})}")
}
logger.lifecycle("")
}
}
}
task gitStatusAll {
description "Do a git status to check moqui, runtime, and each installed component (for each where a .git directory is found)"
doLast {
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
for (String gitDir in gitDirectories) {
def curGrgit = Grgit.open(dir: gitDir)
logger.lifecycle("\nGit status for ${gitDir} (branch:${curGrgit.branch.current()?.name}, tracking:${curGrgit.branch.current()?.trackingBranch?.name})")
try {
if (curGrgit.remote.list().find({ it.name == 'upstream'})) {
def upstreamAhead = curGrgit.log { range curGrgit.resolve.toCommit('refs/remotes/upstream/master'), curGrgit.resolve.toCommit('refs/remotes/origin/master') }
if (upstreamAhead) logger.lifecycle("- origin/master ${upstreamAhead.size()} commits ahead of upstream/master")
}
} catch (Exception e) {
logger.error("Error finding commits ahead of upstream", e)
}
try {
def masterLatest = curGrgit.resolve.toCommit('refs/remotes/origin/master')
if (masterLatest == null) {
logger.error("No origin/master branch exists, can't determine unpushed commits")
} else {
def unpushed = curGrgit.log { range masterLatest, curGrgit.resolve.toCommit('HEAD') }
if (unpushed) logger.lifecycle("--- ${unpushed.size()} commits unpushed (ahead of origin/master)")
for (Commit commit in unpushed) logger.lifecycle(" - ${commit.getAbbreviatedId(8)} - ${commit.shortMessage}")
}
} catch (Exception e) {
logger.error("Error finding unpushed commits", e)
}
def curStatus = curGrgit.status()
if (curStatus.isClean()) logger.lifecycle("* nothing to commit, working directory clean")
if (curStatus.staged.added || curStatus.staged.modified || curStatus.staged.removed) logger.lifecycle("--- Changes to be committed::")
for (String fn in curStatus.staged.added) logger.lifecycle(" added: ${fn}")
for (String fn in curStatus.staged.modified) logger.lifecycle(" modified: ${fn}")
for (String fn in curStatus.staged.removed) logger.lifecycle(" removed: ${fn}")
if (curStatus.unstaged.added || curStatus.unstaged.modified || curStatus.unstaged.removed) logger.lifecycle("--- Changes not staged for commit:")
for (String fn in curStatus.unstaged.added) logger.lifecycle(" added: ${fn}")
for (String fn in curStatus.unstaged.modified) logger.lifecycle(" modified: ${fn}")
for (String fn in curStatus.unstaged.removed) logger.lifecycle(" removed: ${fn}")
}
}
}
task gitUpstreamAll {
description "Do a git pull upstream:master for moqui, runtime, and each installed component (for each where a .git directory is found and has a remote called upstream)"
doLast {
String remoteName = project.hasProperty('remote') ? remote : 'upstream'
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
for (String gitDir in gitDirectories) {
def curGrgit = Grgit.open(dir: gitDir)
if (curGrgit.remote.list().find({ it.name == remoteName})) {
logger.lifecycle("\nGit merge ${remoteName} for ${gitDir}")
curGrgit.pull(remote: remoteName, branch: 'master')
} else {
logger.lifecycle("\nNo ${remoteName} remote for ${gitDir}")
}
}
}
}
task gitTagAll {
description "Do a git add or remove tag on the currently checked out commit in moqui, runtime, and each installed component"
doLast {
def tagName = (project.hasProperty('tag')) ? tag : null;
def tagMessage = (project.hasProperty('message')) ? message : null;
boolean removeTags = (project.hasProperty('remove') && remove == 'true')
boolean pushTags = (project.hasProperty('push') && push == 'true')
// Users can simply push tags to the remote
if (tagName == null && pushTags == false)
throw new InvalidUserDataException("No tag property specified (use -Ptag=...) and No push tag specified (use -Ppush=true)")
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
def frameworkDir = gitDirectories.first()
for (String gitDir in gitDirectories) {
def relativePath = "."+gitDir.minus(frameworkDir)
def curGrgit = Grgit.open(dir: gitDir)
def branchName = curGrgit.branch.current().name
def commit = curGrgit.log(maxCommits: 1).find()
if (tagName != null) {
def tagList = curGrgit.tag.list()
def targetTag = tagList.find({ it.name == tagName })
if (targetTag == null) {
if (removeTags) {
logger.lifecycle("== Git tag '${tagName}' not found in ${branchName} of ${relativePath} ... skipping")
} else {
curGrgit.tag.add(name: tagName, message: tagMessage ?: "Tagging version ${tagName}")
logger.lifecycle("== Git tagging commit ${commit.abbreviatedId} - '${commit.shortMessage}' by '${commit.author.name}' in ${branchName} of ${relativePath}")
}
} else {
if (removeTags) {
curGrgit.tag.remove(names: [tagName])
logger.lifecycle("== Git removing tag '${tagName}' in ${branchName} of ${relativePath}")
} else {
logger.lifecycle("== Git tag '${tagName}' already exists in ${branchName} of ${relativePath}, skipping...")
}
}
}
if (pushTags) {
if (removeTags) {
curGrgit.push(refsOrSpecs: [':refs/tags/'+tagName])
} else {
curGrgit.push(tags: true)
}
logger.lifecycle("== Git pushing tag changes to remote of ${relativePath}")
}
}
}
}
task gitDiffTagsAll {
description "Do a git diff between two tags in the currently checked out branch in moqui, runtime, and each installed component"
doLast {
if (!project.hasProperty('taga') || taga == null)
throw new InvalidUserDataException("No taga property specified (use -Ptaga=...)")
// If tagb is not passed, we assume HEAD
def tagb = (project.hasProperty('tagb') && tagb != null) ? tagb : "HEAD";
logger.lifecycle("== Git diffing tags ${taga} and ${tagb}")
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
def frameworkDir = gitDirectories.first()
for (String gitDir in gitDirectories) {
def relativePath = "."+gitDir.minus(frameworkDir)
def grgit = Grgit.open(dir: gitDir)
def tagList = grgit.tag.list()
def tagaCommit = tagList.find({ it.name == taga })
def tagbCommit = tagList.find({ it.name == tagb })
logger.lifecycle("${relativePath}")
if ((taga == "HEAD" || tagaCommit != null) && (tagb == "HEAD" || tagbCommit != null)) {
grgit.log {
range taga, tagb
}.each {
logger.lifecycle(" ${it.abbreviatedId} - ${it.shortMessage}")
}
}
}
}
}
task gitMergeAll {
description "Do a git diff between two tags in the currently checked out branch in moqui, runtime, and each installed component"
doLast {
def branchName = (project.hasProperty('branch')) ? branch : null;
def tagName = (project.hasProperty('tag')) ? tag : null;
def mergeMode = (project.hasProperty('mode')) ? mode : null;
def mergeMessage = (project.hasProperty('message')) ? message : null;
def pushMerge = (project.hasProperty('push')) ? push : null;
List<String> gitDirectories = []
if (file(".git").exists()) gitDirectories.add(file('.').path)
if (file("runtime/.git").exists()) gitDirectories.add(file('runtime').path)
for (File compDir in file('runtime/component').listFiles().findAll { it.isDirectory() && it.listFiles().find { it.name == '.git' } })
gitDirectories.add(compDir.path)
def frameworkDir = gitDirectories.first()
for (String gitDir in gitDirectories) {
def relativePath = "."+gitDir.minus(frameworkDir)
logger.lifecycle("${relativePath}")
def grgit = Grgit.open(dir: gitDir)
def currentBranch = grgit.branch.current()?.name;
if (branchName == currentBranch)
continue
def doMerge = false;
if (branchName && grgit.branch.list().find({ it.name == branchName }) != null) {
doMerge = true;
}
if (tagName && grgit.tag.list().find({ it.name == tagName }) != null) {
doMerge = true;
}
if (doMerge) {
grgit.merge(head: branchName ?: tagName, mode: mergeMode, message: mergeMessage)
logger.lifecycle(" Merging ${branchName ?: tagName} into ${currentBranch}")
}
if (pushMerge) {
grgit.push();
logger.lifecycle(" Pushing merge")
}
}
}
}
// ========== run tasks ==========
task run(type: JavaExec) {
dependsOn checkRuntime, allBuildTasks, cleanTempDir
workingDir = '.'; jvmArgs = ['-server', '-XX:-OmitStackTraceInFastThrow']
systemProperties = ['moqui.conf':moquiConfDev, 'moqui.runtime':moquiRuntime]
// NOTE: this is a hack, using -jar instead of a class name, and then the first argument is the name of the jar file
main = '-jar'; args = [warName]
}
task runProduction(type: JavaExec) {
dependsOn checkRuntime, allBuildTasks, cleanTempDir
workingDir = '.'; jvmArgs = ['-server', '-Xms1024M']
systemProperties = ['moqui.conf':moquiConfProduction, 'moqui.runtime':moquiRuntime]
main = '-jar'; args = [warName]
}
task load(type: JavaExec) {
description "Run Moqui to load data; to specify data types use something like: gradle load -Ptypes=seed,seed-initial,install"
dependsOn checkRuntime, allBuildTasks
systemProperties = ['moqui.conf':moquiConfDev, 'moqui.runtime':moquiRuntime]
workingDir = '.'; jvmArgs = ['-server']; main = '-jar'
args = [warName, 'load', (project.properties.containsKey('types') ? "types=${types}" : "types=all")]
}
task loadSeed(type: JavaExec) {
dependsOn checkRuntime, allBuildTasks
systemProperties = ['moqui.conf':moquiConfProduction, 'moqui.runtime':moquiRuntime]
workingDir = '.'; jvmArgs = ['-server']; main = '-jar'
args = [warName, 'load', (project.properties.containsKey('types') ? "types=${types}" : "types=seed")]
}
task loadSeedInitial(type: JavaExec) {
dependsOn checkRuntime, allBuildTasks
systemProperties = ['moqui.conf':moquiConfProduction, 'moqui.runtime':moquiRuntime]
workingDir = '.'; jvmArgs = ['-server']; main = '-jar'
args = [warName, 'load', (project.properties.containsKey('types') ? "types=${types}" : "types=seed,seed-initial")]
}
task loadProduction(type: JavaExec) {
dependsOn checkRuntime, allBuildTasks
systemProperties = ['moqui.conf':moquiConfProduction, 'moqui.runtime':moquiRuntime]
workingDir = '.'; jvmArgs = ['-server']; main = '-jar'
args = [warName, 'load', (project.properties.containsKey('types') ? "types=${types}" : "types=seed,seed-initial,install")]
}
task saveDb { doLast {
if (file(moquiRuntime+'/db/derby/moqui').exists())
ant.zip(destfile: 'SaveDerby.zip') { fileset(dir: moquiRuntime+'/db/derby/moqui') { include(name: '**/*') } }
if (file(moquiRuntime+'/db/h2').exists())
ant.zip(destfile: 'SaveH2.zip') { fileset(dir: moquiRuntime+'/db/h2') { include(name: '**/*') } }
if (file(moquiRuntime+'/db/orientdb/databases').exists())
ant.zip(destfile: 'SaveOrientDb.zip') { fileset(dir: moquiRuntime+'/db/orientdb/databases') { include(name: '**/*') } }
File osDir = file(moquiRuntime + '/opensearch')
String workDir = moquiRuntime + (osDir.exists() ? '/opensearch' : '/elasticsearch')
if (file(workDir+'/data').exists()) {
if (file(workDir+'/bin').exists()) {
def pidFile = file(workDir+'/pid')
if (pidFile.exists()) {
String pid = pidFile.getText()
logger.lifecycle("ElasticSearch running with pid ${pid}, stopping before saving data then restarting")
exec { workingDir workDir; commandLine 'kill', pid }
exec { workingDir workDir; commandLine 'tail', "--pid=${pid}", '-f', '/dev/null' }
if (pidFile.exists()) delete pidFile
ant.zip(destfile: (osDir.exists() ? 'SaveOpenSearch.zip' : 'SaveElasticSearch.zip')) { fileset(dir: workDir+'/data') { include(name: '**/*') } }
startSearch(moquiRuntime)
} else {
logger.lifecycle("Found ${osDir.exists() ? 'OpenSearch' : 'ElasticSearch'} ${workDir}/bin directory but no pid, saving data without stop/start; WARNING if ElasticSearch is running this will cause problems!")
ant.zip(destfile: (osDir.exists() ? 'SaveOpenSearch.zip' : 'SaveElasticSearch.zip')) { fileset(dir: workDir+'/data') { include(name: '**/*') } }
}
} else {
ant.zip(destfile: (osDir.exists() ? 'SaveOpenSearch.zip' : 'SaveElasticSearch.zip')) { fileset(dir: workDir+'/data') { include(name: '**/*') } }
}
}
} }
task loadSave {
description "Clean all, build and load, then save database (H2, Derby), OrientDB, and OpenSearch/ElasticSearch files; to be used before reloadSave"
dependsOn cleanAll, load, saveDb
}
task reloadSave {
description "After a loadSave clean database (H2, Derby), OrientDB, and ElasticSearch files and reload from saved copy"
dependsOn cleanTempDir, cleanDb, cleanLog, cleanSessions
dependsOn allBuildTasks
doLast {
if (file('SaveDerby.zip').exists()) copy { from zipTree('SaveDerby.zip'); into file(moquiRuntime+'/db/derby/moqui') }
if (file('SaveH2.zip').exists()) copy { from zipTree('SaveH2.zip'); into file(moquiRuntime+'/db/h2') }
if (file('SaveOrientDb.zip').exists()) copy { from zipTree('SaveOrientDb.zip'); into file(moquiRuntime+'/db/orientdb/databases') }
if (file('SaveElasticSearch.zip').exists()) {
String esDir = moquiRuntime+'/elasticsearch'
if (file(esDir+'/bin').exists()) {
def pidFile = file(esDir+'/pid')
if (pidFile.exists()) {
String pid = pidFile.getText()
logger.lifecycle("ElasticSearch running with pid ${pid}, stopping before restoring data then restarting")
exec { workingDir esDir; commandLine 'kill', pid }
exec { workingDir esDir; commandLine 'tail', "--pid=${pid}", '-f', '/dev/null' }
copy { from zipTree('SaveElasticSearch.zip'); into file(moquiRuntime+'/elasticsearch/data') }
if (pidFile.exists()) delete pidFile
exec { workingDir esDir; commandLine './bin/elasticsearch', '-d', '-p', 'pid' }
} else {
logger.lifecycle("Found ElasticSearch ${esDir}/bin directory but no pid, saving data without stop/start; WARNING if ElasticSearch is running this will cause problems!")
copy { from zipTree('SaveElasticSearch.zip'); into file(moquiRuntime+'/elasticsearch/data') }
}
} else {
copy { from zipTree('SaveElasticSearch.zip'); into file(moquiRuntime+'/elasticsearch/data') }
}
}
if (file('SaveOpenSearch.zip').exists()) {
String esDir = moquiRuntime+'/opensearch'
if (file(esDir+'/bin').exists()) {
def pidFile = file(esDir+'/pid')
if (pidFile.exists()) {
String pid = pidFile.getText()
logger.lifecycle("OpenSearch running with pid ${pid}, stopping before restoring data then restarting")
exec { workingDir esDir; commandLine 'kill', pid }
exec { workingDir esDir; commandLine 'tail', "--pid=${pid}", '-f', '/dev/null' }
copy { from zipTree('SaveOpenSearch.zip'); into file(moquiRuntime+'/opensearch/data') }
if (pidFile.exists()) delete pidFile
exec { workingDir esDir; commandLine './bin/opensearch', '-d', '-p', 'pid' }
} else {
logger.lifecycle("Found OpenSearch ${esDir}/bin directory but no pid, saving data without stop/start; WARNING if OpenSearch is running this will cause problems!")
copy { from zipTree('SaveOpenSearch.zip'); into file(moquiRuntime+'/opensearch/data') }
}
} else {
copy { from zipTree('SaveOpenSearch.zip'); into file(moquiRuntime+'/opensearch/data') }
}
}
}
}
// ========== deploy tasks ==========
task deployTomcat { doLast {
// remove runtime directory, may have been added for logs/etc
delete file(tomcatHome + '/runtime')
// remove ROOT directory and war to avoid conflicts
delete file(tomcatHome + '/webapps/ROOT')
delete file(tomcatHome + '/webapps/ROOT.war')
// copy the war file to ROOT.war
copy { from file(warName); into file(tomcatHome + '/webapps'); rename(warName, 'ROOT.war') }
} }
task plusRuntimeWarTemp {
dependsOn checkRuntime, allBuildTasks
doLast {
File wartempFile = file('wartemp')
if (wartempFile.exists()) delete wartempFile
// make version detail files
makeVersionDetailFiles()
// unzip the "moqui-${version}.war" file to the wartemp directory
copy { from zipTree(warName); into wartempFile }
// copy runtime directory (with a few exceptions) into a runtime directory in the war
copy {
from fileTree(dir: '.', include: moquiRuntime+'/**',
excludes: ['**/*.jar', '**/build', moquiRuntime+'/classes/**', moquiRuntime+'/lib/**', moquiRuntime+'/log/**', moquiRuntime+'/sessions/**'])
into wartempFile
}
// copy the jar files from runtime/lib
copy { from fileTree(dir: moquiRuntime+'/lib', include: '**/*.jar').files into 'wartemp/WEB-INF/lib' }
// copy the classpath resource files from runtime/classes
copy { from fileTree(dir: moquiRuntime+'/classes', include: '**/*') into 'wartemp/WEB-INF/classes' }
// copy the jar files from components
copy { from fileTree(dir: moquiRuntime+'/base-component', include: '**/*.jar').files into 'wartemp/WEB-INF/lib' }
copy {
from fileTree(dir: moquiRuntime+'/component', include: '**/*.jar', exclude: '**/librepo/*.jar').files
into 'wartemp/WEB-INF/lib'
duplicatesStrategy DuplicatesStrategy.WARN
}
copy {
from fileTree(dir: moquiRuntime+'/ecomponent', include: '**/*.jar', exclude: '**/librepo/*.jar').files
into 'wartemp/WEB-INF/lib'
duplicatesStrategy DuplicatesStrategy.WARN
}
// add MoquiInit.properties fresh copy, just in case it was changed
copy { from file('MoquiInit.properties') into 'wartemp/WEB-INF/classes' }
// add Procfile to root
copy { from file('Procfile') into 'wartemp' }
// special case: copy elasticsearch plugin/module jars (needed for ES installed in runtime/elasticsearch
if (file(moquiRuntime+'/elasticsearch').exists())
copy { from fileTree(dir: '.', include: moquiRuntime+'/elasticsearch/**/*.jar') into wartempFile }
// special case: copy opensearch plugin/module jars (needed for ES installed in runtime/opensearch
if (file(moquiRuntime+'/opensearch').exists())
copy { from fileTree(dir: '.', include: moquiRuntime+'/opensearch/**/*.jar') into wartempFile }
// special case: copy jackrabbit standalone jar (if exists)
copy { from fileTree(dir: moquiRuntime + '/jackrabbit', include: 'jackrabbit-standalone-*.jar').files; into 'wartemp/' + moquiRuntime + '/jackrabbit' }
// clean up version detail files
cleanVersionDetailFiles()
}
}
task addRuntime(type: Zip) {
description "Create moqui-plus-runtime.war file from the moqui.war file and the runtime directory embedded in it"
dependsOn checkRuntime, allBuildTasks, plusRuntimeWarTemp
archiveFileName = plusRuntimeName
destinationDirectory = file('.')
from file('wartemp')
doFirst { if (file(plusRuntimeName).exists()) delete file(plusRuntimeName) }
doLast { delete file('wartemp') }
}
// don't use this task directly, use addRuntimeTomcat which calls this
task deployTomcatRuntime { doLast {
delete file(tomcatHome + '/runtime'); delete file(tomcatHome + '/webapps/ROOT'); delete file(tomcatHome + '/webapps/ROOT.war')
copy { from file(plusRuntimeName); into file(tomcatHome + '/webapps'); rename(plusRuntimeName, 'ROOT.war') }
} }
task addRuntimeTomcat {
dependsOn addRuntime
dependsOn deployTomcatRuntime
}
// ========== component tasks ==========
task getDefaults {
description "Get a component using specified location type, also check/get all components it depends on; requires component property; locationType property optional (defaults to git if there is a .git directory, otherwise to current)"
doLast {
String curLocationType = file('.git').exists() ? 'git' : 'current'
if (project.hasProperty('locationType')) curLocationType = locationType
getComponentTop(curLocationType)
}
}
task getComponent {
description "Get a component using specified location type, also check/get all components it depends on; requires component property; locationType property optional (defaults to git if there is a .git directory, otherwise to current)"
doLast {
String curLocationType = file('.git').exists() ? 'git' : 'current'
if (project.hasProperty('locationType')) curLocationType = locationType
getComponentTop(curLocationType)
}
}
task createComponent {
description "Create a new component. Set new component name with -Pcomponent=new_component_name (based on the moqui start component here: https://github.com/moqui/start)"
doLast {
String curLocationType = file('.git').exists() ? 'git' : 'current'
if (project.hasProperty('locationType')) curLocationType = locationType
if (project.hasProperty('component')) {
checkRuntimeDirAndDefaults(curLocationType)
Set compsChecked = new TreeSet()
def startComponentName = 'start'
File componentDir = getComponent(startComponentName, curLocationType, parseAddons(), parseMyaddons(), compsChecked)
if (componentDir?.exists()) {
logger.lifecycle("Got component start, dependent components checked: ${compsChecked}")
def newComponent = file("runtime/component/${component}")
def renameSuccessful = componentDir.renameTo(newComponent)
if (!renameSuccessful) {
logger.error("Failed to rename component start to ${component}. Try removing the existing component directory first or giving this program write permissions.")
} else {
logger.lifecycle("Renamed component start to ${component}")
}
print "Updated file: "
newComponent.eachFileRecurse(groovy.io.FileType.FILES) { file ->
try {
// If file name is startComponentName.* rename to component.*
if (file.name.startsWith(startComponentName)) {
String newFileName = (file.name - startComponentName)
newFileName = component + newFileName
File newFile = new File(file.parent, newFileName)
file.renameTo(newFile)
file = newFile
print "${file.path - newComponent.path - '/'}, "
}
String content = file.text
if (content.contains(startComponentName)) {
content = content.replaceAll(startComponentName, component)
file.text = content
print "${file.path - newComponent.path - '/'}, "
}
} catch (IOException e) {
println "Error processing file ${file.path}: ${e.message}"
}
}
print "\n\n"
println "Select rest api (r), screens (s), or both (B):"
def componentInput = System.in.newReader().readLine()
if (componentInput == 'r') {
new File(newComponent, 'screen').deleteDir()
new File(newComponent, 'template').deleteDir()
new File(newComponent, 'data/AppSeedData.xml').delete()
new File(newComponent, 'MoquiConf.xml').delete()
def moquiConf = new File(newComponent, 'MoquiConf.xml')
moquiConf.append("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n" +
"<!-- No copyright or license for configuration file, details here are not considered a creative work. -->\n" +
"<moqui-conf xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:noNamespaceSchemaLocation=\"http://moqui.org/xsd/moqui-conf-3.xsd\">\n" +
"</moqui-conf>")
println "Selected rest api so, deleted screen, template, and AppSeedData.xml\n"
} else if (componentInput == 's') {
new File(newComponent, "services/${component}.rest.xml").delete()
new File(newComponent, 'data/ApiSeedData.xml').delete()
println "Selected screens so, deleted rest api and ApiSeedData.xml\n"
} else if (componentInput == 'b' || componentInput == 'B' || componentInput == '') {
println "Selected both rest api and screens\n"
} else {
println "Invalid input. Try again"
newComponent.deleteDir()
return
}
println "Are you going to code or test in groovy or java [y/N]"
def codeInput = System.in.newReader().readLine()
if (codeInput == 'y' || codeInput == 'Y') {
println "Keeping src folder\n"
} else if (codeInput == 'n' || codeInput == 'N' || codeInput == '') {
new File(newComponent, 'src').deleteDir()
new File(newComponent, 'build.grade').delete()
println "Selected no so, deleted src and build.grade\n"
} else {
println "Invalid input. Try again"
newComponent.deleteDir()
return
}
println "Setup a git repository [Y/n]"
def gitInput = System.in.newReader().readLine()
if (gitInput == 'y' || gitInput == 'Y' || gitInput == '') {
new File(newComponent, '.git').deleteDir()
// Setup git repository
def grgit = Grgit.init(dir: newComponent.path)
grgit.add(patterns: ['.'])
// Can't get signing to work easily. If signing works well then might as well commit
// grgit.commit(message: 'Initial commit')
println "Selected yes, so git is initialized\n"
println "To setup the git remote origin, type the git remote url or enter to skip"
def remoteUrl = System.in.newReader().readLine()
if (remoteUrl != '') {
grgit.remote.add(name: 'origin', url: remoteUrl)
println "Run the following to push the git repository:\ncd runtime/component/${component} && git commit -m 'Initial commit' && git push && cd ../../.."
} else {
println "Run the following to push the git repository:\ncd runtime/component/${component} && git commit -m 'Initial commit' && git remote add origin [email protected]:yourgroup/${component} && git push && cd ../../.."
}
} else if (gitInput == 'n' || gitInput == 'N') {
new File(newComponent, '.git').deleteDir()
println "Selected no, so git is not initialized\n"
println "Run the following to push the git repository:\ncd runtime/component/${component} && git commit -m 'Initial commit' && git remote add origin [email protected]:yourgroup/${component} && git push && cd ../../.."
} else {
println "Invalid input. Try again"
newComponent.deleteDir()
return
}
println "Add to myaddons.xml [Y/n]"
def myaddonsInput = System.in.newReader().readLine()
if (myaddonsInput == 'y' || myaddonsInput == 'Y' || myaddonsInput == '') {
def myaddonsFile = file('myaddons.xml')
if (myaddonsFile.exists()){
// Iterate through myaddons file and delete the lines that are </addons>
// Read the lines from the file
def lines = myaddonsFile.readLines()
// Filter out the lines that contain </addons>
def filteredLines = lines.findAll { !it.contains("</addons>") }
// Write the filtered lines back to the file
myaddonsFile.text = filteredLines.join('\n')
} else {
println "myaddons.xml not found. Creating one\nEnter repository github (g), github-ssh (GS), bitbucket (b), or bitbucket-ssh (bs)"
def repositoryInput = System.in.newReader().readLine()
myaddonsFile.append("<addons default-repository=\"")
if (repositoryInput == 'g' || repositoryInput == 'G') {
myaddonsFile.append('github')
} else if (repositoryInput == 'gs' || repositoryInput == 'GS' || repositoryInput == '') {
myaddonsFile.append('github-ssh')
} else if (repositoryInput == 'b' || repositoryInput == 'B') {
myaddonsFile.append('bitbucket')
} else if (repositoryInput == 'bs' || repositoryInput == 'BS') {
myaddonsFile.append('bitbucket-ssh')
} else {
println "Invalid input. Setting to github-ssh"
myaddonsFile.append('github-ssh')