tidev 0.2.0

A terminal-based AI coding agent
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
use anyhow::{Context, Result, bail};
use std::{collections::HashSet, ffi::OsString, fs, path::Path, process::Command};

const DEFAULT_IGNORED_DIRS: &[&str] = &[
    ".git",
    "node_modules",
    ".venv",
    "venv",
    "env",
    ".env",
    "dist",
    "build",
    ".pytest_cache",
    ".mypy_cache",
    ".cache",
    ".tox",
    "__pycache__",
    "target",
];

pub fn init_snapshot_repo(gitdir: &Path) -> Result<()> {
    let status = Command::new("git")
        .args(["init"])
        .env("GIT_DIR", gitdir)
        .env("GIT_WORK_TREE", ".")
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git init")?;

    if !status.success() {
        bail!("git init failed for snapshot repo");
    }

    for (key, value) in [
        ("core.autocrlf", "false"),
        ("core.longpaths", "true"),
        ("core.symlinks", "true"),
        ("core.fsmonitor", "false"),
    ] {
        let status = Command::new("git")
            .args(["--git-dir", &gitdir.to_string_lossy(), "config", key, value])
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .with_context(|| format!("failed to set git config {}", key))?;

        if !status.success() {
            bail!("git config {} failed", key);
        }
    }

    Ok(())
}

pub fn sync_exclude(gitdir: &Path, worktree: &Path, extra: &[String]) -> Result<()> {
    let source_exclude = worktree.join(".git").join("info").join("exclude");

    let mut content = String::new();

    if source_exclude.exists()
        && let Ok(text) = fs::read_to_string(&source_exclude)
    {
        content.push_str(&text);
    }

    for item in extra {
        content.push_str(&format!("\n/{}", item.replace('\\', "/")));
    }

    let info_dir = gitdir.join("info");
    fs::create_dir_all(&info_dir)
        .with_context(|| format!("failed to create {}", info_dir.display()))?;

    let target = info_dir.join("exclude");
    fs::write(&target, content).with_context(|| format!("failed to write {}", target.display()))?;

    Ok(())
}

pub fn find_changed_files(gitdir: &Path, worktree: &Path) -> Result<Vec<String>> {
    let args: Vec<OsString> = vec![
        OsString::from("-c"),
        OsString::from("core.autocrlf=false"),
        OsString::from("-c"),
        OsString::from("core.longpaths=true"),
        OsString::from("-c"),
        OsString::from("core.symlinks=true"),
        OsString::from("-c"),
        OsString::from("core.quotepath=false"),
        OsString::from("--git-dir"),
        gitdir.into(),
        OsString::from("--work-tree"),
        worktree.into(),
        OsString::from("diff-files"),
        OsString::from("--name-only"),
        OsString::from("-z"),
        OsString::from("--"),
        OsString::from("."),
    ];

    let diff_output = Command::new("git")
        .args(&args)
        .output()
        .context("failed to run git diff-files")?;

    let tracked: Vec<String> = String::from_utf8_lossy(&diff_output.stdout)
        .split('\0')
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect();

    let args: Vec<OsString> = vec![
        OsString::from("-c"),
        OsString::from("core.autocrlf=false"),
        OsString::from("-c"),
        OsString::from("core.longpaths=true"),
        OsString::from("-c"),
        OsString::from("core.symlinks=true"),
        OsString::from("-c"),
        OsString::from("core.quotepath=false"),
        OsString::from("--git-dir"),
        gitdir.into(),
        OsString::from("--work-tree"),
        worktree.into(),
        OsString::from("ls-files"),
        OsString::from("--others"),
        OsString::from("--exclude-standard"),
        OsString::from("-z"),
        OsString::from("--"),
        OsString::from("."),
    ];

    let untracked_output = Command::new("git")
        .args(&args)
        .output()
        .context("failed to run git ls-files")?;

    let untracked: Vec<String> = String::from_utf8_lossy(&untracked_output.stdout)
        .split('\0')
        .filter(|s| !s.is_empty())
        .filter(|s| !should_ignore_path(s))
        .map(|s| s.to_string())
        .collect();

    let mut all: Vec<String> = tracked;
    all.extend(untracked);
    all.sort();
    all.dedup();

    Ok(all)
}

fn should_ignore_path(path: &str) -> bool {
    let path = Path::new(path);
    path.components().any(|component| {
        if let std::path::Component::Normal(name) = component
            && let Some(name_str) = name.to_str()
        {
            return DEFAULT_IGNORED_DIRS.contains(&name_str);
        }
        false
    })
}

#[cfg(test)]
mod tests {
    use super::should_ignore_path;

