codelens-core 0.1.2

Core library for codelens - high performance code analysis tool
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
//! Trend tracking with snapshots.

use std::fs;
use std::path::{Path, PathBuf};

use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

use crate::analyzer::stats::AnalysisResult;
use crate::error::{Error, Result};
use crate::insight::DeltaValue;

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Snapshot {
    pub version: u32,
    pub timestamp: DateTime<Utc>,
    pub label: Option<String>,
    pub git_commit: Option<String>,
    pub git_branch: Option<String>,
    pub result: AnalysisResult,
}

#[derive(Debug, Clone, Serialize)]
pub struct SnapshotMeta {
    pub timestamp: DateTime<Utc>,
    pub label: Option<String>,
    pub git_commit: Option<String>,
    pub file_path: PathBuf,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum LangStatus {
    Added,
    Removed,
    Changed,
}

impl std::fmt::Display for LangStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LangStatus::Added => write!(f, "+"),
            LangStatus::Removed => write!(f, "-"),
            LangStatus::Changed => write!(f, "~"),
        }
    }
}

#[derive(Debug, Clone, Serialize)]
pub struct LanguageTrend {
    pub language: String,
    pub status: LangStatus,
    pub files: DeltaValue<usize>,
    pub code: DeltaValue<usize>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TrendDelta {
    pub files: DeltaValue<usize>,
    pub lines: DeltaValue<usize>,
    pub code: DeltaValue<usize>,
    pub comment: DeltaValue<usize>,
    pub blank: DeltaValue<usize>,
    pub complexity: DeltaValue<usize>,
    pub functions: DeltaValue<usize>,
}

#[derive(Debug, Clone, Serialize)]
pub struct TrendReport {
    pub from: SnapshotMeta,
    pub to: SnapshotMeta,
    pub delta: TrendDelta,
    pub by_language: Vec<LanguageTrend>,
}

fn snapshots_dir(project_root: &Path) -> PathBuf {
    project_root.join(".codelens").join("snapshots")
}

pub fn save_snapshot(
    project_root: &Path,
    result: AnalysisResult,
    label: Option<String>,
    git_commit: Option<String>,
    git_branch: Option<String>,
) -> Result<PathBuf> {
    let dir = snapshots_dir(project_root);
    fs::create_dir_all(&dir).map_err(|e| Error::FileRead {
        path: dir.clone(),
        source: e,
    })?;

    let gitignore = project_root.join(".codelens").join(".gitignore");
    if !gitignore.exists() {
        let _ = fs::write(
            &gitignore,
            "# codelens snapshots - uncomment the next line to stop tracking\n# *\n",
        );
    }

    let now = Utc::now();
    let snapshot = Snapshot {
        version: 1,
        timestamp: now,
        label,
        git_commit,
        git_branch,
        result,
    };

    let filename = now.format("%Y-%m-%dT%H-%M-%SZ").to_string() + ".json";
    let path = dir.join(&filename);
    let json = serde_json::to_string_pretty(&snapshot)?;
    fs::write(&path, json).map_err(|e| Error::FileRead {
        path: path.clone(),
        source: e,
    })?;

    Ok(path)
}

pub fn list_snapshots(project_root: &Path) -> Result<Vec<SnapshotMeta>> {
    let dir = snapshots_dir(project_root);
    if !dir.exists() {
        return Ok(vec![]);
    }

    let mut metas = Vec::new();
    let entries = fs::read_dir(&dir).map_err(|e| Error::FileRead {
        path: dir.clone(),
        source: e,
    })?;

    for entry in entries {
        let entry = entry.map_err(|e| Error::FileRead {
            path: dir.clone(),
            source: e,
        })?;
        let path = entry.path();
        if path.extension().is_some_and(|e| e == "json") {
            if let Ok(meta) = read_snapshot_meta(&path) {
                metas.push(meta);
            }
        }
    }

    metas.sort_by(|a, b| a.timestamp.cmp(&b.timestamp));
    Ok(metas)
}

fn read_snapshot_meta(path: &Path) -> Result<SnapshotMeta> {
    let content = fs::read_to_string(path).map_err(|e| Error::FileRead {
        path: path.to_path_buf(),
        source: e,
    })?;
    let snapshot: Snapshot = serde_json::from_str(&content)?;
    Ok(SnapshotMeta {
        timestamp: snapshot.timestamp,
        label: snapshot.label,
        git_commit: snapshot.git_commit,
        file_path: path.to_path_buf(),
    })
}

fn load_snapshot(path: &Path) -> Result<Snapshot> {
    let content = fs::read_to_string(path).map_err(|e| Error::FileRead {
        path: path.to_path_buf(),
        source: e,
    })?;
    let snapshot: Snapshot = serde_json::from_str(&content)?;
    Ok(snapshot)
}

pub fn resolve_snapshot(project_root: &Path, reference: &str) -> Result<PathBuf> {
    let metas = list_snapshots(project_root)?;
    if metas.is_empty() {
        return Err(Error::NoSnapshots {
            path: snapshots_dir(project_root),
        });
    }

    if reference == "latest" {
        return Ok(metas.last().unwrap().file_path.clone());
    }

    if let Some(offset_str) = reference.strip_prefix("latest~") {
        let offset: usize = offset_str.parse().map_err(|_| Error::SnapshotNotFound {
            id: reference.to_string(),
        })?;
        let idx = metas
            .len()
            .checked_sub(1 + offset)
            .ok_or(Error::SnapshotNotFound {
                id: reference.to_string(),
            })?;
        return Ok(metas[idx].file_path.clone());
    }

    // Date prefix match
    for meta in metas.iter().rev() {
        let ts = meta.timestamp.format("%Y-%m-%d").to_string();
        if ts.starts_with(reference) {
            return Ok(meta.file_path.clone());
        }
    }

    Err(Error::SnapshotNotFound {
        id: reference.to_string(),
    })
}

pub fn diff(project_root: &Path, from_ref: &str, to_ref: &str) -> Result<TrendReport> {
    let from_path = resolve_snapshot(project_root, from_ref)?;
    let to_path = resolve_snapshot(project_root, to_ref)?;

    let from_snap = load_snapshot(&from_path)?;
    let to_snap = load_snapshot(&to_path)?;

    let from_summary = &from_snap.result.summary;
    let to_summary = &to_snap.result.summary;

    let delta = TrendDelta {
        files: DeltaValue::new(from_summary.total_files, to_summary.total_files),
        lines: DeltaValue::new(from_summary.lines.total, to_summary.lines.total),
        code: DeltaValue::new(from_summary.lines.code, to_summary.lines.code),
        comment: DeltaValue::new(from_summary.lines.comment, to_summary.lines.comment),
        blank: DeltaValue::new(from_summary.lines.blank, to_summary.lines.blank),
        complexity: DeltaValue::new(
            from_summary.complexity.cyclomatic,
            to_summary.complexity.cyclomatic,
        ),
        functions: DeltaValue::new(
            from_summary.complexity.functions,
            to_summary.complexity.functions,
        ),
    };

    let mut by_language = Vec::new();
    let mut seen_langs = std::collections::HashSet::new();

    for (lang, to_stats) in &to_summary.by_language {
        seen_langs.insert(lang.clone());
        if let Some(from_stats) = from_summary.by_language.get(lang) {
            by_language.push(LanguageTrend {
                language: lang.clone(),
                status: LangStatus::Changed,
                files: DeltaValue::new(from_stats.files, to_stats.files),
                code: DeltaValue::new(from_stats.lines.code, to_stats.lines.code),
            });
        } else {
            by_language.push(LanguageTrend {
                language: lang.clone(),
                status: LangStatus::Added,
                files: DeltaValue::new(0, to_stats.files),
                code: DeltaValue::new(0, to_stats.lines.code),
            });
        }
    }

    for (lang, from_stats) in &from_summary.by_language {
        if !seen_langs.contains(lang) {
            by_language.push(LanguageTrend {
                language: lang.clone(),
                status: LangStatus::Removed,
                files: DeltaValue::new(from_stats.files, 0),
                code: DeltaValue::new(from_stats.lines.code, 0),
            });
        }
    }

    by_language.sort_by(|a, b| {
        b.code
            .signed_delta()
            .unsigned_abs()
            .cmp(&a.code.signed_delta().unsigned_abs())
    });

    Ok(TrendReport {
        from: SnapshotMeta {
            timestamp: from_snap.timestamp,
            label: from_snap.label,
            git_commit: from_snap.git_commit,
            file_path: from_path,
        },
        to: SnapshotMeta {
            timestamp: to_snap.timestamp,
            label: to_snap.label,
            git_commit: to_snap.git_commit,
            file_path: to_path,
        },
        delta,
        by_language,
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analyzer::stats::{FileStats, LineStats, Summary};
    use std::time::Duration;
    use tempfile::TempDir;

    fn make_result(code: usize, files: usize) -> AnalysisResult {
        let file_stats: Vec<FileStats> = (0..files)
            .map(|i| FileStats {
                path: PathBuf::from(format!("file_{i}.rs")),
                language: "Rust".to_string(),
                lines: LineStats {
                    total: code / files.max(1),
                    code: code / files.max(1),
                    comment: 0,
                    blank: 0,
                },
                size: 1000,
                complexity: Default::default(),
            })
            .collect();
        AnalysisResult {
            summary: Summary::from_file_stats(&file_stats),
            files: file_stats,
            elapsed: Duration::from_millis(50),
            scanned_files: files,
            skipped_files: 0,
        }
    }

    #[test]
    fn test_save_and_list() {
        let dir = TempDir::new().unwrap();
        let result = make_result(100, 2);
        let path = save_snapshot(dir.path(), result, Some("v1.0".into()), None, None).unwrap();
        assert!(path.exists());
        let metas = list_snapshots(dir.path()).unwrap();
        assert_eq!(metas.len(), 1);
        assert_eq!(metas[0].label.as_deref(), Some("v1.0"));
    }

    #[test]
    fn test_gitignore_created() {
        let dir = TempDir::new().unwrap();
        save_snapshot(dir.path(), make_result(10, 1), None, None, None).unwrap();
        assert!(dir.path().join(".codelens/.gitignore").exists());
    }

    #[test]
    fn test_resolve_latest() {
        let dir = TempDir::new().unwrap();
        save_snapshot(dir.path(), make_result(10, 1), None, None, None).unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100)); // ensure different second in timestamp
        save_snapshot(
            dir.path(),
            make_result(20, 2),
            Some("second".into()),
            None,
            None,
        )
        .unwrap();
        let path = resolve_snapshot(dir.path(), "latest").unwrap();
        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("\"scanned_files\": 2"));
    }

