1mod actions;
3mod graph;
4mod history;
5pub use graph::{graph_for_branch, graph_for_path, GitGraph};
6mod references;
7mod remotes;
8mod repository_actions;
9mod status_files;
10mod tag_actions;
11pub use actions::{commit, discard, set_staged};
12pub(crate) use actions::{run_git, validate_branch_name};
13use anyhow::{bail, Result};
14pub use history::{
15 commit_details, commit_file_view, commit_history, GitCommitDetails, GitCommitFileView,
16 GitHistoryPage,
17};
18pub use references::{references, GitReferences};
19pub use remotes::{remotes, GitRemote};
20pub use repository_actions::{repository_action, GitRepositoryAction};
21use serde::Serialize;
22use std::path::Path;
23pub use tag_actions::{tag_action, GitTagAction};
24
25#[derive(Serialize)]
26pub struct GitFile {
27 pub path: String,
28 pub staged: bool,
29 pub unstaged: bool,
30 pub conflicted: bool,
31 pub status: String,
32}
33#[derive(Serialize)]
34pub struct GitCommit {
35 pub sha: String,
36 pub summary: String,
37 pub author: String,
38 pub time: i64,
39}
40#[derive(Serialize)]
41pub struct GitStatus {
42 pub branch: Option<String>,
43 pub head: Option<String>,
44 pub upstream: Option<String>,
45 pub ahead: Option<usize>,
46 pub behind: Option<usize>,
47 pub state: String,
48 pub files: Vec<GitFile>,
49 pub commits: Vec<GitCommit>,
50 pub truncated: bool,
51}
52
53fn summarize_commit(commit: &git2::Commit<'_>) -> GitCommit {
54 GitCommit {
55 sha: commit.id().to_string(),
56 summary: commit.summary().unwrap_or_default().into(),
57 author: commit.author().name().unwrap_or_default().into(),
58 time: commit.time().seconds(),
59 }
60}
61
62fn history_walk(repo: &git2::Repository, head: git2::Oid) -> Result<git2::Revwalk<'_>> {
63 let mut walk = repo.revwalk()?;
64 walk.set_sorting(git2::Sort::TOPOLOGICAL | git2::Sort::TIME)?;
65 walk.push(head)?;
66 Ok(walk)
67}
68
69pub fn status(root: &Path) -> Result<GitStatus> {
70 let repo =
71 git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
72 repository_status(root, &repo)
73}
74
75pub fn inspect(root: &Path) -> Result<Option<GitStatus>> {
77 match git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path]) {
78 Ok(repo) => repository_status(root, &repo).map(Some),
79 Err(error)
80 if error.code() == git2::ErrorCode::NotFound
81 && root.is_dir()
82 && root
83 .join(".git")
84 .symlink_metadata()
85 .is_err_and(|cause| cause.kind() == std::io::ErrorKind::NotFound) =>
86 {
87 Ok(None)
88 }
89 Err(error) => Err(error.into()),
90 }
91}
92
93pub(crate) fn branch_upstream<'repo>(
94 repo: &'repo git2::Repository,
95 name: &str,
96) -> Option<git2::Branch<'repo>> {
97 repo.find_branch(name, git2::BranchType::Local)
98 .ok()?
99 .upstream()
100 .ok()
101}
102
103pub(crate) fn upstream_divergence(
104 repo: &git2::Repository,
105 head: Option<git2::Oid>,
106 upstream: Option<&git2::Branch<'_>>,
107) -> Option<(usize, usize)> {
108 repo.graph_ahead_behind(head?, upstream?.get().target()?)
109 .ok()
110}
111
112fn repository_status(root: &Path, repo: &git2::Repository) -> Result<GitStatus> {
113 let head = repo.head().ok();
114 let oid = head.as_ref().and_then(|head| head.target());
115 let branch = head
116 .as_ref()
117 .filter(|head| head.is_branch())
118 .and_then(|head| head.shorthand())
119 .map(str::to_owned);
120 let upstream = branch
121 .as_deref()
122 .and_then(|name| branch_upstream(repo, name));
123 let divergence = upstream_divergence(repo, oid, upstream.as_ref());
124 let (files, truncated) = status_files::status_files(root)?;
125 let mut commits = Vec::new();
126 if let Some(oid) = oid {
127 let walk = history_walk(repo, oid)?;
128 for oid in walk.take(30) {
129 let commit = repo.find_commit(oid?)?;
130 commits.push(summarize_commit(&commit));
131 }
132 }
133 Ok(GitStatus {
134 branch,
135 head: oid.map(|oid| oid.to_string()),
136 upstream: upstream.and_then(|branch| branch.name().ok().flatten().map(str::to_owned)),
137 ahead: divergence.map(|value| value.0),
138 behind: divergence.map(|value| value.1),
139 state: format!("{:?}", repo.state()),
140 files,
141 commits,
142 truncated,
143 })
144}
145
146pub fn diff(root: &Path, path: &str, staged: bool) -> Result<String> {
147 validate_file_path(path)?;
148 let repo =
149 git2::Repository::open_ext(root, git2::RepositoryOpenFlags::NO_SEARCH, &[] as &[&Path])?;
150 let mut options = git2::DiffOptions::new();
151 options
152 .context_lines(DIFF_CONTEXT_LINES)
153 .pathspec(path)
154 .disable_pathspec_match(true)
155 .include_untracked(true)
156 .show_untracked_content(true)
157 .recurse_untracked_dirs(true);
158 let tree = repo.head().ok().and_then(|head| head.peel_to_tree().ok());
159 let diff = if staged {
160 repo.diff_tree_to_index(tree.as_ref(), None, Some(&mut options))?
161 } else {
162 repo.diff_index_to_workdir(None, Some(&mut options))?
163 };
164 render_diff(&diff)
165}
166
167const MAX_DIFF_BYTES: usize = 1024 * 1024;
168const DIFF_CONTEXT_LINES: u32 = MAX_DIFF_BYTES as u32;
171
172fn render_diff(diff: &git2::Diff<'_>) -> Result<String> {
173 render_diff_for_path(diff, None)
174}
175
176fn matches_diff_path(delta: &git2::DiffDelta<'_>, path: &Path) -> bool {
177 delta.new_file().path() == Some(path) || delta.old_file().path() == Some(path)
178}
179
180fn render_diff_for_path(diff: &git2::Diff<'_>, path: Option<&str>) -> Result<String> {
181 let mut bytes = Vec::new();
182 let mut oversized = false;
183 diff.print(git2::DiffFormat::Patch, |delta, _, line| {
184 if path.is_some_and(|path| !matches_diff_path(&delta, Path::new(path))) {
185 return true;
186 }
187 if bytes.len() + line.content().len() > MAX_DIFF_BYTES {
188 oversized = true;
189 return false;
190 }
191 if matches!(line.origin(), '+' | '-' | ' ') {
192 bytes.push(line.origin() as u8);
193 }
194 bytes.extend_from_slice(line.content());
195 true
196 })
197 .or_else(|error| if oversized { Ok(()) } else { Err(error) })?;
198 if oversized {
199 bail!("Diff exceeds the 1 MiB preview limit");
200 }
201 Ok(String::from_utf8_lossy(&bytes).into_owned())
202}
203
204fn validate_file_path(path: &str) -> Result<()> {
205 if Path::new(path)
206 .components()
207 .any(|part| !matches!(part, std::path::Component::Normal(_)))
208 || path.is_empty()
209 {
210 bail!("Invalid repository file path");
211 }
212 Ok(())
213}
214
215#[cfg(test)]
216mod tests;