-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbuild.gradle
More file actions
1375 lines (1154 loc) · 50.5 KB
/
Copy pathbuild.gradle
File metadata and controls
1375 lines (1154 loc) · 50.5 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
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
/*
* Bearsampp Module Python - Pure Gradle Build
*
* This is a pure Gradle build configuration that replaces the legacy Ant build system.
* All build logic has been converted to native Gradle tasks.
*
* Usage:
* gradle tasks - List all available tasks
* gradle release - Interactive release (prompts for version)
* gradle release -PbundleVersion=3.13.5 - Non-interactive release
* gradle clean - Clean build artifacts
* gradle info - Display build information
* gradle verify - Verify build environment
*/
plugins {
id 'base'
}
// Load build properties
def buildProps = new Properties()
file('build.properties').withInputStream { buildProps.load(it) }
// Project information
group = 'com.bearsampp.modules'
version = buildProps.getProperty('bundle.release', '1.0.0')
description = "Bearsampp Module - ${buildProps.getProperty('bundle.name', 'python')}"
// Define project paths
ext {
projectBasedir = projectDir.absolutePath
rootDir = projectDir.parent
devPath = file("${rootDir}/dev").absolutePath
buildPropertiesFile = file('build.properties').absolutePath
// Bundle properties from build.properties
bundleName = buildProps.getProperty('bundle.name', 'python')
bundleRelease = buildProps.getProperty('bundle.release', '1.0.0')
bundleType = buildProps.getProperty('bundle.type', 'tools')
bundleFormat = buildProps.getProperty('bundle.format', '7z')
// External build base path precedence: build.properties (build.path) -> env(BEARSAMPP_BUILD_PATH) -> default <root>/bearsampp-build
def buildPathFromProps = (buildProps.getProperty('build.path', '') ?: '').trim()
def buildPathFromEnv = System.getenv('BEARSAMPP_BUILD_PATH') ?: ''
def defaultBuildPath = "${rootDir}/bearsampp-build"
buildBasePath = buildPathFromProps ? buildPathFromProps : (buildPathFromEnv ? buildPathFromEnv : defaultBuildPath)
// Shared external tmp tree
buildTmpPath = file("${buildBasePath}/tmp").absolutePath
bundleTmpPrepPath = file("${buildTmpPath}/bundles_prep/${bundleType}/${bundleName}").absolutePath
bundleTmpBuildPath = file("${buildTmpPath}/bundles_build/${bundleType}/${bundleName}").absolutePath
bundleTmpDownloadPath = file("${buildTmpPath}/downloads/${bundleName}").absolutePath
// Final external output path for archives
moduleBuildOutputPath = file("${buildBasePath}/${bundleType}/${bundleName}/${bundleRelease}").absolutePath
}
// Verify dev path exists
if (!file(ext.devPath).exists()) {
logger.warn("Dev path not found: ${ext.devPath}. Some tasks may not work correctly.")
}
// Configure repositories for dependencies
repositories {
mavenCentral()
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
// Helper function to find 7-Zip executable
def find7ZipExecutable() {
// Check environment variable
def sevenZipHome = System.getenv('7Z_HOME')
if (sevenZipHome) {
def exe = file("${sevenZipHome}/7z.exe")
if (exe.exists()) {
return exe.absolutePath
}
}
// Check common installation paths
def commonPaths = [
'C:/Program Files/7-Zip/7z.exe',
'C:/Program Files (x86)/7-Zip/7z.exe',
'D:/Program Files/7-Zip/7z.exe',
'D:/Program Files (x86)/7-Zip/7z.exe'
]
for (path in commonPaths) {
def exe = file(path)
if (exe.exists()) {
return exe.absolutePath
}
}
// Try to find in PATH
try {
def process = ['where', '7z.exe'].execute()
process.waitFor()
if (process.exitValue() == 0) {
def output = process.text.trim()
if (output) {
return output.split('\n')[0].trim()
}
}
} catch (Exception e) {
// Ignore
}
return null
}
// Helper function to calculate hash
def calculateHash(File file, String algorithm) {
def digest = java.security.MessageDigest.getInstance(algorithm)
file.withInputStream { stream ->
def buffer = new byte[8192]
def bytesRead
while ((bytesRead = stream.read(buffer)) != -1) {
digest.update(buffer, 0, bytesRead)
}
}
return digest.digest().collect { String.format('%02x', it) }.join('')
}
// Helper methods for version discovery
def findAvailableVersions = {
def binDir = new File(projectDir, 'bin')
def archivedDir = new File(projectDir, 'bin/archived')
def versions = [] as List<String>
if (binDir.exists()) {
versions.addAll(
(binDir.listFiles() ?: [])
.findAll { it.isDirectory() && it.name.startsWith(bundleName) && it.name != 'archived' && it.name != 'archi8ved' }
.collect { it.name.replace(bundleName, '') }
)
}
if (archivedDir.exists()) {
versions.addAll(
(archivedDir.listFiles() ?: [])
.findAll { it.isDirectory() && it.name.startsWith(bundleName) }
.collect { it.name.replace(bundleName, '') }
)
}
// Remove duplicates and sort semantically
return versions.unique().sort { a, b ->
def aParts = a.tokenize('.').collect { it.isInteger() ? it.toInteger() : it }
def bParts = b.tokenize('.').collect { it.isInteger() ? it.toInteger() : it }
for (int i = 0; i < Math.max(aParts.size(), bParts.size()); i++) {
def aVal = i < aParts.size() ? aParts[i] : 0
def bVal = i < bParts.size() ? bParts[i] : 0
if (aVal.getClass() != bVal.getClass()) {
aVal = aVal.toString()
bVal = bVal.toString()
}
if (aVal != bVal) return aVal <=> bVal
}
return 0
}
}
// Helper: Fetch python.properties from modules-untouched repository
def fetchModulesUntouchedProperties() {
def propsUrl = "https://raw.githubusercontent.com/Bearsampp/modules-untouched/main/modules/python.properties"
println "Checking modules-untouched repository..."
println "Fetching python.properties from modules-untouched repository..."
println " URL: ${propsUrl}"
def tempFile = file("${bundleTmpDownloadPath}/python-untouched.properties")
tempFile.parentFile.mkdirs()
try {
new URL(propsUrl).withInputStream { input ->
tempFile.withOutputStream { output ->
output << input
}
}
def props = new Properties()
tempFile.withInputStream { props.load(it) }
println " ✓ Successfully loaded ${props.size()} versions from modules-untouched"
return props
} catch (Exception e) {
println " ✗ Warning: Could not fetch python.properties from modules-untouched: ${e.message}"
return null
}
}
// Helper: Download Python binaries from modules-untouched repository
def downloadFromModulesUntouched(String version) {
def untouchedProps = fetchModulesUntouchedProperties()
if (!untouchedProps) {
throw new GradleException("Could not fetch python.properties from modules-untouched repository")
}
def untouchedUrl = untouchedProps.getProperty(version)
if (!untouchedUrl) {
throw new GradleException("Version ${version} not found in modules-untouched python.properties")
}
println "Found version ${version} in modules-untouched python.properties"
println "Downloading from:"
println " ${untouchedUrl}"
def filename = untouchedUrl.substring(untouchedUrl.lastIndexOf('/') + 1)
def downloadDir = file(bundleTmpDownloadPath)
downloadDir.mkdirs()
def downloadedFile = file("${downloadDir}/${filename}")
if (!downloadedFile.exists()) {
println "Downloading to: ${downloadedFile}"
new URL(untouchedUrl).withInputStream { input ->
downloadedFile.withOutputStream { output ->
output << input
}
}
println "Download complete from modules-untouched"
} else {
println "Already downloaded: ${downloadedFile.name}"
}
return downloadedFile
}
// Helper: Extract Python archive
def extractPythonArchive(File archive, String version) {
def extractDir = file("${bundleTmpPath}/extract/${bundleName}")
extractDir.mkdirs()
println "Extracting archive..."
def extractPath = file("${extractDir}/${version}")
if (extractPath.exists()) {
delete extractPath
}
extractPath.mkdirs()
// Extract using Gradle's zipTree
copy {
from zipTree(archive)
into extractPath
}
println "Extraction complete"
// Find the Python directory (it might be nested)
def pythonDir = findPythonDirectory(extractPath)
if (!pythonDir) {
throw new GradleException("Could not find Python directory in extracted archive")
}
println "Found Python directory: ${pythonDir.name}"
return pythonDir
}
// Helper: Find Python directory containing python.exe
def findPythonDirectory(File searchDir) {
// Case 1: Check if python.exe is directly in this directory
def pythonExe = new File(searchDir, 'python.exe')
if (pythonExe.exists()) {
return searchDir
}
// Case 2: Recursively search for a directory containing python.exe
File found = null
def stack = new ArrayDeque<File>()
stack.push(searchDir)
while (!stack.isEmpty() && !found) {
def current = stack.pop()
def children = current.listFiles()
if (children) {
for (def child : children) {
if (child.isDirectory()) {
def exe = new File(child, 'python.exe')
if (exe.exists()) {
found = child
break
}
stack.push(child)
}
}
}
}
return found
}
def latestVersion = { List<String> versions ->
if (versions.isEmpty()) return null
return versions.max { a, b ->
def aParts = a.tokenize('.').collect { it.isInteger() ? it.toInteger() : it }
def bParts = b.tokenize('.').collect { it.isInteger() ? it.toInteger() : it }
for (int i = 0; i < Math.max(aParts.size(), bParts.size()); i++) {
def aVal = i < aParts.size() ? aParts[i] : 0
def bVal = i < bParts.size() ? bParts[i] : 0
if (aVal.getClass() != bVal.getClass()) {
aVal = aVal.toString()
bVal = bVal.toString()
}
if (aVal != bVal) return aVal <=> bVal
}
return 0
}
}
// ============================================================================
// GRADLE NATIVE TASKS
// ============================================================================
// Task: Display build information
tasks.register('info') {
group = 'help'
description = 'Display build configuration information'
def projectName = project.name
def projectVersion = project.version
def projectDescription = project.description
def gradleVersion = gradle.gradleVersion
def gradleHome = gradle.gradleHomeDir
doLast {
println """
================================================================
Bearsampp Module Python - Build Info
================================================================
Project: ${projectName}
Version: ${projectVersion}
Description: ${projectDescription}
Bundle Properties:
Name: ${bundleName}
Release: ${bundleRelease}
Type: ${bundleType}
Format: ${bundleFormat}
Paths:
Project Dir: ${projectBasedir}
Root Dir: ${rootDir}
Dev Path: ${devPath}
Build Base: ${buildBasePath}
Output Dir: ${moduleBuildOutputPath}
Tmp Root: ${buildTmpPath}
Tmp Prep: ${bundleTmpPrepPath}
Tmp Build: ${bundleTmpBuildPath}
Downloads: ${bundleTmpDownloadPath}
Java:
Version: ${JavaVersion.current()}
Home: ${System.getProperty('java.home')}
Gradle:
Version: ${gradleVersion}
Home: ${gradleHome}
Python Build Features:
* Automatic PIP upgrade during build
* Wheel package download and installation
* Support for multiple Python versions
* PyQt5 exclusion handling
Available Task Groups:
* build - Build and package tasks
* help - Help and information tasks
* verification - Verification and validation tasks
Quick Start:
gradle tasks - List all available tasks
gradle info - Show this information
gradle release - Interactive release build
gradle release -PbundleVersion=3.13.5 - Non-interactive release
gradle clean - Clean build artifacts
gradle verify - Verify build environment
gradle listVersions - List available Python versions
""".stripIndent()
}
}
// Task: Enhanced clean task
tasks.named('clean') {
group = 'build'
description = 'Clean build artifacts and temporary files'
doLast {
// Clean Gradle build directory
def buildDir = file("${projectDir}/build")
if (buildDir.exists()) {
delete buildDir
println "Cleaned: ${buildDir}"
}
// Clean temporary directories
def tmpDir = file(buildTmpPath)
if (tmpDir.exists()) {
delete tmpDir
println "Cleaned: ${tmpDir}"
}
// Clean Gradle-specific temp files
def gradleBundleVersion = file("${buildTmpPath}/.gradle-bundleVersion")
if (gradleBundleVersion.exists()) {
delete gradleBundleVersion
println "Cleaned: ${gradleBundleVersion.name}"
}
println "[SUCCESS] Build artifacts cleaned"
}
}
// Task: Verify build environment
tasks.register('verify') {
group = 'verification'
description = 'Verify build environment and dependencies'
doLast {
println "Verifying build environment for module-python..."
def checks = [:]
// Check Java version
def javaVersion = JavaVersion.current()
checks['Java 8+'] = javaVersion >= JavaVersion.VERSION_1_8
// Check required files
checks['build.gradle'] = file('build.gradle').exists()
checks['build.properties'] = file('build.properties').exists()
checks['releases.properties'] = file('releases.properties').exists()
// Check dev directory
checks['dev directory'] = file(devPath).exists()
// Check bin directory for Python versions
def binDir = file("${projectDir}/bin")
checks['bin directory'] = binDir.exists()
if (binDir.exists()) {
def pythonVersions = binDir.listFiles()
.findAll { it.isDirectory() && it.name.startsWith(bundleName) && it.name != 'archived' }
checks['Python versions available'] = pythonVersions.size() > 0
}
// Check for 7z command
def sevenZipExe = find7ZipExecutable()
checks['7-Zip available'] = sevenZipExe != null
println "\nEnvironment Check Results:"
println "-".multiply(60)
checks.each { name, passed ->
def status = passed ? "[PASS]" : "[FAIL]"
println " ${status.padRight(10)} ${name}"
}
println "-".multiply(60)
def allPassed = checks.values().every { it }
if (allPassed) {
println "\n[SUCCESS] All checks passed! Build environment is ready."
println "\nYou can now run:"
println " gradle release - Interactive release"
println " gradle release -PbundleVersion=3.13.5 - Non-interactive release"
println " gradle listVersions - List available Python versions"
} else {
println "\n[WARNING] Some checks failed. Please review the requirements."
throw new GradleException("Build environment verification failed")
}
}
}
// Task: Resolve version (interactive by default; supports -PbundleVersion and '*')
tasks.register('resolveVersion') {
group = 'build'
description = 'Resolve bundleVersion (interactive by default, or use -PbundleVersion=*,<ver>)'
def versionProperty = project.findProperty('bundleVersion')
doLast {
def supplied = versionProperty as String
def all = findAvailableVersions()
def inBin = new File(projectDir, 'bin').exists() ? (new File(projectDir, 'bin').listFiles()
?.findAll { it.isDirectory() && it.name.startsWith(bundleName) && it.name != 'archived' }
?.collect { it.name.replace(bundleName, '') } ?: []) : []
def inArchived = new File(projectDir, 'bin/archived').exists() ? (new File(projectDir, 'bin/archived').listFiles()
?.findAll { it.isDirectory() && it.name.startsWith(bundleName) }
?.collect { it.name.replace(bundleName, '') } ?: []) : []
String resolved
if (supplied) {
if (supplied == '*') {
resolved = latestVersion(all)
if (!resolved) {
throw new GradleException("No versions found under bin/ to resolve latest from.")
}
println "Resolved latest version: ${resolved}"
} else {
resolved = supplied
}
} else {
println "=".multiply(70)
println "\nInteractive Release Mode\n"
println "=".multiply(70)
println "\nAvailable versions:\n"
all.eachWithIndex { v, idx ->
def indexStr = String.format('%2d', idx + 1)
def tag = inBin.contains(v) && inArchived.contains(v) ? '[bin + bin/archived]' : (inBin.contains(v) ? '[bin]' : (inArchived.contains(v) ? '[bin/archived]' : '[unknown]'))
println " ${indexStr}. ${v.padRight(12)} ${tag}"
}
println ""
print "Enter version to build (index or version string): "
System.out.flush()
def reader = new BufferedReader(new InputStreamReader(System.in))
def input = reader.readLine()?.trim()
if (!input) {
throw new GradleException("No version specified")
}
if (input.isInteger()) {
def idx = input.toInteger()
if (idx < 1 || idx > all.size()) {
throw new GradleException("Invalid index: ${input}. Choose 1..${all.size()} or enter a version string.")
}
resolved = all[idx - 1]
} else {
resolved = input
}
}
// Validate existence in bin/ or bin/archived/
def bundlePath = new File(projectDir, "bin/${bundleName}${resolved}")
if (!bundlePath.exists()) {
def archivedPath = new File(projectDir, "bin/archived/${bundleName}${resolved}")
if (archivedPath.exists()) {
bundlePath = archivedPath
} else {
def listing = all.collect { " - ${it}" }.join('\n')
throw new GradleException("Bundle version not found in bin/ or bin/archived/: ${bundleName}${resolved}\n\nAvailable versions:\n${listing}")
}
}
// Store resolved version
def propsFile = file("${buildTmpPath}/.gradle-bundleVersion")
propsFile.parentFile.mkdirs()
propsFile.text = resolved
println "\nSelected version: ${resolved}\n"
}
}
// Provider resolves version from either -PbundleVersion or value set by resolveVersion
def bundleVersionProvider = providers.provider {
def fromProp = project.findProperty('bundleVersion') as String
if (fromProp) return fromProp
def propsFile = file("${buildTmpPath}/.gradle-bundleVersion")
if (propsFile.exists()) {
return propsFile.text.trim()
}
return null
}
// Guard task: ensure bundleVersion is resolved before any packaging runs
tasks.register('assertVersionResolved') {
group = 'build'
description = 'Fail fast if bundleVersion was not resolved by resolveVersion'
dependsOn 'resolveVersion'
doLast {
def versionToBuild = bundleVersionProvider.getOrNull()
if (!versionToBuild) {
throw new GradleException("bundleVersion property not set. Run 'gradle resolveVersion' or invoke 'gradle release -PbundleVersion=<'*'|X.Y.Z>'")
}
}
}
// Task: Actual release build logic
tasks.register('releaseBuild') {
group = 'build'
description = 'Execute the release build process'
dependsOn 'resolveVersion'
doLast {
def versionToBuild = bundleVersionProvider.getOrNull()
if (!versionToBuild) {
throw new GradleException("bundleVersion property not set")
}
// Helper: Fetch python.properties from modules-untouched repository
def fetchModulesUntouchedProperties = {
def propsUrl = "https://raw.githubusercontent.com/Bearsampp/modules-untouched/main/modules/python.properties"
println "Checking modules-untouched repository..."
println "Fetching python.properties from modules-untouched repository..."
println " URL: ${propsUrl}"
def tempFile = file("${bundleTmpDownloadPath}/python-untouched.properties")
tempFile.parentFile.mkdirs()
try {
new URL(propsUrl).withInputStream { input ->
tempFile.withOutputStream { output ->
output << input
}
}
def props = new Properties()
tempFile.withInputStream { props.load(it) }
println " ✓ Successfully loaded ${props.size()} versions from modules-untouched"
return props
} catch (Exception e) {
println " ✗ Warning: Could not fetch python.properties from modules-untouched: ${e.message}"
return null
}
}
// Helper: Download Python binaries from modules-untouched repository
def downloadFromModulesUntouched = { String version ->
def untouchedProps = fetchModulesUntouchedProperties()
if (!untouchedProps) {
throw new GradleException("Could not fetch python.properties from modules-untouched repository")
}
def untouchedUrl = untouchedProps.getProperty(version)
if (!untouchedUrl) {
throw new GradleException("Version ${version} not found in modules-untouched python.properties")
}
println "Found version ${version} in modules-untouched python.properties"
println "Downloading from:"
println " ${untouchedUrl}"
def filename = untouchedUrl.substring(untouchedUrl.lastIndexOf('/') + 1)
def downloadDir = file(bundleTmpDownloadPath)
downloadDir.mkdirs()
def downloadedFile = file("${downloadDir}/${filename}")
if (!downloadedFile.exists()) {
println "Downloading to: ${downloadedFile}"
new URL(untouchedUrl).withInputStream { input ->
downloadedFile.withOutputStream { output ->
output << input
}
}
println "Download complete from modules-untouched"
} else {
println "Already downloaded: ${downloadedFile.name}"
}
return downloadedFile
}
// Helper: Extract Python archive
def extractPythonArchive = { File archive, String version ->
def extractDir = file("${buildTmpPath}/extract/${bundleName}")
extractDir.mkdirs()
println "Extracting archive..."
def extractPath = file("${extractDir}/${version}")
if (extractPath.exists()) {
delete extractPath
}
extractPath.mkdirs()
// Extract using Gradle's zipTree or 7z
if (archive.name.endsWith('.7z')) {
// Use 7z to extract
def sevenZipExe = find7ZipExecutable()
if (!sevenZipExe) {
throw new GradleException("7-Zip not found. Cannot extract .7z archive: ${archive.name}")
}
def command = [
sevenZipExe,
'x',
archive.absolutePath,
"-o${extractPath.absolutePath}",
'-y'
]
def process = new ProcessBuilder(command as String[])
.redirectErrorStream(true)
.start()
process.inputStream.eachLine { line ->
// Suppress output unless there's an error
}
def exitCode = process.waitFor()
if (exitCode != 0) {
throw new GradleException("7-Zip extraction failed with exit code: ${exitCode}")
}
} else {
// Use Gradle's zipTree for .zip files
copy {
from zipTree(archive)
into extractPath
}
}
println "Extraction complete"
// Find the Python directory (it might be nested)
def pythonDir = findPythonDirectory(extractPath)
if (!pythonDir) {
throw new GradleException("Could not find Python directory in extracted archive")
}
println "Found Python directory: ${pythonDir.name}"
return pythonDir
}
// Resolve bundle path from bin/ or bin/archived/
def bundlePath = new File(projectDir, "bin/${bundleName}${versionToBuild}")
if (!bundlePath.exists()) {
def archivedPath = new File(projectDir, "bin/archived/${bundleName}${versionToBuild}")
if (archivedPath.exists()) {
bundlePath = archivedPath
} else {
throw new GradleException("Bundle folder not found in bin/ or bin/archived/: ${bundleName}${versionToBuild}")
}
}
def bundleFolder = bundlePath.name
def bundleVersion = bundleFolder.replace(bundleName, '')
println "=".multiply(70)
println "\nBuilding ${bundleName} ${bundleVersion}\n"
println "=".multiply(70)
println "\nBundle path: ${bundlePath}"
// Prepare Python directory
def pythonPrepPath = new File(bundleTmpPrepPath, bundleFolder)
delete pythonPrepPath
pythonPrepPath.mkdirs()
// Determine source paths for Python binaries
def pythonSrcFinal = bundlePath
// Check if python.exe exists in the bundle directory
def pythonExe = file("${bundlePath}/python.exe")
if (!pythonExe.exists()) {
// Python binaries not found - need to download from modules-untouched
println "\nPython binaries not found"
println "Downloading Python ${bundleVersion}..."
println ""
try {
// Download and extract Python binaries
def downloadedArchive = downloadFromModulesUntouched(bundleVersion)
pythonSrcFinal = extractPythonArchive(downloadedArchive, bundleVersion)
println ""
println "NOTE: Version ${bundleVersion} was sourced from modules-untouched."
println "Source folder: ${pythonSrcFinal}"
} catch (Exception e) {
throw new GradleException("""
Failed to download Python binaries: ${e.message}
You can manually download and extract Python binaries to:
${bundlePath}/
Or check that version ${bundleVersion} exists in modules-untouched python.properties
""".stripIndent())
}
}
// Verify python.exe exists
pythonExe = file("${pythonSrcFinal}/python.exe")
if (!pythonExe.exists()) {
throw new GradleException("python.exe not found at ${pythonExe}")
}
println "\nCopying Python files..."
// For WinPython, we need the entire extracted directory structure
// which includes python/, scripts/, notebooks/, settings/, etc.
def winPythonRoot = pythonSrcFinal.parent
if (winPythonRoot && file(winPythonRoot).exists()) {
println "Copying complete WinPython distribution..."
copy {
from winPythonRoot
into pythonPrepPath
}
} else {
// Fallback: just copy the python directory
copy {
from pythonSrcFinal
into pythonPrepPath
}
}
// Overlay configuration files from bin/ directory (temp copy for PIP/wheel operations)
println "Overlaying bundle files from bin directory..."
copy {
from bundlePath
into pythonPrepPath
exclude 'pyqt5/**'
}
// Check if we have python.bat to run PIP upgrade (matching original build.xml)
def pythonBat = file("${pythonPrepPath}/bin/python.bat")
if (pythonBat.exists()) {
println "Upgrading PIP..."
// Upgrade PIP using bin/python.bat (matching original build.xml)
def pipUpgrade = ["cmd", "/c", "python.bat", "-m", "pip", "install", "--upgrade", "pip"]
def pipProcess = new ProcessBuilder(pipUpgrade as String[])
.directory(file("${pythonPrepPath}/bin"))
.redirectErrorStream(true)
.start()
pipProcess.inputStream.eachLine { line ->
if (line.trim()) println " ${line}"
}
def pipExitCode = pipProcess.waitFor()
if (pipExitCode != 0) {
throw new GradleException("PIP upgrade failed with exit code: ${pipExitCode}")
}
// Download and install wheel
def wheelDir = file("${pythonPrepPath}/wheel")
if (wheelDir.exists()) {
def wheelProps = file("${wheelDir}/wheel.properties")
if (wheelProps.exists()) {
def props = new Properties()
wheelProps.withInputStream { props.load(it) }
def wheelUrl = props.getProperty('wheel')
if (wheelUrl) {
println "Downloading Wheel..."
def wheelFile = wheelUrl.tokenize('/').last()
def wheelDest = file("${wheelDir}/${wheelFile}")
// Download wheel file if it doesn't exist
if (!wheelDest.exists()) {
wheelDest.parentFile.mkdirs()
new URL(wheelUrl).withInputStream { input ->
wheelDest.withOutputStream { output ->
output << input
}
}
}
// Install wheel using install.bat (matching original build.xml)
println "Installing Wheel..."
def installProcess = new ProcessBuilder(["cmd", "/c", "install.bat"] as String[])
.directory(wheelDir)
.redirectErrorStream(true)
.start()
installProcess.inputStream.eachLine { line ->
if (line.trim()) println " ${line}"
}
def installExitCode = installProcess.waitFor()
if (installExitCode != 0) {
throw new GradleException("Wheel installation failed with exit code: ${installExitCode}")
}
}
}
// Clean up wheel directory
wheelDir.deleteDir()
}
} else {
println "Skipping PIP upgrade (python.bat not found)"
println "Skipping wheel processing (python.bat not found)"
}
// Copy to bundles_build directory
def bundlesBuildPath = file("${bundleTmpBuildPath}/${bundleFolder}")
delete bundlesBuildPath
bundlesBuildPath.mkdirs()
println "Copying to bundles_build directory..."
copy {
from pythonPrepPath
into bundlesBuildPath
}
println "\nNon-zip version available at: ${bundlesBuildPath}"
// Store paths in a file for later use (avoid using project.ext at execution time)
def pathsFile = file("${buildTmpPath}/.gradle-build-paths")
pathsFile.parentFile.mkdirs()
pathsFile.text = "preparedBundlePath=${pythonPrepPath.absolutePath}\nbuildBundlePath=${bundlesBuildPath.absolutePath}"
}
}
def externalOutputDir = file("${moduleBuildOutputPath}")
// 7z packager
tasks.register('packageRelease7z') {
group = 'build'
description = 'Package release into a .7z archive (includes version folder at root)'
dependsOn 'assertVersionResolved', 'releaseBuild'
doLast {
def versionToBuild = bundleVersionProvider.getOrNull()
if (!versionToBuild) {
throw new GradleException("bundleVersion property not set")
}
def bundleFolder = "${bundleName}${versionToBuild}"
def prepRoot = file("${bundleTmpPrepPath}")
def srcDir = new File(prepRoot, bundleFolder)
if (!srcDir.exists()) {
throw new GradleException("Prepared folder not found: ${srcDir}. Run releaseBuild first.")
}
externalOutputDir.mkdirs()
def archiveName = "bearsampp-${bundleName}-${versionToBuild}-${bundleRelease}.7z"
def archiveFile = new File(externalOutputDir, archiveName)
if (archiveFile.exists()) {
delete archiveFile
}
println " 5. Creating release archive..."
println "\nPreparing archive..."
println "Compressing ${bundleFolder} to ${archiveName}..."
// Find 7z executable
def sevenZipExe = find7ZipExecutable()
if (!sevenZipExe) {
throw new GradleException("""
7-Zip not found. Please install 7-Zip or set 7Z_HOME environment variable.
Download from: https://www.7-zip.org/
Or set 7Z_HOME to your 7-Zip installation directory.
""".stripIndent())
}
println "Using 7-Zip: ${sevenZipExe}"
println ""
def command = [
sevenZipExe,
'a',
'-t7z',
archiveFile.absolutePath.toString(),
bundleFolder
]
def process = new ProcessBuilder(command as String[])
.directory(prepRoot)
.redirectErrorStream(true)
.start()
process.inputStream.eachLine { line ->
if (line.trim()) println line
}
def exitCode = process.waitFor()
if (exitCode != 0) {
throw new GradleException("7-Zip compression failed with exit code: ${exitCode}")
}
println ""
println "Archive created: ${archiveFile}"
}
}
// Zip packager
tasks.register('packageReleaseZip', Zip) {
group = 'build'
description = 'Package release into a .zip archive (includes version folder at root)'
dependsOn 'assertVersionResolved', 'releaseBuild'
doFirst {
def versionToBuild = bundleVersionProvider.getOrNull()
if (!versionToBuild) {
throw new GradleException("bundleVersion property not set")
}
def bundleFolder = "${bundleName}${versionToBuild}"
def prepRoot = file("${bundleTmpPrepPath}")
def srcDir = new File(prepRoot, bundleFolder)
if (!srcDir.exists()) {
throw new GradleException("Prepared folder not found: ${srcDir}. Run releaseBuild first.")
}
archiveFileName.set("bearsampp-${bundleName}-${versionToBuild}-${bundleRelease}.zip")
destinationDirectory.set(externalOutputDir)
from(prepRoot) {
include "${bundleFolder}/**"
}
println " 5. Creating release archive..."
println "\nPreparing archive..."
println "Compressing ${bundleFolder} to ${archiveFileName.get()}..."
}