Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
Fix file_type matching for local single-file worktrees (#60307)
Peter Tripp224054274483
diff --git a/crates/git_ui/src/commit_view.rs b/crates/git_ui/src/commit_view.rsindex 0db0fe01afc..fb3a0f1de9f 100644--- a/crates/git_ui/src/commit_view.rs+++ b/crates/git_ui/src/commit_view.rs@@ -1536,7 +1536,7 @@ mod tests {use super::*;use gpui::{EmptyView, TestAppContext};use indoc::indoc;- use language::{Language, LanguageConfig, markdown_lang};+ use language::{Language, LanguageConfig, LanguageMatcher, markdown_lang};use settings::SettingsStore;#[gpui::test]@@ -1592,6 +1592,68 @@ mod tests {});}+ #[gpui::test]+ fn test_git_blob_language_detection_ignores_display_name(cx: &mut TestAppContext) {+ cx.update(|cx| {+ let mut store = SettingsStore::test(cx);+ store+ .set_user_settings(r#"{"file_types":{"JSONC":["tsconfig*.json"]}}"#, cx)+ .expect("valid file type settings");+ cx.set_global(store);+ });++ let language_registry = Arc::new(LanguageRegistry::test(cx.executor()));+ language_registry.register_test_language(LanguageConfig {+ name: "JSON".into(),+ matcher: Arc::new(LanguageMatcher {+ path_suffixes: vec!["json".into(), "flake.lock".into()],+ ..LanguageMatcher::default()+ }),+ ..LanguageConfig::default()+ });+ language_registry.register_test_language(LanguageConfig {+ name: "JSONC".into(),+ ..LanguageConfig::default()+ });++ let languages = cx.update(|cx| {+ [+ ("flake.lock", "abc1234 - flake.lock"),+ ("flake.lock", "flake.lock @ abc1234"),+ ("nix/flake.lock", "abc1234 - flake.lock"),+ ("nix/flake.lock", "flake.lock @ abc1234"),+ ("web/tsconfig.json", "abc1234 - tsconfig.json"),+ ("web/tsconfig.json", "tsconfig.json @ abc1234"),+ ]+ .map(|(path, display_name)| {+ let blob = Arc::new(GitBlob {+ path: RepoPath::new(path).expect("valid repository path"),+ worktree_id: WorktreeId::from_usize(0),+ is_deleted: false,+ is_binary: false,+ display_name: display_name.to_string(),+ }) as Arc<dyn File>;+ assert_eq!(blob.file_system_abs_path(cx), None);+ language_registry+ .language_for_file(&blob, None, cx)+ .and_then(|id| language_registry.language_name_for_id(id))+ .map(|name| name.to_string())+ })+ });++ assert_eq!(+ languages.each_ref().map(|name| name.as_deref()),+ [+ Some("JSON"),+ Some("JSON"),+ Some("JSON"),+ Some("JSON"),+ Some("JSONC"),+ Some("JSONC"),+ ]+ );+ }+fn markdown_inline_lang() -> Language {Language::new(LanguageConfig {diff --git a/crates/language/src/available_languages.rs b/crates/language/src/available_languages.rsindex a740c64d388..9b215c36ca4 100644--- a/crates/language/src/available_languages.rs+++ b/crates/language/src/available_languages.rs@@ -240,19 +240,20 @@ impl AvailableLanguages {pub(super) fn find_for_file(&self,- path: &Path,+ filename: Option<&str>,+ paths: &[&Path],content: Option<&Rope>,user_file_types: Option<&FxHashMap<Arc<str>, (GlobSet, Vec<String>)>>,) -> Option<LanguageId> {- let filename = path.file_name().and_then(|filename| filename.to_str());// `Path.extension()` returns None for files with a leading '.'// and no other extension which is not the desired behavior here,// as we want `.zshrc` to result in extension being `Some("zshrc")`let extension = filename.and_then(|filename| filename.split('.').next_back());- let path_suffixes = [extension, filename, path.to_str()]- .iter()+ let path_suffixes = [extension, filename]+ .into_iter()+ .chain(paths.iter().map(|path| path.to_str())).filter_map(|suffix| suffix.map(|suffix| (suffix, globset::Candidate::new(suffix))))- .collect::<SmallVec<[_; 3]>>();+ .collect::<SmallVec<[_; 6]>>();let content = LazyCell::new(|| {content.map(|content| {let end = content.clip_point(Point::new(0, 256), Bias::Left);diff --git a/crates/language/src/buffer.rs b/crates/language/src/buffer.rsindex c3e4030102f..4557cdf5e40 100644--- a/crates/language/src/buffer.rs+++ b/crates/language/src/buffer.rs@@ -376,6 +376,12 @@ pub trait File: Send + Sync + Any {/// includes the name of the worktree's root folder).fn full_path(&self, cx: &App) -> PathBuf;+ /// Returns the absolute path to this file in its backing file system.+ /// For remote files, this is an absolute path on the remote host.+ fn file_system_abs_path(&self, cx: &App) -> Option<PathBuf> {+ self.as_local().map(|file| file.abs_path(cx))+ }+/// Returns the path style of this file.fn path_style(&self, cx: &App) -> PathStyle;@@ -6107,6 +6113,16 @@ impl File for TestFile {PathBuf::from(self.root_name.clone()).join(self.path.as_std_path())}+ fn file_system_abs_path(&self, _: &App) -> Option<PathBuf> {+ let abs_path = self.local_root.as_ref()?.join(&self.root_name);+ // Mirror worktree::Worktree::absolutize: an empty relative path refers to the root itself.+ Some(if self.path.as_std_path().as_os_str().is_empty() {+ abs_path+ } else {+ abs_path.join(self.path.as_std_path())+ })+ }+fn as_local(&self) -> Option<&dyn LocalFile> {if self.local_root.is_some() {Some(self)diff --git a/crates/language/src/buffer_tests.rs b/crates/language/src/buffer_tests.rsindex 28ffa826c70..9c8ec32f9ac 100644--- a/crates/language/src/buffer_tests.rs+++ b/crates/language/src/buffer_tests.rs@@ -293,6 +293,7 @@ async fn test_language_for_file_with_custom_file_types(cx: &mut TestAppContext)"Dockerfile".into(),vec!["Dockerfile".into(), "Dockerfile.*".into()].into(),),+ ("SSH Config".into(), vec!["**/.ssh/config".into()].into()),]);})});@@ -346,6 +347,19 @@ async fn test_language_for_file_with_custom_file_types(cx: &mut TestAppContext).into(),..Default::default()},+ LanguageConfig {+ name: "SSH Config".into(),+ ..Default::default()+ },+ LanguageConfig {+ name: "INI".into(),+ matcher: (LanguageMatcher {+ path_suffixes: vec!["config".into()],+ ..Default::default()+ })+ .into(),+ ..Default::default()+ },] {languages.add(Arc::new(Language::new(config, None)));}@@ -396,6 +410,11 @@ async fn test_language_for_file_with_custom_file_types(cx: &mut TestAppContext).read(|cx| languages.language_for_file(&file("Dockerfile.dev"), None, cx)).unwrap();assert_eq!(language_name(language), "Dockerfile");++ let language = cx+ .read(|cx| languages.language_for_file(&local_file("/root/.ssh", "config"), None, cx))+ .unwrap();+ assert_eq!(language_name(language), "SSH Config");}#[gpui::test]@@ -562,6 +581,14 @@ fn file(path: &str) -> Arc<dyn File> {})}+fn local_file(local_root: &str, root_name: &str) -> Arc<dyn File> {+ Arc::new(TestFile {+ path: Arc::from(rel_path("")),+ root_name: root_name.into(),+ local_root: Some(PathBuf::from(local_root)),+ })+}+#[gpui::test]fn test_edit_events(cx: &mut gpui::App) {let mut now = Instant::now();diff --git a/crates/language/src/language_registry.rs b/crates/language/src/language_registry.rsindex 4a3accb9d17..a68bb69df80 100644--- a/crates/language/src/language_registry.rs+++ b/crates/language/src/language_registry.rs@@ -23,6 +23,7 @@ use gpui::{App, BackgroundExecutor, EntityId, Subscription};use lsp::LanguageServerId;use parking_lot::{Mutex, RwLock};use postage::watch;+use smallvec::SmallVec;use std::{ffi::OsStr,@@ -624,16 +625,42 @@ impl LanguageRegistry {cx: &App,) -> Option<LanguageId> {let user_file_types = all_language_settings(Some(file), cx);-+ let filename = file+ .path()+ .file_name()+ .unwrap_or_else(|| file.file_name(cx));+ let paths = [Some(file.full_path(cx)), file.file_system_abs_path(cx)];+ let path_style = file.path_style(cx);+ let normalized_paths = paths.each_ref().map(|path| {+ if path_style.is_windows()+ && let Some(path) = path.as_deref().and_then(Path::to_str)+ && path.contains('\\')+ {+ Some(PathBuf::from(path.replace('\\', "/")))+ } else {+ None+ }+ });+ let paths = paths+ .iter()+ .filter_map(Option::as_deref)+ .chain(normalized_paths.iter().filter_map(Option::as_deref))+ .collect::<SmallVec<[_; 4]>>();self.language_for_file_internal(- &file.full_path(cx),+ Some(filename),+ &paths,content,Some(&user_file_types.file_types),)}pub fn language_for_file_path(self: &Arc<Self>, path: &Path) -> Option<LanguageId> {- self.language_for_file_internal(path, None, None)+ self.language_for_file_internal(+ path.file_name().and_then(|filename| filename.to_str()),+ &[path],+ None,+ None,+ )}#[ztracing::instrument(skip_all)]@@ -655,14 +682,17 @@ impl LanguageRegistry {fn language_for_file_internal(self: &Arc<Self>,- path: &Path,+ filename: Option<&str>,+ paths: &[&Path],content: Option<&Rope>,user_file_types: Option<&FxHashMap<Arc<str>, (GlobSet, Vec<String>)>>,) -> Option<LanguageId> {- self.state- .read()- .available_languages- .find_for_file(path, content, user_file_types)+ self.state.read().available_languages.find_for_file(+ filename,+ paths,+ content,+ user_file_types,+ )}#[ztracing::instrument(skip_all)]diff --git a/crates/worktree/src/worktree.rs b/crates/worktree/src/worktree.rsindex 537876700a2..5b617447c4c 100644--- a/crates/worktree/src/worktree.rs+++ b/crates/worktree/src/worktree.rs@@ -3847,6 +3847,10 @@ impl language::File for File {self.worktree.read(cx).full_path(&self.path)}+ fn file_system_abs_path(&self, cx: &App) -> Option<PathBuf> {+ Some(self.worktree.read(cx).absolutize(&self.path))+ }+/// Returns the last component of this handle's absolute path. If this handle refers to the root/// of its worktree, then this method will return the name of the worktree itself.fn file_name<'a>(&'a self, cx: &'a App) -> &'a str {diff --git a/crates/worktree/tests/integration/worktree_tests.rs b/crates/worktree/tests/integration/worktree_tests.rsindex 2c7af1413bf..15a8808b316 100644--- a/crates/worktree/tests/integration/worktree_tests.rs+++ b/crates/worktree/tests/integration/worktree_tests.rs@@ -6551,6 +6551,193 @@ async fn test_remote_worktree_without_git_emits_root_repo_event_after_first_upda);}+#[gpui::test]+async fn test_remote_single_file_worktree_abs_path(cx: &mut TestAppContext) {+ cx.update(|cx| {+ let store = SettingsStore::test(cx);+ cx.set_global(store);+ });++ let worktree = cx.update(|cx| {+ Worktree::remote(+ 1,+ clock::ReplicaId::new(1),+ proto::WorktreeMetadata {+ id: 1,+ root_name: "config".to_string(),+ visible: true,+ abs_path: "/home/user/.ssh/config".to_string(),+ root_repo_common_dir: None,+ root_repo_is_linked_worktree: false,+ },+ AnyProtoClient::new(NoopProtoClient::new()),+ PathStyle::Unix,+ cx,+ )+ });++ let file = worktree::File {+ worktree,+ path: Arc::from(rel_path("")),+ disk_state: language::DiskState::New,+ entry_id: None,+ is_local: false,+ is_private: false,+ };++ cx.read(|cx| {+ assert_eq!(+ language::File::full_path(&file, cx),+ PathBuf::from("config")+ );+ assert_eq!(+ language::File::file_system_abs_path(&file, cx),+ Some(PathBuf::from("/home/user/.ssh/config"))+ );+ });+}++#[gpui::test]+fn test_remote_worktree_language_matching(cx: &mut TestAppContext) {+ init_test(cx);+ cx.update_global::<SettingsStore, _>(|store, cx| {+ store.update_user_settings(cx, |settings| {+ settings+ .project+ .all_languages+ .file_types+ .get_or_insert_default()+ .0+ .extend([+ (+ "Plain Text".into(),+ vec![+ "repo/templates/*.html".into(),+ #[cfg(unix)]+ r"repo\\raw\\*.html".into(),+ ]+ .into(),+ ),+ ("SSH Config".into(), vec!["**/.ssh/config".into()].into()),+ ]);+ });+ });+ let registry = Arc::new(language::LanguageRegistry::test(cx.executor()));+ for (name, suffixes) in [+ ("Plain Text", vec![]),+ ("SSH Config", vec![]),+ ("HTML", vec!["html".into()]),+ ("Git Commit", vec!["COMMIT_EDITMSG".into()]),+ ("INI", vec!["config".into()]),+ ] {+ registry.register_test_language(language::LanguageConfig {+ name: name.into(),+ matcher: language::LanguageMatcher {+ path_suffixes: suffixes,+ ..Default::default()+ }+ .into(),+ ..Default::default()+ });+ }++ let mut actual = Vec::new();+ for (root_name, abs_path, path, path_style) in [+ ("repo", "/tmp/repo", "templates/index.html", PathStyle::Unix),+ ("config", "/home/user/.ssh/config", "", PathStyle::Unix),+ (+ "COMMIT_EDITMSG",+ r"C:\review60307\COMMIT_EDITMSG",+ "",+ PathStyle::Windows,+ ),+ (+ "COMMIT_EDITMSG",+ r"\\server\share\COMMIT_EDITMSG",+ "",+ PathStyle::Windows,+ ),+ (+ "config",+ r"C:\Users\user\.ssh\config",+ "",+ PathStyle::Windows,+ ),+ (+ "config",+ r"\\server\share\.ssh\config",+ "",+ PathStyle::Windows,+ ),+ (+ "config",+ "C:/Users/user/.ssh/config",+ "",+ PathStyle::Windows,+ ),+ (".ssh", r"C:\Users\用户\.ssh", "config", PathStyle::Windows),+ (+ "repo",+ r"C:\repo",+ "templates/index.html",+ PathStyle::Windows,+ ),+ #[cfg(unix)]+ ("config", r"/home/user\.ssh/config", "", PathStyle::Unix),+ #[cfg(unix)]+ ("repo", r"C:\repo", "raw/index.html", PathStyle::Windows),+ ] {+ cx.update(|cx| {+ let worktree = Worktree::remote(+ 1,+ clock::ReplicaId::new(1),+ proto::WorktreeMetadata {+ id: 1,+ root_name: root_name.into(),+ visible: true,+ abs_path: abs_path.into(),+ root_repo_common_dir: None,+ root_repo_is_linked_worktree: false,+ },+ AnyProtoClient::new(NoopProtoClient::new()),+ path_style,+ cx,+ );+ let file: Arc<dyn language::File> = Arc::new(worktree::File {+ worktree,+ path: Arc::from(rel_path(path)),+ disk_state: language::DiskState::New,+ entry_id: None,+ is_local: false,+ is_private: false,+ });+ actual.push(+ registry+ .language_for_file(&file, None, cx)+ .and_then(|id| registry.language_name_for_id(id)),+ );+ });+ }+ assert_eq!(+ actual,+ vec![+ Some("Plain Text".into()),+ Some("SSH Config".into()),+ Some("Git Commit".into()),+ Some("Git Commit".into()),+ Some("SSH Config".into()),+ Some("SSH Config".into()),+ Some("SSH Config".into()),+ Some("SSH Config".into()),+ Some("Plain Text".into()),+ #[cfg(unix)]+ Some("INI".into()),+ #[cfg(unix)]+ Some("Plain Text".into()),+ ]+ );+}+#[gpui::test]async fn test_remote_worktree_with_git_emits_root_repo_event_when_repo_info_arrives(cx: &mut TestAppContext,