curd-editor 0.27.3

A terminal code editor: file tree, tabs, git, language servers, run and jump to errors, and a panel for Claude or any other assistant
//! The git menu, the view of changes, and searching the project.

use super::*;

/// The git commands, in the order the menu lists them.
pub(super) const GIT_MENU: [&str; 12] = [
    "Stage this file",
    "Unstage this file",
    "Stage all changes",
    "Unstage everything",
    "Commit...",
    "Switch branch...",
    "New branch...",
    "Pull",
    "Push",
    "Fetch",
    "Show what changed in this file",
    "Show every change in the project",
];

/// When the file at `path` was last changed, and how big it is.
pub(super) fn disk_stamp(path: &str) -> Option<(std::time::SystemTime, u64)> {
    let data = std::fs::metadata(path).ok()?;
    Some((data.modified().ok()?, data.len()))
}

impl Workspace {
    // ---- Project search and git commands ------------------------------

    /// Opens the list over the text for `picker`, offering `items`.
    pub(super) fn pick(&mut self, picker: Picker, items: Vec<String>) {
        self.picker = picker;
        self.finder = Some(match picker {
            Picker::Files => Finder::with_files(items),
            _ => Finder::list(items),
        });
    }

    /// Searches every file of the project for `query` and lists the lines
    /// that hold it.
    pub(super) fn search_project(&mut self, query: &str) {
        let files = finder::project_files(self.tree.root());
        self.hits = search::in_files(self.tree.root(), &files, query);
        if self.hits.is_empty() {
            self.say(format!("No match for {query} in the project"));
            return;
        }
        let lines = self
            .hits
            .iter()
            .map(|hit| format!("{}:{}: {}", hit.file, hit.y + 1, hit.text))
            .collect();
        self.pick(Picker::Results, lines);
    }

    /// Opens the file line `index` of the search results is in, there.
    pub(super) fn open_hit(&mut self, index: usize) {
        let Some(hit) = self.hits.get(index) else {
            return;
        };
        let (path, x, y) = (self.tree.root().join(&hit.file), hit.x, hit.y);
        if self.open(&path) {
            self.editors[self.active].jump_to(x, y);
        }
    }

    pub(super) fn open_git_menu(&mut self) {
        if self.git.is_some() {
            self.pick(Picker::Git, GIT_MENU.iter().map(|item| item.to_string()).collect());
        } else {
            self.say("This folder is not in git".into());
        }
    }

    /// The file a git command is about: the one selected in the tree while
    /// the keys are there, or else the one in front.
    pub(super) fn git_target(&self) -> Option<PathBuf> {
        match (self.focus, self.tree.selected()) {
            (Focus::Tree, Some(entry)) => Some(entry.path.clone()),
            _ => self.editors.get(self.active)?.abs_path.as_ref().map(PathBuf::from),
        }
    }

    /// Runs line `index` of the git menu.
    pub(super) fn git_command(&mut self, index: usize) {
        let unsaved = self.editors.iter().any(|editor| editor.document.dirty);
        match GIT_MENU[index] {
            "Stage this file" | "Unstage this file" => {
                let Some(path) = self.git_target() else {
                    return self.say("No file to stage: open or select one first".into());
                };
                let name = path.file_name().unwrap_or_default().to_string_lossy().into_owned();
                let path = path.to_string_lossy().into_owned();
                if GIT_MENU[index] == "Stage this file" {
                    self.run_git(format!("Staged {name}"), move |root| {
                        git::action(root, &["add", "--", &path])
                    });
                } else {
                    self.run_git(format!("Unstaged {name}"), move |root| {
                        git::action(root, &["restore", "--staged", "--", &path])
                    });
                }
            }
            "Stage all changes" => {
                self.run_git("Staged all changes".into(), |root| git::action(root, &["add", "--all"]));
            }
            "Unstage everything" => {
                self.run_git("Unstaged everything".into(), |root| git::action(root, &["reset", "--quiet"]));
            }
            "Commit..." => self.pick(Picker::Commit, Vec::new()),
            "New branch..." => self.pick(Picker::NewBranch, Vec::new()),
            // These two change files on disk, which unsaved text would
            // then silently disagree with.
            "Switch branch..." | "Pull" if unsaved => {
                self.say("Save your changes first: this changes the files on disk".into());
            }
            "Switch branch..." => {
                let branches = git::branches(self.tree.root());
                self.pick(Picker::Branches, branches);
            }
            "Pull" => {
                self.run_git("Pulled".into(), |root| git::action(root, &["pull", "--no-edit"]));
            }
            "Push" => self.run_git("Pushed".into(), git::push),
            "Fetch" => {
                self.run_git("Fetched".into(), |root| git::action(root, &["fetch", "--all", "--prune"]));
            }
            "Show what changed in this file" => self.show_changes(false),
            _ => self.show_changes(true),
        }
    }