    #[test]
    fn ignores_git_metadata_paths() {
        assert!(should_ignore_path(".git"));
        assert!(should_ignore_path(".git/config"));
        assert!(should_ignore_path("repo/.git/info/exclude"));
        assert!(!should_ignore_path(".gitignore"));
        assert!(!should_ignore_path("src/git.rs"));
    }
}

pub fn check_ignored(gitdir: &Path, worktree: &Path, files: &[String]) -> Result<HashSet<String>> {
    if files.is_empty() {
        return Ok(HashSet::new());
    }

    let input = files.join("\0") + "\0";

    let output = Command::new("git")
        .current_dir(worktree)
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "check-ignore",
            "--no-index",
            "--stdin",
            "-z",
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::null())
        .spawn()
        .context("failed to spawn git check-ignore")?;

    if let Some(mut stdin) = output.stdin.as_ref() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .context("failed to write to git check-ignore stdin")?;
    }

    let result = output
        .wait_with_output()
        .context("failed to wait for git check-ignore")?;

    if result.status.code() == Some(0) || result.status.code() == Some(1) {
        let ignored: HashSet<String> = String::from_utf8_lossy(&result.stdout)
            .split('\0')
            .filter(|s| !s.is_empty())
            .map(|s| s.to_string())
            .collect();
        return Ok(ignored);
    }

    Ok(HashSet::new())
}

pub fn filter_large_files(worktree: &Path, files: &[String], limit: u64) -> Result<Vec<String>> {
    let mut large = Vec::new();

    for file in files {
        let path = worktree.join(file);
        match fs::metadata(&path) {
            Ok(meta) => {
                if meta.is_file() && meta.len() > limit {
                    large.push(file.clone());
                }
            }
            Err(_) => continue,
        }
    }

    Ok(large)
}

pub fn stage_files(gitdir: &Path, worktree: &Path, files: &[String]) -> Result<()> {
    if files.is_empty() {
        return Ok(());
    }

    let input = files.join("\0") + "\0";

    let mut child = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "add",
            "--all",
            "--sparse",
            "--pathspec-from-file=-",
            "--pathspec-file-nul",
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .context("failed to spawn git add")?;

    if let Some(mut stdin) = child.stdin.take() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .context("failed to write to git add stdin")?;
    }

    let status = child.wait().context("failed to wait for git add")?;

    let _ = status;

    Ok(())
}

pub fn write_tree(gitdir: &Path) -> Result<String> {
    let output = Command::new("git")
        .args(["--git-dir", &gitdir.to_string_lossy(), "write-tree"])
        .output()
        .context("failed to run git write-tree")?;

    if !output.status.success() {
        bail!(
            "git write-tree failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );
    }

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

pub fn diff_cached_names(gitdir: &Path, worktree: &Path, hash: &str) -> Result<Vec<String>> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "diff",
            "--cached",
            "--no-ext-diff",
            "--name-only",
            hash,
            "--",
            ".",
        ])
        .output()
        .context("failed to run git diff --cached")?;

    let files: Vec<String> = String::from_utf8_lossy(&output.stdout)
        .lines()
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect();

    Ok(files)
}

pub fn diff_cached(gitdir: &Path, worktree: &Path, hash: &str) -> Result<String> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "diff",
            "--cached",
            "--no-ext-diff",
            hash,
            "--",
            ".",
        ])
        .output()
        .context("failed to run git diff --cached")?;

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

pub fn checkout_file(gitdir: &Path, worktree: &Path, hash: &str, file: &str) -> Result<()> {
    let status = Command::new("git")
        .args([
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "checkout",
            hash,
            "--",
            file,
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git checkout")?;

    if !status.success() {
        bail!("git checkout failed");
    }

    Ok(())
}

pub fn ls_tree(gitdir: &Path, hash: &str, rel: &str) -> Result<Option<String>> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "ls-tree",
            hash,
            "--",
            rel,
        ])
        .output()
        .context("failed to run git ls-tree")?;

    let text = String::from_utf8_lossy(&output.stdout).trim().to_string();

    if text.is_empty() {
        Ok(None)
    } else {
        Ok(Some(text))
    }
}

