@docupace/pipeline 1.0.2 → 1.0.3-1.demo1

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,107 @@
1
+ import axios from 'axios';
2
+
3
+ /**
4
+ * Fetch secrets from Vault.
5
+ * @param {string} vaultPath - The path in Vault to fetch secrets from.
6
+ * @returns {Promise<Object>} - The secret data as a JSON object.
7
+ */
8
+ export async function getVaultSecrets(vaultPath) {
9
+ if (!vaultPath) {
10
+ console.error('Error: VAULT_PATH is required.');
11
+ throw new Error('VAULT_PATH is required.');
12
+ }
13
+
14
+ const vaultToken = process.env.VAULT_TOKEN;
15
+ const vaultAddr = process.env.VAULT_ADDR;
16
+
17
+ if (!vaultToken || !vaultAddr) {
18
+ console.error('Error: VAULT_TOKEN and VAULT_ADDR must be set.');
19
+ throw new Error('VAULT_TOKEN and VAULT_ADDR must be set.');
20
+ }
21
+
22
+ try {
23
+ // Disable SSL verification globally by setting environment variable
24
+ if (process.env.VAULT_SKIP_VERIFY === 'true') {
25
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
26
+ }
27
+
28
+ // Fetch the secret from Vault
29
+ const response = await axios.get(`${vaultAddr}/v1/${vaultPath}`, {
30
+ headers: {
31
+ 'X-Vault-Token': vaultToken,
32
+ },
33
+ });
34
+
35
+ // Validate the response contains JSON data
36
+ const data = response.data;
37
+ if (data && typeof data === 'object') {
38
+ // console.log(`Secrets fetched successfully from Vault at ${JSON.stringify(data.data.data)})`);
39
+ return data.data.data;
40
+ } else {
41
+ console.error('Error: Invalid JSON received from Vault.');
42
+ throw new Error('Invalid JSON received from Vault.');
43
+ }
44
+ } catch (error) {
45
+ if (error.response) {
46
+ console.error(
47
+ `Error: Failed to connect to Vault server at ${vaultAddr}. Response: ${error.response.status} ${error.response.statusText}`
48
+ );
49
+ } else {
50
+ console.error(`Error: ${error.message}`);
51
+ }
52
+ // throw error;
53
+ }
54
+ }
55
+
56
+ /**
57
+ * Update a secret in Vault.
58
+ * @param {string} vaultPath - The path in Vault where the secret should be updated.
59
+ * @param {Object} secretData - The secret data to be stored (as a JSON object).
60
+ * @returns {Promise<Object>} - The response from Vault as a JSON object.
61
+ */
62
+ export async function updateVaultSecrets(vaultPath, secretData) {
63
+ if (!vaultPath || !secretData) {
64
+ console.error('Usage: updateVaultSecret(vaultPath, secretData)');
65
+ throw new Error('Both vaultPath and secretData are required.');
66
+ }
67
+
68
+ const vaultToken = process.env.VAULT_TOKEN;
69
+ const vaultAddr = process.env.VAULT_ADDR;
70
+
71
+ if (!vaultToken || !vaultAddr) {
72
+ console.error('Error: VAULT_TOKEN and VAULT_ADDR must be set.');
73
+ throw new Error('VAULT_TOKEN and VAULT_ADDR must be set.');
74
+ }
75
+
76
+ try {
77
+ // Disable SSL verification globally if VAULT_SKIP_VERIFY is set
78
+ if (process.env.VAULT_SKIP_VERIFY === 'true') {
79
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
80
+ }
81
+
82
+ // Make the POST request to update the Vault secret
83
+ const response = await axios.post(
84
+ `${vaultAddr}/v1/${vaultPath}`,
85
+ secretData,
86
+ {
87
+ headers: {
88
+ 'X-Vault-Token': vaultToken,
89
+ 'Content-Type': 'application/json',
90
+ },
91
+ }
92
+ );
93
+
94
+ // Return the response from Vault
95
+ console.log(response.data);
96
+ return response.data;
97
+ } catch (error) {
98
+ if (error.response) {
99
+ console.error(
100
+ `Error: Failed to update secret at ${vaultPath}. Response: ${error.response.status} ${error.response.statusText}`
101
+ );
102
+ } else {
103
+ console.error(`Error: ${error.message}`);
104
+ }
105
+ // throw error;
106
+ }
107
+ }
@@ -2,47 +2,70 @@
2
2
  import { Command } from 'commander';
