ai-refactor-cli 0.2.0

Rule-based legacy code refactoring CLI (TypeScript any / Python typing / Django FBV→CBV). Complement to general AI coding agents.
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
//! Django FBV → CBV transformation (v0.2.0 demo rule).
//!
//! **Detection**: finds top-level function-based Django views
//! (functions whose first positional parameter is bare `request`).
//!
//! **Apply**: rewrites a "typical" FBV to a class-based view:
//!
//! ```python
//! # Before
//! def my_view(request):
//!     return HttpResponse("hello")
//!
//! # After
//! class MyView(View):
//!     def get(self, request):
//!         return HttpResponse("hello")
//! ```
//!
//! Scope of the automatic rewrite in v0.2.0:
//! - Only top-level single-method FBVs (GET-only pattern).
//! - Multi-method dispatch (`if request.method == "POST"`) is detected
//!   but not rewritten automatically — a warning is emitted instead.
//! - Decorators are preserved on the generated class.
//! - Extra URL parameters after `request` are preserved.

use anyhow::{Context, Result};
use tree_sitter::{Node, Parser};

use crate::scanner::Finding;

// ── Public API ───────────────────────────────────────────────────────────────

/// Detect FBV patterns in `source`.  Returns one [`Finding`] per FBV function.
pub fn detect(file: &str, source: &[u8], parser: &mut Parser) -> Result<Vec<Finding>> {
    crate::ast::python::detect_django_fbv(file, source, parser)
}

/// Rewrite FBV patterns in `path` to CBV in-place.
///
/// Steps:
/// 1. Read the file.
/// 2. Parse with tree-sitter.
/// 3. Collect all top-level FBV spans.
/// 4. Write `<path>.bak` backup.
/// 5. Apply rewrites from bottom to top (preserving byte offsets).
/// 6. Write the modified source back to `path`.
///
/// Returns a list of human-readable descriptions of each rewrite performed,
/// plus warnings for FBVs that could not be automatically converted.
pub fn apply(path: &str, parser: &mut Parser) -> Result<ApplyResult> {
    let source = std::fs::read(path).with_context(|| format!("cannot read {}", path))?;

    let tree = parser
        .parse(&source, None)
        .ok_or_else(|| anyhow::anyhow!("tree-sitter failed to parse {}", path))?;

    let mut rewrites: Vec<Rewrite> = Vec::new();
    let mut warnings: Vec<String> = Vec::new();

    let root = tree.root_node();
    let mut cursor = root.walk();
    for child in root.children(&mut cursor) {
        match child.kind() {
            "function_definition" => {
                if let Some(rw) = plan_rewrite(child, &source, &mut warnings) {
                    rewrites.push(rw);
                }
            }
            "decorated_definition" => {
                let decorators = collect_decorators(child, &source);
                let mut ic = child.walk();
                for grandchild in child.children(&mut ic) {
                    if grandchild.kind() == "function_definition" {
                        if let Some(mut rw) = plan_rewrite(grandchild, &source, &mut warnings) {
                            // Expand the rewrite span to include decorators.
                            rw.byte_start = child.start_byte();
                            rw.decorators = decorators.clone();
                            rewrites.push(rw);
                        }
                        break;
                    }
                }
            }
            _ => {}
        }
    }

    if rewrites.is_empty() {
        return Ok(ApplyResult {
            rewrites_applied: Vec::new(),
            warnings,
            backup_path: None,
        });
    }

    // Write backup.
    let backup_path = format!("{}.bak", path);
    std::fs::write(&backup_path, &source)
        .with_context(|| format!("cannot write backup {}", backup_path))?;

    // Apply rewrites from bottom to top to keep byte offsets stable.
    rewrites.sort_by_key(|r| std::cmp::Reverse(r.byte_start));

    let mut result = source.clone();
    let mut applied = Vec::new();
    for rw in &rewrites {
        let new_bytes = rw.replacement.as_bytes();
        result.splice(rw.byte_start..rw.byte_end, new_bytes.iter().copied());
        applied.push(rw.description.clone());
    }

    std::fs::write(path, &result).with_context(|| format!("cannot write {}", path))?;

    Ok(ApplyResult {
        rewrites_applied: applied,
        warnings,
        backup_path: Some(backup_path),
    })
}

// ── Internal types ───────────────────────────────────────────────────────────

struct Rewrite {
    byte_start: usize,
    byte_end: usize,
    replacement: String,
    description: String,
    decorators: Vec<String>,
}

