diff --git a/crates/ide-vcs/src/block_history.rs b/crates/ide-vcs/src/block_history.rs index ccea8690f3..6b88c78c45 100644 --- a/crates/ide-vcs/src/block_history.rs +++ b/crates/ide-vcs/src/block_history.rs @@ -47,7 +47,8 @@ pub(crate) fn block_history( return Ok(BlockHistory { head_lines: None, head: None, revisions: Vec::new() }); }; let range = format!("-L{},{}:{rel}", start + 1, end + 1); - let args = ["log", "--no-color", "--no-ext-diff", "--no-textconv", FORMAT, &range, "HEAD"]; + let [c, utf8] = cli::UTF8_LOG_OUTPUT; + let args = [c, utf8, "log", "--no-color", "--no-ext-diff", "--no-textconv", FORMAT, &range, "HEAD"]; let out = cli::run_cancellable(r.root(), &args, cancel)?; // The newest row's block can't stand in for HEAD's: a merge row has none. // Normalise line endings so HEAD's block matches the editor and `line_hunks`. @@ -119,8 +120,8 @@ fn anchor_range(rel: &str, anchor: &BlockHistoryAnchor) -> String { } fn log_args<'a>(options: &[&'a str], ranges: &'a [String], commit: &'a str) -> Vec<&'a str> { - let mut args = - vec!["log", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", FORMAT]; + let mut args = cli::UTF8_LOG_OUTPUT.to_vec(); + args.extend(["log", "--no-color", "--no-ext-diff", "--no-textconv", "--src-prefix=a/", "--dst-prefix=b/", FORMAT]); args.extend_from_slice(options); args.extend(ranges.iter().map(String::as_str)); args.push(commit); diff --git a/crates/ide-vcs/src/cli.rs b/crates/ide-vcs/src/cli.rs index 8f3983b3b1..f18fda1c94 100644 --- a/crates/ide-vcs/src/cli.rs +++ b/crates/ide-vcs/src/cli.rs @@ -290,6 +290,12 @@ pub fn restrict(cmd: &mut Command) { cmd.env_remove("GIT_EXTERNAL_DIFF").env("GIT_NO_LAZY_FETCH", "1"); } +/// Leading options for a git whose printed commit messages or names the IDE reads: each commit is +/// converted to UTF-8 from the encoding it names, instead of being printed in +/// `i18n.logOutputEncoding`, which defaults to `i18n.commitEncoding`. Not for every git: `git stash` +/// writes HEAD's subject into its own message in that encoding. +pub(crate) const UTF8_LOG_OUTPUT: [&str; 2] = ["-c", "i18n.logOutputEncoding=UTF-8"]; + /// Builds a `git` command with the environment every invocation needs. pub(crate) fn command(root: &Path) -> IdeResult { let restricted = !crate::execution_allowed(); diff --git a/crates/ide-vcs/src/commit_message.rs b/crates/ide-vcs/src/commit_message.rs index 44db15e491..75b7603efb 100644 --- a/crates/ide-vcs/src/commit_message.rs +++ b/crates/ide-vcs/src/commit_message.rs @@ -406,9 +406,10 @@ impl Repo { } fn commit_author(&self, commit: &str, cancel: &CancellationToken) -> Option<(String, String)> { + let [c, utf8] = cli::UTF8_LOG_OUTPUT; let raw = cli::run_bounded( self.root(), - &["show", "-s", "--no-show-signature", "--format=%an%x00%ae%x00%aI", commit, "--"], + &[c, utf8, "show", "-s", "--no-show-signature", "--format=%an%x00%ae%x00%aI", commit, "--"], cancel, 64 << 10, ) diff --git a/crates/ide-vcs/src/commit_rewrite.rs b/crates/ide-vcs/src/commit_rewrite.rs index 84930b43c6..e36af70e06 100644 --- a/crates/ide-vcs/src/commit_rewrite.rs +++ b/crates/ide-vcs/src/commit_rewrite.rs @@ -299,7 +299,13 @@ pub(crate) fn amend( ("GIT_INDEX_FILE", chosen.path().as_os_str()), ]; crate::write::fill_commit_index(repo, &env, options, encoding)?; - let message = if message.trim().is_empty() { commit.message() } else { message.as_bytes() }; + let encoded; + let message = if message.trim().is_empty() { + commit.message() + } else { + encoded = crate::write::commit_message_bytes(repo, message)?; + &encoded + }; run_env(repo.root(), commit_args, Some(message), &env)?; let selected = fs::read_to_string(scratch.path().join("HEAD"))?; let selected = selected.trim(); diff --git a/crates/ide-vcs/src/lib.rs b/crates/ide-vcs/src/lib.rs index a534e8de22..fd248c8262 100644 --- a/crates/ide-vcs/src/lib.rs +++ b/crates/ide-vcs/src/lib.rs @@ -1533,7 +1533,8 @@ impl Repo { let _scope = self.execution_scope(); // `%aN <%aE>`: the User filter lists mailmap-mapped identities, so one canonical entry // covers all name variants of the same person. - let out = cli::run(self.root(), &["log", "--all", "--format=%aN <%aE>"], None)?; + let [c, utf8] = cli::UTF8_LOG_OUTPUT; + let out = cli::run(self.root(), &[c, utf8, "log", "--all", "--format=%aN <%aE>"], None)?; Ok(out .stdout_str() .lines() diff --git a/crates/ide-vcs/src/log_index.rs b/crates/ide-vcs/src/log_index.rs index 27e0984d71..81e4572ff6 100644 --- a/crates/ide-vcs/src/log_index.rs +++ b/crates/ide-vcs/src/log_index.rs @@ -2,7 +2,7 @@ //! projections are deliberately never cached as commit metadata. use crate::Commit; -use crate::repo::{gx, to_string}; +use crate::repo::{commit_encoding, commit_text, gx, to_string}; use gix::ObjectId; use gix::bstr::ByteSlice; use ide_core::IdeResult; @@ -13,9 +13,12 @@ use std::sync::{Arc, Mutex, OnceLock, Weak}; use std::time::SystemTime; // v3: summaries follow git's subject (the first paragraph on one line), not the first line. -pub(crate) const COMMITS: TableDefinition<&str, &[u8]> = TableDefinition::new("summaries-v3"); -const STALE_COMMITS: TableDefinition<&str, &[u8]> = TableDefinition::new("summaries-v2"); -const MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v1"); +// v4 and messages v2: text is decoded from the encoding the commit names, not always UTF-8. +pub(crate) const COMMITS: TableDefinition<&str, &[u8]> = TableDefinition::new("summaries-v4"); +const STALE_COMMITS: [TableDefinition<&str, &[u8]>; 2] = + [TableDefinition::new("summaries-v2"), TableDefinition::new("summaries-v3")]; +const MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v2"); +const STALE_MESSAGES: TableDefinition<&str, &str> = TableDefinition::new("messages-v1"); const MAX_MEMORY_COMMITS: usize = 4096; const MAX_MEMORY_MESSAGES: usize = 1024; const MAX_DIRTY_BATCH: usize = 16_384; @@ -362,9 +365,11 @@ impl LogIndex { let commit = repo.find_commit(id).map_err(gx)?; let author = commit.author().map_err(gx)?; let committer = commit.committer().map_err(gx)?; - let raw = commit.message_raw_sloppy(); - let summary_text = subject(raw.as_bstr()); - let message_truncated = raw.trim() != summary_text.as_bytes(); + let encoding = commit_encoding(&commit); + let text = |bytes: &[u8]| commit_text(bytes.trim().as_bstr(), encoding); + let message = text(commit.message_raw_sloppy()); + let summary_text = subject(message.as_bytes().as_bstr()); + let message_truncated = message != summary_text; let record = Arc::new(Commit { id: key.clone(), short_id: key[..key.len().min(8)].to_string(), @@ -373,10 +378,10 @@ impl LogIndex { graph_dashed: Vec::new(), dashed: Vec::new(), on_current_branch: None, - author: to_string(author.name.trim().as_bstr()), - email: to_string(author.email.trim().as_bstr()), - committer: to_string(committer.name.trim().as_bstr()), - committer_email: to_string(committer.email.trim().as_bstr()), + author: text(author.name), + email: text(author.email), + committer: text(committer.name), + committer_email: text(committer.email), time_ms: author.time().map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0), commit_time_ms: committer.time().map(|t| t.seconds as f64 * 1000.0).unwrap_or(0.0), summary: summary_text.clone(), @@ -418,7 +423,8 @@ impl LogIndex { let message = if let Some(message) = cached { message } else { - let message = to_string(repo.find_commit(id).map_err(gx)?.message_raw_sloppy()).trim_end().to_string(); + let commit = repo.find_commit(id).map_err(gx)?; + let message = commit_text(commit.message_raw_sloppy(), commit_encoding(&commit)).trim_end().to_string(); if self.db.is_some() { self.dirty_messages.push((key, message.clone())); } @@ -492,7 +498,12 @@ pub(crate) fn subject(message: &gix::bstr::BStr) -> String { /// Drops tables an older version wrote, so outdated summaries don't stay on disk. fn drop_stale_tables(db: &Database) { let Ok(txn) = db.begin_write() else { return }; - if txn.delete_table(STALE_COMMITS).unwrap_or(false) { + let mut dropped = false; + for table in STALE_COMMITS { + dropped |= txn.delete_table(table).unwrap_or(false); + } + dropped |= txn.delete_table(STALE_MESSAGES).unwrap_or(false); + if dropped { let _ = txn.commit(); } } diff --git a/crates/ide-vcs/src/ops.rs b/crates/ide-vcs/src/ops.rs index 90048daeee..d6a5850d11 100644 --- a/crates/ide-vcs/src/ops.rs +++ b/crates/ide-vcs/src/ops.rs @@ -177,7 +177,7 @@ pub(crate) fn commit_apply_message( out: &dyn Fn(String), ) -> IdeResult<()> { let mut file = tempfile::NamedTempFile::new_in(&r.git_dir)?; - file.write_all(message.as_bytes())?; + file.write_all(&crate::write::commit_message_bytes(r, message)?)?; let path = file.path().to_str().ok_or_else(|| IdeError::invalid("Invalid commit message file path"))?; let flags = crate::write::commit_metadata_flags( options.sign_off, @@ -453,7 +453,7 @@ pub(crate) fn interactive_rebase( )); } let file = work.join(format!("msg-{i}")); - std::fs::write(&file, m)?; + std::fs::write(&file, crate::write::commit_message_bytes(r, m)?)?; // After a step that was skipped or came out empty, HEAD is still the commit below. let mut made = format!("test \"$(git rev-parse HEAD)\" != \"$(cat {})\"", head_before(i)); // When its target was skipped, Git melds the squash into the commit below and so diff --git a/crates/ide-vcs/src/rebase_editor.rs b/crates/ide-vcs/src/rebase_editor.rs index 7c4b392f57..8e2d8a64ab 100644 --- a/crates/ide-vcs/src/rebase_editor.rs +++ b/crates/ide-vcs/src/rebase_editor.rs @@ -1,4 +1,5 @@ -use crate::{RebaseAction, RebaseOptions, Repo, cli, log_index::subject, manage::rebase_args, ops, repo::resolve}; +use crate::repo::{commit_encoding, commit_text, resolve}; +use crate::{RebaseAction, RebaseOptions, Repo, cli, log_index::subject, manage::rebase_args, ops}; use gix::bstr::ByteSlice; use ide_core::{CancellationToken, IdeError, IdeResult}; use serde::{Deserialize, Serialize}; @@ -391,8 +392,9 @@ fn simple_plan(r: &Repo, text: &str, comment: &str, cancel: &CancellationToken) return None; } let commit = repo.find_commit(id).ok()?; - let raw = commit.message_raw_sloppy(); - let author = commit.author().ok()?.name.trim().to_str_lossy().into_owned(); + let encoding = commit_encoding(&commit); + let message = commit_text(commit.message_raw_sloppy(), encoding); + let author = commit_text(commit.author().ok()?.name.trim().as_bstr(), encoding); todo.push(RebaseTodoRow::Commit { line, action, @@ -400,8 +402,8 @@ fn simple_plan(r: &Repo, text: &str, comment: &str, cancel: &CancellationToken) id: id.to_string(), revision: revision.to_owned(), author, - summary: subject(raw), - message: raw.to_str_lossy().trim_end().to_owned(), + summary: subject(message.as_bytes().as_bstr()), + message: message.trim_end().to_owned(), }); } (!todo.is_empty()).then_some(todo) diff --git a/crates/ide-vcs/src/repo.rs b/crates/ide-vcs/src/repo.rs index 2696bdbcc7..31b85d47f0 100644 --- a/crates/ide-vcs/src/repo.rs +++ b/crates/ide-vcs/src/repo.rs @@ -713,6 +713,22 @@ pub(crate) fn to_string(b: &BStr) -> String { b.to_str_lossy().into_owned() } +/// The encoding `commit`'s `encoding` header names (`i18n.commitEncoding` when it was made), when +/// it is one other than UTF-8 that the IDE can decode. +pub(crate) fn commit_encoding(commit: &gix::Commit<'_>) -> Option<&'static encoding_rs::Encoding> { + let label = commit.decode().ok()?.encoding?; + encoding_rs::Encoding::for_label(label.trim()).filter(|encoding| *encoding != encoding_rs::UTF_8) +} + +/// Text of a commit (its message or a name in it) decoded from `encoding`, as `git log +/// --encoding=UTF-8` shows it. +pub(crate) fn commit_text(text: &BStr, encoding: Option<&'static encoding_rs::Encoding>) -> String { + match encoding { + Some(encoding) => encoding.decode_without_bom_handling(text).0.into_owned(), + None => to_string(text), + } +} + #[cfg(all(test, unix))] mod tests { use super::*; diff --git a/crates/ide-vcs/src/write.rs b/crates/ide-vcs/src/write.rs index 1519a93c08..d50d732d56 100644 --- a/crates/ide-vcs/src/write.rs +++ b/crates/ide-vcs/src/write.rs @@ -139,7 +139,8 @@ pub(crate) fn blame( }; let text = current_text.map(str::to_owned).unwrap_or_else(|| decode(&disk, encoding).into_owned()); let ignore = ignore_revs_args(r); - let mut args = vec!["--literal-pathspecs", "blame", "--porcelain"]; + let mut args = cli::UTF8_LOG_OUTPUT.to_vec(); + args.extend(["--literal-pathspecs", "blame", "--porcelain"]); if options.ignore_whitespace { args.push("-w"); } @@ -515,6 +516,28 @@ pub(crate) fn discard(r: &Repo, paths: &[PathBuf]) -> IdeResult<()> { Ok(()) } +/// `message` as `git commit -F` expects it: in `i18n.commitEncoding`, which Git names in the +/// commit's `encoding` header (UTF-8 when unset or unknown). Text that encoding cannot represent +/// is refused rather than committed as replacement characters. +pub(crate) fn commit_message_bytes(r: &Repo, message: &str) -> IdeResult> { + let label = match r.gix()?.config_snapshot().string("i18n.commitEncoding") { + Some(label) => label.to_str_lossy().trim().to_owned(), + None => return Ok(message.as_bytes().to_vec()), + }; + let Some(encoding) = encoding_rs::Encoding::for_label(label.as_bytes()) + .filter(|encoding| *encoding != encoding_rs::UTF_8 && encoding.output_encoding() == *encoding) + else { + return Ok(message.as_bytes().to_vec()); + }; + let (bytes, _, unmappable) = encoding.encode(message); + if unmappable { + return Err(IdeError::invalid(format!( + "The commit message has characters that {label} (i18n.commitEncoding) cannot represent" + ))); + } + Ok(bytes.into_owned()) +} + pub(crate) fn commit_metadata_flags( sign_off: bool, run_hooks: bool, @@ -563,6 +586,7 @@ pub(crate) fn commit( args.extend(["-F", "-"]); return crate::commit_rewrite::amend(r, target, message, &args, options, encoding); } + let encoded; let stdin = if options.amend && message.trim().is_empty() { args.push("--no-edit"); None @@ -571,7 +595,8 @@ pub(crate) fn commit( return Err(IdeError::invalid("commit message is empty")); } args.extend(["-F", "-"]); - Some(message.as_bytes()) + encoded = commit_message_bytes(r, message)?; + Some(encoded.as_slice()) }; if selects(options) { commit_selected(r, &args, stdin, options, encoding)?; @@ -1469,7 +1494,8 @@ pub(crate) fn undo_commit(r: &Repo, commit: &str) -> IdeResult { return Err(IdeError::invalid("only the latest commit of the current branch can be undone")); } let c = repo.find_commit(head).map_err(gx)?; - let message = crate::repo::to_string(c.message_raw_sloppy()).trim_end().to_string(); + let encoding = crate::repo::commit_encoding(&c); + let message = crate::repo::commit_text(c.message_raw_sloppy(), encoding).trim_end().to_string(); (message, c.parent_ids().count(), repo.head_name().map_err(gx)?.is_some()) }; match parents { diff --git a/crates/ide-vcs/tests/git_workflows.rs b/crates/ide-vcs/tests/git_workflows.rs index b0235681eb..fb9402d423 100644 --- a/crates/ide-vcs/tests/git_workflows.rs +++ b/crates/ide-vcs/tests/git_workflows.rs @@ -462,6 +462,46 @@ fn undo_commit_on_detached_head() { assert_eq!(fx.git(&["rev-parse", "main"]), base, "branch untouched"); } +/// With `i18n.commitEncoding` set, Git names that encoding in each commit and expects the message +/// in it: the IDE writes messages in it and reads each commit in the encoding the commit names. +#[test] +fn commit_messages_follow_the_commit_encoding() { + for (label, text) in [("ISO-8859-1", "café"), ("Shift_JIS", "日本語"), ("windows-1251", "привет")] { + let fx = Fixture::new(); + fx.git(&["config", "i18n.commitEncoding", label]); + let encoding = encoding_rs::Encoding::for_label(label.as_bytes()).unwrap(); + // A commit made by Git from a message in that encoding. + fx.write("a.txt", "1\n"); + fx.git(&["add", "a.txt"]); + std::fs::write(fx.path(".git/msg"), encoding.encode(&format!("{text} by git\n")).0).unwrap(); + fx.git(&["commit", "-q", "-F", ".git/msg"]); + let by_git = fx.head(); + let repo = fx.repo(); + let log = repo.log(&LogQuery { limit: 1, ..Default::default() }).unwrap(); + assert_eq!(log[0].summary, format!("{text} by git"), "{label}: Git Log row"); + assert_eq!(repo.log_details(&by_git).unwrap().message, format!("{text} by git"), "{label}: details"); + let blame = repo.blame(&fx.path("a.txt"), None, None, encoding_rs::UTF_8).unwrap(); + assert_eq!(blame[0].summary, format!("{text} by git"), "{label}: Annotate"); + + // Commit, reword and Undo Commit in the IDE. + let utf8_subject = || fx.git(&["log", "-1", "--encoding=UTF-8", "--format=%s"]); + fx.write("a.txt", "2\n"); + repo.stage(&[fx.path("a.txt")]).unwrap(); + let committed = repo.commit(&format!("{text} by the IDE"), false, false).unwrap(); + assert_eq!(utf8_subject(), format!("{text} by the IDE"), "{label}: Commit"); + let (cancel, out) = quiet(); + let reword = entry(&committed, RebaseAction::Reword, Some(&format!("{text} reworded"))); + repo.interactive_rebase(Some(&by_git), &[reword], &cancel, &out).unwrap(); + assert_eq!(utf8_subject(), format!("{text} reworded"), "{label}: rebase reword"); + assert_eq!(repo.undo_commit(&fx.head()).unwrap(), format!("{text} reworded"), "{label}: Undo Commit"); + + // Text the encoding cannot hold is refused, not committed as replacement characters. + let error = repo.commit("emoji 😀", false, false).unwrap_err(); + assert!(error.message.contains("i18n.commitEncoding"), "{label}: {}", error.message); + assert_eq!(fx.head(), by_git, "{label}: nothing committed"); + } +} + // --------------------------------------------------------------------------- // Interactive rebase diff --git a/crates/ide-vcs/tests/history_ops.rs b/crates/ide-vcs/tests/history_ops.rs index 12c9b14009..df2183875e 100644 --- a/crates/ide-vcs/tests/history_ops.rs +++ b/crates/ide-vcs/tests/history_ops.rs @@ -410,6 +410,21 @@ fn reviewed_formatting_keeps_the_index_transaction_scoped_and_preserves_worktree assert_eq!(fx.read("f.txt"), "other unstaged edit\n"); } +#[test] +fn reviewed_cherry_pick_writes_the_edited_message_in_the_commit_encoding() { + let (fx, picks) = mixed_cherry_pick_fixture(); + fx.git(&["config", "i18n.commitEncoding", "ISO-8859-1"]); + let (cancel, out) = quiet(); + let repo = fx.repo(); + assert!(repo.cherry_pick_with(&picks, false, &cancel, &out).is_err()); + fx.write("f.txt", "resolved\n"); + repo.stage(&[fx.path("f.txt")]).unwrap(); + let review = repo.review_apply_commit(&cancel).unwrap().unwrap(); + let options = Default::default(); + repo.continue_reviewed_apply(&review.checkpoint, "Café pick", &options, Default::default(), &cancel, &out).unwrap(); + assert_eq!(fx.git(&["log", "-1", "--encoding=UTF-8", "--format=%s", "HEAD~1"]), "Café pick"); +} + #[test] fn reviewed_cherry_pick_keeps_the_edited_message_and_resumes_both_kinds_of_queue() { for mixed in [false, true] {