3
3
  import { $ } from 'zx';
4
4
  import path from 'path';
5
- import {validateChangesets} from "./validate.js";
5
+ import { validateChangesets } from './validate.js';
6
6
  import fs from 'fs';
7
- import OpenAI from "openai";
8
- import {zodResponseFormat} from "openai/helpers/zod";
9
- import z from 'zod'
7
+ import OpenAI from 'openai';
8
+ import { zodResponseFormat } from 'openai/helpers/zod';
9
+ import z from 'zod';
10
10
  import dotenv from 'dotenv';
11
- dotenv.config({path : ['.env.pipeline.local', 'config/.env.pipeline.local']});
11
+ import { makeJiraRequest, updateComponentVersion } from '../next/jira.js';
12
+ dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
12
13
 
13
14
  const program = new Command();
14
15
 
15
16
  const args = process.argv;
16
17
 
17
- const DIR = path.resolve(process.cwd());
18
+ async function createChangesetDirectory() {
19
+ try {
20
+ // Use path.join to build a safe path to `.changeset`
21
+ const targetDir = path.join(process.cwd(), '.changeset');
22
+
23
+ // Create the directory recursively if it doesn't exist
24
+ await fs.promises.mkdir(targetDir, { recursive: true });
25
+ } catch (error) {
26
+ console.error('Error creating .changeset directory:', error);
27
+ }
28
+ }
29
+
30
+ function run(command) {
31
+ return new Promise((resolve, reject) => {
32
+ exec(command, { shell: true }, (error, stdout, stderr) => {
33
+ if (error) {
34
+ reject(error);
35
+ } else {
36
+ resolve({ stdout, stderr });
37
+ }
38
+ });
39
+ });
40
+ }
18
41
 
