tuicr 0.4.0

Review AI-generated diffs like a GitHub pull request, right from your terminal.
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
use std::path::{Path, PathBuf};
use std::process::Command;

use chrono::{TimeZone, Utc};

use crate::error::{Result, TuicrError};
use crate::model::{DiffFile, DiffLine, FileStatus, LineOrigin};
use crate::syntax::SyntaxHighlighter;
use crate::vcs::diff_parser::{self, DiffFormat};
use crate::vcs::traits::{CommitInfo, VcsBackend, VcsInfo, VcsType};

/// Mercurial backend implementation using hg CLI commands
pub struct HgBackend {
    info: VcsInfo,
}

impl HgBackend {
    /// Discover a Mercurial repository from the current directory
    pub fn discover() -> Result<Self> {
        // Use `hg root` to find the repository root
        // This handles being called from subdirectories
        let root_output = Command::new("hg")
            .args(["root"])
            .output()
            .map_err(|e| TuicrError::VcsCommand(format!("Failed to run hg: {}", e)))?;

        if !root_output.status.success() {
            return Err(TuicrError::NotARepository);
        }

        let root_path = PathBuf::from(String::from_utf8_lossy(&root_output.stdout).trim());

        Self::from_path(root_path)
    }

    /// Create backend from a known path (used by discover and tests)
    fn from_path(root_path: PathBuf) -> Result<Self> {
        // Get current revision info
        let head_commit = run_hg_command(&root_path, &["id", "-i"])
            .map(|s| s.trim().trim_end_matches('+').to_string())
            .unwrap_or_else(|_| "unknown".to_string());

        let branch_name = run_hg_command(&root_path, &["branch"])
            .ok()
            .map(|s| s.trim().to_string());

        let info = VcsInfo {
            root_path,
            head_commit,
            branch_name,
            vcs_type: VcsType::Mercurial,
        };

        Ok(Self { info })
    }
}

impl VcsBackend for HgBackend {
    fn info(&self) -> &VcsInfo {
        &self.info
    }

    fn get_working_tree_diff(&self, highlighter: &SyntaxHighlighter) -> Result<Vec<DiffFile>> {
        // Get unified diff output from hg
        let diff_output = run_hg_command(&self.info.root_path, &["diff"])?;

        if diff_output.trim().is_empty() {
            return Err(TuicrError::NoChanges);
        }

        diff_parser::parse_unified_diff(&diff_output, DiffFormat::Hg, highlighter)
    }

    fn fetch_context_lines(
        &self,
        file_path: &Path,
        file_status: FileStatus,
        start_line: u32,
        end_line: u32,
    ) -> Result<Vec<DiffLine>> {
        if start_line > end_line || start_line == 0 {
            return Ok(Vec::new());
        }

        let content = match file_status {
            FileStatus::Deleted => {
                // Read from hg cat (last committed version)
                run_hg_command(
                    &self.info.root_path,
                    &["cat", "-r", ".", &file_path.to_string_lossy()],
                )?
            }
            _ => {
                // Read from working tree
                let full_path = self.info.root_path.join(file_path);
                std::fs::read_to_string(&full_path)?
            }
        };

        let lines: Vec<&str> = content.lines().collect();
        let mut result = Vec::new();

        for line_num in start_line..=end_line {
            let idx = (line_num - 1) as usize;
            if idx < lines.len() {
                result.push(DiffLine {
                    origin: LineOrigin::Context,
                    content: lines[idx].to_string(),
                    old_lineno: Some(line_num),
                    new_lineno: Some(line_num),
                    highlighted_spans: None,
                });
            }
        }

        Ok(result)
    }

    fn get_recent_commits(&self, count: usize) -> Result<Vec<CommitInfo>> {
        // Use hg log with a template to get structured output
        // Template fields separated by \x00, records separated by \x01
        let template =
            "{node}\\x00{node|short}\\x00{desc|firstline}\\x00{author|user}\\x00{date|hgdate}\\x01";
        let output = run_hg_command(
            &self.info.root_path,
            &["log", "-l", &count.to_string(), "--template", template],
        )?;

        let mut commits = Vec::new();
        for record in output.split('\x01') {
            let record = record.trim();
            if record.is_empty() {
                continue;
            }

            let parts: Vec<&str> = record.split('\x00').collect();
            if parts.len() < 5 {
                continue;
            }

            let id = parts[0].to_string();
            let short_id = parts[1].to_string();
            let summary = parts[2].to_string();
            let author = parts[3].to_string();

            // hgdate format is "unix_timestamp timezone_offset"
            let time = parts[4]
                .split_whitespace()
                .next()
                .and_then(|s| s.parse::<i64>().ok())
                .and_then(|ts| Utc.timestamp_opt(ts, 0).single())
                .unwrap_or_else(Utc::now);

            commits.push(CommitInfo {
                id,
                short_id,
                summary,
                author,
                time,
            });
        }

        Ok(commits)
    }

