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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// 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.

//! Builder patterns for creating complex dissolve operations

use crate::config::Config;
use crate::core::{CollectorResult, ReplaceInfo};
use crate::domain_types::{ModuleName, QualifiedName, Version};
use crate::error::{DissolveError, Result};
use crate::performance::PerformanceMonitor;
use crate::type_introspection_context::TypeIntrospectionContext;
use crate::types::TypeIntrospectionMethod;
use std::collections::HashMap;
use std::path::{Path, PathBuf};

/// Builder for migration operations
pub struct MigrationBuilder {
    config: Config,
    replacements: HashMap<QualifiedName, ReplaceInfo>,
    source_paths: Vec<PathBuf>,
    target_module: Option<ModuleName>,
    performance_monitor: Option<PerformanceMonitor>,
}

impl MigrationBuilder {
    /// Create a new migration builder
    pub fn new() -> Self {
        Self {
            config: Config::default(),
            replacements: HashMap::new(),
            source_paths: Vec::new(),
            target_module: None,
            performance_monitor: None,
        }
    }

    /// Set the configuration
    pub fn with_config(mut self, config: Config) -> Self {
        self.config = config;
        self
    }

    /// Set the type introspection method
    pub fn with_type_introspection(mut self, method: TypeIntrospectionMethod) -> Self {
        self.config.type_introspection = method;
        self
    }

    /// Add source paths to process
    pub fn with_sources<P: AsRef<Path>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
        self.source_paths
            .extend(paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    /// Add a single source path
    pub fn with_source<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.source_paths.push(path.as_ref().to_path_buf());
        self
    }

    /// Set the target module for replacements
    pub fn with_target_module(mut self, module: ModuleName) -> Self {
        self.target_module = Some(module);
        self
    }

    /// Add replacement info
    pub fn with_replacement(mut self, qualified_name: QualifiedName, info: ReplaceInfo) -> Self {
        self.replacements.insert(qualified_name, info);
        self
    }

    /// Add multiple replacements from a collector result
    pub fn with_replacements_from_collector(mut self, collector_result: CollectorResult) -> Self {
        for (name, info) in collector_result.replacements {
            if let Ok(qualified_name) = QualifiedName::from_string(&name) {
                self.replacements.insert(qualified_name, info);
            }
        }
        self
    }

    /// Enable performance monitoring
    pub fn with_performance_monitoring(mut self, enable: bool) -> Self {
        if enable {
            self.performance_monitor = Some(PerformanceMonitor::new(
                self.config.performance.batch_size,
                1000, // Default type cache size
            ));
        } else {
            self.performance_monitor = None;
        }
        self
    }

    /// Enable writing changes to files
    pub fn write_changes(mut self, write: bool) -> Self {
        self.config.write_changes = write;
        self
    }

    /// Set current version for version-based operations
    pub fn with_current_version(mut self, version: Version) -> Self {
        self.config.current_version = Some(version);
        self
    }

    /// Build and execute the migration
    pub fn execute(self) -> Result<MigrationResult> {
        self.validate()?;

        let mut type_context = TypeIntrospectionContext::new(self.config.type_introspection)
            .map_err(|e| {
                DissolveError::internal(format!("Failed to create type context: {}", e))
            })?;
        let mut results = MigrationResult::new();

        // Process each source path
        for source_path in &self.source_paths {
            if source_path.is_file() {
                let result = self.process_file(source_path, &mut type_context)?;
                results.merge(result);
            } else if source_path.is_dir() {
                let result = self.process_directory(source_path, &mut type_context)?;
                results.merge(result);
            } else {
                return Err(DissolveError::invalid_input(format!(
                    "Path does not exist: {}",
                    source_path.display()
                )));
            }
        }

        type_context.shutdown().map_err(|e| {
            DissolveError::internal(format!("Failed to shutdown type context: {}", e))
        })?;

        // Add performance summary if monitoring was enabled
        if let Some(monitor) = &self.performance_monitor {
            results.performance_summary = Some(monitor.summary());
        }

        Ok(results)
    }

    /// Validate the builder configuration
    fn validate(&self) -> Result<()> {
        if self.source_paths.is_empty() {
            return Err(DissolveError::invalid_input("No source paths specified"));
        }

        if self.replacements.is_empty() {
            return Err(DissolveError::invalid_input("No replacements specified"));
        }

        self.config.validate()?;
        Ok(())
    }

