@eldrforge/git-tools 0.1.1

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