-
Notifications
You must be signed in to change notification settings - Fork 4
/
Jenkinsfile
1518 lines (1486 loc) · 83.4 KB
/
Jenkinsfile
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
library identifier: 'JenkinsPythonHelperLibrary@2024.1.2', retriever: modernSCM(
[$class: 'GitSCMSource',
remote: 'https://github.com/UIUCLibrary/JenkinsPythonHelperLibrary.git',
])
def getVersion(){
node(){
checkout scm
def props = readTOML( file: 'pyproject.toml')['project']
return props.version
}
}
def getPypiConfig() {
retry(conditions: [agent()], count: 3) {
node(){
configFileProvider([configFile(fileId: 'pypi_config', variable: 'CONFIG_FILE')]) {
def config = readJSON( file: CONFIG_FILE)
return config['deployment']['indexes']
}
}
}
}
def getChocolateyServers() {
retry(conditions: [agent()], count: 3) {
node(){
configFileProvider([configFile(fileId: 'deploymentStorageConfig', variable: 'CONFIG_FILE')]) {
def config = readJSON( file: CONFIG_FILE)
return config['chocolatey']['sources']
}
}
}
}
def getStandAloneStorageServers(){
retry(conditions: [agent()], count: 3) {
node(){
configFileProvider([configFile(fileId: 'deploymentStorageConfig', variable: 'CONFIG_FILE')]) {
def config = readJSON( file: CONFIG_FILE)
return config['publicReleases']['urls']
}
}
}
}
def deployStandalone(glob, url) {
script{
findFiles(glob: glob).each{
try{
def put_response = httpRequest authentication: NEXUS_CREDS, httpMode: 'PUT', uploadFile: it.path, url: "${url}/${it.name}", wrapAsMultipart: false
echo "http request response: ${put_response.content}"
} catch(Exception e){
throw e;
}
}
// deploy_artifacts_to_url('dist/*.msi,dist/*.exe,dist/*.zip,dist/*.tar.gz,dist/docs/*.pdf,dist/docs/*.dng', "https://jenkins.library.illinois.edu/nexus/repository/prescon-beta/speedwagon/${props.version}/")
}
}
def macAppleBundle() {
stage('Create Build Environment'){
unstash 'PYTHON_PACKAGES'
sh(
label: 'Creating build environment',
script: '''python3 -m venv --upgrade-deps venv
. ./venv/bin/activate
pip install wheel
pip install -r requirements-freeze.txt
'''
)
findFiles(glob: 'dist/speedwagon*.whl').each{ wheel ->
sh(label: "Installing ${wheel.name}", script: "venv/bin/pip install ${wheel}")
}
sh('venv/bin/pip list')
}
stage('Building Apple Application Bundle'){
sh(label: 'Running pyinstaller script', script: 'venv/bin/python packaging/create_osx_app_bundle.py')
findFiles(glob: 'dist/*.dmg').each{
echo "SHA256 value of ${it.path} = \"${sha256 (it.path)}\""
}
}
}
def run_pylint(){
def MAX_TIME = 10
withEnv(['PYLINTHOME=.']) {
sh '''. ./venv/bin/activate
pylint --version
'''
catchError(buildResult: 'SUCCESS', message: 'Pylint found issues', stageResult: 'UNSTABLE') {
timeout(MAX_TIME){
tee('reports/pylint_issues.txt'){
sh(
label: 'Running pylint',
script: '''. ./venv/bin/activate
pylint speedwagon -j 2 -r n --msg-template="{path}:{module}:{line}: [{msg_id}({symbol}), {obj}] {msg}"
''',
)
}
}
}
timeout(MAX_TIME){
sh(
label: 'Running pylint for sonarqube',
script: '''. ./venv/bin/activate
pylint speedwagon -j 2 -d duplicate-code --output-format=parseable | tee reports/pylint.txt
''',
returnStatus: true
)
}
}
}
def get_build_number(){
script{
try{
def versionPrefix = ''
if(currentBuild.getBuildCauses()[0].shortDescription == 'Started by timer'){
versionPrefix = 'Nightly'
}
return VersionNumber(projectStartDate: '2017-11-08', versionNumberString: '${BUILD_DATE_FORMATTED, "yy"}${BUILD_MONTH, XX}${BUILDS_THIS_MONTH, XXX}', versionPrefix: '', worstResultForIncrement: 'SUCCESS')
} catch(e){
return ''
}
}
}
def testSpeedwagonChocolateyPkg(version){
script{
def chocolatey = load('ci/jenkins/scripts/chocolatey.groovy')
chocolatey.install_chocolatey_package(
name: 'speedwagon',
version: chocolatey.sanitize_chocolatey_version(version),
source: './packages/;CHOCOLATEY_SOURCE;chocolatey',
retries: 3
)
}
powershell(
label: 'Checking for Start Menu shortcut',
script: 'Get-ChildItem "$Env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs" -Recurse -Include *.lnk'
)
// powershell('''
// $proc = Start-Process "$Env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs\\speedwagon\\speedwagon.lnk" --PassThru
// (Get-Process -Id $proc.Id).MainWindowHandle
// Stop-Process -Id $proc.Id
// '''
// )
bat 'speedwagon --help'
}
def testReinstallSpeedwagonChocolateyPkg(version){
script{
def chocolatey = load('ci/jenkins/scripts/chocolatey.groovy')
chocolatey.reinstall_chocolatey_package(
name: 'speedwagon',
version: chocolatey.sanitize_chocolatey_version(version),
source: './packages/;CHOCOLATEY_SOURCE;chocolatey',
retries: 3
)
}
powershell(
label: 'Checking for Start Menu shortcut',
script: 'Get-ChildItem "$Env:ProgramData\\Microsoft\\Windows\\Start Menu\\Programs" -Recurse -Include *.lnk'
)
bat 'speedwagon --help'
}
def startup(){
parallel(
[
failFast: true,
'Loading Reference Build Information': {
node(){
checkout scm
discoverGitReferenceBuild(latestBuildIfNotFound: true)
}
},
'Enable Git Forensics': {
node(){
checkout scm
mineRepository()
}
},
]
)
}
def testChocolateyPackage(){
def props = readTOML( file: 'pyproject.toml')['project']
stage('Install'){
unstash 'CHOCOLATEY_PACKAGE'
testSpeedwagonChocolateyPkg(props.version)
}
stage('Reinstall/Upgrade'){
testReinstallSpeedwagonChocolateyPkg(props.version)
}
stage('Uninstall'){
bat 'choco uninstall speedwagon --confirm'
}
}
startup()
def get_sonarqube_unresolved_issues(report_task_file){
script{
def props = readProperties file: '.scannerwork/report-task.txt'
def response = httpRequest url : props['serverUrl'] + "/api/issues/search?componentKeys=" + props['projectKey'] + "&resolved=no"
def outstandingIssues = readJSON text: response.content
return outstandingIssues
}
}
def installMSVCRuntime(cacheLocation){
def cachedFile = "${cacheLocation}\\vc_redist.x64.exe".replaceAll(/\\\\+/, '\\\\')
withEnv(
[
"CACHED_FILE=${cachedFile}",
"RUNTIME_DOWNLOAD_URL=https://aka.ms/vs/17/release/vc_redist.x64.exe"
]
){
lock("${cachedFile}-${env.NODE_NAME}"){
powershell(
label: 'Ensuring vc_redist runtime installer is available',
script: '''if ([System.IO.File]::Exists("$Env:CACHED_FILE"))
{
Write-Host 'Found installer'
} else {
Write-Host 'No installer found'
Write-Host 'Downloading runtime'
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12;Invoke-WebRequest "$Env:RUNTIME_DOWNLOAD_URL" -OutFile "$Env:CACHED_FILE"
}
'''
)
}
powershell(label: 'Install VC Runtime', script: 'Start-Process -filepath "$Env:CACHED_FILE" -ArgumentList "/install", "/passive", "/norestart" -Passthru | Wait-Process;')
}
}
def hasSonarCreds(credentialsId){
try{
withCredentials([string(credentialsId: credentialsId, variable: 'dddd')]) {
echo 'Found credentials for sonarqube'
}
} catch(e){
return false
}
return true
}
pipeline {
agent none
parameters {
booleanParam(name: 'RUN_CHECKS', defaultValue: true, description: 'Run checks on code')
booleanParam(name: 'USE_SONARQUBE', defaultValue: true, description: 'Send data test data to SonarQube')
credentials(name: 'SONARCLOUD_TOKEN', credentialType: 'org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl', defaultValue: 'sonarcloud_token', required: false)
booleanParam(name: 'TEST_RUN_TOX', defaultValue: false, description: 'Run Tox Tests')
booleanParam(name: 'BUILD_PACKAGES', defaultValue: false, description: 'Build Packages')
booleanParam(name: 'TEST_STANDALONE_PACKAGE_DEPLOYMENT', defaultValue: true, description: 'Test deploying any packages that are designed to be installed without using Python directly')
booleanParam(name: 'BUILD_CHOCOLATEY_PACKAGE', defaultValue: false, description: 'Build package for chocolatey package manager')
booleanParam(name: 'INCLUDE_LINUX-ARM64', defaultValue: false, description: 'Include ARM architecture for Linux')
booleanParam(name: 'INCLUDE_LINUX-X86_64', defaultValue: true, description: 'Include x86_64 architecture for Linux')
booleanParam(name: 'INCLUDE_MACOS-ARM64', defaultValue: false, description: 'Include ARM(m1) architecture for Mac')
booleanParam(name: 'INCLUDE_MACOS-X86_64', defaultValue: false, description: 'Include x86_64 architecture for Mac')
booleanParam(name: 'INCLUDE_WINDOWS-X86_64', defaultValue: true, description: 'Include x86_64 architecture for Windows')
booleanParam(name: 'TEST_PACKAGES', defaultValue: true, description: 'Test Python packages by installing them and running tests on the installed package')
booleanParam(name: 'PACKAGE_MAC_OS_STANDALONE_DMG', defaultValue: false, description: 'Create a Apple Application Bundle DMG')
booleanParam(name: 'PACKAGE_WINDOWS_STANDALONE_MSI', defaultValue: false, description: 'Create a standalone wix based .msi installer')
booleanParam(name: 'PACKAGE_WINDOWS_STANDALONE_NSIS', defaultValue: false, description: 'Create a standalone NULLSOFT NSIS based .exe installer')
booleanParam(name: 'PACKAGE_WINDOWS_STANDALONE_ZIP', defaultValue: false, description: 'Create a standalone portable package')
booleanParam(name: 'DEPLOY_PYPI', defaultValue: false, description: 'Deploy to pypi')
booleanParam(name: 'DEPLOY_CHOCOLATEY', defaultValue: false, description: 'Deploy to Chocolatey repository')
booleanParam(name: 'DEPLOY_STANDALONE_PACKAGERS', defaultValue: false, description: 'Deploy standalone packages')
booleanParam(name: 'DEPLOY_DOCS', defaultValue: false, description: 'Update online documentation')
}
stages {
stage('Build Sphinx Documentation'){
agent {
docker{
image 'sphinxdoc/sphinx-latexpdf'
label 'linux && docker && x86'
}
}
options {
retry(conditions: [agent()], count: 2)
}
environment{
PIP_CACHE_DIR = '/tmp/pipcache'
UV_INDEX_STRATEGY = 'unsafe-best-match'
UV_TOOL_DIR = '/tmp/uvtools'
UV_PYTHON_INSTALL_DIR = '/tmp/uvpython'
UV_CACHE_DIR = '/tmp/uvcache'
UV_PYTHON = '3.11'
}
steps {
catchError(buildResult: 'UNSTABLE', message: 'Sphinx has warnings', stageResult: 'UNSTABLE') {
sh(label: 'Build docs in html and Latex formats',
script:'''python3 -m venv venv
trap "rm -rf venv" EXIT
. ./venv/bin/activate
pip install uv
uvx --from sphinx --with-editable . --with-requirements requirements-dev.txt sphinx-build -W --keep-going -b html -d build/docs/.doctrees -w logs/build_sphinx_html.log docs/source build/docs/html
uvx --from sphinx --with-editable . --with-requirements requirements-dev.txt sphinx-build -W --keep-going -b latex -d build/docs/.doctrees docs/source build/docs/latex
''')
sh(label: 'Building PDF docs',
script: '''make -C build/docs/latex
mkdir -p dist/docs
mv build/docs/latex/*.pdf dist/docs/
'''
)
}
}
post{
always{
recordIssues(tools: [sphinxBuild(pattern: 'logs/build_sphinx_html.log')])
}
success{
stash includes: 'dist/docs/*.pdf', name: 'SPEEDWAGON_DOC_PDF'
script{
def props = readTOML( file: 'pyproject.toml')['project']
zip archive: true, dir: 'build/docs/html', glob: '', zipFile: "dist/${props.name}-${props.version}.doc.zip"
}
stash includes: 'dist/*.doc.zip,build/docs/html/**', name: 'DOCS_ARCHIVE'
archiveArtifacts artifacts: 'dist/docs/*.pdf'
}
cleanup{
cleanWs(
notFailBuild: true,
deleteDirs: true,
patterns: [
[pattern: 'logs/', type: 'INCLUDE'],
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: 'dist/', type: 'INCLUDE'],
[pattern: 'build/', type: 'INCLUDE'],
]
)
}
}
}
stage('Checks'){
stages{
stage('Code Quality'){
when{
equals expected: true, actual: params.RUN_CHECKS
beforeAgent true
}
agent {
dockerfile {
filename 'ci/docker/python/linux/jenkins/Dockerfile'
label 'linux && docker && x86'
args '--mount source=python-tmp-speedwagon,target=/tmp'
}
}
environment{
PIP_CACHE_DIR='/tmp/pipcache'
UV_INDEX_STRATEGY='unsafe-best-match'
UV_TOOL_DIR='/tmp/uvtools'
UV_PYTHON_INSTALL_DIR='/tmp/uvpython'
UV_CACHE_DIR='/tmp/uvcache'
UV_PYTHON='3.11'
QT_QPA_PLATFORM='offscreen'
}
options {
retry(conditions: [agent()], count: 2)
}
stages{
stage('Test') {
stages{
stage('Configuring Testing Environment'){
steps{
sh(
label: 'Create virtual environment',
script: '''python3 -m venv bootstrap_uv
bootstrap_uv/bin/pip install uv
bootstrap_uv/bin/uv venv venv
. ./venv/bin/activate
bootstrap_uv/bin/uv pip install uv
rm -rf bootstrap_uv
uv pip install -r requirements-dev.txt -r requirements-gui.txt
'''
)
sh(
label: 'Install package in development mode',
script: '''. ./venv/bin/activate
uv pip install -e .
'''
)
sh(
label: 'Creating logging and report directories',
script: '''mkdir -p logs
mkdir -p reports
'''
)
}
}
stage('Run Tests'){
parallel {
stage('Run PyTest Unit Tests'){
steps{
catchError(buildResult: 'UNSTABLE', message: 'Did not pass all pytest tests', stageResult: 'UNSTABLE') {
sh(
script: '''. ./venv/bin/activate
PYTHONFAULTHANDLER=1 coverage run --parallel-mode --source=speedwagon -m pytest --junitxml=./reports/tests/pytest/pytest-junit.xml --capture=no
'''
)
}
}
post {
always {
junit(allowEmptyResults: true, testResults: 'reports/tests/pytest/pytest-junit.xml')
stash(allowEmpty: true, includes: 'reports/tests/pytest/*.xml', name: 'PYTEST_UNIT_TEST_RESULTS')
}
}
}
stage('Task Scanner'){
steps{
recordIssues(tools: [taskScanner(highTags: 'FIXME', includePattern: 'speedwagon/**/*.py', normalTags: 'TODO')])
}
}
stage('Audit Requirement Freeze File'){
steps{
catchError(buildResult: 'SUCCESS', message: 'pip-audit found issues', stageResult: 'UNSTABLE') {
sh './venv/bin/uvx --python-preference=only-managed --with-requirements requirements-gui.txt pip-audit --cache-dir=/tmp/pip-audit-cache --local'
}
}
}
stage('Run Doctest Tests'){
steps {
sh(
label: 'Running Doctest Tests',
script: '''. ./venv/bin/activate
coverage run --parallel-mode --source=speedwagon -m sphinx -b doctest docs/source build/docs -d build/docs/doctrees --no-color -w logs/doctest.txt
'''
)
}
post{
always {
recordIssues(tools: [sphinxBuild(id: 'doctest', name: 'Doctest', pattern: 'logs/doctest.txt')])
}
}
}
stage('Run MyPy Static Analysis') {
steps{
catchError(buildResult: 'SUCCESS', message: 'MyPy found issues', stageResult: 'UNSTABLE') {
tee('logs/mypy.log'){
sh(label: 'Running MyPy',
script: '''. ./venv/bin/activate
mypy -p speedwagon --html-report reports/mypy/html
'''
)
}
}
}
post {
always {
recordIssues(tools: [myPy(pattern: 'logs/mypy.log')])
publishHTML([allowMissing: true, alwaysLinkToLastBuild: false, keepAll: false, reportDir: 'reports/mypy/html/', reportFiles: 'index.html', reportName: 'MyPy HTML Report', reportTitles: ''])
}
}
}
stage('Run Ruff Static Analysis') {
steps{
catchError(buildResult: 'SUCCESS', message: 'Ruff found issues', stageResult: 'UNSTABLE') {
sh(label: 'Running Ruff',
script: '''. ./venv/bin/activate
mkdir -p reports && ruff check --config=pyproject.toml -o reports/ruffoutput.json --output-format json
'''
)
}
}
}
stage('Run Pylint Static Analysis') {
steps{
run_pylint()
}
post{
always{
stash includes: 'reports/pylint_issues.txt,reports/pylint.txt', name: 'PYLINT_REPORT'
recordIssues(tools: [pyLint(pattern: 'reports/pylint_issues.txt')])
}
}
}
stage('Run Flake8 Static Analysis') {
steps{
catchError(buildResult: 'SUCCESS', message: 'Flake8 found issues', stageResult: 'UNSTABLE') {
sh script: '''. ./venv/bin/activate
flake8 speedwagon -j 1 --tee --output-file=logs/flake8.log
'''
}
}
post {
always {
stash includes: 'logs/flake8.log', name: 'FLAKE8_REPORT'
recordIssues(tools: [flake8(pattern: 'logs/flake8.log')])
}
}
}
stage('pyDocStyle'){
steps{
catchError(buildResult: 'SUCCESS', message: 'Did not pass all pyDocStyle tests', stageResult: 'UNSTABLE') {
sh(
label: 'Run pydocstyle',
script: '''. ./venv/bin/activate
pydocstyle speedwagon > reports/pydocstyle-report.txt
'''
)
}
}
post {
always{
recordIssues(tools: [pyDocStyle(pattern: 'reports/pydocstyle-report.txt')])
}
}
}
}
post{
always{
sh '''. ./venv/bin/activate
coverage combine && coverage xml -o reports/coverage.xml && coverage html -d reports/coverage
'''
stash includes: 'reports/coverage.xml', name: 'COVERAGE_REPORT_DATA'
recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'reports/coverage.xml']])
}
}
}
}
}
stage('Run Sonarqube Analysis'){
options{
lock('speedwagon-sonarscanner')
}
when{
allOf{
equals expected: true, actual: params.USE_SONARQUBE
expression{
return hasSonarCreds(params.SONARCLOUD_TOKEN)
}
}
}
environment{
VERSION="${readTOML( file: 'pyproject.toml')['project'].version}"
SONAR_USER_HOME='/tmp/sonar'
}
steps{
script{
withSonarQubeEnv(installationName:'sonarcloud', credentialsId: params.SONARCLOUD_TOKEN) {
def sourceInstruction
if (env.CHANGE_ID){
sourceInstruction = '-Dsonar.pullrequest.key=$CHANGE_ID -Dsonar.pullrequest.base=$BRANCH_NAME'
} else{
sourceInstruction = '-Dsonar.branch.name=$BRANCH_NAME'
}
sh(
label: 'Running Sonar Scanner',
script: """. ./venv/bin/activate
uv tool run pysonar-scanner -Dsonar.projectVersion=$VERSION -Dsonar.buildString=\"$BUILD_TAG\" ${sourceInstruction}
"""
)
}
timeout(time: 1, unit: 'HOURS') {
def sonarqube_result = waitForQualityGate(abortPipeline: false)
if (sonarqube_result.status != 'OK') {
unstable "SonarQube quality gate: ${sonarqube_result.status}"
}
def outstandingIssues = get_sonarqube_unresolved_issues('.scannerwork/report-task.txt')
writeJSON file: 'reports/sonar-report.json', json: outstandingIssues
}
milestone label: 'sonarcloud'
}
}
post {
always{
recordIssues(tools: [sonarQube(pattern: 'reports/sonar-report.json')])
}
}
}
}
post{
cleanup{
cleanWs(patterns: [
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: 'logs/*', type: 'INCLUDE'],
[pattern: 'reports/', type: 'INCLUDE'],
[pattern: '.coverage', type: 'INCLUDE']
])
}
failure{
sh 'pip list'
}
}
}
stage('Run Tox'){
when{
equals expected: true, actual: params.TEST_RUN_TOX
}
parallel{
stage('Linux') {
when{
expression {return nodesByLabel('linux && docker').size() > 0}
}
environment{
PIP_CACHE_DIR='/tmp/pipcache'
UV_INDEX_STRATEGY='unsafe-best-match'
UV_TOOL_DIR='/tmp/uvtools'
UV_PYTHON_INSTALL_DIR='/tmp/uvpython'
UV_CACHE_DIR='/tmp/uvcache'
}
steps{
script{
def envs = []
node('docker && linux'){
docker.image('python').inside('--mount source=python-tmp-speedwagon,target=/tmp'){
try{
checkout scm
sh(script: 'python3 -m venv venv && venv/bin/pip install uv')
envs = sh(
label: 'Get tox environments',
script: './venv/bin/uvx --quiet --with tox-uv tox list -d --no-desc',
returnStdout: true,
).trim().split('\n')
} finally{
cleanWs(
patterns: [
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '.tox', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
}
parallel(
envs.collectEntries{toxEnv ->
def version = toxEnv.replaceAll(/py(\d)(\d+).*/, '$1.$2')
[
"Tox Environment: ${toxEnv}",
{
node('docker && linux && x86_64'){
checkout scm
def image = docker.build(UUID.randomUUID().toString(), '-f ci/docker/python/linux/jenkins/Dockerfile .')
try{
image.inside('--mount source=python-tmp-speedwagon,target=/tmp'){
try{
sh( label: 'Running Tox',
script: """python3 -m venv venv && venv/bin/pip install uv
. ./venv/bin/activate
uv python install cpython-${version}
uvx -p ${version} --with tox-uv tox run -e ${toxEnv}
"""
)
} catch(e) {
sh(script: '''. ./venv/bin/activate
uv python list
'''
)
throw e
} finally{
cleanWs(
patterns: [
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '.tox/', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
} finally {
sh "docker image rm --force ${image.imageName()}"
}
}
}
]
}
)
}
}
}
stage('Windows') {
when{
expression {return nodesByLabel('windows && docker && x86').size() > 0}
}
environment{
UV_INDEX_STRATEGY='unsafe-best-match'
PIP_CACHE_DIR='C:\\Users\\ContainerUser\\Documents\\pipcache'
UV_TOOL_DIR='C:\\Users\\ContainerUser\\Documents\\uvtools'
UV_PYTHON_INSTALL_DIR='C:\\Users\\ContainerUser\\Documents\\uvpython'
UV_CACHE_DIR='C:\\Users\\ContainerUser\\Documents\\uvcache'
VC_RUNTIME_INSTALLER_LOCATION='c:\\msvc_runtime\\'
}
steps{
script{
def envs = []
node('docker && windows'){
docker.image('python').inside('--mount source=python-tmp-speedwagon,target=C:\\Users\\ContainerUser\\Documents'){
try{
checkout scm
bat(script: 'python -m venv venv && venv\\Scripts\\pip install uv')
envs = bat(
label: 'Get tox environments',
script: '@.\\venv\\Scripts\\uvx --quiet --with tox-uv tox list -d --no-desc',
returnStdout: true,
).trim().split('\r\n')
} finally{
cleanWs(
patterns: [
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '.tox/', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
}
parallel(
envs.collectEntries{toxEnv ->
def version = toxEnv.replaceAll(/py(\d)(\d+).*/, '$1.$2')
[
"Tox Environment: ${toxEnv}",
{
node('docker && windows'){
docker.image('python').inside('--mount source=python-tmp-speedwagon,target=C:\\Users\\ContainerUser\\Documents --mount source=msvc-runtime,target=$VC_RUNTIME_INSTALLER_LOCATION'){
installMSVCRuntime(env.VC_RUNTIME_INSTALLER_LOCATION)
checkout scm
try{
bat(label: 'Install uv',
script: 'python -m venv venv && venv\\Scripts\\pip install uv'
)
retry(3){
bat(label: 'Running Tox',
script: """call venv\\Scripts\\activate.bat
uv python install cpython-${version}
uvx -p ${version} --with tox-uv tox run -e ${toxEnv}
"""
)
}
} finally{
cleanWs(
patterns: [
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '.tox', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
}
}
]
}
)
}
}
}
}
}
}
}
stage('Packaging'){
when{
anyOf{
equals expected: true, actual: params.BUILD_PACKAGES
equals expected: true, actual: params.BUILD_CHOCOLATEY_PACKAGE
equals expected: true, actual: params.PACKAGE_MAC_OS_STANDALONE_DMG
equals expected: true, actual: params.DEPLOY_STANDALONE_PACKAGES
equals expected: true, actual: params.DEPLOY_CHOCOLATEY
equals expected: true, actual: params.PACKAGE_WINDOWS_STANDALONE_MSI
equals expected: true, actual: params.PACKAGE_WINDOWS_STANDALONE_NSIS
equals expected: true, actual: params.PACKAGE_WINDOWS_STANDALONE_ZIP
}
beforeAgent true
}
stages{
stage('Python Packages'){
stages{
stage('Packaging sdist and wheel'){
agent {
docker{
image 'python'
label 'linux && docker'
args '--mount source=python-tmp-speedwagon,target=/tmp'
}
}
environment{
PIP_CACHE_DIR='/tmp/pipcache'
UV_INDEX_STRATEGY='unsafe-best-match'
UV_CACHE_DIR='/tmp/uvcache'
}
options {
retry(2)
}
steps{
timeout(5){
sh(
label: 'Package',
script: '''python3 -m venv venv && venv/bin/pip install uv
trap "rm -rf venv" EXIT
. ./venv/bin/activate
uv build
'''
)
}
}
post{
always{
stash includes: 'dist/*.whl,dist/*.tar.gz,dist/*.zip', name: 'PYTHON_PACKAGES'
}
cleanup{
cleanWs(
deleteDirs: true,
patterns: [
[pattern: '**/__pycache__/', type: 'INCLUDE'],
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: 'dist/', type: 'INCLUDE']
]
)
}
}
}
stage('Testing Python Package'){
when{
equals expected: true, actual: params.TEST_PACKAGES
}
matrix {
axes {
axis {
name 'PYTHON_VERSION'
values '3.9', '3.10', '3.11', '3.12'
}
axis {
name 'OS'
values 'linux', 'macos', 'windows'
}
axis {
name 'ARCHITECTURE'
values 'arm64', 'x86_64'
}
axis {
name 'PACKAGE_TYPE'
values 'wheel', 'sdist'
}
}
excludes {
exclude {
axis {
name 'ARCHITECTURE'
values 'arm64'
}
axis {
name 'OS'
values 'windows'
}
}
}
when{
expression{
params.containsKey("INCLUDE_${OS}-${ARCHITECTURE}".toUpperCase()) && params["INCLUDE_${OS}-${ARCHITECTURE}".toUpperCase()]
}
}
options {
retry(conditions: [agent()], count: 2)
}
environment{
UV_PYTHON="${PYTHON_VERSION}"
TOX_ENV="py${PYTHON_VERSION.replace('.', '')}"
UV_INDEX_STRATEGY='unsafe-best-match'
}
stages {
stage('Test Package in container') {
when{
expression{['linux', 'windows'].contains(OS)}
beforeAgent true
}
environment{
PIP_CACHE_DIR="${isUnix() ? '/tmp/pipcache': 'C:\\Users\\ContainerUser\\Documents\\pipcache'}"
UV_TOOL_DIR="${isUnix() ? '/tmp/uvtools': 'C:\\Users\\ContainerUser\\Documents\\uvtools'}"
UV_PYTHON_INSTALL_DIR="${isUnix() ? '/tmp/uvpython': 'C:\\Users\\ContainerUser\\Documents\\uvpython'}"
UV_CACHE_DIR="${isUnix() ? '/tmp/uvcache': 'C:\\Users\\ContainerUser\\Documents\\uvcache'}"
}
agent {
docker {
image 'python'
label "${OS} && ${ARCHITECTURE} && docker"
args "--mount source=python-tmp-speedwagon,target=${['windows'].contains(OS) ? 'C:\\Users\\ContainerUser\\Documents': '/tmp'} ${['windows'].contains(OS) ? '--mount source=msvc-runtime,target=c:\\msvc_runtime\\': ''}"
}
}
steps {
unstash 'PYTHON_PACKAGES'
script{
withEnv(
["TOX_INSTALL_PKG=${findFiles(glob: PACKAGE_TYPE == 'wheel' ? 'dist/*.whl' : 'dist/*.tar.gz')[0].path}"]
) {
if(isUnix()){
sh(
label: 'Testing with tox',
script: '''python3 -m venv venv
. ./venv/bin/activate
trap "rm -rf venv" EXIT
pip install uv
uvx --with tox-uv tox
'''
)
} else {
installMSVCRuntime('c:\\msvc_runtime\\')
script{
retry(3){
bat(
label: 'Testing with tox',
script: '''python -m venv venv
call venv\\Scripts\\activate.bat
pip install uv
uvx --with tox-uv tox
rmdir /S /Q .tox
rmdir /S /Q venv
'''
)
}
}
}
}
}
}
post{
cleanup{
cleanWs(
patterns: [
[pattern: 'dist/', type: 'INCLUDE'],
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
}
stage('Test Package directly on agent') {
when{
expression{['macos'].contains(OS)}
beforeAgent true
}
agent {
label "${OS} && ${ARCHITECTURE}"
}
steps {
unstash 'PYTHON_PACKAGES'
withEnv(
["TOX_INSTALL_PKG=${findFiles(glob: PACKAGE_TYPE == 'wheel' ? 'dist/*.whl' : 'dist/*.tar.gz')[0].path}"]
) {
sh(
label: 'Testing with tox',
script: '''python3 -m venv venv
trap "rm -rf venv" EXIT
. ./venv/bin/activate
pip install uv
uvx --with tox-uv tox
'''
)
}
}
post{
cleanup{
cleanWs(
patterns: [
[pattern: 'dist/', type: 'INCLUDE'],
[pattern: 'venv/', type: 'INCLUDE'],
[pattern: '**/__pycache__/', type: 'INCLUDE'],
]
)
}
}
}
}
}
}
}
}
stage('End-user packages'){
parallel{
stage('Mac Application Bundle x86_64'){
agent{
label 'mac && python3 && x86_64'
}
when{
allOf{
equals expected: true, actual: params.PACKAGE_MAC_OS_STANDALONE_DMG
expression {return nodesByLabel('mac && x86_64 && python3').size() > 0}
}
beforeInput true
}