    /// Process a single file
    fn process_file(
        &self,
        file_path: &Path,
        type_context: &mut TypeIntrospectionContext,
    ) -> Result<MigrationResult> {
        let source = std::fs::read_to_string(file_path)?;
        let module_name = self.detect_module_name(file_path)?;

        let start = std::time::Instant::now();

        // Use the migration logic from existing modules
        let replacements_map: HashMap<String, ReplaceInfo> = self
            .replacements
            .iter()
            .map(|(k, v)| (k.to_string(), v.clone()))
            .collect();

        let migrated_source = crate::migrate_stub::migrate_file(
            &source,
            &module_name.to_string(),
            file_path,
            type_context,
            replacements_map,
            HashMap::new(), // Empty unreplaceable map
        )
        .map_err(|e| DissolveError::internal(format!("Migration failed: {}", e)))?;

        let elapsed = start.elapsed();

        if let Some(monitor) = &self.performance_monitor {
            monitor.record_file_processed();
            monitor.record_migration_time(elapsed);
        }

        let mut result = MigrationResult::new();
        result.files_processed.push(FileResult {
            path: file_path.to_path_buf(),
            original_size: source.len(),
            migrated_size: migrated_source.len(),
            processing_time: elapsed,
            changes_made: source != migrated_source,
        });

        if self.config.write_changes && source != migrated_source {
            if self.config.create_backups {
                let backup_path = format!("{}.bak", file_path.display());
                std::fs::copy(file_path, &backup_path)?;
                result.backups_created.push(PathBuf::from(backup_path));
            }

            std::fs::write(file_path, &migrated_source)?;
            result.files_written += 1;
        }

        Ok(result)
    }

    /// Process a directory recursively
    fn process_directory(
        &self,
        dir_path: &Path,
        type_context: &mut TypeIntrospectionContext,
    ) -> Result<MigrationResult> {
        let mut results = MigrationResult::new();

        for entry in walkdir::WalkDir::new(dir_path) {
            let entry = entry.map_err(|e| DissolveError::Io(e.into()))?;
            let path = entry.path();

            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("py") {
                // Check if this module should be excluded
                if let Ok(module_name) = self.detect_module_name(path) {
                    if self.config.excluded_modules.contains(&module_name) {
                        continue;
                    }
                }

                let file_result = self.process_file(path, type_context)?;
                results.merge(file_result);
            }
        }

        Ok(results)
    }

    /// Detect module name from file path
    fn detect_module_name(&self, file_path: &Path) -> Result<ModuleName> {
        // Simple implementation - in practice this would be more sophisticated
        let stem = file_path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| DissolveError::invalid_input("Invalid file path"))?;

        if stem == "__init__" {
            // Use parent directory name
            let parent = file_path
                .parent()
                .and_then(|p| p.file_name())
                .and_then(|n| n.to_str())
                .ok_or_else(|| DissolveError::invalid_input("Cannot determine module name"))?;
            Ok(ModuleName::new(parent))
        } else {
            Ok(ModuleName::new(stem))
        }
    }
}

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

/// Builder for collection operations (finding deprecated functions)
pub struct CollectionBuilder {
    config: Config,
    source_paths: Vec<PathBuf>,
    target_modules: Vec<ModuleName>,
}

impl CollectionBuilder {
    pub fn new() -> Self {
        Self {
            config: Config::default(),
            source_paths: Vec::new(),
            target_modules: Vec::new(),
        }
    }

    pub fn with_config(mut self, config: Config) -> Self {
        self.config = config;
        self
    }

    pub fn with_sources<P: AsRef<Path>>(mut self, paths: impl IntoIterator<Item = P>) -> Self {
        self.source_paths
            .extend(paths.into_iter().map(|p| p.as_ref().to_path_buf()));
        self
    }

    pub fn with_target_modules(mut self, modules: impl IntoIterator<Item = ModuleName>) -> Self {
        self.target_modules.extend(modules);
        self
    }

    pub fn execute(self) -> Result<CollectorResult> {
        self.validate()?;

        let mut all_replacements = HashMap::new();
        let mut all_unreplaceable = HashMap::new();
        let mut all_imports = Vec::new();

        for source_path in &self.source_paths {
            if source_path.is_file() {
                let result = self.collect_from_file(source_path)?;
                all_replacements.extend(result.replacements);
                all_unreplaceable.extend(result.unreplaceable);
                all_imports.extend(result.imports);
            } else if source_path.is_dir() {
                let result = self.collect_from_directory(source_path)?;
                all_replacements.extend(result.replacements);
                all_unreplaceable.extend(result.unreplaceable);
                all_imports.extend(result.imports);
            }
        }

        Ok(CollectorResult {
            replacements: all_replacements,
            unreplaceable: all_unreplaceable,
            imports: all_imports,
            class_methods: HashMap::new(),
            inheritance_map: HashMap::new(),
        })
    }

    fn validate(&self) -> Result<()> {
        if self.source_paths.is_empty() {
            return Err(DissolveError::invalid_input("No source paths specified"));
        }
        Ok(())
    }