19
42
  async function fileExists(filePath) {
20
- try {
21
- await fs.promises.access(filePath);
22
- return true;
23
- } catch {
24
- return false;
25
- }
43
+ try {
44
+ await fs.promises.access(filePath);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
26
49
  }
27
50
 
28
51
  async function getMainPackage() {
29
- const mainModulePath = process.env.PWD;
30
- if (mainModulePath) {
31
- const packageJsonPath = path.join(mainModulePath, 'package.json');
32
- if (await fileExists(packageJsonPath)) {
33
- const fileContent = await fs.promises.readFile(packageJsonPath, 'utf-8');
34
- const packageJson = JSON.parse(fileContent);
35
- return packageJson;
36
- }
52
+ const mainModulePath = process.cwd();
53
+ if (mainModulePath) {
54
+ const packageJsonPath = path.join(mainModulePath, 'package.json');
55
+ if (await fileExists(packageJsonPath)) {
56
+ const fileContent = await fs.promises.readFile(packageJsonPath, 'utf-8');
57
+ const packageJson = JSON.parse(fileContent);
58
+ return packageJson;
37
59
  }
38
- throw new Error('Main package.json not found');
60
+ }
61
+ throw new Error('Main package.json not found');
39
62
  }
40
63
 
41
64
  // Helper function to set Git info
42
65
  async function setGitInfo() {
43
- await $`git config --global user.email "gitops@docupace.com"`;
44
- await $`git config --global user.name "Gitops"`;
45
- await $`git remote set-url origin https://${process.env.THIS_REP_TOKEN}@bitbucket.org/${process.env.BITBUCKET_REPO_FULL_NAME}.git`;
66
+ await $`git config --global user.email "gitops@docupace.com"`;
67
+ await $`git config --global user.name "Gitops"`;
68
+ await $`git remote set-url origin https://${process.env.THIS_REP_TOKEN}@bitbucket.org/${process.env.BITBUCKET_REPO_FULL_NAME}.git`;
46
69
  }
47
70
 
48
71
  const changeSetPackage = `{
@@ -60,176 +83,242 @@ const changeSetPackage = `{
60
83
  "@changesets/cli": "^2.27.10"
61
84
  }
62
85
  }
63
- `
64
-
65
- async function versionCommand() {
66
- console.log('📦 Running Changeset versioning...');
67
- await setGitInfo();
68
- await $`mv package.json package.json.bak`
69
- await $`mv pnpm-lock.yaml pnpm-lock.yaml.bak`
70
- await fs.promises.writeFile('package.json', changeSetPackage);
71
- await $`pnpm install`;
72
- await $`rm package.json pnpm-lock.yaml`
73
- await $`mv package.json.bak package.json`
74
- await $`mv pnpm-lock.yaml.bak pnpm-lock.yaml`
75
- await $`pnpm changeset version`;
76
- console.log('✅ Changeset versioning complete.');
86
+ `;
87
+
88
+ async function versionCommand(closeVersion = false) {
89
+ console.log('📦 Running Changeset versioning...');
90
+ await setGitInfo();
91
+ await $`mv package.json package.json.bak`;
92
+ await $`mv pnpm-lock.yaml pnpm-lock.yaml.bak`;
93
+ await fs.promises.writeFile('package.json', changeSetPackage);
94
+ await $`pnpm install`;
95
+ await $`rm package.json pnpm-lock.yaml`;
96
+ await $`mv package.json.bak package.json`;
97
+ await $`mv pnpm-lock.yaml.bak pnpm-lock.yaml`;
98
+ if (closeVersion) {
99
+ await $`pnpm changeset pre exit`;
100
+ }
101
+
102
+ await $`pnpm changeset version`;
103
+
104
+ // Read the updated package.json to get the new version and package name
105
+ const packageJson = JSON.parse(
106
+ await fs.promises.readFile('package.json', 'utf-8'),
107
+ );
108
+ const version = packageJson.version;
109
+ const packageName = packageJson.name;
110
+
111
+ if (closeVersion) {
112
+ return { version, packageName };
113
+ }
114
+
115
+ // Get the last commit message and extract Jira ticket
116
+ const lastCommit = (await $`git log -1 --pretty=%B`).stdout.trim();
117
+ console.log(`Last commit '${lastCommit}' being processed to get Jira ticket`);
118
+
119
+ const jiraTicketMatch = lastCommit.match(/([A-Z]+-\d+)/);
120
+ const jiraTicketId = jiraTicketMatch ? jiraTicketMatch[0] : null;
121
+
122
+ // If we have all the necessary data, update the component version in Jira
123
+ if (jiraTicketId && version && packageName) {
124
+ try {
125
+ await updateComponentVersion(jiraTicketId, packageName, version);
126
+ } catch (error) {
127
+ console.error(
128
+ `Failed to update Jira component version: ${error.message}`,
129
+ );
130
+ }
131
+ }
132
+
133
+ console.log('✅ Changeset versioning complete.');
134
+ return { version, packageName };
77
135
  }
78
136
 
79
137
  async function commitTagCommand() {
80
- console.log('📌 Committing and tagging the new version...');
81
- await setGitInfo();
82
- await $`git add .`;
83
- const newVersion = (await $`node -p "require('./package.json').version"`).stdout.trim();
84
- await $`git commit -m "Version bump to ${newVersion} and changelog"`;
85
- await $`git push origin`;
86
- await $`git tag v${newVersion}`;
87
- await $`git push origin --tags`;
88
- console.log(`✅ Version ${newVersion} tagged and pushed.`);
138
+ console.log('📌 Checking for updates to commit...');
139
+
140
+ // Check if there are changes to commit
141
+ const status = (await $`git status --porcelain`).stdout.trim();
142
+ if (!status) {
143
+ console.log('✅ No changes to commit. Exiting.');
144
+ return;
145
+ }
146
+
147
+ console.log('📌 Committing and tagging the new version...');
148
+ await setGitInfo();
149
+ await $`git add .`;
150
+ const newVersion = (
151
+ await $`node -p "require('./package.json').version"`
152
+ ).stdout.trim();
153
+ await $`git commit -m "Version bump to ${newVersion} and changelog"`;
154
+ await $`git push origin`;
155
+ await $`git tag v${newVersion}`;
156
+ await $`git push origin --tags`;
157
+ console.log(`✅ Version ${newVersion} tagged and pushed.`);
89
158
  }
90
159
 
91
160
  // Command: validate
92
161
  program
93
- .command('validate <path>')
94
- .description('Validate changesets for the provided PR')
95
- .action(async (path) => {
96
- if(!process.env.BITBUCKET_PR_ID) {
97
- return;
98
- }
99
- console.log('🔍 Validating changesets...');
100
- try {
101
- await validateChangesets(path);
102
- console.log('✅ Changeset validation passed.');
103
- } catch (error) {
104
- console.error(
105
- '❌ No changeset found. Please add a changeset to this PR. Please see more information at https://docupacellc.atlassian.net/wiki/spaces/PM/pages/1350893571/Creating+changesets+for+Docupace+Next'
106
- );
107
- process.exit(1);
108
- }
109
- });
162
+ .command('validate <path>')
163
+ .description('Validate changesets for the provided PR')
164
+ .action(async (path) => {
165
+ if (!process.env.BITBUCKET_PR_ID) {
166
+ return;
167
+ }
168
+ console.log('🔍 Validating changesets...');
169
+ try {
170
+ await validateChangesets(path);
171
+ console.log('✅ Changeset validation passed.');
172
+ } catch (error) {
173
+ console.error(
174
+ '❌ No changeset found. Please add a changeset to this PR. Please see more information at https://docupacellc.atlassian.net/wiki/spaces/PM/pages/1350893571/Creating+changesets+for+Docupace+Next',
175
+ );
176
+ process.exit(1);
177
+ }
178
+ });
110
179
  // Command: version
111
180
  program
112
- .command('version')
113
- .description('Run Changeset versioning')
114
- .action(async () => {
115
- await versionCommand();
116
- });
181
+ .command('version')
182
+ .description('Run Changeset versioning')
183
+ .action(async () => {
184
+ await versionCommand();
185
+ });
117
186
 
118
187
  // Command: commit-and-tag
119
188
  program
120
- .command('commit-tag')
121
- .description('Commit and tag the new version')
122
- .action(async () => {
123
- await commitTagCommand();
124
- });
189
+ .command('commit-tag')
190
+ .description('Commit and tag the new version')
191
+ .action(async () => {
192
+ await commitTagCommand();
193
+ });
125
194
 
126
195
  // Command: all
127
196
  program
128
- .command('version-commit-tag')
129
- .description('Run versioning and commit-and-tag in sequence')
130
- .action(async () => {
131
- console.log('📦 Running all steps...');
132
- await versionCommand();
133
- await commitTagCommand();
134
- });
197
+ .command('version-commit-tag')
198
+ .description('Run versioning and commit-and-tag in sequence')
199
+ .action(async () => {
200
+ console.log('📦 Running all steps...');
201
+ await versionCommand();
202
+ await commitTagCommand();
203
+ });
135
204
 
136
205
  program
137
- .name('create-changeset')
138
- .description('Creates a changeset based on the current branch and Jira ticket information')
139
- .action(async () => {
140
- const mainPackage = await getMainPackage();
141
- const componentName = mainPackage.name;
142
-
143
- try {
144
- // Step 1: Get the current branch name
145
- const branchName = (await $`git branch --show-current`).stdout.trim();
146
- console.log(`Current branch: ${branchName}`);
147
-
148
- // Step 2: Extract Jira ticket number (e.g., matching JIRA-1234 pattern)
149
- const jiraTicketMatch = branchName.match(/([A-Z]+-\d+)/);
150
- if (!jiraTicketMatch) {
151
- throw new Error('No Jira ticket found in the branch name.');
152
- }
153
- const jiraTicketId = jiraTicketMatch[0];
154
-
155
- // Step 3: Fetch Jira ticket information
156
- const jiraBaseUrl = 'https://docupacellc.atlassian.net';
157
- const jiraEmail = process.env.JIRA_API_EMAIL;
158
- const jiraApiKey = process.env.JIRA_API_KEY;
159
- const jiraFullApiKey = `${jiraEmail}:${jiraApiKey}`;
160
- const jiraUrl = `${jiraBaseUrl}/rest/api/2/issue/${jiraTicketId}`;
161
- const jiraResponse = await fetch(jiraUrl, {
162
- headers: {
163
- Authorization: `Basic ${Buffer.from(jiraFullApiKey).toString('base64')}`,
164
- 'Content-Type': 'application/json',
165
- },
166
- });
167
-
168
- if (!jiraResponse.ok) {
169
- throw new Error(`Failed to fetch Jira ticket. Status: ${jiraResponse.status}`);
170
- }
171
- const jiraTicketData = await jiraResponse.json();
172
-
173
- if(jiraTicketData.fields.customfield_10107?.value !== 'Product') {
174
- throw new Error("Issue Type of Work must be Product")
175
- }
176
-
177
- const jiraSummary = jiraTicketData.fields.summary;
178
-
179
- console.log(`Generating release notes for ${jiraTicketId} - ${jiraSummary}`)
180
-
181
- const openaiClient = new OpenAI({
182
- apiKey: process.env['OPENAI_API_KEY'],
183
- });
184
-
185
- const ChangeRequestSchema = z.object({
186
- change_type: z.enum(["patch", "minor"]),
187
- summary: z.string(),
188
- jira_ticket_id: z.string(),
189
- });
190
-
191
- const openAiResponse = await openaiClient.chat.completions.create({
192
- model: "gpt-4o-mini",
193
- messages: [
194
- {
195
- role: "system",
196
- content: `Process JSON from a Jira ticket to generate simple maximum 2 sentence release note for the ticket and determine the change type for bug it should be a patch for new feature it should be a minor change`,
197
- },
198
- {
199
- role: "user",
200
- content: JSON.stringify(jiraTicketData),
201
- },
202
- ],
203
- response_format: zodResponseFormat(ChangeRequestSchema, 'changeset_schema'),
204
- temperature: 0
205
- });
206
-
207
- const assistantResponse = openAiResponse.choices[0].message.content;
208
- const parsedResponse = JSON.parse(assistantResponse);
209
-
210
- const { change_type, summary } = parsedResponse;
211
- console.log(`Change type: ${change_type}`);
212
- console.log(`Release note: ${summary}`);
213
-
214
- // Step 5: Create a changeset using pnpm
215
- const changesetContent = `---
206
+ .command('close-version')
207
+ .description('Closes a version')
208
+ .action(async () => {
209
+ console.log('📦 Running all steps...');
210
+ const { version } = await versionCommand(true);
211
+ await commitTagCommand();
212
+
213
+ // Get current branch
214
+ const { stdout: currentBranch } = await $`git rev-parse --abbrev-ref HEAD`;
215
+
216
+ // Create and push release branch
217
+ await $`git checkout -b release/${version}`;
218
+ await $`git push origin release/${version}`;
219
+
220
+ // Return to original branch
221
+ await $`git checkout ${currentBranch.trim()}`;
222
+
223
+ // Open next alpha version
224
+ await $`pnpm changeset pre enter alpha`;
225
+ await $`git add .`;
226
+ await $`git commit -m "Open next alpha version"`;
227
+ await $`git push origin`;
228
+
229
+ });
230
+
231
+ program
232
+ .name('create-changeset')
233
+ .description(
234
+ 'Creates a changeset based on the current branch and Jira ticket information',
235
+ )
236
+ .action(async () => {
237
+ const mainPackage = await getMainPackage();
238
+ const componentName = mainPackage.name;
239
+
240
+ try {
241
+ // Step 1: Get the current branch name
242
+ const branchName = (await $`git branch --show-current`).stdout.trim();
243
+ console.log(`Current branch: ${branchName}`);
244
+
245
+ // Step 2: Extract Jira ticket number (e.g., matching JIRA-1234 pattern)
246
+ const jiraTicketMatch = branchName.match(/([A-Z]+-\d+)/);
247
+ if (!jiraTicketMatch) {
248
+ throw new Error('No Jira ticket found in the branch name.');
249
+ }
250
+ const jiraTicketId = jiraTicketMatch[0];
251
+
252
+ // Step 3: Fetch Jira ticket information
253
+ const jiraTicketData = await makeJiraRequest(
254
+ `/rest/api/2/issue/${jiraTicketId}`,
255
+ );
256
+
257
+ if (jiraTicketData.fields.customfield_10107?.value !== 'Product') {
258
+ throw new Error('Issue Type of Work must be Product');
259
+ }
260
+
261
+ const jiraSummary = jiraTicketData.fields.summary;
262
+
263
+ console.log(
264
+ `Generating release notes for ${jiraTicketId} - ${jiraSummary}`,
265
+ );
266
+
267
+ const openaiClient = new OpenAI({
268
+ apiKey: process.env['OPENAI_API_KEY'],
269
+ });
270
+
271
+ const ChangeRequestSchema = z.object({
272
+ change_type: z.enum(['patch', 'minor']),
273
+ summary: z.string(),
274
+ jira_ticket_id: z.string(),
275
+ });
276
+
277
+ const openAiResponse = await openaiClient.chat.completions.create({
278
+ model: 'gpt-4o-mini',
279
+ messages: [
280
+ {
281
+ role: 'system',
282
+ content: `Process JSON from a Jira ticket to generate simple maximum 2 sentence release note for the ticket and determine the change type for bug it should be a patch for new feature it should be a minor change`,
283
+ },
284
+ {
285
+ role: 'user',
286
+ content: JSON.stringify(jiraTicketData),
287
+ },
288
+ ],
289
+ response_format: zodResponseFormat(
290
+ ChangeRequestSchema,
291
+ 'changeset_schema',
292
+ ),
293
+ temperature: 0,
294
+ });
295
+
296
+ const assistantResponse = openAiResponse.choices[0].message.content;
297
+ const parsedResponse = JSON.parse(assistantResponse);
298
+
299
+ const { change_type, summary } = parsedResponse;
300
+ console.log(`Change type: ${change_type}`);
301
+ console.log(`Release note: ${summary}`);
302
+
303
+ // Step 5: Create a changeset .md file
304
+ const changesetContent = `---
216
305
  "${componentName}": ${change_type}
217
306
  ---
218
307
 
219
308
  ${summary} [${jiraTicketId}]
220
309
  `;
221
- const changesetFile = `./.changeset/${jiraTicketId}.md`;
310
+ const changesetFile = `./.changeset/${jiraTicketId}.md`;
222
311
 
223
- await $`mkdir -p ./.changeset`;
224
- await fs.promises.writeFile(changesetFile, changesetContent);
225
- console.log(`Created changeset file at ${changesetFile}`);
226
-
227
- console.log('Done!');
228
- } catch (err) {
229
- console.error(`Error: ${err.message}`);
230
- }
231
- });
312
+ await createChangesetDirectory();
313
+ await fs.promises.writeFile(changesetFile, changesetContent);
314
+ console.log(`Created changeset file at ${changesetFile}`);
232
315
 
316
+ console.log('Done!');
317
+ } catch (err) {
318
+ console.error(`Error: ${err.message}`);
319
+ process.exit(1);
320
+ }
321
+ });
233
322
 
234
323
  // Parse arguments
235
324
  program.parse(args);