tuit-bin 0.1.5

A TUI git log viewer built with ratatui and gix (gitoxide)
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
use std::path::Path;

use anyhow::{Context, Result};
use gix::diff::Options;
use gix::revision::walk::Sorting;
use gix::traverse::commit::simple::CommitTimeOrder;

/// A single commit's summary data.
#[derive(Clone, Debug)]
pub struct Commit {
    /// 7-character abbreviated hash.
    pub hash: String,
    /// Full OID hex string (40 characters).
    pub oid: String,
    /// Subject line (first line of the commit message).
    pub message: String,
    /// Author name.
    pub author: String,
    /// Relative timestamp (e.g. "3d ago").
    pub date: String,
    /// Full commit body (populated lazily by load_diff).
    pub body: String,
    /// Unified diff text (populated lazily by load_diff).
    pub diff: String,
}

/// Open the given directory as a git repository, walking up the file system
/// from `path` to discover the `.git` directory.
pub fn open_repo(path: &Path) -> Result<gix::Repository> {
    gix::discover(path).with_context(|| {
        format!(
            "tuit は git リポジトリの中で実行してください: {}",
            path.display()
        )
    })
}

/// Return the current branch name (e.g. `"main"`), or `"HEAD"` if detached.
pub fn current_branch(repo: &gix::Repository) -> Result<String> {
    let head = repo.head().context("No HEAD reference found")?;
    Ok(match head.referent_name() {
        Some(name) => name.shorten().to_string(),
        None => "HEAD".to_string(),
    })
}

/// Return the hex string of the HEAD commit OID from an already-opened repository.
pub fn current_head_oid(repo: &gix::Repository) -> Result<String> {
    let mut head = repo.head().context("No HEAD reference found")?;
    let commit = head
        .peel_to_commit_in_place()
        .map_err(|_| anyhow::anyhow!("このリポジトリにはまだコミットがありません。"))?;
    Ok(commit.id().to_hex().to_string())
}

/// Check whether a git object identified by its hex OID still exists in the repository.
pub fn object_exists(repo: &gix::Repository, oid_hex: &str) -> Result<bool> {
    let oid: gix::hash::ObjectId = oid_hex.parse().context("Invalid OID format")?;
    match repo.find_object(oid) {
        Ok(_) => Ok(true),
        Err(gix::object::find::existing::Error::NotFound { .. }) => Ok(false),
        Err(e) => Err(e.into()),
    }
}

/// Load all commits reachable from HEAD (newest first), opening a fresh repository.
pub fn load_commits(path: &Path) -> Result<Vec<Commit>> {
    let repo = open_repo(path)?;
    load_commits_from(&repo)
}

/// Load all commits reachable from HEAD using an already-opened repository.
pub fn load_commits_from(repo: &gix::Repository) -> Result<Vec<Commit>> {
    // Resolve HEAD to a commit OID.
    let mut head = repo.head().context("No HEAD reference found")?;
    let head_id = match head.peel_to_commit_in_place() {
        Ok(commit) => commit.id(),
        Err(_) => anyhow::bail!("このリポジトリにはまだコミットがありません。"),
    };

    // Walk commits newest-first.
    let walk = repo
        .rev_walk(Some(head_id))
        .sorting(Sorting::ByCommitTime(CommitTimeOrder::NewestFirst))
        .all()
        .context("Failed to create revision walk")?;

    let mut commits = Vec::new();
    for entry in walk {
        let info = entry.context("Error walking commits")?;
        let commit_obj = info.object().context("Failed to read commit object")?;

        let oid_hex = info.id().to_hex().to_string();
        let short_hash = oid_hex.chars().take(7).collect::<String>();

        let msg_ref = commit_obj.message().context("Failed to decode message")?;
        let subject = msg_ref.title.to_string();

        let author = commit_obj.author().context("Failed to decode author")?;
        let author_name = author.name.to_string();

        let time_seconds = commit_obj
            .committer()
            .context("Failed to decode committer")?
            .seconds();
        let date_str = format_relative_time(time_seconds);

        commits.push(Commit {
            hash: short_hash,
            oid: oid_hex,
            message: subject,
            author: author_name,
            date: date_str,
            body: String::new(),
            diff: String::new(),
        });
    }

    Ok(commits)
}