    fn get_commit_range_diff(
        &self,
        commit_ids: &[String],
        highlighter: &SyntaxHighlighter,
    ) -> Result<Vec<DiffFile>> {
        if commit_ids.is_empty() {
            return Err(TuicrError::NoChanges);
        }

        // commit_ids are ordered from oldest to newest
        //
        // Note on Sapling/Mercurial compatibility:
        // - Sapling (Meta's hg fork) has issues with full 40-char hashes in certain operations
        // - We use 12-char short hashes which work with both standard Mercurial and Sapling
        // - The parents() revset is used to find the parent commit for diffing
        let oldest = &commit_ids[0];
        let oldest_short = if oldest.len() > 12 {
            &oldest[..12]
        } else {
            oldest.as_str()
        };

        let newest = commit_ids.last().unwrap();
        let newest_short = if newest.len() > 12 {
            &newest[..12]
        } else {
            newest.as_str()
        };

        // First, get the parent commit of the oldest
        // We use "log -r 'parents({oldest})'" to get the parent hash
        let parent_output = run_hg_command(
            &self.info.root_path,
            &[
                "log",
                "-r",
                &format!("parents({})", oldest_short),
                "--template",
                "{node|short}",
            ],
        );

        // If there's no parent (first commit), diff from null
        let from_rev = match parent_output {
            Ok(parent) if !parent.trim().is_empty() => parent.trim().to_string(),
            _ => "null".to_string(),
        };

        let diff_output = run_hg_command(
            &self.info.root_path,
            &["diff", "-r", &from_rev, "-r", newest_short],
        )?;

        if diff_output.trim().is_empty() {
            return Err(TuicrError::NoChanges);
        }

        diff_parser::parse_unified_diff(&diff_output, DiffFormat::Hg, highlighter)
    }
}

