feat(vcs): add a global Enable Git integration switch (#6704)

Settings > Version Control > Git gets an Enable Git integration master toggle (global, on by default). While it is off the IDE discovers no repositories and runs no git: status, log, blame, fetch, clone, GitHub, the MCP git tools, plugin repository access and agent worktrees refuse to run, and the Git menu, Get from Version Control, the Git, Commit and GitHub Actions tool windows, Git actions and the branch widget are hidden. Turning it back on restores them without reopening the project. Settings pages gain a reusable master toggle that disables the page's sections, and MenuConfig gains a hidden list applied to the native and in-app menus.

Co-authored-by: bertyhell <[email protected]>
Цей коміт міститься в:
Bert Verhelstтаbertyhell authored and GitHub committed 2026-11-29 15:45:38 +08:00
1 джерело 68e3adde99
коміт d897236bd7
30 files changed
+505 -92

No files matched your search

+30 -4
Переглянути файл
@@ -112,6 +112,8 @@ pub type WorkspaceRootsHook = Arc<dyn Fn() -> Vec<PathBuf> + Send + Sync>;
/// Returns the project's git executable (`None`: the default), which the tasks' git runs.
pub type GitExecutableHook = Arc<dyn Fn() -> Option<PathBuf> + Send + Sync>;
/// Whether the project's Git integration is on (Settings › Version Control › Git).
pub type GitEnabledHook = Arc<dyn Fn() -> 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<Option<WorkspaceRootsHook>>,
git_executable: RwLock<Option<GitExecutableHook>>,
git_enabled: RwLock<Option<GitEnabledHook>>,
change_reads: Arc<tokio::sync::Semaphore>,
known: Arc<Mutex<HashMap<String, Known>>>,
providers: RwLock<Vec<provider::ProviderSpec>>,
@@ -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<T: Send + 'static>(f: impl FnOnce() -> IdeResult<T> + 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<T: Send + 'static>(shared: &Shared, f: impl FnOnce() -> IdeResult<T> + Send + 'static) -> IdeResult<T> {
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
}
+12
Переглянути файл
@@ -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();
+19
Переглянути файл
@@ -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)]
+2
Переглянути файл
@@ -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"))?;
+20 -2
Переглянути файл
@@ -947,12 +947,27 @@ pub fn route(spec: &[Entry], id: &str) -> Option<MenuRoute> {
/// `entries` without the action `id` (and a separator it leaves doubled or trailing).
pub fn without_action(entries: Vec<Entry>, id: &str) -> Vec<Entry> {
without(entries, &|e| e == id)
}
/// `entries` without the submenus and actions [`MenuConfig::hidden`] lists.
pub fn without_hidden(entries: Vec<Entry>, config: &MenuConfig) -> Vec<Entry> {
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<Entry>, drop: &dyn Fn(&str) -> bool) -> Vec<Entry> {
let mut out: Vec<Entry> = 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<String>,
/// Ids of submenus and actions left out of the menu (the Git menu while Git integration is off).
#[serde(default)]
pub hidden: Vec<String>,
}
/// An item of a frontend-listed menu slot.
+17
Переглянути файл
@@ -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<PathBuf>) -> IdeResult<PathBuf> {
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);
}
}
+7 -2
Переглянути файл
@@ -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 {
+5
Переглянути файл
@@ -911,6 +911,7 @@ pub async fn vcs_log_users(host: &Host, window: &str, repo: Option<PathBuf>) ->
#[command(trust = always)]
pub async fn vcs_open_external_log(host: &Host, window: &str, path: PathBuf) -> IdeResult<ide_core::IpcPath> {
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<String>,
) -> 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 || {
+24
Переглянути файл
@@ -155,6 +155,11 @@ pub trait PluginWorkspace: Send + Sync {
fn git_executable(&self, _root: &Path) -> Option<PathBuf> {
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<PathBuf>;
/// 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<Vec<(String, String)>, 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<PathBuf> {
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<Option<ide_vcs::Repo>, 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);
+11
Переглянути файл
@@ -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<Repos> {
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
+1
Переглянути файл
@@ -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)
}
+17 -2
Переглянути файл
@@ -309,7 +309,7 @@ pub fn build<R: Runtime>(
recent: &[RecentItem],
disabled: &HashSet<String>,
) -> tauri::Result<Menu<R>> {
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<R: Runtime>(
@@ -597,7 +597,7 @@ pub fn install<R: Runtime>(app: &AppHandle<R>, 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 {
+7
Переглянути файл
@@ -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[],
};
/**
+3 -1
Переглянути файл
@@ -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 =
+4
Переглянути файл
@@ -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;
+32 -25
Переглянути файл
@@ -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);
+2 -1
Переглянути файл
@@ -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<string, string> = {
@@ -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(
+76
Переглянути файл
@@ -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(
<PageContext.Provider value={{ pageId: PAGE.id, scope: "project" }}>
<OptionsPage spec={PAGE} />
</PageContext.Provider>,
);
}
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");
});
});
+33 -5
Переглянути файл
@@ -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<OptionSpec, { kind: "toggle"
/** Renders a declarative page spec. */
export function OptionsPage({ spec }: { spec: PageSpec }) {
const Footer = spec.footer;
return (
<div className={styles.options}>
const body = (
<>
{spec.sections?.map((section, i) => (
<Section key={section.title ?? i} title={section.title}>
{section.options.map((o) => (
@@ -64,6 +73,25 @@ export function OptionsPage({ spec }: { spec: PageSpec }) {
</Section>
))}
{Footer && <Footer />}
</div>
</>
);
return (
<div className={styles.options}>{spec.master ? <MasterGate master={spec.master}>{body}</MasterGate> : body}</div>
);
}
/** The page's master checkbox; while it is unchecked the rest of the page is dimmed and inert. */
function MasterGate({ master, children }: { master: MasterToggleSpec; children: ReactNode }) {
const [on, set] = useSetting<boolean>(master.key, master.scope);
const off = !on;
return (
<>
<Section>
<Toggle label={master.label} checked={!!on} onChange={set} hint={master.hint} />
</Section>
<fieldset disabled={off} inert={off} aria-disabled={off} className={off ? styles.gatedOff : styles.gated}>
{children}
</fieldset>
</>
);
}
+15
Переглянути файл
@@ -4,6 +4,21 @@
max-width: 680px;
}
/* The sections below a page's master checkbox (Settings › Git › Enable Git integration). */
.gated,
.gatedOff {
display: flex;
flex-direction: column;
min-width: 0;
margin: 0;
padding: 0;
border: 0;
}
.gatedOff {
opacity: 0.5;
}
.durationAmount {
width: 12ch;
font-variant-numeric: tabular-nums;
+13
Переглянути файл
@@ -5,6 +5,7 @@
*/
import type { ComponentType, ReactNode } from "react";
import type { SelectOption } from "@/ui";
import type { Scope } from "../model/staging";
export type OptionSpec =
| {
@@ -36,6 +37,15 @@ export interface SectionSpec {
options: OptionSpec[];
}
/** A checkbox above every section that switches the whole page on (Settings › Git › Enable Git integration). */
export interface MasterToggleSpec {
key: string;
label: string;
hint?: ReactNode;
/** Bound to this scope whatever the page shows (`global`: one value for every project). */
scope?: Scope;
}
export interface PageSpec {
id: string;
title: string;
@@ -50,6 +60,8 @@ export interface PageSpec {
scopeGroup?: string;
/** The page picks its scope itself (Code Style's Scheme): no Global / This project switch. */
ownScopeSwitch?: boolean;
/** Rendered first; while it is unchecked every section and the footer are disabled. */
master?: MasterToggleSpec;
sections?: SectionSpec[];
/** Rendered below the sections (previews). */
footer?: ComponentType;
@@ -62,6 +74,7 @@ export interface PageSpec {
/** Search texts of a spec: section titles, option labels and keywords. */
export function specLabels(spec: PageSpec): string[] {
const out: string[] = [...(spec.keywords ?? [])];
if (spec.master) out.push(spec.master.label);
for (const section of spec.sections ?? []) {
if (section.title) out.push(section.title);
for (const o of flattenOptions(section.options)) {
+7 -1
Переглянути файл
@@ -950,7 +950,13 @@ export const VCS_PAGES: PageSpec[] = [
title: "Git",
order: 8,
projectScope: true,
keywords: ["git", "executable", "push", "pull", "update"],
keywords: ["git", "executable", "push", "pull", "update", "disable git"],
master: {
key: "vcs.git.enabled",
label: "Enable Git integration",
hint: "Off, the IDE runs no git: repositories are not detected, and Git actions, menus and tool windows are hidden. Applies to all projects.",
scope: "global",
},
sections: [
{
options: [
+7 -1
Переглянути файл
@@ -6,6 +6,7 @@ import { getContext } from "@/platform/context";
import { loadSettings, useProject } from "@/platform/project";
import { call, commands } from "@/platform/ipc";
import { workflowSettings } from "@/platform/workflowSettings";
import { whileGitEnabled } from "@/platform/gitEnabled";
import { activeEditor, editorsFor } from "@/editor/api";
import { Menu, type MenuItem } from "@/ui";
import {
@@ -415,6 +416,9 @@ interface TagTarget {
repo: string | null;
}
/** Actions that do not run git, registered while Git integration is off too. */
const KEPT_WITHOUT_GIT = new Set(["vcs.localHistory"]);
export function registerVcsActions(): () => void {
const actions: Action[] = [
{
@@ -1425,8 +1429,10 @@ export function registerVcsActions(): () => void {
},
];
const stopTracking = trackFileHistory();
const unregister = registerActions(actions);
const unregister = registerActions(actions.filter((a) => KEPT_WITHOUT_GIT.has(a.id)));
const unregisterGit = whileGitEnabled(() => registerActions(actions.filter((a) => !KEPT_WITHOUT_GIT.has(a.id))));
return () => {
unregisterGit();
unregister();
stopTracking();
};
+56 -45
Переглянути файл
@@ -4,6 +4,7 @@
* merge and Local History editors, remote operations.
*/
import { onWorkflowSettingsChange, workflowSettings } from "@/platform/workflowSettings";
import { installGitEnabledContext, whileGitEnabled } from "@/platform/gitEnabled";
import { useTodoSettings } from "@/platform/todo";
import { editorsFor, registerEditorContribution } from "@/editor/api";
import {
@@ -193,6 +194,58 @@ function conflictsBody(names: string[]): string {
: tx`${names.length} files have conflicts: ${list}`;
}
/** The Git tool windows, actions, menus, editor markers and background checks. */
function registerGitContributions(): () => void {
const disposers = [
installIncomingCheck(),
registerActions(openOnRemoteActions),
registerOpenOnRemote(),
registerActions(copyRepositoryPathActions),
registerActions(copyBranchNameActions),
registerCopyRepositoryPath(),
registerHistoryActions(),
registerLogPaneActions(),
trackTitleItem(),
trackMergeRebaseItem(),
installHunkPopup(),
installCloneHandoff(),
registerOverlay({ id: "vcs.branches", component: BranchesPopupHost }),
registerOverlay({ id: "vcs.syncCommits", component: SyncCommitsPopupHost }),
activateConflictBanner(),
trackCommitWindow(),
registerToolWindow({
id: "git",
title: "Git",
icon: "toolwindow-git",
anchor: "bottom",
order: 5,
component: lazyComponent(() => import("./GitLog").then((m) => m.GitToolWindow), { prefetch: true }),
headerContent: lazyComponent(() => import("./GitLog").then((m) => m.GitTabs)),
}),
registerEditorContribution({
id: "vcs.changeMarkers",
order: 60,
extensions: (ctx) => [changeMarkers(ctx), blameSlot(), inlineBlame(ctx)],
}),
registerMenuGroup({
id: "vcs.gutter",
menus: ["editorGutter"],
order: 10,
items: (_menu, { paths: [path] }) => {
if (!path || !getContext().vcsAvailable) return [];
const shown = editorsFor(path).some((h) => annotationsShown(h.view));
return [
{
label: shown ? "Close Annotations" : "Annotate with Git Blame",
run: () => void executeAction("vcs.annotate", path),
},
];
},
}),
];
return () => disposers.reverse().forEach((d) => d());
}
/** Once per repository and session, names the LFS files still checked out as pointer files. */
function installLfsNotice(): () => void {
// A repository counts as checked once it answered; a failed check runs again on the next update.
@@ -293,6 +346,7 @@ export function activate(): () => void {
useCommit.setState({ signOff: workflowSettings().vcs.git.signOff });
const disposers = [
installGitEnabledContext(),
installVcsStore(),
installLfsNotice(),
installSubmoduleNotice(),
@@ -324,7 +378,6 @@ export function activate(): () => void {
.selection.filter((p) => !deleted.has(p))
.map(stripSlash);
}),
installIncomingCheck(),
installFileConfirmations(),
installDiffEditorHost(),
// Settings › Git › Sign-off commit: the default of Commit Options › Sign-off Commit.
@@ -333,39 +386,15 @@ export function activate(): () => void {
(signOff) => useCommit.setState({ signOff }),
),
registerVcsActions(),
registerActions(openOnRemoteActions),
registerOpenOnRemote(),
registerActions(copyRepositoryPathActions),
registerActions(copyBranchNameActions),
registerCopyRepositoryPath(),
registerHistoryActions(),
registerLogPaneActions(),
activateSettingsPages(),
registerLocalHistoryActions(),
installChangelists(),
trackOperationContext(),
registerCompareActions(),
registerMergeActions(),
trackTitleItem(),
trackMergeRebaseItem(),
installHunkPopup(),
registerOverlay({ id: "vcs.dialogs", component: VcsDialogHost }),
installCloneHandoff(),
registerOverlay({ id: "vcs.branches", component: BranchesPopupHost }),
registerOverlay({ id: "vcs.syncCommits", component: SyncCommitsPopupHost }),
activateConflictBanner(),
registerWorktreeIncludeEditor(),
activateConflictMarkers(),
trackCommitWindow(),
registerToolWindow({
id: "git",
title: "Git",
icon: "toolwindow-git",
anchor: "bottom",
order: 5,
component: lazyComponent(() => import("./GitLog").then((m) => m.GitToolWindow), { prefetch: true }),
headerContent: lazyComponent(() => import("./GitLog").then((m) => m.GitTabs)),
}),
registerEditorKind({
kind: "git-revision",
standalone: true,
@@ -433,26 +462,8 @@ export function activate(): () => void {
},
icon: () => "history",
}),
registerEditorContribution({
id: "vcs.changeMarkers",
order: 60,
extensions: (ctx) => [changeMarkers(ctx), blameSlot(), inlineBlame(ctx)],
}),
registerMenuGroup({
id: "vcs.gutter",
menus: ["editorGutter"],
order: 10,
items: (_menu, { paths: [path] }) => {
if (!path || !getContext().vcsAvailable) return [];
const shown = editorsFor(path).some((h) => annotationsShown(h.view));
return [
{
label: shown ? "Close Annotations" : "Annotate with Git Blame",
run: () => void executeAction("vcs.annotate", path),
},
];
},
}),
// Everything that shows or runs Git: registered only while Settings › Git › Enable Git integration is on.
whileGitEnabled(registerGitContributions),
];
return () => {
onConflictsChanged(() => undefined);
+50
Переглянути файл
@@ -0,0 +1,50 @@
/**
* Settings › Version Control › Git › Enable Git integration. Off, the backend finds no
* repositories and refuses the commands that start git on their own (clone, init, GitHub);
* the frontend leaves out every Git action, tool window and menu.
*/
import { setContext } from "./context";
import { onWorkflowSettingsChange, useWorkflowSettings, workflowSettings } from "./workflowSettings";
export function gitEnabled(): boolean {
return workflowSettings().vcs.git.enabled;
}
export function useGitEnabled(): boolean {
return useWorkflowSettings((w) => w.vcs.git.enabled);
}
/**
* Keeps the `gitDisabled` context key (for `when` clauses) in step with the setting.
* Unset it reads as enabled, so a window that never installs it keeps its Git actions.
*/
export function installGitEnabledContext(): () => void {
setContext("gitDisabled", !gitEnabled());
const off = onWorkflowSettingsChange(
(w) => w.vcs.git.enabled,
(on) => setContext("gitDisabled", !on),
);
return () => {
off();
setContext("gitDisabled", false);
};
}
/** Runs `register` while Git integration is on and disposes what it registered while it is off. */
export function whileGitEnabled(register: () => () => void): () => void {
let dispose: (() => void) | null = null;
const sync = (on: boolean) => {
if (on && !dispose) dispose = register();
else if (!on && dispose) {
dispose();
dispose = null;
}
};
sync(gitEnabled());
const off = onWorkflowSettingsChange((w) => w.vcs.git.enabled, sync);
return () => {
off();
dispose?.();
dispose = null;
};
}
+2
Переглянути файл
@@ -1,4 +1,6 @@
{
"Enable Git integration": "启用 Git 集成",
"Off, the IDE runs no git: repositories are not detected, and Git actions, menus and tool windows are hidden. Applies to all projects.": "关闭后 IDE 不运行 git:不检测仓库,并隐藏 Git 操作、菜单和工具窗口。对所有项目生效。",
"No SQL client": "没有 SQL 客户端",
"Quick Preview": "快速预览",
"No images to compare": "没有可比较的图像",
+7
Переглянути файл
@@ -3,6 +3,13 @@ import { splitCommandLine } from "./commandLine";
import { DEFAULT_WORKFLOW, validateWorkflow } from "./workflowSettings";
describe("validateWorkflow", () => {
it("keeps Git enabled unless switched off", () => {
const enabled = (value: unknown) => validateWorkflow({ vcs: { git: { enabled: value } } }).vcs.git.enabled;
expect(enabled(undefined)).toBe(true);
expect(enabled(false)).toBe(false);
expect(enabled("off")).toBe(true);
});
it("recurses into submodules when cloning unless switched off", () => {
const recurse = (cloneSubmodules: unknown) =>
validateWorkflow({ vcs: { git: { cloneSubmodules } } }).vcs.git.cloneSubmodules;
+9
Переглянути файл
@@ -28,6 +28,8 @@ export interface IssueLinkValid {
}
export interface GitSettingsValid {
/** Git integration on; off, no repository is found, no git runs and the Git UI is hidden. */
enabled: boolean;
annotate: { ignoreWhitespace: boolean; movement: GitAnnotateMovement };
inlineBlame: boolean;
inlineBlameClickable: boolean;
@@ -308,6 +310,7 @@ export const DEFAULT_WORKFLOW: WorkflowSettings = {
limitHistory: true,
historyLimit: 1000,
git: {
enabled: true,
annotate: { ignoreWhitespace: true, movement: "none" },
inlineBlame: false,
inlineBlameClickable: true,
@@ -498,6 +501,7 @@ export function validateVcs(raw: unknown): VcsSettingsValid {
limitHistory: bool(v.limitHistory, d.limitHistory),
historyLimit: num(v.historyLimit, d.historyLimit, L.historyLimit, true),
git: {
enabled: bool(g.enabled, d.git.enabled),
annotate: {
ignoreWhitespace: bool(annotate.ignoreWhitespace, d.git.annotate.ignoreWhitespace),
movement: oneOf(annotate.movement, ["none", "withinFile", "acrossFiles"], d.git.annotate.movement),
@@ -807,6 +811,11 @@ export function useWorkflowSettings<T>(select: (s: WorkflowSettings) => T): T {
});
}
/** Main menu entries (submenu and action ids) left out while Settings › Git › Enable Git integration is off. */
export function hiddenMenuEntries(settings: WorkflowSettings = workflowSettings()): string[] {
return settings.vcs.git.enabled ? [] : ["git", "vcs.cloneProject"];
}
/** Calls `listener` whenever a section changes (deep-compared by JSON), not initially. */
export function onWorkflowSettingsChange<T>(
select: (s: WorkflowSettings) => T,
+13 -2
Переглянути файл
@@ -6,6 +6,7 @@ import { useProject } from "@/platform/project";
import { lookup, t, useI18n } from "@/platform/i18n";
import { commands, type MenuNode } from "@/platform/ipc";
import { usePlatform } from "@/platform/platformInfo";
import { hiddenMenuEntries, useWorkflowSettings } from "@/platform/workflowSettings";
import { Icon, MenuList, Popup, type MenuItem } from "@/ui";
import { useChromeIconSize } from "@/ui/density";
import menuStyles from "@/ui/Menu.module.css";
@@ -83,9 +84,18 @@ export function onLoneAlt(target: Window, onAlt: () => void): () => void {
};
}
/** `nodes` without the entries `hidden` names (the backend may not have the latest list yet). */
function withoutHidden(nodes: MenuNode[], hidden: readonly string[]): MenuNode[] {
if (!hidden.length) return nodes;
return nodes.flatMap((n): MenuNode[] => {
if ((n.kind === "submenu" || n.kind === "action") && hidden.includes(n.id)) return [];
return n.kind === "submenu" ? [{ ...n, children: withoutHidden(n.children, hidden) }] : [n];
});
}
async function loadMenus(): Promise<Submenu[]> {
const model: MenuNode[] = await commands.menuModel().catch(() => []);
return model.filter(isSubmenu);
return withoutHidden(model, hiddenMenuEntries()).filter(isSubmenu);
}
type MainMenuProps = {
@@ -102,6 +112,7 @@ export function MainMenu({ row = false, ...props }: MainMenuProps) {
function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged: boolean; row: boolean }) {
useI18n((s) => s.locale);
useContextKeys((s) => javaFileNameOf(s.editorPath));
const gitEnabled = useWorkflowSettings((w) => w.vcs.git.enabled);
const iconSize = useChromeIconSize();
const [menus, setMenus] = useState<Submenu[]>([]);
const [expanded, setExpanded] = useState(false);
@@ -137,7 +148,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
return () => {
disposed = true;
};
}, [merged, row]);
}, [merged, row, gitEnabled]);
useEffect(() => {
if (!(merged || row) || open === null) return;
let disposed = false;
+4 -1
Переглянути файл
@@ -37,6 +37,7 @@ import { windowDragRegion } from "./window-drag";
import { useToolbarCenter } from "./toolbarCenter";
import { useProjectGradientAnchor } from "./projectGradient";
import { useToolbarLabelWidth } from "./toolbarLabelWidth";
import { useGitEnabled } from "@/platform/gitEnabled";
export function orderTitleItems(items: Iterable<TitleItemContribution>) {
const all = [...items];
@@ -109,6 +110,7 @@ const VCS_FALLBACK_ACTIONS = ["vcs.createRepository", "vcs.clone", "vcs.localHis
/** "Version Control ▾" shown while no VCS widget is contributed (project without a repository). */
function VcsFallback() {
const gitOn = useGitEnabled();
const [open, setOpen] = useState(false);
const ref = useRef<HTMLButtonElement>(null);
const actions = useActions((s) => s.actions);
@@ -116,7 +118,8 @@ function VcsFallback() {
() => VCS_FALLBACK_ACTIONS.filter((id) => actions.has(id)).map((action) => ({ kind: "action", action })),
[actions],
);
if (!items.length) return null;
// Git integration off: no Version Control widget at all (Local History stays in Find Action).
if (!gitOn || !items.length) return null;
return (
<>
<BarButton