/// Load the list of files changed in a commit identified by its full OID hex string.
pub fn load_changed_files(path: &Path, oid_hex: &str) -> Result<Vec<String>> {
    let repo = open_repo(path)?;
    let oid: gix::hash::ObjectId = oid_hex.parse().context("Invalid OID format")?;
    let commit_obj = repo.find_commit(oid).context("Commit not found")?;

    let tree = repo
        .find_tree(commit_obj.tree_id()?)
        .context("Failed to find commit tree")?;
    let parent_tree = commit_obj.parent_ids().next().and_then(|pid| {
        repo.find_commit(pid.detach())
            .ok()
            .and_then(|pc| pc.tree_id().ok())
            .and_then(|tid| repo.find_tree(tid.detach()).ok())
    });

    let mut opts = gix::diff::Options::default();
    opts.track_path();
    opts.track_rewrites(None);

    let changes: Vec<gix::object::tree::diff::ChangeDetached> = repo
        .diff_tree_to_tree(parent_tree.as_ref(), Some(&tree), opts)
        .context("Failed to diff trees")?;

    // Filter: only blob (regular file) changes — skip tree (directory) entries.
    use gix::object::tree::EntryKind;

    let is_blob = |mode: gix::object::tree::EntryMode| -> bool {
        let kind: EntryKind = mode.into();
        matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable)
    };

    let mut files: Vec<String> = changes
        .iter()
        .filter_map(|change| match change {
            gix::object::tree::diff::ChangeDetached::Addition {
                entry_mode,
                location,
                ..
            }
            | gix::object::tree::diff::ChangeDetached::Deletion {
                entry_mode,
                location,
                ..
            } if is_blob(*entry_mode) => Some(location.to_string()),
            gix::object::tree::diff::ChangeDetached::Modification {
                entry_mode,
                location,
                ..
            } if is_blob(*entry_mode) => Some(location.to_string()),
            _ => None,
        })
        .collect();
    files.sort();
    files.dedup();
    Ok(files)
}

/// Load the union of files changed between two commits (`older..newer`).
pub fn load_range_changed_files(
    path: &Path,
    older_oid_hex: &str,
    newer_oid_hex: &str,
) -> Result<Vec<String>> {
    let repo = open_repo(path)?;
    let older_oid: gix::hash::ObjectId = older_oid_hex.parse().context("Invalid OID format")?;
    let newer_oid: gix::hash::ObjectId = newer_oid_hex.parse().context("Invalid OID format")?;

    let older_commit = repo.find_commit(older_oid).context("Older commit not found")?;
    let newer_commit = repo.find_commit(newer_oid).context("Newer commit not found")?;

    let older_tree = repo
        .find_tree(older_commit.tree_id()?)
        .context("Failed to find older commit tree")?;
    let newer_tree = repo
        .find_tree(newer_commit.tree_id()?)
        .context("Failed to find newer commit tree")?;

    let mut opts = gix::diff::Options::default();
    opts.track_path();
    opts.track_rewrites(None);

    let changes: Vec<gix::object::tree::diff::ChangeDetached> = repo
        .diff_tree_to_tree(Some(&older_tree), Some(&newer_tree), opts)
        .context("Failed to diff range trees")?;

    use gix::object::tree::EntryKind;

    let is_blob = |mode: gix::object::tree::EntryMode| -> bool {
        let kind: EntryKind = mode.into();
        matches!(kind, EntryKind::Blob | EntryKind::BlobExecutable)
    };

    let mut files: Vec<String> = changes
        .iter()
        .filter_map(|change| match change {
            gix::object::tree::diff::ChangeDetached::Addition {
                entry_mode,
                location,
                ..
            }
            | gix::object::tree::diff::ChangeDetached::Deletion {
                entry_mode,
                location,
                ..
            } if is_blob(*entry_mode) => Some(location.to_string()),
            gix::object::tree::diff::ChangeDetached::Modification {
                entry_mode,
                location,
                ..
            } if is_blob(*entry_mode) => Some(location.to_string()),
            _ => None,
        })
        .collect();
    files.sort();
    files.dedup();
    Ok(files)
}

