@eldrforge/git-tools 0.1.7 → 0.1.9

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