@docupace/pipeline 1.0.26 → 1.0.28-matttest.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.
@@ -1,281 +1,289 @@
1
- #!/usr/bin/env node
2
- import { Command } from 'commander';
3
- import { $ } from 'zx';
4
- import path from 'path';
5
- import { validateChangesets } from './validate.js';
6
- import fs from 'fs';
7
- import OpenAI from 'openai';
8
- import { zodResponseFormat } from 'openai/helpers/zod';
9
- import z from 'zod';
10
- import dotenv from 'dotenv';
11
- dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
12
- import { exec } from 'child_process';
13
-
14
- const program = new Command();
15
-
16
- const args = process.argv;
17
-
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
-
31
- function run(command) {
32
- return new Promise((resolve, reject) => {
33
- exec(command, { shell: true }, (error, stdout, stderr) => {
34
- if (error) {
35
- reject(error);
36
- } else {
37
- resolve({ stdout, stderr });
38
- }
39
- });
40
- });
41
- }
42
-
43
- async function fileExists(filePath) {
44
- try {
45
- await fs.promises.access(filePath);
46
- return true;
47
- } catch {
48
- return false;
49
- }
50
- }
51
-
52
- async function getMainPackage() {
53
- const mainModulePath = process.cwd();
54
- if (mainModulePath) {
55
- const packageJsonPath = path.join(mainModulePath, 'package.json');
56
- if (await fileExists(packageJsonPath)) {
57
- const fileContent = await fs.promises.readFile(packageJsonPath, 'utf-8');
58
- const packageJson = JSON.parse(fileContent);
59
- return packageJson;
60
- }
61
- }
62
- throw new Error('Main package.json not found');
63
- }
64
-
65
- // Helper function to set Git info
66
- async function setGitInfo() {
67
- await $`git config --global user.email "gitops@docupace.com"`;
68
- await $`git config --global user.name "Gitops"`;
69
- await $`git remote set-url origin https://${process.env.THIS_REP_TOKEN}@bitbucket.org/${process.env.BITBUCKET_REPO_FULL_NAME}.git`;
70
- }
71
-
72
- const changeSetPackage = `{
73
- "name": "changeset-package",
74
- "version": "1.0.0",
75
- "description": "",
76
- "scripts": {
77
- },
78
- "type": "module",
79
- "keywords": [],
80
- "author": "",
81
- "license": "ISC",
82
- "dependencies": {},
83
- "devDependencies": {
84
- "@changesets/cli": "^2.27.10"
85
- }
86
- }
87
- `;
88
-
89
- async function versionCommand() {
90
- console.log('📦 Running Changeset versioning...');
91
- await setGitInfo();
92
- await $`mv package.json package.json.bak`;
93
- await $`mv pnpm-lock.yaml pnpm-lock.yaml.bak`;
94
- await fs.promises.writeFile('package.json', changeSetPackage);
95
- await $`pnpm install`;
96
- await $`rm package.json pnpm-lock.yaml`;
97
- await $`mv package.json.bak package.json`;
98
- await $`mv pnpm-lock.yaml.bak pnpm-lock.yaml`;
99
- await $`pnpm changeset version`;
100
- console.log('✅ Changeset versioning complete.');
101
- }
102
-
103
- async function commitTagCommand() {
104
- console.log('📌 Checking for updates to commit...');
105
-
106
- // Check if there are changes to commit
107
- const status = (await $`git status --porcelain`).stdout.trim();
108
- if (!status) {
109
- console.log('✅ No changes to commit. Exiting.');
110
- return;
111
- }
112
-
113
- console.log('📌 Committing and tagging the new version...');
114
- await setGitInfo();
115
- await $`git add .`;
116
- const newVersion = (
117
- await $`node -p "require('./package.json').version"`
118
- ).stdout.trim();
119
- await $`git commit -m "Version bump to ${newVersion} and changelog"`;
120
- await $`git push origin`;
121
- await $`git tag v${newVersion}`;
122
- await $`git push origin --tags`;
123
- console.log(`✅ Version ${newVersion} tagged and pushed.`);
124
- }
125
-
126
- // Command: validate
127
- program
128
- .command('validate <path>')
129
- .description('Validate changesets for the provided PR')
130
- .action(async (path) => {
131
- if (!process.env.BITBUCKET_PR_ID) {
132
- return;
133
- }
134
- console.log('🔍 Validating changesets...');
135
- try {
136
- await validateChangesets(path);
137
- console.log('✅ Changeset validation passed.');
138
- } catch (error) {
139
- console.error(
140
- '❌ 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',
141
- );
142
- process.exit(1);
143
- }
144
- });
145
- // Command: version
146
- program
147
- .command('version')
148
- .description('Run Changeset versioning')
149
- .action(async () => {
150
- await versionCommand();
151
- });
152
-
153
- // Command: commit-and-tag
154
- program
155
- .command('commit-tag')
156
- .description('Commit and tag the new version')
157
- .action(async () => {
158
- await commitTagCommand();
159
- });
160
-
161
- // Command: all
162
- program
163
- .command('version-commit-tag')
164
- .description('Run versioning and commit-and-tag in sequence')
165
- .action(async () => {
166
- console.log('📦 Running all steps...');
167
- await versionCommand();
168
- await commitTagCommand();
169
- });
170
-
171
- program
172
- .name('create-changeset')
173
- .description(
174
- 'Creates a changeset based on the current branch and Jira ticket information',
175
- )
176
- .action(async () => {
177
- const mainPackage = await getMainPackage();
178
- const componentName = mainPackage.name;
179
-
180
- try {
181
- // Step 1: Get the current branch name
182
- const { stdout: branchStdout } = await run(`git branch --show-current`);
183
- const branchName = branchStdout.trim();
184
- console.log(`Current branch: ${branchName}`);
185
-
186
- // Step 2: Extract Jira ticket number (e.g., matching JIRA-1234 pattern)
187
- const jiraTicketMatch = branchName.match(/([A-Z]+-\d+)/);
188
- if (!jiraTicketMatch) {
189
- throw new Error('No Jira ticket found in the branch name.');
190
- }
191
- const jiraTicketId = jiraTicketMatch[0];
192
-
193
- // Step 3: Fetch Jira ticket information
194
- const jiraBaseUrl = 'https://docupacellc.atlassian.net';
195
- const jiraEmail = process.env.JIRA_API_EMAIL;
196
- const jiraApiKey = process.env.JIRA_API_KEY;
197
- const jiraFullApiKey = `${jiraEmail}:${jiraApiKey}`;
198
- const jiraUrl = `${jiraBaseUrl}/rest/api/2/issue/${jiraTicketId}`;
199
- const jiraResponse = await fetch(jiraUrl, {
200
- headers: {
201
- Authorization: `Basic ${Buffer.from(jiraFullApiKey).toString('base64')}`,
202
- 'Content-Type': 'application/json',
203
- },
204
- });
205
-
206
- if (!jiraResponse.ok) {
207
- throw new Error(
208
- `Failed to fetch Jira ticket. Status: ${jiraResponse.status}`,
209
- );
210
- }
211
- const jiraTicketData = await jiraResponse.json();
212
-
213
- if (jiraTicketData.fields.customfield_10107?.value !== 'Product') {
214
- throw new Error('Issue Type of Work must be Product');
215
- }
216
-
217
- const jiraSummary = jiraTicketData.fields.summary;
218
-
219
- console.log(
220
- `Generating release notes for ${jiraTicketId} - ${jiraSummary}`,
221
- );
222
-
223
- // Step 4: Use OpenAI to generate release notes
224
- const openaiClient = new OpenAI({
225
- apiKey: process.env['OPENAI_API_KEY'],
226
- });
227
-
228
- const ChangeRequestSchema = z.object({
229
- change_type: z.enum(['patch', 'minor']),
230
- summary: z.string(),
231
- jira_ticket_id: z.string(),
232
- });
233
-
234
- const openAiResponse = await openaiClient.chat.completions.create({
235
- model: 'gpt-4o-mini',
236
- messages: [
237
- {
238
- role: 'system',
239
- 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`,
240
- },
241
- {
242
- role: 'user',
243
- content: JSON.stringify(jiraTicketData),
244
- },
245
- ],
246
- response_format: zodResponseFormat(
247
- ChangeRequestSchema,
248
- 'changeset_schema',
249
- ),
250
- temperature: 0,
251
- });
252
-
253
- const assistantResponse = openAiResponse.choices[0].message.content;
254
- const parsedResponse = JSON.parse(assistantResponse);
255
-
256
- const { change_type, summary } = parsedResponse;
257
- console.log(`Change type: ${change_type}`);
258
- console.log(`Release note: ${summary}`);
259
-
260
- // Step 5: Create a changeset .md file
261
- const changesetContent = `---
262
- "${componentName}": ${change_type}
263
- ---
264
-
265
- ${summary} [${jiraTicketId}]
266
- `;
267
- const changesetFile = `./.changeset/${jiraTicketId}.md`;
268
-
269
- await createChangesetDirectory();
270
- await fs.promises.writeFile(changesetFile, changesetContent);
271
- console.log(`Created changeset file at ${changesetFile}`);
272
-
273
- console.log('Done!');
274
- } catch (err) {
275
- console.error(`Error: ${err.message}`);
276
- process.exit(1);
277
- }
278
- });
279
-
280
- // Parse arguments
281
- program.parse(args);
1
+ #!/usr/bin/env node
2
+ import { Command } from 'commander';
3
+ import { $ } from 'zx';
4
+ import path from 'path';
5
+ import { validateChangesets } from './validate.js';
6
+ import fs from 'fs';
7
+ import OpenAI from 'openai';
8
+ import { zodResponseFormat } from 'openai/helpers/zod';
9
+ import z from 'zod';
10
+ import dotenv from 'dotenv';
11
+ import { makeJiraRequest, updateComponentVersion } from '../next/jira.js';
12
+ dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
13
+
14
+ const program = new Command();
15
+
16
+ const args = process.argv;
17
+
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
+ }
41
+
42
+ async function fileExists(filePath) {
43
+ try {
44
+ await fs.promises.access(filePath);
45
+ return true;
46
+ } catch {
47
+ return false;
48
+ }
49
+ }
50
+
51
+ async function getMainPackage() {
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;
59
+ }
60
+ }
61
+ throw new Error('Main package.json not found');
62
+ }
63
+
64
+ // Helper function to set Git info
65
+ async function setGitInfo() {
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`;
69
+ }
70
+
71
+ const changeSetPackage = `{
72
+ "name": "changeset-package",
73
+ "version": "1.0.0",
74
+ "description": "",
75
+ "scripts": {
76
+ },
77
+ "type": "module",
78
+ "keywords": [],
79
+ "author": "",
80
+ "license": "ISC",
81
+ "dependencies": {},
82
+ "devDependencies": {
83
+ "@changesets/cli": "^2.27.10"
84
+ }
85
+ }
86
+ `;
87
+
88
+ async function versionCommand() {
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
+ await $`pnpm changeset version`;
99
+
100
+ // Read the updated package.json to get the new version and package name
101
+ const packageJson = JSON.parse(
102
+ await fs.promises.readFile('package.json', 'utf-8'),
103
+ );
104
+ const version = packageJson.version;
105
+ const packageName = packageJson.name;
106
+
107
+ // Get the last commit message and extract Jira ticket
108
+ const lastCommit = (await $`git log -1 --pretty=%B`).stdout.trim();
109
+ console.log(`Last commit '${lastCommit}' being processed to get Jira ticket`);
110
+
111
+ const jiraTicketMatch = lastCommit.match(/([A-Z]+-\d+)/);
112
+ const jiraTicketId = jiraTicketMatch ? jiraTicketMatch[0] : null;
113
+
114
+ // If we have all the necessary data, update the component version in Jira
115
+ if (jiraTicketId && version && packageName) {
116
+ try {
117
+ await updateComponentVersion(jiraTicketId, packageName, version);
118
+ } catch (error) {
119
+ console.error(
120
+ `Failed to update Jira component version: ${error.message}`,
121
+ );
122
+ }
123
+ }
124
+
125
+ console.log('✅ Changeset versioning complete.');
126
+ }
127
+
128
+ async function commitTagCommand() {
129
+ console.log('📌 Checking for updates to commit...');
130
+
131
+ // Check if there are changes to commit
132
+ const status = (await $`git status --porcelain`).stdout.trim();
133
+ if (!status) {
134
+ console.log('✅ No changes to commit. Exiting.');
135
+ return;
136
+ }
137
+
138
+ console.log('📌 Committing and tagging the new version...');
139
+ await setGitInfo();
140
+ await $`git add .`;
141
+ const newVersion = (
142
+ await $`node -p "require('./package.json').version"`
143
+ ).stdout.trim();
144
+ await $`git commit -m "Version bump to ${newVersion} and changelog"`;
145
+ await $`git push origin`;
146
+ await $`git tag v${newVersion}`;
147
+ await $`git push origin --tags`;
148
+ console.log(`✅ Version ${newVersion} tagged and pushed.`);
149
+ }
150
+
151
+ // Command: validate
152
+ program
153
+ .command('validate <path>')
154
+ .description('Validate changesets for the provided PR')
155
+ .action(async (path) => {
156
+ if (!process.env.BITBUCKET_PR_ID) {
157
+ return;
158
+ }
159
+ console.log('🔍 Validating changesets...');
160
+ try {
161
+ await validateChangesets(path);
162
+ console.log('✅ Changeset validation passed.');
163
+ } catch (error) {
164
+ console.error(
165
+ '❌ 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',
166
+ );
167
+ process.exit(1);
168
+ }
169
+ });
170
+ // Command: version
171
+ program
172
+ .command('version')
173
+ .description('Run Changeset versioning')
174
+ .action(async () => {
175
+ await versionCommand();
176
+ });
177
+
178
+ // Command: commit-and-tag
179
+ program
180
+ .command('commit-tag')
181
+ .description('Commit and tag the new version')
182
+ .action(async () => {
183
+ await commitTagCommand();
184
+ });
185
+
186
+ // Command: all
187
+ program
188
+ .command('version-commit-tag')
189
+ .description('Run versioning and commit-and-tag in sequence')
190
+ .action(async () => {
191
+ console.log('📦 Running all steps...');
192
+ await versionCommand();
193
+ await commitTagCommand();
194
+ });
195
+
196
+ program
197
+ .name('create-changeset')
198
+ .description(
199
+ 'Creates a changeset based on the current branch and Jira ticket information',
200
+ )
201
+ .action(async () => {
202
+ const mainPackage = await getMainPackage();
203
+ const componentName = mainPackage.name;
204
+
205
+ try {
206
+ // Step 1: Get the current branch name
207
+ const branchName = (await $`git branch --show-current`).stdout.trim();
208
+ console.log(`Current branch: ${branchName}`);
209
+
210
+ // Step 2: Extract Jira ticket number (e.g., matching JIRA-1234 pattern)
211
+ const jiraTicketMatch = branchName.match(/([A-Z]+-\d+)/);
212
+ if (!jiraTicketMatch) {
213
+ throw new Error('No Jira ticket found in the branch name.');
214
+ }
215
+ const jiraTicketId = jiraTicketMatch[0];
216
+
217
+ // Step 3: Fetch Jira ticket information
218
+ const jiraTicketData = await makeJiraRequest(
219
+ `/rest/api/2/issue/${jiraTicketId}`,
220
+ );
221
+
222
+ if (jiraTicketData.fields.customfield_10107?.value !== 'Product') {
223
+ throw new Error('Issue Type of Work must be Product');
224
+ }
225
+
226
+ const jiraSummary = jiraTicketData.fields.summary;
227
+
228
+ console.log(
229
+ `Generating release notes for ${jiraTicketId} - ${jiraSummary}`,
230
+ );
231
+
232
+ const openaiClient = new OpenAI({
233
+ apiKey: process.env['OPENAI_API_KEY'],
234
+ });
235
+
236
+ const ChangeRequestSchema = z.object({
237
+ change_type: z.enum(['patch', 'minor']),
238
+ summary: z.string(),
239
+ jira_ticket_id: z.string(),
240
+ });
241
+
242
+ const openAiResponse = await openaiClient.chat.completions.create({
243
+ model: 'gpt-4o-mini',
244
+ messages: [
245
+ {
246
+ role: 'system',
247
+ 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`,
248
+ },
249
+ {
250
+ role: 'user',
251
+ content: JSON.stringify(jiraTicketData),
252
+ },
253
+ ],
254
+ response_format: zodResponseFormat(
255
+ ChangeRequestSchema,
256
+ 'changeset_schema',
257
+ ),
258
+ temperature: 0,
259
+ });
260
+
261
+ const assistantResponse = openAiResponse.choices[0].message.content;
262
+ const parsedResponse = JSON.parse(assistantResponse);
263
+
264
+ const { change_type, summary } = parsedResponse;
265
+ console.log(`Change type: ${change_type}`);
266
+ console.log(`Release note: ${summary}`);
267
+
268
+ // Step 5: Create a changeset .md file
269
+ const changesetContent = `---
270
+ "${componentName}": ${change_type}
271
+ ---
272
+
273
+ ${summary} [${jiraTicketId}]
274
+ `;
275
+ const changesetFile = `./.changeset/${jiraTicketId}.md`;
276
+
277
+ await createChangesetDirectory();
278
+ await fs.promises.writeFile(changesetFile, changesetContent);
279
+ console.log(`Created changeset file at ${changesetFile}`);
280
+
281
+ console.log('Done!');
282
+ } catch (err) {
283
+ console.error(`Error: ${err.message}`);
284
+ process.exit(1);
285
+ }
286
+ });
287
+
288
+ // Parse arguments
289
+ program.parse(args);