dissolve-python 0.3.0

A tool to dissolve deprecated calls in Python codebases
Documentation
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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright (C) 2024 Jelmer Vernooij <jelmer@samba.org>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Configuration management for dissolve

use crate::domain_types::{ModuleName, Version};
use crate::error::{DissolveError, Result};
use crate::types::TypeIntrospectionMethod;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Main configuration structure
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Config {
    /// Type introspection method to use
    pub type_introspection: TypeIntrospectionMethod,

    /// Paths to scan for deprecated functions
    pub scan_paths: Vec<PathBuf>,

    /// Modules to exclude from scanning
    pub excluded_modules: Vec<ModuleName>,

    /// Whether to write changes back to files
    pub write_changes: bool,

    /// Whether to create backup files
    pub create_backups: bool,

    /// Current version for version-based removal
    pub current_version: Option<Version>,

    /// Timeout settings
    pub timeout: TimeoutConfig,

    /// Performance settings
    pub performance: PerformanceConfig,

    /// Output settings
    pub output: OutputConfig,
}

/// Timeout configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TimeoutConfig {
    /// Timeout for LSP operations in seconds
    pub lsp_timeout: u64,

    /// Timeout for file operations in seconds
    pub file_timeout: u64,

    /// Timeout for type introspection queries in seconds
    pub type_query_timeout: u64,
}

/// Performance configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceConfig {
    /// Number of parallel workers for file processing
    pub parallel_workers: usize,

    /// Whether to cache parsed ASTs
    pub cache_asts: bool,

    /// Whether to use string interning
    pub string_interning: bool,

    /// Maximum files to process in a single batch
    pub batch_size: usize,
}

/// Output configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct OutputConfig {
    /// Whether to show progress bars
    pub show_progress: bool,

    /// Verbosity level (0 = quiet, 1 = normal, 2 = verbose, 3 = debug)
    pub verbosity: u8,

    /// Whether to colorize output
    pub colorize: bool,

    /// Whether to show statistics at the end
    pub show_stats: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            type_introspection: TypeIntrospectionMethod::PyrightLsp,
            scan_paths: vec![PathBuf::from(".")],
            excluded_modules: vec![],
            write_changes: false,
            create_backups: true,
            current_version: None,
            timeout: TimeoutConfig::default(),
            performance: PerformanceConfig::default(),
            output: OutputConfig::default(),
        }
    }
}

impl Default for TimeoutConfig {
    fn default() -> Self {
        Self {
            lsp_timeout: 30,
            file_timeout: 10,
            type_query_timeout: 5,
        }
    }
}

impl Default for PerformanceConfig {
    fn default() -> Self {
        Self {
            parallel_workers: num_cpus::get(),
            cache_asts: true,
            string_interning: true,
            batch_size: 100,
        }
    }
}

impl Default for OutputConfig {
    fn default() -> Self {
        Self {
            show_progress: true,
            verbosity: 1,
            colorize: atty::is(atty::Stream::Stdout),
            show_stats: true,
        }
    }
}

impl Config {
    /// Create a new configuration with defaults
    pub fn new() -> Self {
        Self::default()
    }

    /// Load configuration from a file
    pub fn from_file<P: AsRef<Path>>(path: P) -> Result<Self> {
        let content = std::fs::read_to_string(&path).map_err(|e| {
            DissolveError::config_error(format!(
                "Failed to read config file {}: {}",
                path.as_ref().display(),
                e
            ))
        })?;

        let config: Config = if path.as_ref().extension().and_then(|s| s.to_str()) == Some("toml") {
            toml::from_str(&content).map_err(|e| {
                DissolveError::config_error(format!("Failed to parse TOML config: {}", e))
            })?
        } else {
            serde_json::from_str(&content).map_err(|e| {
                DissolveError::config_error(format!("Failed to parse JSON config: {}", e))
            })?
        };

        Ok(config)
    }

    /// Save configuration to a file
    pub fn save_to_file<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        let content = if path.as_ref().extension().and_then(|s| s.to_str()) == Some("toml") {
            toml::to_string_pretty(self).map_err(|e| {
                DissolveError::config_error(format!("Failed to serialize to TOML: {}", e))
            })?
        } else {
            serde_json::to_string_pretty(self).map_err(|e| {
                DissolveError::config_error(format!("Failed to serialize to JSON: {}", e))
            })?
        };

        std::fs::write(&path, content).map_err(|e| {
            DissolveError::config_error(format!(
                "Failed to write config file {}: {}",
                path.as_ref().display(),
                e
            ))
        })?;