pub fn read_tree(gitdir: &Path, hash: &str) -> Result<()> {
    let status = Command::new("git")
        .args([
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "read-tree",
            hash,
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git read-tree")?;

    if !status.success() {
        bail!("git read-tree failed");
    }

    Ok(())
}

pub fn checkout_index(gitdir: &Path, worktree: &Path) -> Result<()> {
    let status = Command::new("git")
        .args([
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "checkout-index",
            "-a",
            "-f",
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git checkout-index")?;

    if !status.success() {
        bail!("git checkout-index failed");
    }

    Ok(())
}

pub fn gc_prune(gitdir: &Path, period: &str) -> Result<()> {
    let status = Command::new("git")
        .args([
            "--git-dir",
            &gitdir.to_string_lossy(),
            "gc",
            &format!("--prune={}", period),
        ])
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git gc")?;

    if !status.success() {
        bail!("git gc failed");
    }

    Ok(())
}

pub fn drop_files(gitdir: &Path, worktree: &Path, files: &[String]) -> Result<()> {
    if files.is_empty() {
        return Ok(());
    }

    let input = files.join("\0") + "\0";

    let mut child = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "rm",
            "--cached",
            "-f",
            "--ignore-unmatch",
            "--pathspec-from-file=-",
            "--pathspec-file-nul",
        ])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
        .context("failed to spawn git rm")?;

    if let Some(mut stdin) = child.stdin.take() {
        use std::io::Write;
        stdin
            .write_all(input.as_bytes())
            .context("failed to write to git rm stdin")?;
    }

    let _ = child.wait().context("failed to wait for git rm")?;

    Ok(())
}

pub fn ls_tree_names(gitdir: &Path, hash: &str, rels: &[&str]) -> Result<String> {
    let mut args: Vec<OsString> = vec![
        OsString::from("-c"),
        OsString::from("core.longpaths=true"),
        OsString::from("-c"),
        OsString::from("core.symlinks=true"),
        OsString::from("--git-dir"),
        OsString::from(gitdir.to_string_lossy().to_string()),
        OsString::from("ls-tree"),
        OsString::from("--name-only"),
        OsString::from(hash),
        OsString::from("--"),
    ];
    args.extend(rels.iter().map(|r| OsString::from(*r)));

    let output = Command::new("git")
        .args(&args)
        .output()
        .context("failed to run git ls-tree")?;

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

pub fn checkout_files(gitdir: &Path, worktree: &Path, hash: &str, files: &[&str]) -> Result<()> {
    let mut args: Vec<OsString> = vec![
        OsString::from("-c"),
        OsString::from("core.longpaths=true"),
        OsString::from("-c"),
        OsString::from("core.symlinks=true"),
        OsString::from("--git-dir"),
        OsString::from(gitdir.to_string_lossy().to_string()),
        OsString::from("--work-tree"),
        OsString::from(worktree.to_string_lossy().to_string()),
        OsString::from("checkout"),
        OsString::from(hash),
        OsString::from("--"),
    ];
    args.extend(files.iter().map(|f| OsString::from(*f)));

    let status = Command::new("git")
        .args(&args)
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .status()
        .context("failed to run git checkout")?;

    if !status.success() {
        bail!("git checkout failed");
    }

    Ok(())
}

pub fn diff_name_status(
    gitdir: &Path,
    worktree: &Path,
    from: &str,
    to: &str,
) -> Result<Vec<(String, String)>> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "diff",
            "--no-ext-diff",
            "--name-status",
            "--no-renames",
            from,
            to,
            "--",
            ".",
        ])
        .output()
        .context("failed to run git diff --name-status")?;

    let mut result = Vec::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() >= 2 {
            result.push((parts[0].to_string(), parts[1].to_string()));
        }
    }

    Ok(result)
}

pub fn diff_numstat(
    gitdir: &Path,
    worktree: &Path,
    from: &str,
    to: &str,
) -> Result<Vec<(String, String, String)>> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "diff",
            "--no-ext-diff",
            "--no-renames",
            "--numstat",
            from,
            to,
            "--",
            ".",
        ])
        .output()
        .context("failed to run git diff --numstat")?;

    let mut result = Vec::new();
    for line in String::from_utf8_lossy(&output.stdout).lines() {
        let parts: Vec<&str> = line.split('\t').collect();
        if parts.len() >= 3 {
            result.push((
                parts[0].to_string(),
                parts[1].to_string(),
                parts[2].to_string(),
            ));
        }
    }

    Ok(result)
}

pub fn diff_file(
    gitdir: &Path,
    worktree: &Path,
    from: &str,
    to: &str,
    file: &str,
) -> Result<String> {
    let output = Command::new("git")
        .args([
            "-c",
            "core.autocrlf=false",
            "-c",
            "core.longpaths=true",
            "-c",
            "core.symlinks=true",
            "-c",
            "core.quotepath=false",
            "--git-dir",
            &gitdir.to_string_lossy(),
            "--work-tree",
            &worktree.to_string_lossy(),
            "diff",
            "--no-ext-diff",
            "--no-renames",
            from,
            to,
            "--",
            file,
        ])
        .output()
        .context("failed to run git diff for file")?;

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