@eldrforge/git-tools 0.1.3 → 0.1.4
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 +4 -1
- package/.github/dependabot.yml +0 -12
- package/.github/workflows/npm-publish.yml +0 -48
- package/.github/workflows/test.yml +0 -33
- package/CODE-DIFF-SUMMARY.md +0 -93
- package/MIGRATION-VERIFICATION.md +0 -436
- package/eslint.config.mjs +0 -84
- package/src/child.ts +0 -249
- package/src/git.ts +0 -1120
- package/src/index.ts +0 -58
- package/src/logger.ts +0 -81
- package/src/validation.ts +0 -62
- package/tests/child.integration.test.ts +0 -170
- package/tests/child.test.ts +0 -1035
- package/tests/git.test.ts +0 -1931
- package/tests/logger.test.ts +0 -211
- package/tests/setup.ts +0 -17
- package/tests/validation.test.ts +0 -152
- package/tsconfig.json +0 -35
- package/vite.config.ts +0 -78
- package/vitest.config.ts +0 -37
package/src/git.ts
DELETED
|
@@ -1,1120 +0,0 @@
|
|
|
1
|
-
import { getLogger } from './logger';
|
|
2
|
-
import { run, runSecure, validateGitRef } from './child';
|
|
3
|
-
import fs from 'fs/promises';
|
|
4
|
-
import path from 'path';
|
|
5
|
-
import { exec } from 'child_process';
|
|
6
|
-
import util from 'util';
|
|
7
|
-
import * as semver from 'semver';
|
|
8
|
-
import { safeJsonParse, validatePackageJson } from './validation';
|
|
9
|
-
|
|
10
|
-
/**
|
|
11
|
-
* Tests if a git reference exists and is valid (silent version that doesn't log errors)
|
|
12
|
-
*/
|
|
13
|
-
const isValidGitRefSilent = async (ref: string): Promise<boolean> => {
|
|
14
|
-
try {
|
|
15
|
-
// Validate the ref first to prevent injection
|
|
16
|
-
if (!validateGitRef(ref)) {
|
|
17
|
-
return false;
|
|
18
|
-
}
|
|
19
|
-
await runSecure('git', ['rev-parse', '--verify', ref], { stdio: 'ignore' });
|
|
20
|
-
return true;
|
|
21
|
-
} catch {
|
|
22
|
-
return false;
|
|
23
|
-
}
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
/**
|
|
27
|
-
* Tests if a git reference exists and is valid
|
|
28
|
-
*/
|
|
29
|
-
export const isValidGitRef = async (ref: string): Promise<boolean> => {
|
|
30
|
-
const logger = getLogger();
|
|
31
|
-
try {
|
|
32
|
-
// Validate the ref first to prevent injection
|
|
33
|
-
if (!validateGitRef(ref)) {
|
|
34
|
-
logger.debug(`Git reference '${ref}' contains invalid characters`);
|
|
35
|
-
return false;
|
|
36
|
-
}
|
|
37
|
-
await runSecure('git', ['rev-parse', '--verify', ref], { stdio: 'ignore' });
|
|
38
|
-
logger.debug(`Git reference '${ref}' is valid`);
|
|
39
|
-
return true;
|
|
40
|
-
} catch (error) {
|
|
41
|
-
logger.debug(`Git reference '${ref}' is not valid: ${error}`);
|
|
42
|
-
return false;
|
|
43
|
-
}
|
|
44
|
-
};
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Finds the previous release tag based on the current version using semantic versioning.
|
|
48
|
-
* Returns the highest version tag that is less than the current version.
|
|
49
|
-
*
|
|
50
|
-
* @param currentVersion The current version (e.g., "1.2.3", "2.0.0")
|
|
51
|
-
* @param tagPattern The pattern to match tags (e.g., "v*", "working/v*")
|
|
52
|
-
* @returns The previous release tag or null if none found
|
|
53
|
-
*/
|
|
54
|
-
export const findPreviousReleaseTag = async (
|
|
55
|
-
currentVersion: string,
|
|
56
|
-
tagPattern: string = 'v*'
|
|
57
|
-
): Promise<string | null> => {
|
|
58
|
-
const logger = getLogger();
|
|
59
|
-
|
|
60
|
-
try {
|
|
61
|
-
// Parse current version first to validate it
|
|
62
|
-
const currentSemver = semver.parse(currentVersion);
|
|
63
|
-
if (!currentSemver) {
|
|
64
|
-
logger.warn(`❌ Invalid version format: ${currentVersion}`);
|
|
65
|
-
return null;
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
logger.info(`🔍 findPreviousReleaseTag: Looking for tags matching "${tagPattern}" < ${currentVersion}`);
|
|
69
|
-
|
|
70
|
-
// Get all tags - try sorted first, fallback to unsorted
|
|
71
|
-
let tags: string[];
|
|
72
|
-
try {
|
|
73
|
-
logger.info(` Running: git tag -l "${tagPattern}" --sort=-version:refname`);
|
|
74
|
-
const { stdout } = await runSecure('git', ['tag', '-l', tagPattern, '--sort=-version:refname']);
|
|
75
|
-
tags = stdout.trim().split('\n').filter(tag => tag.length > 0);
|
|
76
|
-
logger.info(` ✅ Found ${tags.length} tags matching pattern "${tagPattern}"`);
|
|
77
|
-
if (tags.length > 0) {
|
|
78
|
-
logger.info(` 📋 Tags (newest first): ${tags.slice(0, 15).join(', ')}${tags.length > 15 ? ` ... (${tags.length - 15} more)` : ''}`);
|
|
79
|
-
}
|
|
80
|
-
} catch (sortError: any) {
|
|
81
|
-
// Fallback for older git versions that don't support --sort
|
|
82
|
-
logger.info(` ⚠️ Git tag --sort failed: ${sortError.message}`);
|
|
83
|
-
logger.info(` Falling back to manual sorting...`);
|
|
84
|
-
const { stdout } = await runSecure('git', ['tag', '-l', tagPattern]);
|
|
85
|
-
tags = stdout.trim().split('\n').filter(tag => tag.length > 0);
|
|
86
|
-
logger.info(` Found ${tags.length} tags (unsorted) matching pattern "${tagPattern}"`);
|
|
87
|
-
|
|
88
|
-
// Manual semantic version sorting
|
|
89
|
-
tags.sort((a, b) => {
|
|
90
|
-
const aMatch = a.match(/v?(\d+\.\d+\.\d+.*?)$/);
|
|
91
|
-
const bMatch = b.match(/v?(\d+\.\d+\.\d+.*?)$/);
|
|
92
|
-
if (!aMatch || !bMatch) return 0;
|
|
93
|
-
|
|
94
|
-
const aSemver = semver.parse(aMatch[1]);
|
|
95
|
-
const bSemver = semver.parse(bMatch[1]);
|
|
96
|
-
if (!aSemver || !bSemver) return 0;
|
|
97
|
-
|
|
98
|
-
return semver.rcompare(aSemver, bSemver);
|
|
99
|
-
});
|
|
100
|
-
logger.info(` ✅ Sorted ${tags.length} tags manually`);
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
if (tags.length === 0) {
|
|
104
|
-
logger.warn('');
|
|
105
|
-
logger.warn(`❌ NO TAGS FOUND matching pattern "${tagPattern}"`);
|
|
106
|
-
logger.warn(` To verify, run: git tag -l '${tagPattern}'`);
|
|
107
|
-
logger.warn('');
|
|
108
|
-
return null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
logger.info(` 🔬 Processing ${tags.length} tags to find the highest version < ${currentVersion}...`);
|
|
112
|
-
|
|
113
|
-
// Find the highest version that is less than the current version
|
|
114
|
-
let previousTag: string | null = null;
|
|
115
|
-
let previousVersion: semver.SemVer | null = null;
|
|
116
|
-
let validTags = 0;
|
|
117
|
-
let skippedTags = 0;
|
|
118
|
-
|
|
119
|
-
for (const tag of tags) {
|
|
120
|
-
// Extract version from tag - handle "v1.2.13", "1.2.13", and "working/v1.2.13"
|
|
121
|
-
const versionMatch = tag.match(/v?(\d+\.\d+\.\d+.*?)$/);
|
|
122
|
-
if (!versionMatch) {
|
|
123
|
-
logger.debug(` ⏭️ Skipping tag "${tag}" (doesn't match version pattern)`);
|
|
124
|
-
continue;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
const versionString = versionMatch[1];
|
|
128
|
-
const tagSemver = semver.parse(versionString);
|
|
129
|
-
|
|
130
|
-
if (tagSemver) {
|
|
131
|
-
validTags++;
|
|
132
|
-
|
|
133
|
-
// Check if this tag version is less than current version
|
|
134
|
-
if (semver.lt(tagSemver, currentSemver)) {
|
|
135
|
-
// If we don't have a previous version yet, or this one is higher than our current previous
|
|
136
|
-
if (!previousVersion || semver.gt(tagSemver, previousVersion)) {
|
|
137
|
-
previousVersion = tagSemver;
|
|
138
|
-
previousTag = tag; // Keep the original tag format
|
|
139
|
-
logger.info(` ✅ New best candidate: ${tag} (${versionString} < ${currentVersion})`);
|
|
140
|
-
} else {
|
|
141
|
-
logger.debug(` ⏭️ ${tag} (${versionString}) is < current but not better than ${previousTag}`);
|
|
142
|
-
}
|
|
143
|
-
} else {
|
|
144
|
-
skippedTags++;
|
|
145
|
-
logger.debug(` ⏭️ ${tag} (${versionString}) >= current (${currentVersion}), skipping`);
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
logger.info('');
|
|
151
|
-
logger.info(` 📊 Tag analysis results:`);
|
|
152
|
-
logger.info(` - Total tags examined: ${tags.length}`);
|
|
153
|
-
logger.info(` - Valid semver tags: ${validTags}`);
|
|
154
|
-
logger.info(` - Tags >= current version (skipped): ${skippedTags}`);
|
|
155
|
-
logger.info(` - Best match: ${previousTag || 'none'}`);
|
|
156
|
-
logger.info('');
|
|
157
|
-
|
|
158
|
-
if (previousTag) {
|
|
159
|
-
logger.info(`✅ SUCCESS: Found previous tag: ${previousTag}`);
|
|
160
|
-
logger.info(` Version comparison: ${previousVersion?.version} < ${currentVersion}`);
|
|
161
|
-
logger.info('');
|
|
162
|
-
return previousTag;
|
|
163
|
-
}
|
|
164
|
-
|
|
165
|
-
logger.warn(`❌ FAILED: No previous tag found for version ${currentVersion}`);
|
|
166
|
-
logger.warn(` Pattern searched: "${tagPattern}"`);
|
|
167
|
-
logger.warn(` Reason: All ${validTags} valid tags were >= ${currentVersion}`);
|
|
168
|
-
logger.warn('');
|
|
169
|
-
return null;
|
|
170
|
-
} catch (error: any) {
|
|
171
|
-
logger.debug(`Error finding previous release tag: ${error.message}`);
|
|
172
|
-
return null;
|
|
173
|
-
}
|
|
174
|
-
};
|
|
175
|
-
|
|
176
|
-
/**
|
|
177
|
-
* Gets the current version from package.json
|
|
178
|
-
*
|
|
179
|
-
* @returns The current version string or null if not found
|
|
180
|
-
*/
|
|
181
|
-
export const getCurrentVersion = async (): Promise<string | null> => {
|
|
182
|
-
const logger = getLogger();
|
|
183
|
-
|
|
184
|
-
try {
|
|
185
|
-
// First try to get from committed version in HEAD
|
|
186
|
-
const { stdout } = await runSecure('git', ['show', 'HEAD:package.json']);
|
|
187
|
-
const packageJson = safeJsonParse(stdout, 'package.json');
|
|
188
|
-
const validated = validatePackageJson(packageJson, 'package.json');
|
|
189
|
-
|
|
190
|
-
if (validated.version) {
|
|
191
|
-
logger.debug(`Current version from HEAD:package.json: ${validated.version}`);
|
|
192
|
-
return validated.version;
|
|
193
|
-
}
|
|
194
|
-
|
|
195
|
-
return null;
|
|
196
|
-
} catch (error: any) {
|
|
197
|
-
logger.debug(`Could not read version from HEAD:package.json: ${error.message}`);
|
|
198
|
-
|
|
199
|
-
// Fallback to reading from working directory
|
|
200
|
-
try {
|
|
201
|
-
const packageJsonPath = path.join(process.cwd(), 'package.json');
|
|
202
|
-
const content = await fs.readFile(packageJsonPath, 'utf-8');
|
|
203
|
-
const packageJson = safeJsonParse(content, 'package.json');
|
|
204
|
-
const validated = validatePackageJson(packageJson, 'package.json');
|
|
205
|
-
|
|
206
|
-
if (validated.version) {
|
|
207
|
-
logger.debug(`Current version from working directory package.json: ${validated.version}`);
|
|
208
|
-
return validated.version;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
return null;
|
|
212
|
-
} catch (fallbackError: any) {
|
|
213
|
-
logger.debug(`Error reading current version from filesystem: ${fallbackError.message}`);
|
|
214
|
-
return null;
|
|
215
|
-
}
|
|
216
|
-
}
|
|
217
|
-
};
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* Gets a reliable default for the --from parameter by trying multiple fallbacks
|
|
221
|
-
*
|
|
222
|
-
* Tries in order:
|
|
223
|
-
* 1. Previous working branch tag (if on working branch)
|
|
224
|
-
* 2. Previous release tag (if current version can be determined)
|
|
225
|
-
* 3. main (local main branch - typical release comparison base)
|
|
226
|
-
* 4. master (local master branch - legacy default)
|
|
227
|
-
* 5. origin/main (remote main branch fallback)
|
|
228
|
-
* 6. origin/master (remote master branch fallback)
|
|
229
|
-
*
|
|
230
|
-
* @param forceMainBranch If true, skip tag detection and use main branch
|
|
231
|
-
* @param currentBranch Current branch name for branch-aware tag detection
|
|
232
|
-
* @returns A valid git reference to use as the default from parameter
|
|
233
|
-
* @throws Error if no valid reference can be found
|
|
234
|
-
*/
|
|
235
|
-
export const getDefaultFromRef = async (
|
|
236
|
-
forceMainBranch: boolean = false,
|
|
237
|
-
currentBranch?: string
|
|
238
|
-
): Promise<string> => {
|
|
239
|
-
const logger = getLogger();
|
|
240
|
-
|
|
241
|
-
logger.info('');
|
|
242
|
-
logger.info('═══════════════════════════════════════════════════════════');
|
|
243
|
-
logger.info('🔍 DETECTING DEFAULT --from REFERENCE FOR RELEASE NOTES');
|
|
244
|
-
logger.info('═══════════════════════════════════════════════════════════');
|
|
245
|
-
logger.info(`📋 Input parameters:`);
|
|
246
|
-
logger.info(` - forceMainBranch: ${forceMainBranch}`);
|
|
247
|
-
logger.info(` - currentBranch: "${currentBranch}"`);
|
|
248
|
-
logger.info('');
|
|
249
|
-
|
|
250
|
-
// If forced to use main branch, skip tag detection
|
|
251
|
-
if (forceMainBranch) {
|
|
252
|
-
logger.info('⚡ Forced to use main branch, skipping tag detection');
|
|
253
|
-
} else {
|
|
254
|
-
// If on working branch, look for working branch tags first
|
|
255
|
-
logger.info(`🎯 Branch check: currentBranch="${currentBranch}", isWorking=${currentBranch === 'working'}`);
|
|
256
|
-
if (currentBranch && currentBranch === 'working') {
|
|
257
|
-
logger.info('');
|
|
258
|
-
logger.info('📍 DETECTED WORKING BRANCH - Searching for working branch tags...');
|
|
259
|
-
logger.info('───────────────────────────────────────────────────────────');
|
|
260
|
-
try {
|
|
261
|
-
const currentVersion = await getCurrentVersion();
|
|
262
|
-
logger.info(`📦 Current version from package.json: ${currentVersion}`);
|
|
263
|
-
if (currentVersion) {
|
|
264
|
-
logger.info(`🔍 Searching for tags matching pattern: "working/v*"`);
|
|
265
|
-
logger.info(` (Looking for tags < ${currentVersion})`);
|
|
266
|
-
logger.info('');
|
|
267
|
-
const previousTag = await findPreviousReleaseTag(
|
|
268
|
-
currentVersion,
|
|
269
|
-
'working/v*'
|
|
270
|
-
);
|
|
271
|
-
logger.info(`🎯 findPreviousReleaseTag result: ${previousTag || 'null (no tag found)'}`);
|
|
272
|
-
|
|
273
|
-
if (previousTag) {
|
|
274
|
-
logger.info(`🔬 Validating tag reference: "${previousTag}"`);
|
|
275
|
-
const isValid = await isValidGitRef(previousTag);
|
|
276
|
-
logger.info(` Tag is valid git ref: ${isValid}`);
|
|
277
|
-
|
|
278
|
-
if (isValid) {
|
|
279
|
-
logger.info('');
|
|
280
|
-
logger.info(`✅ SUCCESS: Using previous working branch tag '${previousTag}'`);
|
|
281
|
-
logger.info(` This shows commits added since the last release`);
|
|
282
|
-
logger.info('═══════════════════════════════════════════════════════════');
|
|
283
|
-
logger.info('');
|
|
284
|
-
return previousTag;
|
|
285
|
-
} else {
|
|
286
|
-
logger.warn('');
|
|
287
|
-
logger.warn(`⚠️ VALIDATION FAILED: Tag "${previousTag}" exists but is not a valid git reference`);
|
|
288
|
-
logger.warn(` This should not happen - the tag might be corrupted`);
|
|
289
|
-
}
|
|
290
|
-
} else {
|
|
291
|
-
logger.warn('');
|
|
292
|
-
logger.warn('❌ NO WORKING BRANCH TAG FOUND matching pattern "working/v*"');
|
|
293
|
-
logger.warn(` Current version: ${currentVersion}`);
|
|
294
|
-
logger.warn(' 💡 To create working branch tags for past releases, run:');
|
|
295
|
-
logger.warn(' kodrdriv development --create-retroactive-tags');
|
|
296
|
-
logger.warn('');
|
|
297
|
-
logger.warn(' Falling back to regular tag search...');
|
|
298
|
-
}
|
|
299
|
-
} else {
|
|
300
|
-
logger.warn('');
|
|
301
|
-
logger.warn('❌ CANNOT READ VERSION from package.json');
|
|
302
|
-
logger.warn(' Cannot search for working branch tags without current version');
|
|
303
|
-
}
|
|
304
|
-
} catch (error: any) {
|
|
305
|
-
logger.warn('');
|
|
306
|
-
logger.warn(`❌ ERROR while searching for working branch tag: ${error.message}`);
|
|
307
|
-
logger.debug(`Full error stack: ${error.stack}`);
|
|
308
|
-
logger.warn(' Falling back to regular tag search...');
|
|
309
|
-
}
|
|
310
|
-
logger.info('───────────────────────────────────────────────────────────');
|
|
311
|
-
logger.info('');
|
|
312
|
-
} else {
|
|
313
|
-
logger.info(`ℹ️ Not on "working" branch - skipping working tag search`);
|
|
314
|
-
logger.info(` (Only search for working/v* tags when on working branch)`);
|
|
315
|
-
logger.info('');
|
|
316
|
-
}
|
|
317
|
-
|
|
318
|
-
// First, try to find the previous release tag
|
|
319
|
-
try {
|
|
320
|
-
const currentVersion = await getCurrentVersion();
|
|
321
|
-
if (currentVersion) {
|
|
322
|
-
const previousTag = await findPreviousReleaseTag(currentVersion);
|
|
323
|
-
if (previousTag && await isValidGitRef(previousTag)) {
|
|
324
|
-
logger.info(`Using previous release tag '${previousTag}' as default --from reference`);
|
|
325
|
-
return previousTag;
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
} catch (error: any) {
|
|
329
|
-
logger.debug(`Could not determine previous release tag: ${error.message}`);
|
|
330
|
-
}
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// Fallback to branch-based references
|
|
334
|
-
const candidates = [
|
|
335
|
-
'main',
|
|
336
|
-
'master',
|
|
337
|
-
'origin/main',
|
|
338
|
-
'origin/master'
|
|
339
|
-
];
|
|
340
|
-
|
|
341
|
-
for (const candidate of candidates) {
|
|
342
|
-
logger.debug(`Testing git reference candidate: ${candidate}`);
|
|
343
|
-
if (await isValidGitRef(candidate)) {
|
|
344
|
-
if (forceMainBranch) {
|
|
345
|
-
logger.info(`Using '${candidate}' as forced main branch reference`);
|
|
346
|
-
} else {
|
|
347
|
-
logger.info(`Using '${candidate}' as fallback --from reference (no previous release tag found)`);
|
|
348
|
-
}
|
|
349
|
-
return candidate;
|
|
350
|
-
}
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
// If we get here, something is seriously wrong with the git repository
|
|
354
|
-
throw new Error(
|
|
355
|
-
'Could not find a valid default git reference for --from parameter. ' +
|
|
356
|
-
'Please specify --from explicitly or check your git repository configuration. ' +
|
|
357
|
-
`Tried: ${forceMainBranch ? 'main branch only' : 'previous release tag'}, ${candidates.join(', ')}`
|
|
358
|
-
);
|
|
359
|
-
};
|
|
360
|
-
|
|
361
|
-
/**
|
|
362
|
-
* Gets the default branch name from the remote repository
|
|
363
|
-
*/
|
|
364
|
-
export const getRemoteDefaultBranch = async (): Promise<string | null> => {
|
|
365
|
-
const logger = getLogger();
|
|
366
|
-
try {
|
|
367
|
-
// Try to get the symbolic reference for origin/HEAD
|
|
368
|
-
const { stdout } = await run('git symbolic-ref refs/remotes/origin/HEAD 2>/dev/null || echo ""');
|
|
369
|
-
if (stdout.trim()) {
|
|
370
|
-
// Extract branch name from refs/remotes/origin/branch-name
|
|
371
|
-
const match = stdout.trim().match(/refs\/remotes\/origin\/(.+)$/);
|
|
372
|
-
if (match) {
|
|
373
|
-
const branchName = match[1];
|
|
374
|
-
logger.debug(`Remote default branch is: ${branchName}`);
|
|
375
|
-
return branchName;
|
|
376
|
-
}
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
// Fallback: try to get it from ls-remote
|
|
380
|
-
const { stdout: lsRemoteOutput } = await run('git ls-remote --symref origin HEAD');
|
|
381
|
-
const symrefMatch = lsRemoteOutput.match(/ref: refs\/heads\/(.+)\s+HEAD/);
|
|
382
|
-
if (symrefMatch) {
|
|
383
|
-
const branchName = symrefMatch[1];
|
|
384
|
-
logger.debug(`Remote default branch from ls-remote: ${branchName}`);
|
|
385
|
-
return branchName;
|
|
386
|
-
}
|
|
387
|
-
|
|
388
|
-
logger.debug('Could not determine remote default branch');
|
|
389
|
-
return null;
|
|
390
|
-
} catch (error) {
|
|
391
|
-
logger.debug(`Failed to get remote default branch: ${error}`);
|
|
392
|
-
return null;
|
|
393
|
-
}
|
|
394
|
-
};
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* Checks if a local branch exists
|
|
398
|
-
*/
|
|
399
|
-
export const localBranchExists = async (branchName: string): Promise<boolean> => {
|
|
400
|
-
const logger = getLogger();
|
|
401
|
-
const result = await isValidGitRefSilent(`refs/heads/${branchName}`);
|
|
402
|
-
if (result) {
|
|
403
|
-
logger.debug(`Local branch '${branchName}' exists`);
|
|
404
|
-
} else {
|
|
405
|
-
logger.debug(`Local branch '${branchName}' does not exist`);
|
|
406
|
-
}
|
|
407
|
-
return result;
|
|
408
|
-
};
|
|
409
|
-
|
|
410
|
-
/**
|
|
411
|
-
* Checks if a remote branch exists
|
|
412
|
-
*/
|
|
413
|
-
export const remoteBranchExists = async (branchName: string, remote: string = 'origin'): Promise<boolean> => {
|
|
414
|
-
const logger = getLogger();
|
|
415
|
-
const result = await isValidGitRefSilent(`refs/remotes/${remote}/${branchName}`);
|
|
416
|
-
if (result) {
|
|
417
|
-
logger.debug(`Remote branch '${remote}/${branchName}' exists`);
|
|
418
|
-
} else {
|
|
419
|
-
logger.debug(`Remote branch '${remote}/${branchName}' does not exist`);
|
|
420
|
-
}
|
|
421
|
-
return result;
|
|
422
|
-
};
|
|
423
|
-
|
|
424
|
-
/**
|
|
425
|
-
* Gets the commit SHA for a given branch (local or remote)
|
|
426
|
-
*/
|
|
427
|
-
export const getBranchCommitSha = async (branchRef: string): Promise<string> => {
|
|
428
|
-
// Validate the ref first to prevent injection
|
|
429
|
-
if (!validateGitRef(branchRef)) {
|
|
430
|
-
throw new Error(`Invalid git reference: ${branchRef}`);
|
|
431
|
-
}
|
|
432
|
-
const { stdout } = await runSecure('git', ['rev-parse', branchRef]);
|
|
433
|
-
return stdout.trim();
|
|
434
|
-
};
|
|
435
|
-
|
|
436
|
-
/**
|
|
437
|
-
* Checks if a local branch is in sync with its remote counterpart
|
|
438
|
-
*/
|
|
439
|
-
export const isBranchInSyncWithRemote = async (branchName: string, remote: string = 'origin'): Promise<{
|
|
440
|
-
inSync: boolean;
|
|
441
|
-
localSha?: string;
|
|
442
|
-
remoteSha?: string;
|
|
443
|
-
localExists: boolean;
|
|
444
|
-
remoteExists: boolean;
|
|
445
|
-
error?: string;
|
|
446
|
-
}> => {
|
|
447
|
-
const logger = getLogger();
|
|
448
|
-
|
|
449
|
-
try {
|
|
450
|
-
// Validate inputs first to prevent injection
|
|
451
|
-
if (!validateGitRef(branchName)) {
|
|
452
|
-
throw new Error(`Invalid branch name: ${branchName}`);
|
|
453
|
-
}
|
|
454
|
-
if (!validateGitRef(remote)) {
|
|
455
|
-
throw new Error(`Invalid remote name: ${remote}`);
|
|
456
|
-
}
|
|
457
|
-
|
|
458
|
-
// First, fetch latest remote refs without affecting working directory
|
|
459
|
-
await runSecure('git', ['fetch', remote, '--quiet']);
|
|
460
|
-
|
|
461
|
-
const localExists = await localBranchExists(branchName);
|
|
462
|
-
const remoteExists = await remoteBranchExists(branchName, remote);
|
|
463
|
-
|
|
464
|
-
if (!localExists) {
|
|
465
|
-
return {
|
|
466
|
-
inSync: false,
|
|
467
|
-
localExists: false,
|
|
468
|
-
remoteExists,
|
|
469
|
-
error: `Local branch '${branchName}' does not exist`
|
|
470
|
-
};
|
|
471
|
-
}
|
|
472
|
-
|
|
473
|
-
if (!remoteExists) {
|
|
474
|
-
return {
|
|
475
|
-
inSync: false,
|
|
476
|
-
localExists: true,
|
|
477
|
-
remoteExists: false,
|
|
478
|
-
error: `Remote branch '${remote}/${branchName}' does not exist`
|
|
479
|
-
};
|
|
480
|
-
}
|
|
481
|
-
|
|
482
|
-
// Both branches exist, compare their SHAs
|
|
483
|
-
const localSha = await getBranchCommitSha(`refs/heads/${branchName}`);
|
|
484
|
-
const remoteSha = await getBranchCommitSha(`refs/remotes/${remote}/${branchName}`);
|
|
485
|
-
|
|
486
|
-
const inSync = localSha === remoteSha;
|
|
487
|
-
|
|
488
|
-
logger.debug(`Branch sync check for '${branchName}': local=${localSha.substring(0, 8)}, remote=${remoteSha.substring(0, 8)}, inSync=${inSync}`);
|
|
489
|
-
|
|
490
|
-
return {
|
|
491
|
-
inSync,
|
|
492
|
-
localSha,
|
|
493
|
-
remoteSha,
|
|
494
|
-
localExists: true,
|
|
495
|
-
remoteExists: true
|
|
496
|
-
};
|
|
497
|
-
|
|
498
|
-
} catch (error: any) {
|
|
499
|
-
logger.debug(`Failed to check branch sync for '${branchName}': ${error.message}`);
|
|
500
|
-
return {
|
|
501
|
-
inSync: false,
|
|
502
|
-
localExists: false,
|
|
503
|
-
remoteExists: false,
|
|
504
|
-
error: `Failed to check branch sync: ${error.message}`
|
|
505
|
-
};
|
|
506
|
-
}
|
|
507
|
-
};
|
|
508
|
-
|
|
509
|
-
/**
|
|
510
|
-
* Attempts to safely sync a local branch with its remote counterpart
|
|
511
|
-
* Returns true if successful, false if conflicts exist that require manual resolution
|
|
512
|
-
*/
|
|
513
|
-
export const safeSyncBranchWithRemote = async (branchName: string, remote: string = 'origin'): Promise<{
|
|
514
|
-
success: boolean;
|
|
515
|
-
error?: string;
|
|
516
|
-
conflictResolutionRequired?: boolean;
|
|
517
|
-
}> => {
|
|
518
|
-
const logger = getLogger();
|
|
519
|
-
|
|
520
|
-
try {
|
|
521
|
-
// Validate inputs first to prevent injection
|
|
522
|
-
if (!validateGitRef(branchName)) {
|
|
523
|
-
throw new Error(`Invalid branch name: ${branchName}`);
|
|
524
|
-
}
|
|
525
|
-
if (!validateGitRef(remote)) {
|
|
526
|
-
throw new Error(`Invalid remote name: ${remote}`);
|
|
527
|
-
}
|
|
528
|
-
|
|
529
|
-
// Check current branch to restore later if needed
|
|
530
|
-
const { stdout: currentBranch } = await runSecure('git', ['branch', '--show-current']);
|
|
531
|
-
const originalBranch = currentBranch.trim();
|
|
532
|
-
|
|
533
|
-
// Fetch latest remote refs
|
|
534
|
-
await runSecure('git', ['fetch', remote, '--quiet']);
|
|
535
|
-
|
|
536
|
-
// Check if local branch exists
|
|
537
|
-
const localExists = await localBranchExists(branchName);
|
|
538
|
-
const remoteExists = await remoteBranchExists(branchName, remote);
|
|
539
|
-
|
|
540
|
-
if (!remoteExists) {
|
|
541
|
-
return {
|
|
542
|
-
success: false,
|
|
543
|
-
error: `Remote branch '${remote}/${branchName}' does not exist`
|
|
544
|
-
};
|
|
545
|
-
}
|
|
546
|
-
|
|
547
|
-
if (!localExists) {
|
|
548
|
-
// Create local branch tracking the remote
|
|
549
|
-
await runSecure('git', ['branch', branchName, `${remote}/${branchName}`]);
|
|
550
|
-
logger.debug(`Created local branch '${branchName}' tracking '${remote}/${branchName}'`);
|
|
551
|
-
return { success: true };
|
|
552
|
-
}
|
|
553
|
-
|
|
554
|
-
// Check if we need to switch to the target branch
|
|
555
|
-
const needToSwitch = originalBranch !== branchName;
|
|
556
|
-
|
|
557
|
-
if (needToSwitch) {
|
|
558
|
-
// Check for uncommitted changes before switching
|
|
559
|
-
const { stdout: statusOutput } = await runSecure('git', ['status', '--porcelain']);
|
|
560
|
-
if (statusOutput.trim()) {
|
|
561
|
-
return {
|
|
562
|
-
success: false,
|
|
563
|
-
error: `Cannot switch to branch '${branchName}' because you have uncommitted changes. Please commit or stash your changes first.`
|
|
564
|
-
};
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
// Switch to target branch
|
|
568
|
-
await runSecure('git', ['checkout', branchName]);
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
try {
|
|
572
|
-
// Try to pull with fast-forward only
|
|
573
|
-
await runSecure('git', ['pull', remote, branchName, '--ff-only']);
|
|
574
|
-
logger.debug(`Successfully synced '${branchName}' with '${remote}/${branchName}'`);
|
|
575
|
-
|
|
576
|
-
// Switch back to original branch if we switched
|
|
577
|
-
if (needToSwitch && originalBranch) {
|
|
578
|
-
await runSecure('git', ['checkout', originalBranch]);
|
|
579
|
-
}
|
|
580
|
-
|
|
581
|
-
return { success: true };
|
|
582
|
-
|
|
583
|
-
} catch (pullError: any) {
|
|
584
|
-
// Switch back to original branch if we switched
|
|
585
|
-
if (needToSwitch && originalBranch) {
|
|
586
|
-
try {
|
|
587
|
-
await runSecure('git', ['checkout', originalBranch]);
|
|
588
|
-
} catch (checkoutError) {
|
|
589
|
-
logger.warn(`Failed to switch back to original branch '${originalBranch}': ${checkoutError}`);
|
|
590
|
-
}
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
// Check if this is a merge conflict or diverged branches
|
|
594
|
-
if (pullError.message.includes('diverged') ||
|
|
595
|
-
pullError.message.includes('non-fast-forward') ||
|
|
596
|
-
pullError.message.includes('conflict') ||
|
|
597
|
-
pullError.message.includes('CONFLICT')) {
|
|
598
|
-
return {
|
|
599
|
-
success: false,
|
|
600
|
-
conflictResolutionRequired: true,
|
|
601
|
-
error: `Branch '${branchName}' has diverged from '${remote}/${branchName}' and requires manual conflict resolution`
|
|
602
|
-
};
|
|
603
|
-
}
|
|
604
|
-
|
|
605
|
-
return {
|
|
606
|
-
success: false,
|
|
607
|
-
error: `Failed to sync branch '${branchName}': ${pullError.message}`
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
|
|
611
|
-
} catch (error: any) {
|
|
612
|
-
return {
|
|
613
|
-
success: false,
|
|
614
|
-
error: `Failed to sync branch '${branchName}': ${error.message}`
|
|
615
|
-
};
|
|
616
|
-
}
|
|
617
|
-
};
|
|
618
|
-
|
|
619
|
-
/**
|
|
620
|
-
* Gets the current branch name
|
|
621
|
-
*/
|
|
622
|
-
export const getCurrentBranch = async (): Promise<string> => {
|
|
623
|
-
const { stdout } = await runSecure('git', ['branch', '--show-current']);
|
|
624
|
-
return stdout.trim();
|
|
625
|
-
};
|
|
626
|
-
|
|
627
|
-
/**
|
|
628
|
-
* Gets git status summary including unstaged files, uncommitted changes, and unpushed commits
|
|
629
|
-
*/
|
|
630
|
-
export const getGitStatusSummary = async (workingDir?: string): Promise<{
|
|
631
|
-
branch: string;
|
|
632
|
-
hasUnstagedFiles: boolean;
|
|
633
|
-
hasUncommittedChanges: boolean;
|
|
634
|
-
hasUnpushedCommits: boolean;
|
|
635
|
-
unstagedCount: number;
|
|
636
|
-
uncommittedCount: number;
|
|
637
|
-
unpushedCount: number;
|
|
638
|
-
status: string; // summary status string
|
|
639
|
-
}> => {
|
|
640
|
-
const logger = getLogger();
|
|
641
|
-
|
|
642
|
-
try {
|
|
643
|
-
const originalCwd = process.cwd();
|
|
644
|
-
if (workingDir) {
|
|
645
|
-
process.chdir(workingDir);
|
|
646
|
-
}
|
|
647
|
-
|
|
648
|
-
try {
|
|
649
|
-
// Get current branch
|
|
650
|
-
const branch = await getCurrentBranch();
|
|
651
|
-
|
|
652
|
-
// Get git status for unstaged and uncommitted changes
|
|
653
|
-
const { stdout: statusOutput } = await runSecure('git', ['status', '--porcelain']);
|
|
654
|
-
const statusLines = statusOutput.trim().split('\n').filter(line => line.trim());
|
|
655
|
-
|
|
656
|
-
// Count different types of changes
|
|
657
|
-
let unstagedCount = 0;
|
|
658
|
-
let uncommittedCount = 0;
|
|
659
|
-
|
|
660
|
-
for (const line of statusLines) {
|
|
661
|
-
const statusCode = line.substring(0, 2);
|
|
662
|
-
|
|
663
|
-
// For untracked files (??) count as unstaged only once
|
|
664
|
-
if (statusCode === '??') {
|
|
665
|
-
unstagedCount++;
|
|
666
|
-
continue;
|
|
667
|
-
}
|
|
668
|
-
|
|
669
|
-
// Check for unstaged changes (working directory changes)
|
|
670
|
-
// Second character represents working tree status
|
|
671
|
-
if (statusCode[1] !== ' ' && statusCode[1] !== '') {
|
|
672
|
-
unstagedCount++;
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
// Check for uncommitted changes (staged changes)
|
|
676
|
-
// First character represents index status
|
|
677
|
-
if (statusCode[0] !== ' ' && statusCode[0] !== '') {
|
|
678
|
-
uncommittedCount++;
|
|
679
|
-
}
|
|
680
|
-
}
|
|
681
|
-
|
|
682
|
-
// Check for unpushed commits by comparing with remote
|
|
683
|
-
let unpushedCount = 0;
|
|
684
|
-
let hasUnpushedCommits = false;
|
|
685
|
-
|
|
686
|
-
try {
|
|
687
|
-
// First fetch to get latest remote refs
|
|
688
|
-
await runSecure('git', ['fetch', 'origin', '--quiet']);
|
|
689
|
-
|
|
690
|
-
// Check if remote branch exists
|
|
691
|
-
const remoteExists = await remoteBranchExists(branch);
|
|
692
|
-
|
|
693
|
-
if (remoteExists) {
|
|
694
|
-
// Get count of commits ahead of remote (branch already validated in calling function)
|
|
695
|
-
const { stdout: aheadOutput } = await runSecure('git', ['rev-list', '--count', `origin/${branch}..HEAD`]);
|
|
696
|
-
unpushedCount = parseInt(aheadOutput.trim()) || 0;
|
|
697
|
-
hasUnpushedCommits = unpushedCount > 0;
|
|
698
|
-
}
|
|
699
|
-
} catch (error) {
|
|
700
|
-
logger.debug(`Could not check for unpushed commits: ${error}`);
|
|
701
|
-
// Remote might not exist or other issues - not critical for status
|
|
702
|
-
}
|
|
703
|
-
|
|
704
|
-
const hasUnstagedFiles = unstagedCount > 0;
|
|
705
|
-
const hasUncommittedChanges = uncommittedCount > 0;
|
|
706
|
-
|
|
707
|
-
// Build status summary
|
|
708
|
-
const statusParts: string[] = [];
|
|
709
|
-
|
|
710
|
-
if (hasUnstagedFiles) {
|
|
711
|
-
statusParts.push(`${unstagedCount} unstaged`);
|
|
712
|
-
}
|
|
713
|
-
if (hasUncommittedChanges) {
|
|
714
|
-
statusParts.push(`${uncommittedCount} uncommitted`);
|
|
715
|
-
}
|
|
716
|
-
if (hasUnpushedCommits) {
|
|
717
|
-
statusParts.push(`${unpushedCount} unpushed`);
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
const status = statusParts.length > 0 ? statusParts.join(', ') : 'clean';
|
|
721
|
-
|
|
722
|
-
return {
|
|
723
|
-
branch,
|
|
724
|
-
hasUnstagedFiles,
|
|
725
|
-
hasUncommittedChanges,
|
|
726
|
-
hasUnpushedCommits,
|
|
727
|
-
unstagedCount,
|
|
728
|
-
uncommittedCount,
|
|
729
|
-
unpushedCount,
|
|
730
|
-
status
|
|
731
|
-
};
|
|
732
|
-
|
|
733
|
-
} finally {
|
|
734
|
-
if (workingDir) {
|
|
735
|
-
process.chdir(originalCwd);
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
|
|
739
|
-
} catch (error: any) {
|
|
740
|
-
logger.debug(`Failed to get git status summary: ${error.message}`);
|
|
741
|
-
return {
|
|
742
|
-
branch: 'unknown',
|
|
743
|
-
hasUnstagedFiles: false,
|
|
744
|
-
hasUncommittedChanges: false,
|
|
745
|
-
hasUnpushedCommits: false,
|
|
746
|
-
unstagedCount: 0,
|
|
747
|
-
uncommittedCount: 0,
|
|
748
|
-
unpushedCount: 0,
|
|
749
|
-
status: 'error'
|
|
750
|
-
};
|
|
751
|
-
}
|
|
752
|
-
};
|
|
753
|
-
|
|
754
|
-
/**
|
|
755
|
-
* Gets the list of globally linked packages (packages available to be linked to)
|
|
756
|
-
*/
|
|
757
|
-
export const getGloballyLinkedPackages = async (): Promise<Set<string>> => {
|
|
758
|
-
const execPromise = util.promisify(exec);
|
|
759
|
-
|
|
760
|
-
try {
|
|
761
|
-
const { stdout } = await execPromise('npm ls --link -g --json');
|
|
762
|
-
const result = safeJsonParse(stdout, 'npm ls global output');
|
|
763
|
-
|
|
764
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
765
|
-
return new Set(Object.keys(result.dependencies));
|
|
766
|
-
}
|
|
767
|
-
|
|
768
|
-
return new Set();
|
|
769
|
-
} catch (error: any) {
|
|
770
|
-
// Try to parse from error stdout if available
|
|
771
|
-
if (error.stdout) {
|
|
772
|
-
try {
|
|
773
|
-
const result = safeJsonParse(error.stdout, 'npm ls global error output');
|
|
774
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
775
|
-
return new Set(Object.keys(result.dependencies));
|
|
776
|
-
}
|
|
777
|
-
} catch {
|
|
778
|
-
// If JSON parsing fails, return empty set
|
|
779
|
-
}
|
|
780
|
-
}
|
|
781
|
-
|
|
782
|
-
return new Set();
|
|
783
|
-
}
|
|
784
|
-
};
|
|
785
|
-
|
|
786
|
-
/**
|
|
787
|
-
* Gets the list of packages that this package is actively linking to (consuming linked packages)
|
|
788
|
-
*/
|
|
789
|
-
export const getLinkedDependencies = async (packageDir: string): Promise<Set<string>> => {
|
|
790
|
-
const execPromise = util.promisify(exec);
|
|
791
|
-
|
|
792
|
-
try {
|
|
793
|
-
const { stdout } = await execPromise('npm ls --link --json', { cwd: packageDir });
|
|
794
|
-
const result = safeJsonParse(stdout, 'npm ls local output');
|
|
795
|
-
|
|
796
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
797
|
-
return new Set(Object.keys(result.dependencies));
|
|
798
|
-
}
|
|
799
|
-
|
|
800
|
-
return new Set();
|
|
801
|
-
} catch (error: any) {
|
|
802
|
-
// npm ls --link often exits with non-zero code but still provides valid JSON in stdout
|
|
803
|
-
if (error.stdout) {
|
|
804
|
-
try {
|
|
805
|
-
const result = safeJsonParse(error.stdout, 'npm ls local error output');
|
|
806
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
807
|
-
return new Set(Object.keys(result.dependencies));
|
|
808
|
-
}
|
|
809
|
-
} catch {
|
|
810
|
-
// If JSON parsing fails, return empty set
|
|
811
|
-
}
|
|
812
|
-
}
|
|
813
|
-
|
|
814
|
-
return new Set();
|
|
815
|
-
}
|
|
816
|
-
};
|
|
817
|
-
|
|
818
|
-
/**
|
|
819
|
-
* Checks for actual semantic version compatibility issues between linked packages and their consumers
|
|
820
|
-
* Returns a set of dependency names that have real compatibility problems
|
|
821
|
-
*
|
|
822
|
-
* This function ignores npm's strict prerelease handling and focuses on actual compatibility:
|
|
823
|
-
* - "^4.4" is compatible with "4.4.53-dev.0" (prerelease of compatible minor version)
|
|
824
|
-
* - "^4.4" is incompatible with "4.5.3" (different minor version)
|
|
825
|
-
*/
|
|
826
|
-
export const getLinkCompatibilityProblems = async (
|
|
827
|
-
packageDir: string,
|
|
828
|
-
allPackagesInfo?: Map<string, { name: string; version: string; path: string }>
|
|
829
|
-
): Promise<Set<string>> => {
|
|
830
|
-
try {
|
|
831
|
-
// Read the consumer package.json
|
|
832
|
-
const packageJsonPath = path.join(packageDir, 'package.json');
|
|
833
|
-
const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
|
|
834
|
-
const parsed = safeJsonParse(packageJsonContent, packageJsonPath);
|
|
835
|
-
const packageJson = validatePackageJson(parsed, packageJsonPath);
|
|
836
|
-
|
|
837
|
-
const problemDependencies = new Set<string>();
|
|
838
|
-
|
|
839
|
-
// Get linked dependencies
|
|
840
|
-
const linkedDeps = await getLinkedDependencies(packageDir);
|
|
841
|
-
|
|
842
|
-
// Check each dependency type
|
|
843
|
-
const dependencyTypes = ['dependencies', 'devDependencies', 'peerDependencies', 'optionalDependencies'];
|
|
844
|
-
|
|
845
|
-
for (const depType of dependencyTypes) {
|
|
846
|
-
const deps = packageJson[depType];
|
|
847
|
-
if (!deps || typeof deps !== 'object') continue;
|
|
848
|
-
|
|
849
|
-
for (const [depName, versionRange] of Object.entries(deps)) {
|
|
850
|
-
// Only check dependencies that are currently linked
|
|
851
|
-
if (!linkedDeps.has(depName)) continue;
|
|
852
|
-
|
|
853
|
-
// Skip if version range is not a string or is invalid
|
|
854
|
-
if (typeof versionRange !== 'string') continue;
|
|
855
|
-
|
|
856
|
-
try {
|
|
857
|
-
let linkedVersion: string | undefined;
|
|
858
|
-
|
|
859
|
-
// If we have package info provided, use it
|
|
860
|
-
if (allPackagesInfo) {
|
|
861
|
-
const packageInfo = allPackagesInfo.get(depName);
|
|
862
|
-
if (packageInfo) {
|
|
863
|
-
linkedVersion = packageInfo.version;
|
|
864
|
-
}
|
|
865
|
-
}
|
|
866
|
-
|
|
867
|
-
// If we don't have version from package info, try to read it from the linked package
|
|
868
|
-
if (!linkedVersion) {
|
|
869
|
-
try {
|
|
870
|
-
// Get the linked package path and read its version
|
|
871
|
-
const nodeModulesPath = path.join(packageDir, 'node_modules', depName, 'package.json');
|
|
872
|
-
const linkedPackageJson = await fs.readFile(nodeModulesPath, 'utf-8');
|
|
873
|
-
const linkedParsed = safeJsonParse(linkedPackageJson, nodeModulesPath);
|
|
874
|
-
const linkedValidated = validatePackageJson(linkedParsed, nodeModulesPath);
|
|
875
|
-
linkedVersion = linkedValidated.version;
|
|
876
|
-
} catch {
|
|
877
|
-
// Could not read linked package version, skip this dependency
|
|
878
|
-
continue;
|
|
879
|
-
}
|
|
880
|
-
}
|
|
881
|
-
|
|
882
|
-
if (!linkedVersion) continue;
|
|
883
|
-
|
|
884
|
-
// Check compatibility with custom logic for prerelease versions
|
|
885
|
-
if (!isVersionCompatibleWithRange(linkedVersion, versionRange)) {
|
|
886
|
-
problemDependencies.add(depName);
|
|
887
|
-
}
|
|
888
|
-
} catch {
|
|
889
|
-
// Skip dependencies we can't process
|
|
890
|
-
continue;
|
|
891
|
-
}
|
|
892
|
-
}
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
return problemDependencies;
|
|
896
|
-
} catch {
|
|
897
|
-
// If we can't read the package.json or process it, return empty set
|
|
898
|
-
return new Set();
|
|
899
|
-
}
|
|
900
|
-
};
|
|
901
|
-
|
|
902
|
-
/**
|
|
903
|
-
* Custom semver compatibility check that handles prerelease versions more intelligently
|
|
904
|
-
* than npm's strict checking, with stricter caret range handling
|
|
905
|
-
*
|
|
906
|
-
* Examples:
|
|
907
|
-
* - isVersionCompatibleWithRange("4.4.53-dev.0", "^4.4") => true
|
|
908
|
-
* - isVersionCompatibleWithRange("4.5.3", "^4.4") => false
|
|
909
|
-
* - isVersionCompatibleWithRange("4.4.1", "^4.4") => true
|
|
910
|
-
*/
|
|
911
|
-
const isVersionCompatibleWithRange = (version: string, range: string): boolean => {
|
|
912
|
-
try {
|
|
913
|
-
const parsedVersion = semver.parse(version);
|
|
914
|
-
if (!parsedVersion) return false;
|
|
915
|
-
|
|
916
|
-
// Parse the range to understand what we're comparing against
|
|
917
|
-
const rangeObj = semver.validRange(range);
|
|
918
|
-
if (!rangeObj) return false;
|
|
919
|
-
|
|
920
|
-
// For caret ranges like "^4.4", we want more strict checking than semver's default
|
|
921
|
-
if (range.startsWith('^')) {
|
|
922
|
-
const rangeVersion = range.substring(1); // Remove the ^
|
|
923
|
-
|
|
924
|
-
// Try to parse as a complete version first
|
|
925
|
-
let parsedRange = semver.parse(rangeVersion);
|
|
926
|
-
|
|
927
|
-
// If that fails, try to coerce it (handles cases like "4.4" -> "4.4.0")
|
|
928
|
-
if (!parsedRange) {
|
|
929
|
-
const coercedRange = semver.coerce(rangeVersion);
|
|
930
|
-
if (coercedRange) {
|
|
931
|
-
parsedRange = coercedRange;
|
|
932
|
-
} else {
|
|
933
|
-
return false;
|
|
934
|
-
}
|
|
935
|
-
}
|
|
936
|
-
|
|
937
|
-
// For prerelease versions, check if the base version (without prerelease)
|
|
938
|
-
// matches the major.minor from the range
|
|
939
|
-
if (parsedVersion.prerelease.length > 0) {
|
|
940
|
-
return parsedVersion.major === parsedRange.major &&
|
|
941
|
-
parsedVersion.minor === parsedRange.minor;
|
|
942
|
-
}
|
|
943
|
-
|
|
944
|
-
// For regular versions with caret ranges, be strict about minor version
|
|
945
|
-
// ^4.4 should only accept 4.4.x, not 4.5.x
|
|
946
|
-
return parsedVersion.major === parsedRange.major &&
|
|
947
|
-
parsedVersion.minor === parsedRange.minor;
|
|
948
|
-
}
|
|
949
|
-
|
|
950
|
-
// For other range types (exact, tilde, etc.), use standard semver checking
|
|
951
|
-
if (parsedVersion.prerelease.length > 0) {
|
|
952
|
-
const baseVersion = `${parsedVersion.major}.${parsedVersion.minor}.${parsedVersion.patch}`;
|
|
953
|
-
return semver.satisfies(baseVersion, range);
|
|
954
|
-
}
|
|
955
|
-
|
|
956
|
-
return semver.satisfies(version, range);
|
|
957
|
-
} catch {
|
|
958
|
-
// If semver parsing fails, assume incompatible
|
|
959
|
-
return false;
|
|
960
|
-
}
|
|
961
|
-
};
|
|
962
|
-
|
|
963
|
-
/**
|
|
964
|
-
* Checks for npm link problems (version mismatches) in a package directory
|
|
965
|
-
* Returns a set of dependency names that have link problems
|
|
966
|
-
*
|
|
967
|
-
* @deprecated Use getLinkCompatibilityProblems instead for better prerelease version handling
|
|
968
|
-
*/
|
|
969
|
-
export const getLinkProblems = async (packageDir: string): Promise<Set<string>> => {
|
|
970
|
-
const execPromise = util.promisify(exec);
|
|
971
|
-
|
|
972
|
-
try {
|
|
973
|
-
const { stdout } = await execPromise('npm ls --link --json', { cwd: packageDir });
|
|
974
|
-
const result = safeJsonParse(stdout, 'npm ls troubleshoot output');
|
|
975
|
-
|
|
976
|
-
const problemDependencies = new Set<string>();
|
|
977
|
-
|
|
978
|
-
// Check if there are any problems reported
|
|
979
|
-
if (result.problems && Array.isArray(result.problems)) {
|
|
980
|
-
// Parse problems array to extract dependency names
|
|
981
|
-
for (const problem of result.problems) {
|
|
982
|
-
if (typeof problem === 'string' && problem.includes('invalid:')) {
|
|
983
|
-
// Extract package name from problem string like "invalid: @fjell/eslint-config@1.1.20-dev.0 ..."
|
|
984
|
-
// Handle both scoped (@scope/name) and unscoped (name) packages
|
|
985
|
-
const match = problem.match(/invalid:\s+(@[^/]+\/[^@\s]+|[^@\s]+)@/);
|
|
986
|
-
if (match) {
|
|
987
|
-
problemDependencies.add(match[1]);
|
|
988
|
-
}
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
}
|
|
992
|
-
|
|
993
|
-
// Also check individual dependencies for problems
|
|
994
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
995
|
-
for (const [depName, depInfo] of Object.entries(result.dependencies)) {
|
|
996
|
-
if (depInfo && typeof depInfo === 'object') {
|
|
997
|
-
const dep = depInfo as any;
|
|
998
|
-
// Check if this dependency has problems or is marked as invalid
|
|
999
|
-
if ((dep.problems && Array.isArray(dep.problems) && dep.problems.length > 0) ||
|
|
1000
|
-
dep.invalid) {
|
|
1001
|
-
problemDependencies.add(depName);
|
|
1002
|
-
}
|
|
1003
|
-
}
|
|
1004
|
-
}
|
|
1005
|
-
}
|
|
1006
|
-
|
|
1007
|
-
return problemDependencies;
|
|
1008
|
-
} catch (error: any) {
|
|
1009
|
-
// npm ls --link often exits with non-zero code when there are problems
|
|
1010
|
-
// but still provides valid JSON in stdout
|
|
1011
|
-
if (error.stdout) {
|
|
1012
|
-
try {
|
|
1013
|
-
const result = safeJsonParse(error.stdout, 'npm ls troubleshoot error output');
|
|
1014
|
-
const problemDependencies = new Set<string>();
|
|
1015
|
-
|
|
1016
|
-
// Check if there are any problems reported
|
|
1017
|
-
if (result.problems && Array.isArray(result.problems)) {
|
|
1018
|
-
for (const problem of result.problems) {
|
|
1019
|
-
if (typeof problem === 'string' && problem.includes('invalid:')) {
|
|
1020
|
-
const match = problem.match(/invalid:\s+(@[^/]+\/[^@\s]+|[^@\s]+)@/);
|
|
1021
|
-
if (match) {
|
|
1022
|
-
problemDependencies.add(match[1]);
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// Also check individual dependencies for problems
|
|
1029
|
-
if (result.dependencies && typeof result.dependencies === 'object') {
|
|
1030
|
-
for (const [depName, depInfo] of Object.entries(result.dependencies)) {
|
|
1031
|
-
if (depInfo && typeof depInfo === 'object') {
|
|
1032
|
-
const dep = depInfo as any;
|
|
1033
|
-
if ((dep.problems && Array.isArray(dep.problems) && dep.problems.length > 0) ||
|
|
1034
|
-
dep.invalid) {
|
|
1035
|
-
problemDependencies.add(depName);
|
|
1036
|
-
}
|
|
1037
|
-
}
|
|
1038
|
-
}
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
return problemDependencies;
|
|
1042
|
-
} catch {
|
|
1043
|
-
// If JSON parsing fails, return empty set
|
|
1044
|
-
return new Set();
|
|
1045
|
-
}
|
|
1046
|
-
}
|
|
1047
|
-
|
|
1048
|
-
return new Set();
|
|
1049
|
-
}
|
|
1050
|
-
};
|
|
1051
|
-
|
|
1052
|
-
/**
|
|
1053
|
-
* Checks if a package directory is npm linked (has a global symlink)
|
|
1054
|
-
*/
|
|
1055
|
-
export const isNpmLinked = async (packageDir: string): Promise<boolean> => {
|
|
1056
|
-
const logger = getLogger();
|
|
1057
|
-
|
|
1058
|
-
try {
|
|
1059
|
-
// Read package.json to get the package name
|
|
1060
|
-
const packageJsonPath = path.join(packageDir, 'package.json');
|
|
1061
|
-
|
|
1062
|
-
try {
|
|
1063
|
-
await fs.access(packageJsonPath);
|
|
1064
|
-
} catch {
|
|
1065
|
-
// No package.json found
|
|
1066
|
-
return false;
|
|
1067
|
-
}
|
|
1068
|
-
|
|
1069
|
-
const packageJsonContent = await fs.readFile(packageJsonPath, 'utf-8');
|
|
1070
|
-
const packageJson = safeJsonParse(packageJsonContent, packageJsonPath);
|
|
1071
|
-
const packageName = packageJson.name;
|
|
1072
|
-
|
|
1073
|
-
if (!packageName) {
|
|
1074
|
-
return false;
|
|
1075
|
-
}
|
|
1076
|
-
|
|
1077
|
-
// Check if the package is globally linked by running npm ls -g --depth=0
|
|
1078
|
-
try {
|
|
1079
|
-
const { stdout } = await runSecure('npm', ['ls', '-g', '--depth=0', '--json']);
|
|
1080
|
-
const globalPackages = safeJsonParse(stdout, 'npm ls global depth check output');
|
|
1081
|
-
|
|
1082
|
-
// Check if our package is in the global dependencies
|
|
1083
|
-
if (globalPackages.dependencies && globalPackages.dependencies[packageName]) {
|
|
1084
|
-
// Verify the symlink actually points to our directory
|
|
1085
|
-
const globalPath = globalPackages.dependencies[packageName].resolved;
|
|
1086
|
-
if (globalPath && globalPath.startsWith('file:')) {
|
|
1087
|
-
const linkedPath = globalPath.replace('file:', '');
|
|
1088
|
-
const realPackageDir = await fs.realpath(packageDir);
|
|
1089
|
-
const realLinkedPath = await fs.realpath(linkedPath);
|
|
1090
|
-
return realPackageDir === realLinkedPath;
|
|
1091
|
-
}
|
|
1092
|
-
}
|
|
1093
|
-
} catch (error) {
|
|
1094
|
-
// If npm ls fails, try alternative approach
|
|
1095
|
-
logger.debug(`npm ls failed for ${packageName}, trying alternative check: ${error}`);
|
|
1096
|
-
|
|
1097
|
-
// Alternative: check if there's a symlink in npm's global node_modules
|
|
1098
|
-
try {
|
|
1099
|
-
const { stdout: npmPrefix } = await run('npm prefix -g');
|
|
1100
|
-
const globalNodeModules = path.join(npmPrefix.trim(), 'node_modules', packageName);
|
|
1101
|
-
|
|
1102
|
-
const stat = await fs.lstat(globalNodeModules);
|
|
1103
|
-
if (stat.isSymbolicLink()) {
|
|
1104
|
-
const realGlobalPath = await fs.realpath(globalNodeModules);
|
|
1105
|
-
const realPackageDir = await fs.realpath(packageDir);
|
|
1106
|
-
return realGlobalPath === realPackageDir;
|
|
1107
|
-
}
|
|
1108
|
-
} catch {
|
|
1109
|
-
// If all else fails, assume not linked
|
|
1110
|
-
return false;
|
|
1111
|
-
}
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
return false;
|
|
1115
|
-
} catch (error) {
|
|
1116
|
-
logger.debug(`Error checking npm link status for ${packageDir}: ${error}`);
|
|
1117
|
-
return false;
|
|
1118
|
-
}
|
|
1119
|
-
};
|
|
1120
|
-
|