@docupace/pipeline 1.0.2-5.1 โ†’ 1.0.2

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.
@@ -2,11 +2,10 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import yaml from 'js-yaml';
4
4
  import { $ } from 'zx';
5
- import lodash from 'lodash';
6
- import { appInfo, environmentConfig, getRepUrl } from './config.js';
7
- import { copy2 } from './copy.js';
8
- import axios from 'axios';
9
- import { deployCore, deployConnect } from './jenkins.js';
5
+
6
+ const REPO_NAME = 'gitops-dev';
7
+ const REPO_URL = `https://x-token-auth:${process.env.GITOPS_DEV_REP_TOKEN}@bitbucket.org/dp-cloud/${REPO_NAME}.git`;
8
+ const GITOPS_BRANCH = 'master';
10
9
 
11
10
  /**
12
11
  * Clone the repository, read the YAML file, and return the parsed data and file paths.
@@ -14,179 +13,24 @@ import { deployCore, deployConnect } from './jenkins.js';
14
13
  * @param {string} site - The site name.
15
14
  * @returns {object} - The repository path, file path, and YAML data.
16
15
  */
16
+ export async function readDeployConfig(application, site) {
17
+ const repoPath = path.join(process.cwd(), REPO_NAME);
18
+ const deployConfigFilePath = path.join(repoPath, `dp/${site}/${application}.values.yaml`);
17
19
 
18
- function getRepoLocalPath(env) {
19
- const repoName = `gitops-${env}`;
20
- const repoPath = path.join(process.cwd(), repoName);
21
- return { repoPath, repoName };
22
- }
23
-
24
- async function updateAndCommitConnectVersion(
25
- toEnv,
26
- toSite,
27
- getComparedVersion,
28
- connectDeployPath,
29
- ) {
30
- const filePath = path.join(
31
- connectDeployPath,
32
- 'envs',
33
- toEnv,
34
- toSite,
35
- 'dock.sh',
36
- );
37
-
38
- try {
39
- let content = fs.readFileSync(filePath, 'utf8');
40
- content = content.replace(
41
- /IMAGE_VERSION=.*/,
42
- `IMAGE_VERSION=git-commit-${getComparedVersion}`,
43
- );
44
- fs.writeFileSync(filePath, content, 'utf8');
45
-
46
- // Git commands to stage, commit and push changes
47
- await $`cd ${connectDeployPath} && git config user.email "gitops@docupace.com"`;
48
- await $`cd ${connectDeployPath} && git add .`;
49
- await $`cd ${connectDeployPath} && git commit -m "Update Connect version for ${toSite} in ${toEnv} to ${getComparedVersion}"`;
50
- await $`cd ${connectDeployPath} && git push`;
51
-
52
- console.log('๐Ÿงน Cleaning up...');
53
- await $`rm -rf ${connectDeployPath}`;
54
- console.log('โœ… Cleanup complete.');
55
- } catch (error) {
56
- console.error('Error updating Connect version:', error);
57
- throw error;
58
- }
59
- }
60
-
61
- async function fetchLoginFooter(env, site, isNewUrl) {
62
- const url = isNewUrl
63
- ? environmentConfig[env].newUrl(site)
64
- : environmentConfig[env].oldUrl(site);
65
- const endpoint = isNewUrl ? '/connect/loginFooter' : '_ui/loginFooter';
66
- return await axios.get(`${url}${endpoint}`);
67
- }
68
-
69
- async function compareGetConnectSiteVersions(fromEnv, fromSite, toEnv, toSite) {
70
- try {
71
- let fromResponse, toResponse;
72
- try {
73
- fromResponse = await fetchLoginFooter(fromEnv, fromSite, true);
74
- } catch {
75
- fromResponse = await fetchLoginFooter(fromEnv, fromSite, false);
76
- }
20
+ console.log(`Cloning repository: ${REPO_NAME}`);
21
+ await $`git clone ${REPO_URL}`;
22
+ console.log(`Repository cloned to: ${repoPath}`);
77
23
 
24
+ let deployConfig;
78
25
  try {
79
- toResponse = await fetchLoginFooter(toEnv, toSite, true);
80
- } catch {
81
- toResponse = await fetchLoginFooter(toEnv, toSite, false);
26
+ deployConfig = yaml.load(fs.readFileSync(deployConfigFilePath, 'utf8'));
27
+ console.log(`YAML file loaded from: ${deployConfigFilePath}`);
28
+ } catch (error) {
29
+ console.error(`Error reading YAML file: ${error.message}`);
30
+ process.exit(1);
82
31
  }
83
32
 
84
- const fromMatch = fromResponse.data.match(/UI Build: ([a-f0-9]*)/);
85
- const toMatch = toResponse.data.match(/UI Build: ([a-f0-9]*)/);
86
-
87
- if (fromMatch && fromMatch[1] && toMatch && toMatch[1]) {
88
- if (fromMatch[1] !== toMatch[1]) {
89
- return fromMatch[1];
90
- }
91
- }
92
- return false;
93
- } catch (error) {
94
- console.error('Error fetching Connect versions:', error);
95
- throw error;
96
- }
97
- }
98
- function getRepoLocalPathByRepoSlug(repoSlug) {
99
- const repoName = `${repoSlug}`;
100
- const repoPath = path.join(process.cwd(), repoName);
101
- return { repoPath, repoName };
102
- }
103
-
104
- function cleanUpRepoPath(repoPath) {
105
- // Check and handle repo directory
106
- if (fs.existsSync(repoPath)) {
107
- console.log(`${repoPath} directory exists. Removing it...`);
108
- fs.rmSync(repoPath, {
109
- recursive: true,
110
- force: true,
111
- });
112
- }
113
- }
114
-
115
- export async function cloneEnvRepository(env) {
116
- const { repoPath, repoName } = getRepoLocalPath(env);
117
- const repoUrl = getRepUrl(repoName);
118
- console.log(`Cloning repository: ${repoName}`);
119
- await cleanUpRepoPath(repoPath);
120
- await $`git clone --depth 1 ${repoUrl}`;
121
- console.log(`Repository cloned to: ${repoPath}`);
122
- return repoPath;
123
- }
124
-
125
- export async function cloneRepository(repoSlug) {
126
- const { repoPath, repoName } = getRepoLocalPathByRepoSlug(repoSlug);
127
- const repoUrl = getRepUrl(repoName);
128
-
129
- await cleanUpRepoPath(repoPath);
130
-
131
- console.log(`Cloning repository: ${repoName}`);
132
- await $`git clone --depth 1 ${repoUrl}`;
133
- console.log(`Repository cloned to: ${repoPath}`);
134
- return repoPath;
135
- }
136
-
137
- function getConfigPath(application, env, site, name) {
138
- const { repoPath } = getRepoLocalPath(env);
139
- const deployConfigFilePath = path.join(
140
- repoPath,
141
- `dp/${site}/${application}.${name}.yaml`,
142
- );
143
-
144
- return { repoPath, deployConfigFilePath };
145
- }
146
-
147
- function getAppTypesFromRepo(env, site) {
148
- const { repoPath } = getRepoLocalPath(env);
149
- const deployConfigFilePath = path.join(repoPath, `dp/${site}`);
150
- const applications = [];
151
- if (fs.existsSync(deployConfigFilePath)) {
152
- const files = fs.readdirSync(deployConfigFilePath);
153
- files.forEach((file) => {
154
- if (file.includes('.values.yaml')) {
155
- const appName = file.split('.')[0];
156
- applications.push(appName);
157
- }
158
- });
159
- }
160
-
161
- return { applications };
162
- }
163
-
164
- export async function readDeployConfig(application, env, site, name) {
165
- const { deployConfigFilePath } = getConfigPath(application, env, site, name);
166
-
167
- let deployConfig;
168
- try {
169
- deployConfig = yaml.load(fs.readFileSync(deployConfigFilePath, 'utf8'));
170
- console.log(`YAML file loaded from: ${deployConfigFilePath}`);
171
- } catch (error) {
172
- console.error(`Error reading YAML file: ${error.message}`);
173
- process.exit(1);
174
- }
175
-
176
- return { deployConfig, deployConfigFilePath };
177
- }
178
-
179
- export async function cloneAndReadDeployConfig(application, env, site) {
180
- const repoPath = await cloneEnvRepository(env);
181
-
182
- const { deployConfig, deployConfigFilePath } = await readDeployConfig(
183
- application,
184
- env,
185
- site,
186
- 'values',
187
- );
188
-
189
- return { repoPath, deployConfigFilePath, deployConfig };
33
+ return { repoPath, deployConfigFilePath, deployConfig };
190
34
  }
191
35
 
192
36
  /**
@@ -196,15 +40,15 @@ export async function cloneAndReadDeployConfig(application, env, site) {
196
40
  * @returns {object} - The updated YAML data.
197
41
  */
198
42
  export function setTag(deployConfig, tag) {
199
- if (deployConfig.image && deployConfig.image.tag) {
200
- console.log(`Current image tag: ${deployConfig.image.tag}`);
201
- deployConfig.image.tag = tag;
202
- console.log(`Updated image tag to: ${deployConfig.image.tag}`);
203
- } else {
204
- console.error('No "image.tag" field found in the YAML file.');
205
- process.exit(1);
206
- }
207
- return deployConfig;
43
+ if (deployConfig.image && deployConfig.image.tag) {
44
+ console.log(`Current image tag: ${deployConfig.image.tag}`);
45
+ deployConfig.image.tag = tag;
46
+ console.log(`Updated image tag to: ${deployConfig.image.tag}`);
47
+ } else {
48
+ console.error('No "image.tag" field found in the YAML file.');
49
+ process.exit(1);
50
+ }
51
+ return deployConfig;
208
52
  }
209
53
 
210
54
  /**
@@ -213,50 +57,25 @@ export function setTag(deployConfig, tag) {
213
57
  * @param {string} deployConfigFilePath - The path to the YAML file.
214
58
  * @param {object} deployConfig - The updated YAML data.
215
59
  */
60
+ export async function writeDeployConfig(repoPath, deployConfigFilePath, deployConfig) {
61
+ try {
62
+ fs.writeFileSync(deployConfigFilePath, yaml.dump(deployConfig), 'utf8');
63
+ console.log(`Updated YAML file saved at: ${deployConfigFilePath}`);
64
+ } catch (error) {
65
+ console.error(`Error writing YAML file: ${error.message}`);
66
+ process.exit(1);
67
+ }
216
68
 
217
- export async function pushDeployConfig(repoPath, commitMessage) {
218
- console.log('๐Ÿ“Œ Checking for updates to commit...');
219
- // Check if there are any changes to commit
220
- const status = (
221
- await $`cd ${repoPath} && git status --porcelain`
222
- ).stdout.trim();
223
- if (!status) {
224
- console.log('โœ… No changes to commit. Exiting.');
225
- await $`rm -rf ${repoPath}`;
226
- console.log('๐Ÿงน Cleanup complete.');
227
- return;
228
- }
229
-
230
- console.log('๐Ÿ“Œ Committing changes to the repository...');
231
- await $`cd ${repoPath} && git config user.email "gitops@docupace.com"`;
232
- await $`cd ${repoPath} && git add .`;
233
- await $`cd ${repoPath} && git commit -m ${commitMessage}`;
234
- await $`cd ${repoPath} && git push`;
235
- console.log('โœ… Changes pushed to the remote repository.');
69
+ console.log('Committing changes to the repository...');
70
+ await $`cd ${repoPath} && git config user.email "gitops@docupace.com"`;
71
+ await $`cd ${repoPath} && git add ${deployConfigFilePath}`;
72
+ await $`cd ${repoPath} && git commit -m "Update image tag to ${deployConfig.image.tag}"`;
73
+ await $`cd ${repoPath} && git push origin ${GITOPS_BRANCH}`;
74
+ console.log('Changes pushed to the remote repository.');
236
75
 
237
- console.log('๐Ÿงน Cleaning up...');
238
- await $`rm -rf ${repoPath}`;
239
- console.log('โœ… Cleanup complete.');
240
- }
241
-
242
- function writeDeployConfig(deployConfigFilePath, deployConfig) {
243
- try {
244
- fs.writeFileSync(deployConfigFilePath, yaml.dump(deployConfig), 'utf8');
245
- console.log(`โœ… Updated YAML file saved at: ${deployConfigFilePath}`);
246
- } catch (error) {
247
- console.error(`โŒ Error writing YAML file: ${error.message}`);
248
- process.exit(1);
249
- }
250
- }
251
-
252
- export async function writeAndPushDeployConfig(
253
- repoPath,
254
- deployConfigFilePath,
255
- deployConfig,
256
- commitMessage,
257
- ) {
258
- writeDeployConfig(deployConfigFilePath, deployConfig);
259
- await pushDeployConfig(repoPath, commitMessage);
76
+ console.log('Cleaning up...');
77
+ await $`rm -rf ${repoPath}`;
78
+ console.log('Cleanup complete.');
260
79
  }
261
80
 
262
81
  /**
@@ -266,266 +85,34 @@ export async function writeAndPushDeployConfig(
266
85
  */
267
86
 
268
87
  async function getDeployTag() {
269
- const gitTag = (
270
- await $`git tag --points-at HEAD | grep '^v' | head -n 1`
271
- ).stdout.trim();
272
- const deployTag = gitTag || `build-${process.env.BITBUCKET_BUILD_NUMBER}`;
273
- return deployTag;
88
+ const gitTag = (await $`git tag --points-at HEAD | grep '^v' | head -n 1`).stdout.trim()
89
+ const deployTag = gitTag || `build-${process.env.BITBUCKET_BUILD_NUMBER}`;
90
+ return deployTag;
274
91
  }
275
92
 
276
93
  export async function deployTemplate(site) {
277
- const deployTag = await getDeployTag();
278
- console.log(`Deploying standard template for site: ${site}`);
279
- console.log(`Using deployment tag: ${deployTag}`);
280
- const { repoPath, deployConfigFilePath, deployConfig } =
281
- await cloneAndReadDeployConfig('graphql-server', 'dev', site);
282
-
283
- deployConfig.graphqlServer.standardConfigRemoteBranch = deployTag;
284
-
285
- await writeAndPushDeployConfig(
286
- repoPath,
287
- deployConfigFilePath,
288
- deployConfig,
289
- `Update template to ${deployConfig.graphqlServer.standardConfigRemoteBranch}`,
290
- );
291
- console.log('Deployment completed successfully.');
292
- }
293
-
294
- export async function deploy(application, site) {
295
- const deployTag = getDeployTag();
296
-
297
- console.log(`Deploying application: ${application} for site: ${site}`);
298
- console.log(`Using deployment tag: ${deployTag}`);
299
-
300
- const { repoPath, deployConfigFilePath, deployConfig } =
301
- await cloneAndReadDeployConfig(application, 'dev', site);
302
- const updatedConfigData = setTag(deployConfig, deployTag);
303
- await writeAndPushDeployConfig(
304
- repoPath,
305
- deployConfigFilePath,
306
- updatedConfigData,
307
- `Update image tag to ${deployConfig.image.tag}`,
308
- );
309
-
310
- console.log('Deployment completed successfully.');
311
- }
312
-
313
- async function getAppInfo(coreUrl) {
314
- const url = `${coreUrl}/b2b/rest/v1/appinfo`;
315
- return await axios.get(url);
316
- }
317
-
318
- function getBranchNameFromVersion(version) {
319
- const match = version.match(/(\d+\.\d+\.[^\-]+)(?:-(\d+)-g([a-f0-9]+))?/);
320
-
321
- if (!match) {
322
- throw new Error(`Invalid version format: ${version}`);
323
- }
324
-
325
- const fullVersion = match[1]; // e.g., 24.19.19, 24.20.alpha3, etc.
326
- const customBranch = match[2]; // e.g., 4, 58, or 0
327
- const commitHash = match[3]; // e.g., 668edef58e, 634cf6c904, etc.
328
-
329
- // If "alpha" is in the version or customBranch is non-zero, use the commit hash
330
- if (fullVersion.includes('alpha') || (customBranch && customBranch !== '0')) {
331
- return commitHash;
332
- }
333
-
334
- // Otherwise, use the full version
335
- return fullVersion;
336
- }
337
-
338
- async function getCoreBranchName(fromEnv, fromSite) {
339
- const envConfig = environmentConfig[fromEnv];
340
- const oldUrl = envConfig.oldUrl(fromSite);
341
- const newUrl = envConfig.newUrl(fromSite) + '/core';
342
-
343
- let appinfo;
344
- try {
345
- appinfo = await getAppInfo(oldUrl);
346
- } catch {
347
- try {
348
- appinfo = await getAppInfo(newUrl);
349
- } catch {
350
- throw new Error('Cannot get app info');
351
- }
352
- }
353
-
354
- const coreVersion = appinfo.data.core.version;
355
- const branchName = getBranchNameFromVersion(coreVersion);
356
- return branchName;
357
- }
358
-
359
- export async function deployApp(
360
- application,
361
- appDetails,
362
- fromEnv,
363
- fromSite,
364
- toEnv,
365
- toSite,
366
- ) {
367
- let changesMade = false;
368
- console.log(`Processing application: ${application}`);
369
-
370
- // Read the deployment configuration for the source environment and site
371
- const { deployConfig: fromDeployConfig } = await readDeployConfig(
372
- application,
373
- fromEnv,
374
- fromSite,
375
- 'values',
376
- );
377
-
378
- if (fromEnv !== toEnv) {
379
- await copy2(
380
- appDetails.repositoryName,
381
- fromEnv,
382
- toEnv,
383
- fromDeployConfig.image.tag,
384
- );
385
- }
386
-
387
- // Read the deployment configuration for the target environment and site
388
- const {
389
- deployConfig: toDeployConfig,
390
- deployConfigFilePath: toDeployConfigFilePath,
391
- } = await readDeployConfig(application, toEnv, toSite, 'values');
392
-
393
- // Update target configuration using attributes specified in appInfo
394
- for (const attribute of appDetails.deployAttributes) {
395
- const sourceValue = lodash.get(fromDeployConfig, attribute);
396
-
397
- if (sourceValue !== undefined) {
398
- // Update the target configuration with the source value
399
- lodash.set(toDeployConfig, attribute, sourceValue);
400
- changesMade = true;
401
- }
402
- }
403
-
404
- const {
405
- deployConfig: toDeployAppConfig,
406
- deployConfigFilePath: toDeployAppConfigFilePath,
407
- } = await readDeployConfig(application, toEnv, toSite, 'app');
94
+ const deployTag = await getDeployTag();
95
+ console.log(`Deploying standard template for site: ${site}`);
96
+ console.log(`Using deployment tag: ${deployTag}`);
97
+ const { repoPath, deployConfigFilePath, deployConfig } = await readDeployConfig('graphql-server', site);
408
98
 
409
- toDeployAppConfig.revision = fromDeployConfig.image.tag;
99
+ deployConfig.graphqlServer.standardConfigRemoteBranch = deployTag;
410
100
 
411
- // Write updated configuration to the target YAML file
412
- writeDeployConfig(toDeployConfigFilePath, toDeployConfig);
101
+ await writeDeployConfig(repoPath, deployConfigFilePath, deployConfig);
102
+ console.log('Deployment completed successfully.');
413
103
 
414
- writeDeployConfig(toDeployAppConfigFilePath, toDeployAppConfig);
415
- return changesMade;
416
104
  }
417
105
 
418
- export async function deployFromSite(
419
- fromEnv,
420
- fromSite,
421
- toEnv,
422
- toSite,
423
- isDeployCore,
424
- isDeployConnect,
425
- ) {
426
- if (isDeployCore === 'true') {
427
- const branchName = await getCoreBranchName(fromEnv, fromSite);
428
106
 
429
- const coreEnv = toEnv == 'qa' ? 'preprod' : toEnv;
430
- await deployCore(coreEnv, toSite, 'true', branchName);
431
-
432
- // To be added back when splitting between on prem and in cloud
433
- /*await runPipeline('site-deploy', 'deploy-core', 'main', {
434
- ENV: toEnv,
435
- SITE: toSite,
436
- LIQUIBASE: 'true',
437
- BRANCH: branchName,
438
- });*/
439
- }
440
-
441
- if (isDeployConnect === 'true') {
442
- const branch = '';
443
- const getComparedVersion = await compareGetConnectSiteVersions(
444
- fromEnv,
445
- fromSite,
446
- toEnv,
447
- toSite,
448
- );
449
- if (getComparedVersion) {
450
- console.log('Version to deploy is: ', getComparedVersion);
451
- const connectDeployPath = await cloneRepository('connect-deploy');
452
- // update target version set to git-commit-${getCommparedVersion}}
453
- await updateAndCommitConnectVersion(
454
- toEnv,
455
- toSite,
456
- getComparedVersion,
457
- connectDeployPath,
458
- );
459
- // save and deploy
460
- const runLiquibase = true;
461
- await deployConnect(toEnv, toSite, runLiquibase, branch);
462
- }
463
- }
464
-
465
- // Clone repositories for source and target environments
466
- const fromRepoPath = await cloneEnvRepository(fromEnv);
467
- const toRepoPath =
468
- toEnv === fromEnv ? fromRepoPath : await cloneEnvRepository(toEnv);
469
-
470
- // Initialize a flag to track changes
471
- let changesMade = false;
472
- const applications = await getAppTypesFromRepo(toEnv, toSite);
473
- console.log(applications);
474
- // Iterate over applications in appInfo
475
-
476
- let appInfoLocal = Object.fromEntries(
477
- applications.applications
478
- .filter((application) =>
479
- Object.prototype.hasOwnProperty.call(appInfo, application),
480
- )
481
- .map((application) => [application, appInfo[application]]),
482
- );
483
-
484
- // let appInfoLocal = {};
485
- // for (const application of applications.applications) {
486
- // if (Object.prototype.hasOwnProperty.call(appInfo, application)) {
487
- // appInfoLocal[application] = appInfo[application];
488
- // }
489
- // }
490
-
491
- if (Object.keys(appInfoLocal).length === 0) {
492
- const { deployConfig: toDeployAppConfig } = await readDeployConfig(
493
- fromSite,
494
- toEnv,
495
- toSite,
496
- 'app',
497
- );
498
-
499
- appInfoLocal[fromSite] = {
500
- repositoryName: toDeployAppConfig.repo,
501
- deployAttributes: ['image.tag'],
502
- };
503
- }
107
+ export async function deploy(application, site) {
108
+ const deployTag = getDeployTag();
504
109
 
505
- console.log('appinfoLocal', appInfoLocal);
110
+ console.log(`Deploying application: ${application} for site: ${site}`);
111
+ console.log(`Using deployment tag: ${deployTag}`);
506
112
 
507
- for (const [application, appDetails] of Object.entries(appInfoLocal)) {
508
- let cm = await deployApp(
509
- application,
510
- appDetails,
511
- fromEnv,
512
- fromSite,
513
- toEnv,
514
- toSite,
515
- );
516
- if (cm) {
517
- changesMade = true;
518
- }
519
- }
113
+ const { repoPath, deployConfigFilePath, deployConfig } = await readDeployConfig(application, site);
114
+ const updatedConfigData = setTag(deployConfig, deployTag);
115
+ await writeDeployConfig(repoPath, deployConfigFilePath, updatedConfigData);
520
116
 
521
- // Push all changes if any updates were made
522
- if (changesMade) {
523
- await pushDeployConfig(
524
- toRepoPath,
525
- `Updated deployment configurations from ${fromEnv}/${fromSite} to ${toEnv}/${toSite}`,
526
- );
527
- console.log('โœ… All configurations updated and pushed successfully.');
528
- } else {
529
- console.log('โœ… No changes detected. Nothing to push.');
530
- }
117
+ console.log('Deployment completed successfully.');
531
118
  }
@@ -1,48 +1,46 @@
1
- import { $ } from 'zx';
2
-
3
- export async function publish(GIT_SHA) {
4
- const BITBUCKET_REPO_SLUG = process.env.BITBUCKET_REPO_SLUG;
5
- const BUILD_IMAGE_NAME = `${BITBUCKET_REPO_SLUG}:build-${process.env.BITBUCKET_BUILD_NUMBER}`;
6
- const IMAGE_NAME = `${BITBUCKET_REPO_SLUG}:sha-${GIT_SHA}`;
7
- const JF_REGISTRY_FULL_URL = `${process.env.JF_REGISTRY_URL}/${process.env.JF_REGISTRY_REPO_NAME}`;
8
-
9
- console.log(`Publishing Docker image: ${IMAGE_NAME}`);
10
-
11
- // Docker login
12
- await $`echo ${process.env.JF_REGISTRY_PASSWORD_DEV} | docker login --username ${process.env.JF_REGISTRY_USER_DEV} --password-stdin ${process.env.JF_REGISTRY_URL}`;
13
-
14
- // Check if the image already exists
15
- try {
16
- await $`docker manifest inspect ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
17
- console.log(
18
- `Tag sha-${GIT_SHA} already exists in the remote repository. Skipping push.`,
19
- );
20
- } catch {
21
- await $`docker tag ${IMAGE_NAME} ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
22
- await $`docker push ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
23
- }
24
-
25
- // Tag and push build image
26
- await $`docker tag ${IMAGE_NAME} ${JF_REGISTRY_FULL_URL}/${BUILD_IMAGE_NAME}`;
27
- await $`docker push ${JF_REGISTRY_FULL_URL}/${BUILD_IMAGE_NAME}`;
28
-
29
- // Fetch Git tags pointing to the current HEAD
30
- const gitTagsOutput = (await $`git tag --points-at HEAD`).stdout.trim();
31
- const gitTags = gitTagsOutput.split('\n').filter((tag) => tag);
32
-
33
- // Tag and push each Git tag as a Docker tag
34
- if (gitTags.length > 0) {
35
- console.log(`Found Git tags pointing to HEAD: ${gitTags.join(', ')}`);
36
- for (const gitTag of gitTags) {
37
- const dockerTag = `${JF_REGISTRY_FULL_URL}/${BITBUCKET_REPO_SLUG}:${gitTag}`;
38
- console.log(`Tagging and pushing Docker image for Git tag: ${gitTag}`);
39
- await $`docker tag ${IMAGE_NAME} ${dockerTag}`;
40
- await $`docker push ${dockerTag}`;
41
- }
42
- } else {
43
- console.log('No Git tags found pointing to the current HEAD.');
44
- }
45
-
46
- // Docker logout
47
- await $`docker logout ${process.env.JF_REGISTRY_URL}`;
48
- }
1
+ import { $ } from 'zx';
2
+
3
+ export async function publish(GIT_SHA) {
4
+ const BITBUCKET_REPO_SLUG = process.env.BITBUCKET_REPO_SLUG;
5
+ const BUILD_IMAGE_NAME = `${BITBUCKET_REPO_SLUG}:build-${process.env.BITBUCKET_BUILD_NUMBER}`;
6
+ const IMAGE_NAME = `${BITBUCKET_REPO_SLUG}:sha-${GIT_SHA}`;
7
+ const JF_REGISTRY_FULL_URL = `${process.env.JF_REGISTRY_URL}/${process.env.JF_REGISTRY_REPO_NAME}`;
8
+
9
+ console.log(`Publishing Docker image: ${IMAGE_NAME}`);
10
+
11
+ // Docker login
12
+ await $`echo ${process.env.JF_REGISTRY_PASSWORD_DEV} | docker login --username ${process.env.JF_REGISTRY_USER_DEV} --password-stdin ${process.env.JF_REGISTRY_URL}`;
13
+
14
+ // Check if the image already exists
15
+ try {
16
+ await $`docker manifest inspect ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
17
+ console.log(`Tag sha-${GIT_SHA} already exists in the remote repository. Skipping push.`);
18
+ } catch {
19
+ await $`docker tag ${IMAGE_NAME} ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
20
+ await $`docker push ${JF_REGISTRY_FULL_URL}/${IMAGE_NAME}`;
21
+ }
22
+
23
+ // Tag and push build image
24
+ await $`docker tag ${IMAGE_NAME} ${JF_REGISTRY_FULL_URL}/${BUILD_IMAGE_NAME}`;
25
+ await $`docker push ${JF_REGISTRY_FULL_URL}/${BUILD_IMAGE_NAME}`;
26
+
27
+ // Fetch Git tags pointing to the current HEAD
28
+ const gitTagsOutput = (await $`git tag --points-at HEAD`).stdout.trim();
29
+ const gitTags = gitTagsOutput.split('\n').filter((tag) => tag);
30
+
31
+ // Tag and push each Git tag as a Docker tag
32
+ if (gitTags.length > 0) {
33
+ console.log(`Found Git tags pointing to HEAD: ${gitTags.join(', ')}`);
34
+ for (const gitTag of gitTags) {
35
+ const dockerTag = `${JF_REGISTRY_FULL_URL}/${BITBUCKET_REPO_SLUG}:${gitTag}`;
36
+ console.log(`Tagging and pushing Docker image for Git tag: ${gitTag}`);
37
+ await $`docker tag ${IMAGE_NAME} ${dockerTag}`;
38
+ await $`docker push ${dockerTag}`;
39
+ }
40
+ } else {
41
+ console.log('No Git tags found pointing to the current HEAD.');
42
+ }
43
+
44
+ // Docker logout
45
+ await $`docker logout ${process.env.JF_REGISTRY_URL}`;
46
+ }