/// Load the full commit body and diff for a commit identified by its full OID hex string.
///
/// Returns `(body, diff_text)`.
pub fn load_diff(path: &Path, oid_hex: &str) -> Result<(String, String)> {
    let repo = open_repo(path)?;

    let oid: gix::hash::ObjectId = oid_hex.parse().context("Invalid OID format")?;

    let commit_obj = repo.find_commit(oid).context("Commit not found")?;

    let msg_ref = commit_obj.message().context("Failed to decode message")?;
    let body = msg_ref.body.map(|b| b.to_string()).unwrap_or_default();

    // Get the commit tree.
    let tree = repo
        .find_tree(commit_obj.tree_id()?)
        .context("Failed to find commit tree")?;

    // Get parent tree (first parent only for merge commits).
    let parent_tree = commit_obj.parent_ids().next().and_then(|pid| {
        repo.find_commit(pid.detach())
            .ok()
            .and_then(|pc| pc.tree_id().ok())
            .and_then(|tid| repo.find_tree(tid.detach()).ok())
    });

    // Build unified diff.
    let diff_text = build_diff(&repo, parent_tree.as_ref(), &tree)?;

    Ok((body, diff_text))
}

/// Build a unified-diff formatted string between an optional old tree and a new tree.
fn build_diff(
    repo: &gix::Repository,
    old_tree: Option<&gix::Tree<'_>>,
    new_tree: &gix::Tree<'_>,
) -> Result<String> {
    use gix::object::tree::diff::ChangeDetached;

    // Build diff options with path tracking and no rename tracking.
    let mut opts = Options::default();
    opts.track_path();
    opts.track_rewrites(None);

    let changes: Vec<ChangeDetached> = repo
        .diff_tree_to_tree(old_tree, Some(new_tree), opts)
        .context("Failed to diff trees")?;

    let mut out = String::new();

    for change in &changes {
        match change {
            ChangeDetached::Addition {
                location,
                entry_mode: _,
                relation: _,
                id,
            } => {
                let path = location.to_string();
                out.push_str(&format!("diff --git a/dev/null b/{path}\n"));
                out.push_str("--- /dev/null\n");
                out.push_str(&format!("+++ b/{path}\n"));

                if let Ok(blob) = repo.find_object(*id) {
                    let content = String::from_utf8_lossy(&blob.data);
                    let lines: Vec<&str> = content.lines().collect();
                    let n = if content.is_empty() {
                        0
                    } else {
                        lines.len() + content.ends_with('\n') as usize
                    };
                    if n > 0 {
                        out.push_str(&format!("@@ -0,0 +1,{n} @@\n"));
                        for line in lines {
                            out.push('+');
                            out.push_str(line);
                            out.push('\n');
                        }
                    }
                }
            }
            ChangeDetached::Deletion {
                location,
                entry_mode: _,
                relation: _,
                id,
            } => {
                let path = location.to_string();
                out.push_str(&format!("diff --git a/{path} b/dev/null\n"));
                out.push_str(&format!("--- a/{path}\n"));
                out.push_str("+++ /dev/null\n");

                if let Ok(blob) = repo.find_object(*id) {
                    let content = String::from_utf8_lossy(&blob.data);
                    let lines: Vec<&str> = content.lines().collect();
                    let n = if content.is_empty() {
                        0
                    } else {
                        lines.len() + content.ends_with('\n') as usize
                    };
                    if n > 0 {
                        out.push_str(&format!("@@ -1,{n} +0,0 @@\n"));
                        for line in lines {
                            out.push('-');
                            out.push_str(line);
                            out.push('\n');
                        }
                    }
                }
            }
            ChangeDetached::Modification {
                location,
                previous_entry_mode: _,
                previous_id,
                entry_mode: _,
                id,
            } => {
                let path = location.to_string();
                out.push_str(&format!("diff --git a/{path} b/{path}\n"));
                out.push_str(&format!("--- a/{path}\n"));
                out.push_str(&format!("+++ b/{path}\n"));

                let old_content = repo.find_object(*previous_id).ok().map(|o| o.data.to_vec());
                let new_content = repo.find_object(*id).ok().map(|o| o.data.to_vec());

                match (old_content, new_content) {
                    (Some(old), Some(new)) => {
                        let old_str = String::from_utf8_lossy(&old).to_string();
                        let new_str = String::from_utf8_lossy(&new).to_string();
                        append_unified_diff(&mut out, &old_str, &new_str);
                    }
                    (Some(old), None) => {
                        let content = String::from_utf8_lossy(&old);
                        let lines: Vec<&str> = content.lines().collect();
                        let n = if content.is_empty() {
                            0
                        } else {
                            lines.len() + content.ends_with('\n') as usize
                        };
                        if n > 0 {
                            out.push_str(&format!("@@ -1,{n} +0,0 @@\n"));
                            for line in lines {
                                out.push('-');
                                out.push_str(line);
                                out.push('\n');
                            }
                        }
                    }
                    (None, Some(new)) => {
                        let content = String::from_utf8_lossy(&new);
                        let lines: Vec<&str> = content.lines().collect();
                        let n = if content.is_empty() {
                            0
                        } else {
                            lines.len() + content.ends_with('\n') as usize
                        };
                        if n > 0 {
                            out.push_str(&format!("@@ -0,0 +1,{n} @@\n"));
                            for line in lines {
                                out.push('+');
                                out.push_str(line);
                                out.push('\n');
                            }
                        }
                    }
                    (None, None) => {}
                }
            }
            ChangeDetached::Rewrite { .. } => {
                // Phase 1: skip rewrite entries (rename/copy is disabled anyway).
            }
        }
    }

    Ok(out)
}

