2139 lines · 70.3 KB · Rust
RawDownload
use crate::status::GitStatus;use crate::{Oid, SHORT_SHA_LENGTH};use anyhow::{anyhow, Context as _, Result};use collections::HashMap;use futures::future::BoxFuture;use futures::{select_biased, AsyncWriteExt, FutureExt as _};use git2::BranchType;use gpui::{AsyncApp, BackgroundExecutor, SharedString};use parking_lot::Mutex;use rope::Rope;use schemars::JsonSchema;use serde::Deserialize;use std::borrow::{Borrow, Cow};use std::ffi::{OsStr, OsString};use std::path::Component;use std::process::{ExitStatus, Stdio};use std::sync::LazyLock;use std::{    cmp::Ordering,    path::{Path, PathBuf},    sync::Arc,};use std::{future, mem};use sum_tree::MapSeekTarget;use thiserror::Error;use util::command::{new_smol_command, new_std_command};use util::ResultExt;use uuid::Uuid; pub use askpass::{AskPassResult, AskPassSession}; pub const REMOTE_CANCELLED_BY_USER: &str = "Operation cancelled by user"; #[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>,} impl Branch {    pub fn tracking_status(&self) -> Option<UpstreamTrackingStatus> {        self.upstream            .as_ref()            .and_then(|upstream| upstream.tracking.status())    }     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,} impl Upstream {    pub fn remote_name(&self) -> Option<&str> {        self.ref_name            .strip_prefix("refs/remotes/")            .and_then(|stripped| stripped.split("/").next())    }} #[derive(Clone, Copy, 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 From<UpstreamTrackingStatus> for UpstreamTracking {    fn from(status: UpstreamTrackingStatus) -> Self {        UpstreamTracking::Tracked(status)    }} impl UpstreamTracking {    pub fn is_gone(&self) -> bool {        matches!(self, UpstreamTracking::Gone)    }     pub fn status(&self) -> Option<UpstreamTrackingStatus> {        match self {            UpstreamTracking::Gone => None,            UpstreamTracking::Tracked(status) => Some(*status),        }    }} #[derive(Debug, Clone)]pub struct RemoteCommandOutput {    pub stdout: String,    pub stderr: String,} impl RemoteCommandOutput {    pub fn is_empty(&self) -> bool {        self.stdout.is_empty() && self.stderr.is_empty()    }} #[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,    pub has_parent: bool,} #[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,} impl CommitDetails {    pub fn short_sha(&self) -> SharedString {        self.sha[..SHORT_SHA_LENGTH].to_string().into()    }} #[derive(Debug, Clone, Hash, PartialEq, Eq)]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, index: Option<GitIndex>, path: RepoPath)        -> BoxFuture<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) -> BoxFuture<Option<String>>;     fn set_index_text(        &self,        path: RepoPath,        content: Option<String>,        env: HashMap<String, String>,    ) -> BoxFuture<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>;     fn status(        &self,        index: Option<GitIndex>,        path_prefixes: &[RepoPath],    ) -> BoxFuture<'static, Result<GitStatus>>;    fn status_blocking(&self, path_prefixes: &[RepoPath]) -> Result<GitStatus>;     fn branches(&self) -> BoxFuture<Result<Vec<Branch>>>;     fn change_branch(&self, name: String) -> BoxFuture<Result<()>>;    fn create_branch(&self, name: String) -> BoxFuture<Result<()>>;     fn reset(        &self,        commit: String,        mode: ResetMode,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>>;     fn checkout_files(        &self,        commit: String,        paths: Vec<RepoPath>,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>>;     fn show(&self, commit: String) -> BoxFuture<Result<CommitDetails>>;     fn blame(&self, path: RepoPath, content: Rope) -> BoxFuture<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: Vec<RepoPath>,        env: HashMap<String, String>,    ) -> BoxFuture<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: Vec<RepoPath>,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>>;     fn commit(        &self,        message: SharedString,        name_and_email: Option<(SharedString, SharedString)>,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>>;     fn push(        &self,        branch_name: String,        upstream_name: String,        options: Option<PushOptions>,        askpass: AskPassSession,        env: HashMap<String, String>,        // This method takes an AsyncApp to ensure it's invoked on the main thread,        // otherwise git-credentials-manager won't work.        cx: AsyncApp,    ) -> BoxFuture<Result<RemoteCommandOutput>>;     fn pull(        &self,        branch_name: String,        upstream_name: String,        askpass: AskPassSession,        env: HashMap<String, String>,        // This method takes an AsyncApp to ensure it's invoked on the main thread,        // otherwise git-credentials-manager won't work.        cx: AsyncApp,    ) -> BoxFuture<Result<RemoteCommandOutput>>;     fn fetch(        &self,        askpass: AskPassSession,        env: HashMap<String, String>,        // This method takes an AsyncApp to ensure it's invoked on the main thread,        // otherwise git-credentials-manager won't work.        cx: AsyncApp,    ) -> BoxFuture<Result<RemoteCommandOutput>>;     fn get_remotes(&self, branch_name: Option<String>) -> BoxFuture<Result<Vec<Remote>>>;     /// returns a list of remote branches that contain HEAD    fn check_for_pushed_commit(&self) -> BoxFuture<Result<Vec<SharedString>>>;     /// Run git diff    fn diff(&self, diff: DiffType) -> BoxFuture<Result<String>>;     /// Creates a checkpoint for the repository.    fn checkpoint(&self) -> BoxFuture<'static, Result<GitRepositoryCheckpoint>>;     /// Resets to a previously-created checkpoint.    fn restore_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<Result<()>>;     /// Compares two checkpoints, returning true if they are equal    fn compare_checkpoints(        &self,        left: GitRepositoryCheckpoint,        right: GitRepositoryCheckpoint,    ) -> BoxFuture<Result<bool>>;     /// Deletes a previously-created checkpoint.    fn delete_checkpoint(&self, checkpoint: GitRepositoryCheckpoint) -> BoxFuture<Result<()>>;     /// Computes a diff between two checkpoints.    fn diff_checkpoints(        &self,        base_checkpoint: GitRepositoryCheckpoint,        target_checkpoint: GitRepositoryCheckpoint,    ) -> BoxFuture<Result<String>>;     /// Creates a new index for the repository.    fn create_index(&self) -> BoxFuture<Result<GitIndex>>;     /// Applies a diff to the repository's index.    fn apply_diff(&self, index: GitIndex, diff: String) -> BoxFuture<Result<()>>;} pub enum DiffType {    HeadToIndex,    HeadToWorktree,} #[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, JsonSchema)]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: Arc<Mutex<git2::Repository>>,    pub git_binary_path: PathBuf,    executor: BackgroundExecutor,} impl RealGitRepository {    pub fn new(        dotgit_path: &Path,        git_binary_path: Option<PathBuf>,        executor: BackgroundExecutor,    ) -> Option<Self> {        let workdir_root = dotgit_path.parent()?;        let repository = git2::Repository::open(workdir_root).log_err()?;        Some(Self {            repository: Arc::new(Mutex::new(repository)),            git_binary_path: git_binary_path.unwrap_or_else(|| PathBuf::from("git")),            executor,        })    }     fn working_directory(&self) -> Result<PathBuf> {        self.repository            .lock()            .workdir()            .context("failed to read git work directory")            .map(Path::to_path_buf)    }} #[derive(Clone, Debug)]pub struct GitRepositoryCheckpoint {    ref_name: String,    head_sha: Option<Oid>,    commit_sha: Oid,} #[derive(Copy, Clone, Debug)]pub struct GitIndex {    id: Uuid,} 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: String) -> BoxFuture<Result<CommitDetails>> {        let repo = self.repository.clone();        self.executor            .spawn(async move {                let repo = repo.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)            })            .boxed()    }     fn reset(        &self,        commit: String,        mode: ResetMode,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>> {        async move {            let working_directory = self.working_directory();             let mode_flag = match mode {                ResetMode::Mixed => "--mixed",                ResetMode::Soft => "--soft",            };             let output = new_smol_command(&self.git_binary_path)                .envs(env)                .current_dir(&working_directory?)                .args(["reset", mode_flag, &commit])                .output()                .await?;            if !output.status.success() {                return Err(anyhow!(                    "Failed to reset:\n{}",                    String::from_utf8_lossy(&output.stderr)                ));            }            Ok(())        }        .boxed()    }     fn checkout_files(        &self,        commit: String,        paths: Vec<RepoPath>,        env: HashMap<String, String>,    ) -> BoxFuture<Result<()>> {        let working_directory = self.working_directory();        let git_binary_path = self.git_binary_path.clone();        async move {            if paths.is_empty() {                return Ok(());            }             let output = new_smol_command(&git_binary_path)                .current_dir(&working_directory?)                .envs(env)                .args(["checkout", &commit, "--"])                .args(paths.iter().map(|path| path.as_ref()))                .output()                .await?;            if !output.status.success() {                return Err(anyhow!(                    "Failed to checkout files:\n{}",                    String::from_utf8_lossy(&output.stderr)                ));            }            Ok(())        }        .boxed()    }     fn load_index_text(        &self,        index: Option<GitIndex>,        path: RepoPath,    ) -> BoxFuture<Option<String>> {        let working_directory = self.working_directory();        let git_binary_path = self.git_binary_path.clone();        let executor = self.executor.clone();        self.executor            .spawn(async move {                match check_path_to_repo_path_errors(&path) {                    Ok(_) => {}                    Err(err) => {                        log::error!("Error with repo path: {:?}", err);

Lines 1–500 of 2139.

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