    fn collect_from_file(&self, file_path: &Path) -> Result<CollectorResult> {
        let source = std::fs::read_to_string(file_path)?;
        let module_name = self.detect_module_name(file_path)?;

        // Use existing collector
        let collector = crate::stub_collector::RuffDeprecatedFunctionCollector::new(
            module_name.to_string(),
            None,
        );

        collector
            .collect_from_source(source)
            .map_err(|e| DissolveError::internal(format!("Collection failed: {}", e)))
    }

    fn collect_from_directory(&self, dir_path: &Path) -> Result<CollectorResult> {
        let mut all_replacements = HashMap::new();
        let mut all_unreplaceable = HashMap::new();
        let mut all_imports = Vec::new();

        for entry in walkdir::WalkDir::new(dir_path) {
            let entry = entry.map_err(|e| DissolveError::Io(e.into()))?;
            let path = entry.path();

            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("py") {
                let result = self.collect_from_file(path)?;
                all_replacements.extend(result.replacements);
                all_unreplaceable.extend(result.unreplaceable);
                all_imports.extend(result.imports);
            }
        }

        Ok(CollectorResult {
            replacements: all_replacements,
            unreplaceable: all_unreplaceable,
            imports: all_imports,
            class_methods: HashMap::new(),
            inheritance_map: HashMap::new(),
        })
    }

    fn detect_module_name(&self, file_path: &Path) -> Result<ModuleName> {
        let stem = file_path
            .file_stem()
            .and_then(|s| s.to_str())
            .ok_or_else(|| DissolveError::invalid_input("Invalid file path"))?;
        Ok(ModuleName::new(stem))
    }
}

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

/// Result of a migration operation
#[derive(Debug)]
pub struct MigrationResult {
    pub files_processed: Vec<FileResult>,
    pub files_written: usize,
    pub backups_created: Vec<PathBuf>,
    pub performance_summary: Option<crate::performance::PerformanceSummary>,
}

impl MigrationResult {
    pub fn new() -> Self {
        Self {
            files_processed: Vec::new(),
            files_written: 0,
            backups_created: Vec::new(),
            performance_summary: None,
        }
    }

    pub fn merge(&mut self, other: MigrationResult) {
        self.files_processed.extend(other.files_processed);
        self.files_written += other.files_written;
        self.backups_created.extend(other.backups_created);
        // Performance summary would be combined differently in a real implementation
    }

    pub fn total_files(&self) -> usize {
        self.files_processed.len()
    }

    pub fn files_with_changes(&self) -> usize {
        self.files_processed
            .iter()
            .filter(|f| f.changes_made)
            .count()
    }

    pub fn total_processing_time(&self) -> std::time::Duration {
        self.files_processed.iter().map(|f| f.processing_time).sum()
    }
}

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

#[derive(Debug)]
pub struct FileResult {
    pub path: PathBuf,
    pub original_size: usize,
    pub migrated_size: usize,
    pub processing_time: std::time::Duration,
    pub changes_made: bool,
}

impl std::fmt::Display for MigrationResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        writeln!(f, "Migration Results:")?;
        writeln!(f, "  Files processed: {}", self.total_files())?;
        writeln!(f, "  Files with changes: {}", self.files_with_changes())?;
        writeln!(f, "  Files written: {}", self.files_written)?;
        writeln!(f, "  Backups created: {}", self.backups_created.len())?;
        writeln!(
            f,
            "  Total processing time: {:.2?}",
            self.total_processing_time()
        )?;

        if let Some(perf) = &self.performance_summary {
            write!(f, "\n{}", perf)?;
        }

        Ok(())
    }
}

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

    #[test]
    fn test_migration_builder() {
        let builder = MigrationBuilder::new()
            .with_type_introspection(TypeIntrospectionMethod::MypyDaemon)
            .write_changes(false)
            .with_performance_monitoring(true);

        // Validation should fail because no sources or replacements
        assert!(builder.validate().is_err());
    }

    #[test]
    fn test_collection_builder() {
        let temp_dir = TempDir::new().unwrap();
        let test_file = temp_dir.path().join("test.py");
        std::fs::write(&test_file, "# empty file").unwrap();

        let builder = CollectionBuilder::new().with_sources(vec![test_file]);

        assert!(builder.validate().is_ok());
    }

    #[test]
    fn test_migration_result_display() {
        let mut result = MigrationResult::new();
        result.files_processed.push(FileResult {
            path: PathBuf::from("test.py"),
            original_size: 100,
            migrated_size: 95,
            processing_time: std::time::Duration::from_millis(10),
            changes_made: true,
        });
        result.files_written = 1;

        let display = format!("{}", result);
        assert!(display.contains("Files processed: 1"));
        assert!(display.contains("Files with changes: 1"));
    }
}