ZIm/crates/worktree/src/worktree_settings.rs
Julia Ryan f11c749353
VSCode Settings import (#29018)
Things this doesn't currently handle:

- [x] ~testing~
- ~we really need an snapshot test that takes a vscode settings file
with all options that we support, and verifies the zed settings file you
get from importing it, both from an empty starting file or one with lots
of conflicts. that way we can open said vscode settings file in vscode
to ensure that those options all still exist in the future.~
- Discussed this, we don't think this will meaningfully protect us from
future failures, and we will just do this as a manual validation step
before merging this PR. Any imports that have meaningfully complex
translation steps should still be tested.
- [x] confirmation (right now it just clobbers your settings file
silently)
- it'd be really cool if we could show a diff multibuffer of your
current settings with the result of the vscode import and let you pick
"hunks" to keep, but that's probably too much effort for this feature,
especially given that we expect most of the people using it to have an
empty/barebones zed config when they run the import.
- [x] ~UI in the "welcome" page~
- we're planning on redoing our welcome/walkthrough experience anyways,
but in the meantime it'd be nice to conditionally show a button there if
we see a user level vscode config
- we'll add it to the UI when we land the new walkthrough experience,
for now it'll be accessible through the action
- [ ] project-specific settings
- handling translation of `.vscode/settings.json` or `.code-workspace`
settings to `.zed/settings.json` will come in a future PR, along with UI
to prompt the user for those actions when opening a project with local
vscode settings for the first time
- [ ] extension settings
- we probably want to do a best-effort pass of popular extensions like
vim and git lens
- it's also possible to look for installed/enabled extensions with `code
--list-extensions`, but we'd have to maintain some sort of mapping of
those to our settings and/or extensions
- [ ] LSP settings
- these are tricky without access to the json schemas for various
language server extensions. we could probably manage to do translations
for a couple popular languages and avoid solving it in the general case.
- [ ] platform specific settings (`[macos].blah`)
  - this is blocked on #16392 which I'm hoping to address soon
- [ ] language specific settings (`[rust].foo`)
  - totally doable, just haven't gotten to it yet
 
~We may want to put this behind some kind of flag and/or not land it
until some of the above issues are addressed, given that we expect
people to only run this importer once there's an incentive to get it
right the first time. Maybe we land it alongside a keymap importer so
you don't have to go through separate imports for those?~

We are gonna land this as-is, all these unchecked items at the bottom
will be addressed in followup PRs, so maybe don't run the importer for
now if you have a large and complex VsCode settings file you'd like to
import.

Release Notes:

- Added a VSCode settings importer, available via a
`zed::ImportVsCodeSettings` action

---------

Co-authored-by: Mikayla Maki <mikayla@zed.dev>
Co-authored-by: Kirill Bulatov <kirill@zed.dev>
Co-authored-by: Mikayla Maki <mikayla.c.maki@gmail.com>
Co-authored-by: Marshall Bowers <git@maxdeviant.com>
2025-04-23 20:54:09 +00:00

128 lines
4.3 KiB
Rust

use std::path::Path;
use anyhow::Context as _;
use gpui::App;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use settings::{Settings, SettingsSources};
use util::paths::PathMatcher;
#[derive(Clone, PartialEq, Eq)]
pub struct WorktreeSettings {
pub file_scan_inclusions: PathMatcher,
pub file_scan_exclusions: PathMatcher,
pub private_files: PathMatcher,
}
impl WorktreeSettings {
pub fn is_path_private(&self, path: &Path) -> bool {
path.ancestors()
.any(|ancestor| self.private_files.is_match(ancestor))
}
pub fn is_path_excluded(&self, path: &Path) -> bool {
path.ancestors()
.any(|ancestor| self.file_scan_exclusions.is_match(&ancestor))
}
pub fn is_path_always_included(&self, path: &Path) -> bool {
path.ancestors()
.any(|ancestor| self.file_scan_inclusions.is_match(&ancestor))
}
}
#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
pub struct WorktreeSettingsContent {
/// Completely ignore files matching globs from `file_scan_exclusions`. Overrides
/// `file_scan_inclusions`.
///
/// Default: [
/// "**/.git",
/// "**/.svn",
/// "**/.hg",
/// "**/.jj",
/// "**/CVS",
/// "**/.DS_Store",
/// "**/Thumbs.db",
/// "**/.classpath",
/// "**/.settings"
/// ]
#[serde(default)]
pub file_scan_exclusions: Option<Vec<String>>,
/// Always include files that match these globs when scanning for files, even if they're
/// ignored by git. This setting is overridden by `file_scan_exclusions`.
/// Default: [
/// ".env*",
/// "docker-compose.*.yml",
/// ]
#[serde(default)]
pub file_scan_inclusions: Option<Vec<String>>,
/// Treat the files matching these globs as `.env` files.
/// Default: [ "**/.env*" ]
pub private_files: Option<Vec<String>>,
}
impl Settings for WorktreeSettings {
const KEY: Option<&'static str> = None;
type FileContent = WorktreeSettingsContent;
fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> anyhow::Result<Self> {
let result: WorktreeSettingsContent = sources.json_merge()?;
let mut file_scan_exclusions = result.file_scan_exclusions.unwrap_or_default();
let mut private_files = result.private_files.unwrap_or_default();
let mut parsed_file_scan_inclusions: Vec<String> = result
.file_scan_inclusions
.unwrap_or_default()
.iter()
.flat_map(|glob| {
Path::new(glob)
.ancestors()
.map(|a| a.to_string_lossy().into())
})
.filter(|p| p != "")
.collect();
file_scan_exclusions.sort();
private_files.sort();
parsed_file_scan_inclusions.sort();
Ok(Self {
file_scan_exclusions: path_matchers(&file_scan_exclusions, "file_scan_exclusions")?,
private_files: path_matchers(&private_files, "private_files")?,
file_scan_inclusions: path_matchers(
&parsed_file_scan_inclusions,
"file_scan_inclusions",
)?,
})
}
fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
if let Some(inclusions) = vscode
.read_value("files.watcherInclude")
.and_then(|v| v.as_array())
.and_then(|v| v.iter().map(|n| n.as_str().map(str::to_owned)).collect())
{
if let Some(old) = current.file_scan_inclusions.as_mut() {
old.extend(inclusions)
} else {
current.file_scan_inclusions = Some(inclusions)
}
}
if let Some(exclusions) = vscode
.read_value("files.watcherExclude")
.and_then(|v| v.as_array())
.and_then(|v| v.iter().map(|n| n.as_str().map(str::to_owned)).collect())
{
if let Some(old) = current.file_scan_exclusions.as_mut() {
old.extend(exclusions)
} else {
current.file_scan_exclusions = Some(exclusions)
}
}
}
}
fn path_matchers(values: &[String], context: &'static str) -> anyhow::Result<PathMatcher> {
PathMatcher::new(values).with_context(|| format!("Failed to parse globs from {}", context))
}