/// Run an hg command and return its stdout
fn run_hg_command(root: &Path, args: &[&str]) -> Result<String> {
    let output = Command::new("hg")
        .current_dir(root)
        .args(args)
        .output()
        .map_err(|e| TuicrError::VcsCommand(format!("Failed to run hg: {}", e)))?;

    if !output.status.success() {
        let stderr = String::from_utf8_lossy(&output.stderr);
        return Err(TuicrError::VcsCommand(format!(
            "hg {} failed: {}",
            args.join(" "),
            stderr
        )));
    }

    Ok(String::from_utf8_lossy(&output.stdout).to_string())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;

    /// Check if hg command is available
    fn hg_available() -> bool {
        Command::new("hg")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Discover a Mercurial repository from a specific directory
    fn discover_in(path: &Path) -> Result<HgBackend> {
        let root_output = Command::new("hg")
            .args(["root"])
            .current_dir(path)
            .output()
            .map_err(|e| TuicrError::VcsCommand(format!("Failed to run hg: {}", e)))?;

        if !root_output.status.success() {
            return Err(TuicrError::NotARepository);
        }

        let root_path = PathBuf::from(String::from_utf8_lossy(&root_output.stdout).trim());

        HgBackend::from_path(root_path)
    }

    /// Create a temporary hg repo for testing.
    /// Returns None if hg is not available.
    fn setup_test_repo() -> Option<tempfile::TempDir> {
        if !hg_available() {
            return None;
        }

        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let root = temp_dir.path();

        // Initialize hg repo
        Command::new("hg")
            .args(["init"])
            .current_dir(root)
            .output()
            .expect("Failed to init hg repo");

        // Create initial file
        fs::write(root.join("hello.txt"), "hello world\n").expect("Failed to write file");

        // Add and commit
        Command::new("hg")
            .args(["add", "hello.txt"])
            .current_dir(root)
            .output()
            .expect("Failed to add file");

        Command::new("hg")
            .args(["commit", "-m", "Initial commit"])
            .current_dir(root)
            .output()
            .expect("Failed to commit");

        // Make a modification
        fs::write(root.join("hello.txt"), "hello world\nmodified line\n")
            .expect("Failed to modify file");

        Some(temp_dir)
    }

    #[test]
    fn test_hg_discover() {
        let Some(temp) = setup_test_repo() else {
            eprintln!("Skipping test: hg command not available");
            return;
        };

        // Use discover_in to avoid set_current_dir race conditions
        let backend = discover_in(temp.path()).expect("Failed to discover hg repo");
        let info = backend.info();

        assert_eq!(info.root_path, temp.path());
        assert_eq!(info.vcs_type, VcsType::Mercurial);
        assert!(!info.head_commit.is_empty());
    }

    #[test]
    fn test_hg_working_tree_diff() {
        let Some(temp) = setup_test_repo() else {
            eprintln!("Skipping test: hg command not available");
            return;
        };

        // Use from_path directly to avoid set_current_dir race conditions
        let backend =
            HgBackend::from_path(temp.path().to_path_buf()).expect("Failed to create hg backend");

        assert_eq!(backend.info().root_path, temp.path());
        assert_eq!(backend.info().vcs_type, VcsType::Mercurial);

        let files = backend
            .get_working_tree_diff(&SyntaxHighlighter::default())
            .expect("Failed to get diff");

        assert_eq!(files.len(), 1);
        assert_eq!(
            files[0].new_path.as_ref().unwrap().to_str().unwrap(),
            "hello.txt"
        );
        assert_eq!(files[0].status, FileStatus::Modified);
    }

    #[test]
    fn test_hg_fetch_context_lines() {
        let Some(temp) = setup_test_repo() else {
            eprintln!("Skipping test: hg command not available");
            return;
        };

        // Use from_path directly to avoid set_current_dir race conditions
        let backend =
            HgBackend::from_path(temp.path().to_path_buf()).expect("Failed to create hg backend");

        assert_eq!(backend.info().root_path, temp.path());

        // Fetch context lines from working tree (modified file)
        let lines = backend
            .fetch_context_lines(Path::new("hello.txt"), FileStatus::Modified, 1, 2)
            .expect("Failed to fetch context lines");

        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].content, "hello world");
        assert_eq!(lines[1].content, "modified line");
    }

    /// Create a test repo with multiple commits (no pending changes).
    /// Returns None if hg is not available.
    fn setup_test_repo_with_commits() -> Option<tempfile::TempDir> {
        if !hg_available() {
            return None;
        }

        let temp_dir = tempfile::tempdir().expect("Failed to create temp dir");
        let root = temp_dir.path();

        // Initialize hg repo
        Command::new("hg")
            .args(["init"])
            .current_dir(root)
            .output()
            .expect("Failed to init hg repo");

        // First commit
        fs::write(root.join("file1.txt"), "first file\n").expect("Failed to write file");
        Command::new("hg")
            .args(["add", "file1.txt"])
            .current_dir(root)
            .output()
            .expect("Failed to add file");
        Command::new("hg")
            .args(["commit", "-m", "First commit"])
            .current_dir(root)
            .output()
            .expect("Failed to commit");

        // Second commit
        fs::write(root.join("file2.txt"), "second file\n").expect("Failed to write file");
        Command::new("hg")
            .args(["add", "file2.txt"])
            .current_dir(root)
            .output()
            .expect("Failed to add file");
        Command::new("hg")
            .args(["commit", "-m", "Second commit"])
            .current_dir(root)
            .output()
            .expect("Failed to commit");

        // Third commit - modify first file
        fs::write(root.join("file1.txt"), "first file\nmodified\n").expect("Failed to write file");
        Command::new("hg")
            .args(["commit", "-m", "Third commit"])
            .current_dir(root)
            .output()
            .expect("Failed to commit");

        Some(temp_dir)
    }

    #[test]
    fn test_hg_get_recent_commits() {
        let Some(temp) = setup_test_repo_with_commits() else {
            eprintln!("Skipping test: hg command not available");
            return;
        };

        let backend =
            HgBackend::from_path(temp.path().to_path_buf()).expect("Failed to create hg backend");

        let commits = backend
            .get_recent_commits(5)
            .expect("Failed to get commits");

        assert_eq!(commits.len(), 3);
        // Most recent commit should be first
        assert_eq!(commits[0].summary, "Third commit");
        assert_eq!(commits[1].summary, "Second commit");
        assert_eq!(commits[2].summary, "First commit");

        // All commits should have valid ids
        for commit in &commits {
            assert!(!commit.id.is_empty());
            assert!(!commit.short_id.is_empty());
            assert!(commit.short_id.len() <= commit.id.len());
        }
    }

    #[test]
    fn test_hg_get_commit_range_diff() {
        let Some(temp) = setup_test_repo_with_commits() else {
            eprintln!("Skipping test: hg command not available");
            return;
        };

        let backend =
            HgBackend::from_path(temp.path().to_path_buf()).expect("Failed to create hg backend");

        let commits = backend
            .get_recent_commits(5)
            .expect("Failed to get commits");
        assert_eq!(commits.len(), 3);

        // Get diff for the last two commits (Second and Third)
        let commit_ids = vec![commits[1].id.clone(), commits[0].id.clone()];
        let diff_result = backend.get_commit_range_diff(&commit_ids, &SyntaxHighlighter::default());

        // Note: Sapling (Meta's hg fork) may fail with "id_dag_snapshot()" error
        // in certain temporary directory configurations. Skip the test in that case.
        let diff = match diff_result {
            Ok(d) => d,
            Err(TuicrError::VcsCommand(msg)) if msg.contains("id_dag_snapshot") => {
                eprintln!("Skipping test: Sapling-specific issue with tempdir repos");
                return;
            }
            Err(e) => panic!("Failed to get commit range diff: {:?}", e),
        };

        // Should have changes from both commits
        // Second commit added file2.txt, Third modified file1.txt
        assert!(!diff.is_empty());

        let file_paths: Vec<_> = diff
            .iter()
            .filter_map(|f| f.new_path.as_ref().map(|p| p.to_string_lossy().to_string()))
            .collect();

        // Both files should be in the diff
        assert!(
            file_paths.contains(&"file2.txt".to_string()),
            "Expected file2.txt in diff, got {:?}",
            file_paths
        );
        assert!(
            file_paths.contains(&"file1.txt".to_string()),
            "Expected file1.txt in diff, got {:?}",
            file_paths
        );
    }
}