    /// Opens a view of what changed since the last commit: in the file in
    /// front, or in the whole project. Enter on a line of it goes to that
    /// line in its file.
    pub(super) fn show_changes(&mut self, everything: bool) {
        let file = self.git_target().filter(|_| !everything);
        if !everything && file.is_none() {
            return self.say("No file to show the changes of: open one first".into());
        }
        if self.editors.iter().any(|editor| editor.document.dirty) {
            self.say("Unsaved changes are not shown: the files are compared as they are on disk".into());
        }
        let title = match &file {
            Some(file) => format!("changes: {}", file.file_name().unwrap_or_default().to_string_lossy()),
            None => "changes: everything".to_string(),
        };
        let Some(text) = git::diff(self.tree.root(), file.as_deref()) else {
            return self.say("This folder is not in git".into());
        };
        if text.trim().is_empty() {
            return self.say("Nothing has changed since the last commit".into());
        }
        let lines = text.lines().map(String::from).collect();
        let view = Editor::view_of(&title, lines, crate::snippets::Language::Diff);
        // One view per title: asked again, it is brought up to date.
        match self.editors.iter().position(|editor| editor.view.as_deref() == Some(title.as_str())) {
            Some(index) => {
                self.editors[index] = view;
                self.active = index;
            }
            None => {
                self.editors.push(view);
                self.active = self.editors.len() - 1;
            }
        }
        self.focus = Focus::Editor;
        self.say("Enter on a line goes to it in its file".into());
    }

    /// Runs `job` (a git command) in the project folder, away from the
    /// keys so a slow one does not freeze the editor, and says `done`
    /// afterwards, or what went wrong.
    pub(super) fn run_git(
        &mut self,
        done: String,
        job: impl FnOnce(&Path) -> Result<(), String> + Send + 'static,
    ) {
        let root = self.tree.root().to_path_buf();
        let report = move || match job(&root) {
            Ok(()) => done,
            Err(error) => format!("git: {error}"),
        };
        match &self.events {
            Some(events) => {
                let events = events.clone();
                std::thread::spawn(move || {
                    let _ = events.send(AppEvent::GitDone(report()));
                });
                self.say("Running git...".into());
            }
            // Tests have no queue to answer on: do it on the spot.
            None => {
                let message = report();
                self.git_done(message);
            }
        }
    }

    /// A git command finished: files, branch and states may all be new.
    pub(super) fn git_done(&mut self, message: String) {
        self.tree.refresh();
        self.reload_changed();
        self.refresh_git();
        self.say(message);
    }

    /// Reads again every open file that was changed on disk by something
    /// else (a branch switch, a pull, another program). Files with unsaved
    /// changes are left alone.
    pub(super) fn reload_changed(&mut self) {
        for editor in &mut self.editors {
            let Some(path) = editor.abs_path.clone().filter(|path| Path::new(path).is_file()) else {
                continue;
            };
            if editor.document.dirty {
                continue;
            }
            // A file that was last changed when it was last looked at, and
            // is as big, has not been touched: it need not be read. With
            // many files open, reading them all took long enough to feel.
            let now = disk_stamp(&path);
            if now.is_some() && now == editor.disk {
                continue;
            }
            if let Ok(on_disk) = Document::open(&path)
                && on_disk.lines.join("\n") != editor.document.lines.join("\n")
            {
                editor.reload(&on_disk.lines);
            }
            editor.disk = now;
        }
    }
}