Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,10 @@ All notable changes to AngKorGit are documented here. The format follows
`git merge` does, so `git diff ORIG_HEAD HEAD` shows what a pull brought in.

### Fixed
- **Pull with rebase handles upstream submodule updates.** Local commits now replay
when the upstream changes a submodule's recorded commit. Continue rebase also
recovers a rebase stopped by this problem in an older version and updates clean
submodules still at their pre-rebase commits. (#89)
- **Discarding staged changes writes the index once and leaves other files alone.**
A file whose name contains `[`, `]`, `*` or `?` no longer resets files the name
happens to match. The whole batch takes Git's index lock and stops without
Expand Down
73 changes: 65 additions & 8 deletions CLAUDE.md

Large diffs are not rendered by default.

4 changes: 1 addition & 3 deletions apps/desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ notify-debouncer-mini = "0.4"
reqwest = { version = "0.12", default-features = false, features = ["rustls-tls", "json"] }
which = "7"
same-file = "1"
tempfile = "3"
fontdb = { version = "0.24", default-features = false, features = ["std", "fs", "memmap", "fontconfig"] }

[target.'cfg(unix)'.dependencies]
Expand All @@ -51,9 +52,6 @@ gtk = "0.18"
libssh2-sys = { version = "0.3", features = ["openssl-on-win32", "vendored-openssl"] }
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_Diagnostics_ToolHelp", "Win32_System_JobObjects", "Win32_System_Threading"] }

[dev-dependencies]
tempfile = "3"

[profile.release]
codegen-units = 1
lto = true
Expand Down
81 changes: 78 additions & 3 deletions apps/desktop/src-tauri/src/core/branch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -364,7 +364,7 @@ pub(crate) fn rebase_with_hooks(
if index.has_conflicts() {
return Ok(paused_rebase());
}
match rebase.commit(None, &sig, None) {
match commit_rebase_step(&repo, &mut rebase, &sig) {
Ok(_) => {}
Err(e) if e.code() == git2::ErrorCode::Applied => {}
Err(e) => return Err(e.into()),
Expand All @@ -381,6 +381,81 @@ pub(crate) fn rebase_with_hooks(
})
}

struct RebaseCommitIndex<'repo> {
repo: &'repo Repository,
original: git2::Index,
}

impl Drop for RebaseCommitIndex<'_> {
fn drop(&mut self) {
let _ = self.repo.set_index(&mut self.original);
}
}

fn commit_rebase_step(
repo: &Repository,
rebase: &mut git2::Rebase<'_>,
signature: &git2::Signature<'_>,
) -> Result<git2::Oid, git2::Error> {
let error = match rebase.commit(None, signature, None) {
Ok(oid) => return Ok(oid),
Err(error)
if error.code() == git2::ErrorCode::Unmerged
&& error.class() == git2::ErrorClass::Rebase =>
{
error
}
Err(error) => return Err(error),
};
let original = repo.index()?;
let mut drifted = Vec::new();
let Ok(submodules) = repo.submodules() else {
return Err(error);
};
for submodule in submodules {
let (Some(recorded), Some(checked_out)) = (submodule.index_id(), submodule.workdir_id())
else {
continue;
};
if recorded == checked_out {
continue;
}
let Some(name) = submodule.name() else {
continue;
};
let Ok(status) = repo.submodule_status(name, git2::SubmoduleIgnore::Untracked) else {
return Err(error);
};
if status.intersects(
git2::SubmoduleStatus::WD_ADDED
| git2::SubmoduleStatus::WD_DELETED
| git2::SubmoduleStatus::WD_INDEX_MODIFIED
| git2::SubmoduleStatus::WD_WD_MODIFIED,
) {
continue;
}
if let Some(mut entry) = original.get_path(submodule.path(), 0) {
if entry.mode == u32::from(git2::FileMode::Commit) {
entry.flags |= git2::IndexEntryFlag::VALID.bits();
drifted.push(entry);
}
}
}
if drifted.is_empty() || original.has_conflicts() {
return Err(error);
}
let mut temporary = git2::Index::new()?;
for entry in original.iter() {
temporary.add(&entry)?;
}
for entry in drifted {
temporary.add(&entry)?;
}
repo.set_index(&mut temporary)?;
let _restore = RebaseCommitIndex { repo, original };
rebase.commit(None, signature, None)
}