/// Append a unified-diff hunk for the two text contents using imara-diff.
fn append_unified_diff(out: &mut String, old: &str, new: &str) {
    use imara_diff::UnifiedDiffBuilder;
    use imara_diff::intern::InternedInput;
    use imara_diff::{Algorithm, diff};

    if old.is_empty() && new.is_empty() {
        return;
    }

    let input = InternedInput::new(old, new);
    let builder = UnifiedDiffBuilder::new(&input);
    let result = diff(Algorithm::Histogram, &input, builder);
    if !result.is_empty() {
        out.push_str(&result);
    }
}

/// Convert a Unix timestamp to a human-readable relative time string.
fn format_relative_time(seconds: i64) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs() as i64;

    let diff = now - seconds;
    if diff < 0 {
        return "just now".into();
    }

    let minutes = diff / 60;
    let hours = minutes / 60;
    let days = hours / 24;
    let months = days / 30;
    let years = months / 12;

    if minutes < 1 {
        "just now".into()
    } else if minutes < 60 {
        format!("{}m ago", minutes)
    } else if hours < 24 {
        format!("{}h ago", hours)
    } else if days < 30 {
        format!("{}d ago", days)
    } else if months < 12 {
        format!("{}mo ago", months)
    } else {
        format!("{}y ago", years)
    }
}

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

    #[test]
    fn test_relative_time() {
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs() as i64;

        assert_eq!(format_relative_time(now), "just now");
        assert_eq!(format_relative_time(now - 30), "just now");
        assert_eq!(format_relative_time(now - 120), "2m ago");
        assert_eq!(format_relative_time(now - 3600), "1h ago");
        assert_eq!(format_relative_time(now - 7200), "2h ago");
        assert_eq!(format_relative_time(now - 86400), "1d ago");
        assert_eq!(format_relative_time(now - 86400 * 5), "5d ago");
        assert_eq!(format_relative_time(now - 86400 * 60), "2mo ago");
        assert_eq!(format_relative_time(now - 86400 * 400), "1y ago");
    }
}