diff --git a/crates/ide-agent/src/lib.rs b/crates/ide-agent/src/lib.rs index a1444f952..48a9ff010 100644 --- a/crates/ide-agent/src/lib.rs +++ b/crates/ide-agent/src/lib.rs @@ -112,6 +112,8 @@ pub type WorkspaceRootsHook = Arc Vec + Send + Sync>; /// Returns the project's git executable (`None`: the default), which the tasks' git runs. pub type GitExecutableHook = Arc Option + Send + Sync>; +/// Whether the project's Git integration is on (Settings › Version Control › Git). +pub type GitEnabledHook = Arc bool + Send + Sync>; /// Returns the user's transient network retry window and cold-reopen recovery policy. pub type RecoverySettingsHook = Arc< @@ -260,6 +262,7 @@ struct Shared { reconciled: AtomicBool, workspace_roots: RwLock>, git_executable: RwLock>, + git_enabled: RwLock>, change_reads: Arc, known: Arc>>, providers: RwLock>, @@ -1011,6 +1014,7 @@ impl AgentManager { reconciled: AtomicBool::new(false), workspace_roots: RwLock::new(None), git_executable: RwLock::new(None), + git_enabled: RwLock::new(None), change_reads: Arc::new(tokio::sync::Semaphore::new(MAX_CHANGE_READS)), known, providers, @@ -1118,6 +1122,11 @@ impl AgentManager { *self.shared.git_executable.write() = Some(hook); } + /// Sets the callback that tells whether Git integration is on; off, tasks run no git. + pub fn set_git_enabled_hook(&self, hook: GitEnabledHook) { + *self.shared.git_enabled.write() = Some(hook); + } + /// Directory holding linked Git worktrees created for agent tasks of this project. pub fn worktrees_dir(&self) -> &Path { &self.shared.paths.worktrees_dir @@ -1585,6 +1594,11 @@ impl AgentManager { let project_root = Some(IpcPath(root.clone())); let (cwd, branch, base, base_commit, before) = match req.isolation { Isolation::Worktree => { + if !git_enabled(&self.shared) { + return Err(IdeError::invalid( + "worktrees need Git, which is disabled: run the task in the local checkout", + )); + } // The UI offers worktrees for git projects only; state it when it isn't one. if Repo::discover(&root)?.is_none() { return Err(IdeError::invalid( @@ -1598,10 +1612,14 @@ impl AgentManager { } Isolation::Local => { let r = root.clone(); - let (head, before) = vcs(&self.shared, move || { - Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())) - }) - .await?; + let (head, before) = if git_enabled(&self.shared) { + vcs(&self.shared, move || { + Ok((worktree::head_of(&r).ok(), worktree::snapshot(&r).unwrap_or_default())) + }) + .await? + } else { + (None, BTreeMap::new()) + }; let (base, commit) = head.unzip(); (root, None, base, commit, before) } @@ -6291,8 +6309,16 @@ async fn blocking(f: impl FnOnce() -> IdeResult + Send + ' tokio::task::spawn_blocking(f).await.map_err(|e| IdeError::internal(e.to_string()))? } +fn git_enabled(shared: &Shared) -> bool { + shared.git_enabled.read().as_ref().is_none_or(|hook| hook()) +} + /// [`blocking`] for work that runs git: the repositories it opens run the project's git. +/// Fails without running it while Git integration is off. async fn vcs(shared: &Shared, f: impl FnOnce() -> IdeResult + Send + 'static) -> IdeResult { + if !git_enabled(shared) { + return Err(IdeError::unavailable("Git integration is disabled")); + } let git = shared.git_executable.read().as_ref().and_then(|hook| hook()); blocking(move || ide_vcs::with_git_executable(git.as_deref(), f)).await } diff --git a/crates/ide-core/src/workflow_settings.rs b/crates/ide-core/src/workflow_settings.rs index 5775b9ae6..72710b526 100644 --- a/crates/ide-core/src/workflow_settings.rs +++ b/crates/ide-core/src/workflow_settings.rs @@ -143,6 +143,9 @@ impl Default for GitAnnotateSettings { #[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct GitSettings { + /// Git integration on: off, the IDE finds no repositories and runs no git at all + /// (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI. + pub enabled: bool, pub annotate: GitAnnotateSettings, /// Show blame after the current editor line. pub inline_blame: bool, @@ -201,6 +204,7 @@ pub struct GitSettings { impl Default for GitSettings { fn default() -> Self { Self { + enabled: true, annotate: GitAnnotateSettings::default(), inline_blame: false, inline_blame_clickable: true, @@ -755,6 +759,14 @@ mod tests { assert_eq!(serde_json::to_value(&on).unwrap()["fixOnCommit"], true); } + #[test] + fn git_defaults_enabled_and_can_be_disabled() { + let missing: GitSettings = serde_json::from_str("{}").unwrap(); + let off: GitSettings = serde_json::from_str(r#"{"enabled":false}"#).unwrap(); + assert!(missing.enabled); + assert!(!off.enabled); + } + #[test] fn clone_submodules_defaults_on_and_can_be_disabled() { let missing: GitSettings = serde_json::from_str("{}").unwrap(); diff --git a/crates/ide-host/src/lib.rs b/crates/ide-host/src/lib.rs index 678dfaab9..cd87e8e7b 100644 --- a/crates/ide-host/src/lib.rs +++ b/crates/ide-host/src/lib.rs @@ -791,6 +791,25 @@ impl Host { let exe = self.global_settings.read_effective(|s| s.vcs.git.executable.trim().to_owned()); ide_vcs::set_default_git_executable((!exe.is_empty()).then(|| Path::new(&exe))); } + + /// Settings › Version Control › Git › Enable Git integration, as it applies to `window` + /// (its project's effective value, the global one without a project). + pub fn git_enabled(&self, window: &str) -> bool { + match self.project(window) { + Ok(project) => project.git_enabled(), + Err(_) => self.global_settings.read_effective(|s| s.vcs.git.enabled), + } + } + + /// Fails while Git integration is switched off for `window`: commands that start git + /// outside the project's repositories (clone, init, an external log) check it first. + pub fn ensure_git_enabled(&self, window: &str) -> IdeResult<()> { + if self.git_enabled(window) { + Ok(()) + } else { + Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git")) + } + } } #[cfg(test)] diff --git a/crates/ide-host/src/mcp/vcs.rs b/crates/ide-host/src/mcp/vcs.rs index 8d20b8ce7..74551b4fc 100644 --- a/crates/ide-host/src/mcp/vcs.rs +++ b/crates/ide-host/src/mcp/vcs.rs @@ -251,6 +251,7 @@ fn git_status() -> Tool { Returns porcelain-style index/worktree status codes and summary counters. By default all Git repositories are returned.", |call| async move { + call.host.ensure_git_enabled(&call.window)?; let include_untracked = call.flag("includeUntracked", true)?; let include_ignored = call.flag("includeIgnored", false)?; let page = Page::of(&call, STATUS_DEFAULT_LIMIT)?; @@ -360,6 +361,7 @@ By default all Git repositories are returned.", fn git_diff() -> Tool { Tool::new("git_diff", "Read a Git diff for a file or the working tree. staged=true compares the index with HEAD; otherwise compares disk with the index. Unsaved editor text is not part of this diff.", |call| async move { + call.host.ensure_git_enabled(&call.window)?; let wanted = call.opt_str("repositoryPathRelativeToProject")?; let path = wanted.as_deref().map(|p| call.resolve_inside(p)).transpose()?.unwrap_or_else(|| call.root().to_path_buf()); let root = find_git_root(call.root(), &path).ok_or_else(|| IdeError::not_found("No git repository found"))?; diff --git a/crates/ide-host/src/menu.rs b/crates/ide-host/src/menu.rs index 2d731e1b0..6d7e0fd7e 100644 --- a/crates/ide-host/src/menu.rs +++ b/crates/ide-host/src/menu.rs @@ -947,12 +947,27 @@ pub fn route(spec: &[Entry], id: &str) -> Option { /// `entries` without the action `id` (and a separator it leaves doubled or trailing). pub fn without_action(entries: Vec, id: &str) -> Vec { + without(entries, &|e| e == id) +} + +/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists. +pub fn without_hidden(entries: Vec, config: &MenuConfig) -> Vec { + if config.hidden.is_empty() { + return entries; + } + without(entries, &|id| config.hidden.iter().any(|h| h == id)) +} + +/// `entries` without the actions and submenus whose id `drop` matches, and the separators +/// left dangling. +fn without(entries: Vec, drop: &dyn Fn(&str) -> bool) -> Vec { let mut out: Vec = Vec::with_capacity(entries.len()); for e in entries { match e { - Entry::Action { id: a, .. } if a == id => {} + Entry::Action { id: a, .. } if drop(a) => {} + Entry::Submenu { id: sid, .. } if drop(sid) => {} Entry::Submenu { id: sid, label, children } => { - out.push(Entry::Submenu { id: sid, label, children: without_action(children, id) }) + out.push(Entry::Submenu { id: sid, label, children: without(children, drop) }) } Entry::Separator if matches!(out.last(), None | Some(Entry::Separator)) => {} e => out.push(e), @@ -996,6 +1011,9 @@ pub struct MenuConfig { /// Ids of the toggle actions currently on. #[serde(default)] pub checked: Vec, + /// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off). + #[serde(default)] + pub hidden: Vec, } /// An item of a frontend-listed menu slot. diff --git a/crates/ide-host/src/ops/github.rs b/crates/ide-host/src/ops/github.rs index 5f2a1f9a7..72986b9a5 100644 --- a/crates/ide-host/src/ops/github.rs +++ b/crates/ide-host/src/ops/github.rs @@ -18,6 +18,9 @@ use std::path::{Path, PathBuf}; /// primary repository (a folder holding several repositories is not one itself). fn root(host: &Host, window: &str, repo: Option) -> IdeResult { let project = host.project(window)?; + if !project.git_enabled() { + return Err(IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git")); + } let repos = project.repos(); match repo { Some(at) => match repos.at_root(&at) { @@ -220,6 +223,7 @@ mod tests { use crate::rpc::Dispatcher; use crate::{Host, HostConfig}; use ide_core::error::ErrorKind; + use ide_workspace::SettingsScope; use std::path::Path; use std::sync::Arc; @@ -272,4 +276,17 @@ mod tests { let outsider = root(&host, "main", Some(dir.path().join("other"))).unwrap_err(); assert_eq!(outsider.kind, ErrorKind::Unavailable); } + + #[tokio::test] + async fn refuses_gh_while_git_integration_is_off() { + let dir = tempfile::tempdir().unwrap(); + let host = test_host(dir.path()); + let proj_dir = dir.path().join("repo"); + std::fs::create_dir_all(&proj_dir).unwrap(); + host.global_settings.set(SettingsScope::Global, "vcs.git.enabled", serde_json::json!(false)).unwrap(); + host.open_project("main", &proj_dir).unwrap(); + let err = root(&host, "main", None).unwrap_err(); + assert_eq!(err.kind, ErrorKind::Unavailable); + assert!(err.message.contains("Git integration is disabled"), "{}", err.message); + } } diff --git a/crates/ide-host/src/ops/project.rs b/crates/ide-host/src/ops/project.rs index 59a67494d..e513293e3 100644 --- a/crates/ide-host/src/ops/project.rs +++ b/crates/ide-host/src/ops/project.rs @@ -437,8 +437,13 @@ pub fn set_settings( } }); } - // Directory Mappings change which repositories the project has. - if key == "vcs" || key == "vcs.mappings" || key.starts_with("vcs.mappings.") { + // Directory Mappings and Enable Git integration change which repositories the project has. + if key == "vcs" + || key == "vcs.mappings" + || key.starts_with("vcs.mappings.") + || key == "vcs.git" + || key == "vcs.git.enabled" + { let affected = affected(); host.runtime.spawn_blocking(move || { for project in affected { diff --git a/crates/ide-host/src/ops/vcs/commands.rs b/crates/ide-host/src/ops/vcs/commands.rs index 5d4bdd9ff..fd3fa065c 100644 --- a/crates/ide-host/src/ops/vcs/commands.rs +++ b/crates/ide-host/src/ops/vcs/commands.rs @@ -911,6 +911,7 @@ pub async fn vcs_log_users(host: &Host, window: &str, repo: Option) -> #[command(trust = always)] pub async fn vcs_open_external_log(host: &Host, window: &str, path: PathBuf) -> IdeResult { + host.ensure_git_enabled(window)?; let path = dunce::canonicalize(path)?; let repo = Repo::discover(&path)?.ok_or_else(|| ide_core::IdeError::unavailable("folder is not a Git worktree"))?; let root = repo.root().to_path_buf(); @@ -2002,6 +2003,9 @@ pub async fn vcs_clone( on_output: Channel, ) -> IdeResult<()> { let settings = host.global_settings.effective(); + if !settings.vcs.git.enabled { + return Err(ide_core::IdeError::unavailable("Git integration is disabled in Settings › Version Control › Git")); + } let recurse_submodules = settings.vcs.git.clone_submodules; let cancel = host.begin_request(request); let result = tokio::task::spawn_blocking(move || { @@ -2020,6 +2024,7 @@ pub async fn vcs_clone( /// detected again before it returns, so the new one is known to the next command. #[command(trust = always)] pub async fn vcs_init(host: &Host, window: &str, dir: PathBuf) -> IdeResult<()> { + host.ensure_git_enabled(window)?; let project = host.project(window).ok(); let git = project.as_ref().and_then(|p| p.git_executable()); blocking(move || { diff --git a/crates/ide-host/src/plugins/api.rs b/crates/ide-host/src/plugins/api.rs index 29c7b3dde..804ef1c85 100644 --- a/crates/ide-host/src/plugins/api.rs +++ b/crates/ide-host/src/plugins/api.rs @@ -155,6 +155,11 @@ pub trait PluginWorkspace: Send + Sync { fn git_executable(&self, _root: &Path) -> Option { None } + /// Settings › Version Control › Git › Enable Git integration of the project at `root`: + /// off, plugins find no repository there. + fn git_enabled(&self, _root: &Path) -> bool { + true + } /// Root of the project open in `window`. fn project_of(&self, window: &str) -> Option; /// Windows showing the open project at `root`, the most recently focused first. @@ -1584,6 +1589,9 @@ pub(super) fn commit_draft( if cancel.is_cancelled() { return Err(HostError::Cancelled); } + if !workspace.git_enabled(&repo.root.0) { + return Err(HostError::Failed("Git integration is disabled".into())); + } let Some(r) = ide_vcs::Repo::discover(&repo.root.0).map_err(failed)? else { return Err(HostError::NotFound(format!("{} is not in a git repository", repo.root.0.display()))); }; @@ -2633,6 +2641,9 @@ impl HostApi for PluginApi { } fn vcs_remotes(&self, root: &Path) -> Result, HostError> { + if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) { + return Ok(Vec::new()); + } let Some(repo) = ide_vcs::Repo::discover(root).map_err(failed)? else { return Ok(Vec::new()) }; plugin_remotes(&repo) } @@ -4053,6 +4064,13 @@ impl PluginWorkspace for HostWorkspace { HostWorkspace::project_covering(self, root)?.git_executable() } + fn git_enabled(&self, root: &Path) -> bool { + match HostWorkspace::project_covering(self, root) { + Some(project) => project.git_enabled(), + None => self.0.upgrade().is_none_or(|host| host.global_settings.read_effective(|s| s.vcs.git.enabled)), + } + } + fn project_of(&self, window: &str) -> Option { self.0.upgrade()?.project(window).ok().map(|p| p.root.clone()) } @@ -5144,6 +5162,9 @@ impl PluginApi { /// Status needs it there: a restricted repository is read without its config, so it knows /// no upstream. The other reads use [`Self::read_repo`] and never execute. fn repo(&self, root: &Path) -> Result, HostError> { + if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) { + return Ok(None); + } let repo = ide_vcs::Repo::discover(root).map_err(failed)?; if let Some(repo) = &repo && let Some(workspace) = self.shared.workspace() @@ -5158,6 +5179,9 @@ impl PluginApi { if !self.shared.workspace().is_some_and(|w| w.trusted(root)) { return Err(HostError::Failed("the project is in Restricted Mode: git does not run there".into())); } + if self.shared.workspace().is_some_and(|w| !w.git_enabled(root)) { + return Ok(None); + } let repo = ide_vcs::Repo::discover(root).map_err(failed)?; if let Some(repo) = &repo { repo.set_execution_allowed(false); diff --git a/crates/ide-host/src/project.rs b/crates/ide-host/src/project.rs index f08753e21..31e7478b2 100644 --- a/crates/ide-host/src/project.rs +++ b/crates/ide-host/src/project.rs @@ -765,6 +765,8 @@ impl Host { { let weak = Arc::downgrade(&project); project.agents.set_git_executable_hook(Arc::new(move || weak.upgrade()?.git_executable())); + let weak = Arc::downgrade(&project); + project.agents.set_git_enabled_hook(Arc::new(move || weak.upgrade().is_some_and(|p| p.git_enabled()))); } self.insert_project(window, project.clone()); for (key, text, dirty) in &carried { @@ -1134,6 +1136,10 @@ fn scan_repositories( /// The project-open scan and the watcher's rescan share these skip rules. fn discover_repositories(root: &Path, settings: &SettingsStore, build_cache: &Path, trusted: bool) -> IdeResult { let settings = settings.effective(); + // Git integration off: the project has no repositories, so nothing runs git for it. + if !settings.vcs.git.enabled { + return Ok(Repos::default()); + } let found = detect_repositories(root, &settings, build_cache, trusted)?; let mappings = &settings.vcs.mappings; if mappings.is_empty() { @@ -1182,6 +1188,11 @@ impl Project { ); } + /// Settings › Version Control › Git › Enable Git integration (effective value). + pub fn git_enabled(&self) -> bool { + self.settings.read_effective(|s| s.vcs.git.enabled) + } + /// Settings › Version Control › Git › Path to Git executable, this project's value (its own /// layer over the global one); `None` when it is empty or the project is not trusted. /// Every git started for the project runs it: the project's repositories carry it, and work diff --git a/src-tauri/src/commands/window.rs b/src-tauri/src/commands/window.rs index 2ef523eff..8b9a25142 100644 --- a/src-tauri/src/commands/window.rs +++ b/src-tauri/src/commands/window.rs @@ -499,6 +499,7 @@ pub fn menu_model(app: AppHandle, state: State<'_, AppState>, menu_state: State< } let home = dirs::home_dir(); let config = menu_state.config.lock().clone(); + let spec = menu::without_hidden(spec, &config); let remote = menu_state.remote_recent.lock().clone(); menu::model(&spec, &menu::recent_items(&state.recent.list(), &remote, home.as_deref()), &config) } diff --git a/src-tauri/src/menu.rs b/src-tauri/src/menu.rs index 3ee19725d..7eb8ea8ba 100644 --- a/src-tauri/src/menu.rs +++ b/src-tauri/src/menu.rs @@ -309,7 +309,7 @@ pub fn build( recent: &[RecentItem], disabled: &HashSet, ) -> tauri::Result> { - build_rendered(app, &render_bar(&prepared_spec(app, os), config, recent), disabled) + build_rendered(app, &render_bar(&without_hidden(prepared_spec(app, os), config), config, recent), disabled) } fn build_rendered( @@ -597,7 +597,7 @@ pub fn install(app: &AppHandle, menu_state: &MenuState, recent: & let items = recent_items(recent, &menu_state.remote_recent.lock(), home.as_deref()); let config = menu_state.config.lock().clone(); let disabled = menu_state.disabled.lock().clone(); - let rendered = render_bar(&prepared_spec(app, Os::current()), &config, &items); + let rendered = render_bar(&without_hidden(prepared_spec(app, Os::current()), &config), &config, &items); let mut slot = menu_state.rendered.lock(); if slot.as_ref() == Some(&rendered) { return; @@ -999,6 +999,21 @@ mod tests { } } + #[test] + fn hidden_submenus_and_actions_leave_the_menu() { + let config = MenuConfig { hidden: vec!["git".into(), "vcs.cloneProject".into()], ..MenuConfig::default() }; + for os in ALL_OS { + let all = spec(os); + assert!(all.iter().any(|e| matches!(e, Entry::Submenu { id: "git", .. }))); + let spec = without_hidden(all, &config); + assert!(!spec.iter().any(|e| matches!(e, Entry::Submenu { id: "git", .. }))); + let ids = action_ids(&spec); + assert!(!ids.contains(&"vcs.commit") && !ids.contains(&"vcs.cloneProject")); + assert!(ids.contains(&"file.openProject")); + } + assert_eq!(action_ids(&without_hidden(spec(Os::Linux), &MenuConfig::default())), action_ids(&spec(Os::Linux))); + } + #[test] fn action_ids_are_unique_per_menu_bar() { for os in ALL_OS { diff --git a/src/bindings.ts b/src/bindings.ts index 52bb92408..0d9cc4592 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -8305,6 +8305,11 @@ export type GitOperation_Serialize = export type GitSaveChangesPolicy = "shelve" | "stash"; export type GitSettings = { + /** + * Git integration on: off, the IDE finds no repositories and runs no git at all + * (no status, log, blame, fetch, clone or agent worktrees), and hides its Git UI. + */ + enabled?: boolean, annotate?: GitAnnotateSettings, /** Show blame after the current editor line. */ inlineBlame?: boolean, @@ -10981,6 +10986,8 @@ export type MenuConfig = { dynamic?: { [key in string]: DynamicItem[] }, /** Ids of the toggle actions currently on. */ checked?: string[], + /** Ids of submenus and actions left out of the menu (the Git menu while Git integration is off). */ + hidden?: string[], }; /** diff --git a/src/features/agents/HomeEditor.tsx b/src/features/agents/HomeEditor.tsx index 44f20ca2d..871a7a1ef 100644 --- a/src/features/agents/HomeEditor.tsx +++ b/src/features/agents/HomeEditor.tsx @@ -34,6 +34,7 @@ import { useAgentCommands, useAgents, } from "./store"; +import { useGitEnabled } from "@/platform/gitEnabled"; import { useAgentSettings } from "./agentSettings"; import styles from "./Home.module.css"; @@ -154,7 +155,8 @@ export function HomeEditor({ docked = false, input }: { docked?: boolean; input? const agentCommands = useAgentCommands(provider?.id, null, provider?.commands ?? NO_COMMANDS); const providerOptions: SelectOption[] = agentOptions(providers, tx, providerIcon); // Without git under the project there are no worktrees: force the local checkout. - const isGit = project?.workspace ? repoState?.root === root && repoState.isGit : (project?.isGit ?? false); + const gitOn = useGitEnabled(); + const isGit = gitOn && (project?.workspace ? repoState?.root === root && repoState.isGit : (project?.isGit ?? false)); const isolation = isGit ? draft.isolation : "local"; const base = draft.base ?? current; const canStart = diff --git a/src/features/app/menuBridge.ts b/src/features/app/menuBridge.ts index 9a20c60f9..fde18f2d4 100644 --- a/src/features/app/menuBridge.ts +++ b/src/features/app/menuBridge.ts @@ -20,6 +20,7 @@ import { useKeymap, } from "@/platform/keymap"; import { useProject } from "@/platform/project"; +import { hiddenMenuEntries, onWorkflowSettingsChange } from "@/platform/workflowSettings"; import { syncRemoteRecentMenu } from "@/platform/remote"; import { useContributions, useMenuSlotItems, useStandaloneEditor } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; @@ -126,6 +127,7 @@ export function buildMenuConfig(os: HostOs): MenuConfig { accelerators, dynamic: dynamicMenuItems(), checked: toggledActions(), + hidden: hiddenMenuEntries(), }; } @@ -304,6 +306,8 @@ export function installMenuBridge(): () => void { // View › Appearance check marks and Status Bar Widgets. if (s.settings?.appearance !== prev.settings?.appearance) push(); }), + // Settings › Git › Enable Git integration shows or hides the Git menu. + onWorkflowSettingsChange((w) => w.vcs.git.enabled, push), ]; return () => { disposed = true; diff --git a/src/features/github/index.ts b/src/features/github/index.ts index 398c3a114..648cbfcbf 100644 --- a/src/features/github/index.ts +++ b/src/features/github/index.ts @@ -11,6 +11,7 @@ import "./ui/palette.css"; import { registerActions, type Action } from "@/platform/actions"; import { setContext } from "@/platform/context"; +import { whileGitEnabled } from "@/platform/gitEnabled"; import { lazyComponent } from "@/ui"; import { githubCloneSource } from "./clone/source"; import { @@ -325,30 +326,6 @@ export function activate(): () => void { setContext("githubPrTab", "list"); const disposers = [ activateSettingsPages(), - registerCloneSource(githubCloneSource), - registerGitLogChecks(lazyComponent(() => import("./LogCommitChecks").then((m) => m.LogCommitChecks))), - registerToolWindow({ - id: WINDOW, - title: "Pull Requests", - icon: "toolwindow-pull-requests", - anchor: "left", - order: 2, - stripe: "onUse", - component: lazyView("PullRequestsToolWindow"), - headerContent: lazyView("PullRequestsTabs"), - headerActions: lazyView("PullRequestsHeaderActions"), - headerMenu: useHeaderMenu, - }), - registerToolWindow({ - id: ACTIONS_WINDOW, - title: "GitHub Actions", - icon: "github", - anchor: "bottom", - stripe: "onUse", - component: lazyComponent<{ id: string }>(() => - import("./actions/ActionsToolWindow").then((m) => m.ActionsToolWindow), - ), - }), registerEditorKind({ kind: TIMELINE_KIND, component: lazyComponent(() => import("./timeline/TimelineEditor").then((m) => m.TimelineEditor)), @@ -357,7 +334,37 @@ export function activate(): () => void { icon: (input) => runtime?.timeline.icon(input) ?? "github-timeline", }), registerOverlay({ id: "github.dialogs", component: GithubDialogHost }), - registerActions(actions().map((a) => ({ ...a, run: a.run ?? (async (c) => (await load()).runs[a.id]!(c)) }))), + // Pull requests, GitHub clone and actions need Git (Settings › Git › Enable Git integration). + whileGitEnabled(() => { + const git = [ + registerCloneSource(githubCloneSource), + registerGitLogChecks(lazyComponent(() => import("./LogCommitChecks").then((m) => m.LogCommitChecks))), + registerToolWindow({ + id: WINDOW, + title: "Pull Requests", + icon: "toolwindow-pull-requests", + anchor: "left", + order: 2, + stripe: "onUse", + component: lazyView("PullRequestsToolWindow"), + headerContent: lazyView("PullRequestsTabs"), + headerActions: lazyView("PullRequestsHeaderActions"), + headerMenu: useHeaderMenu, + }), + registerToolWindow({ + id: ACTIONS_WINDOW, + title: "GitHub Actions", + icon: "github", + anchor: "bottom", + stripe: "onUse", + component: lazyComponent<{ id: string }>(() => + import("./actions/ActionsToolWindow").then((m) => m.ActionsToolWindow), + ), + }), + registerActions(actions().map((a) => ({ ...a, run: a.run ?? (async (c) => (await load()).runs[a.id]!(c)) }))), + ]; + return () => git.reverse().forEach((d) => d()); + }), ]; // Review mode follows the current branch: start once the window is up. const idle = typeof requestIdleCallback === "function" ? requestIdleCallback : (f: () => void) => setTimeout(f, 200); diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts index 455f0b616..bbbd5b9c9 100644 --- a/src/features/project-tree/contextMenu.ts +++ b/src/features/project-tree/contextMenu.ts @@ -43,6 +43,7 @@ import { canDownload } from "./download"; import { isSameOrInside } from "./paths"; import { useProjectTree } from "./store"; import { tx, txPart } from "@/platform/i18n"; +import { gitEnabled } from "@/platform/gitEnabled"; /** Keys handled by the project view itself (the default keymap has no entries for them). */ export const LOCAL_KEYS: Record = { @@ -367,7 +368,7 @@ export function contextMenuItems(nodes: ProjectNode[], at: MenuPoint = "center") ); // Git › (`vcsAvailable` also covers repositories nested below a non-Git project root) - if (inWorkspace && (project?.isGit || getContext().vcsAvailable === true)) { + if (inWorkspace && gitEnabled() && (project?.isGit || getContext().vcsAvailable === true)) { const dirs = nodes.map((n) => n.dir); push( submenu( diff --git a/src/features/settings/__tests__/masterToggle.test.tsx b/src/features/settings/__tests__/masterToggle.test.tsx new file mode 100644 index 000000000..702af4422 --- /dev/null +++ b/src/features/settings/__tests__/masterToggle.test.tsx @@ -0,0 +1,76 @@ +import { cleanup, fireEvent, render, screen } from "@testing-library/react"; +import { afterEach, describe, expect, it } from "vitest"; +import { useProject } from "@/platform/project"; +import { PageContext } from "../components/context"; +import { DEFAULT_SETTINGS } from "../model/schema"; +import { openSettings } from "../model/staging"; +import { OptionsPage } from "../pages/OptionsPage"; +import { pageLabels } from "../pages/registry"; +import type { PageSpec } from "../pages/spec"; +import { VCS_PAGES } from "../pages/vcs"; + +afterEach(cleanup); + +const PAGE: PageSpec = { + id: "test.masterToggle", + title: "Master toggle", + order: 0, + master: { key: "vcs.git.enabled", label: "Enable Git integration", scope: "global" }, + sections: [ + { options: [{ kind: "text", key: "editor.fontFamily", label: "Family" }] }, + { + title: "More", + options: [ + { kind: "toggle", key: "editor.insertSpaces", label: "Spaces" }, + { kind: "number", key: "editor.tabSize", label: "Tab size", min: 1, max: 16 }, + ], + }, + ], +}; + +function renderPage(enabled: boolean) { + const settings = { ...structuredClone(DEFAULT_SETTINGS), vcs: { git: { enabled } } } as typeof DEFAULT_SETTINGS; + useProject.setState({ settings, project: null }); + openSettings(PAGE.id); + render( + + + , + ); +} + +const gated = () => [ + screen.getByRole("textbox", { name: "Family" }), + screen.getByRole("checkbox", { name: "Spaces" }), + screen.getByRole("textbox", { name: "Tab size" }), +]; + +describe("a page's master checkbox", () => { + it("disables every option below it while it is unchecked, and enables them once it is checked", () => { + renderPage(false); + const master = screen.getByRole("checkbox", { name: "Enable Git integration" }); + expect(master).toBeEnabled(); + expect(master).not.toBeChecked(); + for (const control of gated()) { + expect(control).toBeDisabled(); + expect(control.closest("[inert]")).not.toBeNull(); + } + fireEvent.click(master); + for (const control of gated()) { + expect(control).toBeEnabled(); + expect(control.closest("[inert]")).toBeNull(); + } + }); + + it("leaves the options enabled while it is checked", () => { + renderPage(true); + expect(screen.getByRole("checkbox", { name: "Enable Git integration" })).toBeChecked(); + for (const control of gated()) expect(control).toBeEnabled(); + }); + + it("switches the Git page and is found by search", () => { + const git = VCS_PAGES.find((p) => p.id === "vcs.git")!; + expect(git.master).toMatchObject({ key: "vcs.git.enabled", label: "Enable Git integration", scope: "global" }); + expect(pageLabels(git.id)).toContain("Enable Git integration"); + }); +}); diff --git a/src/features/settings/pages/OptionsPage.tsx b/src/features/settings/pages/OptionsPage.tsx index 9e67b865a..56665ac9b 100644 --- a/src/features/settings/pages/OptionsPage.tsx +++ b/src/features/settings/pages/OptionsPage.tsx @@ -1,6 +1,15 @@ -import { FormGroup, Section, SettingNumber, SettingSelect, SettingText, SettingToggle } from "../components/Form"; +import type { ReactNode } from "react"; +import { + FormGroup, + Section, + SettingNumber, + SettingSelect, + SettingText, + SettingToggle, + Toggle, +} from "../components/Form"; import { useSetting } from "../components/context"; -import type { OptionSpec, PageSpec } from "./spec"; +import type { MasterToggleSpec, OptionSpec, PageSpec } from "./spec"; import styles from "./Pages.module.css"; const optionKey = (o: OptionSpec) => ("key" in o ? o.key : o.label); @@ -54,8 +63,8 @@ function ToggleOption({ o, disabled }: { o: Extract + const body = ( + <> {spec.sections?.map((section, i) => (
{section.options.map((o) => ( @@ -64,6 +73,25 @@ export function OptionsPage({ spec }: { spec: PageSpec }) {
))} {Footer &&