use super::*;
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",
];
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 {
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),
});
}
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);
}
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());
}
}
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),
}
}
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()),
"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),
}
}
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);
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());
}
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());
}
None => {
let message = report();
self.git_done(message);
}
}
}
pub(super) fn git_done(&mut self, message: String) {
self.tree.refresh();
self.reload_changed();
self.refresh_git();
self.say(message);
}
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;
}
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;
}
}
}