fn rewritten_pairs(repo: &Repository) -> Vec<(git2::Oid, git2::Oid)> {
let file = rebase_state_dir(repo).join("rewritten");
let Ok(text) = std::fs::read_to_string(file) else {
Expand Down Expand Up @@ -423,7 +498,7 @@ pub(crate) fn rebase_continue_with_hooks(
});
}
}
match rebase.commit(None, &sig, None) {
match commit_rebase_step(&repo, &mut rebase, &sig) {
Ok(_) => {}
Err(e) if e.code() == git2::ErrorCode::Applied => {}
Err(e) => return Err(e.into()),
Expand All @@ -437,7 +512,7 @@ pub(crate) fn rebase_continue_with_hooks(
if index.has_conflicts() {
return Ok(paused_rebase());
}
match rebase.commit(None, &sig, None) {
match commit_rebase_step(&repo, &mut rebase, &sig) {
Ok(_) => {}
Err(e) if e.code() == git2::ErrorCode::Applied => {}
Err(e) => return Err(e.into()),
Expand Down
6 changes: 3 additions & 3 deletions apps/desktop/src-tauri/src/core/post_hooks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ pub fn pull(
no_verify: bool,
) -> Hooked<AppResult<OpOutcome>> {
let mut hooks = PostHooks::new(no_verify);
let outcome = submodule::synced(path, || {
let outcome = submodule::synced_rebase(path, || {
remote::pull_with_hooks(path, remote_name, mode, &mut hooks)
});
finished_or_failed(path, outcome, hooks)
Expand All @@ -175,15 +175,15 @@ pub fn pull_branch(path: &str, branch_name: &str, no_verify: bool) -> AppResult<

pub fn rebase(path: &str, upstream: &str, no_verify: bool) -> Hooked<AppResult<OpOutcome>> {
let mut hooks = PostHooks::new(no_verify);
let outcome = submodule::synced(path, || {
let outcome = submodule::synced_rebase(path, || {
branch::rebase_with_hooks(path, upstream, &mut hooks)
});
finished_or_failed(path, outcome, hooks)
}

pub fn rebase_continue(path: &str, no_verify: bool) -> AppResult<Hooked<OpOutcome>> {
let mut hooks = PostHooks::new(no_verify);
let outcome = submodule::synced(path, || {
let outcome = submodule::synced_rebase(path, || {
branch::rebase_continue_with_hooks(path, &mut hooks)
})?;
Ok(finished(path, outcome, hooks))
Expand Down
136 changes: 135 additions & 1 deletion apps/desktop/src-tauri/src/core/submodule.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use git2::{Oid, Repository, Submodule, SubmoduleIgnore, SubmoduleStatus};
use std::{io::Write, path::Path};

use crate::error::AppResult;
use crate::error::{AppError, AppResult};

use super::types::{SubmoduleCommits, SubmoduleInfo};

Expand Down Expand Up @@ -54,6 +55,104 @@ pub fn synced<T>(path: &str, op: impl FnOnce() -> AppResult<T>) -> AppResult<T>
Ok(result)
}

const REBASE_BASELINE: &str = "angkorgit-submodules";

pub fn synced_rebase<T>(path: &str, op: impl FnOnce() -> AppResult<T>) -> AppResult<T> {
let before = rebase_baseline(&super::repo::open(path)?)?;
let result = op();
if result.is_ok() {
follow_recorded(path, &before, true);
}
if let Err(error) = save_rebase_baseline(path, &before, result.is_ok()) {
eprintln!("Cannot save rebase submodule baseline in {path}: {error}");
}
result
}

fn rebase_baseline(repo: &Repository) -> AppResult<Vec<(String, Oid)>> {
let mut before = at_recorded_commit(repo);
if repo.state() != git2::RepositoryState::RebaseMerge {
return Ok(before);
}
let file = repo.path().join("rebase-merge").join(REBASE_BASELINE);
let saved = match std::fs::read(file) {
Ok(bytes) => serde_json::from_slice::<Vec<(String, String)>>(&bytes)
.map_err(|error| {
AppError::other(format!("Cannot read rebase submodule baseline: {error}"))
})?
.into_iter()
.map(|(name, oid)| Ok((name, Oid::from_str(&oid)?)))
.collect::<AppResult<Vec<_>>>()?,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
let rebase = repo.open_rebase(None)?;
let original = rebase
.orig_head_id()
.ok_or_else(|| AppError::other("The rebase has no original commit"))?;
let tree = repo.find_commit(original)?.tree()?;
repo.submodules()
.unwrap_or_default()
.iter()
.filter_map(|submodule| {
let entry = tree.get_path(submodule.path()).ok()?;
let name = submodule.name()?.to_string();
(entry.kind() == Some(git2::ObjectType::Commit)).then(|| (name, entry.id()))
})
.collect()
}
Err(error) => return Err(error.into()),
};
for (name, previous) in saved {
if before.iter().any(|(existing, _)| existing == &name) {
continue;
}
if repo
.find_submodule(&name)
.ok()
.and_then(|sub| sub.workdir_id())
== Some(previous)
{
before.push((name, previous));
}
}
Ok(before)
}

fn save_rebase_baseline(path: &str, before: &[(String, Oid)], followed: bool) -> AppResult<()> {
let repo = super::repo::open(path)?;
if repo.state() != git2::RepositoryState::RebaseMerge {
return Ok(());
}
let saved: Vec<_> = before
.iter()
.filter_map(|(name, previous)| {
let submodule = repo.find_submodule(name).ok()?;
let current = submodule.workdir_id()?;
(current == *previous || (followed && submodule.index_id() == Some(current)))
.then(|| (name, current.to_string()))
})
.collect();
let bytes = serde_json::to_vec(&saved).map_err(|error| {
AppError::other(format!("Cannot save rebase submodule baseline: {error}"))
})?;
publish_rebase_baseline(&repo.path().join("rebase-merge"), |file| {
file.write_all(&bytes)
})?;
Ok(())
}

fn publish_rebase_baseline(
directory: &Path,
write: impl FnOnce(&mut std::fs::File) -> std::io::Result<()>,
) -> std::io::Result<()> {
let mut temporary = tempfile::NamedTempFile::new_in(directory)?;
write(temporary.as_file_mut())?;
temporary.as_file().sync_all()?;
temporary
.persist(directory.join(REBASE_BASELINE))
.map_err(|error| error.error)?;
Ok(())
}

pub fn at_recorded_commit(repo: &Repository) -> Vec<(String, Oid)> {
let Ok(submodules) = repo.submodules() else {
return Vec::new();
Expand Down Expand Up @@ -152,3 +251,38 @@ fn run_update(sub: &mut Submodule, init: bool, fetch: bool) -> AppResult<()> {
sub.update(init, Some(&mut opts))?;
Ok(())
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn publishing_a_baseline_replaces_only_the_complete_snapshot() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join(REBASE_BASELINE);
std::fs::write(&file, b"[ ]").unwrap();
publish_rebase_baseline(directory.path(), |temporary| {
temporary.write_all(b"[")?;
assert_eq!(std::fs::read(&file).unwrap(), b"[ ]");
temporary.write_all(b"]")
})
.unwrap();
assert_eq!(std::fs::read(&file).unwrap(), b"[]");
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}

#[test]
fn a_partial_baseline_write_failure_keeps_the_previous_snapshot() {
let directory = tempfile::tempdir().unwrap();
let file = directory.path().join(REBASE_BASELINE);
let previous = b"[[\"library\",\"0123456789012345678901234567890123456789\"]]";
std::fs::write(&file, previous).unwrap();
let result = publish_rebase_baseline(directory.path(), |temporary| {
temporary.write_all(b"[")?;
Err(std::io::Error::other("disk full"))
});
assert!(result.is_err());
assert_eq!(std::fs::read(&file).unwrap(), previous);
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
}
}
Loading
Loading