1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335import { EnvFileParser } from './EnvFileParser.js';
import { EnvVariable, EnvDiff, EnvModification, SyncTargets, DiffSummary } from '../types/index.js';
import { existsSync } from 'fs';
/**
* Environment Differ
*
* Compares environment variables between two .env files and generates
* a structured diff showing:
* - Added variables (in source, not in target - will be added to target)
* - Removed variables (in target, not in source - will be removed from target)
* - Modified variables (in both, different values - target will be updated)
* - Unchanged variables (in both, same values)
*/
export class EnvDiffer {
private parser: EnvFileParser;
constructor() {
this.parser = new EnvFileParser();
}
/**
* Compare two .env files and generate diff
*
* @param sourcePath - Path to source .env file
* @param targetPath - Path to target .env file
* @param targets - Sync targets information (for context)
* @returns EnvDiff object with all changes
* @throws Error if files don't exist or can't be parsed
*/
compare(sourcePath: string, targetPath: string, targets: SyncTargets): EnvDiff {
// Validate files exist
if (!existsSync(sourcePath)) {
throw new Error(`Source .env file not found: ${sourcePath}`);
}
if (!existsSync(targetPath)) {
throw new Error(`Target .env file not found: ${targetPath}`);
}
// Parse both files
const sourceVars = this.parser.parse(sourcePath);
const targetVars = this.parser.parse(targetPath);
// Generate diff
return this.compareVariables(sourceVars, targetVars, targets);
}
/**
* Compare two sets of variables
*
* @param sourceVars - Variables from source
* @param targetVars - Variables from target
* @param targets - Sync targets information
* @returns EnvDiff object
*/
compareVariables(
sourceVars: Map<string, EnvVariable>,
targetVars: Map<string, EnvVariable>,
targets: SyncTargets
): EnvDiff {
const added: EnvVariable[] = [];
const removed: EnvVariable[] = [];
const modified: EnvModification[] = [];
const unchanged: EnvVariable[] = [];
const sourceKeys = new Set(sourceVars.keys());
const targetKeys = new Set(targetVars.keys());
// Find added variables (in source, not in target - will be added to target)
for (const key of sourceKeys) {
if (!targetKeys.has(key)) {
const sourceVar = sourceVars.get(key)!;
added.push(sourceVar);
}
}
// Find removed variables (in target, not in source - will be removed from target)
for (const key of targetKeys) {
if (!sourceKeys.has(key)) {
const targetVar = targetVars.get(key)!;
removed.push(targetVar);
}
}
// Find modified and unchanged variables (in both)
for (const key of sourceKeys) {
if (targetKeys.has(key)) {
const sourceVar = sourceVars.get(key)!;
const targetVar = targetVars.get(key)!;
if (this.areVariablesEqual(sourceVar, targetVar)) {
// Unchanged
unchanged.push(sourceVar);
} else {
// Modified - show current target value as old, source value as new
modified.push({
key,
oldValue: targetVar.value, // Current value in target
newValue: sourceVar.value, // New value from source
oldLineNumber: targetVar.lineNumber,
newLineNumber: sourceVar.lineNumber,
oldComment: targetVar.comment,
newComment: sourceVar.comment,
oldHasQuotes: targetVar.hasQuotes,
newHasQuotes: sourceVar.hasQuotes,
oldQuoteType: targetVar.quoteType,
newQuoteType: sourceVar.quoteType
});
}
}
}
// Sort by key name for consistent display
added.sort((a, b) => a.key.localeCompare(b.key));
removed.sort((a, b) => a.key.localeCompare(b.key));
modified.sort((a, b) => a.key.localeCompare(b.key));
unchanged.sort((a, b) => a.key.localeCompare(b.key));
return {
added,
removed,
modified,
unchanged,
targets
};
}
/**
* Check if two variables are equal
*
* Variables are considered equal if:
* - They have the same key (already guaranteed by caller)
* - They have the same value
*
* Note: Comments, quotes, and line numbers are NOT considered for equality.
* Only the actual variable value matters.
*
* @param var1 - First variable
* @param var2 - Second variable
* @returns True if variables are equal
*/
private areVariablesEqual(var1: EnvVariable, var2: EnvVariable): boolean {
return var1.value === var2.value;
}
/**
* Get summary statistics for a diff
*
* @param diff - EnvDiff object
* @returns Summary object with counts
*/
getSummary(diff: EnvDiff): DiffSummary {
const addedCount = diff.added.length;
const removedCount = diff.removed.length;
const modifiedCount = diff.modified.length;
const unchangedCount = diff.unchanged.length;
const totalChanges = addedCount + removedCount + modifiedCount;
return {
addedCount,
removedCount,
modifiedCount,
unchangedCount,
totalChanges,
hasChanges: totalChanges > 0
};
}
/**
* Check if diff is empty (no changes)
*
* @param diff - EnvDiff object
* @returns True if no changes
*/
isEmpty(diff: EnvDiff): boolean {
return (
diff.added.length === 0 &&
diff.removed.length === 0 &&
diff.modified.length === 0
);
}
/**
* Filter diff to only include specified keys
*
* Useful for interactive selection where user chooses which variables to sync
*
* @param diff - Original diff
* @param selectedKeys - Set of keys to include
* @returns Filtered diff
*/
filterDiff(diff: EnvDiff, selectedKeys: Set<string>): EnvDiff {
return {
added: diff.added.filter(v => selectedKeys.has(v.key)),
removed: diff.removed.filter(v => selectedKeys.has(v.key)),
modified: diff.modified.filter(m => selectedKeys.has(m.key)),
unchanged: diff.unchanged, // Keep all unchanged
targets: diff.targets
};
}
/**
* Merge multiple diffs into one
*
* Useful when syncing between multiple worktrees
*
* @param diffs - Array of diffs to merge
* @returns Merged diff
*/
mergeDiffs(diffs: EnvDiff[]): EnvDiff | null {
if (diffs.length === 0) {
return null;
}
if (diffs.length === 1) {
return diffs[0];
}
const allAdded = new Map<string, EnvVariable>();
const allRemoved = new Map<string, EnvVariable>();
const allModified = new Map<string, EnvModification>();
const allUnchanged = new Map<string, EnvVariable>();
for (const diff of diffs) {
// Merge added
for (const variable of diff.added) {
if (!allAdded.has(variable.key)) {
allAdded.set(variable.key, variable);
}
}
// Merge removed
for (const variable of diff.removed) {
if (!allRemoved.has(variable.key)) {
allRemoved.set(variable.key, variable);
}
}
// Merge modified
for (const modification of diff.modified) {
if (!allModified.has(modification.key)) {
allModified.set(modification.key, modification);
}
}
// Merge unchanged
for (const variable of diff.unchanged) {
if (!allUnchanged.has(variable.key)) {
allUnchanged.set(variable.key, variable);
}
}
}
// Use targets from first diff
const targets = diffs[0].targets;
return {
added: Array.from(allAdded.values()).sort((a, b) => a.key.localeCompare(b.key)),
removed: Array.from(allRemoved.values()).sort((a, b) => a.key.localeCompare(b.key)),
modified: Array.from(allModified.values()).sort((a, b) => a.key.localeCompare(b.key)),
unchanged: Array.from(allUnchanged.values()).sort((a, b) => a.key.localeCompare(b.key)),
targets
};
}
/**
* Invert a diff (swap source and target)
*
* Useful for bidirectional sync where user can choose direction
*
* @param diff - Original diff
* @returns Inverted diff
*/
invertDiff(diff: EnvDiff): EnvDiff {
return {
added: diff.removed, // What was removed becomes added
removed: diff.added, // What was added becomes removed
modified: diff.modified.map(m => ({
key: m.key,
oldValue: m.newValue, // Swap old and new
newValue: m.oldValue,
oldLineNumber: m.newLineNumber,
newLineNumber: m.oldLineNumber,
oldComment: m.newComment,
newComment: m.oldComment,
oldHasQuotes: m.newHasQuotes,
newHasQuotes: m.oldHasQuotes,
oldQuoteType: m.newQuoteType,
newQuoteType: m.oldQuoteType
})),
unchanged: diff.unchanged,
targets: diff.targets ? {
sourceLabel: diff.targets.targetLabel, // Swap labels
targetLabel: diff.targets.sourceLabel,
sourcePath: diff.targets.targetPath,
targetPath: diff.targets.sourcePath
} : undefined
};
}
/**
* Get all variable keys from a diff
*
* @param diff - EnvDiff object
* @returns Set of all keys
*/
getAllKeys(diff: EnvDiff): Set<string> {
const keys = new Set<string>();
diff.added.forEach(v => keys.add(v.key));
diff.removed.forEach(v => keys.add(v.key));
diff.modified.forEach(m => keys.add(m.key));
diff.unchanged.forEach(v => keys.add(v.key));
return keys;
}
/**
* Get only changed variable keys from a diff
*
* @param diff - EnvDiff object
* @returns Set of changed keys
*/
getChangedKeys(diff: EnvDiff): Set<string> {
const keys = new Set<string>();
diff.added.forEach(v => keys.add(v.key));
diff.removed.forEach(v => keys.add(v.key));
diff.modified.forEach(m => keys.add(m.key));
return keys;
}
}