-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
2090 lines (1855 loc) · 79.9 KB
/
index.js
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
/* eslint no-underscore-dangle: ["error", { "allowAfterThis": true }] */
'use strict';
const Breaker = require('circuit-fuses').breaker;
const { Octokit } = require('@octokit/rest');
const { verify } = require('@octokit/webhooks-methods');
const hoek = require('@hapi/hoek');
const Path = require('path');
const joi = require('joi');
const keygen = require('ssh-keygen');
const schema = require('screwdriver-data-schema');
const ScmGithubGraphQL = require('screwdriver-scm-github-graphql');
const CHECKOUT_URL_REGEX = schema.config.regex.CHECKOUT_URL;
const PR_COMMENTS_REGEX = /^.+pipelines\/(\d+)\/builds.+ ([\w-:]+)$/;
const PR_COMMENTS_KEYWORD_REGEX = /^__(.*)__.*$/;
const Scm = require('screwdriver-scm-base');
const logger = require('screwdriver-logger');
const DEFAULT_AUTHOR = {
avatar: 'https://cd.screwdriver.cd/assets/unknown_user.png',
name: 'n/a',
username: 'n/a',
url: 'https://cd.screwdriver.cd/'
};
const MATCH_COMPONENT_ROOTDIR_NAME = 5;
const MATCH_COMPONENT_BRANCH_NAME = 4;
const MATCH_COMPONENT_REPO_NAME = 3;
const MATCH_COMPONENT_USER_NAME = 2;
const MATCH_COMPONENT_HOST_NAME = 1;
const WEBHOOK_PAGE_SIZE = 30;
const BRANCH_PAGE_SIZE = 100;
const PR_FILES_PAGE_SIZE = 100;
const POLLING_INTERVAL = 0.2;
const POLLING_MAX_ATTEMPT = 10;
const STATE_MAP = {
SUCCESS: 'success',
PENDING: 'pending',
FAILURE: 'failure'
};
const DESCRIPTION_MAP = {
SUCCESS: 'Everything looks good!',
FAILURE: 'Did not work as expected.',
PENDING: 'Parked it as Pending...'
};
const PERMITTED_RELEASE_EVENT = ['published'];
const DEPLOY_KEY_GENERATOR_CONFIG = {
DEPLOY_KEYS_FILE: `${__dirname}/keys_rsa`,
DEPLOY_KEYS_FORMAT: 'PEM',
DEPLOY_KEYS_PASSWORD: '',
DEPLOY_KEY_TITLE: 'sd@screwdriver.cd'
};
const DEFAULT_BRANCH = 'main';
const ENTERPRISE_USER = 'EnterpriseUserAccount';
/**
* Escape quotes (single quote) for single quote enclosure
* @param {String} command escape command
* @returns {String}
*/
function escapeForSingleQuoteEnclosure(command) {
return command.replace(/'/g, `'"'"'`);
}
/**
* Escape quotes (double or back quote) for double quote enclosure
* @param {String} command escape command
* @returns {String}
*/
function escapeForDoubleQuoteEnclosure(command) {
return command.replace(/"/g, '\\"').replace(/`/g, '\\`');
}
/**
* Escape dollar for double quote enclosure
* @param {String} command escape command
* @returns {String}
*/
function escapeDollarForDoubleQuoteEnclosure(command) {
return command.replace(/\$/g, '\\$');
}
/**
* Throw error with error code
* @param {Number} errorCode Error code
* @param {String} errorReason Error message
* @throws {Error} Throws error
*/
function throwError(errorReason, errorCode = 500) {
const err = new Error(errorReason);
err.statusCode = errorCode;
throw err;
}
/**
* Get repo information
* @method getInfo
* @param {String} scmUrl scmUrl of the repo
* @param {String} [rootDir] Root dir of the pipeline
* @return {Object} An object with the owner, repo, host, branch, and rootDir
*/
function getInfo(scmUrl, rootDir) {
const matched = schema.config.regex.CHECKOUT_URL.exec(scmUrl);
// Check if regex did not pass
if (!matched) {
throwError(`Invalid scmUrl: ${scmUrl}`, 400);
}
const branch = matched[MATCH_COMPONENT_BRANCH_NAME];
const rootDirFromScmUrl = matched[MATCH_COMPONENT_ROOTDIR_NAME];
return {
owner: matched[MATCH_COMPONENT_USER_NAME],
repo: matched[MATCH_COMPONENT_REPO_NAME],
host: matched[MATCH_COMPONENT_HOST_NAME],
branch: branch ? branch.slice(1) : undefined,
rootDir: rootDir || (rootDirFromScmUrl ? rootDirFromScmUrl.slice(1) : undefined)
};
}
class GithubScm extends Scm {
/**
* Github command to run
* @method _githubCommand
* @param {Object} options An object that tells what command & params to run
* @param {String} options.action Github method. For example: get
* @param {String} options.token Github token used for authentication of requests
* @param {Object} options.params Parameters to run with
* @param {String} [options.scopeType] Type of request to make. Default is 'repos'
* @param {String} [options.route] Route for octokit.request()
* @param {Function} callback Callback function from github API
*/
_githubCommand(options, callback) {
const config = { auth: `token ${options.token}`, ...this.octokitConfig };
const octokit = new Octokit(config);
const scopeType = options.scopeType || 'repos';
if (scopeType === 'request' || scopeType === 'paginate') {
// for deprecation of 'octokit.repos.getById({id})'
// ref: https://github.com/octokit/rest.js/releases/tag/v16.0.1
// octokit return response code as `response.status`, but screwdriver usually use `response.statusCode`
octokit[scopeType](options.route, options.params)
.then(response => {
response.statusCode = response.status;
callback(null, response);
})
.catch(err => {
err.statusCode = err.status;
callback(err);
});
} else {
octokit[scopeType][options.action](options.params)
.then(response => {
response.statusCode = response.status;
callback(null, response);
})
.catch(err => {
err.statusCode = err.status;
callback(err);
});
}
}
/**
* Constructor
* @method constructor
* @param {Object} config Configuration object
* @param {Boolean} [config.privateRepo=false] Request 'repo' scope, which allows read/write access for public & private repos
* @param {String} [config.gheHost=null] If using GitHub Enterprise, the host/port of the deployed instance
* @param {String} [config.gheProtocol=https] If using GitHub Enterprise, the protocol to use
* @param {String} [config.username=sd-buildbot] GitHub username for checkout
* @param {String} [config.email=dev-null@screwdriver.cd] GitHub user email for checkout
* @param {Object} [options.readOnly={}] Read-only SCM instance config with: enabled, username, accessToken, cloneType
* @param {Boolean} [config.https=false] Is the Screwdriver API running over HTTPS
* @param {String} config.oauthClientId OAuth Client ID provided by GitHub application
* @param {String} config.oauthClientSecret OAuth Client Secret provided by GitHub application
* @param {Object} [config.fusebox={}] Circuit Breaker configuration
* @param {String} config.secret Secret to validate the signature of webhook events
* @param {Boolean} [config.gheCloud=false] Flag set to true if using Github Enterprise Cloud
* @param {Boolean} [config.gheCloudSlug] The Github Enterprise Cloud Slug
* @param {Boolean} [config.gheCloudCookie] The Github Enterprise Cloud Cookie name
* @param {Boolean} [config.gheCloudContext] The Github Enterprise Cloud scm context
* @param {String} config.githubGraphQLUrl GraphQL endpoint for GitHub https://api.github.com/graphql
* @return {GithubScm}
*/
constructor(config = {}) {
super();
// Validate configuration
this.config = joi.attempt(
config,
joi
.object()
.keys({
privateRepo: joi.boolean().optional().default(false),
gheProtocol: joi.string().optional().default('https'),
gheHost: joi.string().optional().description('GitHub Enterprise host'),
username: joi.string().optional().default('sd-buildbot'),
email: joi.string().optional().default('dev-null@screwdriver.cd'),
commentUserToken: joi.string().optional().description('Token for PR comments'),
autoDeployKeyGeneration: joi.boolean().optional().default(false),
readOnly: joi
.object()
.keys({
enabled: joi.boolean().optional(),
username: joi.string().optional(),
accessToken: joi.string().optional(),
cloneType: joi.string().valid('https', 'ssh').optional().default('https')
})
.optional()
.default({}),
https: joi.boolean().optional().default(false),
oauthClientId: joi.string().required(),
oauthClientSecret: joi.string().required(),
fusebox: joi.object().default({}),
secret: joi.string().required(),
gheCloud: joi.boolean().optional().default(false),
gheCloudSlug: joi.string().optional(),
gheCloudCookie: joi.string().optional(),
gheCloudContext: joi.string().optional(),
githubGraphQLUrl: joi.string().optional().default('https://api.github.com/graphql')
})
.unknown(true),
'Invalid config for GitHub'
);
this.octokitConfig = {};
if (this.config.gheHost) {
this.octokitConfig.baseUrl = `${this.config.gheProtocol}://${this.config.gheHost}/api/v3`;
}
// eslint-disable-next-line no-underscore-dangle
this.breaker = new Breaker(this._githubCommand.bind(this), {
// Do not retry when there is a 4XX error
shouldRetry: err => err && err.statusCode && !(err.statusCode >= 400 && err.statusCode < 500),
retry: this.config.fusebox.retry,
breaker: {
...this.config.fusebox.breaker,
errorFn(err) {
if (err.statusCode) {
return !(err.statusCode >= 400 && err.statusCode < 500);
}
return true;
}
}
});
this.scmGithubGQL = config.gheCloud
? new ScmGithubGraphQL({
graphqlUrl: this.config.githubGraphQLUrl
})
: null;
}
/**
* Look up a repo by SCM URI
* @async lookupScmUri
* @param {Object} config
* @param {Object} config.scmUri The SCM URI to look up relevant info
* @param {Object} [config.scmRepo] The SCM repository to look up
* @param {Object} config.token Service token to authenticate with Github
* @return {Promise} Resolves to an object containing repository-related information
*/
async lookupScmUri({ scmUri, scmRepo, token }) {
const parts = scmUri.split(':');
const [scmHost, scmId, scmBranch, ...rootDirParts] = parts;
const rootDir = rootDirParts.join(':');
let repoFullName;
let defaultBranch;
let privateRepo;
if (scmRepo) {
repoFullName = scmRepo.name;
privateRepo = scmRepo.privateRepo || false;
defaultBranch = scmRepo.branch;
} else {
try {
const myHost = this.config.gheHost || 'github.com';
if (scmHost !== myHost) {
throwError(
`Pipeline's scmHost ${scmHost} does not match with user's scmHost ${this.config.gheHost}`,
403
);
}
// https://github.com/octokit/rest.js/issues/163
const repo = await this.breaker.runCommand({
scopeType: 'request',
route: 'GET /repositories/:id',
token,
params: { id: scmId }
});
repoFullName = repo.data.full_name;
defaultBranch = repo.data.default_branch;
privateRepo = repo.data.private;
} catch (err) {
logger.error('Failed to lookupScmUri: ', err);
throw err;
}
}
const [repoOwner, repoName] = repoFullName.split('/');
return {
branch: scmBranch || defaultBranch,
host: scmHost,
repo: repoName,
owner: repoOwner,
rootDir: rootDir || '',
privateRepo
};
}
/**
* Promise to wait a certain number of seconds
*
* Might make this centralized for other tests to leverage
*
* @method promiseToWait
* @param {Number} timeToWait Number of seconds to wait before continuing the chain
* @return {Promise}
*/
promiseToWait(timeToWait) {
return new Promise(resolve => {
setTimeout(() => resolve(), timeToWait * 1000);
});
}
/**
* Wait computing mergeability
* @async waitPrMergeable
* @param {Object} config
* @param {String} config.scmUri The scmUri to get PR info of
* @param {String} config.token The token used to authenticate to the SCM
* @param {Object} [config.scmRepo] The SCM repository to look up
* @param {Integer} config.prNum The PR number used to fetch the PR
* @param {Integer} count The polling count
* @return {Promise} Resolves to object containing result of computing mergeability
* The parameter of success exists for testing
*/
async waitPrMergeability({ scmUri, token, scmRepo, prNum }, count) {
try {
const pullRequestInfo = await this.getPrInfo({ scmUri, token, scmRepo, prNum });
if (pullRequestInfo.mergeable !== null && pullRequestInfo.mergeable !== undefined) {
return { success: pullRequestInfo.mergeable, pullRequestInfo };
}
if (count >= POLLING_MAX_ATTEMPT - 1) {
logger.warn(`Computing mergerbility did not finish. scmUri: ${scmUri}, prNum: ${prNum}`);
return { success: false, pullRequestInfo };
}
await this.promiseToWait(POLLING_INTERVAL);
} catch (err) {
logger.error('Failed to getPrInfo: ', err);
throw err;
}
return this.waitPrMergeability({ scmUri, token, scmRepo, prNum }, count + 1);
}
/**
* Get all the comments of a particular Pull Request
* @async prComments
* @param {Object} scmInfo The information regarding SCM like repo, owner
* @param {Integer} prNum The PR number used to fetch the PR
* @param {String} token The PA token of the owner
* @return {Promise} Resolves to object containing the list of comments of this PR
*/
async prComments(scmInfo, prNum, token) {
try {
const { data } = await this.breaker.runCommand({
action: 'listComments',
scopeType: 'issues',
token,
params: {
issue_number: prNum,
owner: scmInfo.owner,
repo: scmInfo.repo
}
});
return {
comments: data
};
} catch (err) {
logger.error('Failed to fetch PR comments: ', err);
return null;
}
}
/**
* Edit a particular comment in the PR
* @async editPrComment
* @param {Integer} commentId The id of the particular comment to be edited
* @param {Object} scmInfo The information regarding SCM like repo, owner
* @param {String} comment The new comment body
* @return {Promise} Resolves to object containing PR comment info
*/
async editPrComment(commentId, scmInfo, comment) {
try {
const pullRequestComment = await this.breaker.runCommand({
action: 'updateComment',
scopeType: 'issues',
token: this.config.commentUserToken, // need to use a token with public_repo permissions
params: {
owner: scmInfo.owner,
repo: scmInfo.repo,
comment_id: commentId,
body: comment
}
});
return pullRequestComment;
} catch (err) {
logger.error('Failed to edit PR comment: ', err);
return null;
}
}
/**
* Generate a deploy private and public key pair
* @async generateDeployKey
* @return {Promise} Resolves to object containing the public and private key pair
*/
async generateDeployKey() {
return new Promise((resolve, reject) => {
const location = DEPLOY_KEY_GENERATOR_CONFIG.DEPLOY_KEYS_FILE;
const comment = this.config.email;
const password = DEPLOY_KEY_GENERATOR_CONFIG.DEPLOY_KEYS_PASSWORD;
const format = DEPLOY_KEY_GENERATOR_CONFIG.DEPLOY_KEYS_FORMAT;
keygen(
{
location,
comment,
password,
read: true,
format
},
(err, keyPair) => {
if (err) {
logger.error('Failed to create keys: ', err);
return reject(err);
}
return resolve(keyPair);
}
);
});
}
/**
* Adds deploy public key to the github repo and returns the private key
* @async _addDeployKey
* @param {Object} config
* @param {Object} config.token Admin token for repo
* @param {String} config.checkoutUrl The checkoutUrl to parse
* @return {Promise} Resolves to the private key string
*/
async _addDeployKey(config) {
const { token, checkoutUrl } = config;
const { owner, repo } = getInfo(checkoutUrl);
const { pubKey, key } = await this.generateDeployKey();
try {
await this.breaker.runCommand({
action: 'createDeployKey',
token,
params: {
owner,
repo,
title: DEPLOY_KEY_GENERATOR_CONFIG.DEPLOY_KEY_TITLE,
key: pubKey,
read_only: true
}
});
return key;
} catch (err) {
logger.error('Failed to add token: ', err);
throw err;
}
}
/**
* Get the webhook events mapping of screwdriver events and scm events
* @method _getWebhookEventsMapping
* @return {Object} Returns a mapping of the events
*/
_getWebhookEventsMapping() {
return {
pr: 'pull_request',
release: 'release',
tag: 'create',
commit: 'push'
};
}
/**
* Look up a webhook from a repo
* @async _findWebhook
* @param {Object} config
* @param {Object} config.scmInfo Data about repo
* @param {String} config.token Admin token for repo
* @param {Number} config.page Pagination: page number to search next
* @param {String} config.url Url for webhook notifications
* @return {Promise} Resolves to a list of hooks
*/
async _findWebhook(config) {
try {
const hooks = await this.breaker.runCommand({
action: 'listWebhooks',
token: config.token,
params: {
owner: config.scmInfo.owner,
repo: config.scmInfo.repo,
page: config.page,
per_page: WEBHOOK_PAGE_SIZE
}
});
const screwdriverHook = hooks.data.find(hook => hoek.reach(hook, 'config.url') === config.url);
if (!screwdriverHook && hooks.data.length === WEBHOOK_PAGE_SIZE) {
config.page += 1;
return this._findWebhook(config);
}
return screwdriverHook;
} catch (err) {
logger.error('Failed to findWebhook: ', err);
throw err;
}
}
/**
* Create or edit a webhook (edits if hookInfo exists)
* @async _createWebhook
* @param {Object} config
* @param {Object} [config.hookInfo] Information about a existing webhook
* @param {Object} config.scmInfo Information about the repo
* @param {String} config.token Admin token for repo
* @param {String} config.url Payload destination url for webhook notifications
* @param {String} config.actions Actions for the webhook events
* @return {Promise} Resolves when complete
*/
async _createWebhook(config) {
let action = 'createWebhook';
const params = {
active: true,
events: config.actions.length === 0 ? ['push', 'pull_request', 'create', 'release'] : config.actions,
owner: config.scmInfo.owner,
repo: config.scmInfo.repo,
name: 'web',
config: {
content_type: 'json',
secret: this.config.secret,
url: config.url
}
};
if (config.hookInfo) {
action = 'updateWebhook';
Object.assign(params, { hook_id: config.hookInfo.id });
}
try {
const hooks = await this.breaker.runCommand({
action,
token: config.token,
params
});
return hooks.data;
} catch (err) {
logger.error('Failed to createWebhook: ', err);
throw err;
}
}
/**
* Adds the Screwdriver webhook to the Github repository
* @async _addWebhook
* @param {Object} config Config object
* @param {String} config.scmUri The SCM URI to add the webhook to
* @param {String} config.token Service token to authenticate with Github
* @param {Object} [config.scmRepo] The SCM repo to look up
* @param {String} config.webhookUrl The URL to use for the webhook notifications
* @param {Array} config.actions The list of actions to be added for this webhook
* @return {Promise} Resolve means operation completed without failure
*/
async _addWebhook(config) {
const lookupConfig = {
scmUri: config.scmUri,
token: config.token
};
if (config.scmRepo) {
lookupConfig.scmRepo = config.scmRepo;
}
const scmInfo = await this.lookupScmUri(lookupConfig);
const hookInfo = await this._findWebhook({
scmInfo,
url: config.webhookUrl,
page: 1,
token: config.token
});
return this._createWebhook({
hookInfo,
scmInfo,
actions: config.actions,
token: config.token,
url: config.webhookUrl
});
}
/**
* Get the command to check out source code from a repository
* @async _getCheckoutCommand
* @param {Object} config
* @param {String} config.branch Pipeline branch
* @param {String} config.host Scm host to checkout source code from
* @param {String} config.org Scm org name
* @param {String} config.repo Scm repo name
* @param {String} config.sha Commit sha
* @param {String} [config.commitBranch] Commit branch
* @param {String} [config.prRef] PR reference (can be a PR branch or reference)
* @param {String} [config.rootDir] Root directory
* @param {String} [config.scmContext] The scm context name
* @param {String} [config.manifest] Repo manifest URL (only defined if `screwdriver.cd/repoManifest` annotation is)
* @param {Object} [config.parentConfig] Config for parent pipeline
* @return {Promise} Resolves to object containing name and checkout commands
*/
async _getCheckoutCommand(config) {
const checkoutUrl = `${config.host}/${config.org}/${config.repo}`; // URL for https
const sshCheckoutUrl = `git@${config.host}:${config.org}/${config.repo}`; // URL for ssh
const branch = config.commitBranch ? config.commitBranch : config.branch; // use commit branch
const singleQuoteEscapedBranch = escapeForSingleQuoteEnclosure(branch);
const doubleQuoteEscapedBranch = escapeForDoubleQuoteEnclosure(
escapeDollarForDoubleQuoteEnclosure(singleQuoteEscapedBranch)
);
const ghHost = config.host || 'github.com'; // URL for host to checkout from
const gitConfigString = `
Host ${ghHost}
StrictHostKeyChecking no
`; // config to permit SCM host for one time SSH connect
const gitConfigB64 = Buffer.from(gitConfigString).toString('base64'); // encode the config to b64 to maintain format
const command = [];
command.push(
// eslint-disable-next-line no-template-curly-in-string
"export SD_GIT_WRAPPER=\"$(if [ `uname` = 'Darwin' ] || [ ${SD_HAB_ENABLED:-false} = 'false' ]; " +
"then echo 'eval'; " +
"else echo 'sd-step exec core/git'; fi)\""
);
command.push('if [ ! -z $SD_SCM_DEPLOY_KEY ]; then export SCM_CLONE_TYPE=ssh; fi');
// Set recursive option
command.push(
'if [ ! -z $GIT_RECURSIVE_CLONE ] && [ $GIT_RECURSIVE_CLONE = false ]; ' +
`then export GIT_RECURSIVE_OPTION=""; ` +
`else export GIT_RECURSIVE_OPTION="--recursive"; fi`
);
// Export environment variables
command.push('echo Exporting environment variables');
// Use read-only clone type
if (hoek.reach(this.config, 'readOnly.enabled')) {
if (hoek.reach(this.config, 'readOnly.cloneType') === 'ssh') {
command.push(`export SCM_URL=${sshCheckoutUrl}`);
} else {
command.push(
'if [ ! -z $SCM_USERNAME ] && [ ! -z $SCM_ACCESS_TOKEN ]; ' +
`then export SCM_URL=https://$SCM_USERNAME:$SCM_ACCESS_TOKEN@${checkoutUrl}; ` +
`else export SCM_URL=https://${checkoutUrl}; fi`
);
}
} else {
command.push(
'if [ ! -z $SCM_CLONE_TYPE ] && [ $SCM_CLONE_TYPE = ssh ]; ' +
`then export SCM_URL=${sshCheckoutUrl}; ` +
'elif [ ! -z $SCM_USERNAME ] && [ ! -z $SCM_ACCESS_TOKEN ]; ' +
`then export SCM_URL=https://$SCM_USERNAME:$SCM_ACCESS_TOKEN@${checkoutUrl}; ` +
`else export SCM_URL=https://${checkoutUrl}; fi`
);
}
command.push('export GIT_URL=$SCM_URL.git');
// git 1.7.1 doesn't support --no-edit with merge, this should do same thing
command.push('export GIT_MERGE_AUTOEDIT=no');
// Configure git to use SSH based checkout
// 1. Check for presence of deploy keys and clone type
// 2. Store the deploy private key to /tmp/git_key
// 3. Give it the necessary permissions and set env var to instruct git to use the key
// 4. Add SCM host as a known host by adding config to ~/.ssh/config
command.push(
'if [ ! -z $SD_SCM_DEPLOY_KEY ] && [ $SCM_CLONE_TYPE = ssh ]; ' +
'then ' +
'echo $SD_SCM_DEPLOY_KEY | base64 -d > /tmp/git_key && echo "" >> /tmp/git_key && ' +
'chmod 600 /tmp/git_key && export GIT_SSH_COMMAND="ssh -i /tmp/git_key" && ' +
`mkdir -p ~/.ssh/ && printf "%s\n" "${gitConfigB64}" | base64 -d >> ~/.ssh/config; fi`
);
// Set config
command.push('echo Setting user name and user email');
command.push(`$SD_GIT_WRAPPER "git config --global user.name ${this.config.username}"`);
command.push(`$SD_GIT_WRAPPER "git config --global user.email ${this.config.email}"`);
// Set final checkout dir, default to SD_SOURCE_DIR for backward compatibility
command.push('export SD_CHECKOUT_DIR_FINAL=$SD_SOURCE_DIR');
// eslint-disable-next-line max-len
command.push('if [ ! -z $SD_CHECKOUT_DIR ]; then export SD_CHECKOUT_DIR_FINAL=$SD_CHECKOUT_DIR; fi');
const shallowCloneCmd =
'else if [ ! -z "$GIT_SHALLOW_CLONE_SINCE" ]; ' +
'then export GIT_SHALLOW_CLONE_DEPTH_OPTION=' +
'"--shallow-since=\'$GIT_SHALLOW_CLONE_SINCE\'"; ' +
'else if [ -z $GIT_SHALLOW_CLONE_DEPTH ]; ' +
'then export GIT_SHALLOW_CLONE_DEPTH=50; fi; ' +
'export GIT_SHALLOW_CLONE_DEPTH_OPTION="--depth=$GIT_SHALLOW_CLONE_DEPTH"; fi; ' +
'export GIT_SHALLOW_CLONE_BRANCH="--no-single-branch"; ' +
'if [ "$GIT_SHALLOW_CLONE_SINGLE_BRANCH" = true ]; ' +
'then export GIT_SHALLOW_CLONE_BRANCH=""; fi; ' +
'$SD_GIT_WRAPPER ' +
'"git clone $GIT_SHALLOW_CLONE_DEPTH_OPTION $GIT_SHALLOW_CLONE_BRANCH ';
// Checkout config pipeline if this is a child pipeline
if (config.parentConfig) {
const parentCheckoutUrl = `${config.parentConfig.host}/${config.parentConfig.org}/${config.parentConfig.repo}`; // URL for https
const parentSshCheckoutUrl = `git@${config.parentConfig.host}:${config.parentConfig.org}/${config.parentConfig.repo}`; // URL for ssh
const parentBranch = config.parentConfig.branch;
const escapedParentBranch = escapeForDoubleQuoteEnclosure(escapeForSingleQuoteEnclosure(parentBranch));
const externalConfigDir = '$SD_ROOT_DIR/config';
command.push(
'if [ ! -z $SCM_CLONE_TYPE ] && [ $SCM_CLONE_TYPE = ssh ]; ' +
`then export CONFIG_URL=${parentSshCheckoutUrl}; ` +
'elif [ ! -z $SCM_USERNAME ] && [ ! -z $SCM_ACCESS_TOKEN ]; ' +
'then export CONFIG_URL=https://$SCM_USERNAME:$SCM_ACCESS_TOKEN@' +
`${parentCheckoutUrl}; ` +
`else export CONFIG_URL=https://${parentCheckoutUrl}; fi`
);
command.push(`export SD_CONFIG_DIR=${externalConfigDir}`);
// Git clone
command.push(`echo 'Cloning external config repo ${parentCheckoutUrl}'`);
command.push(
`${
'if [ ! -z $GIT_SHALLOW_CLONE ] && [ $GIT_SHALLOW_CLONE = false ]; ' +
'then $SD_GIT_WRAPPER ' +
`"git clone $GIT_RECURSIVE_OPTION --quiet --progress --branch '${escapedParentBranch}' ` +
'$CONFIG_URL $SD_CONFIG_DIR"; '
}${shallowCloneCmd}` +
`$GIT_RECURSIVE_OPTION --quiet --progress --branch '${escapedParentBranch}' ` +
'$CONFIG_URL $SD_CONFIG_DIR"; fi'
);
// Reset to SHA
command.push(`$SD_GIT_WRAPPER "git -C $SD_CONFIG_DIR reset --hard ${config.parentConfig.sha} --"`);
command.push(`echo Reset external config repo to ${config.parentConfig.sha}`);
}
if (config.manifest) {
const curlWrapper =
'$(if curl --version > /dev/null 2>&1; ' +
"then echo 'eval'; " +
"else echo 'sd-step exec core/curl'; fi)";
const grepWrapper =
'$(if grep --version > /dev/null 2>&1; ' +
"then echo 'eval'; " +
"else echo 'sd-step exec core/grep'; fi)";
const repoDownloadUrl = 'https://storage.googleapis.com/git-repo-downloads/repo';
const sdRepoReleasesUrl = 'https://api.github.com/repos/screwdriver-cd/sd-repo/releases/latest';
const sdRepoDownloadUrl =
'https://github.com/screwdriver-cd/sd-repo/releases/download/v[0-9.]*/sd-repo_linux_amd64';
const sdRepoReleasesFile = 'sd-repo-releases.html';
const sdRepoLatestFile = 'sd-repo-latest';
command.push(`echo Checking out code using the repo manifest defined in ${config.manifest}`);
// Get the repo binary
command.push(`${curlWrapper} "curl -s ${repoDownloadUrl} > /usr/local/bin/repo"`);
command.push('chmod a+x /usr/local/bin/repo');
// Get the sd-repo binary and execute it
command.push(`${curlWrapper} "curl -s ${sdRepoReleasesUrl} > ${sdRepoReleasesFile}"`);
command.push(
`${grepWrapper} "grep -E -o '${sdRepoDownloadUrl}' ${sdRepoReleasesFile} > ${sdRepoLatestFile}"`
);
command.push(`${curlWrapper} "curl -Ls $(cat ${sdRepoLatestFile}) > /usr/local/bin/sd-repo"`);
command.push('chmod a+x /usr/local/bin/sd-repo');
command.push(`sd-repo -manifestUrl=${config.manifest} -sourceRepo=${config.org}/${config.repo}`);
// sourcePath is the file created by `sd-repo` which contains the relative path to the source repository
const sourcePath = 'sourcePath';
// Export $SD_SOURCE_DIR to source repo path and cd into it
command.push(
`if [ $(cat ${sourcePath}) != "." ]; ` +
`then export SD_SOURCE_DIR=$SD_SOURCE_DIR/$(cat ${sourcePath}); fi`
);
command.push('cd $SD_SOURCE_DIR');
} else {
// Git clone
command.push(`echo 'Cloning ${checkoutUrl}, on branch ${singleQuoteEscapedBranch}'`);
command.push(
`${
'if [ ! -z $GIT_SHALLOW_CLONE ] && [ $GIT_SHALLOW_CLONE = false ]; ' +
'then $SD_GIT_WRAPPER ' +
`"git clone $GIT_RECURSIVE_OPTION --quiet --progress --branch '${doubleQuoteEscapedBranch}' ` +
'$SCM_URL $SD_CHECKOUT_DIR_FINAL"; '
}${shallowCloneCmd}` +
`$GIT_RECURSIVE_OPTION --quiet --progress --branch '${doubleQuoteEscapedBranch}' ` +
'$SCM_URL $SD_CHECKOUT_DIR_FINAL"; fi'
);
// Reset to SHA
if (config.prRef) {
command.push(`$SD_GIT_WRAPPER "git reset --hard '${doubleQuoteEscapedBranch}' --"`);
command.push(`echo 'Reset to ${singleQuoteEscapedBranch}'`);
} else {
command.push(
'if [ ! -z $GIT_SHALLOW_CLONE ] && [ $GIT_SHALLOW_CLONE = false ]; ' +
`then $SD_GIT_WRAPPER "git fetch origin '${config.sha}'"; ` +
`else $SD_GIT_WRAPPER "git fetch $GIT_SHALLOW_CLONE_DEPTH_OPTION origin '${config.sha}'"; fi`
);
command.push(`$SD_GIT_WRAPPER "git reset --hard '${config.sha}' --"`);
command.push(`echo 'Reset to ${config.sha}'`);
}
}
// For pull requests
if (config.prRef) {
const LOCAL_BRANCH_NAME = 'pr';
const prRef = config.prRef.replace('merge', `head:${LOCAL_BRANCH_NAME}`);
const baseRepo = config.prSource === 'fork' ? 'upstream' : 'origin';
const prBranch = config.prBranchName;
const singleQuoteEscapedPrBranch = escapeForSingleQuoteEnclosure(prBranch);
// Fetch a pull request
command.push(`echo 'Fetching PR ${prRef}'`);
command.push(`$SD_GIT_WRAPPER "git fetch origin ${prRef}"`);
command.push(`export PR_BASE_BRANCH_NAME='${singleQuoteEscapedBranch}'`);
command.push(`export PR_BRANCH_NAME='${baseRepo}/${singleQuoteEscapedPrBranch}'`);
command.push(`echo 'Checking out the PR branch ${singleQuoteEscapedPrBranch}'`);
command.push(`$SD_GIT_WRAPPER "git checkout ${LOCAL_BRANCH_NAME}"`);
command.push(`$SD_GIT_WRAPPER "git merge '${doubleQuoteEscapedBranch}'"`);
command.push(`export GIT_BRANCH=origin/refs/${prRef}`);
} else {
command.push(`export GIT_BRANCH='origin/${singleQuoteEscapedBranch}'`);
}
if (!config.manifest) {
// Init & Update submodule only when sd-repo is not used
command.push(
'if [ ! -z $GIT_RECURSIVE_CLONE ] && [ $GIT_RECURSIVE_CLONE = false ]; ' +
`then $SD_GIT_WRAPPER "git submodule init"; ` +
`else $SD_GIT_WRAPPER "git submodule update --init --recursive"; fi`
);
// cd into rootDir after merging
if (config.rootDir) {
// Escape single quotes in the root directory path to handle special characters.
// The path is then wrapped in single quotes to safely change directories using the 'cd' command.
const escapedRootDir = config.rootDir.replace(/'/g, "'\\''");
command.push(`cd '${escapedRootDir}'`);
}
}
return {
name: 'sd-checkout-code',
command: command.join(' && ')
};
}
/**
* Get a list of names and references of opened PRs
* @async _getOpenedPRs
* @param {Object} config
* @param {String} config.scmUri The scmUri to get opened PRs from
* @param {String} config.token The token used to authenticate with the SCM
* @param {Object} [config.scmRepo] The SCM repo to look up
* @return {Promise} Resolves to an array of objects storing opened PR names and refs
*/
async _getOpenedPRs({ scmUri, token, scmRepo }) {
const lookupConfig = {
scmUri,
token
};
if (scmRepo) {
lookupConfig.scmRepo = scmRepo;
}
const { owner, repo } = await this.lookupScmUri(lookupConfig);
try {
const pullRequests = await this.breaker.runCommand({
action: 'list',
scopeType: 'pulls',
token,
params: {
owner,
repo,
state: 'open',
per_page: 100
}
});
return pullRequests.data.map(pullRequest => ({
name: `PR-${pullRequest.number}`,
ref: `pull/${pullRequest.number}/merge`,
username: pullRequest.user.login,
title: pullRequest.title,
createTime: pullRequest.created_at,
url: pullRequest.html_url,
userProfile: pullRequest.user.html_url
}));
} catch (err) {
logger.error('Failed to getOpenedPRs: ', err);
throw err;
}
}
/**
* Get an owner's permissions on a repository
* @async _getPermissions
* @param {Object} config
* @param {String} config.scmUri The scmUri to get permissions on
* @param {Object} [config.scmRepo] The SCM repo to look up
* @param {String} config.token The token used to authenticate to the SCM
* @return {Promise} Resolves to the owner's repository permissions
*/
async _getPermissions(config) {
const lookupConfig = {
scmUri: config.scmUri,
token: config.token
};
if (config.scmRepo) {
lookupConfig.scmRepo = config.scmRepo;
}
try {
const scmInfo = await this.lookupScmUri(lookupConfig);
const repo = await this.breaker.runCommand({
action: 'get',
token: config.token,
params: {
owner: scmInfo.owner,
repo: scmInfo.repo
}
});
return repo.data.permissions;
} catch (err) {
// Suspended user
if (err.message.match(/suspend/i)) {
logger.info(`User's account suspended for ${config.scmUri}, it will be removed from pipeline admins.`);
return { admin: false, push: false, pull: false };
}
logger.error('Failed to getPermissions: ', err);
throw err;
}
}
/**
* Get a users permissions on an organization
* @method _getOrgPermissions
* @param {Object} config Configuration
* @param {String} config.organization The organization to get permissions on
* @param {String} config.username The user to check against
* @param {String} config.token The token used to authenticate to the SCM
* @param {String} [config.scmContext] The scm context name
* @return {Promise}