Mikayla MakiNotes....0d705bd1 year agoHistory
1165 lines · 38.8 KB · Rust
RawDownload
use crate::status::FileStatus;use crate::GitHostingProviderRegistry;use crate::{blame::Blame, status::GitStatus};use anyhow::{anyhow, Context, Result};use collections::{HashMap, HashSet};use git2::BranchType;use gpui::SharedString;use parking_lot::Mutex;use rope::Rope;use std::borrow::Borrow;use std::io::Write as _;use std::process::Stdio;use std::sync::LazyLock;use std::{    cmp::Ordering,    path::{Component, Path, PathBuf},    sync::Arc,};use sum_tree::MapSeekTarget;use util::command::new_std_command;use util::ResultExt; // GIT MERGE-BASE:// git merge-base main HEAD -> Most recent commit from main// git merge-base @{u} HEAD -> Most recent commit from upstream//// We can detect what branch is 'main' via `git symbolic-ref refs/remotes/origin/HEAD` (producing: refs/remotes/origin/main)// -> This then requires finding which branch has this set as the upstream.// -> If all that works, we can reliably determine a branch for checking uncommit.// If the above process doesn't work, we can fall back on checking if there's a master or main OR init.defaultBranch at all.// -> If there is one, we use that.// If both of the above fail, we simply don't do that check.//// To determine what remote to use for 'main detection' above, we just check every configured remote// and then when doing the "most recent commit from main" check, we use all of the branches that we found// as 'mains', and show that in the prompt//// What if git-merge-base is slow?// Let's build a git log debug view, so that we can collect timing information on all git commands// This will probably be useful for debugging monorepos in various ways.//// Treat this like LSP commands, only shown and stored if you have a git log debug view open//// GIT FETCH// Need a sync button for running git fetch. VSCode uses `git fetch --all`,,,, so it can help you manage all the git things// (and a tree view)//  but we should probably just use `git fetch`, as we don't need a tree view//// GIT PUSH:// To figure out which origin to set, just get a list of all origins and ask in a picker prompt, then use '--set-upstream'// OR if there is just one origin, use that// git push --set-upstream origin git-push// (just like VSCode)//// GIT PULL:// VSCode just uses:// git pull --tags origin fix-pop-over-2//           ^ I wonder why they do this.... probably just so they can always have the latest tags//// This can cause a confusing scenario when you know a remote branch with the same name exists// (and you can even see it in the history view in vscode), but somehow you haven't setup the upstream properly yet.// Perhaps we enable git pull, but prompt you in this case that we're going to do this thing. IDK.// ^ above is probably too niche to care about//// Merge / Rebase issue:// I'd like there to be contextual buttons for this as well. Maybe "pull" if you're behind, and "rebase" if you're ahead and behind// - Check a zed project setting for "default pull behavior" (default: rebase), then check for 'git config pull.rebase'//   If either of those set to merge, change the button to 'merge'// ALTERNATIVELY: just always delegate to git pull, and if it fails prompt the user to select "merge or rebase"// I kind of like making people think about always doing a rebase though. Feels nicely opinionated.// I think telling the user what git is going to do is difficult, branches can be individually set to manage this at the git level,// and git can be locally or globally configured on what to do in this scenario. Adding another layer of Zed querying or settings seems 😮‍💨// I think the alternative plan is more straightforward.// ALTERNATIVELY again: If get allows a general "what will pull do on this branch" query that resolves all these settings, maybe we show the merge / rebase buttons//  if configured then fallback to prompting//// GIT CONFLICTS:// Create a simple 'git conflicts' tree sitter language that we add, that supports all files// It adds a special 'git conflicts' query that we can use to run editor APIs off of// This query is only accessible from native zed languages (e.g. extensions can't override this)// This allows us to:// - Highlight conflicts in the editor and provide UI for resolving them// - Open conflicts in one big excerpt in the project diff// TODO: Can the syntax map handle this situation? Or does it need a single root language? Or can we//       carve out a one-off for this situation?// Why use tree-sitter at all? Fast, incremental parsing that we already know how to use efficiently.//// LOG VIEW:// Basically, a way of looking at the output of 'git log'. It's what opens up if you click on the most recent commit.// Should be pretty easy and nice. Model it after github desktop.// - Each item should allow you to open a read-only multibuffer diff of the commit.//  - Let's not worry about large commits for now. Same issue as with our project search// - Maybe a button "checkout this commit detached"//   If adding this button, make sure that creating a branch correctly handles the detached state.//   Git will probably do it for us. But you never know.//// STAGING VIEW:// essentially the same as `git: Diff` except:// 0. `git: Staging`// 1. No integration with the existing git panel//  - MAYBE: You can have a setting which controls which of these diffs the panel tracks// 2. Staging and unstaging are seperated one after the other// 3. Items re-sort (basically a copy of the sublime merge experience)//// PANEL://  - Sinced everything is very stable with these checkboxes, we can restore the tree view in the combined diff panel.//  - Maybe we have a switcher here for flat vs. tree view//  - This does not apply to the staging mode for this panel.//// KEYBINDINGS / PANEL UX:// - Need to add more contextual keystrokes for all the various commands.// - TODO: Figure out how to make it feel good to manuever the panel via the keyboard...//  - The diff view is pretty reliable for keyboard navigation. I like what conrad has built//  - TODO: Make sure everything he's been adding gets merged even if it's broken when doing this big upgrade I have planned.// Issues://  - Very little context as to what's been changed and how. If I'm looking at the panel I need those line numbers//    to contextualize where I want to double check//   - Git performance might be a blocker for line numbers, again let's add that debug view and see how it goes.// - How to get down to the commit panel in a way that feels good?// - How to show who the collaborators are automatically? - switch to avatars instead of this weird blue button// - Once in the commit panel, I need a prompt to finish the commit,//  - and another to close this all out and get back to editing.// - Essentially, there's a top to bottom flow implied by the panel, but no consistent keyboard driven way to follow (or escape) the flow.//// ^ I think if we can get all this, we'll have a nice and featureful feeling git experience in Zed. Right now it feels too narrow//   to me.//// SPLIT VIEW://  - Out of scope.// HISTORY TREE VIEW://  - Out of scope// STASH//  - Out of scope//// Goals for this weekend:// - Fetch (remote syncing)// - Push// - Pull (settings integration?)// - keybindings// Stretch goals:// - git conflicts// -  cli log debug view// - line numbers// - merge-base// - git log view// - Staging diff and staging panel #[derive(Clone, Debug, Hash, PartialEq, Eq)]pub struct Branch {    pub is_head: bool,    pub name: SharedString,    pub upstream: Option<Upstream>,    pub most_recent_commit: Option<CommitSummary>,} #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)]pub enum PushAction {    Republish,    Publish,    ForcePush { ahead: u32, behind: u32 },    Push { ahead: u32 },} impl Branch {    pub fn push_action(&self) -> Option<PushAction> {        if let Some(upstream) = &self.upstream {            match upstream.tracking {                UpstreamTracking::Gone => Some(PushAction::Republish),                UpstreamTracking::Tracked(tracking) => {                    if tracking.behind > 0 {                        Some(PushAction::ForcePush {                            ahead: tracking.ahead,                            behind: tracking.behind,                        })                    } else if tracking.ahead > 0 {                        Some(PushAction::Push {                            ahead: tracking.ahead,                        })                    } else {                        None                    }                }            }        } else {            Some(PushAction::Publish)        }    }     pub fn priority_key(&self) -> (bool, Option<i64>) {        (            self.is_head,            self.most_recent_commit                .as_ref()                .map(|commit| commit.commit_timestamp),        )    }} #[derive(Clone, Debug, Hash, PartialEq, Eq)]pub struct Upstream {    pub ref_name: SharedString,    pub tracking: UpstreamTracking,} #[derive(Clone, Debug, Hash, PartialEq, Eq)]pub enum UpstreamTracking {    /// Remote ref not present in local repository.    Gone,    /// Remote ref present in local repository (fetched from remote).    Tracked(UpstreamTrackingStatus),} impl UpstreamTracking {    pub fn status(&self) -> Option<UpstreamTrackingStatus> {        match self {            UpstreamTracking::Gone => None,            UpstreamTracking::Tracked(status) => Some(*status),        }    }} #[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]pub struct UpstreamTrackingStatus {    pub ahead: u32,    pub behind: u32,} #[derive(Clone, Debug, Hash, PartialEq, Eq)]pub struct CommitSummary {    pub sha: SharedString,    pub subject: SharedString,    /// This is a unix timestamp    pub commit_timestamp: i64,} #[derive(Clone, Debug, Hash, PartialEq, Eq)]pub struct CommitDetails {    pub sha: SharedString,    pub message: SharedString,    pub commit_timestamp: i64,    pub committer_email: SharedString,    pub committer_name: SharedString,} pub struct Remote {    pub name: SharedString,} pub enum ResetMode {    // reset the branch pointer, leave index and worktree unchanged    // (this will make it look like things that were committed are now    // staged)    Soft,    // reset the branch pointer and index, leave worktree unchanged    // (this makes it look as though things that were committed are now    // unstaged)    Mixed,} pub trait GitRepository: Send + Sync {    fn reload_index(&self);     /// Returns the contents of an entry in the repository's index, or None if there is no entry for the given path.    ///    /// Also returns `None` for symlinks.    fn load_index_text(&self, path: &RepoPath) -> Option<String>;     /// Returns the contents of an entry in the repository's HEAD, or None if HEAD does not exist or has no entry for the given path.    ///    /// Also returns `None` for symlinks.    fn load_committed_text(&self, path: &RepoPath) -> Option<String>;     fn set_index_text(&self, path: &RepoPath, content: Option<String>) -> anyhow::Result<()>;     /// Returns the URL of the remote with the given name.    fn remote_url(&self, name: &str) -> Option<String>;     /// Returns the SHA of the current HEAD.    fn head_sha(&self) -> Option<String>;     fn merge_head_shas(&self) -> Vec<String>;     /// Returns the list of git statuses, sorted by path    fn status(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus>;     fn branches(&self) -> Result<Vec<Branch>>;    fn change_branch(&self, _: &str) -> Result<()>;    fn create_branch(&self, _: &str) -> Result<()>;    fn branch_exits(&self, _: &str) -> Result<bool>;     fn reset(&self, commit: &str, mode: ResetMode) -> Result<()>;    fn checkout_files(&self, commit: &str, paths: &[RepoPath]) -> Result<()>;     fn show(&self, commit: &str) -> Result<CommitDetails>;     fn blame(&self, path: &Path, content: Rope) -> Result<crate::blame::Blame>;     /// Returns the absolute path to the repository. For worktrees, this will be the path to the    /// worktree's gitdir within the main repository (typically `.git/worktrees/<name>`).    fn path(&self) -> PathBuf;     /// Returns the absolute path to the ".git" dir for the main repository, typically a `.git`    /// folder. For worktrees, this will be the path to the repository the worktree was created    /// from. Otherwise, this is the same value as `path()`.    ///    /// Git documentation calls this the "commondir", and for git CLI is overridden by    /// `GIT_COMMON_DIR`.    fn main_repository_path(&self) -> PathBuf;     /// Updates the index to match the worktree at the given paths.    ///    /// If any of the paths have been deleted from the worktree, they will be removed from the index if found there.    fn stage_paths(&self, paths: &[RepoPath]) -> Result<()>;    /// Updates the index to match HEAD at the given paths.    ///    /// If any of the paths were previously staged but do not exist in HEAD, they will be removed from the index.    fn unstage_paths(&self, paths: &[RepoPath]) -> Result<()>;     fn commit(&self, message: &str, name_and_email: Option<(&str, &str)>) -> Result<()>;     // With set_upstream, we pass this configured remote to push    // Otherwise we just use `git push origin branch`    fn push(&self, upstream: Remote, options: Option<PushOptions>) -> Result<()>;} #[derive(Debug, Clone, Copy, PartialEq, Eq)]pub enum PushOptions {    SetUpstream,    Force,} impl std::fmt::Debug for dyn GitRepository {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.debug_struct("dyn GitRepository<...>").finish()    }} pub struct RealGitRepository {    pub repository: Mutex<git2::Repository>,    pub git_binary_path: PathBuf,    hosting_provider_registry: Arc<GitHostingProviderRegistry>,} impl RealGitRepository {    pub fn new(        repository: git2::Repository,        git_binary_path: Option<PathBuf>,        hosting_provider_registry: Arc<GitHostingProviderRegistry>,    ) -> Self {        Self {            repository: Mutex::new(repository),            git_binary_path: git_binary_path.unwrap_or_else(|| PathBuf::from("git")),            hosting_provider_registry,        }    }     fn working_directory(&self) -> Result<PathBuf> {        self.repository            .lock()            .workdir()            .context("failed to read git work directory")            .map(Path::to_path_buf)    }} // https://git-scm.com/book/en/v2/Git-Internals-Git-Objectsconst GIT_MODE_SYMLINK: u32 = 0o120000; impl GitRepository for RealGitRepository {    fn reload_index(&self) {        if let Ok(mut index) = self.repository.lock().index() {            _ = index.read(false);        }    }     fn path(&self) -> PathBuf {        let repo = self.repository.lock();        repo.path().into()    }     fn main_repository_path(&self) -> PathBuf {        let repo = self.repository.lock();        repo.commondir().into()    }     fn show(&self, commit: &str) -> Result<CommitDetails> {        let repo = self.repository.lock();        let Ok(commit) = repo.revparse_single(commit)?.into_commit() else {            anyhow::bail!("{} is not a commit", commit);        };        let details = CommitDetails {            sha: commit.id().to_string().into(),            message: String::from_utf8_lossy(commit.message_raw_bytes())                .to_string()                .into(),            commit_timestamp: commit.time().seconds(),            committer_email: String::from_utf8_lossy(commit.committer().email_bytes())                .to_string()                .into(),            committer_name: String::from_utf8_lossy(commit.committer().name_bytes())                .to_string()                .into(),        };        Ok(details)    }     fn reset(&self, commit: &str, mode: ResetMode) -> Result<()> {        let working_directory = self.working_directory()?;         let mode_flag = match mode {            ResetMode::Mixed => "--mixed",            ResetMode::Soft => "--soft",        };         let output = new_std_command(&self.git_binary_path)            .current_dir(&working_directory)            .args(["reset", mode_flag, commit])            .output()?;        if !output.status.success() {            return Err(anyhow!(                "Failed to reset:\n{}",                String::from_utf8_lossy(&output.stderr)            ));        }        Ok(())    }     fn checkout_files(&self, commit: &str, paths: &[RepoPath]) -> Result<()> {        if paths.is_empty() {            return Ok(());        }        let working_directory = self.working_directory()?;         let output = new_std_command(&self.git_binary_path)            .current_dir(&working_directory)            .args(["checkout", commit, "--"])            .args(paths.iter().map(|path| path.as_ref()))            .output()?;        if !output.status.success() {            return Err(anyhow!(                "Failed to checkout files:\n{}",                String::from_utf8_lossy(&output.stderr)            ));        }        Ok(())    }     fn load_index_text(&self, path: &RepoPath) -> Option<String> {        fn logic(repo: &git2::Repository, path: &RepoPath) -> Result<Option<String>> {            const STAGE_NORMAL: i32 = 0;            let index = repo.index()?;             // This check is required because index.get_path() unwraps internally :(            check_path_to_repo_path_errors(path)?;             let oid = match index.get_path(path, STAGE_NORMAL) {                Some(entry) if entry.mode != GIT_MODE_SYMLINK => entry.id,                _ => return Ok(None),            };             let content = repo.find_blob(oid)?.content().to_owned();            Ok(Some(String::from_utf8(content)?))        }         match logic(&self.repository.lock(), path) {            Ok(value) => return value,            Err(err) => log::error!("Error loading index text: {:?}", err),        }        None    }     fn load_committed_text(&self, path: &RepoPath) -> Option<String> {        let repo = self.repository.lock();        let head = repo.head().ok()?.peel_to_tree().log_err()?;        let entry = head.get_path(path).ok()?;        if entry.filemode() == i32::from(git2::FileMode::Link) {            return None;        }        let content = repo.find_blob(entry.id()).log_err()?.content().to_owned();        let content = String::from_utf8(content).log_err()?;        Some(content)    }     fn set_index_text(&self, path: &RepoPath, content: Option<String>) -> anyhow::Result<()> {        let working_directory = self.working_directory()?;        if let Some(content) = content {            let mut child = new_std_command(&self.git_binary_path)                .current_dir(&working_directory)                .args(["hash-object", "-w", "--stdin"])                .stdin(Stdio::piped())                .stdout(Stdio::piped())                .spawn()?;            child.stdin.take().unwrap().write_all(content.as_bytes())?;            let output = child.wait_with_output()?.stdout;            let sha = String::from_utf8(output)?;             log::debug!("indexing SHA: {sha}, path {path:?}");             let status = new_std_command(&self.git_binary_path)                .current_dir(&working_directory)

Lines 1–500 of 1165.

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t