@backstage/plugin-scaffolder-backend-module-bitbucket-cloud 0.2.1-next.1 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -2,1248 +2,15 @@
2
2
 
3
3
  Object.defineProperty(exports, '__esModule', { value: true });
4
4
 
5
- var errors = require('@backstage/errors');
6
- var pluginScaffolderNode = require('@backstage/plugin-scaffolder-node');
7
- var fetch = require('node-fetch');
8
- var yaml = require('yaml');
9
- var fs = require('fs-extra');
10
- var backendPluginApi = require('@backstage/backend-plugin-api');
11
- var alpha = require('@backstage/plugin-scaffolder-node/alpha');
12
- var integration = require('@backstage/integration');
13
- var pluginBitbucketCloudCommon = require('@backstage/plugin-bitbucket-cloud-common');
5
+ var bitbucketCloud = require('./actions/bitbucketCloud.cjs.js');
6
+ var bitbucketCloudPipelinesRun = require('./actions/bitbucketCloudPipelinesRun.cjs.js');
7
+ var bitbucketCloudPullRequest = require('./actions/bitbucketCloudPullRequest.cjs.js');
8
+ var module$1 = require('./module.cjs.js');
14
9
 
15
- function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e : { default: e }; }
16
10
 
17
- var fetch__default = /*#__PURE__*/_interopDefaultCompat(fetch);
18
- var yaml__default = /*#__PURE__*/_interopDefaultCompat(yaml);
19
- var fs__default = /*#__PURE__*/_interopDefaultCompat(fs);
20
11
 
