File size: 1,443 Bytes
1dbc34b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Shared settings utility functions
 */

export interface WorktreeSelection {
  path: string | null;
  branch: string;
}

/**
 * Check whether an unknown value is a valid worktree selection.
 */
export function isValidWorktreeSelection(value: unknown): value is WorktreeSelection {
  if (typeof value !== 'object' || value === null) {
    return false;
  }

  const entry = value as Record<string, unknown>;
  const branch = entry.branch;
  const path = entry.path;

  if (typeof branch !== 'string' || branch.trim().length === 0) {
    return false;
  }

  if (path === null) {
    return true;
  }

  return typeof path === 'string' && path.trim().length > 0;
}

/**
 * Validate and sanitize currentWorktreeByProject entries.
 *
 * Keeps all valid entries (both main branch and feature worktrees).
 * The validation against actual worktrees happens in use-worktrees.ts
 * which resets to main branch if the selected worktree no longer exists.
 *
 * Only drops entries with invalid structure (not an object, missing/invalid
 * path or branch).
 */
export function sanitizeWorktreeByProject(
  raw: Record<string, unknown> | undefined
): Record<string, WorktreeSelection> {
  if (!raw) return {};
  const sanitized: Record<string, WorktreeSelection> = {};
  for (const [projectPath, worktree] of Object.entries(raw)) {
    if (isValidWorktreeSelection(worktree)) {
      sanitized[projectPath] = worktree;
    }
  }
  return sanitized;
}