๐Ÿ“ฆ juspay / workforge

๐Ÿ“„ ConfigManager.ts ยท 221 lines
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
221import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';
import * as path from 'path';
import * as os from 'os';
import { Config, ConfigValue, ConfigObject, ConfigPath } from '../types/index.js';

/**
 * Default configuration for WorkForge
 */
const DEFAULT_CONFIG: Config = {
  version: '3.0.0',
  preferences: {
    defaultBaseBranch: 'main',
    autoDeleteBranch: false,
    skipConfirmations: false,
    packageManager: 'auto',
    showExistingWorktrees: true
  },
  backup: {
    enabled: true,
    maxBackupsPerProject: 10,
    autoCleanup: true
  },
  sync: {
    createBackupBeforeSync: true,
    defaultSyncDirection: 'ask'
  },
  audit: {
    enabled: true,
    includeVariableValues: true,
    retentionDays: 90
  },
  display: {
    colorEnabled: true,
    verboseOutput: false,
    showProgressIndicators: true
  }
};

/**
 * Configuration Manager
 *
 * Handles loading, saving, and accessing configuration from ~/.workforge/config.json
 */
export class ConfigManager {
  private configPath: string;

  constructor() {
    this.configPath = path.join(os.homedir(), '.workforge', 'config.json');
  }

  /**
   * Load configuration, merging user config with defaults
   */
  load(): Config {
    if (!existsSync(this.configPath)) {
      return DEFAULT_CONFIG;
    }

    try {
      const userConfig = JSON.parse(readFileSync(this.configPath, 'utf8'));
      return this.merge(DEFAULT_CONFIG, userConfig);
    } catch (error) {
      console.warn(`Warning: Failed to load config from ${this.configPath}, using defaults`);
      return DEFAULT_CONFIG;
    }
  }

  /**
   * Save configuration to disk
   */
  save(config: Config): void {
    try {
      mkdirSync(path.dirname(this.configPath), { recursive: true });
      writeFileSync(this.configPath, JSON.stringify(config, null, 2), 'utf8');
    } catch (error) {
      throw new Error(`Failed to save config to ${this.configPath}: ${error}`);
    }
  }

  /**
   * Get a specific nested configuration value
   *
   * @param key - Dot-separated path (e.g., 'backup.maxBackupsPerProject')
   */
  get(key: ConfigPath): ConfigValue {
    const config = this.load();
    return this.getNestedValue(config, key);
  }

  /**
   * Set a specific nested configuration value
   *
   * @param key - Dot-separated path (e.g., 'backup.maxBackupsPerProject')
   * @param value - Value to set
   */
  set(key: ConfigPath, value: ConfigValue): void {
    const config = this.load();
    this.setNestedValue(config, key, value);
    this.save(config);
  }

  /**
   * Reset configuration to defaults
   */
  reset(): void {
    this.save(DEFAULT_CONFIG);
  }

  /**
   * Get the path to the config file
   */
  getConfigPath(): string {
    return this.configPath;
  }

  /**
   * Deep merge two configuration objects
   * User values override defaults
   */
  private merge(defaults: Config, user: Partial<Config>): Config {
    const result = { ...defaults };

    for (const key in user) {
      if (Object.prototype.hasOwnProperty.call(user, key)) {
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const userValue = (user as any)[key];
        // eslint-disable-next-line @typescript-eslint/no-explicit-any
        const defaultValue = (defaults as any)[key];

        if (
          typeof userValue === 'object' &&
          userValue !== null &&
          !Array.isArray(userValue) &&
          typeof defaultValue === 'object' &&
          defaultValue !== null &&
          !Array.isArray(defaultValue)
        ) {
          // Recursively merge objects
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (result as any)[key] = this.mergeObjects(defaultValue, userValue);
        } else {
          // Direct assignment for primitives and arrays
          // eslint-disable-next-line @typescript-eslint/no-explicit-any
          (result as any)[key] = userValue;
        }
      }
    }

    return result;
  }

  /**
   * Merge two objects recursively
   */
  private mergeObjects(obj1: ConfigObject, obj2: ConfigObject): ConfigObject {
    const result = { ...obj1 };

    for (const key in obj2) {
      if (Object.prototype.hasOwnProperty.call(obj2, key)) {
        const val2 = obj2[key];
        const val1 = obj1[key];

        if (
          typeof val2 === 'object' &&
          val2 !== null &&
          !Array.isArray(val2) &&
          typeof val1 === 'object' &&
          val1 !== null &&
          !Array.isArray(val1)
        ) {
          result[key] = this.mergeObjects(val1 as ConfigObject, val2 as ConfigObject);
        } else {
          result[key] = val2;
        }
      }
    }

    return result;
  }

  /**
   * Get value from nested path (e.g., 'backup.maxBackupsPerProject')
   */
  private getNestedValue(obj: ConfigObject, path: string): ConfigValue {
    const keys = path.split('.');
    let current: ConfigValue = obj;

    for (const key of keys) {
      if (current === null || current === undefined) {
        return undefined as unknown as ConfigValue;
      }
      if (typeof current === 'object' && !Array.isArray(current)) {
        current = (current as ConfigObject)[key];
      }
    }

    return current;
  }

  /**
   * Set value at nested path
   */
  private setNestedValue(obj: ConfigObject, path: string, value: ConfigValue): void {
    const keys = path.split('.');
    const lastKey = keys.pop()!;

    let current: ConfigObject = obj;
    for (const key of keys) {
      if (!(key in current)) {
        current[key] = {};
      }
      const next = current[key];
      if (typeof next === 'object' && !Array.isArray(next) && next !== null) {
        current = next as ConfigObject;
      }
    }

    current[lastKey] = value;
  }
}