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
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353import * as path from 'path';
import { existsSync } from 'fs';
import { WorktreeResolver } from './WorktreeResolver.js';
import { SyncTargets, SyncEnvOptions, ResolvedPath, ValidationResult } from '../types/index.js';
/**
* Sync Target Resolver
*
* Resolves source and target for environment sync operations:
* - Pattern 1: --from and --to (explicit source and target)
* - Pattern 2: --from only (to = main repo)
* - Pattern 3: --to only (from = main repo)
* - Pattern 4: --between (bidirectional, let user choose direction)
* - Auto-detection: Detect from current directory if no flags
*/
export class SyncTargetResolver {
private worktreeResolver: WorktreeResolver;
constructor() {
this.worktreeResolver = new WorktreeResolver();
}
/**
* Resolve sync targets from options
*
* @param options - Sync-env command options
* @returns SyncTargets with source and target information
* @throws Error if targets cannot be resolved or .env files don't exist
*/
async resolve(options: SyncEnvOptions): Promise<SyncTargets> {
// Pattern 4: Bidirectional sync (--between)
if (options.between) {
return this.resolveBidirectional(options.between);
}
// Pattern 1: Both --from and --to
if (options.from && options.to) {
return this.resolveBoth(options.from, options.to);
}
// Pattern 2: Only --from (target is main repo)
if (options.from && !options.to) {
return this.resolveFromOnly(options.from);
}
// Pattern 3: Only --to (source is main repo)
if (!options.from && options.to) {
return this.resolveToOnly(options.to);
}
// Auto-detection: Detect from current directory
return this.autoDetect();
}
/**
* Resolve bidirectional sync
*
* @param between - Worktree name/path for bidirectional sync
* @returns SyncTargets (source and target will be swappable)
*/
private async resolveBidirectional(between: string): Promise<SyncTargets> {
// Resolve the worktree
const worktree = await this.worktreeResolver.resolve(between);
// Get main repository
const mainRepo = await this.worktreeResolver.getMainRepo(worktree.path);
// Build paths
const worktreeEnvPath = path.join(worktree.path, '.env');
const mainEnvPath = path.join(mainRepo, '.env');
// Validate files exist
if (!existsSync(worktreeEnvPath)) {
throw new Error(`Environment file not found: ${worktreeEnvPath}`);
}
if (!existsSync(mainEnvPath)) {
throw new Error(`Environment file not found: ${mainEnvPath}`);
}
// Return targets (direction will be chosen interactively)
return {
sourceLabel: `Main (${path.basename(mainRepo)})`,
targetLabel: `Worktree (${worktree.branchName})`,
sourcePath: mainEnvPath,
targetPath: worktreeEnvPath
};
}
/**
* Resolve both --from and --to
*
* @param from - Source worktree name/path
* @param to - Target worktree name/path
* @returns SyncTargets
*/
private async resolveBoth(from: string, to: string): Promise<SyncTargets> {
// Resolve source (try worktree first, fall back to direct path)
const source = await this.resolvePathFlexibly(from);
if (!existsSync(source.envPath)) {
throw new Error(`Source environment file not found: ${source.envPath}`);
}
// Resolve target (try worktree first, fall back to direct path)
const target = await this.resolvePathFlexibly(to);
if (!existsSync(target.envPath)) {
throw new Error(`Target environment file not found: ${target.envPath}`);
}
return {
sourceLabel: source.label,
targetLabel: target.label,
sourcePath: source.envPath,
targetPath: target.envPath
};
}
/**
* Resolve --from only (target is current location)
*
* @param from - Source worktree name/path
* @returns SyncTargets
*/
private async resolveFromOnly(from: string): Promise<SyncTargets> {
// Resolve source (try worktree first, fall back to direct path)
const source = await this.resolvePathFlexibly(from);
if (!existsSync(source.envPath)) {
throw new Error(`Source environment file not found: ${source.envPath}`);
}
// Get current location as target
try {
const currentWorktree = await this.worktreeResolver.resolve();
// Use the current worktree path directly, not the main repo
const targetEnvPath = path.join(currentWorktree.path, '.env');
if (!existsSync(targetEnvPath)) {
throw new Error(`Target environment file not found: ${targetEnvPath}`);
}
return {
sourceLabel: source.label,
targetLabel: currentWorktree.isMainRepo
? `Main (${path.basename(currentWorktree.path)})`
: `Worktree (${currentWorktree.branchName})`,
sourcePath: source.envPath,
targetPath: targetEnvPath
};
} catch (error) {
// If we can't detect current location, use current directory
const cwd = process.cwd();
const targetEnvPath = path.join(cwd, '.env');
if (!existsSync(targetEnvPath)) {
throw new Error(`Target environment file not found: ${targetEnvPath}`);
}
return {
sourceLabel: source.label,
targetLabel: `Current (${path.basename(cwd)})`,
sourcePath: source.envPath,
targetPath: targetEnvPath
};
}
}
/**
* Resolve --to only (source is current location)
*
* @param to - Target worktree name/path
* @returns SyncTargets
*/
private async resolveToOnly(to: string): Promise<SyncTargets> {
// Resolve target (try worktree first, fall back to direct path)
const target = await this.resolvePathFlexibly(to);
if (!existsSync(target.envPath)) {
throw new Error(`Target environment file not found: ${target.envPath}`);
}
// Get current location as source (use current worktree/repo, not main repo)
try {
const currentWorktree = await this.worktreeResolver.resolve();
// Use the current worktree path directly, not the main repo
const sourceEnvPath = path.join(currentWorktree.path, '.env');
if (!existsSync(sourceEnvPath)) {
throw new Error(`Source environment file not found: ${sourceEnvPath}`);
}
return {
sourceLabel: currentWorktree.isMainRepo
? `Main (${path.basename(currentWorktree.path)})`
: `Worktree (${currentWorktree.branchName})`,
targetLabel: target.label,
sourcePath: sourceEnvPath,
targetPath: target.envPath
};
} catch (error) {
// If we can't detect current location, use current directory
const cwd = process.cwd();
const sourceEnvPath = path.join(cwd, '.env');
if (!existsSync(sourceEnvPath)) {
throw new Error(`Source environment file not found: ${sourceEnvPath}`);
}
return {
sourceLabel: `Current (${path.basename(cwd)})`,
targetLabel: target.label,
sourcePath: sourceEnvPath,
targetPath: target.envPath
};
}
}
/**
* Auto-detect from current directory
*
* If in worktree: sync from main to worktree
* If in main repo: error (need to specify target)
*
* @returns SyncTargets
*/
private async autoDetect(): Promise<SyncTargets> {
// Try to detect current worktree
const worktree = await this.worktreeResolver.resolve();
// If we're in main repo, we need explicit target
if (worktree.isMainRepo) {
throw new Error(
'Cannot auto-detect sync target from main repository. Use --to to specify target worktree.'
);
}
// We're in a worktree - sync from main to current worktree
const mainRepo = await this.worktreeResolver.getMainRepo(worktree.path);
const sourceEnvPath = path.join(mainRepo, '.env');
const targetEnvPath = path.join(worktree.path, '.env');
// Validate files exist
if (!existsSync(sourceEnvPath)) {
throw new Error(`Source environment file not found: ${sourceEnvPath}`);
}
if (!existsSync(targetEnvPath)) {
throw new Error(`Target environment file not found: ${targetEnvPath}`);
}
return {
sourceLabel: `Main (${path.basename(mainRepo)})`,
targetLabel: `Worktree (${worktree.branchName})`,
sourcePath: sourceEnvPath,
targetPath: targetEnvPath
};
}
/**
* Flexibly resolve a path - try as worktree first, then as direct path
*
* @param input - Path or worktree name
* @returns Object with label and envPath
*/
private async resolvePathFlexibly(input: string): Promise<ResolvedPath> {
try {
// Try to resolve as worktree first
const worktree = await this.worktreeResolver.resolve(input);
return {
label: worktree.isMainRepo
? `Main (${path.basename(worktree.path)})`
: `Worktree (${worktree.branchName})`,
envPath: path.join(worktree.path, '.env'),
repoPath: worktree.path
};
} catch (error) {
// If worktree resolution fails, treat as direct path
const absolutePath = path.resolve(input);
if (!existsSync(absolutePath)) {
throw new Error(`Path not found: ${absolutePath}`);
}
// Check if it's a git repository
const gitPath = path.join(absolutePath, '.git');
const isRepo = existsSync(gitPath);
return {
label: isRepo ? `Repository (${path.basename(absolutePath)})` : `Path (${path.basename(absolutePath)})`,
envPath: path.join(absolutePath, '.env'),
repoPath: absolutePath
};
}
}
/**
* Validate sync targets
*
* Ensures source and target are different
*
* @param targets - Sync targets to validate
* @returns Validation result
*/
validate(targets: SyncTargets): ValidationResult {
// Normalize paths for comparison (resolve symlinks, relative paths, etc.)
const normalizedSource = path.resolve(targets.sourcePath);
const normalizedTarget = path.resolve(targets.targetPath);
// Check if source and target are the same
if (normalizedSource === normalizedTarget) {
return {
valid: false,
errors: ['Source and target cannot be the same']
};
}
// Check if files exist
if (!existsSync(targets.sourcePath)) {
return {
valid: false,
errors: [`Source file not found: ${targets.sourcePath}`]
};
}
if (!existsSync(targets.targetPath)) {
return {
valid: false,
errors: [`Target file not found: ${targets.targetPath}`]
};
}
return { valid: true };
}
/**
* Swap source and target (for bidirectional sync direction change)
*
* @param targets - Original targets
* @returns Swapped targets
*/
swap(targets: SyncTargets): SyncTargets {
return {
sourceLabel: targets.targetLabel,
targetLabel: targets.sourceLabel,
sourcePath: targets.targetPath,
targetPath: targets.sourcePath
};
}
}