/// Result returned by [`apply`].
pub struct ApplyResult {
    pub rewrites_applied: Vec<String>,
    pub warnings: Vec<String>,
    pub backup_path: Option<String>,
}

// ── Rewrite planning ─────────────────────────────────────────────────────────

fn plan_rewrite(func: Node, source: &[u8], warnings: &mut Vec<String>) -> Option<Rewrite> {
    if !is_fbv(func, source) {
        return None;
    }

    let name_node = func.child_by_field_name("name")?;
    let func_name = node_text(name_node, source);
    let params_node = func.child_by_field_name("parameters")?;
    let body_node = func.child_by_field_name("body")?;

    // Detect multi-method dispatch — bail out with warning.
    let body_text = node_text(body_node, source);
    if body_text.contains("request.method") {
        warnings.push(format!(
            "`{}`: multi-method dispatch detected — manual CBV conversion required",
            func_name
        ));
        return None;
    }

    // Build the CBV class name: snake_case → PascalCase + "View".
    let class_name = to_pascal_case(func_name) + "View";

    // Collect extra URL parameters (everything after `request`).
    let extra_params = collect_extra_params(params_node, source);

    // Determine indentation of the original function.
    let indent = leading_spaces(func, source);

    // Build the body with one extra level of indentation.
    let body_lines = reindent_body(body_text, &indent);

    // Compose get method signature.
    let get_params = if extra_params.is_empty() {
        "self, request".to_string()
    } else {
        format!("self, request, {}", extra_params.join(", "))
    };

    let replacement = format!(
        "{indent}class {class_name}(View):\n{indent}    def get({get_params}):\n{body_lines}",
        indent = indent,
        class_name = class_name,
        get_params = get_params,
        body_lines = body_lines,
    );

    Some(Rewrite {
        byte_start: func.start_byte(),
        byte_end: func.end_byte(),
        replacement,
        description: format!(
            "`def {}()` → `class {}(View)` at byte {}",
            func_name,
            class_name,
            func.start_byte()
        ),
        decorators: Vec::new(),
    })
}

// ── Helpers ───────────────────────────────────────────────────────────────────

fn is_fbv(func: Node, source: &[u8]) -> bool {
    let params = match func.child_by_field_name("parameters") {
        Some(p) => p,
        None => return false,
    };
    let mut cursor = params.walk();
    let first_positional = params.children(&mut cursor).find(|n| {
        matches!(
            n.kind(),
            "identifier" | "typed_parameter" | "list_splat_pattern" | "dictionary_splat_pattern"
        )
    });
    match first_positional {
        Some(n) if n.kind() == "identifier" => node_text(n, source) == "request",
        _ => false,
    }
}

fn collect_extra_params(params: Node, source: &[u8]) -> Vec<String> {
    let mut result = Vec::new();
    let mut cursor = params.walk();
    let mut skip_first = true;
    for child in params.children(&mut cursor) {
        if matches!(
            child.kind(),
            "identifier" | "typed_parameter" | "default_parameter"
        ) {
            if skip_first {
                skip_first = false;
                continue; // skip `request`
            }
            result.push(node_text(child, source).to_string());
        }
    }
    result
}

fn collect_decorators(decorated: Node, source: &[u8]) -> Vec<String> {
    let mut result = Vec::new();
    let mut cursor = decorated.walk();
    for child in decorated.children(&mut cursor) {
        if child.kind() == "decorator" {
            result.push(node_text(child, source).to_string());
        }
    }
    result
}

/// Convert `snake_case` to `PascalCase`.
fn to_pascal_case(s: &str) -> String {
    s.split('_')
        .filter(|part| !part.is_empty())
        .map(|part| {
            let mut chars = part.chars();
            match chars.next() {
                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
                None => String::new(),
            }
        })
        .collect()
}

/// Return the leading whitespace of the function's start line.
fn leading_spaces(node: Node, source: &[u8]) -> String {
    let text = std::str::from_utf8(source).unwrap_or("");
    let line_start = text[..node.start_byte()]
        .rfind('\n')
        .map(|p| p + 1)
        .unwrap_or(0);
    let line = &text[line_start..];
    let spaces: String = line.chars().take_while(|c| c.is_whitespace()).collect();
    spaces
}

/// Re-indent body text from original indentation to `base_indent + 8 spaces`.
fn reindent_body(body_text: &str, base_indent: &str) -> String {
    let target_indent = format!("{}        ", base_indent); // base + 8
    body_text
        .lines()
        .map(|line| {
            if line.trim().is_empty() {
                String::new()
            } else {
                // Strip any leading whitespace and re-indent.
                format!("{}{}", target_indent, line.trim_start())
            }
        })
        .collect::<Vec<_>>()
        .join("\n")
}