21
- const getAuthorizationHeader = (config) => {
22
- if (config.username && config.appPassword) {
23
- const buffer = Buffer.from(
24
- `${config.username}:${config.appPassword}`,
25
- "utf8"
26
- );
27
- return `Basic ${buffer.toString("base64")}`;
28
- }
29
- if (config.token) {
30
- return `Bearer ${config.token}`;
31
- }
32
- throw new Error(
33
- `Authorization has not been provided for Bitbucket Cloud. Please add either username + appPassword to the Integrations config or a user login auth token`
34
- );
35
- };
36
-
37
- const examples$2 = [
38
- {
39
- description: "Initializes a git repository with the content in the workspace, and publishes it to Bitbucket Cloud with the default configuration.",
40
- example: yaml__default.default.stringify({
41
- steps: [
42
- {
43
- id: "publish",
44
- action: "publish:bitbucketCloud",
45
- name: "Publish to Bitbucket Cloud",
46
- input: {
47
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project"
48
- }
49
- }
50
- ]
51
- })
52
- },
53
- {
54
- description: "Initializes a Bitbucket Cloud repository with a description.",
55
- example: yaml__default.default.stringify({
56
- steps: [
57
- {
58
- id: "publish",
59
- action: "publish:bitbucketCloud",
60
- name: "Publish to Bitbucket Cloud",
61
- input: {
62
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
63
- description: "Initialize a git repository"
64
- }
65
- }
66
- ]
67
- })
68
- },
69
- {
70
- description: "Initializes a Bitbucket Cloud repository with public repo visibility, if not set defaults to private",
71
- example: yaml__default.default.stringify({
72
- steps: [
73
- {
74
- id: "publish",
75
- action: "publish:bitbucketCloud",
76
- name: "Publish to Bitbucket Cloud",
77
- input: {
78
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
79
- repoVisibility: "public"
80
- }
81
- }
82
- ]
83
- })
84
- },
85
- {
86
- description: "Initializes a Bitbucket Cloud repository with a default Branch, if not set defaults to master",
87
- example: yaml__default.default.stringify({
88
- steps: [
89
- {
90
- id: "publish",
91
- action: "publish:bitbucketCloud",
92
- name: "Publish to Bitbucket Cloud",
93
- input: {
94
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
95
- defaultBranch: "main"
96
- }
97
- }
98
- ]
99
- })
100
- },
101
- {
102
- description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository",
103
- example: yaml__default.default.stringify({
104
- steps: [
105
- {
106
- id: "publish",
107
- action: "publish:bitbucketCloud",
108
- name: "Publish to Bitbucket Cloud",
109
- input: {
110
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
111
- sourcePath: "./repoRoot"
112
- }
113
- }
114
- ]
115
- })
116
- },
117
- {
118
- description: "Initializes a Bitbucket Cloud repository with a custom authentication token",
119
- example: yaml__default.default.stringify({
120
- steps: [
121
- {
122
- id: "publish",
123
- action: "publish:bitbucketCloud",
124
- name: "Publish to Bitbucket Cloud",
125
- input: {
126
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
127
- token: "your-custom-auth-token"
128
- }
129
- }
130
- ]
131
- })
132
- },
133
- {
134
- description: "Initializes a Bitbucket Cloud repository with all proporties being set",
135
- example: yaml__default.default.stringify({
136
- steps: [
137
- {
138
- id: "publish",
139
- action: "publish:bitbucketCloud",
140
- name: "Publish to Bitbucket Cloud",
141
- input: {
142
- repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
143
- description: "Initialize a git repository",
144
- repoVisibility: "public",
145
- defaultBranch: "main",
146
- token: "your-custom-auth-token"
147
- }
148
- }
149
- ]
150
- })
151
- }
152
- ];
153
-
154
- const createRepository = async (opts) => {
155
- const {
156
- workspace,
157
- project,
158
- repo,
159
- description,
160
- repoVisibility,
161
- mainBranch,
162
- authorization,
163
- apiBaseUrl
164
- } = opts;
165
- const options = {
166
- method: "POST",
167
- body: JSON.stringify({
168
- scm: "git",
169
- description,
170
- is_private: repoVisibility === "private",
171
- project: { key: project }
172
- }),
173
- headers: {
174
- Authorization: authorization,
175
- "Content-Type": "application/json"
176
- }
177
- };
178
- let response;
179
- try {
180
- response = await fetch__default.default(
181
- `${apiBaseUrl}/repositories/${workspace}/${repo}`,
182
- options
183
- );
184
- } catch (e) {
185
- throw new Error(`Unable to create repository, ${e}`);
186
- }
187
- if (response.status !== 200) {
188
- throw new Error(
189
- `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
190
- );
191
- }
192
- const r = await response.json();
193
- let remoteUrl = "";
194
- for (const link of r.links.clone) {
195
- if (link.name === "https") {
196
- remoteUrl = link.href;
197
- }
198
- }
199
- const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;
200
- return { remoteUrl, repoContentsUrl };
201
- };
202
- function createPublishBitbucketCloudAction(options) {
203
- const { integrations, config } = options;
204
- return pluginScaffolderNode.createTemplateAction({
205
- id: "publish:bitbucketCloud",
206
- examples: examples$2,
207
- description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Cloud.",
208
- schema: {
209
- input: {
210
- type: "object",
211
- required: ["repoUrl"],
212
- properties: {
213
- repoUrl: {
214
- title: "Repository Location",
215
- type: "string"
216
- },
217
- description: {
218
- title: "Repository Description",
219
- type: "string"
220
- },
221
- repoVisibility: {
222
- title: "Repository Visibility",
223
- type: "string",
224
- enum: ["private", "public"]
225
- },
226
- defaultBranch: {
227
- title: "Default Branch",
228
- type: "string",
229
- description: `Sets the default branch on the repository. The default value is 'master'`
230
- },
231
- gitCommitMessage: {
232
- title: "Git Commit Message",
233
- type: "string",
234
- description: `Sets the commit message on the repository. The default value is 'initial commit'`
235
- },
236
- sourcePath: {
237
- title: "Source Path",
238
- description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
239
- type: "string"
240
- },
241
- token: {
242
- title: "Authentication Token",
243
- type: "string",
244
- description: "The token to use for authorization to BitBucket Cloud"
245
- }
246
- }
247
- },
248
- output: {
249
- type: "object",
250
- properties: {
251
- remoteUrl: {
252
- title: "A URL to the repository with the provider",
253
- type: "string"
254
- },
255
- repoContentsUrl: {
256
- title: "A URL to the root of the repository",
257
- type: "string"
258
- },
259
- commitHash: {
260
- title: "The git commit hash of the initial commit",
261
- type: "string"
262
- }
263
- }
264
- }
265
- },
266
- async handler(ctx) {
267
- const {
268
- repoUrl,
269
- description,
270
- defaultBranch = "master",
271
- gitCommitMessage,
272
- repoVisibility = "private"
273
- } = ctx.input;
274
- const { workspace, project, repo, host } = pluginScaffolderNode.parseRepoUrl(
275
- repoUrl,
276
- integrations
277
- );
278
- if (!workspace) {
279
- throw new errors.InputError(
280
- `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
281
- );
282
- }
283
- if (!project) {
284
- throw new errors.InputError(
285
- `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
286
- );
287
- }
288
- const integrationConfig = integrations.bitbucketCloud.byHost(host);
289
- if (!integrationConfig) {
290
- throw new errors.InputError(
291
- `No matching integration configuration for host ${host}, please check your integrations config`
292
- );
293
- }
294
- const authorization = getAuthorizationHeader(
295
- ctx.input.token ? { token: ctx.input.token } : integrationConfig.config
296
- );
297
- const apiBaseUrl = integrationConfig.config.apiBaseUrl;
298
- const { remoteUrl, repoContentsUrl } = await createRepository({
299
- authorization,
300
- workspace: workspace || "",
301
- project,
302
- repo,
303
- repoVisibility,
304
- mainBranch: defaultBranch,
305
- description,
306
- apiBaseUrl
307
- });
308
- const gitAuthorInfo = {
309
- name: config.getOptionalString("scaffolder.defaultAuthor.name"),
310
- email: config.getOptionalString("scaffolder.defaultAuthor.email")
311
- };
312
- let auth;
313
- if (ctx.input.token) {
314
- auth = {
315
- username: "x-token-auth",
316
- password: ctx.input.token
317
- };
318
- } else {
319
- if (!integrationConfig.config.username || !integrationConfig.config.appPassword) {
320
- throw new Error(
321
- "Credentials for Bitbucket Cloud integration required for this action."
322
- );
323
- }
324
- auth = {
325
- username: integrationConfig.config.username,
326
- password: integrationConfig.config.appPassword
327
- };
328
- }
329
- const commitResult = await pluginScaffolderNode.initRepoAndPush({
330
- dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
331
- remoteUrl,
332
- auth,
333
- defaultBranch,
334
- logger: ctx.logger,
335
- commitMessage: gitCommitMessage || config.getOptionalString("scaffolder.defaultCommitMessage"),
336
- gitAuthorInfo
337
- });
338
- ctx.output("commitHash", commitResult?.commitHash);
339
- ctx.output("remoteUrl", remoteUrl);
340
- ctx.output("repoContentsUrl", repoContentsUrl);
341
- }
342
- });
343
- }
344
-
345
- const examples$1 = [
346
- {
347
- description: "Trigger a pipeline for a branch",
348
- example: yaml__default.default.stringify({
349
- steps: [
350
- {
351
- action: "bitbucket:pipelines:run",
352
- id: "run-bitbucket-pipeline",
353
- name: "Run an example bitbucket pipeline",
354
- input: {
355
- workspace: "test-workspace",
356
- repo_slug: "test-repo-slug",
357
- body: {
358
- target: {
359
- ref_type: "branch",
360
- type: "pipeline_ref_target",
361
- ref_name: "master"
362
- }
363
- }
364
- }
365
- }
366
- ]
367
- })
368
- },
369
- {
370
- description: "Trigger a pipeline for a commit on a branch",
371
- example: yaml__default.default.stringify({
372
- steps: [
373
- {
374
- action: "bitbucket:pipelines:run",
375
- id: "run-bitbucket-pipeline",
376
- name: "Run an example bitbucket pipeline",
377
- input: {
378
- workspace: "test-workspace",
379
- repo_slug: "test-repo-slug",
380
- body: {
381
- target: {
382
- commit: {
383
- type: "commit",
384
- hash: "ce5b7431602f7cbba007062eeb55225c6e18e956"
385
- },
386
- ref_type: "branch",
387
- type: "pipeline_ref_target",
388
- ref_name: "master"
389
- }
390
- }
391
- }
392
- }
393
- ]
394
- })
395
- },
396
- {
397
- description: "Trigger a specific pipeline definition for a commit",
398
- example: yaml__default.default.stringify({
399
- steps: [
400
- {
401
- action: "bitbucket:pipelines:run",
402
- id: "run-bitbucket-pipeline",
403
- name: "Run an example bitbucket pipeline",
404
- input: {
405
- workspace: "test-workspace",
406
- repo_slug: "test-repo-slug",
407
- body: {
408
- target: {
409
- commit: {
410
- type: "commit",
411
- hash: "a3c4e02c9a3755eccdc3764e6ea13facdf30f923"
412
- },
413
- selector: {
414
- type: "custom",
415
- pattern: "Deploy to production"
416
- },
417
- type: "pipeline_commit_target"
418
- }
419
- }
420
- }
421
- }
422
- ]
423
- })
424
- },
425
- {
426
- description: "Trigger a specific pipeline definition for a commit on a branch or tag",
427
- example: yaml__default.default.stringify({
428
- steps: [
429
- {
430
- action: "bitbucket:pipelines:run",
431
- id: "run-bitbucket-pipeline",
432
- name: "Run an example bitbucket pipeline",
433
- input: {
434
- workspace: "test-workspace",
435
- repo_slug: "test-repo-slug",
436
- body: {
437
- target: {
438
- commit: {
439
- type: "commit",
440
- hash: "a3c4e02c9a3755eccdc3764e6ea13facdf30f923"
441
- },
442
- selector: {
443
- type: "custom",
444
- pattern: "Deploy to production"
445
- },
446
- type: "pipeline_ref_target",
447
- ref_name: "master",
448
- ref_type: "branch"
449
- }
450
- }
451
- }
452
- }
453
- ]
454
- })
455
- },
456
- {
457
- description: "Trigger a custom pipeline with variables",
458
- example: yaml__default.default.stringify({
459
- steps: [
460
- {
461
- action: "bitbucket:pipelines:run",
462
- id: "run-bitbucket-pipeline",
463
- name: "Run an example bitbucket pipeline",
464
- input: {
465
- workspace: "test-workspace",
466
- repo_slug: "test-repo-slug",
467
- body: {
468
- target: {
469
- type: "pipeline_ref_target",
470
- ref_name: "master",
471
- ref_type: "branch",
472
- selector: {
473
- type: "custom",
474
- pattern: "Deploy to production"
475
- }
476
- },
477
- variables: [
478
- { key: "var1key", value: "var1value", secured: true },
479
- {
480
- key: "var2key",
481
- value: "var2value"
482
- }
483
- ]
484
- }
485
- }
486
- }
487
- ]
488
- })
489
- },
490
- {
491
- description: "Trigger a pull request pipeline",
492
- example: yaml__default.default.stringify({
493
- steps: [
494
- {
495
- action: "bitbucket:pipelines:run",
496
- id: "run-bitbucket-pipeline",
497
- name: "Run an example bitbucket pipeline",
498
- input: {
499
- workspace: "test-workspace",
500
- repo_slug: "test-repo-slug",
501
- body: {
502
- target: {
503
- type: "pipeline_pullrequest_target",
504
- source: "pull-request-branch",
505
- destination: "master",
506
- destination_commit: {
507
- hash: "9f848b7"
508
- },
509
- commit: {
510
- hash: "1a372fc"
511
- },
512
- pull_request: {
513
- id: "3"
514
- },
515
- selector: {
516
- type: "pull-requests",
517
- pattern: "**"
518
- }
519
- }
520
- }
521
- }
522
- }
523
- ]
524
- })
525
- }
526
- ];
527
-
528
- const workspace = {
529
- title: "Workspace",
530
- description: `The workspace name`,
531
- type: "string"
532
- };
533
- const repo_slug = {
534
- title: "Repository name",
535
- description: "The repository name",
536
- type: "string"
537
- };
538
- const ref_type = {
539
- title: "ref_type",
540
- type: "string"
541
- };
542
- const type = {
543
- title: "type",
544
- type: "string"
545
- };
546
- const ref_name = {
547
- title: "ref_name",
548
- type: "string"
549
- };
550
- const source = {
551
- title: "source",
552
- type: "string"
553
- };
554
- const destination = {
555
- title: "destination",
556
- type: "string"
557
- };
558
- const hash = {
559
- title: "hash",
560
- type: "string"
561
- };
562
- const pattern = {
563
- title: "pattern",
564
- type: "string"
565
- };
566
- const id$1 = {
567
- title: "id",
568
- type: "string"
569
- };
570
- const key = {
571
- title: "key",
572
- type: "string"
573
- };
574
- const value = {
575
- title: "value",
576
- type: "string"
577
- };
578
- const secured = {
579
- title: "secured",
580
- type: "boolean"
581
- };
582
- const token = {
583
- title: "Authentication Token",
584
- type: "string",
585
- description: "The token to use for authorization to BitBucket Cloud"
586
- };
587
- const destination_commit = {
588
- title: "destination_commit",
589
- type: "object",
590
- properties: {
591
- hash
592
- }
593
- };
594
- const commit = {
595
- title: "commit",
596
- type: "object",
597
- properties: {
598
- type,
599
- hash
600
- }
601
- };
602
- const selector = {
603
- title: "selector",
604
- type: "object",
605
- properties: {
606
- type,
607
- pattern
608
- }
609
- };
610
- const pull_request = {
611
- title: "pull_request",
612
- type: "object",
613
- properties: {
614
- id: id$1
615
- }
616
- };
617
- const pipelinesRunBody = {
618
- title: "Request Body",
619
- description: "Request body properties: see Bitbucket Cloud Rest API documentation for more details",
620
- type: "object",
621
- properties: {
622
- target: {
623
- title: "target",
624
- type: "object",
625
- properties: {
626
- ref_type,
627
- type,
628
- ref_name,
629
- source,
630
- destination,
631
- destination_commit,
632
- commit,
633
- selector,
634
- pull_request
635
- }
636
- },
637
- variables: {
638
- title: "variables",
639
- type: "array",
640
- items: {
641
- type: "object",
642
- properties: {
643
- key,
644
- value,
645
- secured
646
- }
647
- }
648
- }
649
- }
650
- };
651
-
652
- const id = "bitbucket:pipelines:run";
653
- const createBitbucketPipelinesRunAction = (options) => {
654
- const { integrations } = options;
655
- return pluginScaffolderNode.createTemplateAction({
656
- id,
657
- description: "Run a bitbucket cloud pipeline",
658
- examples: examples$1,
659
- schema: {
660
- input: {
661
- type: "object",
662
- required: ["workspace", "repo_slug"],
663
- properties: {
664
- workspace: workspace,
665
- repo_slug: repo_slug,
666
- body: pipelinesRunBody,
667
- token: token
668
- }
669
- },
670
- output: {
671
- type: "object",
672
- properties: {
673
- buildNumber: {
674
- title: "Build number",
675
- type: "number"
676
- },
677
- repoUrl: {
678
- title: "A URL to the pipeline repositry",
679
- type: "string"
680
- },
681
- repoContentsUrl: {
682
- title: "A URL to the pipeline",
683
- type: "string"
684
- }
685
- }
686
- }
687
- },
688
- supportsDryRun: false,
689
- async handler(ctx) {
690
- const { workspace, repo_slug, body, token } = ctx.input;
691
- const host = "bitbucket.org";
692
- const integrationConfig = integrations.bitbucketCloud.byHost(host);
693
- const authorization = getAuthorizationHeader(
694
- token ? { token } : integrationConfig.config
695
- );
696
- let response;
697
- try {
698
- response = await fetch__default.default(
699
- `https://api.bitbucket.org/2.0/repositories/${workspace}/${repo_slug}/pipelines`,
700
- {
701
- method: "POST",
702
- headers: {
703
- Authorization: authorization,
704
- Accept: "application/json",
705
- "Content-Type": "application/json"
706
- },
707
- body: JSON.stringify(body) ?? {}
708
- }
709
- );
710
- } catch (e) {
711
- throw new Error(`Unable to run pipeline, ${e}`);
712
- }
713
- if (response.status !== 201) {
714
- throw new Error(
715
- `Unable to run pipeline, ${response.status} ${response.statusText}, ${await response.text()}`
716
- );
717
- }
718
- const responseObject = await response.json();
719
- ctx.output("buildNumber", responseObject.build_number);
720
- ctx.output("repoUrl", responseObject.repository.links.html.href);
721
- ctx.output(
722
- "pipelinesUrl",
723
- `${responseObject.repository.links.html.href}/pipelines`
724
- );
725
- }
726
- });
727
- };
728
-
729
- const examples = [
730
- {
731
- description: "Creating pull request on bitbucket cloud with required fields",
732
- example: yaml__default.default.stringify({
733
- steps: [
734
- {
735
- action: "publish:bitbucketCloud:pull-request",
736
- id: "publish-bitbucket-cloud-pull-request-minimal",
737
- name: "Creating pull request on bitbucket cloud",
738
- input: {
739
- repoUrl: "bitbucket.org?workspace=workspace&project=project&repo=repo",
740
- title: "My pull request",
741
- sourceBranch: "my-feature-branch"
742
- }
743
- }
744
- ]
745
- })
746
- },
747
- {
748
- description: "Creating pull request on bitbucket cloud with custom descriptions",
749
- example: yaml__default.default.stringify({
750
- steps: [
751
- {
752
- action: "publish:bitbucketCloud:pull-request",
753
- id: "publish-bitbucket-cloud-pull-request-minimal",
754
- name: "Creating pull request on bitbucket cloud",
755
- input: {
756
- repoUrl: "bitbucket.org?workspace=workspace&project=project&repo=repo",
757
- title: "My pull request",
758
- sourceBranch: "my-feature-branch",
759
- description: "This is a detailed description of my pull request"
760
- }
761
- }
762
- ]
763
- })
764
- },
765
- {
766
- description: "Creating pull request on bitbucket cloud with different target branch",
767
- example: yaml__default.default.stringify({
768
- steps: [
769
- {
770
- action: "publish:bitbucketCloud:pull-request",
771
- id: "publish-bitbucket-cloud-pull-request-target-branch",
772
- name: "Creating pull request on bitbucket cloud",
773
- input: {
774
- repoUrl: "bitbucket.org?workspace=workspace&project=project&repo=repo",
775
- title: "My pull request",
776
- sourceBranch: "my-feature-branch",
777
- targetBranch: "development"
778
- }
779
- }
780
- ]
781
- })
782
- },
783
- {
784
- description: "Creating pull request on bitbucket cloud with authorization token",
785
- example: yaml__default.default.stringify({
786
- steps: [
787
- {
788
- action: "publish:bitbucketCloud:pull-request",
789
- id: "publish-bitbucket-cloud-pull-request-minimal",
790
- name: "Creating pull request on bitbucket cloud",
791
- input: {
792
- repoUrl: "bitbucket.org?workspace=workspace&project=project&repo=repo",
793
- title: "My pull request",
794
- sourceBranch: "my-feature-branch",
795
- token: "my-auth-token"
796
- }
797
- }
798
- ]
799
- })
800
- },
801
- {
802
- description: "Creating pull request on bitbucket cloud with all fields",
803
- example: yaml__default.default.stringify({
804
- steps: [
805
- {
806
- action: "publish:bitbucketCloud:pull-request",
807
- id: "publish-bitbucket-cloud-pull-request-minimal",
808
- name: "Creating pull request on bitbucket cloud",
809
- input: {
810
- repoUrl: "bitbucket.org?workspace=workspace&project=project&repo=repo",
811
- title: "My pull request",
812
- sourceBranch: "my-feature-branch",
813
- targetBranch: "development",
814
- description: "This is a detailed description of my pull request",
815
- token: "my-auth-token",
816
- gitAuthorName: "test-user",
817
- gitAuthorEmail: "test-user@sample.com"
818
- }
819
- }
820
- ]
821
- })
822
- }
823
- ];
824
-
825
- const createPullRequest = async (opts) => {
826
- const {
827
- workspace,
828
- repo,
829
- title,
830
- description,
831
- targetBranch,
832
- sourceBranch,
833
- authorization,
834
- apiBaseUrl
835
- } = opts;
836
- let response;
837
- const data = {
838
- method: "POST",
839
- body: JSON.stringify({
840
- title,
841
- summary: {
842
- raw: description
843
- },
844
- state: "OPEN",
845
- source: {
846
- branch: {
847
- name: sourceBranch
848
- }
849
- },
850
- destination: {
851
- branch: {
852
- name: targetBranch
853
- }
854
- }
855
- }),
856
- headers: {
857
- Authorization: authorization,
858
- "Content-Type": "application/json"
859
- }
860
- };
861
- try {
862
- response = await fetch__default.default(
863
- `${apiBaseUrl}/repositories/${workspace}/${repo}/pullrequests`,
864
- data
865
- );
866
- } catch (e) {
867
- throw new Error(`Unable to create pull-reqeusts, ${e}`);
868
- }
869
- if (response.status !== 201) {
870
- throw new Error(
871
- `Unable to create pull requests, ${response.status} ${response.statusText}, ${await response.text()}`
872
- );
873
- }
874
- const r = await response.json();
875
- return r.links.html.href;
876
- };
877
- const findBranches = async (opts) => {
878
- const { workspace, repo, branchName, authorization, apiBaseUrl } = opts;
879
- let response;
880
- const options = {
881
- method: "GET",
882
- headers: {
883
- Authorization: authorization,
884
- "Content-Type": "application/json"
885
- }
886
- };
887
- try {
888
- response = await fetch__default.default(
889
- `${apiBaseUrl}/repositories/${workspace}/${repo}/refs/branches?q=${encodeURIComponent(
890
- `name = "${branchName}"`
891
- )}`,
892
- options
893
- );
894
- } catch (e) {
895
- throw new Error(`Unable to get branches, ${e}`);
896
- }
897
- if (response.status !== 200) {
898
- throw new Error(
899
- `Unable to get branches, ${response.status} ${response.statusText}, ${await response.text()}`
900
- );
901
- }
902
- const r = await response.json();
903
- return r.values[0];
904
- };
905
- const createBranch = async (opts) => {
906
- const {
907
- workspace,
908
- repo,
909
- branchName,
910
- authorization,
911
- apiBaseUrl,
912
- startBranch
913
- } = opts;
914
- let response;
915
- const options = {
916
- method: "POST",
917
- body: JSON.stringify({
918
- name: branchName,
919
- target: {
920
- hash: startBranch
921
- }
922
- }),
923
- headers: {
924
- Authorization: authorization,
925
- "Content-Type": "application/json"
926
- }
927
- };
928
- try {
929
- response = await fetch__default.default(
930
- `${apiBaseUrl}/repositories/${workspace}/${repo}/refs/branches`,
931
- options
932
- );
933
- } catch (e) {
934
- throw new Error(`Unable to create branch, ${e}`);
935
- }
936
- if (response.status !== 201) {
937
- throw new Error(
938
- `Unable to create branch, ${response.status} ${response.statusText}, ${await response.text()}`
939
- );
940
- }
941
- return await response.json();
942
- };
943
- const getDefaultBranch = async (opts) => {
944
- const { workspace, repo, authorization, apiBaseUrl } = opts;
945
- let response;
946
- const options = {
947
- method: "GET",
948
- headers: {
949
- Authorization: authorization,
950
- "Content-Type": "application/json"
951
- }
952
- };
953
- try {
954
- response = await fetch__default.default(
955
- `${apiBaseUrl}/repositories/${workspace}/${repo}`,
956
- options
957
- );
958
- } catch (error) {
959
- throw error;
960
- }
961
- const { mainbranch } = await response.json();
962
- const defaultBranch = mainbranch.name;
963
- if (!defaultBranch) {
964
- throw new Error(`Could not fetch default branch for ${workspace}/${repo}`);
965
- }
966
- return defaultBranch;
967
- };
968
- function createPublishBitbucketCloudPullRequestAction(options) {
969
- const { integrations, config } = options;
970
- return pluginScaffolderNode.createTemplateAction({
971
- id: "publish:bitbucketCloud:pull-request",
972
- examples,
973
- schema: {
974
- input: {
975
- type: "object",
976
- required: ["repoUrl", "title", "sourceBranch"],
977
- properties: {
978
- repoUrl: {
979
- title: "Repository Location",
980
- type: "string"
981
- },
982
- title: {
983
- title: "Pull Request title",
984
- type: "string",
985
- description: "The title for the pull request"
986
- },
987
- description: {
988
- title: "Pull Request Description",
989
- type: "string",
990
- description: "The description of the pull request"
991
- },
992
- targetBranch: {
993
- title: "Target Branch",
994
- type: "string",
995
- description: `Branch of repository to apply changes to. The default value is 'master'`
996
- },
997
- sourceBranch: {
998
- title: "Source Branch",
999
- type: "string",
1000
- description: "Branch of repository to copy changes from"
1001
- },
1002
- token: {
1003
- title: "Authorization Token",
1004
- type: "string",
1005
- description: "The token to use for authorization to BitBucket Cloud"
1006
- },
1007
- gitAuthorName: {
1008
- title: "Author Name",
1009
- type: "string",
1010
- description: `Sets the author name for the commit. The default value is 'Scaffolder'`
1011
- },
1012
- gitAuthorEmail: {
1013
- title: "Author Email",
1014
- type: "string",
1015
- description: `Sets the author email for the commit.`
1016
- }
1017
- }
1018
- },
1019
- output: {
1020
- type: "object",
1021
- properties: {
1022
- pullRequestUrl: {
1023
- title: "A URL to the pull request with the provider",
1024
- type: "string"
1025
- }
1026
- }
1027
- }
1028
- },
1029
- async handler(ctx) {
1030
- const {
1031
- repoUrl,
1032
- title,
1033
- description,
1034
- targetBranch,
1035
- sourceBranch,
1036
- gitAuthorName,
1037
- gitAuthorEmail
1038
- } = ctx.input;
1039
- const { workspace, repo, host } = pluginScaffolderNode.parseRepoUrl(repoUrl, integrations);
1040
- if (!workspace) {
1041
- throw new errors.InputError(
1042
- `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
1043
- );
1044
- }
1045
- const integrationConfig = integrations.bitbucketCloud.byHost(host);
1046
- if (!integrationConfig) {
1047
- throw new errors.InputError(
1048
- `No matching integration configuration for host ${host}, please check your integrations config`
1049
- );
1050
- }
1051
- const authorization = getAuthorizationHeader(
1052
- ctx.input.token ? { token: ctx.input.token } : integrationConfig.config
1053
- );
1054
- const apiBaseUrl = integrationConfig.config.apiBaseUrl;
1055
- let finalTargetBranch = targetBranch;
1056
- if (!finalTargetBranch) {
1057
- finalTargetBranch = await getDefaultBranch({
1058
- workspace,
1059
- repo,
1060
- authorization,
1061
- apiBaseUrl
1062
- });
1063
- }
1064
- const sourceBranchRef = await findBranches({
1065
- workspace,
1066
- repo,
1067
- branchName: sourceBranch,
1068
- authorization,
1069
- apiBaseUrl
1070
- });
1071
- if (!sourceBranchRef) {
1072
- ctx.logger.info(
1073
- `source branch not found -> creating branch named: ${sourceBranch}`
1074
- );
1075
- await createBranch({
1076
- workspace,
1077
- repo,
1078
- branchName: sourceBranch,
1079
- authorization,
1080
- apiBaseUrl,
1081
- startBranch: finalTargetBranch
1082
- });
1083
- const remoteUrl = `https://${host}/${workspace}/${repo}.git`;
1084
- let auth;
1085
- if (ctx.input.token) {
1086
- auth = {
1087
- username: "x-token-auth",
1088
- password: ctx.input.token
1089
- };
1090
- } else {
1091
- if (!integrationConfig.config.username || !integrationConfig.config.appPassword) {
1092
- throw new Error(
1093
- "Credentials for Bitbucket Cloud integration required for this action."
1094
- );
1095
- }
1096
- auth = {
1097
- username: integrationConfig.config.username,
1098
- password: integrationConfig.config.appPassword
1099
- };
1100
- }
1101
- const gitAuthorInfo = {
1102
- name: gitAuthorName || config.getOptionalString("scaffolder.defaultAuthor.name"),
1103
- email: gitAuthorEmail || config.getOptionalString("scaffolder.defaultAuthor.email")
1104
- };
1105
- const tempDir = await ctx.createTemporaryDirectory();
1106
- const sourceDir = pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, void 0);
1107
- await pluginScaffolderNode.cloneRepo({
1108
- url: remoteUrl,
1109
- dir: tempDir,
1110
- auth,
1111
- logger: ctx.logger,
1112
- ref: sourceBranch
1113
- });
1114
- await pluginScaffolderNode.createBranch({
1115
- dir: tempDir,
1116
- auth,
1117
- logger: ctx.logger,
1118
- ref: sourceBranch
1119
- });
1120
- fs__default.default.cpSync(sourceDir, tempDir, {
1121
- recursive: true,
1122
- filter: (path) => {
1123
- return !(path.indexOf(".git") > -1);
1124
- }
1125
- });
1126
- await pluginScaffolderNode.addFiles({
1127
- dir: tempDir,
1128
- auth,
1129
- logger: ctx.logger,
1130
- filepath: "."
1131
- });
1132
- await pluginScaffolderNode.commitAndPushBranch({
1133
- dir: tempDir,
1134
- auth,
1135
- logger: ctx.logger,
1136
- commitMessage: description ?? config.getOptionalString("scaffolder.defaultCommitMessage") ?? "",
1137
- gitAuthorInfo,
1138
- branch: sourceBranch
1139
- });
1140
- }
1141
- const pullRequestUrl = await createPullRequest({
1142
- workspace,
1143
- repo,
1144
- title,
1145
- description,
1146
- targetBranch: finalTargetBranch,
1147
- sourceBranch,
1148
- authorization,
1149
- apiBaseUrl
1150
- });
1151
- ctx.output("pullRequestUrl", pullRequestUrl);
1152
- }
1153
- });
1154
- }
1155
-
1156
- async function handleAutocompleteRequest({
1157
- resource,
1158
- token,
1159
- context
1160
- }) {
1161
- const client = pluginBitbucketCloudCommon.BitbucketCloudClient.fromConfig({
1162
- host: "bitbucket.org",
1163
- apiBaseUrl: "https://api.bitbucket.org/2.0",
1164
- token
1165
- });
1166
- switch (resource) {
1167
- case "workspaces": {
1168
- const results = [];
1169
- for await (const page of client.listWorkspaces().iteratePages()) {
1170
- const slugs = [...page.values].map((p) => ({ title: p.slug }));
1171
- results.push(...slugs);
1172
- }
1173
- return { results };
1174
- }
1175
- case "projects": {
1176
- if (!context.workspace)
1177
- throw new errors.InputError("Missing workspace context parameter");
1178
- const results = [];
1179
- for await (const page of client.listProjectsByWorkspace(context.workspace).iteratePages()) {
1180
- const keys = [...page.values].map((p) => ({ title: p.key }));
1181
- results.push(...keys);
1182
- }
1183
- return { results };
1184
- }
1185
- case "repositories": {
1186
- if (!context.workspace || !context.project)
1187
- throw new errors.InputError(
1188
- "Missing workspace and/or project context parameter"
1189
- );
1190
- const results = [];
1191
- for await (const page of client.listRepositoriesByWorkspace(context.workspace, {
1192
- q: `project.key="${context.project}"`
1193
- }).iteratePages()) {
1194
- const slugs = [...page.values].map((p) => ({ title: p.slug }));
1195
- results.push(...slugs);
1196
- }
1197
- return { results };
1198
- }
1199
- case "branches": {
1200
- if (!context.workspace || !context.repository)
1201
- throw new errors.InputError(
1202
- "Missing workspace and/or repository context parameter"
1203
- );
1204
- const results = [];
1205
- for await (const page of client.listBranchesByRepository(context.repository, context.workspace).iteratePages()) {
1206
- const names = [...page.values].map((p) => ({ title: p.name }));
1207
- results.push(...names);
1208
- }
1209
- return { results };
1210
- }
1211
- default:
1212
- throw new errors.InputError(`Invalid resource: ${resource}`);
1213
- }
1214
- }
1215
-
1216
- const bitbucketCloudModule = backendPluginApi.createBackendModule({
1217
- moduleId: "bitbucketCloud",
1218
- pluginId: "scaffolder",
1219
- register({ registerInit }) {
1220
- registerInit({
1221
- deps: {
1222
- scaffolder: alpha.scaffolderActionsExtensionPoint,
1223
- autocomplete: alpha.scaffolderAutocompleteExtensionPoint,
1224
- config: backendPluginApi.coreServices.rootConfig
1225
- },
1226
- async init({ scaffolder, config, autocomplete }) {
1227
- const integrations = integration.ScmIntegrations.fromConfig(config);
1228
- scaffolder.addActions(
1229
- createPublishBitbucketCloudAction({ integrations, config }),
1230
- createBitbucketPipelinesRunAction({ integrations }),
1231
- createPublishBitbucketCloudPullRequestAction({
1232
- integrations,
1233
- config
1234
- })
1235
- );
1236
- autocomplete.addAutocompleteProvider({
1237
- id: "bitbucket-cloud",
1238
- handler: handleAutocompleteRequest
1239
- });
1240
- }
1241
- });
1242
- }
1243
- });
1244
-
1245
- exports.createBitbucketPipelinesRunAction = createBitbucketPipelinesRunAction;
1246
- exports.createPublishBitbucketCloudAction = createPublishBitbucketCloudAction;
1247
- exports.createPublishBitbucketCloudPullRequestAction = createPublishBitbucketCloudPullRequestAction;
1248
- exports.default = bitbucketCloudModule;
12
+ exports.createPublishBitbucketCloudAction = bitbucketCloud.createPublishBitbucketCloudAction;
13
+ exports.createBitbucketPipelinesRunAction = bitbucketCloudPipelinesRun.createBitbucketPipelinesRunAction;
14
+ exports.createPublishBitbucketCloudPullRequestAction = bitbucketCloudPullRequest.createPublishBitbucketCloudPullRequestAction;
15
+ exports.default = module$1.bitbucketCloudModule;
1249
16
  //# sourceMappingURL=index.cjs.js.map