        Ok(())
    }

    /// Load configuration from multiple sources with priority
    /// 1. Command line arguments (highest priority)
    /// 2. Environment variables
    /// 3. Configuration file
    /// 4. Defaults (lowest priority)
    pub fn load_merged(
        config_file: Option<&Path>,
        env_overrides: &HashMap<String, String>,
        cli_overrides: &CliOverrides,
    ) -> Result<Self> {
        let mut config = if let Some(config_path) = config_file {
            if config_path.exists() {
                Self::from_file(config_path)?
            } else {
                Self::default()
            }
        } else {
            Self::default()
        };

        // Apply environment variable overrides
        config.apply_env_overrides(env_overrides)?;

        // Apply CLI overrides (highest priority)
        config.apply_cli_overrides(cli_overrides);

        Ok(config)
    }

    /// Apply environment variable overrides
    fn apply_env_overrides(&mut self, env_vars: &HashMap<String, String>) -> Result<()> {
        if let Some(timeout) = env_vars.get("DISSOLVE_LSP_TIMEOUT") {
            self.timeout.lsp_timeout = timeout
                .parse()
                .map_err(|_| DissolveError::config_error("Invalid LSP timeout value"))?;
        }

        if let Some(workers) = env_vars.get("DISSOLVE_PARALLEL_WORKERS") {
            self.performance.parallel_workers = workers
                .parse()
                .map_err(|_| DissolveError::config_error("Invalid parallel workers value"))?;
        }

        if let Some(verbosity) = env_vars.get("DISSOLVE_VERBOSITY") {
            self.output.verbosity = verbosity
                .parse()
                .map_err(|_| DissolveError::config_error("Invalid verbosity value"))?;
        }

        Ok(())
    }

    /// Apply CLI overrides
    fn apply_cli_overrides(&mut self, overrides: &CliOverrides) {
        if let Some(type_method) = overrides.type_introspection {
            self.type_introspection = type_method;
        }

        if let Some(write) = overrides.write_changes {
            self.write_changes = write;
        }

        if let Some(verbosity) = overrides.verbosity {
            self.output.verbosity = verbosity;
        }

        if let Some(no_color) = overrides.no_color {
            self.output.colorize = !no_color;
        }
    }

    /// Validate the configuration
    pub fn validate(&self) -> Result<()> {
        if self.timeout.lsp_timeout == 0 {
            return Err(DissolveError::config_error(
                "LSP timeout must be greater than 0",
            ));
        }

        if self.performance.parallel_workers == 0 {
            return Err(DissolveError::config_error(
                "Parallel workers must be greater than 0",
            ));
        }

        if self.output.verbosity > 3 {
            return Err(DissolveError::config_error("Verbosity level must be 0-3"));
        }

        Ok(())
    }
}

/// CLI overrides for configuration
#[derive(Debug, Default)]
pub struct CliOverrides {
    pub type_introspection: Option<TypeIntrospectionMethod>,
    pub write_changes: Option<bool>,
    pub verbosity: Option<u8>,
    pub no_color: Option<bool>,
}

/// Configuration builder for programmatic configuration
pub struct ConfigBuilder {
    config: Config,
}

impl ConfigBuilder {
    pub fn new() -> Self {
        Self {
            config: Config::default(),
        }
    }

    pub fn type_introspection(mut self, method: TypeIntrospectionMethod) -> Self {
        self.config.type_introspection = method;
        self
    }

    pub fn scan_paths(mut self, paths: Vec<PathBuf>) -> Self {
        self.config.scan_paths = paths;
        self
    }

    pub fn write_changes(mut self, write: bool) -> Self {
        self.config.write_changes = write;
        self
    }

    pub fn current_version(mut self, version: Version) -> Self {
        self.config.current_version = Some(version);
        self
    }

    pub fn parallel_workers(mut self, workers: usize) -> Self {
        self.config.performance.parallel_workers = workers;
        self
    }

    pub fn verbosity(mut self, level: u8) -> Self {
        self.config.output.verbosity = level;
        self
    }

    pub fn build(self) -> Result<Config> {
        self.config.validate()?;
        Ok(self.config)
    }
}

impl Default for ConfigBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::TempDir;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(
            config.type_introspection,
            TypeIntrospectionMethod::PyrightLsp
        );
        assert!(!config.write_changes);
        assert!(config.create_backups);
    }

    #[test]
    fn test_config_builder() {
        let config = ConfigBuilder::new()
            .type_introspection(TypeIntrospectionMethod::MypyDaemon)
            .write_changes(true)
            .verbosity(2)
            .build()
            .unwrap();

        assert_eq!(
            config.type_introspection,
            TypeIntrospectionMethod::MypyDaemon
        );
        assert!(config.write_changes);
        assert_eq!(config.output.verbosity, 2);
    }

    #[test]
    fn test_config_file_operations() {
        let temp_dir = TempDir::new().unwrap();
        let config_path = temp_dir.path().join("test_config.json");

        let config = ConfigBuilder::new()
            .verbosity(3)
            .write_changes(true)
            .build()
            .unwrap();

        config.save_to_file(&config_path).unwrap();

        let loaded_config = Config::from_file(&config_path).unwrap();
        assert_eq!(loaded_config.output.verbosity, 3);
        assert!(loaded_config.write_changes);
    }

    #[test]
    fn test_config_validation() {
        let mut config = Config::default();
        config.timeout.lsp_timeout = 0;

        assert!(config.validate().is_err());
    }
}