fn node_text<'a>(node: Node, source: &'a [u8]) -> &'a str {
    std::str::from_utf8(&source[node.byte_range()]).unwrap_or("")
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ast::python::make_parser;
    use std::io::Write;

    fn parser() -> Parser {
        make_parser().unwrap()
    }

    // ---- Detection tests ----

    #[test]
    fn detect_simple_fbv() {
        let src = b"def home(request):\n    return HttpResponse('hello')\n";
        let findings = detect("views.py", src, &mut parser()).unwrap();
        assert_eq!(findings.len(), 1);
        assert_eq!(findings[0].rule_id, "django-fbv");
        assert_eq!(findings[0].line, 1);
    }

    #[test]
    fn detect_fbv_with_url_params() {
        let src = b"def detail(request, pk):\n    return HttpResponse(pk)\n";
        let findings = detect("views.py", src, &mut parser()).unwrap();
        assert_eq!(findings.len(), 1);
    }

    #[test]
    fn detect_skips_cbv_method() {
        let src = b"class MyView(View):\n    def get(self, request):\n        pass\n";
        let findings = detect("views.py", src, &mut parser()).unwrap();
        assert!(findings.is_empty(), "CBV method must not be detected");
    }

    #[test]
    fn detect_skips_non_view_function() {
        let src = b"def helper(x, y):\n    return x + y\n";
        let findings = detect("views.py", src, &mut parser()).unwrap();
        assert!(findings.is_empty());
    }

    #[test]
    fn detect_skips_comment_lookalike() {
        // Regex-based detection would flag a comment; AST-based must not.
        let src = b"# def home(request):\ndef real(x: int):\n    return x\n";
        let findings = detect("views.py", src, &mut parser()).unwrap();
        assert!(findings.is_empty(), "comment must not be detected as FBV");
    }

    // ---- Apply tests (write to tmp file) ----

    fn write_tmp(content: &str) -> tempfile::NamedTempFile {
        let mut f = tempfile::NamedTempFile::new().unwrap();
        f.write_all(content.as_bytes()).unwrap();
        f
    }

    #[test]
    fn apply_simple_fbv_produces_cbv() {
        let tmp = write_tmp("def home(request):\n    return HttpResponse('hello')\n");
        let path = tmp.path().to_str().unwrap();
        let result = apply(path, &mut parser()).unwrap();

        assert_eq!(result.rewrites_applied.len(), 1, "one rewrite expected");
        assert!(result.backup_path.is_some());

        let written = std::fs::read_to_string(path).unwrap();
        assert!(
            written.contains("class HomeView(View):"),
            "class not found:\n{}",
            written
        );
        assert!(
            written.contains("def get(self, request):"),
            "get method not found:\n{}",
            written
        );
        assert!(
            written.contains("HttpResponse"),
            "body not preserved:\n{}",
            written
        );
    }

    #[test]
    fn apply_creates_bak_file() {
        let tmp = write_tmp("def list_items(request):\n    return HttpResponse('ok')\n");
        let path = tmp.path().to_str().unwrap();
        apply(path, &mut parser()).unwrap();

        let bak = format!("{}.bak", path);
        assert!(std::path::Path::new(&bak).exists(), ".bak file must exist");
        let bak_content = std::fs::read_to_string(&bak).unwrap();
        assert!(
            bak_content.contains("def list_items"),
            "bak must have original"
        );
        // cleanup
        let _ = std::fs::remove_file(&bak);
    }

    #[test]
    fn apply_no_fbv_returns_empty() {
        let tmp = write_tmp("def helper(x):\n    return x\n");
        let path = tmp.path().to_str().unwrap();
        let result = apply(path, &mut parser()).unwrap();
        assert!(result.rewrites_applied.is_empty());
        assert!(result.backup_path.is_none());
    }

    #[test]
    fn apply_multi_method_emits_warning() {
        let src = "def view(request):\n    if request.method == 'POST':\n        pass\n    return HttpResponse('ok')\n";
        let tmp = write_tmp(src);
        let path = tmp.path().to_str().unwrap();
        let result = apply(path, &mut parser()).unwrap();
        assert!(
            !result.warnings.is_empty(),
            "multi-method must emit warning"
        );
        assert!(
            result.rewrites_applied.is_empty(),
            "multi-method must not be auto-converted"
        );
    }
}