@docupace/pipeline 1.0.63 → 1.0.64-alpha.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.
- package/package.json +3 -3
- package/src/changeset/changelog-wiki.js +313 -0
- package/src/changeset/cli.js +46 -0
- package/src/changeset/create.js +15 -5
- package/src/changeset/package-util.js +2 -1
- package/src/lib/merge-driver.js +204 -0
- package/src/merge/cli-merge-all.js +472 -0
- package/src/merge/cli-merge.js +492 -0
- package/src/merge/cli-resolve.js +395 -0
- package/src/merge/cli.js +38 -0
- package/src/merge/merge-changelog.js +87 -0
- package/src/merge/merge-package.js +106 -0
- package/src/merge/merge-types.js +82 -0
- package/src/merge/pr.js +85 -0
package/package.json
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@docupace/pipeline",
|
|
3
|
-
"version": "1.0.
|
|
4
|
-
"description": "",
|
|
3
|
+
"version": "1.0.64-alpha.0",
|
|
5
4
|
"main": "index.js",
|
|
6
5
|
"type": "module",
|
|
7
6
|
"bin": {
|
|
8
7
|
"dp-changeset-cli": "src/changeset/cli.js",
|
|
9
8
|
"dp-next-cli": "src/next/cli.js",
|
|
10
|
-
"dp-auth0-cli": "src/auth0/cli.js"
|
|
9
|
+
"dp-auth0-cli": "src/auth0/cli.js",
|
|
10
|
+
"dp-merge-cli": "src/merge/cli.js"
|
|
11
11
|
},
|
|
12
12
|
"keywords": [
|
|
13
13
|
"bash"
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
// npm i axios
|
|
2
|
+
import axios from 'axios';
|
|
3
|
+
import { readFileSync } from 'fs';
|
|
4
|
+
import { getPackageNames } from './package-util.js';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { toShortVersion } from './version.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Required env:
|
|
10
|
+
* CONFLUENCE_BASE_URL e.g. "https://docupacellc.atlassian.net/wiki"
|
|
11
|
+
* CONFLUENCE_EMAIL e.g. "you@docupace.com"
|
|
12
|
+
* CONFLUENCE_API_TOKEN Atlassian API token
|
|
13
|
+
*/
|
|
14
|
+
const BASE_URL = process.env.CONFLUENCE_BASE_URL;
|
|
15
|
+
const EMAIL = process.env.CONFLUENCE_EMAIL;
|
|
16
|
+
const API_TOKEN = process.env.CONFLUENCE_API_TOKEN;
|
|
17
|
+
|
|
18
|
+
const getHttpService = () =>
|
|
19
|
+
axios.create({
|
|
20
|
+
baseURL: BASE_URL.replace(/\/+$/, ''),
|
|
21
|
+
auth: { username: EMAIL, password: API_TOKEN },
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
/** ---------- ADF builder: Markdown macro ---------- */
|
|
25
|
+
function adfMarkdown(markdown) {
|
|
26
|
+
return {
|
|
27
|
+
type: 'doc',
|
|
28
|
+
version: 1,
|
|
29
|
+
content: [
|
|
30
|
+
{
|
|
31
|
+
type: 'extension',
|
|
32
|
+
attrs: {
|
|
33
|
+
layout: 'default',
|
|
34
|
+
extensionType: 'com.atlassian.confluence.macro.core',
|
|
35
|
+
extensionKey: 'markdown',
|
|
36
|
+
parameters: {
|
|
37
|
+
macroParams: {
|
|
38
|
+
sourceType: { value: 'MacroBody' },
|
|
39
|
+
darkmode: { value: 'auto' },
|
|
40
|
+
syntax: { value: 'Markdown' },
|
|
41
|
+
attachmentPageId: { value: '' },
|
|
42
|
+
attachmentId: { value: '' },
|
|
43
|
+
url: { value: '' },
|
|
44
|
+
__bodyContent: { value: markdown },
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
},
|
|
48
|
+
},
|
|
49
|
+
],
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** ---------- API helpers (v2) ---------- */
|
|
54
|
+
|
|
55
|
+
// get a page (v2) by id
|
|
56
|
+
async function getPage(pageId) {
|
|
57
|
+
const { data } = await getHttpService().get(`/api/v2/pages/${pageId}`);
|
|
58
|
+
return data;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
// list child pages (paginated) and return *all* children
|
|
62
|
+
async function listChildPages(parentId) {
|
|
63
|
+
const all = [];
|
|
64
|
+
let next = `/api/v2/pages/${parentId}/children?limit=200`;
|
|
65
|
+
|
|
66
|
+
while (next) {
|
|
67
|
+
const { data } = await getHttpService().get(next);
|
|
68
|
+
if (Array.isArray(data.results)) all.push(...data.results);
|
|
69
|
+
next = data?._links?.next || null;
|
|
70
|
+
}
|
|
71
|
+
return all;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// find a direct child page by exact title
|
|
75
|
+
async function findChildByTitle(parentId, title) {
|
|
76
|
+
const kids = await listChildPages(parentId);
|
|
77
|
+
return kids.find((p) => (p.title || '').trim() === title.trim()) || null;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// create a child page under a parent
|
|
81
|
+
async function createChildPage({
|
|
82
|
+
parentId,
|
|
83
|
+
spaceId,
|
|
84
|
+
title,
|
|
85
|
+
adf,
|
|
86
|
+
message = 'Create via API',
|
|
87
|
+
}) {
|
|
88
|
+
const payload = {
|
|
89
|
+
status: 'current',
|
|
90
|
+
title,
|
|
91
|
+
spaceId,
|
|
92
|
+
parentId,
|
|
93
|
+
body: {
|
|
94
|
+
atlas_doc_format: {
|
|
95
|
+
value: adf,
|
|
96
|
+
representation: 'atlas_doc_format',
|
|
97
|
+
},
|
|
98
|
+
},
|
|
99
|
+
version: { number: 1, message, minorEdit: false },
|
|
100
|
+
};
|
|
101
|
+
const { data } = await getHttpService().post(`/api/v2/pages`, payload);
|
|
102
|
+
return data;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// update an existing page (replace body + optionally title)
|
|
106
|
+
async function updatePage({
|
|
107
|
+
page,
|
|
108
|
+
title = page.title,
|
|
109
|
+
adf,
|
|
110
|
+
message = 'Update via API',
|
|
111
|
+
}) {
|
|
112
|
+
if (!page.version) {
|
|
113
|
+
page = await getPage(page.id);
|
|
114
|
+
}
|
|
115
|
+
const payload = {
|
|
116
|
+
id: page.id,
|
|
117
|
+
status: 'current',
|
|
118
|
+
title,
|
|
119
|
+
spaceId: page.spaceId,
|
|
120
|
+
body: {
|
|
121
|
+
atlas_doc_format: {
|
|
122
|
+
value: adf,
|
|
123
|
+
representation: 'atlas_doc_format',
|
|
124
|
+
},
|
|
125
|
+
},
|
|
126
|
+
version: {
|
|
127
|
+
number: page.version.number + 1,
|
|
128
|
+
message,
|
|
129
|
+
minorEdit: false,
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
const { data } = await getHttpService().put(
|
|
133
|
+
`/api/v2/pages/${page.id}`,
|
|
134
|
+
payload,
|
|
135
|
+
);
|
|
136
|
+
return data;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
const childPagesAdf = {
|
|
140
|
+
type: 'doc',
|
|
141
|
+
version: 1,
|
|
142
|
+
content: [
|
|
143
|
+
{
|
|
144
|
+
type: 'extension',
|
|
145
|
+
attrs: {
|
|
146
|
+
extensionType: 'com.atlassian.confluence.macro.core',
|
|
147
|
+
extensionKey: 'children',
|
|
148
|
+
layout: 'default',
|
|
149
|
+
parameters: {
|
|
150
|
+
macroParams: {
|
|
151
|
+
allChildren: { value: 'true' },
|
|
152
|
+
},
|
|
153
|
+
macroMetadata: {
|
|
154
|
+
macroId: { value: '9ea4beb6-ac0a-42d7-baf1-e8e6eca01bfd' },
|
|
155
|
+
schemaVersion: { value: '2' },
|
|
156
|
+
title: { value: 'Child pages' },
|
|
157
|
+
},
|
|
158
|
+
},
|
|
159
|
+
localId: '4890f00c-c519-4947-a60c-0c3b7e1c7b72',
|
|
160
|
+
},
|
|
161
|
+
},
|
|
162
|
+
],
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
/** ---------- Main upsert workflow ---------- */
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Upsert release notes at: Versions(parent) -> Version(title) -> Component(title)
|
|
169
|
+
*
|
|
170
|
+
* @param {object} args
|
|
171
|
+
* @param {string} args.versionsParentId - Page ID of the "Versions" page
|
|
172
|
+
* @param {string} args.versionTitle - e.g. "Version 1"
|
|
173
|
+
* @param {string} args.componentTitle - e.g. "Component A"
|
|
174
|
+
* @param {string} args.markdown - Release notes markdown for the component page
|
|
175
|
+
*
|
|
176
|
+
* @returns {Promise<{versionPage:any, componentPage:any}>}
|
|
177
|
+
*/
|
|
178
|
+
export async function upsertReleaseNotes({
|
|
179
|
+
versionsParentId,
|
|
180
|
+
version,
|
|
181
|
+
component,
|
|
182
|
+
markdown,
|
|
183
|
+
group,
|
|
184
|
+
}) {
|
|
185
|
+
if (!BASE_URL || !EMAIL || !API_TOKEN) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
'Missing required env: CONFLUENCE_BASE_URL, CONFLUENCE_EMAIL, CONFLUENCE_API_TOKEN',
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (!versionsParentId || !version || !component) {
|
|
192
|
+
throw new Error(
|
|
193
|
+
'versionsParentId, versionTitle, and componentTitle are required',
|
|
194
|
+
);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (!markdown || markdown.trim() === '') {
|
|
198
|
+
throw new Error('markdown content is required and cannot be empty');
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// 1) fetch the parent to get spaceId
|
|
202
|
+
const parent = await getPage(versionsParentId);
|
|
203
|
+
const spaceId = parent.spaceId;
|
|
204
|
+
|
|
205
|
+
const versionTitle = `Docupace ${group} - Version ${version}`;
|
|
206
|
+
// 2) ensure Version page under parent
|
|
207
|
+
let versionPage = await findChildByTitle(parent.id, versionTitle);
|
|
208
|
+
if (!versionPage) {
|
|
209
|
+
versionPage = await createChildPage({
|
|
210
|
+
parentId: parent.id,
|
|
211
|
+
spaceId,
|
|
212
|
+
title: versionTitle,
|
|
213
|
+
adf: JSON.stringify(childPagesAdf),
|
|
214
|
+
message: `Create version page ${versionTitle}`,
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
const componentTitle = `${versionTitle} - ${component} Changelog`;
|
|
219
|
+
|
|
220
|
+
// 3) ensure Component page under Version
|
|
221
|
+
let componentPage = await findChildByTitle(versionPage.id, componentTitle);
|
|
222
|
+
const adf = adfMarkdown(markdown);
|
|
223
|
+
|
|
224
|
+
if (!componentPage) {
|
|
225
|
+
componentPage = await createChildPage({
|
|
226
|
+
parentId: versionPage.id,
|
|
227
|
+
spaceId,
|
|
228
|
+
title: componentTitle,
|
|
229
|
+
adf: JSON.stringify(adf),
|
|
230
|
+
message: `Create component page ${componentTitle}`,
|
|
231
|
+
});
|
|
232
|
+
} else {
|
|
233
|
+
// update existing component page with new markdown
|
|
234
|
+
componentPage = await updatePage({
|
|
235
|
+
page: componentPage,
|
|
236
|
+
title: componentTitle,
|
|
237
|
+
adf: JSON.stringify(adf),
|
|
238
|
+
message: `Update component page ${componentTitle}`,
|
|
239
|
+
});
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
return { versionPage, componentPage };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Upsert release notes from a markdown file
|
|
247
|
+
*
|
|
248
|
+
* @param {object} args
|
|
249
|
+
* @param {string} args.versionTitle - e.g. "Version 1"
|
|
250
|
+
* @param {string} args.componentTitle - e.g. "Component A"
|
|
251
|
+
* @param {string} args.markdownFile - Path to markdown file
|
|
252
|
+
*
|
|
253
|
+
* @returns {Promise<{versionPage:any, componentPage:any}>}
|
|
254
|
+
*/
|
|
255
|
+
export async function upsertReleaseNotesFromFile({
|
|
256
|
+
version,
|
|
257
|
+
component,
|
|
258
|
+
markdownFile,
|
|
259
|
+
group,
|
|
260
|
+
}) {
|
|
261
|
+
if (!group) {
|
|
262
|
+
throw new Error('changelog.group must be specified in package.json');
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
const versionsParentId =
|
|
266
|
+
process.env[`CONFLUENCE_${group.toUpperCase()}_PARENT_ID`];
|
|
267
|
+
|
|
268
|
+
if (!versionsParentId) {
|
|
269
|
+
throw new Error(
|
|
270
|
+
`CONFLUENCE_${group.toUpperCase()}_PARENT_ID environment variable is required`,
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
if (!markdownFile) {
|
|
275
|
+
throw new Error('markdownFile is required');
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// Read markdown content from file
|
|
279
|
+
const markdown = readFileSync(markdownFile, 'utf8');
|
|
280
|
+
|
|
281
|
+
return upsertReleaseNotes({
|
|
282
|
+
versionsParentId,
|
|
283
|
+
version,
|
|
284
|
+
component,
|
|
285
|
+
markdown,
|
|
286
|
+
group,
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
export async function updateWikiWithVersion(releases) {
|
|
291
|
+
const packageNames = getPackageNames();
|
|
292
|
+
console.log(releases);
|
|
293
|
+
|
|
294
|
+
const promises = packageNames
|
|
295
|
+
.filter(
|
|
296
|
+
(packageName) =>
|
|
297
|
+
releases.find((release) => release.name == packageName.name) &&
|
|
298
|
+
packageName.content?.changelog?.component,
|
|
299
|
+
)
|
|
300
|
+
.map(async (packageName) => {
|
|
301
|
+
const release = releases.find(
|
|
302
|
+
(release) => release.name == packageName.name,
|
|
303
|
+
);
|
|
304
|
+
await upsertReleaseNotesFromFile({
|
|
305
|
+
version: toShortVersion(release.newVersion),
|
|
306
|
+
component: packageName.content.changelog?.component,
|
|
307
|
+
markdownFile: path.join(packageName.path, 'CHANGELOG.md'),
|
|
308
|
+
group: packageName.content.changelog?.group,
|
|
309
|
+
});
|
|
310
|
+
});
|
|
311
|
+
|
|
312
|
+
await Promise.all(promises);
|
|
313
|
+
}
|
package/src/changeset/cli.js
CHANGED
|
@@ -10,6 +10,10 @@ import {
|
|
|
10
10
|
versionCommand,
|
|
11
11
|
} from './version.js';
|
|
12
12
|
import { createChangeset } from './create.js';
|
|
13
|
+
import {
|
|
14
|
+
updateWikiWithVersion,
|
|
15
|
+
upsertReleaseNotesFromFile,
|
|
16
|
+
} from './changelog-wiki.js';
|
|
13
17
|
|
|
14
18
|
dotenv.config({ path: ['.env.pipeline.local', 'config/.env.pipeline.local'] });
|
|
15
19
|
|
|
@@ -93,6 +97,11 @@ async function commitTag() {
|
|
|
93
97
|
await $`node -p "require('./package.json').version"`
|
|
94
98
|
).stdout.trim();
|
|
95
99
|
|
|
100
|
+
if (process.env.IS_DEV) {
|
|
101
|
+
console.log(`Simulate commit of version ${newVersion}`);
|
|
102
|
+
return;
|
|
103
|
+
}
|
|
104
|
+
|
|
96
105
|
const defaultBranch = process.env.BITBUCKET_BRANCH;
|
|
97
106
|
|
|
98
107
|
await $`git commit -m "Version bump to ${newVersion} and changelog"`;
|
|
@@ -136,6 +145,7 @@ program
|
|
|
136
145
|
console.log('📦 Running all steps...');
|
|
137
146
|
const releases = await versionCommand();
|
|
138
147
|
await updateJiraWithVersion(releases);
|
|
148
|
+
await updateWikiWithVersion(releases);
|
|
139
149
|
await commitTagCommand(releases);
|
|
140
150
|
});
|
|
141
151
|
|
|
@@ -187,5 +197,41 @@ program
|
|
|
187
197
|
await createChangeset();
|
|
188
198
|
});
|
|
189
199
|
|
|
200
|
+
program
|
|
201
|
+
.command('upload-wiki')
|
|
202
|
+
.description('Upload release notes from markdown file to Confluence')
|
|
203
|
+
.requiredOption(
|
|
204
|
+
'-v, --version <version>',
|
|
205
|
+
'Version title (e.g., "Version 1.0")',
|
|
206
|
+
)
|
|
207
|
+
.requiredOption(
|
|
208
|
+
'-c, --component <component>',
|
|
209
|
+
'Component title (e.g., "Component A")',
|
|
210
|
+
)
|
|
211
|
+
.requiredOption('-f, --file <file>', 'Path to markdown file')
|
|
212
|
+
.requiredOption('-g, --group <group>', 'Group of release notes')
|
|
213
|
+
|
|
214
|
+
.action(async (options) => {
|
|
215
|
+
try {
|
|
216
|
+
console.log('📤 Uploading release notes to Confluence...');
|
|
217
|
+
const { versionPage, componentPage } = await upsertReleaseNotesFromFile({
|
|
218
|
+
version: options.version,
|
|
219
|
+
component: options.component,
|
|
220
|
+
markdownFile: options.file,
|
|
221
|
+
group: options.group,
|
|
222
|
+
});
|
|
223
|
+
|
|
224
|
+
console.log('✅ Successfully uploaded to Confluence');
|
|
225
|
+
console.log('Version page:', versionPage._links?.webui || versionPage.id);
|
|
226
|
+
console.log(
|
|
227
|
+
'Component page:',
|
|
228
|
+
componentPage._links?.webui || componentPage.id,
|
|
229
|
+
);
|
|
230
|
+
} catch (error) {
|
|
231
|
+
console.error('❌ Error uploading to Confluence:', error.message);
|
|
232
|
+
process.exit(1);
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
|
|
190
236
|
// Parse arguments
|
|
191
237
|
program.parse(args);
|
package/src/changeset/create.js
CHANGED
|
@@ -110,8 +110,17 @@ async function generateReleaseNotes(jiraTicketData) {
|
|
|
110
110
|
/**
|
|
111
111
|
* Writes the changeset file
|
|
112
112
|
*/
|
|
113
|
-
async function
|
|
114
|
-
|
|
113
|
+
async function writeJiraChangesetFile(
|
|
114
|
+
packages,
|
|
115
|
+
jiraTicketId,
|
|
116
|
+
changeType,
|
|
117
|
+
summary,
|
|
118
|
+
) {
|
|
119
|
+
const text = `${summary} [${jiraTicketId}]`;
|
|
120
|
+
await writeChangesetFile(packages, jiraTicketId, changeType, text);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export async function writeChangesetFile(packages, filename, changeType, text) {
|
|
115
124
|
const packageEntries = packages
|
|
116
125
|
.map((pkg) => `'${pkg.name}': ${changeType}`)
|
|
117
126
|
.join('\n');
|
|
@@ -120,9 +129,10 @@ async function writeChangesetFile(packages, jiraTicketId, changeType, summary) {
|
|
|
120
129
|
${packageEntries}
|
|
121
130
|
---
|
|
122
131
|
|
|
123
|
-
${
|
|
132
|
+
${text}
|
|
124
133
|
`;
|
|
125
|
-
|
|
134
|
+
|
|
135
|
+
const changesetFile = `./.changeset/${filename}.md`;
|
|
126
136
|
|
|
127
137
|
await createChangesetDirectory();
|
|
128
138
|
await fs.promises.writeFile(changesetFile, changesetContent);
|
|
@@ -195,7 +205,7 @@ export async function createChangesetForPackage(packages) {
|
|
|
195
205
|
console.log(`Release note: ${summary}`);
|
|
196
206
|
|
|
197
207
|
// Step 5: Create a changeset .md file for all packages
|
|
198
|
-
await
|
|
208
|
+
await writeJiraChangesetFile(packages, jiraTicketId, change_type, summary);
|
|
199
209
|
|
|
200
210
|
console.log('Changeset created successfully!');
|
|
201
211
|
} catch (err) {
|
|
@@ -37,7 +37,7 @@ export function getPackageNames(rootPath = '.') {
|
|
|
37
37
|
fs.readFileSync(rootPackageJson, 'utf8'),
|
|
38
38
|
);
|
|
39
39
|
return packageJson.name
|
|
40
|
-
? [{ name: packageJson.name, path: rootPath }]
|
|
40
|
+
? [{ name: packageJson.name, path: rootPath, content: packageJson }]
|
|
41
41
|
: [];
|
|
42
42
|
} catch (error) {
|
|
43
43
|
console.error('Error reading root package.json:', error);
|
|
@@ -71,6 +71,7 @@ function getPackagesFromDirectory(dirPath) {
|
|
|
71
71
|
packages.push({
|
|
72
72
|
name: packageJson.name,
|
|
73
73
|
path: itemPath,
|
|
74
|
+
content: packageJson,
|
|
74
75
|
});
|
|
75
76
|
}
|
|
76
77
|
} catch (error) {
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
import fs from 'fs';
|
|
4
|
+
import { execSync } from 'child_process';
|
|
5
|
+
import path from 'path';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
|
|
8
|
+
// Get __dirname equivalent in ESM
|
|
9
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
10
|
+
const __dirname = path.dirname(__filename);
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Default merge logic function - can be overridden
|
|
14
|
+
* @param {string} headContent - The content from HEAD (current branch)
|
|
15
|
+
* @param {string} branchContent - The content from the incoming branch
|
|
16
|
+
* @returns {string} - The merged content
|
|
17
|
+
* @throws {Error} - If the conflict cannot be automatically merged
|
|
18
|
+
*/
|
|
19
|
+
export function defaultMergeLogic(headContent, branchContent) {
|
|
20
|
+
// Default implementation - throws error
|
|
21
|
+
// Users should provide their own implementation
|
|
22
|
+
throw new Error(
|
|
23
|
+
'No merge logic provided - please pass a custom merge function',
|
|
24
|
+
);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Main merge driver function
|
|
29
|
+
* @param {string} filePath - Path to the file with conflicts
|
|
30
|
+
* @param {Function} customMergeLogic - Custom merge function (optional)
|
|
31
|
+
* @returns {Promise<{success: boolean, totalConflicts: number, resolvedConflicts: number, hasUnresolvedConflicts: boolean}>}
|
|
32
|
+
*/
|
|
33
|
+
export async function mergeDriver(filePath, customMergeLogic = null) {
|
|
34
|
+
// Use provided merge logic or fall back to default
|
|
35
|
+
const mergeLogic = customMergeLogic || defaultMergeLogic;
|
|
36
|
+
|
|
37
|
+
if (!filePath) {
|
|
38
|
+
throw new Error('File path is required');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Check if file exists
|
|
42
|
+
if (!fs.existsSync(filePath)) {
|
|
43
|
+
throw new Error(`File not found: ${filePath}`);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
console.log(`Processing conflicts in: ${filePath}`);
|
|
47
|
+
|
|
48
|
+
// Read the file content
|
|
49
|
+
let fileContent;
|
|
50
|
+
try {
|
|
51
|
+
fileContent = fs.readFileSync(filePath, 'utf8');
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error(`Error reading file: ${error.message}`);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
// Split content into lines for processing
|
|
57
|
+
const lines = fileContent.split('\n');
|
|
58
|
+
const resultLines = [];
|
|
59
|
+
|
|
60
|
+
// Track merge state
|
|
61
|
+
let hasUnresolvedConflicts = false;
|
|
62
|
+
let totalConflicts = 0;
|
|
63
|
+
let resolvedConflicts = 0;
|
|
64
|
+
|
|
65
|
+
// State variables for parsing
|
|
66
|
+
let inConflict = false;
|
|
67
|
+
let headLines = [];
|
|
68
|
+
let branchLines = [];
|
|
69
|
+
let currentSection = null; // 'head' or 'branch'
|
|
70
|
+
|
|
71
|
+
// Process each line
|
|
72
|
+
for (let i = 0; i < lines.length; i++) {
|
|
73
|
+
const line = lines[i];
|
|
74
|
+
|
|
75
|
+
if (line.startsWith('<<<<<<<')) {
|
|
76
|
+
// Start of conflict marker
|
|
77
|
+
inConflict = true;
|
|
78
|
+
currentSection = 'head';
|
|
79
|
+
headLines = [];
|
|
80
|
+
branchLines = [];
|
|
81
|
+
totalConflicts++;
|
|
82
|
+
} else if (inConflict && line.startsWith('=======')) {
|
|
83
|
+
// Middle of conflict - switch from HEAD to branch
|
|
84
|
+
currentSection = 'branch';
|
|
85
|
+
} else if (inConflict && line.startsWith('>>>>>>>')) {
|
|
86
|
+
// End of conflict marker - attempt to merge
|
|
87
|
+
const headContent = headLines.join('\n');
|
|
88
|
+
const branchContent = branchLines.join('\n');
|
|
89
|
+
|
|
90
|
+
try {
|
|
91
|
+
// Call custom merge logic
|
|
92
|
+
const mergedContent = mergeLogic(headContent, branchContent);
|
|
93
|
+
|
|
94
|
+
// Add merged content to result
|
|
95
|
+
if (mergedContent !== null && mergedContent !== undefined) {
|
|
96
|
+
resultLines.push(mergedContent);
|
|
97
|
+
resolvedConflicts++;
|
|
98
|
+
console.log(`✓ Resolved conflict #${totalConflicts}`);
|
|
99
|
+
}
|
|
100
|
+
} catch (error) {
|
|
101
|
+
// Cannot merge this conflict - keep original conflict markers
|
|
102
|
+
hasUnresolvedConflicts = true;
|
|
103
|
+
|
|
104
|
+
console.log(
|
|
105
|
+
`✗ Could not resolve conflict #${totalConflicts}: ${error.message}`,
|
|
106
|
+
);
|
|
107
|
+
|
|
108
|
+
// Preserve the original conflict
|
|
109
|
+
resultLines.push(`<<<<<<< HEAD`);
|
|
110
|
+
resultLines.push(headContent);
|
|
111
|
+
resultLines.push('=======');
|
|
112
|
+
resultLines.push(branchContent);
|
|
113
|
+
resultLines.push(`>>>>>>> branch`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// Reset conflict state
|
|
117
|
+
inConflict = false;
|
|
118
|
+
currentSection = null;
|
|
119
|
+
headLines = [];
|
|
120
|
+
branchLines = [];
|
|
121
|
+
} else if (inConflict) {
|
|
122
|
+
// Inside conflict - collect lines
|
|
123
|
+
if (currentSection === 'head') {
|
|
124
|
+
headLines.push(line);
|
|
125
|
+
} else if (currentSection === 'branch') {
|
|
126
|
+
branchLines.push(line);
|
|
127
|
+
}
|
|
128
|
+
} else {
|
|
129
|
+
// Normal line outside of conflict
|
|
130
|
+
resultLines.push(line);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Write the result back to the file
|
|
135
|
+
const resultContent = resultLines.join('\n');
|
|
136
|
+
try {
|
|
137
|
+
fs.writeFileSync(filePath, resultContent, 'utf8');
|
|
138
|
+
console.log(`\nFile updated: ${filePath}`);
|
|
139
|
+
} catch (error) {
|
|
140
|
+
throw new Error(`Error writing file: ${error.message}`);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Summary
|
|
144
|
+
console.log('\n--- Merge Summary ---');
|
|
145
|
+
console.log(`Total conflicts found: ${totalConflicts}`);
|
|
146
|
+
console.log(`Conflicts resolved: ${resolvedConflicts}`);
|
|
147
|
+
console.log(`Conflicts remaining: ${totalConflicts - resolvedConflicts}`);
|
|
148
|
+
|
|
149
|
+
// If all conflicts were resolved, stage the file
|
|
150
|
+
if (!hasUnresolvedConflicts && totalConflicts > 0) {
|
|
151
|
+
try {
|
|
152
|
+
execSync(`git add "${filePath}"`, { stdio: 'inherit' });
|
|
153
|
+
console.log(
|
|
154
|
+
`\n✓ All conflicts resolved! File has been staged with 'git add'.`,
|
|
155
|
+
);
|
|
156
|
+
} catch (error) {
|
|
157
|
+
console.error(`\nWarning: Could not stage file: ${error.message}`);
|
|
158
|
+
console.log('You may need to run "git add" manually.');
|
|
159
|
+
}
|
|
160
|
+
} else if (hasUnresolvedConflicts) {
|
|
161
|
+
console.log(`\n⚠ Some conflicts could not be resolved automatically.`);
|
|
162
|
+
console.log('Please review and resolve the remaining conflicts manually.');
|
|
163
|
+
} else if (totalConflicts === 0) {
|
|
164
|
+
console.log('\nNo conflicts found in the file.');
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Return result object for programmatic use
|
|
168
|
+
return {
|
|
169
|
+
success: !hasUnresolvedConflicts,
|
|
170
|
+
totalConflicts,
|
|
171
|
+
resolvedConflicts,
|
|
172
|
+
hasUnresolvedConflicts,
|
|
173
|
+
filePath,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Process multiple files with the same merge logic
|
|
179
|
+
* @param {string[]} filePaths - Array of file paths to process
|
|
180
|
+
* @param {Function} customMergeLogic - Custom merge function
|
|
181
|
+
* @returns {Promise<Array>} - Array of results for each file
|
|
182
|
+
*/
|
|
183
|
+
export async function mergeMultipleFiles(filePaths, customMergeLogic) {
|
|
184
|
+
const results = [];
|
|
185
|
+
|
|
186
|
+
for (const filePath of filePaths) {
|
|
187
|
+
try {
|
|
188
|
+
const result = await mergeDriver(filePath, customMergeLogic);
|
|
189
|
+
results.push(result);
|
|
190
|
+
} catch (error) {
|
|
191
|
+
console.error(`Error processing ${filePath}: ${error.message}`);
|
|
192
|
+
results.push({
|
|
193
|
+
success: false,
|
|
194
|
+
error: error.message,
|
|
195
|
+
filePath,
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
return results;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Default export for convenience
|
|
204
|
+
export default mergeDriver;
|