This repository has been archived by the owner on Jan 30, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgovuk.groovy
952 lines (846 loc) · 27.2 KB
/
govuk.groovy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
#!/usr/bin/env groovy
def buildProject(Map options = [:]) {
def jobName = JOB_NAME.split('/')[0]
def repoName
def gemName
if (options.repoName) {
repoName = options.repoName
} else {
repoName = jobName
}
if (options.gemName) {
gemName = options.gemName
} else {
gemName = repoName
}
def parameterDefinitions = [
booleanParam(
name: 'IS_SCHEMA_TEST',
defaultValue: false,
description: 'Identifies whether this build is being triggered to test a change to the content schemas'
),
booleanParam(
name: 'PUSH_TO_GCR',
defaultValue: false,
description: '--TESTING ONLY-- Whether to push the docker image to Google Container Registry.'
),
booleanParam(
name: 'RUN_DOCKER_TASKS',
defaultValue: true,
description: 'Whether to build and push the Docker image, if a Dockerfile exists.'
),
stringParam(
name: 'SCHEMA_BRANCH',
defaultValue: 'deployed-to-production',
description: 'The branch of govuk-content-schemas to test against'
),
stringParam(
name: 'SCHEMA_COMMIT',
defaultValue: 'invalid',
description: 'The commit of govuk-content-schemas that triggered this build, if it is a schema test'
)
]
if (options.publishingE2ETests == true && env.PUBLISHING_E2E_TESTS_BRANCH == null) {
parameterDefinitions << stringParam(
name: "PUBLISHING_E2E_TESTS_BRANCH",
defaultValue: "test-against",
description: "The branch of publishing-e2e-tests to test against"
)
}
if (options.extraParameters) {
parameterDefinitions.addAll(options.extraParameters)
}
properties([
buildDiscarder(
logRotator(numToKeepStr: '50')
),
[$class: 'RebuildSettings', autoRebuild: false, rebuildDisabled: false],
[$class: 'ParametersDefinitionProperty', parameterDefinitions: parameterDefinitions],
])
def defaultParameterValuesMap = [:]
parameterDefinitions.each {
// to handle params defined with the xxxParam(...) DSL instead of
// [$class: ... ] style because we can't call .name / .defaultValue
// on them directly
if (it.class == org.jenkinsci.plugins.structs.describable.UninstantiatedDescribable) {
def mapVersionOfIt = it.toMap()
defaultParameterValuesMap[mapVersionOfIt.name] = mapVersionOfIt.defaultValue
} else {
defaultParameterValuesMap[it.name] = it.defaultValue
}
}
initializeParameters(defaultParameterValuesMap)
try {
if (!isAllowedBranchBuild(env.BRANCH_NAME)) {
return
}
if (params.IS_SCHEMA_TEST) {
setBuildStatus(jobName, params.SCHEMA_COMMIT, "Downstream ${jobName} job is building on Jenkins", 'PENDING', 'govuk-content-schemas')
}
stage("Checkout") {
checkoutFromGitHubWithSSH(repoName)
}
stage("Merge master") {
mergeMasterBranch()
}
stage("Configure environment") {
setEnvar("DISABLE_DATABASE_ENVIRONMENT_CHECK", "1")
setEnvar("RAILS_ENV", "test")
setEnvar("RACK_ENV", "test")
setEnvar("DISPLAY", ":99")
}
if (hasDockerfile() && params.RUN_DOCKER_TASKS && !params.IS_SCHEMA_TEST) {
parallel (
"build" : { nonDockerBuildTasks(options, jobName, repoName) },
"docker" : { dockerBuildTasks(options, jobName) }
)
} else {
nonDockerBuildTasks(options, jobName, repoName)
}
if (env.BRANCH_NAME == "master" && !params.IS_SCHEMA_TEST) {
if (isGem()) {
stage("Publish Gem to Rubygems") {
publishGem(gemName, repoName, env.BRANCH_NAME)
}
} else {
stage("Push release tag") {
pushTag(repoName, env.BRANCH_NAME, 'release_' + env.BUILD_NUMBER)
}
if (hasDockerfile() && params.RUN_DOCKER_TASKS) {
stage("Tag Docker image") {
dockerTagMasterBranch(jobName, env.BRANCH_NAME, env.BUILD_NUMBER)
}
}
if (!options.skipDeployToIntegration) {
stage("Deploy to integration") {
deployIntegration(jobName, env.BRANCH_NAME, "release_${env.BUILD_NUMBER}", 'deploy')
}
}
}
}
if (params.IS_SCHEMA_TEST) {
setBuildStatus(jobName, params.SCHEMA_COMMIT, "Downstream ${jobName} job succeeded on Jenkins", 'SUCCESS', 'govuk-content-schemas')
}
} catch (e) {
currentBuild.result = "FAILED"
step([$class: 'Mailer',
notifyEveryUnstableBuild: true,
recipients: '[email protected]',
sendToIndividuals: true])
if (params.IS_SCHEMA_TEST) {
setBuildStatus(jobName, params.SCHEMA_COMMIT, "Downstream ${jobName} job failed on Jenkins", 'FAILED', 'govuk-content-schemas')
}
throw e
}
}
def nonDockerBuildTasks(options, jobName, repoName) {
contentSchemaDependency(params.SCHEMA_BRANCH)
stage("bundle install") {
isGem() ? bundleGem() : bundleApp()
}
if (isRails() || options.brakeman) {
stage("Security analysis") {
runBrakemanSecurityScanner(repoName)
}
}
if (options.yarnInstall != false && fileExists(file: "yarn.lock")) {
stage("yarn install") {
sh("yarn install --frozen-lockfile")
}
}
if (options.beforeTest) {
echo "Running pre-test tasks"
options.beforeTest.call()
}
// Prevent a project's tests from running in parallel on the same node
lock("$jobName-$NODE_NAME-test") {
if (hasActiveRecordDatabase()) {
stage("Set up the ActiveRecord database") {
runRakeTask("db:reset")
}
}
if (hasMongoidDatabase()) {
stage("Set up the Mongoid database") {
runRakeTask("db:drop")
runRakeTask("db:setup")
}
}
if (hasAssets()) {
stage("Precompile assets") {
precompileAssets()
}
}
if (options.overrideTestTask) {
echo "Running custom test task"
options.overrideTestTask.call()
} else {
if (isGem()) {
def extraRubyVersions = options.extraRubyVersions == null ? [] : options.extraRubyVersions
testGemWithAllRubies(extraRubyVersions)
} else {
stage("Run tests") {
runTests()
}
}
}
if (fileExists(file: "coverage/rcov")) {
stage("Ruby Code Coverage") {
step([$class: "RcovPublisher", reportDir: "coverage/rcov"])
}
}
if (fileExists("test/reports") ||
fileExists("spec/reports") ||
fileExists("features/reports")) {
stage("junit reports") {
junit(
testResults: "test/reports/*.xml, spec/reports/*.xml, features/reports/*.xml",
allowEmptyResults: true
)
}
}
}
if (options.publishingE2ETests == true && !params.IS_SCHEMA_TEST) {
stage("End-to-end tests") {
if ( env.PUBLISHING_E2E_TESTS_APP_PARAM == null ) {
appCommitishName = jobName.replace("-", "_").toUpperCase() + "_COMMITISH"
} else {
appCommitishName = env.PUBLISHING_E2E_TESTS_APP_PARAM
}
if ( env.PUBLISHING_E2E_TESTS_BRANCH == null ) {
testBranch = "test-against"
} else {
testBranch = env.PUBLISHING_E2E_TESTS_BRANCH
}
if ( env.PUBLISHING_E2E_TESTS_COMMAND == null ) {
testCommand = "test"
} else {
testCommand = env.PUBLISHING_E2E_TESTS_COMMAND
}
runPublishingE2ETests(appCommitishName, testBranch, repoName, testCommand)
}
}
if (options.afterTest) {
echo "Running post-test tasks"
options.afterTest.call()
}
}
def dockerBuildTasks(options, jobName) {
stage("Build Docker image") {
buildDockerImage(jobName, env.BRANCH_NAME, true)
}
if (!(env.BRANCH_NAME ==~ /^deployed-to/)) {
stage("Push Docker image") {
pushDockerImage(jobName, env.BRANCH_NAME)
if (params.PUSH_TO_GCR) {
pushDockerImageToGCR(jobName, env.BRANCH_NAME)
}
}
}
}
/**
* Run the brakeman security scanner against the current project
*
* @param repoName Name of the alphagov repository
*/
def runBrakemanSecurityScanner(repoName) {
def brakemanExitCode = -1
if (hasBrakeman()) {
brakemanExitCode = sh(
script: "bundle exec brakeman . --except CheckRenderInline",
returnStatus: true
)
} else {
// Install the brakeman gem and parse the output to retrieve the version we
// just installed. We'll use that version to run the brakeman binary. We need
// to do this because we can't just `gem install` the gem on Jenkins and want
// to prevent having to add the gem to every Gemfile.
def gemVersion = sh(
script: "gem install --no-document -q --install-dir ${JENKINS_HOME}/manually-installed-gems brakeman | grep 'Successfully installed brakeman'",
returnStdout: true
).replaceAll("Successfully installed ", "").trim()
// Run brakeman's executable. If it finds security alerts it will return with
// an exited code other than 0.
brakemanExitCode = sh(
script: "${JENKINS_HOME}/manually-installed-gems/gems/${gemVersion}/bin/brakeman . --except CheckRenderInline",
returnStatus: true
)
}
if (brakemanExitCode == 0) {
setBuildStatus("security", getFullCommitHash(), "No security issues found", "SUCCESS", repoName)
} else {
setBuildStatus("security", getFullCommitHash(), "Brakeman found security issues", "FAILURE", repoName)
}
}
/**
* Cleanup anything left from previous test runs
*/
def cleanupGit() {
echo 'Cleaning up git'
sh('git clean -fdx')
}
/**
* Checkout repo using SSH key
*/
def checkoutFromGitHubWithSSH(String repository, Map options = [:]) {
def defaultOptions = [
branch: null,
changelog: true,
location: null,
shallow: env.BRANCH_NAME != "master",
org: "alphagov",
poll: true,
host: "github.com"
]
options = defaultOptions << options
def branches
if (options.branch) {
branches = [[ name: options.branch ]]
} else {
branches = scm.branches
}
def extensions = [
[
$class: "CleanCheckout",
],
[
$class: 'CloneOption',
shallow: options.shallow,
noTags: options.shallow,
]
]
if(options.directory) {
extensions << [
$class: "RelativeTargetDirectory",
relativeTargetDir: options.directory
]
}
checkout([
changelog: options.changelog,
poll: options.poll,
scm: [
$class: 'GitSCM',
branches: branches,
doGenerateSubmoduleConfigurations: false,
extensions: extensions,
submoduleCfg: [],
userRemoteConfigs: [[
credentialsId: 'govuk-ci-ssh-key',
url: "git@${options.host}:${options.org}/${repository}.git"
]]
]
])
}
/**
* Checkout a dependent repo.
* This function acts as a wrapper around checkoutFromGitHubWithSSH with
* options tailored towards the needs of a secondary repo cloned as part of a
* pipeline job
*
* It can accept an optional closure that is run within the directory that has
* been cloned
*/
def checkoutDependent(String repository, options = [:], Closure closure = null) {
def defaultOptions = [
branch: "master",
changelog: false,
directory: "tmp/${repository}",
poll: false
]
options = defaultOptions << options
stage("Cloning ${repository}") {
checkoutFromGitHubWithSSH(repository, options)
}
if (closure) {
dir(options.directory) {
closure.call()
}
}
}
/**
* Check if the git HEAD is ahead of master.
* This will be false for development branches and true for release branches,
* and master itself.
*/
def isCurrentCommitOnMaster() {
sh(
script: 'git rev-list origin/master | grep $(git rev-parse HEAD)',
returnStatus: true
) == 0
}
/**
* Check whether there is a git branch named release
* This test is useful for determining whether we should update this branch or
* not
*/
def releaseBranchExists() {
sshagent(["govuk-ci-ssh-key"]) {
sh(
script: "git ls-remote --exit-code --refs origin release",
returnStatus: true
) == 0
}
}
/**
* Try to merge master into the current branch
*
* This will abort if it doesn't exit cleanly (ie there are conflicts), and
* will be a noop if the current branch is master or is in the history for
* master, e.g. a previously-merged dev branch or the deployed-to-production
* branch.
*/
def mergeMasterBranch() {
if (isCurrentCommitOnMaster()) {
echo "Current commit is on master, so building this branch without " +
"merging in master branch."
} else {
echo "Current commit is not on master, so attempting merge of master " +
"branch before proceeding with build"
sshagent(['govuk-ci-ssh-key']) {
sh("git fetch --no-tags --depth=30 origin " +
"+refs/heads/master:refs/remotes/origin/master " +
"refs/heads/${env.BRANCH_NAME}:refs/remotes/origin/${env.BRANCH_NAME}")
}
sh('git merge --no-commit origin/master || git merge --abort')
}
}
/**
* Sets environment variable
*
* Cannot iterate over maps in Jenkins2 currently
*
* Note: for scope-related reasons the code in here is inlined directly
* in the initializeParameters method below, if you change our version
* you should update it there too.
*
* @param key
* @param value
*/
def setEnvar(String key, String value) {
echo "Setting environment variable ${key}"
env."${key}" = value
}
/**
* Ensure missing build parameters are set to their default values
*
* This fixes an issue where the parameters are missing on the very first
* pipeline build of a new branch (JENKINS-40574). They are set correctly on
* every subsequent build, whether it is triggered automatically by a branch
* push or manually by a Jenkins user.
*
* This doesn't use setEnvar because for some scope-related reason we couldn't
* work out, first builds would fail because it couldn't find setEnvar. We
* inline the code instead.
*
* @param defaultBuildParams map of build parameter names to default values
*/
def initializeParameters(Map<String, String> defaultBuildParams) {
for (param in defaultBuildParams) {
if (env."${param.key}" == null) {
echo "Setting environment variable ${param.key}"
env."${param.key}" = param.value
}
}
}
/**
* Check whether the Jenkins build should be run for the current branch
*
* Builds can be run if it's against a regular branch build or if it is
* being run to test the content schema.
*
* Jenkinsfiles should run this check if the project is used to test updates
* to the content schema. Other projects should be configured in Puppet to
* exclude builds of non-dev branches, so this check is unnecessary.
*/
def isAllowedBranchBuild(
String currentBranchName,
String deployedBranchName = "deployed-to-production") {
if (currentBranchName == deployedBranchName) {
if (params.IS_SCHEMA_TEST) {
echo "Branch is '${deployedBranchName}' and this is a schema test " +
"build. Proceeding with build."
return true
} else {
echo "Branch is '${deployedBranchName}', but this is not marked as " +
"a schema test build. '${deployedBranchName}' should only be " +
"built as part of a schema test, so this build will stop here."
return false
}
}
echo "Branch is '${currentBranchName}', so this is a regular dev branch " +
"build. Proceeding with build."
return true
}
def getGitCommit() {
return sh(
script: 'git rev-parse --short HEAD',
returnStdout: true
).trim()
}
/**
* Sets the current git commit in the env. Used by the linter
*/
def setEnvGitCommit() {
env.GIT_COMMIT = getGitCommit()
}
/**
* Precompiles assets
*/
def precompileAssets() {
echo 'Precompiling the assets'
sh('RAILS_ENV=test SECRET_KEY_BASE=1 GOVUK_WEBSITE_ROOT=http://www.test.gov.uk GOVUK_APP_DOMAIN=test.gov.uk GOVUK_APP_DOMAIN_EXTERNAL=test.gov.uk GOVUK_ASSET_ROOT=https://static.test.gov.uk bundle exec rake assets:clobber assets:precompile')
}
/**
* Clone govuk-content-schemas dependency for contract tests
*/
def contentSchemaDependency(String schemaGitCommit = 'deployed-to-production') {
checkoutDependent("govuk-content-schemas", [ branch: schemaGitCommit ]) {
setEnvar("GOVUK_CONTENT_SCHEMAS_PATH", pwd())
}
}
/**
* Sets up test database
*/
def setupDb() {
echo 'Setting up database'
sh('RAILS_ENV=test bundle exec rake db:environment:set db:drop db:create db:schema:load')
}
/**
* Get the number of available processors
*/
def availableProcessors() {
Runtime.getRuntime().availableProcessors()
}
/**
* Bundles all the gems in deployment mode
*/
def bundleApp() {
echo 'Bundling'
lock ("bundle_install-$NODE_NAME") {
sh("bundle install --jobs=${availableProcessors()} --path ${JENKINS_HOME}/bundles --deployment --without development")
}
}
/**
* Bundles all the gems
*/
def bundleGem() {
echo 'Bundling'
lock ("bundle_install-$NODE_NAME") {
sh("bundle install --jobs=${availableProcessors()} --path ${JENKINS_HOME}/bundles")
}
}
/**
* Runs the tests
*
* @param test_task Optional test_task instead of 'default'
*/
def runTests(String test_task = 'default') {
sh("bundle exec rake ${test_task}")
}
/**
* Runs the tests with all the Ruby versions that are currently supported.
*
* Adds a Jenkins stage for each Ruby version, so do not call this from within
* a stage.
*
* @param extraRubyVersions Optional Ruby versions to run the tests against in
* addition to the versions currently supported by all GOV.UK applications
*/
def testGemWithAllRubies(extraRubyVersions = []) {
def rubyVersions = ["2.6", "2.7"]
rubyVersions.addAll(extraRubyVersions)
for (rubyVersion in rubyVersions) {
stage("Test with ruby $rubyVersion") {
sh "rm -f Gemfile.lock"
setEnvar("RBENV_VERSION", rubyVersion)
bundleGem()
runTests()
}
}
sh "unset RBENV_VERSION"
}
/**
* Runs rake task
*
* @param task Task to run
*/
def runRakeTask(String rake_task) {
echo "Running ${rake_task} task"
sh("bundle exec rake ${rake_task}")
}
/**
* Push tags to GitHub repository
*
* @param repository GitHub repository
* @param branch Branch name
* @param tag Tag name
*/
def pushTag(String repository, String branch, String tag) {
if (branch == 'master'){
echo 'Pushing tag'
sshagent(['govuk-ci-ssh-key']) {
sh("git tag -a ${tag} -m 'Jenkinsfile tagging with ${tag}'")
echo "Tagging alphagov/${repository} master branch -> ${tag}"
sh("git push [email protected]:alphagov/${repository}.git ${tag}")
// TODO: pushTag would be better if it only did exactly that,
// but lots of Jenkinsfiles expect it to also update the release
// branch. There are cases where release branches are not used
// (e.g. repositories containing Ruby gems). For now, just check
// if the release branch exists on the remote, and only push to it
// if it does.
if (releaseBranchExists()) {
echo "Updating alphagov/${repository} release branch"
sh("git push [email protected]:alphagov/${repository}.git HEAD:refs/heads/release")
}
}
} else {
echo 'No tagging on branch'
}
}
/**
* Deploy application on the Integration environment
*
* @param application ID of the application, which should match the ID
* configured in puppet and which is usually the same as the repository
* name
* @param branch Branch name
* @param tag Tag to deploy
* @param deployTask Deploy task (deploy, deploy:migrations or deploy:setup)
*/
def deployIntegration(String application, String branch, String tag, String deployTask) {
if (branch == 'master') {
build job: 'Deploy_App_Downstream', parameters: [
string(name: 'TARGET_APPLICATION', value: application),
string(name: 'TAG', value: tag),
string(name: 'DEPLOY_TASK', value: deployTask)
], wait: false
}
}
/**
* Publish a gem to rubygems.org
*
* @param name Name of the gem. This should match the name of the gemspec file.
* @param repository Name of the repository. This is used to add a git tag for the release.
* @param branch Branch name being published. Only publishes if this is 'master'
*/
def publishGem(String name, String repository, String branch) {
if (branch != 'master') {
return
}
def version = sh(
script: /ruby -e "puts eval(File.read('${name}.gemspec'), TOPLEVEL_BINDING).version.to_s"/,
returnStdout: true
).trim()
sshagent(['govuk-ci-ssh-key']) {
echo "Fetching remote tags"
sh("git fetch --tags")
}
def escapedVersion = version.replaceAll(/\./, /\\\\./)
def versionAlreadyPublished = sh(
script: /gem list ^${name}\$ --remote --all --quiet | grep [^0-9\\.]${escapedVersion}[^0-9\\.]/,
returnStatus: true
) == 0
if (versionAlreadyPublished) {
echo "Version ${version} has already been published to rubygems.org. Skipping publication."
} else {
echo('Publishing gem')
sh("gem build ${name}.gemspec")
sh("gem push ${name}-${version}.gem")
}
def taggedReleaseExists = false
sshagent(['govuk-ci-ssh-key']) {
taggedReleaseExists = sh(
script: "git ls-remote --exit-code --tags origin v${version}",
returnStatus: true
) == 0
}
if (taggedReleaseExists) {
echo "Version ${version} has already been tagged on GitHub. Skipping publication."
} else {
echo('Pushing tag')
pushTag(repository, branch, 'v' + version)
}
}
/**
* Does this project use Rails-style assets?
*/
def hasAssets() {
sh(script: "test -d app/assets", returnStatus: true) == 0
}
/**
* Does this project use Rubocop?
*/
def hasRubocop() {
sh(script: "grep 'rubocop' Gemfile.lock", returnStatus: true) == 0
}
/**
* Does this project use Brakeman?
*/
def hasBrakeman() {
sh(script: "grep 'brakeman' Gemfile.lock", returnStatus: true) == 0
}
/**
* Is this a Ruby gem?
*
* Determined by checking the presence of a `.gemspec` file
*/
def isGem() {
sh(script: "ls | grep gemspec", returnStatus: true) == 0
}
/**
* Is this a Rails app?
*
* Determined by checking if bin/rails exists.
*/
def isRails() {
fileExists(file: "bin/rails")
}
/**
* Does this project use a Rails-style database?
*
* Determined by checking the presence of a `database.yml` file
*/
def hasActiveRecordDatabase() {
fileExists(file: "config/database.yml")
}
/**
* Does this project use a Mongoid-style database?
*
* Determined by checking the presence of a `mongoid.yml` file.
*/
def hasMongoidDatabase() {
fileExists(file: "config/mongoid.yml")
}
def validateDockerFileRubyVersion() {
if (fileExists(file: ".ruby-version")) {
def rubyVersion = readFile(file: ".ruby-version")
// Remove any patch information from the ruby version. 2.0.0-p648 -> 2.0.0
rubyVersion = rubyVersion.trim().split("-")[0]
// The Dockerfile base image version can be optionally suffixed with a - followed by a variant
// e.g. ruby:2.4.2-slim
def hasMatchingVersions = sh(script: "egrep \"FROM ruby:${rubyVersion}(\$|-)\" Dockerfile", returnStatus: true) == 0
if (!hasMatchingVersions) {
def baseImageDefinition = sh(script: "egrep \"FROM \" Dockerfile", returnStdout: true).trim()
error("Dockerfile uses base image \"${baseImageDefinition}\", this mismatches .ruby-version \"${rubyVersion}\"")
}
}
}
def hasDockerfile() {
sh(script: "test -e Dockerfile", returnStatus: true) == 0
}
def buildDockerImage(imageName, tagName, quiet = false) {
validateDockerFileRubyVersion()
tagName = safeDockerTag(tagName)
args = "${quiet ? '--quiet' : ''} --pull ."
docker.build("govuk/${imageName}:${tagName}", args)
}
/**
*/
def dockerTagMasterBranch(jobName, branchName, buildNumber) {
dockerTag = "release_${buildNumber}"
pushDockerImage(jobName, branchName, dockerTag)
if (releaseBranchExists()) {
pushDockerImage(jobName, branchName, "release")
}
}
/*
* Push the image to the govuk docker hub and tag it. If `asTag` is set then
* the image is also tagged with that value otherwise the `tagName` is used.
*/
def pushDockerImage(imageName, tagName, asTag = null) {
tagName = safeDockerTag(tagName)
docker.withRegistry('https://index.docker.io/v1/', 'govukci-docker-hub') {
docker.image("govuk/${imageName}:${tagName}").push(asTag ?: tagName)
}
}
def pushDockerImageToGCR(imageName, tagName) {
tagName = safeDockerTag(tagName)
gcrName = "gcr.io/govuk-test/${imageName}"
docker.build(gcrName)
withCredentials([file(credentialsId: 'govuk-test', variable: 'GCR_CRED_FILE')]) {
// We don't want to interpolate this command as GCR_CRED_FILE is set as an
// environment variable in bash.
command = 'gcloud auth activate-service-account --key-file "$GCR_CRED_FILE"'
sh command
// We do want to interpolate this command to get the value of gcrName
command = "gcloud docker -- push ${gcrName}"
sh command
// Add the tag, again this needs to be interpolated
command = "gcloud container images add-tag ${gcrName} ${gcrName}:${tagName}"
sh command
}
}
def safeDockerTag(tagName) {
// A valid tag is:
// ascii, uppercase, lowercase, digits, underscore, dash, period,
// 128 chars, can't start with dash or period
// See: https://docs.docker.com/engine/reference/commandline/tag/#extended-description
return tagName.replaceAll(/[^a-zA-Z0-9-_.]|^[-.]/, "_").take(128)
}
/*
* Upload the artefact at artefact_path to the given s3_path. Uses the
* govuk-s3-artefact-creds for access.
*/
def uploadArtefactToS3(artefact_path, s3_path){
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'govuk-s3-artefact-creds',
usernameVariable: 'AWS_ACCESS_KEY_ID',
passwordVariable: 'AWS_SECRET_ACCESS_KEY']]){
sh "s3cmd --region eu-west-1 --acl-public --access_key $AWS_ACCESS_KEY_ID --secret_key $AWS_SECRET_ACCESS_KEY put $artefact_path $s3_path"
}
}
/**
* Manually set build status in GitHub.
*
* Useful for downstream builds that want to report on the upstream PR.
*
* @param jobName Name of the jenkins job being built
* @param commit SHA of the triggering commit on govuk-content-schemas
* @param message The message to report
* @param state The build state: one of PENDING, SUCCESS, FAILED
* @param repoName The alphagov repository
*/
def setBuildStatus(jobName, commit, message, state, repoName) {
step([
$class: "GitHubCommitStatusSetter",
commitShaSource: [$class: "ManuallyEnteredShaSource", sha: commit],
reposSource: [$class: "ManuallyEnteredRepositorySource", url: "https://github.com/alphagov/${repoName}"],
contextSource: [$class: "ManuallyEnteredCommitContextSource", context: "continuous-integration/jenkins/${jobName}"],
errorHandlers: [[$class: "ChangingBuildStatusErrorHandler", result: "UNSTABLE"]],
statusResultSource: [ $class: "ConditionalStatusResultSource", results: [[$class: "AnyBuildResult", message: message, state: state]] ]
]);
}
def runPublishingE2ETests(appCommitishName, testBranch, repo, testCommand = "test") {
fullCommitHash = getFullCommitHash()
build(
job: "publishing-e2e-tests/${testBranch}",
parameters: [
[$class: "StringParameterValue",
name: appCommitishName,
value: fullCommitHash],
[$class: "StringParameterValue",
name: "TEST_COMMAND",
value: testCommand],
[$class: "StringParameterValue",
name: "ORIGIN_REPO",
value: repo],
[$class: "StringParameterValue",
name: "ORIGIN_COMMIT",
value: fullCommitHash]
],
wait: false,
)
}
def getFullCommitHash() {
return sh(
script: "git rev-parse HEAD",
returnStdout: true
).trim()
}
/*
* This is a method to test that the external library loading
* works as expect
*/
def pipelineTest() {
sh("echo 'If you see this I am working as expected'")
}
return this;