    #[test]
    fn test_resolve_latest_offset() {
        let dir = TempDir::new().unwrap();
        save_snapshot(
            dir.path(),
            make_result(10, 1),
            Some("first".into()),
            None,
            None,
        )
        .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        save_snapshot(
            dir.path(),
            make_result(20, 2),
            Some("second".into()),
            None,
            None,
        )
        .unwrap();
        let path = resolve_snapshot(dir.path(), "latest~1").unwrap();
        let content = fs::read_to_string(&path).unwrap();
        assert!(content.contains("\"scanned_files\": 1"));
    }

    #[test]
    fn test_resolve_not_found() {
        let dir = TempDir::new().unwrap();
        let result = resolve_snapshot(dir.path(), "latest");
        assert!(result.is_err());
    }

    #[test]
    fn test_diff() {
        let dir = TempDir::new().unwrap();
        save_snapshot(
            dir.path(),
            make_result(100, 5),
            Some("v1".into()),
            None,
            None,
        )
        .unwrap();
        std::thread::sleep(std::time::Duration::from_millis(1100));
        save_snapshot(
            dir.path(),
            make_result(150, 7),
            Some("v2".into()),
            None,
            None,
        )
        .unwrap();
        let report = diff(dir.path(), "latest~1", "latest").unwrap();
        assert_eq!(report.from.label.as_deref(), Some("v1"));
        assert_eq!(report.to.label.as_deref(), Some("v2"));
        assert_eq!(report.delta.files.from, 5);
        assert_eq!(report.delta.files.to, 7);
        // 100/5=20 per file * 5 = 100 total; 150/7=21 per file * 7 = 147 total; delta = 47
        assert_eq!(report.delta.code.signed_delta(), 47);
    }

    #[test]
    fn test_list_empty() {
        let dir = TempDir::new().unwrap();
        let metas = list_snapshots(dir.path()).unwrap();
        assert!(metas.is_empty());
    }

    #[test]
    fn test_lang_status_display() {
        assert_eq!(LangStatus::Added.to_string(), "+");
        assert_eq!(LangStatus::Removed.to_string(), "-");
        assert_eq!(LangStatus::Changed.to_string(), "~");
    }
}