logiguard fork: GPUI xdg-activation keyboard-focus serial fix
Some checks failed
Update All Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Triage Project Sync (#84) / Sync triage project (push) Has been cancelled
release_nightly / notify_on_failure (push) Has been cancelled
release_nightly / check_style (push) Has been cancelled
release_nightly / run_tests_windows (push) Has been cancelled
release_nightly / clippy_windows (push) Has been cancelled
release_nightly / bundle_linux_aarch64 (push) Has been cancelled
release_nightly / bundle_linux_x86_64 (push) Has been cancelled
release_nightly / bundle_mac_aarch64 (push) Has been cancelled
release_nightly / bundle_mac_x86_64 (push) Has been cancelled
release_nightly / bundle_windows_aarch64 (push) Has been cancelled
release_nightly / bundle_windows_x86_64 (push) Has been cancelled
release_nightly / build_nix_linux_x86_64 (push) Has been cancelled
release_nightly / build_nix_mac_aarch64 (push) Has been cancelled
release_nightly / update_nightly_tag (push) Has been cancelled
Hotfix Review Monitor / check-hotfix-reviews (push) Has been cancelled
Stale PR Review Reminder / check-stale-prs (push) Has been cancelled
Update Weekly Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Bump collab-staging Tag / update-collab-staging-tag (push) Has been cancelled
compliance_check / scheduled_compliance_check (push) Has been cancelled
Some checks failed
Update All Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Triage Project Sync (#84) / Sync triage project (push) Has been cancelled
release_nightly / notify_on_failure (push) Has been cancelled
release_nightly / check_style (push) Has been cancelled
release_nightly / run_tests_windows (push) Has been cancelled
release_nightly / clippy_windows (push) Has been cancelled
release_nightly / bundle_linux_aarch64 (push) Has been cancelled
release_nightly / bundle_linux_x86_64 (push) Has been cancelled
release_nightly / bundle_mac_aarch64 (push) Has been cancelled
release_nightly / bundle_mac_x86_64 (push) Has been cancelled
release_nightly / bundle_windows_aarch64 (push) Has been cancelled
release_nightly / bundle_windows_x86_64 (push) Has been cancelled
release_nightly / build_nix_linux_x86_64 (push) Has been cancelled
release_nightly / build_nix_mac_aarch64 (push) Has been cancelled
release_nightly / update_nightly_tag (push) Has been cancelled
Hotfix Review Monitor / check-hotfix-reviews (push) Has been cancelled
Stale PR Review Reminder / check-stale-prs (push) Has been cancelled
Update Weekly Top Ranking Issues / update_top_ranking_issues (push) Has been cancelled
Bump collab-staging Tag / update-collab-staging-tag (push) Has been cancelled
compliance_check / scheduled_compliance_check (push) Has been cancelled
Single-commit orphan branch: full zed-industries/zed @ 8c74db0 source tree with a 3-file patch applied (no upstream history). Patch (crates/gpui_linux/src/linux/wayland/): - serial.rs: add SerialKind::KeyboardEnter - client.rs: store wl_keyboard.enter serial; add latest_serial_of() - window.rs: activate() uses keyboard-enter serial (Mutter focus gate) Mutter honors window activation only when the token carries the keyboard- focus serial from wl_keyboard.enter; GPUI used a stale mouse-press serial. See docs/tray-window-focus-wayland.md in logiguard. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
354
crates/git/src/blame.rs
Normal file
354
crates/git/src/blame.rs
Normal file
@@ -0,0 +1,354 @@
|
||||
use crate::Oid;
|
||||
use crate::commit::get_messages;
|
||||
use crate::repository::{GitBinary, RepoPath};
|
||||
use anyhow::{Context as _, Result};
|
||||
use collections::{HashMap, HashSet};
|
||||
use futures::AsyncWriteExt;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::ops::Range;
|
||||
use text::{LineEnding, Rope};
|
||||
use time::OffsetDateTime;
|
||||
use time::UtcOffset;
|
||||
use time::macros::format_description;
|
||||
use util::command::Stdio;
|
||||
|
||||
pub use git2 as libgit;
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Blame {
|
||||
pub entries: Vec<BlameEntry>,
|
||||
pub messages: HashMap<Oid, String>,
|
||||
}
|
||||
|
||||
impl Blame {
|
||||
pub(crate) async fn for_path(
|
||||
git: &GitBinary,
|
||||
path: &RepoPath,
|
||||
content: &Rope,
|
||||
line_ending: LineEnding,
|
||||
) -> Result<Self> {
|
||||
let output = run_git_blame(git, path, content, line_ending).await?;
|
||||
let mut entries = parse_git_blame(&output)?;
|
||||
entries.sort_unstable_by_key(|entry| entry.range.start);
|
||||
|
||||
let mut unique_shas = HashSet::default();
|
||||
|
||||
for entry in entries.iter_mut() {
|
||||
unique_shas.insert(entry.sha);
|
||||
}
|
||||
|
||||
let shas = unique_shas.into_iter().collect::<Vec<_>>();
|
||||
let messages = get_messages(git, &shas)
|
||||
.await
|
||||
.context("failed to get commit messages")?;
|
||||
|
||||
Ok(Self { entries, messages })
|
||||
}
|
||||
}
|
||||
|
||||
const GIT_BLAME_NO_COMMIT_ERROR: &str = "fatal: no such ref: HEAD";
|
||||
const GIT_BLAME_NO_PATH: &str = "fatal: no such path";
|
||||
|
||||
async fn run_git_blame(
|
||||
git: &GitBinary,
|
||||
path: &RepoPath,
|
||||
contents: &Rope,
|
||||
line_ending: LineEnding,
|
||||
) -> Result<String> {
|
||||
let mut child = {
|
||||
let span = ztracing::debug_span!("spawning git-blame command", path = path.as_unix_str());
|
||||
let _enter = span.enter();
|
||||
git.build_command(&["blame", "--incremental", "--contents", "-", "--"])
|
||||
.arg(path.as_unix_str())
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.context("starting git blame process")?
|
||||
};
|
||||
|
||||
let stdin = child
|
||||
.stdin
|
||||
.as_mut()
|
||||
.context("failed to get pipe to stdin of git blame command")?;
|
||||
|
||||
for chunk in text::chunks_with_line_ending(contents, line_ending) {
|
||||
stdin.write_all(chunk.as_bytes()).await?;
|
||||
}
|
||||
stdin.flush().await?;
|
||||
|
||||
let output = child.output().await.context("reading git blame output")?;
|
||||
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
let trimmed = stderr.trim();
|
||||
if trimmed == GIT_BLAME_NO_COMMIT_ERROR || trimmed.contains(GIT_BLAME_NO_PATH) {
|
||||
return Ok(String::new());
|
||||
}
|
||||
anyhow::bail!("git blame process failed: {stderr}");
|
||||
}
|
||||
|
||||
Ok(String::from_utf8(output.stdout)?)
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default, Debug, Clone, PartialEq, Eq)]
|
||||
pub struct BlameEntry {
|
||||
pub sha: Oid,
|
||||
|
||||
pub range: Range<u32>,
|
||||
|
||||
pub original_line_number: u32,
|
||||
|
||||
pub author: Option<String>,
|
||||
pub author_mail: Option<String>,
|
||||
pub author_time: Option<i64>,
|
||||
pub author_tz: Option<String>,
|
||||
|
||||
pub committer_name: Option<String>,
|
||||
pub committer_email: Option<String>,
|
||||
pub committer_time: Option<i64>,
|
||||
pub committer_tz: Option<String>,
|
||||
|
||||
pub summary: Option<String>,
|
||||
|
||||
pub previous: Option<String>,
|
||||
pub filename: String,
|
||||
}
|
||||
|
||||
impl BlameEntry {
|
||||
// Returns a BlameEntry by parsing the first line of a `git blame --incremental`
|
||||
// entry. The line MUST have this format:
|
||||
//
|
||||
// <40-byte-hex-sha1> <sourceline> <resultline> <num-lines>
|
||||
fn new_from_blame_line(line: &str) -> Result<BlameEntry> {
|
||||
let mut parts = line.split_whitespace();
|
||||
|
||||
let sha = parts
|
||||
.next()
|
||||
.and_then(|line| line.parse::<Oid>().ok())
|
||||
.context("parsing sha")?;
|
||||
|
||||
let original_line_number = parts
|
||||
.next()
|
||||
.and_then(|line| line.parse::<u32>().ok())
|
||||
.context("parsing original line number")?;
|
||||
let final_line_number = parts
|
||||
.next()
|
||||
.and_then(|line| line.parse::<u32>().ok())
|
||||
.context("parsing final line number")?;
|
||||
|
||||
let line_count = parts
|
||||
.next()
|
||||
.and_then(|line| line.parse::<u32>().ok())
|
||||
.context("parsing line count")?;
|
||||
|
||||
let start_line = final_line_number.saturating_sub(1);
|
||||
let end_line = start_line + line_count;
|
||||
let range = start_line..end_line;
|
||||
|
||||
Ok(Self {
|
||||
sha,
|
||||
range,
|
||||
original_line_number,
|
||||
..Default::default()
|
||||
})
|
||||
}
|
||||
|
||||
pub fn author_offset_date_time(&self) -> Result<time::OffsetDateTime> {
|
||||
if let (Some(author_time), Some(author_tz)) = (self.author_time, &self.author_tz) {
|
||||
let format = format_description!("[offset_hour][offset_minute]");
|
||||
let offset = UtcOffset::parse(author_tz, &format)?;
|
||||
let date_time_utc = OffsetDateTime::from_unix_timestamp(author_time)?;
|
||||
|
||||
Ok(date_time_utc.to_offset(offset))
|
||||
} else {
|
||||
// Directly return current time in UTC if there's no committer time or timezone
|
||||
Ok(time::OffsetDateTime::now_utc())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// parse_git_blame parses the output of `git blame --incremental`, which returns
|
||||
// all the blame-entries for a given path incrementally, as it finds them.
|
||||
//
|
||||
// Each entry *always* starts with:
|
||||
//
|
||||
// <40-byte-hex-sha1> <sourceline> <resultline> <num-lines>
|
||||
//
|
||||
// Each entry *always* ends with:
|
||||
//
|
||||
// filename <whitespace-quoted-filename-goes-here>
|
||||
//
|
||||
// Line numbers are 1-indexed.
|
||||
//
|
||||
// A `git blame --incremental` entry looks like this:
|
||||
//
|
||||
// 6ad46b5257ba16d12c5ca9f0d4900320959df7f4 2 2 1
|
||||
// author Joe Schmoe
|
||||
// author-mail <joe.schmoe@example.com>
|
||||
// author-time 1709741400
|
||||
// author-tz +0100
|
||||
// committer Joe Schmoe
|
||||
// committer-mail <joe.schmoe@example.com>
|
||||
// committer-time 1709741400
|
||||
// committer-tz +0100
|
||||
// summary Joe's cool commit
|
||||
// previous 486c2409237a2c627230589e567024a96751d475 index.js
|
||||
// filename index.js
|
||||
//
|
||||
// If the entry has the same SHA as an entry that was already printed then no
|
||||
// signature information is printed:
|
||||
//
|
||||
// 6ad46b5257ba16d12c5ca9f0d4900320959df7f4 3 4 1
|
||||
// previous 486c2409237a2c627230589e567024a96751d475 index.js
|
||||
// filename index.js
|
||||
//
|
||||
// More about `--incremental` output: https://mirrors.edge.kernel.org/pub/software/scm/git/docs/git-blame.html
|
||||
fn parse_git_blame(output: &str) -> Result<Vec<BlameEntry>> {
|
||||
let mut entries: Vec<BlameEntry> = Vec::new();
|
||||
let mut index: HashMap<Oid, usize> = HashMap::default();
|
||||
|
||||
let mut current_entry: Option<BlameEntry> = None;
|
||||
|
||||
for line in output.lines() {
|
||||
let mut done = false;
|
||||
|
||||
match &mut current_entry {
|
||||
None => {
|
||||
let mut new_entry = BlameEntry::new_from_blame_line(line)?;
|
||||
|
||||
if let Some(existing_entry) = index
|
||||
.get(&new_entry.sha)
|
||||
.and_then(|slot| entries.get(*slot))
|
||||
{
|
||||
new_entry.author.clone_from(&existing_entry.author);
|
||||
new_entry
|
||||
.author_mail
|
||||
.clone_from(&existing_entry.author_mail);
|
||||
new_entry.author_time = existing_entry.author_time;
|
||||
new_entry.author_tz.clone_from(&existing_entry.author_tz);
|
||||
new_entry
|
||||
.committer_name
|
||||
.clone_from(&existing_entry.committer_name);
|
||||
new_entry
|
||||
.committer_email
|
||||
.clone_from(&existing_entry.committer_email);
|
||||
new_entry.committer_time = existing_entry.committer_time;
|
||||
new_entry
|
||||
.committer_tz
|
||||
.clone_from(&existing_entry.committer_tz);
|
||||
new_entry.summary.clone_from(&existing_entry.summary);
|
||||
}
|
||||
|
||||
current_entry.replace(new_entry);
|
||||
}
|
||||
Some(entry) => {
|
||||
let Some((key, value)) = line.split_once(' ') else {
|
||||
continue;
|
||||
};
|
||||
let is_committed = !entry.sha.is_zero();
|
||||
match key {
|
||||
"filename" => {
|
||||
entry.filename = value.into();
|
||||
done = true;
|
||||
}
|
||||
"previous" => entry.previous = Some(value.into()),
|
||||
|
||||
"summary" if is_committed => entry.summary = Some(value.into()),
|
||||
"author" if is_committed => entry.author = Some(value.into()),
|
||||
"author-mail" if is_committed => entry.author_mail = Some(value.into()),
|
||||
"author-time" if is_committed => {
|
||||
entry.author_time = Some(value.parse::<i64>()?)
|
||||
}
|
||||
"author-tz" if is_committed => entry.author_tz = Some(value.into()),
|
||||
|
||||
"committer" if is_committed => entry.committer_name = Some(value.into()),
|
||||
"committer-mail" if is_committed => entry.committer_email = Some(value.into()),
|
||||
"committer-time" if is_committed => {
|
||||
entry.committer_time = Some(value.parse::<i64>()?)
|
||||
}
|
||||
"committer-tz" if is_committed => entry.committer_tz = Some(value.into()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
if done && let Some(entry) = current_entry.take() {
|
||||
index.insert(entry.sha, entries.len());
|
||||
|
||||
// We only want annotations that have a commit.
|
||||
if !entry.sha.is_zero() {
|
||||
entries.push(entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
use super::BlameEntry;
|
||||
use super::parse_git_blame;
|
||||
|
||||
fn read_test_data(filename: &str) -> String {
|
||||
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
path.push("test_data");
|
||||
path.push(filename);
|
||||
|
||||
std::fs::read_to_string(&path)
|
||||
.unwrap_or_else(|_| panic!("Could not read test data at {:?}. Is it generated?", path))
|
||||
}
|
||||
|
||||
fn assert_eq_golden(entries: &Vec<BlameEntry>, golden_filename: &str) {
|
||||
let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
|
||||
path.push("test_data");
|
||||
path.push("golden");
|
||||
path.push(format!("{}.json", golden_filename));
|
||||
|
||||
let mut have_json =
|
||||
serde_json::to_string_pretty(&entries).expect("could not serialize entries to JSON");
|
||||
// We always want to save with a trailing newline.
|
||||
have_json.push('\n');
|
||||
|
||||
let update = std::env::var("UPDATE_GOLDEN")
|
||||
.map(|val| val.eq_ignore_ascii_case("true"))
|
||||
.unwrap_or(false);
|
||||
|
||||
if update {
|
||||
std::fs::create_dir_all(path.parent().unwrap())
|
||||
.expect("could not create golden test data directory");
|
||||
std::fs::write(&path, have_json).expect("could not write out golden data");
|
||||
} else {
|
||||
let want_json =
|
||||
std::fs::read_to_string(&path).unwrap_or_else(|_| {
|
||||
panic!("could not read golden test data file at {:?}. Did you run the test with UPDATE_GOLDEN=true before?", path);
|
||||
}).replace("\r\n", "\n");
|
||||
|
||||
pretty_assertions::assert_eq!(have_json, want_json, "wrong blame entries");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_git_blame_not_committed() {
|
||||
let output = read_test_data("blame_incremental_not_committed");
|
||||
let entries = parse_git_blame(&output).unwrap();
|
||||
assert_eq_golden(&entries, "blame_incremental_not_committed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_git_blame_simple() {
|
||||
let output = read_test_data("blame_incremental_simple");
|
||||
let entries = parse_git_blame(&output).unwrap();
|
||||
assert_eq_golden(&entries, "blame_incremental_simple");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_git_blame_complex() {
|
||||
let output = read_test_data("blame_incremental_complex");
|
||||
let entries = parse_git_blame(&output).unwrap();
|
||||
assert_eq_golden(&entries, "blame_incremental_complex");
|
||||
}
|
||||
}
|
||||
91
crates/git/src/checkpoint.gitignore
Normal file
91
crates/git/src/checkpoint.gitignore
Normal file
@@ -0,0 +1,91 @@
|
||||
# This lists files that we don't track in checkpoints
|
||||
|
||||
# Compiled source and executables
|
||||
*.exe
|
||||
*.dll
|
||||
*.so
|
||||
*.dylib
|
||||
*.a
|
||||
*.lib
|
||||
*.o
|
||||
*.obj
|
||||
*.elf
|
||||
*.out
|
||||
*.app
|
||||
*.deb
|
||||
*.rpm
|
||||
*.dmg
|
||||
*.pkg
|
||||
*.msi
|
||||
|
||||
# Archives and compressed files
|
||||
*.7z
|
||||
*.zip
|
||||
*.tar
|
||||
*.tar.gz
|
||||
*.tgz
|
||||
*.tar.bz2
|
||||
*.tbz2
|
||||
*.tar.xz
|
||||
*.txz
|
||||
*.rar
|
||||
*.jar
|
||||
*.war
|
||||
*.ear
|
||||
|
||||
# Media files
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.png
|
||||
*.gif
|
||||
*.ico
|
||||
*.svg
|
||||
*.webp
|
||||
*.bmp
|
||||
*.tiff
|
||||
*.mp3
|
||||
*.mp4
|
||||
*.avi
|
||||
*.mov
|
||||
*.wmv
|
||||
*.flv
|
||||
*.mkv
|
||||
*.webm
|
||||
*.wav
|
||||
*.flac
|
||||
*.aac
|
||||
|
||||
# Database files
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
*.mdb
|
||||
|
||||
# Documents (often binary)
|
||||
*.pdf
|
||||
*.doc
|
||||
*.docx
|
||||
*.xls
|
||||
*.xlsx
|
||||
*.ppt
|
||||
*.pptx
|
||||
|
||||
# IDE and editor files
|
||||
.idea/
|
||||
.vscode/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Language-specific files
|
||||
*.rlib
|
||||
*.rmeta
|
||||
*.pdb
|
||||
*.class
|
||||
*.egg
|
||||
*.egg-info/
|
||||
*.pyc
|
||||
*.pto
|
||||
__pycache__
|
||||
162
crates/git/src/commit.rs
Normal file
162
crates/git/src/commit.rs
Normal file
@@ -0,0 +1,162 @@
|
||||
use crate::{
|
||||
BuildCommitPermalinkParams, GitHostingProviderRegistry, GitRemote, Oid, parse_git_remote_url,
|
||||
repository::GitBinary, status::StatusCode,
|
||||
};
|
||||
use anyhow::{Context as _, Result};
|
||||
use collections::HashMap;
|
||||
use gpui::SharedString;
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub struct ParsedCommitMessage {
|
||||
pub message: SharedString,
|
||||
pub permalink: Option<url::Url>,
|
||||
pub pull_request: Option<crate::hosting_provider::PullRequest>,
|
||||
pub remote: Option<GitRemote>,
|
||||
}
|
||||
|
||||
impl ParsedCommitMessage {
|
||||
pub fn parse(
|
||||
sha: String,
|
||||
message: String,
|
||||
remote_url: Option<&str>,
|
||||
provider_registry: Option<Arc<GitHostingProviderRegistry>>,
|
||||
) -> Self {
|
||||
if let Some((hosting_provider, remote)) = provider_registry
|
||||
.and_then(|reg| remote_url.and_then(|url| parse_git_remote_url(reg, url)))
|
||||
{
|
||||
let pull_request = hosting_provider.extract_pull_request(&remote, &message);
|
||||
Self {
|
||||
message: message.into(),
|
||||
permalink: Some(
|
||||
hosting_provider
|
||||
.build_commit_permalink(&remote, BuildCommitPermalinkParams { sha: &sha }),
|
||||
),
|
||||
pull_request,
|
||||
remote: Some(GitRemote {
|
||||
host: hosting_provider,
|
||||
owner: remote.owner.into(),
|
||||
repo: remote.repo.into(),
|
||||
}),
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
message: message.into(),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn get_messages(git: &GitBinary, shas: &[Oid]) -> Result<HashMap<Oid, String>> {
|
||||
if shas.is_empty() {
|
||||
return Ok(HashMap::default());
|
||||
}
|
||||
|
||||
let output = if cfg!(windows) {
|
||||
// Windows has a maximum invocable command length, so we chunk the input.
|
||||
// Actual max is 32767, but we leave some room for the rest of the command as we aren't in precise control of what std might do here
|
||||
const MAX_CMD_LENGTH: usize = 30000;
|
||||
// 40 bytes of hash, 2 quotes and a separating space
|
||||
const SHA_LENGTH: usize = 40 + 2 + 1;
|
||||
const MAX_ENTRIES_PER_INVOCATION: usize = MAX_CMD_LENGTH / SHA_LENGTH;
|
||||
|
||||
let mut result = vec![];
|
||||
for shas in shas.chunks(MAX_ENTRIES_PER_INVOCATION) {
|
||||
let partial = get_messages_impl(git, shas).await?;
|
||||
result.extend(partial);
|
||||
}
|
||||
result
|
||||
} else {
|
||||
get_messages_impl(git, shas).await?
|
||||
};
|
||||
|
||||
Ok(shas
|
||||
.iter()
|
||||
.cloned()
|
||||
.zip(output)
|
||||
.collect::<HashMap<Oid, String>>())
|
||||
}
|
||||
|
||||
async fn get_messages_impl(git: &GitBinary, shas: &[Oid]) -> Result<Vec<String>> {
|
||||
const MARKER: &str = "<MARKER>";
|
||||
let output = git
|
||||
.build_command(&["show"])
|
||||
.arg("-s")
|
||||
.arg(format!("--format=%B{}", MARKER))
|
||||
.args(shas.iter().map(ToString::to_string))
|
||||
.output()
|
||||
.await
|
||||
.context("starting git show process")?;
|
||||
anyhow::ensure!(
|
||||
output.status.success(),
|
||||
"'git show' failed with error {:?}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
Ok(String::from_utf8_lossy(&output.stdout)
|
||||
.trim()
|
||||
.split_terminator(MARKER)
|
||||
.map(|str| str.trim().replace("<", "<").replace(">", ">"))
|
||||
.collect::<Vec<_>>())
|
||||
}
|
||||
|
||||
/// Parse the output of `git diff --name-status -z`
|
||||
pub fn parse_git_diff_name_status(content: &str) -> impl Iterator<Item = (&str, StatusCode)> {
|
||||
let mut parts = content.split('\0');
|
||||
std::iter::from_fn(move || {
|
||||
loop {
|
||||
let status_str = parts.next()?;
|
||||
let path = parts.next()?;
|
||||
let status = match status_str {
|
||||
"M" => StatusCode::Modified,
|
||||
"A" => StatusCode::Added,
|
||||
"D" => StatusCode::Deleted,
|
||||
_ => continue,
|
||||
};
|
||||
return Some((path, status));
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_git_diff_name_status() {
|
||||
let input = concat!(
|
||||
"M\x00Cargo.lock\x00",
|
||||
"M\x00crates/project/Cargo.toml\x00",
|
||||
"M\x00crates/project/src/buffer_store.rs\x00",
|
||||
"D\x00crates/project/src/git.rs\x00",
|
||||
"A\x00crates/project/src/git_store.rs\x00",
|
||||
"A\x00crates/project/src/git_store/git_traversal.rs\x00",
|
||||
"M\x00crates/project/src/project.rs\x00",
|
||||
"M\x00crates/project/src/worktree_store.rs\x00",
|
||||
"M\x00crates/project_panel/src/project_panel.rs\x00",
|
||||
);
|
||||
|
||||
let output = parse_git_diff_name_status(input).collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
output,
|
||||
&[
|
||||
("Cargo.lock", StatusCode::Modified),
|
||||
("crates/project/Cargo.toml", StatusCode::Modified),
|
||||
("crates/project/src/buffer_store.rs", StatusCode::Modified),
|
||||
("crates/project/src/git.rs", StatusCode::Deleted),
|
||||
("crates/project/src/git_store.rs", StatusCode::Added),
|
||||
(
|
||||
"crates/project/src/git_store/git_traversal.rs",
|
||||
StatusCode::Added,
|
||||
),
|
||||
("crates/project/src/project.rs", StatusCode::Modified),
|
||||
("crates/project/src/worktree_store.rs", StatusCode::Modified),
|
||||
(
|
||||
"crates/project_panel/src/project_panel.rs",
|
||||
StatusCode::Modified
|
||||
),
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
272
crates/git/src/git.rs
Normal file
272
crates/git/src/git.rs
Normal file
@@ -0,0 +1,272 @@
|
||||
pub mod blame;
|
||||
pub mod commit;
|
||||
mod hosting_provider;
|
||||
mod remote;
|
||||
pub mod repository;
|
||||
pub mod stash;
|
||||
pub mod status;
|
||||
|
||||
pub use crate::hosting_provider::*;
|
||||
pub use crate::remote::*;
|
||||
use anyhow::{Context as _, Result};
|
||||
pub use git2 as libgit;
|
||||
use gpui::{Action, actions};
|
||||
pub use repository::RemoteCommandOutput;
|
||||
use schemars::JsonSchema;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fmt;
|
||||
use std::str::FromStr;
|
||||
|
||||
pub const DOT_GIT: &str = ".git";
|
||||
pub const GITIGNORE: &str = ".gitignore";
|
||||
pub const FSMONITOR_DAEMON: &str = "fsmonitor--daemon";
|
||||
pub const LFS_DIR: &str = "lfs";
|
||||
pub const COMMIT_MESSAGE: &str = "COMMIT_EDITMSG";
|
||||
pub const INDEX_LOCK: &str = "index.lock";
|
||||
pub const REPO_EXCLUDE: &str = "info/exclude";
|
||||
|
||||
actions!(
|
||||
git,
|
||||
[
|
||||
// per-hunk
|
||||
/// Toggles the staged state of the hunk or status entry at cursor.
|
||||
ToggleStaged,
|
||||
/// Stage status entries between an anchor entry and the cursor.
|
||||
StageRange,
|
||||
/// Stages the current hunk and moves to the next one.
|
||||
StageAndNext,
|
||||
/// Unstages the current hunk and moves to the next one.
|
||||
UnstageAndNext,
|
||||
/// Restores the selected hunks to their original state.
|
||||
#[action(deprecated_aliases = ["editor::RevertSelectedHunks"])]
|
||||
Restore,
|
||||
/// Restores the selected hunks to their original state and moves to the
|
||||
/// next one.
|
||||
RestoreAndNext,
|
||||
// per-file
|
||||
/// Shows git blame information for the current file.
|
||||
#[action(deprecated_aliases = ["editor::ToggleGitBlame"])]
|
||||
Blame,
|
||||
/// Shows the git history for the selected file, folder, or project.
|
||||
FileHistory,
|
||||
/// Stages the current file.
|
||||
StageFile,
|
||||
/// Unstages the current file.
|
||||
UnstageFile,
|
||||
// repo-wide
|
||||
/// Stages all changes in the repository.
|
||||
StageAll,
|
||||
/// Unstages all changes in the repository.
|
||||
UnstageAll,
|
||||
/// Stashes all changes in the repository, including untracked files.
|
||||
StashAll,
|
||||
/// Pops the most recent stash.
|
||||
StashPop,
|
||||
/// Apply the most recent stash.
|
||||
StashApply,
|
||||
/// Restores all tracked files to their last committed state.
|
||||
RestoreTrackedFiles,
|
||||
/// Moves all untracked files to trash.
|
||||
TrashUntrackedFiles,
|
||||
/// Undoes the last commit, keeping changes in the working directory.
|
||||
Uncommit,
|
||||
/// Pushes commits to the remote repository.
|
||||
Push,
|
||||
/// Pushes commits to a specific remote branch.
|
||||
PushTo,
|
||||
/// Force pushes commits to the remote repository.
|
||||
ForcePush,
|
||||
/// Pulls changes from the remote repository.
|
||||
Pull,
|
||||
/// Pulls changes from the remote repository with rebase.
|
||||
PullRebase,
|
||||
/// Fetches changes from the remote repository.
|
||||
Fetch,
|
||||
/// Fetches changes from a specific remote.
|
||||
FetchFrom,
|
||||
/// Creates a new commit with staged changes.
|
||||
Commit,
|
||||
/// Amends the last commit with staged changes.
|
||||
Amend,
|
||||
/// Enable the --signoff option.
|
||||
Signoff,
|
||||
/// Cancels the current git operation.
|
||||
Cancel,
|
||||
/// Expands the commit message editor.
|
||||
ExpandCommitEditor,
|
||||
/// Toggles whether the commit message editor fills all the available
|
||||
/// vertical space within the git panel.
|
||||
ToggleFillCommitEditor,
|
||||
/// Generates a commit message using AI.
|
||||
GenerateCommitMessage,
|
||||
/// Initializes a new git repository.
|
||||
Init,
|
||||
/// Opens all modified files in the editor.
|
||||
OpenModifiedFiles,
|
||||
/// Clones a repository.
|
||||
Clone,
|
||||
ViewCommit,
|
||||
/// Adds a file to .gitignore.
|
||||
AddToGitignore,
|
||||
/// Copies the current branch name to the clipboard.
|
||||
CopyBranchName,
|
||||
]
|
||||
);
|
||||
|
||||
/// Renames a git branch.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
|
||||
#[action(namespace = git)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RenameBranch {
|
||||
/// The branch to rename.
|
||||
///
|
||||
/// Default: the current branch.
|
||||
#[serde(default)]
|
||||
pub branch: Option<String>,
|
||||
}
|
||||
|
||||
/// Restores a file to its last committed state, discarding local changes.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
|
||||
#[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct RestoreFile {
|
||||
#[serde(default)]
|
||||
pub skip_prompt: bool,
|
||||
}
|
||||
|
||||
/// The length of a Git short SHA.
|
||||
pub const SHORT_SHA_LENGTH: usize = 7;
|
||||
|
||||
#[derive(Clone, Copy, Eq, Hash, PartialEq)]
|
||||
pub struct Oid(libgit::Oid);
|
||||
|
||||
impl Oid {
|
||||
pub fn from_bytes(bytes: &[u8]) -> Result<Self> {
|
||||
let oid = libgit::Oid::from_bytes(bytes).context("failed to parse bytes into git oid")?;
|
||||
Ok(Self(oid))
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub fn random(rng: &mut impl rand::Rng) -> Self {
|
||||
let mut bytes = [0; 20];
|
||||
rng.fill(&mut bytes);
|
||||
Self::from_bytes(&bytes).unwrap()
|
||||
}
|
||||
|
||||
pub fn as_bytes(&self) -> &[u8] {
|
||||
self.0.as_bytes()
|
||||
}
|
||||
|
||||
pub(crate) fn is_zero(&self) -> bool {
|
||||
self.0.is_zero()
|
||||
}
|
||||
|
||||
/// Returns this [`Oid`] as a short SHA.
|
||||
pub fn display_short(&self) -> String {
|
||||
self.to_string().chars().take(SHORT_SHA_LENGTH).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<&str> for Oid {
|
||||
type Error = anyhow::Error;
|
||||
|
||||
fn try_from(value: &str) -> std::prelude::v1::Result<Self, Self::Error> {
|
||||
Oid::from_str(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for Oid {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> std::prelude::v1::Result<Self, Self::Err> {
|
||||
libgit::Oid::from_str(s)
|
||||
.context("parsing git oid")
|
||||
.map(Self)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Debug for Oid {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
fmt::Display::fmt(self, f)
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Oid {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
self.0.fmt(f)
|
||||
}
|
||||
}
|
||||
|
||||
impl Serialize for Oid {
|
||||
fn serialize<S>(&self, serializer: S) -> std::prelude::v1::Result<S::Ok, S::Error>
|
||||
where
|
||||
S: serde::Serializer,
|
||||
{
|
||||
serializer.serialize_str(&self.0.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Oid {
|
||||
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
|
||||
where
|
||||
D: serde::Deserializer<'de>,
|
||||
{
|
||||
let s = String::deserialize(deserializer)?;
|
||||
s.parse::<Oid>().map_err(serde::de::Error::custom)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for Oid {
|
||||
fn default() -> Self {
|
||||
Self(libgit::Oid::zero())
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Oid> for u32 {
|
||||
fn from(oid: Oid) -> Self {
|
||||
let bytes = oid.0.as_bytes();
|
||||
debug_assert!(bytes.len() > 4);
|
||||
|
||||
let mut u32_bytes: [u8; 4] = [0; 4];
|
||||
u32_bytes.copy_from_slice(&bytes[..4]);
|
||||
|
||||
u32::from_ne_bytes(u32_bytes)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Oid> for usize {
|
||||
fn from(oid: Oid) -> Self {
|
||||
let bytes = oid.0.as_bytes();
|
||||
debug_assert!(bytes.len() > 8);
|
||||
|
||||
let mut u64_bytes: [u8; 8] = [0; 8];
|
||||
u64_bytes.copy_from_slice(&bytes[..8]);
|
||||
|
||||
u64::from_ne_bytes(u64_bytes) as usize
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(i32)]
|
||||
#[derive(Copy, Clone, Debug)]
|
||||
pub enum RunHook {
|
||||
PreCommit,
|
||||
}
|
||||
|
||||
impl RunHook {
|
||||
pub fn as_str(&self) -> &str {
|
||||
match self {
|
||||
Self::PreCommit => "pre-commit",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn to_proto(&self) -> i32 {
|
||||
*self as i32
|
||||
}
|
||||
|
||||
pub fn from_proto(value: i32) -> Option<Self> {
|
||||
match value {
|
||||
0 => Some(Self::PreCommit),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
255
crates/git/src/hosting_provider.rs
Normal file
255
crates/git/src/hosting_provider.rs
Normal file
@@ -0,0 +1,255 @@
|
||||
use std::{ops::Range, sync::Arc};
|
||||
|
||||
use anyhow::Result;
|
||||
use async_trait::async_trait;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use gpui::{App, Global, SharedString};
|
||||
use http_client::HttpClient;
|
||||
use itertools::Itertools;
|
||||
use parking_lot::RwLock;
|
||||
use url::Url;
|
||||
|
||||
use crate::repository::RepoPath;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone)]
|
||||
pub struct PullRequest {
|
||||
pub number: u32,
|
||||
pub url: Url,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct GitRemote {
|
||||
pub host: Arc<dyn GitHostingProvider + Send + Sync + 'static>,
|
||||
pub owner: SharedString,
|
||||
pub repo: SharedString,
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for GitRemote {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("GitRemote")
|
||||
.field("host", &self.host.name())
|
||||
.field("owner", &self.owner)
|
||||
.field("repo", &self.repo)
|
||||
.finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl GitRemote {
|
||||
pub fn host_supports_avatars(&self) -> bool {
|
||||
self.host.supports_avatars()
|
||||
}
|
||||
|
||||
pub async fn avatar_url(
|
||||
&self,
|
||||
commit: SharedString,
|
||||
author_email: Option<SharedString>,
|
||||
client: Arc<dyn HttpClient>,
|
||||
) -> Option<Url> {
|
||||
self.host
|
||||
.commit_author_avatar_url(&self.owner, &self.repo, commit, author_email, client)
|
||||
.await
|
||||
.ok()
|
||||
.flatten()
|
||||
}
|
||||
}
|
||||
|
||||
pub struct BuildCommitPermalinkParams<'a> {
|
||||
pub sha: &'a str,
|
||||
}
|
||||
|
||||
pub struct BuildPermalinkParams<'a> {
|
||||
pub sha: &'a str,
|
||||
/// URL-escaped path using unescaped `/` as the directory separator.
|
||||
pub path: String,
|
||||
pub selection: Option<Range<u32>>,
|
||||
}
|
||||
|
||||
impl<'a> BuildPermalinkParams<'a> {
|
||||
pub fn new(sha: &'a str, path: &RepoPath, selection: Option<Range<u32>>) -> Self {
|
||||
Self {
|
||||
sha,
|
||||
path: path.components().map(urlencoding::encode).join("/"),
|
||||
selection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Git hosting provider.
|
||||
#[async_trait]
|
||||
pub trait GitHostingProvider {
|
||||
/// Returns the name of the provider.
|
||||
fn name(&self) -> String;
|
||||
|
||||
/// Returns the base URL of the provider.
|
||||
fn base_url(&self) -> Url;
|
||||
|
||||
/// Returns a permalink to a Git commit on this hosting provider.
|
||||
fn build_commit_permalink(
|
||||
&self,
|
||||
remote: &ParsedGitRemote,
|
||||
params: BuildCommitPermalinkParams,
|
||||
) -> Url;
|
||||
|
||||
/// Returns a permalink to a file and/or selection on this hosting provider.
|
||||
fn build_permalink(&self, remote: ParsedGitRemote, params: BuildPermalinkParams) -> Url;
|
||||
|
||||
/// Returns a URL to create a pull request on this hosting provider.
|
||||
fn build_create_pull_request_url(
|
||||
&self,
|
||||
_remote: &ParsedGitRemote,
|
||||
_source_branch: &str,
|
||||
) -> Option<Url> {
|
||||
None
|
||||
}
|
||||
|
||||
/// Returns whether this provider supports avatars.
|
||||
fn supports_avatars(&self) -> bool;
|
||||
|
||||
/// Returns a URL fragment to the given line selection.
|
||||
fn line_fragment(&self, selection: &Range<u32>) -> String {
|
||||
if selection.start == selection.end {
|
||||
let line = selection.start + 1;
|
||||
|
||||
self.format_line_number(line)
|
||||
} else {
|
||||
let start_line = selection.start + 1;
|
||||
let end_line = selection.end + 1;
|
||||
|
||||
self.format_line_numbers(start_line, end_line)
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns a formatted line number to be placed in a permalink URL.
|
||||
fn format_line_number(&self, line: u32) -> String;
|
||||
|
||||
/// Returns a formatted range of line numbers to be placed in a permalink URL.
|
||||
fn format_line_numbers(&self, start_line: u32, end_line: u32) -> String;
|
||||
|
||||
fn parse_remote_url(&self, url: &str) -> Option<ParsedGitRemote>;
|
||||
|
||||
fn extract_pull_request(
|
||||
&self,
|
||||
_remote: &ParsedGitRemote,
|
||||
_message: &str,
|
||||
) -> Option<PullRequest> {
|
||||
None
|
||||
}
|
||||
|
||||
async fn commit_author_avatar_url(
|
||||
&self,
|
||||
_repo_owner: &str,
|
||||
_repo: &str,
|
||||
_commit: SharedString,
|
||||
_author_email: Option<SharedString>,
|
||||
_http_client: Arc<dyn HttpClient>,
|
||||
) -> Result<Option<Url>> {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default, Deref, DerefMut)]
|
||||
struct GlobalGitHostingProviderRegistry(Arc<GitHostingProviderRegistry>);
|
||||
|
||||
impl Global for GlobalGitHostingProviderRegistry {}
|
||||
|
||||
#[derive(Default)]
|
||||
struct GitHostingProviderRegistryState {
|
||||
default_providers: Vec<Arc<dyn GitHostingProvider + Send + Sync + 'static>>,
|
||||
setting_providers: Vec<Arc<dyn GitHostingProvider + Send + Sync + 'static>>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct GitHostingProviderRegistry {
|
||||
state: RwLock<GitHostingProviderRegistryState>,
|
||||
}
|
||||
|
||||
impl GitHostingProviderRegistry {
|
||||
/// Returns the global [`GitHostingProviderRegistry`].
|
||||
#[track_caller]
|
||||
pub fn global(cx: &App) -> Arc<Self> {
|
||||
cx.global::<GlobalGitHostingProviderRegistry>().0.clone()
|
||||
}
|
||||
|
||||
/// Returns the global [`GitHostingProviderRegistry`], if one is set.
|
||||
pub fn try_global(cx: &App) -> Option<Arc<Self>> {
|
||||
cx.try_global::<GlobalGitHostingProviderRegistry>()
|
||||
.map(|registry| registry.0.clone())
|
||||
}
|
||||
|
||||
/// Returns the global [`GitHostingProviderRegistry`].
|
||||
///
|
||||
/// Inserts a default [`GitHostingProviderRegistry`] if one does not yet exist.
|
||||
pub fn default_global(cx: &mut App) -> Arc<Self> {
|
||||
cx.default_global::<GlobalGitHostingProviderRegistry>()
|
||||
.0
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Sets the global [`GitHostingProviderRegistry`].
|
||||
pub fn set_global(registry: Arc<GitHostingProviderRegistry>, cx: &mut App) {
|
||||
cx.set_global(GlobalGitHostingProviderRegistry(registry));
|
||||
}
|
||||
|
||||
/// Returns a new [`GitHostingProviderRegistry`].
|
||||
pub fn new() -> Self {
|
||||
Self {
|
||||
state: RwLock::new(GitHostingProviderRegistryState {
|
||||
setting_providers: Vec::default(),
|
||||
default_providers: Vec::default(),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the list of all [`GitHostingProvider`]s in the registry.
|
||||
pub fn list_hosting_providers(
|
||||
&self,
|
||||
) -> Vec<Arc<dyn GitHostingProvider + Send + Sync + 'static>> {
|
||||
let state = self.state.read();
|
||||
state
|
||||
.default_providers
|
||||
.iter()
|
||||
.cloned()
|
||||
.chain(state.setting_providers.iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn set_setting_providers(
|
||||
&self,
|
||||
providers: impl IntoIterator<Item = Arc<dyn GitHostingProvider + Send + Sync + 'static>>,
|
||||
) {
|
||||
let mut state = self.state.write();
|
||||
state.setting_providers.clear();
|
||||
state.setting_providers.extend(providers);
|
||||
}
|
||||
|
||||
/// Adds the provided [`GitHostingProvider`] to the registry.
|
||||
pub fn register_hosting_provider(
|
||||
&self,
|
||||
provider: Arc<dyn GitHostingProvider + Send + Sync + 'static>,
|
||||
) {
|
||||
self.state.write().default_providers.push(provider);
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct ParsedGitRemote {
|
||||
pub owner: Arc<str>,
|
||||
pub repo: Arc<str>,
|
||||
}
|
||||
|
||||
pub fn parse_git_remote_url(
|
||||
provider_registry: Arc<GitHostingProviderRegistry>,
|
||||
url: &str,
|
||||
) -> Option<(
|
||||
Arc<dyn GitHostingProvider + Send + Sync + 'static>,
|
||||
ParsedGitRemote,
|
||||
)> {
|
||||
provider_registry
|
||||
.list_hosting_providers()
|
||||
.into_iter()
|
||||
.find_map(|provider| {
|
||||
provider
|
||||
.parse_remote_url(url)
|
||||
.map(|parsed_remote| (provider, parsed_remote))
|
||||
})
|
||||
}
|
||||
98
crates/git/src/remote.rs
Normal file
98
crates/git/src/remote.rs
Normal file
@@ -0,0 +1,98 @@
|
||||
use std::str::FromStr;
|
||||
use std::sync::LazyLock;
|
||||
|
||||
use derive_more::Deref;
|
||||
use regex::Regex;
|
||||
use url::Url;
|
||||
|
||||
/// The URL to a Git remote.
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Deref)]
|
||||
pub struct RemoteUrl(Url);
|
||||
|
||||
static USERNAME_REGEX: LazyLock<Regex> =
|
||||
LazyLock::new(|| Regex::new(r"^[0-9a-zA-Z\-_]+@").expect("Failed to create USERNAME_REGEX"));
|
||||
|
||||
impl FromStr for RemoteUrl {
|
||||
type Err = url::ParseError;
|
||||
|
||||
fn from_str(input: &str) -> Result<Self, Self::Err> {
|
||||
if USERNAME_REGEX.is_match(input) {
|
||||
// Rewrite remote URLs like `git@github.com:user/repo.git` to `ssh://git@github.com/user/repo.git`
|
||||
let ssh_url = format!("ssh://{}", input.replacen(':', "/", 1));
|
||||
Ok(RemoteUrl(Url::parse(&ssh_url)?))
|
||||
} else {
|
||||
Ok(RemoteUrl(Url::parse(input)?))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parsing_valid_remote_urls() {
|
||||
let valid_urls = vec![
|
||||
(
|
||||
"https://github.com/octocat/zed.git",
|
||||
"https",
|
||||
"github.com",
|
||||
"/octocat/zed.git",
|
||||
),
|
||||
(
|
||||
"git@github.com:octocat/zed.git",
|
||||
"ssh",
|
||||
"github.com",
|
||||
"/octocat/zed.git",
|
||||
),
|
||||
(
|
||||
"org-000000@github.com:octocat/zed.git",
|
||||
"ssh",
|
||||
"github.com",
|
||||
"/octocat/zed.git",
|
||||
),
|
||||
(
|
||||
"ssh://git@github.com/octocat/zed.git",
|
||||
"ssh",
|
||||
"github.com",
|
||||
"/octocat/zed.git",
|
||||
),
|
||||
(
|
||||
"file:///path/to/local/zed",
|
||||
"file",
|
||||
"",
|
||||
"/path/to/local/zed",
|
||||
),
|
||||
];
|
||||
|
||||
for (input, expected_scheme, expected_host, expected_path) in valid_urls {
|
||||
let parsed = input.parse::<RemoteUrl>().expect("failed to parse URL");
|
||||
let url = parsed.0;
|
||||
assert_eq!(
|
||||
url.scheme(),
|
||||
expected_scheme,
|
||||
"unexpected scheme for {input:?}",
|
||||
);
|
||||
assert_eq!(
|
||||
url.host_str().unwrap_or(""),
|
||||
expected_host,
|
||||
"unexpected host for {input:?}",
|
||||
);
|
||||
assert_eq!(url.path(), expected_path, "unexpected path for {input:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parsing_invalid_remote_urls() {
|
||||
let invalid_urls = vec!["not_a_url", "http://"];
|
||||
|
||||
for url in invalid_urls {
|
||||
assert!(
|
||||
url.parse::<RemoteUrl>().is_err(),
|
||||
"expected \"{url}\" to not parse as a Git remote URL",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
4578
crates/git/src/repository.rs
Normal file
4578
crates/git/src/repository.rs
Normal file
File diff suppressed because it is too large
Load Diff
223
crates/git/src/stash.rs
Normal file
223
crates/git/src/stash.rs
Normal file
@@ -0,0 +1,223 @@
|
||||
use crate::Oid;
|
||||
use anyhow::{Context, Result, anyhow};
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
pub struct StashEntry {
|
||||
pub index: usize,
|
||||
pub oid: Oid,
|
||||
pub message: String,
|
||||
pub branch: Option<String>,
|
||||
pub timestamp: i64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
|
||||
pub struct GitStash {
|
||||
pub entries: Arc<[StashEntry]>,
|
||||
}
|
||||
|
||||
impl GitStash {
|
||||
pub fn apply(&mut self, other: GitStash) {
|
||||
self.entries = other.entries;
|
||||
}
|
||||
}
|
||||
|
||||
impl FromStr for GitStash {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
if s.trim().is_empty() {
|
||||
return Ok(Self::default());
|
||||
}
|
||||
|
||||
let mut entries = Vec::new();
|
||||
let mut errors = Vec::new();
|
||||
|
||||
for (line_num, line) in s.lines().enumerate() {
|
||||
if line.trim().is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
match parse_stash_line(line) {
|
||||
Ok(entry) => entries.push(entry),
|
||||
Err(e) => {
|
||||
errors.push(format!("Line {}: {}", line_num + 1, e));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we have some valid entries but also some errors, log the errors but continue
|
||||
if !errors.is_empty() && !entries.is_empty() {
|
||||
log::warn!("Failed to parse some stash entries: {}", errors.join(", "));
|
||||
} else if !errors.is_empty() {
|
||||
return Err(anyhow!(
|
||||
"Failed to parse stash entries: {}",
|
||||
errors.join(", ")
|
||||
));
|
||||
}
|
||||
|
||||
Ok(Self {
|
||||
entries: entries.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a single stash line in the format: "stash@{N}\0<oid>\0<timestamp>\0<message>"
|
||||
fn parse_stash_line(line: &str) -> Result<StashEntry> {
|
||||
let parts: Vec<&str> = line.splitn(4, '\0').collect();
|
||||
|
||||
if parts.len() != 4 {
|
||||
return Err(anyhow!(
|
||||
"Expected 4 null-separated parts, got {}",
|
||||
parts.len()
|
||||
));
|
||||
}
|
||||
|
||||
let index = parse_stash_index(parts[0])
|
||||
.with_context(|| format!("Failed to parse stash index from '{}'", parts[0]))?;
|
||||
|
||||
let oid = Oid::from_str(parts[1])
|
||||
.with_context(|| format!("Failed to parse OID from '{}'", parts[1]))?;
|
||||
|
||||
let timestamp = parts[2]
|
||||
.parse::<i64>()
|
||||
.with_context(|| format!("Failed to parse timestamp from '{}'", parts[2]))?;
|
||||
|
||||
let (branch, message) = parse_stash_message(parts[3]);
|
||||
|
||||
Ok(StashEntry {
|
||||
index,
|
||||
oid,
|
||||
message: message.to_string(),
|
||||
branch: branch.map(Into::into),
|
||||
timestamp,
|
||||
})
|
||||
}
|
||||
|
||||
/// Parse stash index from format "stash@{N}" where N is the index
|
||||
fn parse_stash_index(input: &str) -> Result<usize> {
|
||||
let trimmed = input.trim();
|
||||
|
||||
if !trimmed.starts_with("stash@{") || !trimmed.ends_with('}') {
|
||||
return Err(anyhow!(
|
||||
"Invalid stash index format: expected 'stash@{{N}}'"
|
||||
));
|
||||
}
|
||||
|
||||
let index_str = trimmed
|
||||
.strip_prefix("stash@{")
|
||||
.and_then(|s| s.strip_suffix('}'))
|
||||
.ok_or_else(|| anyhow!("Failed to extract index from stash reference"))?;
|
||||
|
||||
index_str
|
||||
.parse::<usize>()
|
||||
.with_context(|| format!("Invalid stash index number: '{}'", index_str))
|
||||
}
|
||||
|
||||
/// Parse stash message and extract branch information if present
|
||||
///
|
||||
/// Handles the following formats:
|
||||
/// - "WIP on <branch>: <message>" -> (Some(branch), message)
|
||||
/// - "On <branch>: <message>" -> (Some(branch), message)
|
||||
/// - "<message>" -> (None, message)
|
||||
fn parse_stash_message(input: &str) -> (Option<&str>, &str) {
|
||||
// Handle "WIP on <branch>: <message>" pattern
|
||||
if let Some(stripped) = input.strip_prefix("WIP on ")
|
||||
&& let Some(colon_pos) = stripped.find(": ")
|
||||
{
|
||||
let branch = &stripped[..colon_pos];
|
||||
let message = &stripped[colon_pos + 2..];
|
||||
if !branch.is_empty() && !message.is_empty() {
|
||||
return (Some(branch), message);
|
||||
}
|
||||
}
|
||||
|
||||
// Handle "On <branch>: <message>" pattern
|
||||
if let Some(stripped) = input.strip_prefix("On ")
|
||||
&& let Some(colon_pos) = stripped.find(": ")
|
||||
{
|
||||
let branch = &stripped[..colon_pos];
|
||||
let message = &stripped[colon_pos + 2..];
|
||||
if !branch.is_empty() && !message.is_empty() {
|
||||
return (Some(branch), message);
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: treat entire input as message with no branch
|
||||
(None, input)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_parse_stash_index() {
|
||||
assert_eq!(parse_stash_index("stash@{0}").unwrap(), 0);
|
||||
assert_eq!(parse_stash_index("stash@{42}").unwrap(), 42);
|
||||
assert_eq!(parse_stash_index(" stash@{5} ").unwrap(), 5);
|
||||
|
||||
assert!(parse_stash_index("invalid").is_err());
|
||||
assert!(parse_stash_index("stash@{not_a_number}").is_err());
|
||||
assert!(parse_stash_index("stash@{0").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_stash_message() {
|
||||
// WIP format
|
||||
let (branch, message) = parse_stash_message("WIP on main: working on feature");
|
||||
assert_eq!(branch, Some("main"));
|
||||
assert_eq!(message, "working on feature");
|
||||
|
||||
// On format
|
||||
let (branch, message) = parse_stash_message("On feature-branch: some changes");
|
||||
assert_eq!(branch, Some("feature-branch"));
|
||||
assert_eq!(message, "some changes");
|
||||
|
||||
// No branch format
|
||||
let (branch, message) = parse_stash_message("just a regular message");
|
||||
assert_eq!(branch, None);
|
||||
assert_eq!(message, "just a regular message");
|
||||
|
||||
// Edge cases
|
||||
let (branch, message) = parse_stash_message("WIP on : empty message");
|
||||
assert_eq!(branch, None);
|
||||
assert_eq!(message, "WIP on : empty message");
|
||||
|
||||
let (branch, message) = parse_stash_message("On branch-name:");
|
||||
assert_eq!(branch, None);
|
||||
assert_eq!(message, "On branch-name:");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_stash_line() {
|
||||
let line = "stash@{0}\u{0000}abc123\u{0000}1234567890\u{0000}WIP on main: test commit";
|
||||
let entry = parse_stash_line(line).unwrap();
|
||||
|
||||
assert_eq!(entry.index, 0);
|
||||
assert_eq!(entry.message, "test commit");
|
||||
assert_eq!(entry.branch, Some("main".to_string()));
|
||||
assert_eq!(entry.timestamp, 1234567890);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_git_stash_from_str() {
|
||||
let input = "stash@{0}\u{0000}abc123\u{0000}1234567890\u{0000}WIP on main: first stash\nstash@{1}\u{0000}def456\u{0000}1234567891\u{0000}On feature: second stash";
|
||||
let stash = GitStash::from_str(input).unwrap();
|
||||
|
||||
assert_eq!(stash.entries.len(), 2);
|
||||
assert_eq!(stash.entries[0].index, 0);
|
||||
assert_eq!(stash.entries[0].branch, Some("main".to_string()));
|
||||
assert_eq!(stash.entries[1].index, 1);
|
||||
assert_eq!(stash.entries[1].branch, Some("feature".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_git_stash_empty_input() {
|
||||
let stash = GitStash::from_str("").unwrap();
|
||||
assert_eq!(stash.entries.len(), 0);
|
||||
|
||||
let stash = GitStash::from_str(" \n \n ").unwrap();
|
||||
assert_eq!(stash.entries.len(), 0);
|
||||
}
|
||||
}
|
||||
775
crates/git/src/status.rs
Normal file
775
crates/git/src/status.rs
Normal file
@@ -0,0 +1,775 @@
|
||||
use crate::{Oid, repository::RepoPath};
|
||||
use anyhow::{Result, anyhow};
|
||||
use collections::HashMap;
|
||||
use gpui::SharedString;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
use util::{ResultExt, rel_path::RelPath};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum FileStatus {
|
||||
Untracked,
|
||||
Ignored,
|
||||
Unmerged(UnmergedStatus),
|
||||
Tracked(TrackedStatus),
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct UnmergedStatus {
|
||||
pub first_head: UnmergedStatusCode,
|
||||
pub second_head: UnmergedStatusCode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum UnmergedStatusCode {
|
||||
Added,
|
||||
Deleted,
|
||||
Updated,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub struct TrackedStatus {
|
||||
pub index_status: StatusCode,
|
||||
pub worktree_status: StatusCode,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
pub enum StatusCode {
|
||||
Modified,
|
||||
TypeChanged,
|
||||
Added,
|
||||
Deleted,
|
||||
Renamed,
|
||||
Copied,
|
||||
Unmodified,
|
||||
}
|
||||
|
||||
impl From<UnmergedStatus> for FileStatus {
|
||||
fn from(value: UnmergedStatus) -> Self {
|
||||
FileStatus::Unmerged(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<TrackedStatus> for FileStatus {
|
||||
fn from(value: TrackedStatus) -> Self {
|
||||
FileStatus::Tracked(value)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
|
||||
pub enum StageStatus {
|
||||
Staged,
|
||||
Unstaged,
|
||||
PartiallyStaged,
|
||||
}
|
||||
|
||||
impl StageStatus {
|
||||
pub const fn is_fully_staged(&self) -> bool {
|
||||
matches!(self, StageStatus::Staged)
|
||||
}
|
||||
|
||||
pub const fn is_fully_unstaged(&self) -> bool {
|
||||
matches!(self, StageStatus::Unstaged)
|
||||
}
|
||||
|
||||
pub const fn has_staged(&self) -> bool {
|
||||
matches!(self, StageStatus::Staged | StageStatus::PartiallyStaged)
|
||||
}
|
||||
|
||||
pub const fn has_unstaged(&self) -> bool {
|
||||
matches!(self, StageStatus::Unstaged | StageStatus::PartiallyStaged)
|
||||
}
|
||||
|
||||
pub const fn as_bool(self) -> Option<bool> {
|
||||
match self {
|
||||
StageStatus::Staged => Some(true),
|
||||
StageStatus::Unstaged => Some(false),
|
||||
StageStatus::PartiallyStaged => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl FileStatus {
|
||||
pub const fn worktree(worktree_status: StatusCode) -> Self {
|
||||
FileStatus::Tracked(TrackedStatus {
|
||||
index_status: StatusCode::Unmodified,
|
||||
worktree_status,
|
||||
})
|
||||
}
|
||||
|
||||
pub const fn index(index_status: StatusCode) -> Self {
|
||||
FileStatus::Tracked(TrackedStatus {
|
||||
worktree_status: StatusCode::Unmodified,
|
||||
index_status,
|
||||
})
|
||||
}
|
||||
|
||||
/// Generate a FileStatus Code from a byte pair, as described in
|
||||
/// https://git-scm.com/docs/git-status#_output
|
||||
///
|
||||
/// NOTE: That instead of '', we use ' ' to denote no change
|
||||
fn from_bytes(bytes: [u8; 2]) -> anyhow::Result<Self> {
|
||||
let status = match bytes {
|
||||
[b'?', b'?'] => FileStatus::Untracked,
|
||||
[b'!', b'!'] => FileStatus::Ignored,
|
||||
[b'A', b'A'] => UnmergedStatus {
|
||||
first_head: UnmergedStatusCode::Added,
|
||||
second_head: UnmergedStatusCode::Added,
|
||||
}
|
||||
.into(),
|
||||
[b'D', b'D'] => UnmergedStatus {
|
||||
first_head: UnmergedStatusCode::Added,
|
||||
second_head: UnmergedStatusCode::Added,
|
||||
}
|
||||
.into(),
|
||||
[x, b'U'] => UnmergedStatus {
|
||||
first_head: UnmergedStatusCode::from_byte(x)?,
|
||||
second_head: UnmergedStatusCode::Updated,
|
||||
}
|
||||
.into(),
|
||||
[b'U', y] => UnmergedStatus {
|
||||
first_head: UnmergedStatusCode::Updated,
|
||||
second_head: UnmergedStatusCode::from_byte(y)?,
|
||||
}
|
||||
.into(),
|
||||
[x, y] => TrackedStatus {
|
||||
index_status: StatusCode::from_byte(x)?,
|
||||
worktree_status: StatusCode::from_byte(y)?,
|
||||
}
|
||||
.into(),
|
||||
};
|
||||
Ok(status)
|
||||
}
|
||||
|
||||
pub fn staging(self) -> StageStatus {
|
||||
match self {
|
||||
FileStatus::Untracked | FileStatus::Ignored | FileStatus::Unmerged { .. } => {
|
||||
StageStatus::Unstaged
|
||||
}
|
||||
FileStatus::Tracked(tracked) => match (tracked.index_status, tracked.worktree_status) {
|
||||
(StatusCode::Unmodified, _) => StageStatus::Unstaged,
|
||||
(_, StatusCode::Unmodified) => StageStatus::Staged,
|
||||
_ => StageStatus::PartiallyStaged,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_conflicted(self) -> bool {
|
||||
matches!(self, FileStatus::Unmerged { .. })
|
||||
}
|
||||
|
||||
pub fn is_ignored(self) -> bool {
|
||||
matches!(self, FileStatus::Ignored)
|
||||
}
|
||||
|
||||
pub fn has_changes(&self) -> bool {
|
||||
self.is_modified()
|
||||
|| self.is_created()
|
||||
|| self.is_deleted()
|
||||
|| self.is_untracked()
|
||||
|| self.is_conflicted()
|
||||
}
|
||||
|
||||
pub fn is_modified(self) -> bool {
|
||||
match self {
|
||||
FileStatus::Tracked(tracked) => matches!(
|
||||
(tracked.index_status, tracked.worktree_status),
|
||||
(StatusCode::Modified, _) | (_, StatusCode::Modified)
|
||||
),
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_created(self) -> bool {
|
||||
match self {
|
||||
FileStatus::Tracked(tracked) => matches!(
|
||||
(tracked.index_status, tracked.worktree_status),
|
||||
(StatusCode::Added, _) | (_, StatusCode::Added)
|
||||
),
|
||||
FileStatus::Untracked => true,
|
||||
_ => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_deleted(self) -> bool {
|
||||
let FileStatus::Tracked(tracked) = self else {
|
||||
return false;
|
||||
};
|
||||
tracked.index_status == StatusCode::Deleted && tracked.worktree_status != StatusCode::Added
|
||||
|| tracked.worktree_status == StatusCode::Deleted
|
||||
}
|
||||
|
||||
pub fn is_untracked(self) -> bool {
|
||||
matches!(self, FileStatus::Untracked)
|
||||
}
|
||||
|
||||
pub fn summary(self) -> GitSummary {
|
||||
match self {
|
||||
FileStatus::Ignored => GitSummary::UNCHANGED,
|
||||
FileStatus::Untracked => GitSummary::UNTRACKED,
|
||||
FileStatus::Unmerged(_) => GitSummary::CONFLICT,
|
||||
FileStatus::Tracked(TrackedStatus {
|
||||
index_status,
|
||||
worktree_status,
|
||||
}) => GitSummary {
|
||||
index: index_status.to_summary(),
|
||||
worktree: worktree_status.to_summary(),
|
||||
conflict: 0,
|
||||
untracked: 0,
|
||||
count: 1,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StatusCode {
|
||||
fn from_byte(byte: u8) -> anyhow::Result<Self> {
|
||||
match byte {
|
||||
b'M' => Ok(StatusCode::Modified),
|
||||
b'T' => Ok(StatusCode::TypeChanged),
|
||||
b'A' => Ok(StatusCode::Added),
|
||||
b'D' => Ok(StatusCode::Deleted),
|
||||
b'R' => Ok(StatusCode::Renamed),
|
||||
b'C' => Ok(StatusCode::Copied),
|
||||
b' ' => Ok(StatusCode::Unmodified),
|
||||
_ => anyhow::bail!("Invalid status code: {byte}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn to_summary(self) -> TrackedSummary {
|
||||
match self {
|
||||
StatusCode::Modified | StatusCode::TypeChanged => TrackedSummary {
|
||||
modified: 1,
|
||||
..TrackedSummary::UNCHANGED
|
||||
},
|
||||
StatusCode::Added => TrackedSummary {
|
||||
added: 1,
|
||||
..TrackedSummary::UNCHANGED
|
||||
},
|
||||
StatusCode::Deleted => TrackedSummary {
|
||||
deleted: 1,
|
||||
..TrackedSummary::UNCHANGED
|
||||
},
|
||||
StatusCode::Renamed | StatusCode::Copied | StatusCode::Unmodified => {
|
||||
TrackedSummary::UNCHANGED
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn index(self) -> FileStatus {
|
||||
FileStatus::Tracked(TrackedStatus {
|
||||
index_status: self,
|
||||
worktree_status: StatusCode::Unmodified,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn worktree(self) -> FileStatus {
|
||||
FileStatus::Tracked(TrackedStatus {
|
||||
index_status: StatusCode::Unmodified,
|
||||
worktree_status: self,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl UnmergedStatusCode {
|
||||
fn from_byte(byte: u8) -> anyhow::Result<Self> {
|
||||
match byte {
|
||||
b'A' => Ok(UnmergedStatusCode::Added),
|
||||
b'D' => Ok(UnmergedStatusCode::Deleted),
|
||||
b'U' => Ok(UnmergedStatusCode::Updated),
|
||||
_ => anyhow::bail!("Invalid unmerged status code: {byte}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
|
||||
pub struct TrackedSummary {
|
||||
pub added: usize,
|
||||
pub modified: usize,
|
||||
pub deleted: usize,
|
||||
}
|
||||
|
||||
impl TrackedSummary {
|
||||
pub const UNCHANGED: Self = Self {
|
||||
added: 0,
|
||||
modified: 0,
|
||||
deleted: 0,
|
||||
};
|
||||
|
||||
pub const ADDED: Self = Self {
|
||||
added: 1,
|
||||
modified: 0,
|
||||
deleted: 0,
|
||||
};
|
||||
|
||||
pub const MODIFIED: Self = Self {
|
||||
added: 0,
|
||||
modified: 1,
|
||||
deleted: 0,
|
||||
};
|
||||
|
||||
pub const DELETED: Self = Self {
|
||||
added: 0,
|
||||
modified: 0,
|
||||
deleted: 1,
|
||||
};
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for TrackedSummary {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.added += rhs.added;
|
||||
self.modified += rhs.modified;
|
||||
self.deleted += rhs.deleted;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add for TrackedSummary {
|
||||
type Output = Self;
|
||||
|
||||
fn add(self, rhs: Self) -> Self::Output {
|
||||
TrackedSummary {
|
||||
added: self.added + rhs.added,
|
||||
modified: self.modified + rhs.modified,
|
||||
deleted: self.deleted + rhs.deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Sub for TrackedSummary {
|
||||
type Output = Self;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
TrackedSummary {
|
||||
added: self.added - rhs.added,
|
||||
modified: self.modified - rhs.modified,
|
||||
deleted: self.deleted - rhs.deleted,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, Copy, PartialEq, Eq)]
|
||||
pub struct GitSummary {
|
||||
pub index: TrackedSummary,
|
||||
pub worktree: TrackedSummary,
|
||||
pub conflict: usize,
|
||||
pub untracked: usize,
|
||||
pub count: usize,
|
||||
}
|
||||
|
||||
impl GitSummary {
|
||||
pub const CONFLICT: Self = Self {
|
||||
conflict: 1,
|
||||
count: 1,
|
||||
..Self::UNCHANGED
|
||||
};
|
||||
|
||||
pub const UNTRACKED: Self = Self {
|
||||
untracked: 1,
|
||||
count: 1,
|
||||
..Self::UNCHANGED
|
||||
};
|
||||
|
||||
pub const UNCHANGED: Self = Self {
|
||||
index: TrackedSummary::UNCHANGED,
|
||||
worktree: TrackedSummary::UNCHANGED,
|
||||
conflict: 0,
|
||||
untracked: 0,
|
||||
count: 0,
|
||||
};
|
||||
}
|
||||
|
||||
impl From<FileStatus> for GitSummary {
|
||||
fn from(status: FileStatus) -> Self {
|
||||
status.summary()
|
||||
}
|
||||
}
|
||||
|
||||
impl sum_tree::ContextLessSummary for GitSummary {
|
||||
fn zero() -> Self {
|
||||
Default::default()
|
||||
}
|
||||
|
||||
fn add_summary(&mut self, rhs: &Self) {
|
||||
*self += *rhs;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Add<Self> for GitSummary {
|
||||
type Output = Self;
|
||||
|
||||
fn add(mut self, rhs: Self) -> Self {
|
||||
self += rhs;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::AddAssign for GitSummary {
|
||||
fn add_assign(&mut self, rhs: Self) {
|
||||
self.index += rhs.index;
|
||||
self.worktree += rhs.worktree;
|
||||
self.conflict += rhs.conflict;
|
||||
self.untracked += rhs.untracked;
|
||||
self.count += rhs.count;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Sub for GitSummary {
|
||||
type Output = GitSummary;
|
||||
|
||||
fn sub(self, rhs: Self) -> Self::Output {
|
||||
GitSummary {
|
||||
index: self.index - rhs.index,
|
||||
worktree: self.worktree - rhs.worktree,
|
||||
conflict: self.conflict - rhs.conflict,
|
||||
untracked: self.untracked - rhs.untracked,
|
||||
count: self.count - rhs.count,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GitStatus {
|
||||
pub entries: Arc<[(RepoPath, FileStatus)]>,
|
||||
}
|
||||
|
||||
impl FromStr for GitStatus {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
let mut entries = s
|
||||
.split('\0')
|
||||
.filter_map(|entry| {
|
||||
let sep = entry.get(2..3)?;
|
||||
if sep != " " {
|
||||
return None;
|
||||
};
|
||||
let path = &entry[3..];
|
||||
// The git status output includes untracked directories as well as untracked files.
|
||||
// We do our own processing to compute the "summary" status of each directory,
|
||||
// so just skip any directories in the output, since they'll otherwise interfere
|
||||
// with our handling of nested repositories.
|
||||
if path.ends_with('/') {
|
||||
return None;
|
||||
}
|
||||
let status = entry.as_bytes()[0..2].try_into().unwrap();
|
||||
let status = FileStatus::from_bytes(status).log_err()?;
|
||||
// git-status outputs `/`-delimited repo paths, even on Windows.
|
||||
let path = RepoPath::from_rel_path(RelPath::unix(path).log_err()?);
|
||||
Some((path, status))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
entries.sort_unstable_by(|(a, _), (b, _)| a.cmp(b));
|
||||
// When a file exists in HEAD, is deleted in the index, and exists again in the working copy,
|
||||
// git produces two lines for it, one reading `D ` (deleted in index, unmodified in working copy)
|
||||
// and the other reading `??` (untracked). Merge these two into the equivalent of `DA`.
|
||||
entries.dedup_by(|(a, a_status), (b, b_status)| {
|
||||
const INDEX_DELETED: FileStatus = FileStatus::index(StatusCode::Deleted);
|
||||
if a.ne(&b) {
|
||||
return false;
|
||||
}
|
||||
match (*a_status, *b_status) {
|
||||
(INDEX_DELETED, FileStatus::Untracked) | (FileStatus::Untracked, INDEX_DELETED) => {
|
||||
*b_status = TrackedStatus {
|
||||
index_status: StatusCode::Deleted,
|
||||
worktree_status: StatusCode::Added,
|
||||
}
|
||||
.into();
|
||||
}
|
||||
(x, y) if x == y => {}
|
||||
_ => {
|
||||
log::warn!(
|
||||
"Unexpected duplicated status entries: {a_status:?} and {b_status:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
true
|
||||
});
|
||||
Ok(Self {
|
||||
entries: entries.into(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for GitStatus {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
entries: Arc::new([]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub enum DiffTreeType {
|
||||
MergeBase {
|
||||
base: SharedString,
|
||||
head: SharedString,
|
||||
},
|
||||
Since {
|
||||
base: SharedString,
|
||||
head: SharedString,
|
||||
},
|
||||
}
|
||||
|
||||
impl DiffTreeType {
|
||||
pub fn base(&self) -> &SharedString {
|
||||
match self {
|
||||
DiffTreeType::MergeBase { base, .. } => base,
|
||||
DiffTreeType::Since { base, .. } => base,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn head(&self) -> &SharedString {
|
||||
match self {
|
||||
DiffTreeType::MergeBase { head, .. } => head,
|
||||
DiffTreeType::Since { head, .. } => head,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub struct TreeDiff {
|
||||
pub entries: HashMap<RepoPath, TreeDiffStatus>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum TreeDiffStatus {
|
||||
Added,
|
||||
Modified { old: Oid },
|
||||
Deleted { old: Oid },
|
||||
}
|
||||
|
||||
impl FromStr for TreeDiff {
|
||||
type Err = anyhow::Error;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self> {
|
||||
let mut fields = s.split('\0');
|
||||
let mut parsed = HashMap::default();
|
||||
while let Some((status, path)) = fields.next().zip(fields.next()) {
|
||||
let path = RepoPath::from_rel_path(RelPath::unix(path)?);
|
||||
|
||||
let mut fields = status.split(" ").skip(2);
|
||||
let old_sha = fields
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("expected to find old_sha"))?
|
||||
.to_owned()
|
||||
.parse()?;
|
||||
let _new_sha = fields
|
||||
.next()
|
||||
.ok_or_else(|| anyhow!("expected to find new_sha"))?;
|
||||
let status = fields
|
||||
.next()
|
||||
.and_then(|s| {
|
||||
if s.len() == 1 {
|
||||
s.as_bytes().first()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.ok_or_else(|| anyhow!("expected to find status"))?;
|
||||
|
||||
let result = match StatusCode::from_byte(*status)? {
|
||||
StatusCode::Modified => TreeDiffStatus::Modified { old: old_sha },
|
||||
StatusCode::Added => TreeDiffStatus::Added,
|
||||
StatusCode::Deleted => TreeDiffStatus::Deleted { old: old_sha },
|
||||
_status => continue,
|
||||
};
|
||||
|
||||
parsed.insert(path, result);
|
||||
}
|
||||
|
||||
Ok(Self { entries: parsed })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub struct DiffStat {
|
||||
pub added: u32,
|
||||
pub deleted: u32,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GitDiffStat {
|
||||
pub entries: Arc<[(RepoPath, DiffStat)]>,
|
||||
}
|
||||
|
||||
/// Parses the output of `git diff --numstat` where output looks like:
|
||||
///
|
||||
/// ```text
|
||||
/// 24 12 dir/file.txt
|
||||
/// ```
|
||||
pub fn parse_numstat(output: &str) -> GitDiffStat {
|
||||
let mut entries = Vec::new();
|
||||
for line in output.lines() {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let mut parts = line.splitn(3, '\t');
|
||||
let (Some(added_str), Some(deleted_str), Some(path_str)) =
|
||||
(parts.next(), parts.next(), parts.next())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let Ok(added) = added_str.parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(deleted) = deleted_str.parse::<u32>() else {
|
||||
continue;
|
||||
};
|
||||
let Ok(path) = RepoPath::new(path_str) else {
|
||||
continue;
|
||||
};
|
||||
entries.push((path, DiffStat { added, deleted }));
|
||||
}
|
||||
entries.sort_by(|(a, _), (b, _)| a.cmp(b));
|
||||
entries.dedup_by(|(a, _), (b, _)| a == b);
|
||||
|
||||
GitDiffStat {
|
||||
entries: entries.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use crate::{
|
||||
repository::RepoPath,
|
||||
status::{FileStatus, GitStatus, TreeDiff, TreeDiffStatus},
|
||||
};
|
||||
|
||||
use super::{DiffStat, parse_numstat};
|
||||
|
||||
fn lookup<'a>(entries: &'a [(RepoPath, DiffStat)], path: &str) -> Option<&'a DiffStat> {
|
||||
let path = RepoPath::new(path).unwrap();
|
||||
entries.iter().find(|(p, _)| p == &path).map(|(_, s)| s)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_normal() {
|
||||
let input = "10\t5\tsrc/main.rs\n3\t1\tREADME.md\n";
|
||||
let result = parse_numstat(input);
|
||||
assert_eq!(result.entries.len(), 2);
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "src/main.rs"),
|
||||
Some(&DiffStat {
|
||||
added: 10,
|
||||
deleted: 5
|
||||
})
|
||||
);
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "README.md"),
|
||||
Some(&DiffStat {
|
||||
added: 3,
|
||||
deleted: 1
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_binary_files_skipped() {
|
||||
// git diff --numstat outputs "-\t-\tpath" for binary files
|
||||
let input = "-\t-\timage.png\n5\t2\tsrc/lib.rs\n";
|
||||
let result = parse_numstat(input);
|
||||
assert_eq!(result.entries.len(), 1);
|
||||
assert!(lookup(&result.entries, "image.png").is_none());
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "src/lib.rs"),
|
||||
Some(&DiffStat {
|
||||
added: 5,
|
||||
deleted: 2
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_empty_input() {
|
||||
assert!(parse_numstat("").entries.is_empty());
|
||||
assert!(parse_numstat("\n\n").entries.is_empty());
|
||||
assert!(parse_numstat(" \n \n").entries.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_malformed_lines_skipped() {
|
||||
let input = "not_a_number\t5\tfile.rs\n10\t5\tvalid.rs\n";
|
||||
let result = parse_numstat(input);
|
||||
assert_eq!(result.entries.len(), 1);
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "valid.rs"),
|
||||
Some(&DiffStat {
|
||||
added: 10,
|
||||
deleted: 5
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_incomplete_lines_skipped() {
|
||||
// Lines with fewer than 3 tab-separated fields are skipped
|
||||
let input = "10\t5\n7\t3\tok.rs\n";
|
||||
let result = parse_numstat(input);
|
||||
assert_eq!(result.entries.len(), 1);
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "ok.rs"),
|
||||
Some(&DiffStat {
|
||||
added: 7,
|
||||
deleted: 3
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_parse_numstat_zero_stats() {
|
||||
let input = "0\t0\tunchanged_but_present.rs\n";
|
||||
let result = parse_numstat(input);
|
||||
assert_eq!(
|
||||
lookup(&result.entries, "unchanged_but_present.rs"),
|
||||
Some(&DiffStat {
|
||||
added: 0,
|
||||
deleted: 0
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_duplicate_untracked_entries() {
|
||||
// Regression test for ZED-2XA: git can produce duplicate untracked entries
|
||||
// for the same path. This should deduplicate them instead of panicking.
|
||||
let input = "?? file.txt\0?? file.txt";
|
||||
let status: GitStatus = input.parse().unwrap();
|
||||
assert_eq!(status.entries.len(), 1);
|
||||
assert_eq!(status.entries[0].1, FileStatus::Untracked);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_tree_diff_parsing() {
|
||||
let input = ":000000 100644 0000000000000000000000000000000000000000 0062c311b8727c3a2e3cd7a41bc9904feacf8f98 A\x00.zed/settings.json\x00".to_owned() +
|
||||
":100644 000000 bb3e9ed2e97a8c02545bae243264d342c069afb3 0000000000000000000000000000000000000000 D\x00README.md\x00" +
|
||||
":100644 100644 42f097005a1f21eb2260fad02ec8c991282beee8 a437d85f63bb8c62bd78f83f40c506631fabf005 M\x00parallel.go\x00";
|
||||
|
||||
let output: TreeDiff = input.parse().unwrap();
|
||||
assert_eq!(
|
||||
output,
|
||||
TreeDiff {
|
||||
entries: [
|
||||
(
|
||||
RepoPath::new(".zed/settings.json").unwrap(),
|
||||
TreeDiffStatus::Added,
|
||||
),
|
||||
(
|
||||
RepoPath::new("README.md").unwrap(),
|
||||
TreeDiffStatus::Deleted {
|
||||
old: "bb3e9ed2e97a8c02545bae243264d342c069afb3".parse().unwrap()
|
||||
}
|
||||
),
|
||||
(
|
||||
RepoPath::new("parallel.go").unwrap(),
|
||||
TreeDiffStatus::Modified {
|
||||
old: "42f097005a1f21eb2260fad02ec8c991282beee8".parse().unwrap(),
|
||||
}
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.collect()
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user