@backstage/plugin-scaffolder-backend-module-bitbucket 0.1.0-next.0

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.
@@ -0,0 +1,1093 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
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 integration = require('@backstage/integration');
10
+
11
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
+
13
+ var fetch__default = /*#__PURE__*/_interopDefaultLegacy(fetch);
14
+ var yaml__default = /*#__PURE__*/_interopDefaultLegacy(yaml);
15
+
16
+ const examples = [
17
+ {
18
+ description: "Initializes a git repository of contents in workspace and publish it to Bitbucket with default configuration.",
19
+ example: yaml__default["default"].stringify({
20
+ steps: [
21
+ {
22
+ id: "publish",
23
+ action: "publish:bitbucket",
24
+ name: "Publish to Bitbucket",
25
+ input: {
26
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project"
27
+ }
28
+ }
29
+ ]
30
+ })
31
+ },
32
+ {
33
+ description: "Add a description.",
34
+ example: yaml__default["default"].stringify({
35
+ steps: [
36
+ {
37
+ id: "publish",
38
+ action: "publish:bitbucket",
39
+ name: "Publish to Bitbucket",
40
+ input: {
41
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
42
+ description: "Initialize a git repository"
43
+ }
44
+ }
45
+ ]
46
+ })
47
+ },
48
+ {
49
+ description: "Change visibility of the repository.",
50
+ example: yaml__default["default"].stringify({
51
+ steps: [
52
+ {
53
+ id: "publish",
54
+ action: "publish:bitbucket",
55
+ name: "Publish to Bitbucket",
56
+ input: {
57
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
58
+ description: "Initialize a git repository",
59
+ repoVisibility: "public"
60
+ }
61
+ }
62
+ ]
63
+ })
64
+ },
65
+ {
66
+ description: "Set the default branch.",
67
+ example: yaml__default["default"].stringify({
68
+ steps: [
69
+ {
70
+ id: "publish",
71
+ action: "publish:bitbucket",
72
+ name: "Publish to Bitbucket",
73
+ input: {
74
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
75
+ description: "Initialize a git repository",
76
+ repoVisibility: "public",
77
+ defaultBranch: "main"
78
+ }
79
+ }
80
+ ]
81
+ })
82
+ },
83
+ {
84
+ description: "Specify a source path within the workspace.",
85
+ example: yaml__default["default"].stringify({
86
+ steps: [
87
+ {
88
+ id: "publish",
89
+ action: "publish:bitbucket",
90
+ name: "Publish to Bitbucket",
91
+ input: {
92
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
93
+ description: "Initialize a git repository",
94
+ repoVisibility: "public",
95
+ defaultBranch: "main",
96
+ sourcePath: "./repoRoot"
97
+ }
98
+ }
99
+ ]
100
+ })
101
+ },
102
+ {
103
+ description: "Enable LFS for the repository.",
104
+ example: yaml__default["default"].stringify({
105
+ steps: [
106
+ {
107
+ id: "publish",
108
+ action: "publish:bitbucket",
109
+ name: "Publish to Bitbucket",
110
+ input: {
111
+ repoUrl: "hosted.bitbucket.com?project=project&repo=repo",
112
+ description: "Initialize a git repository",
113
+ repoVisibility: "public",
114
+ defaultBranch: "main",
115
+ sourcePath: "./repoRoot",
116
+ enableLFS: true
117
+ }
118
+ }
119
+ ]
120
+ })
121
+ },
122
+ {
123
+ description: "Provide an authentication token for Bitbucket.",
124
+ example: yaml__default["default"].stringify({
125
+ steps: [
126
+ {
127
+ id: "publish",
128
+ action: "publish:bitbucket",
129
+ name: "Publish to Bitbucket",
130
+ input: {
131
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
132
+ description: "Initialize a git repository",
133
+ repoVisibility: "public",
134
+ defaultBranch: "main",
135
+ token: "your-auth-token"
136
+ }
137
+ }
138
+ ]
139
+ })
140
+ },
141
+ {
142
+ description: "Set a custom commit message.",
143
+ example: yaml__default["default"].stringify({
144
+ steps: [
145
+ {
146
+ id: "publish",
147
+ action: "publish:bitbucket",
148
+ name: "Publish to Bitbucket",
149
+ input: {
150
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
151
+ description: "Initialize a git repository",
152
+ repoVisibility: "public",
153
+ defaultBranch: "main",
154
+ token: "your-auth-token",
155
+ gitCommitMessage: "Initial commit with custom message"
156
+ }
157
+ }
158
+ ]
159
+ })
160
+ },
161
+ {
162
+ description: "Set a custom author name and email for the commit.",
163
+ example: yaml__default["default"].stringify({
164
+ steps: [
165
+ {
166
+ id: "publish",
167
+ action: "publish:bitbucket",
168
+ name: "Publish to Bitbucket",
169
+ input: {
170
+ repoUrl: "bitbucket.org?repo=repo&workspace=workspace&project=project",
171
+ description: "Initialize a git repository",
172
+ repoVisibility: "public",
173
+ defaultBranch: "main",
174
+ token: "your-auth-token",
175
+ gitCommitMessage: "Initial commit with custom message",
176
+ gitAuthorName: "Your Name",
177
+ gitAuthorEmail: "your.email@example.com"
178
+ }
179
+ }
180
+ ]
181
+ })
182
+ }
183
+ ];
184
+
185
+ const createBitbucketCloudRepository = async (opts) => {
186
+ const {
187
+ workspace,
188
+ project,
189
+ repo,
190
+ description,
191
+ repoVisibility,
192
+ mainBranch,
193
+ authorization,
194
+ apiBaseUrl
195
+ } = opts;
196
+ const options = {
197
+ method: "POST",
198
+ body: JSON.stringify({
199
+ scm: "git",
200
+ description,
201
+ is_private: repoVisibility === "private",
202
+ project: { key: project }
203
+ }),
204
+ headers: {
205
+ Authorization: authorization,
206
+ "Content-Type": "application/json"
207
+ }
208
+ };
209
+ let response;
210
+ try {
211
+ response = await fetch__default["default"](
212
+ `${apiBaseUrl}/repositories/${workspace}/${repo}`,
213
+ options
214
+ );
215
+ } catch (e) {
216
+ throw new Error(`Unable to create repository, ${e}`);
217
+ }
218
+ if (response.status !== 200) {
219
+ throw new Error(
220
+ `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
221
+ );
222
+ }
223
+ const r = await response.json();
224
+ let remoteUrl = "";
225
+ for (const link of r.links.clone) {
226
+ if (link.name === "https") {
227
+ remoteUrl = link.href;
228
+ }
229
+ }
230
+ const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;
231
+ return { remoteUrl, repoContentsUrl };
232
+ };
233
+ const createBitbucketServerRepository = async (opts) => {
234
+ const {
235
+ project,
236
+ repo,
237
+ description,
238
+ authorization,
239
+ repoVisibility,
240
+ apiBaseUrl
241
+ } = opts;
242
+ let response;
243
+ const options = {
244
+ method: "POST",
245
+ body: JSON.stringify({
246
+ name: repo,
247
+ description,
248
+ public: repoVisibility === "public"
249
+ }),
250
+ headers: {
251
+ Authorization: authorization,
252
+ "Content-Type": "application/json"
253
+ }
254
+ };
255
+ try {
256
+ response = await fetch__default["default"](`${apiBaseUrl}/projects/${project}/repos`, options);
257
+ } catch (e) {
258
+ throw new Error(`Unable to create repository, ${e}`);
259
+ }
260
+ if (response.status !== 201) {
261
+ throw new Error(
262
+ `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
263
+ );
264
+ }
265
+ const r = await response.json();
266
+ let remoteUrl = "";
267
+ for (const link of r.links.clone) {
268
+ if (link.name === "http") {
269
+ remoteUrl = link.href;
270
+ }
271
+ }
272
+ const repoContentsUrl = `${r.links.self[0].href}`;
273
+ return { remoteUrl, repoContentsUrl };
274
+ };
275
+ const getAuthorizationHeader$1 = (config) => {
276
+ if (config.username && config.appPassword) {
277
+ const buffer = Buffer.from(
278
+ `${config.username}:${config.appPassword}`,
279
+ "utf8"
280
+ );
281
+ return `Basic ${buffer.toString("base64")}`;
282
+ }
283
+ if (config.token) {
284
+ return `Bearer ${config.token}`;
285
+ }
286
+ throw new Error(
287
+ `Authorization has not been provided for Bitbucket. Please add either username + appPassword or token to the Integrations config`
288
+ );
289
+ };
290
+ const performEnableLFS$1 = async (opts) => {
291
+ const { authorization, host, project, repo } = opts;
292
+ const options = {
293
+ method: "PUT",
294
+ headers: {
295
+ Authorization: authorization
296
+ }
297
+ };
298
+ const { ok, status, statusText } = await fetch__default["default"](
299
+ `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
300
+ options
301
+ );
302
+ if (!ok)
303
+ throw new Error(
304
+ `Failed to enable LFS in the repository, ${status}: ${statusText}`
305
+ );
306
+ };
307
+ function createPublishBitbucketAction(options) {
308
+ const { integrations, config } = options;
309
+ return pluginScaffolderNode.createTemplateAction({
310
+ id: "publish:bitbucket",
311
+ description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket.",
312
+ examples,
313
+ schema: {
314
+ input: {
315
+ type: "object",
316
+ required: ["repoUrl"],
317
+ properties: {
318
+ repoUrl: {
319
+ title: "Repository Location",
320
+ type: "string"
321
+ },
322
+ description: {
323
+ title: "Repository Description",
324
+ type: "string"
325
+ },
326
+ repoVisibility: {
327
+ title: "Repository Visibility",
328
+ type: "string",
329
+ enum: ["private", "public"]
330
+ },
331
+ defaultBranch: {
332
+ title: "Default Branch",
333
+ type: "string",
334
+ description: `Sets the default branch on the repository. The default value is 'master'`
335
+ },
336
+ sourcePath: {
337
+ title: "Source Path",
338
+ description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
339
+ type: "string"
340
+ },
341
+ enableLFS: {
342
+ title: "Enable LFS?",
343
+ description: "Enable LFS for the repository. Only available for hosted Bitbucket.",
344
+ type: "boolean"
345
+ },
346
+ token: {
347
+ title: "Authentication Token",
348
+ type: "string",
349
+ description: "The token to use for authorization to BitBucket"
350
+ },
351
+ gitCommitMessage: {
352
+ title: "Git Commit Message",
353
+ type: "string",
354
+ description: `Sets the commit message on the repository. The default value is 'initial commit'`
355
+ },
356
+ gitAuthorName: {
357
+ title: "Default Author Name",
358
+ type: "string",
359
+ description: `Sets the default author name for the commit. The default value is 'Scaffolder'`
360
+ },
361
+ gitAuthorEmail: {
362
+ title: "Default Author Email",
363
+ type: "string",
364
+ description: `Sets the default author email for the commit.`
365
+ }
366
+ }
367
+ },
368
+ output: {
369
+ type: "object",
370
+ properties: {
371
+ remoteUrl: {
372
+ title: "A URL to the repository with the provider",
373
+ type: "string"
374
+ },
375
+ repoContentsUrl: {
376
+ title: "A URL to the root of the repository",
377
+ type: "string"
378
+ },
379
+ commitHash: {
380
+ title: "The git commit hash of the initial commit",
381
+ type: "string"
382
+ }
383
+ }
384
+ }
385
+ },
386
+ async handler(ctx) {
387
+ var _a;
388
+ ctx.logger.warn(
389
+ `[Deprecated] Please migrate the use of action "publish:bitbucket" to "publish:bitbucketCloud" or "publish:bitbucketServer".`
390
+ );
391
+ const {
392
+ repoUrl,
393
+ description,
394
+ defaultBranch = "master",
395
+ repoVisibility = "private",
396
+ enableLFS = false,
397
+ gitCommitMessage = "initial commit",
398
+ gitAuthorName,
399
+ gitAuthorEmail
400
+ } = ctx.input;
401
+ const { workspace, project, repo, host } = pluginScaffolderNode.parseRepoUrl(
402
+ repoUrl,
403
+ integrations
404
+ );
405
+ if (host === "bitbucket.org") {
406
+ if (!workspace) {
407
+ throw new errors.InputError(
408
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
409
+ );
410
+ }
411
+ }
412
+ if (!project) {
413
+ throw new errors.InputError(
414
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
415
+ );
416
+ }
417
+ const integrationConfig = integrations.bitbucket.byHost(host);
418
+ if (!integrationConfig) {
419
+ throw new errors.InputError(
420
+ `No matching integration configuration for host ${host}, please check your integrations config`
421
+ );
422
+ }
423
+ const authorization = getAuthorizationHeader$1(
424
+ ctx.input.token ? {
425
+ host: integrationConfig.config.host,
426
+ apiBaseUrl: integrationConfig.config.apiBaseUrl,
427
+ token: ctx.input.token
428
+ } : integrationConfig.config
429
+ );
430
+ const apiBaseUrl = integrationConfig.config.apiBaseUrl;
431
+ const createMethod = host === "bitbucket.org" ? createBitbucketCloudRepository : createBitbucketServerRepository;
432
+ const { remoteUrl, repoContentsUrl } = await createMethod({
433
+ authorization,
434
+ workspace: workspace || "",
435
+ project,
436
+ repo,
437
+ repoVisibility,
438
+ mainBranch: defaultBranch,
439
+ description,
440
+ apiBaseUrl
441
+ });
442
+ const gitAuthorInfo = {
443
+ name: gitAuthorName ? gitAuthorName : config.getOptionalString("scaffolder.defaultAuthor.name"),
444
+ email: gitAuthorEmail ? gitAuthorEmail : config.getOptionalString("scaffolder.defaultAuthor.email")
445
+ };
446
+ let auth;
447
+ if (ctx.input.token) {
448
+ auth = {
449
+ username: "x-token-auth",
450
+ password: ctx.input.token
451
+ };
452
+ } else {
453
+ auth = {
454
+ username: integrationConfig.config.username ? integrationConfig.config.username : "x-token-auth",
455
+ password: integrationConfig.config.appPassword ? integrationConfig.config.appPassword : (_a = integrationConfig.config.token) != null ? _a : ""
456
+ };
457
+ }
458
+ const commitResult = await pluginScaffolderNode.initRepoAndPush({
459
+ dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
460
+ remoteUrl,
461
+ auth,
462
+ defaultBranch,
463
+ logger: ctx.logger,
464
+ commitMessage: gitCommitMessage ? gitCommitMessage : config.getOptionalString("scaffolder.defaultCommitMessage"),
465
+ gitAuthorInfo
466
+ });
467
+ if (enableLFS && host !== "bitbucket.org") {
468
+ await performEnableLFS$1({ authorization, host, project, repo });
469
+ }
470
+ ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
471
+ ctx.output("remoteUrl", remoteUrl);
472
+ ctx.output("repoContentsUrl", repoContentsUrl);
473
+ }
474
+ });
475
+ }
476
+
477
+ const createRepository$1 = async (opts) => {
478
+ const {
479
+ workspace,
480
+ project,
481
+ repo,
482
+ description,
483
+ repoVisibility,
484
+ mainBranch,
485
+ authorization,
486
+ apiBaseUrl
487
+ } = opts;
488
+ const options = {
489
+ method: "POST",
490
+ body: JSON.stringify({
491
+ scm: "git",
492
+ description,
493
+ is_private: repoVisibility === "private",
494
+ project: { key: project }
495
+ }),
496
+ headers: {
497
+ Authorization: authorization,
498
+ "Content-Type": "application/json"
499
+ }
500
+ };
501
+ let response;
502
+ try {
503
+ response = await fetch__default["default"](
504
+ `${apiBaseUrl}/repositories/${workspace}/${repo}`,
505
+ options
506
+ );
507
+ } catch (e) {
508
+ throw new Error(`Unable to create repository, ${e}`);
509
+ }
510
+ if (response.status !== 200) {
511
+ throw new Error(
512
+ `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
513
+ );
514
+ }
515
+ const r = await response.json();
516
+ let remoteUrl = "";
517
+ for (const link of r.links.clone) {
518
+ if (link.name === "https") {
519
+ remoteUrl = link.href;
520
+ }
521
+ }
522
+ const repoContentsUrl = `${r.links.html.href}/src/${mainBranch}`;
523
+ return { remoteUrl, repoContentsUrl };
524
+ };
525
+ const getAuthorizationHeader = (config) => {
526
+ if (config.username && config.appPassword) {
527
+ const buffer = Buffer.from(
528
+ `${config.username}:${config.appPassword}`,
529
+ "utf8"
530
+ );
531
+ return `Basic ${buffer.toString("base64")}`;
532
+ }
533
+ if (config.token) {
534
+ return `Bearer ${config.token}`;
535
+ }
536
+ throw new Error(
537
+ `Authorization has not been provided for Bitbucket Cloud. Please add either username + appPassword to the Integrations config or a user login auth token`
538
+ );
539
+ };
540
+ function createPublishBitbucketCloudAction(options) {
541
+ const { integrations, config } = options;
542
+ return pluginScaffolderNode.createTemplateAction({
543
+ id: "publish:bitbucketCloud",
544
+ description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Cloud.",
545
+ schema: {
546
+ input: {
547
+ type: "object",
548
+ required: ["repoUrl"],
549
+ properties: {
550
+ repoUrl: {
551
+ title: "Repository Location",
552
+ type: "string"
553
+ },
554
+ description: {
555
+ title: "Repository Description",
556
+ type: "string"
557
+ },
558
+ repoVisibility: {
559
+ title: "Repository Visibility",
560
+ type: "string",
561
+ enum: ["private", "public"]
562
+ },
563
+ defaultBranch: {
564
+ title: "Default Branch",
565
+ type: "string",
566
+ description: `Sets the default branch on the repository. The default value is 'master'`
567
+ },
568
+ sourcePath: {
569
+ title: "Source Path",
570
+ description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
571
+ type: "string"
572
+ },
573
+ token: {
574
+ title: "Authentication Token",
575
+ type: "string",
576
+ description: "The token to use for authorization to BitBucket Cloud"
577
+ }
578
+ }
579
+ },
580
+ output: {
581
+ type: "object",
582
+ properties: {
583
+ remoteUrl: {
584
+ title: "A URL to the repository with the provider",
585
+ type: "string"
586
+ },
587
+ repoContentsUrl: {
588
+ title: "A URL to the root of the repository",
589
+ type: "string"
590
+ },
591
+ commitHash: {
592
+ title: "The git commit hash of the initial commit",
593
+ type: "string"
594
+ }
595
+ }
596
+ }
597
+ },
598
+ async handler(ctx) {
599
+ const {
600
+ repoUrl,
601
+ description,
602
+ defaultBranch = "master",
603
+ repoVisibility = "private"
604
+ } = ctx.input;
605
+ const { workspace, project, repo, host } = pluginScaffolderNode.parseRepoUrl(
606
+ repoUrl,
607
+ integrations
608
+ );
609
+ if (!workspace) {
610
+ throw new errors.InputError(
611
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing workspace`
612
+ );
613
+ }
614
+ if (!project) {
615
+ throw new errors.InputError(
616
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
617
+ );
618
+ }
619
+ const integrationConfig = integrations.bitbucketCloud.byHost(host);
620
+ if (!integrationConfig) {
621
+ throw new errors.InputError(
622
+ `No matching integration configuration for host ${host}, please check your integrations config`
623
+ );
624
+ }
625
+ const authorization = getAuthorizationHeader(
626
+ ctx.input.token ? { token: ctx.input.token } : integrationConfig.config
627
+ );
628
+ const apiBaseUrl = integrationConfig.config.apiBaseUrl;
629
+ const { remoteUrl, repoContentsUrl } = await createRepository$1({
630
+ authorization,
631
+ workspace: workspace || "",
632
+ project,
633
+ repo,
634
+ repoVisibility,
635
+ mainBranch: defaultBranch,
636
+ description,
637
+ apiBaseUrl
638
+ });
639
+ const gitAuthorInfo = {
640
+ name: config.getOptionalString("scaffolder.defaultAuthor.name"),
641
+ email: config.getOptionalString("scaffolder.defaultAuthor.email")
642
+ };
643
+ let auth;
644
+ if (ctx.input.token) {
645
+ auth = {
646
+ username: "x-token-auth",
647
+ password: ctx.input.token
648
+ };
649
+ } else {
650
+ if (!integrationConfig.config.username || !integrationConfig.config.appPassword) {
651
+ throw new Error(
652
+ "Credentials for Bitbucket Cloud integration required for this action."
653
+ );
654
+ }
655
+ auth = {
656
+ username: integrationConfig.config.username,
657
+ password: integrationConfig.config.appPassword
658
+ };
659
+ }
660
+ const commitResult = await pluginScaffolderNode.initRepoAndPush({
661
+ dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
662
+ remoteUrl,
663
+ auth,
664
+ defaultBranch,
665
+ logger: ctx.logger,
666
+ commitMessage: config.getOptionalString(
667
+ "scaffolder.defaultCommitMessage"
668
+ ),
669
+ gitAuthorInfo
670
+ });
671
+ ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
672
+ ctx.output("remoteUrl", remoteUrl);
673
+ ctx.output("repoContentsUrl", repoContentsUrl);
674
+ }
675
+ });
676
+ }
677
+
678
+ const createRepository = async (opts) => {
679
+ const {
680
+ project,
681
+ repo,
682
+ description,
683
+ authorization,
684
+ repoVisibility,
685
+ defaultBranch,
686
+ apiBaseUrl
687
+ } = opts;
688
+ let response;
689
+ const options = {
690
+ method: "POST",
691
+ body: JSON.stringify({
692
+ name: repo,
693
+ description,
694
+ defaultBranch,
695
+ public: repoVisibility === "public"
696
+ }),
697
+ headers: {
698
+ Authorization: authorization,
699
+ "Content-Type": "application/json"
700
+ }
701
+ };
702
+ try {
703
+ response = await fetch__default["default"](`${apiBaseUrl}/projects/${project}/repos`, options);
704
+ } catch (e) {
705
+ throw new Error(`Unable to create repository, ${e}`);
706
+ }
707
+ if (response.status !== 201) {
708
+ throw new Error(
709
+ `Unable to create repository, ${response.status} ${response.statusText}, ${await response.text()}`
710
+ );
711
+ }
712
+ const r = await response.json();
713
+ let remoteUrl = "";
714
+ for (const link of r.links.clone) {
715
+ if (link.name === "http") {
716
+ remoteUrl = link.href;
717
+ }
718
+ }
719
+ const repoContentsUrl = `${r.links.self[0].href}`;
720
+ return { remoteUrl, repoContentsUrl };
721
+ };
722
+ const performEnableLFS = async (opts) => {
723
+ const { authorization, host, project, repo } = opts;
724
+ const options = {
725
+ method: "PUT",
726
+ headers: {
727
+ Authorization: authorization
728
+ }
729
+ };
730
+ const { ok, status, statusText } = await fetch__default["default"](
731
+ `https://${host}/rest/git-lfs/admin/projects/${project}/repos/${repo}/enabled`,
732
+ options
733
+ );
734
+ if (!ok)
735
+ throw new Error(
736
+ `Failed to enable LFS in the repository, ${status}: ${statusText}`
737
+ );
738
+ };
739
+ function createPublishBitbucketServerAction(options) {
740
+ const { integrations, config } = options;
741
+ return pluginScaffolderNode.createTemplateAction({
742
+ id: "publish:bitbucketServer",
743
+ description: "Initializes a git repository of the content in the workspace, and publishes it to Bitbucket Server.",
744
+ schema: {
745
+ input: {
746
+ type: "object",
747
+ required: ["repoUrl"],
748
+ properties: {
749
+ repoUrl: {
750
+ title: "Repository Location",
751
+ type: "string"
752
+ },
753
+ description: {
754
+ title: "Repository Description",
755
+ type: "string"
756
+ },
757
+ repoVisibility: {
758
+ title: "Repository Visibility",
759
+ type: "string",
760
+ enum: ["private", "public"]
761
+ },
762
+ defaultBranch: {
763
+ title: "Default Branch",
764
+ type: "string",
765
+ description: `Sets the default branch on the repository. The default value is 'master'`
766
+ },
767
+ sourcePath: {
768
+ title: "Source Path",
769
+ description: "Path within the workspace that will be used as the repository root. If omitted, the entire workspace will be published as the repository.",
770
+ type: "string"
771
+ },
772
+ enableLFS: {
773
+ title: "Enable LFS?",
774
+ description: "Enable LFS for the repository.",
775
+ type: "boolean"
776
+ },
777
+ token: {
778
+ title: "Authentication Token",
779
+ type: "string",
780
+ description: "The token to use for authorization to BitBucket Server"
781
+ },
782
+ gitCommitMessage: {
783
+ title: "Git Commit Message",
784
+ type: "string",
785
+ description: `Sets the commit message on the repository. The default value is 'initial commit'`
786
+ },
787
+ gitAuthorName: {
788
+ title: "Author Name",
789
+ type: "string",
790
+ description: `Sets the author name for the commit. The default value is 'Scaffolder'`
791
+ },
792
+ gitAuthorEmail: {
793
+ title: "Author Email",
794
+ type: "string",
795
+ description: `Sets the author email for the commit.`
796
+ }
797
+ }
798
+ },
799
+ output: {
800
+ type: "object",
801
+ properties: {
802
+ remoteUrl: {
803
+ title: "A URL to the repository with the provider",
804
+ type: "string"
805
+ },
806
+ repoContentsUrl: {
807
+ title: "A URL to the root of the repository",
808
+ type: "string"
809
+ },
810
+ commitHash: {
811
+ title: "The git commit hash of the initial commit",
812
+ type: "string"
813
+ }
814
+ }
815
+ }
816
+ },
817
+ async handler(ctx) {
818
+ var _a;
819
+ const {
820
+ repoUrl,
821
+ description,
822
+ defaultBranch = "master",
823
+ repoVisibility = "private",
824
+ enableLFS = false,
825
+ gitCommitMessage = "initial commit",
826
+ gitAuthorName,
827
+ gitAuthorEmail
828
+ } = ctx.input;
829
+ const { project, repo, host } = pluginScaffolderNode.parseRepoUrl(repoUrl, integrations);
830
+ if (!project) {
831
+ throw new errors.InputError(
832
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
833
+ );
834
+ }
835
+ const integrationConfig = integrations.bitbucketServer.byHost(host);
836
+ if (!integrationConfig) {
837
+ throw new errors.InputError(
838
+ `No matching integration configuration for host ${host}, please check your integrations config`
839
+ );
840
+ }
841
+ const token = (_a = ctx.input.token) != null ? _a : integrationConfig.config.token;
842
+ const authConfig = {
843
+ ...integrationConfig.config,
844
+ ...{ token }
845
+ };
846
+ const reqOpts = integration.getBitbucketServerRequestOptions(authConfig);
847
+ const authorization = reqOpts.headers.Authorization;
848
+ if (!authorization) {
849
+ throw new Error(
850
+ `Authorization has not been provided for ${integrationConfig.config.host}. Please add either (a) a user login auth token, or (b) a token or (c) username + password to the integration config.`
851
+ );
852
+ }
853
+ const apiBaseUrl = integrationConfig.config.apiBaseUrl;
854
+ const { remoteUrl, repoContentsUrl } = await createRepository({
855
+ authorization,
856
+ project,
857
+ repo,
858
+ repoVisibility,
859
+ defaultBranch,
860
+ description,
861
+ apiBaseUrl
862
+ });
863
+ const gitAuthorInfo = {
864
+ name: gitAuthorName ? gitAuthorName : config.getOptionalString("scaffolder.defaultAuthor.name"),
865
+ email: gitAuthorEmail ? gitAuthorEmail : config.getOptionalString("scaffolder.defaultAuthor.email")
866
+ };
867
+ const auth = authConfig.token ? {
868
+ token
869
+ } : {
870
+ username: authConfig.username,
871
+ password: authConfig.password
872
+ };
873
+ const commitResult = await pluginScaffolderNode.initRepoAndPush({
874
+ dir: pluginScaffolderNode.getRepoSourceDirectory(ctx.workspacePath, ctx.input.sourcePath),
875
+ remoteUrl,
876
+ auth,
877
+ defaultBranch,
878
+ logger: ctx.logger,
879
+ commitMessage: gitCommitMessage ? gitCommitMessage : config.getOptionalString("scaffolder.defaultCommitMessage"),
880
+ gitAuthorInfo
881
+ });
882
+ if (enableLFS) {
883
+ await performEnableLFS({ authorization, host, project, repo });
884
+ }
885
+ ctx.output("commitHash", commitResult == null ? void 0 : commitResult.commitHash);
886
+ ctx.output("remoteUrl", remoteUrl);
887
+ ctx.output("repoContentsUrl", repoContentsUrl);
888
+ }
889
+ });
890
+ }
891
+
892
+ const createPullRequest = async (opts) => {
893
+ const {
894
+ project,
895
+ repo,
896
+ title,
897
+ description,
898
+ toRef,
899
+ fromRef,
900
+ authorization,
901
+ apiBaseUrl
902
+ } = opts;
903
+ let response;
904
+ const data = {
905
+ method: "POST",
906
+ body: JSON.stringify({
907
+ title,
908
+ description,
909
+ state: "OPEN",
910
+ open: true,
911
+ closed: false,
912
+ locked: true,
913
+ toRef,
914
+ fromRef
915
+ }),
916
+ headers: {
917
+ Authorization: authorization,
918
+ "Content-Type": "application/json"
919
+ }
920
+ };
921
+ try {
922
+ response = await fetch__default["default"](
923
+ `${apiBaseUrl}/projects/${encodeURIComponent(
924
+ project
925
+ )}/repos/${encodeURIComponent(repo)}/pull-requests`,
926
+ data
927
+ );
928
+ } catch (e) {
929
+ throw new Error(`Unable to create pull-reqeusts, ${e}`);
930
+ }
931
+ if (response.status !== 201) {
932
+ throw new Error(
933
+ `Unable to create pull requests, ${response.status} ${response.statusText}, ${await response.text()}`
934
+ );
935
+ }
936
+ const r = await response.json();
937
+ return `${r.links.self[0].href}`;
938
+ };
939
+ const findBranches = async (opts) => {
940
+ const { project, repo, branchName, authorization, apiBaseUrl } = opts;
941
+ let response;
942
+ const options = {
943
+ method: "GET",
944
+ headers: {
945
+ Authorization: authorization,
946
+ "Content-Type": "application/json"
947
+ }
948
+ };
949
+ try {
950
+ response = await fetch__default["default"](
951
+ `${apiBaseUrl}/projects/${encodeURIComponent(
952
+ project
953
+ )}/repos/${encodeURIComponent(
954
+ repo
955
+ )}/branches?boostMatches=true&filterText=${encodeURIComponent(
956
+ branchName
957
+ )}`,
958
+ options
959
+ );
960
+ } catch (e) {
961
+ throw new Error(`Unable to get branches, ${e}`);
962
+ }
963
+ if (response.status !== 200) {
964
+ throw new Error(
965
+ `Unable to get branches, ${response.status} ${response.statusText}, ${await response.text()}`
966
+ );
967
+ }
968
+ const r = await response.json();
969
+ for (const object of r.values) {
970
+ if (object.displayId === branchName) {
971
+ return object;
972
+ }
973
+ }
974
+ return void 0;
975
+ };
976
+ function createPublishBitbucketServerPullRequestAction(options) {
977
+ const { integrations } = options;
978
+ return pluginScaffolderNode.createTemplateAction({
979
+ id: "publish:bitbucketServer:pull-request",
980
+ schema: {
981
+ input: {
982
+ type: "object",
983
+ required: ["repoUrl", "title", "sourceBranch"],
984
+ properties: {
985
+ repoUrl: {
986
+ title: "Repository Location",
987
+ type: "string"
988
+ },
989
+ title: {
990
+ title: "Pull Request title",
991
+ type: "string",
992
+ description: "The title for the pull request"
993
+ },
994
+ description: {
995
+ title: "Pull Request Description",
996
+ type: "string",
997
+ description: "The description of the pull request"
998
+ },
999
+ targetBranch: {
1000
+ title: "Target Branch",
1001
+ type: "string",
1002
+ description: `Branch of repository to apply changes to. The default value is 'master'`
1003
+ },
1004
+ sourceBranch: {
1005
+ title: "Source Branch",
1006
+ type: "string",
1007
+ description: "Branch of repository to copy changes from"
1008
+ },
1009
+ token: {
1010
+ title: "Authorization Token",
1011
+ type: "string",
1012
+ description: "The token to use for authorization to BitBucket Server"
1013
+ }
1014
+ }
1015
+ },
1016
+ output: {
1017
+ type: "object",
1018
+ properties: {
1019
+ pullRequestUrl: {
1020
+ title: "A URL to the pull request with the provider",
1021
+ type: "string"
1022
+ }
1023
+ }
1024
+ }
1025
+ },
1026
+ async handler(ctx) {
1027
+ var _a;
1028
+ const {
1029
+ repoUrl,
1030
+ title,
1031
+ description,
1032
+ targetBranch = "master",
1033
+ sourceBranch
1034
+ } = ctx.input;
1035
+ const { project, repo, host } = pluginScaffolderNode.parseRepoUrl(repoUrl, integrations);
1036
+ if (!project) {
1037
+ throw new errors.InputError(
1038
+ `Invalid URL provider was included in the repo URL to create ${ctx.input.repoUrl}, missing project`
1039
+ );
1040
+ }
1041
+ const integrationConfig = integrations.bitbucketServer.byHost(host);
1042
+ if (!integrationConfig) {
1043
+ throw new errors.InputError(
1044
+ `No matching integration configuration for host ${host}, please check your integrations config`
1045
+ );
1046
+ }
1047
+ const token = (_a = ctx.input.token) != null ? _a : integrationConfig.config.token;
1048
+ const authConfig = {
1049
+ ...integrationConfig.config,
1050
+ ...{ token }
1051
+ };
1052
+ const reqOpts = integration.getBitbucketServerRequestOptions(authConfig);
1053
+ const authorization = reqOpts.headers.Authorization;
1054
+ if (!authorization) {
1055
+ throw new Error(
1056
+ `Authorization has not been provided for ${integrationConfig.config.host}. Please add either (a) a user login auth token, or (b) a token input from the template or (c) username + password to the integration config.`
1057
+ );
1058
+ }
1059
+ const apiBaseUrl = integrationConfig.config.apiBaseUrl;
1060
+ const toRef = await findBranches({
1061
+ project,
1062
+ repo,
1063
+ branchName: targetBranch,
1064
+ authorization,
1065
+ apiBaseUrl
1066
+ });
1067
+ const fromRef = await findBranches({
1068
+ project,
1069
+ repo,
1070
+ branchName: sourceBranch,
1071
+ authorization,
1072
+ apiBaseUrl
1073
+ });
1074
+ const pullRequestUrl = await createPullRequest({
1075
+ project,
1076
+ repo,
1077
+ title,
1078
+ description,
1079
+ toRef,
1080
+ fromRef,
1081
+ authorization,
1082
+ apiBaseUrl
1083
+ });
1084
+ ctx.output("pullRequestUrl", pullRequestUrl);
1085
+ }
1086
+ });
1087
+ }
1088
+
1089
+ exports.createPublishBitbucketAction = createPublishBitbucketAction;
1090
+ exports.createPublishBitbucketCloudAction = createPublishBitbucketCloudAction;
1091
+ exports.createPublishBitbucketServerAction = createPublishBitbucketServerAction;
1092
+ exports.createPublishBitbucketServerPullRequestAction = createPublishBitbucketServerPullRequestAction;
1093
+ //# sourceMappingURL=index.cjs.js.map