The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.
TypeScript code-editorcross-platformdapdatabase-clientdebuggerdesktop-appdeveloper-toolsgithttp-clientideintellijlsprusttauriterminal
feat(docker): Compose detection, banner, gutter run and Services grouping (#2429)
Deng Liu8cd121ed62c9
diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rsindex c0c720509..d76c14b32 100644--- a/crates/ide-core/src/settings.rs+++ b/crates/ide-core/src/settings.rs@@ -637,6 +637,15 @@ pub struct FileSettings {pub file_types: BTreeMap<String, FileTypeAssociation>,/// Override File Type: file (project-relative and `/`-separated, or absolute) → language id.pub file_type_overrides: BTreeMap<String, String>,+ /// Compose detection choices, keyed by project-relative file path.+ pub compose_file_overrides: BTreeMap<String, ComposeFileOverride>,+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize, Type)]+#[serde(rename_all = "camelCase")]+pub enum ComposeFileOverride {+ Kept,+ Excluded,}/// One language's file name and hashbang patterns on top of its definition.@@ -664,6 +673,7 @@ impl Default for FileSettings {local_history_max_mb: 512,file_types: BTreeMap::new(),file_type_overrides: BTreeMap::new(),+ compose_file_overrides: BTreeMap::new(),}}}diff --git a/crates/ide-workspace/src/settings.rs b/crates/ide-workspace/src/settings.rsindex 3bcab9fa4..f59ef965b 100644--- a/crates/ide-workspace/src/settings.rs+++ b/crates/ide-workspace/src/settings.rs@@ -467,6 +467,22 @@ mod tests {use super::*;use serde_json::json;+ #[test]+ fn compose_file_choices_are_project_settings_and_survive_reload() {+ let tmp = tempfile::tempdir().unwrap();+ let cfg = tmp.path().join("cfg");+ let proj = tmp.path().join("proj");+ std::fs::create_dir_all(proj.join(".openidea")).unwrap();+ let store = SettingsStore::load(&cfg, Some(&proj));+ let choices = json!({"docker/stack.yml": "kept", "manifest.yml": "excluded"});+ store.set(SettingsScope::Project, "files.composeFileOverrides", choices.clone()).unwrap();+ let loaded = SettingsStore::load(&cfg, Some(&proj)).effective();+ assert_eq!(serde_json::to_value(&loaded.files.compose_file_overrides).unwrap(), choices);+ assert!(SettingsStore::load(&cfg, None).effective().files.compose_file_overrides.is_empty());+ assert!(store.set(SettingsScope::Project, "files.composeFileOverrides", json!({"bad.yml": "yes"})).is_err());+ assert_eq!(serde_json::to_value(&store.effective().files.compose_file_overrides).unwrap(), choices);+ }+#[test]fn custom_color_schemes_are_user_settings_and_survive_reload() {let tmp = tempfile::tempdir().unwrap();diff --git a/e2e/editorGitMenu.spec.ts b/e2e/editorGitMenu.spec.tsindex dfb2d3601..e97a9ab4e 100644--- a/e2e/editorGitMenu.spec.ts+++ b/e2e/editorGitMenu.spec.ts@@ -11,7 +11,9 @@ test("editor Git submenu offers the registered file and repository actions in gr/Annotate with Git Blame/,/Show Diff/,/Compare with Branch or Revision…/,+ /Compare with Revision…/,/Show History$/,+ /Show Current Revision/,/Show History for Selection/,/Rollback…/,/Push…/,diff --git a/src/bindings.ts b/src/bindings.tsindex 6627f21ed..ccfc220a7 100644--- a/src/bindings.ts+++ b/src/bindings.ts@@ -2771,6 +2771,8 @@ export type CompletionSettings = {parameterInfoDelay?: number,};+export type ComposeFileOverride = "kept" | "excluded";+export type ComposeOp = "start" | "stop" | "restart" |/** Stops and removes the project's containers and networks. */"down";@@ -4307,6 +4309,8 @@ export type FileSettings = {fileTypes?: { [key in string]: FileTypeAssociation },/** Override File Type: file (project-relative and `/`-separated, or absolute) → language id. */fileTypeOverrides?: { [key in string]: string },+ /** Compose detection choices, keyed by project-relative file path. */+ composeFileOverrides?: { [key in string]: ComposeFileOverride },};export type FileStamp = {diff --git a/src/features/project-tree/fileRefactor.test.tsx b/src/features/project-tree/fileRefactor.test.tsxindex 1e6baf07c..14c8970ea 100644--- a/src/features/project-tree/fileRefactor.test.tsx+++ b/src/features/project-tree/fileRefactor.test.tsx@@ -1,6 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { act, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import type { FileMove, WorkspaceEdit } from "@/bindings";+import { onFilesMoved } from "@/platform/fileOps";import { provideNotificationService } from "@/workbench/contributions";import {lastFileRefactoring,@@ -87,6 +88,29 @@ describe("runFileRefactoring", () => {const moves: FileMove[] = [{ from: "/p/a/util.ts", to: "/p/b/util.ts" }];+ it("awaits move listeners and notifies them of Undo", async () => {+ let finish!: () => void;+ const gate = new Promise<void>((resolve) => {+ finish = resolve;+ });+ const listener = vi.fn(async () => {+ await gate;+ });+ const stop = onFilesMoved(listener);+ try {+ const pending = runFileRefactoring(moves, { references: false, textOccurrences: false }, "Rename");+ await waitFor(() => expect(listener).toHaveBeenCalledWith(moves));+ expect(notify).not.toHaveBeenCalled();+ finish();+ expect(await pending).toBe("done");+ await undoFileRefactoring();+ expect(listener).toHaveBeenLastCalledWith([{ from: "/p/b/util.ts", to: "/p/a/util.ts" }]);+ } finally {+ finish();+ stop();+ }+ });+it("previews edits in other files, applies the move and offers Undo", async () => {render(<RefactoringPreviewHost />);let status: Promise<string> = Promise.resolve("");diff --git a/src/features/project-tree/fileRefactor.ts b/src/features/project-tree/fileRefactor.tsindex 4e090a7a1..12f8e404c 100644--- a/src/features/project-tree/fileRefactor.ts+++ b/src/features/project-tree/fileRefactor.ts@@ -6,6 +6,7 @@*/import type { FileMove, UndoOutcome, WorkspaceEdit } from "@/bindings";import { openEditorPaths } from "@/editor/api";+import { notifyFilesMoved } from "@/platform/fileOps";import { call, commands, emitLocalIdeEvent, isCancelled, isTauri, nextRequestId } from "@/platform/ipc";import { maybeEditorService, notifications } from "@/workbench/contributions";import { projectFs } from "./fs";@@ -190,6 +191,7 @@ async function withEditorsFollowing<T>(run: () => Promise<T>, done: (r: T) => Ficonst active = editor?.activePath() ?? null;const result = await run();const applied = done(result);+ await notifyFilesMoved(applied);const open = openBefore.filter((p) => applied.some((m) => isSameOrInside(p, m.from)));if (applied.length)emitLocalIdeEvent({diff --git a/src/features/run/services.test.ts b/src/features/run/services.test.tsindex d34bfa544..1a9df617f 100644--- a/src/features/run/services.test.ts+++ b/src/features/run/services.test.ts@@ -376,6 +376,19 @@ describe("hidden configurations", () => {expect(readHidden("/q")).toEqual({});expect(readHidden(null)).toEqual({});});++ it("does not duplicate docker-compose, docker-dockerfile or docker-image runs in the run configurations provider", () => {+ const compose = config("docker:compose:docker/playground-compose.yml:postgres", "docker-compose");+ const dockerfile = config("docker:dockerfile:Dockerfile", "docker-dockerfile");+ const image = config("docker:image:postgres", "docker-image");+ const items = runServiceItems(+ [compose, dockerfile, image],+ [session("s1", compose, "running", 1), session("s2", dockerfile, "finished", 2)],+ [...DEFAULT_TYPES, "docker-compose", "docker-dockerfile", "docker-image"],+ [compose.id, dockerfile.id, image.id],+ );+ expect(items).toEqual([]);+ });});describe("add service categories", () => {diff --git a/src/features/run/services.tsx b/src/features/run/services.tsxindex 6e739f726..b82672600 100644--- a/src/features/run/services.tsx+++ b/src/features/run/services.tsx@@ -71,6 +71,8 @@ const STORAGE_KEY = "openidea.services.runTypes:";const RAN_KEY = "openidea.services.ran:";/** Types shown in Services until the user changes the list. */export const DEFAULT_TYPES: readonly string[] = ["spring-boot"];+/** Docker run kinds whose containers/deployments are already shown under the Docker provider in Services. */+const DOCKER_PROVIDER_KINDS: ReadonlySet<string> = new Set(["docker-compose", "docker-dockerfile", "docker-image"]);// ---------------------------------------------------------------------------// Types added to Services, per project@@ -325,12 +327,14 @@ export function runServiceItems(): ServiceTreeItem[] {const executions = serviceSessions(sessions, debug);const latest = currentServiceSessions(executions);- const kinds = [...added];+ const kinds = added.filter((kind) => !DOCKER_PROVIDER_KINDS.has(kind));const shown = (s: ServiceSession) => liveServiceSession(s) || !removed(s.config.id);- for (const s of executions) if (shown(s) && !kinds.includes(s.config.kind)) kinds.push(s.config.kind);+ for (const s of executions)+ if (shown(s) && !DOCKER_PROVIDER_KINDS.has(s.config.kind) && !kinds.includes(s.config.kind))+ kinds.push(s.config.kind);for (const id of ran) {const kind = configs.find((c) => c.id === id)?.kind;- if (kind && !kinds.includes(kind)) kinds.push(kind);+ if (kind && !DOCKER_PROVIDER_KINDS.has(kind) && !kinds.includes(kind)) kinds.push(kind);}return kinds.flatMap((kind) => {const entries: RunConfig[] = added.includes(kind)@@ -847,7 +851,9 @@ function addMenu(): MenuItem[] {const added = currentTypes();const used = [...new Set(useRun.getState().configs.map((c) => c.kind))];const known = [...KIND_OPTIONS.map((o) => o.value), ...useRunConfigTypes.getState().types.keys()];- const kinds = [...new Set([...used, ...known])].filter((k) => k !== "compound" && !added.includes(k));+ const kinds = [...new Set([...used, ...known])].filter(+ (k) => k !== "compound" && !DOCKER_PROVIDER_KINDS.has(k) && !added.includes(k),+ );/** A leaf item: the type's own label; grouped types live in their group's submenu. */const item = (kind: string): MenuItem => ({label: useRunConfigTypes.getState().types.get(kind)?.label ?? kindLabel(kind),diff --git a/src/features/services/Services.module.css b/src/features/services/Services.module.cssindex f29a9d98a..df5278e5b 100644--- a/src/features/services/Services.module.css+++ b/src/features/services/Services.module.css@@ -152,6 +152,10 @@justify-content: center;}.marker {+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;width: 14px;height: 14px;display: flex;diff --git a/src/features/services/compose.test.ts b/src/features/services/compose.test.tsnew file mode 100644index 000000000..a8a3d465d--- /dev/null+++ b/src/features/services/compose.test.ts@@ -0,0 +1,105 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook } from "@testing-library/react";+import { notifyFilesMoved } from "@/platform/fileOps";+import { useProject } from "@/platform/project";+import type { Settings } from "@/platform/ipc";+import {+ activateComposeFiles,+ composeAutoDetectBanner,+ isComposeFile,+ noteComposeContent,+ setComposeFileOverride,+ useComposeFiles,+} from "./compose";++const ipc = vi.hoisted(() => ({ settingsSet: vi.fn() }));+vi.mock("@/platform/ipc", async (original) => ({+ ...(await original<typeof import("@/platform/ipc")>()),+ commands: ipc,+}));++const settings = (overrides = {}): Settings => ({ files: { composeFileOverrides: overrides } }) as Settings;+let stop: () => void;++beforeEach(() => {+ ipc.settingsSet.mockReset().mockImplementation(async (_scope, _key, json) => ({+ status: "ok",+ data: settings(JSON.parse(json)),+ }));+ useProject.setState({ project: { root: "/p" } as never, settings: settings() });+ stop = activateComposeFiles();+});+afterEach(() => {+ stop();+ useProject.setState({ project: null, settings: null });+ useComposeFiles.setState({ overrides: {}, contentDetected: {} });+});++describe("Compose file choices", () => {+ it.each(["kept", "excluded"] as const)("persists %s in project settings and restores it", async (choice) => {+ await setComposeFileOverride("/p/stack.yml", choice);+ expect(ipc.settingsSet).toHaveBeenCalledWith(+ "project",+ "files.composeFileOverrides",+ JSON.stringify({ "stack.yml": choice }),+ );+ const saved = useProject.getState().settings;+ stop();+ useComposeFiles.setState({ overrides: {} });+ useProject.setState({ settings: saved });+ stop = activateComposeFiles();+ expect(useComposeFiles.getState().overrides).toEqual({ "/p/stack.yml": choice });+ expect(isComposeFile("/p/stack.yml")).toBe(choice === "kept");+ });++ it("preserves consecutive choices and follows file/folder moves and Undo", async () => {+ await Promise.all([+ setComposeFileOverride("/p/stack.yml", "kept"),+ setComposeFileOverride("/p/sub/other.yml", "excluded"),+ ]);+ await notifyFilesMoved([{ from: "/p/stack.yml", to: "/p/sub/stack.yml" }]);+ await notifyFilesMoved([{ from: "/p/sub", to: "/p/new" }]);+ expect(useComposeFiles.getState().overrides).toEqual({+ "/p/new/stack.yml": "kept",+ "/p/new/other.yml": "excluded",+ });+ await notifyFilesMoved([{ from: "/p/new", to: "/p/sub" }]);+ expect(useProject.getState().settings?.files?.composeFileOverrides).toEqual({+ "sub/stack.yml": "kept",+ "sub/other.yml": "excluded",+ });+ });++ it("clears detections and reads only the new project's choices on project switch", async () => {+ await setComposeFileOverride("/p/stack.yml", "kept");+ noteComposeContent("/p/other.yml", "services:\n web:\n image: nginx\n");+ useProject.setState({ project: { root: "/q" } as never, settings: settings({ "stack.yml": "excluded" }) });+ expect(useComposeFiles.getState()).toEqual({ overrides: { "/q/stack.yml": "excluded" }, contentDetected: {} });+ });++ it("resolves relative choices on Windows and keeps absolute paths outside the project", () => {+ useProject.setState({+ project: { root: "C:/project" } as never,+ settings: settings({ "docker/stack.yml": "kept", "D:/other.yml": "excluded" }),+ });+ expect(useComposeFiles.getState().overrides).toEqual({+ "C:/project/docker/stack.yml": "kept",+ "D:/other.yml": "excluded",+ });+ });++ it("leaves the banner choice unchanged when saving fails", async () => {+ ipc.settingsSet.mockRejectedValueOnce(new Error("read-only project"));+ await expect(setComposeFileOverride("/p/stack.yml", "excluded")).rejects.toThrow("read-only project");+ expect(useComposeFiles.getState().overrides).toEqual({});+ });++ it("offers the shared banner only for unconfirmed content detection", () => {+ noteComposeContent("/p/stack.yml", "services:\n web:\n image: nginx\n");+ expect(+ renderHook(() => composeAutoDetectBanner.useBanner("/p/stack.yml")).result.current?.actions?.map((a) => a.label),+ ).toEqual(["Not a Compose file", "Keep as Docker Compose"]);+ expect(renderHook(() => composeAutoDetectBanner.useBanner("/p/compose.yml")).result.current).toBeNull();+ expect(renderHook(() => composeAutoDetectBanner.useBanner("/p/kubernetes.yml")).result.current).toBeNull();+ });+});diff --git a/src/features/services/compose.ts b/src/features/services/compose.tsindex 7db483e75..f22d83ede 100644--- a/src/features/services/compose.ts+++ b/src/features/services/compose.ts@@ -3,11 +3,118 @@* (`services:` → up all, each service → up that service), detected per line like* the run gutter does (the configurations they start are in `runTypes.ts`).*/+import { create } from "zustand";+import { executeAction } from "@/platform/actions";+import { onFilesMoved } from "@/platform/fileOps";+import { call, commands, type ComposeFileOverride, type Settings } from "@/platform/ipc";+import { useProject } from "@/platform/project";+import { bumpFileIconRevision } from "@/ui/icons";+import { notifications, type EditorBannerContribution } from "@/workbench/contributions";+export type DockerTarget =| { kind: "build"; line: number; stage: string | null; last: boolean }| { kind: "composeAll"; line: number }| { kind: "composeService"; line: number; service: string };+interface ComposeFilesState {+ overrides: Record<string, ComposeFileOverride>;+ contentDetected: Record<string, boolean>;+}++export const useComposeFiles = create<ComposeFilesState>(() => ({ overrides: {}, contentDetected: {} }));++const absolutePath = (path: string) => path.startsWith("/") || /^[A-Za-z]:\//.test(path);++function syncComposeSettings(settings: Settings | null, root: string | null, reset: boolean) {+ const overrides = Object.fromEntries(+ Object.entries(settings?.files?.composeFileOverrides ?? {}).map(([path, status]) => [+ root && !absolutePath(path) ? `${root}/${path}` : path,+ status,+ ]),+ );+ useComposeFiles.setState({ overrides, ...(reset ? { contentDetected: {} } : {}) });+ bumpFileIconRevision();+}++let saving = Promise.resolve();++function writeComposeOverrides(+ change: (current: Record<string, ComposeFileOverride>) => Record<string, ComposeFileOverride>,+) {+ const root = useProject.getState().project?.root ?? null;+ const pending = saving+ .then(async () => {+ if (root !== (useProject.getState().project?.root ?? null)) return;+ const current = useProject.getState().settings?.files?.composeFileOverrides ?? {};+ const next = change(current);+ const settings = await call(+ commands.settingsSet(root ? "project" : "global", "files.composeFileOverrides", JSON.stringify(next)),+ );+ if (root === (useProject.getState().project?.root ?? null)) useProject.setState({ settings });+ })+ .catch((error: unknown) => {+ notifications().notify({+ level: "error",+ title: "Could not save Docker Compose file detection",+ body: String(error),+ });+ throw error;+ });+ saving = pending.catch(() => {});+ return pending;+}++export function setComposeFileOverride(path: string, status: ComposeFileOverride | null): Promise<void> {+ const root = useProject.getState().project?.root;+ const key = root && path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path;+ return writeComposeOverrides((current) => {+ const next = { ...current };+ if (status) next[key] = status;+ else delete next[key];+ return next;+ });+}++export function activateComposeFiles(): () => void {+ const state = useProject.getState();+ syncComposeSettings(state.settings, state.project?.root ?? null, true);+ const stopSettings = useProject.subscribe((s, prev) => {+ const reset = s.project?.root !== prev.project?.root;+ if (reset || s.settings !== prev.settings) syncComposeSettings(s.settings, s.project?.root ?? null, reset);+ });+ const stopMoves = onFilesMoved(async (moves) => {+ await saving;+ const root = useProject.getState().project?.root;+ const remap = (path: string) => {+ const move = moves.find((m) => path === m.from || path.startsWith(`${m.from}/`));+ return move ? move.to + path.slice(move.from.length) : path;+ };+ const state = useComposeFiles.getState();+ const detected = Object.fromEntries(+ Object.entries(state.contentDetected).map(([path, value]) => [remap(path), value]),+ );+ const changed = Object.keys(state.overrides).some((path) => remap(path) !== path);+ if (changed) {+ await writeComposeOverrides((current) =>+ Object.fromEntries(+ Object.entries(current).map(([key, value]) => {+ const path = remap(root && !absolutePath(key) ? `${root}/${key}` : key);+ return [root && path.startsWith(`${root}/`) ? path.slice(root.length + 1) : path, value];+ }),+ ),+ );+ }+ if (root === useProject.getState().project?.root) {+ useComposeFiles.setState({ contentDetected: detected });+ bumpFileIconRevision();+ }+ });+ return () => {+ stopSettings();+ stopMoves();+ };+}+const base = (path: string) => path.slice(path.lastIndexOf("/") + 1);const dir = (path: string) => path.slice(0, Math.max(0, path.lastIndexOf("/"))) || "/";@@ -16,8 +123,192 @@ export function isDockerfile(path: string): boolean {return /^(Dockerfile|Containerfile)(\.[\w.-]+)?$/i.test(name) || /\.(dockerfile|containerfile)$/i.test(name);}-export function isComposeFile(path: string): boolean {- return /^(docker-)?compose(\.[\w-]+)?\.ya?ml$/i.test(base(path));+export function isYamlFile(path: string): boolean {+ return /\.ya?ml$/i.test(base(path));+}++export function isNamedComposeFile(path: string): boolean {+ return /^.*compose.*\.ya?ml$/i.test(base(path));+}++const COMPOSE_TOP_SECTIONS = new Set(["version", "name", "networks", "volumes", "configs", "secrets", "include"]);++const COMPOSE_SERVICE_KEYS = new Set([+ "image",+ "build",+ "container_name",+ "hostname",+ "domainname",+ "ports",+ "expose",+ "environment",+ "env_file",+ "volumes",+ "volumes_from",+ "networks",+ "network_mode",+ "depends_on",+ "command",+ "entrypoint",+ "restart",+ "pull_policy",+ "healthcheck",+ "deploy",+ "develop",+ "labels",+ "annotations",+ "platform",+ "profiles",+ "user",+ "working_dir",+ "privileged",+ "read_only",+ "stdin_open",+ "tty",+ "init",+ "cap_add",+ "cap_drop",+ "cgroup",+ "cgroup_parent",+ "configs",+ "secrets",+ "cpus",+ "cpu_count",+ "cpu_percent",+ "cpu_shares",+ "cpu_period",+ "cpu_quota",+ "cpuset",+ "devices",+ "dns",+ "dns_opt",+ "dns_search",+ "extends",+ "external_links",+ "extra_hosts",+ "group_add",+ "ipc",+ "isolation",+ "links",+ "logging",+ "mac_address",+ "mem_limit",+ "mem_reservation",+ "oom_kill_disable",+ "oom_score_adj",+ "pid",+ "pids_limit",+ "post_start",+ "pre_stop",+ "runtime",+ "scale",+ "security_opt",+ "shm_size",+ "stop_grace_period",+ "stop_signal",+ "storage_opt",+ "sysctls",+ "tmpfs",+ "ulimits",+ "userns_mode",+ "uts",+]);++export const COMPOSE_SCAN_LIMIT = 64 * 1024;++const isServiceName = (name: string) => /^[a-zA-Z0-9_.-]+$/.test(name) && !name.startsWith("x-");++/** Whether a bounded YAML prefix looks like a Docker Compose configuration. */+export function isComposeContent(text: string): boolean {+ const lines = text+ .slice(0, COMPOSE_SCAN_LIMIT)+ .split("\n", 600)+ .map((l) => l.replace(/\r$/, ""));+ const topKeys = new Set<string>();+ let servicesLine = -1;+ for (let i = 0; i < lines.length; i++) {+ const line = lines[i]!;+ if (!line.trim() || line.trimStart().startsWith("#")) continue;+ const m = /^(?:"([^"]+)"|'([^']+)'|([A-Za-z0-9._-]+))\s*:(?:\s|$)/.exec(line);+ if (m) {+ const k = m[1] ?? m[2] ?? m[3]!;+ topKeys.add(k);+ if (k === "services" && servicesLine < 0) servicesLine = i;+ } else if (!/^\s/.test(line) && line !== "---" && line !== "...") {+ return false;+ }+ }+ if (servicesLine < 0) return false;+ for (const key of topKeys) {+ if (key !== "services" && !COMPOSE_TOP_SECTIONS.has(key) && !key.startsWith("x-")) return false;+ }+ let serviceIndent: number | null = null;+ let propIndent: number | null = null;+ let service = false;+ for (let i = servicesLine + 1; i < lines.length; i++) {+ const line = lines[i]!;+ if (!line.trim() || line.trimStart().startsWith("#")) continue;+ const lead = line.length - line.trimStart().length;+ if (lead === 0) break;+ serviceIndent ??= lead;+ if (lead === serviceIndent) {+ propIndent = null;+ const match = KEY.exec(line);+ const name = match?.[3] ?? match?.[4] ?? match?.[5];+ service = !!name && isServiceName(name);+ continue;+ }+ if (service && lead > serviceIndent) {+ propIndent ??= lead;+ if (lead === propIndent) {+ const km = /^\s*("([^"]+)"|'([^']+)'|([A-Za-z0-9._-]+))\s*:/.exec(line);+ const prop = km?.[2] ?? km?.[3] ?? km?.[4];+ if (prop && (COMPOSE_SERVICE_KEYS.has(prop) || prop.startsWith("x-"))) return true;+ }+ }+ }+ return false;+}++export function noteComposeContent(path: string, text: string): boolean {+ if (!isYamlFile(path)) return false;+ const detected = isComposeContent(text);+ const prev = !!useComposeFiles.getState().contentDetected[path];+ if (detected !== prev) {+ useComposeFiles.setState((s) => {+ const contentDetected = { ...s.contentDetected };+ if (detected) contentDetected[path] = true;+ else delete contentDetected[path];+ return { contentDetected };+ });+ bumpFileIconRevision();+ }+ return detected;+}++export function composeFileIcon(_fileName: string, path: string | null): string | null {+ if (!path || !isYamlFile(path)) return null;+ const state = useComposeFiles.getState();+ const override = state.overrides[path];+ if (override === "excluded") return "file-yaml";+ if (override === "kept" || state.contentDetected[path]) return "file-docker";+ return null;+}++export function isComposeFile(path: string, text?: string): boolean {+ if (!isYamlFile(path)) return false;+ const state = useComposeFiles.getState();+ const override = state.overrides[path];+ if (override === "excluded") return false;+ if (override === "kept") return true;+ if (isNamedComposeFile(path)) return true;+ if (text !== undefined) return isComposeContent(text);+ return !!state.contentDetected[path];+}++export function isAutoDetectedComposeFile(path: string, text?: string): boolean {+ if (isNamedComposeFile(path) || !isComposeFile(path, text)) return false;+ return useComposeFiles.getState().overrides[path] !== "kept";}/** Every `FROM` line; a named stage (`AS build`) is built with `--target`, the last one whole. */@@ -31,13 +322,13 @@ export function dockerfileTargets(text: string): DockerTarget[] {return out;}-const KEY = /^(\s*)("([^"]+)"|'([^']+)'|[A-Za-z0-9._-]+)\s*:\s*(#.*)?$/;+const KEY = /^(\s*)("([^"]+)"|'([^']+)'|([A-Za-z0-9._-]+))\s*:\s*(?:[&*{#].*)?$/;/** The top-level `services:` key and each service directly below it. */export function composeTargets(text: string): DockerTarget[] {const lines = text.split("\n").map((l) => l.replace(/\r$/, ""));const out: DockerTarget[] = [];- const start = lines.findIndex((l) => /^services\s*:\s*(#.*)?$/.test(l));+ const start = lines.findIndex((l) => /^services\s*:\s*(?:[&#].*)?$/.test(l));if (start < 0) return out;out.push({ kind: "composeAll", line: start });let indent: number | null = null;@@ -49,14 +340,41 @@ export function composeTargets(text: string): DockerTarget[] {indent ??= lead;if (lead !== indent) continue;const m = KEY.exec(line);- if (m) out.push({ kind: "composeService", line: i, service: m[3] ?? m[4] ?? m[2]! });+ const service = m?.[3] ?? m?.[4] ?? m?.[5];+ if (service && isServiceName(service)) out.push({ kind: "composeService", line: i, service });}return out;}+/** The Compose target enclosing 0-based `line` (a service block, or `composeAll`). */+export function composeTargetAtLine(text: string, line: number): DockerTarget | null {+ const targets = composeTargets(text);+ if (!targets.length) return null;+ const all = targets.find((t) => t.kind === "composeAll") ?? targets[0]!;+ if (line <= all.line) return all;+ const lines = text.split("\n").map((l) => l.replace(/\r$/, ""));+ let endOfServices = lines.length;+ for (let i = all.line + 1; i < lines.length; i++) {+ const l = lines[i]!;+ if (!l.trim() || l.trimStart().startsWith("#")) continue;+ if (l.length === l.trimStart().length) {+ endOfServices = i;+ break;+ }+ }+ if (line >= endOfServices) return all;+ const services = targets.filter(+ (t): t is Extract<DockerTarget, { kind: "composeService" }> => t.kind === "composeService",+ );+ for (let i = services.length - 1; i >= 0; i--) {+ if (line >= services[i]!.line) return services[i]!;+ }+ return all;+}+export function fileTargets(path: string, text: string): DockerTarget[] {if (isDockerfile(path)) return dockerfileTargets(text);- if (isComposeFile(path)) return composeTargets(text);+ if (isComposeFile(path, text)) return composeTargets(text);return [];}@@ -79,3 +397,31 @@ export function targetTitle(t: DockerTarget, path: string): string {return `Compose Up '${t.service}'`;}}++export const composeAutoDetectBanner: EditorBannerContribution = {+ id: "docker.composeAutoDetect",+ order: 5,+ useBanner: (path) => {+ const detected = useComposeFiles((s) => {+ if (!isYamlFile(path)) return false;+ const override = s.overrides[path];+ if (override === "excluded" || override === "kept") return false;+ return isAutoDetectedComposeFile(path);+ });+ if (!detected) return null;+ return {+ text: "This file was auto-detected as a Docker Compose configuration based on its content",+ icon: "info",+ actions: [+ {+ label: "Not a Compose file",+ run: () => void executeAction("docker.setComposeFileOverride", { path, status: "excluded" }),+ },+ {+ label: "Keep as Docker Compose",+ run: () => void executeAction("docker.setComposeFileOverride", { path, status: "kept" }),+ },+ ],+ };+ },+};diff --git a/src/features/services/dockerGutter.test.ts b/src/features/services/dockerGutter.test.tsnew file mode 100644index 000000000..5c50db365--- /dev/null+++ b/src/features/services/dockerGutter.test.ts@@ -0,0 +1,43 @@+import { afterEach, expect, it, vi } from "vitest";+import { EditorView } from "@codemirror/view";+import * as ui from "@/ui";+import { dockerGutter } from "./dockerGutter";+import { useComposeFiles } from "./compose";++afterEach(() => {+ vi.restoreAllMocks();+ useComposeFiles.setState({ overrides: {}, contentDetected: {} });+});++it("refreshes markers and menus after edits, removes non-service keys and respects exclusions", async () => {+ const menu = vi.spyOn(ui, "showContextMenu").mockImplementation(() => {});+ const view = new EditorView({+ doc: "services:\n web:\n image: nginx\n x-defaults:\n image: nginx\nvolumes:\n data:\n",+ parent: document.body,+ extensions: dockerGutter({ doc: 1, path: "/p/stack.yml", language: "yaml", uiMode: null, readOnly: false }),+ });+ const markers = () => [...view.dom.querySelectorAll<HTMLButtonElement>(".cm-gutterElement button")];+ try {+ await vi.waitFor(() => expect(markers().map((m) => m.title)).toContain("Compose Up 'web'"));+ expect(markers().some((m) => m.title.includes("x-defaults") || m.title.includes("data"))).toBe(false);+ view.dispatch({+ changes: { from: 0, to: view.state.doc.length, insert: "# moved\nservices:\n db:\n image: postgres\n" },+ });+ await vi.waitFor(() => expect(markers().some((m) => m.title === "Compose Up 'db'")).toBe(true));+ expect(markers().some((m) => m.title === "Compose Up 'web'")).toBe(false);+ markers()+ .find((m) => m.title === "Compose Up 'db'")!+ .click();+ expect(menu).toHaveBeenCalledWith(+ expect.anything(),+ expect.arrayContaining([+ expect.objectContaining({ label: "Compose Up 'db'" }),+ expect.objectContaining({ label: "Modify Run Configuration…" }),+ ]),+ );+ useComposeFiles.setState({ overrides: { "/p/stack.yml": "excluded" } });+ await vi.waitFor(() => expect(markers()).toHaveLength(0));+ } finally {+ view.destroy();+ }+});diff --git a/src/features/services/dockerGutter.ts b/src/features/services/dockerGutter.tsindex 4c565aa36..b4115caf9 100644--- a/src/features/services/dockerGutter.ts+++ b/src/features/services/dockerGutter.ts@@ -3,13 +3,23 @@* files (`services:` → up all, each service → up it). As in IDEA they start* temporary Dockerfile / Docker Compose run configurations through `run.runConfig`.*/-import { RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";+import { Compartment, RangeSet, StateEffect, StateField, type EditorState, type Extension } from "@codemirror/state";import { EditorView, GutterMarker, ViewPlugin, gutter, type ViewUpdate } from "@codemirror/view";import type { EditorDocContext } from "@/editor/api";import { executeAction } from "@/platform/actions";import { useProject } from "@/platform/project";import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";-import { fileTargets, isComposeFile, isDockerfile, targetTitle, type DockerTarget } from "./compose";+import {+ fileTargets,+ COMPOSE_SCAN_LIMIT,+ isComposeFile,+ isDockerfile,+ isYamlFile,+ noteComposeContent,+ targetTitle,+ useComposeFiles,+ type DockerTarget,+} from "./compose";import { gutterActions } from "./runTypes";import styles from "./Services.module.css";@@ -30,18 +40,34 @@ const targetsField = StateField.define<Placed[]>({});function place(state: EditorState, path: string): Placed[] {- return fileTargets(path, state.doc.toString())+ const prefix = state.doc.sliceString(0, Math.min(state.doc.length, COMPOSE_SCAN_LIMIT));+ noteComposeContent(path, prefix);+ if (!isDockerfile(path) && !isComposeFile(path, prefix)) return [];+ const text = state.doc.toString();+ return fileTargets(path, text).filter((t) => t.line < state.doc.lines).map((target) => ({ target, pos: state.doc.line(target.line + 1).from }));}function menu(target: DockerTarget, path: string): MenuItem[] {const root = useProject.getState().project?.root ?? null;- return gutterActions(target, path, root).map(({ title, config }, i) => ({+ const actions = gutterActions(target, path, root);+ const items: MenuItem[] = actions.map(({ title, config }, i) => ({label: title,icon: i === 0 ? "run" : "build-project",run: () => void executeAction("run.runConfig", { config, temporary: true }),}));+ if (actions[0]) {+ items.push(+ { kind: "separator" },+ {+ label: "Modify Run Configuration…",+ icon: "edit",+ run: () => void executeAction("run.createConfig", actions[0]!.config),+ },+ );+ }+ return items;}class Marker extends GutterMarker {@@ -59,63 +85,72 @@ class Marker extends GutterMarker {);}override toDOM(): Node {- const el = document.createElement("div");+ const el = document.createElement("button");+ el.type = "button";el.className = styles.marker ?? "";el.title = targetTitle(this.target, this.path);- el.setAttribute("role", "button");el.setAttribute("aria-label", el.title);el.innerHTML = gutterIconMarkup(this.target.kind === "composeAll" ? "gutter-run-all" : "gutter-run") ?? "";+ el.onclick = (event) => {+ event.preventDefault();+ event.stopPropagation();+ const rect = el.getBoundingClientRect();+ showContextMenu({ x: rect.left, y: rect.bottom + 2 }, menu(this.target, this.path));+ };return el;}}+function makeGutter(path: string): Extension {+ return gutter({+ // Shares the run gutter's class so "Show run icons" hides these too.+ class: `${styles.gutter} cm-openidea-gutter-run`,+ markers: (view) =>+ RangeSet.of(+ view.state.field(targetsField).map((p) => new Marker(p.target, path).range(p.pos)),+ true,+ ),+ initialSpacer: () => new Marker({ kind: "composeAll", line: 0 }, path),+ });+}+export function dockerGutter(ctx: EditorDocContext): Extension {const path = ctx.path;- if (ctx.virtual || !(isDockerfile(path) || isComposeFile(path))) return [];+ if (ctx.virtual || !(isDockerfile(path) || isYamlFile(path))) return [];+ const gutterSlot = new Compartment();+ const gutterExt = makeGutter(path);+ let hasGutter = false;const detector = ViewPlugin.fromClass(class {timer: ReturnType<typeof setTimeout> | undefined;+ unsubscribe: () => void;constructor(readonly view: EditorView) {this.schedule(0);+ this.unsubscribe = useComposeFiles.subscribe((s, prev) => {+ if (s.overrides[path] !== prev.overrides[path]) this.schedule(0);+ });}update(u: ViewUpdate) {if (u.docChanged) this.schedule(300);}schedule(delay: number) {clearTimeout(this.timer);- this.timer = setTimeout(- () => this.view.dispatch({ effects: setTargets.of(place(this.view.state, path)) }),- delay,- );+ this.timer = setTimeout(() => {+ const placed = place(this.view.state, path);+ const wantGutter = placed.length > 0;+ const effects: StateEffect<unknown>[] = [setTargets.of(placed)];+ if (wantGutter !== hasGutter) {+ hasGutter = wantGutter;+ effects.push(gutterSlot.reconfigure(wantGutter ? gutterExt : []));+ }+ this.view.dispatch({ effects });+ }, delay);}destroy() {clearTimeout(this.timer);+ this.unsubscribe();}},);- return [- targetsField,- detector,- gutter({- // Shares the run gutter's class so "Show run icons" hides these too.- class: `${styles.gutter} cm-openidea-gutter-run`,- markers: (view) =>- RangeSet.of(- view.state.field(targetsField).map((p) => new Marker(p.target, path).range(p.pos)),- true,- ),- initialSpacer: () => new Marker({ kind: "composeAll", line: 0 }, path),- domEventHandlers: {- mousedown: (view, block, event) => {- const placed = view.state.field(targetsField).find((p) => p.pos === block.from);- if (!placed || (event as MouseEvent).button !== 0) return false;- const el = (event.target as HTMLElement).closest?.(`.${styles.marker}`) ?? (event.target as HTMLElement);- const rect = el.getBoundingClientRect();- event.preventDefault();- showContextMenu({ x: rect.left, y: rect.bottom + 2 }, menu(placed.target, path));- return true;- },- },- }),- ];+ return [targetsField, gutterSlot.of([]), detector];}diff --git a/src/features/services/index.ts b/src/features/services/index.tsindex 63f8aed2a..a8e6e5f2d 100644--- a/src/features/services/index.ts+++ b/src/features/services/index.ts@@ -8,10 +8,11 @@* Compose run configuration types; Dockerfiles and Compose files get gutter run* icons that start them.*/-import { registerActions } from "@/platform/actions";-import { registerEditorContribution } from "@/editor/api";+import { executeAction, registerActions } from "@/platform/actions";+import { activeEditor, registerEditorContribution } from "@/editor/api";import {SERVICES_WINDOW,+ registerEditorBanner,registerEditorKind,registerOverlay,registerServiceProvider,@@ -19,8 +20,18 @@ import {registerToolWindow,showServiceView,} from "@/workbench/contributions";+import { useProject } from "@/platform/project";+import { addFileIconProvider } from "@/ui";+import {+ activateComposeFiles,+ composeAutoDetectBanner,+ composeFileIcon,+ composeTargetAtLine,+ isComposeFile,+ setComposeFileOverride,+} from "./compose";import { dockerGutter } from "./dockerGutter";-import { registerDockerRunTypes } from "./runTypes";+import { gutterActions, registerDockerRunTypes } from "./runTypes";import { ServicesDialogHost } from "./dialogs";import { dockerProvider, selectedTarget } from "./docker";import { DOCKER_LOG_EDITOR_KIND, DockerLogEditor, dockerLogEditorTitle, openContainerLogInEditor } from "./logEditor";@@ -51,6 +62,7 @@ const currentConnection = () => selectedTarget()?.conn ?? connections()[0]?.id ?export function activate(): () => void {const disposers = [+ activateComposeFiles(),registerToolWindow({id: SERVICES_WINDOW,title: "Services",@@ -78,9 +90,21 @@ export function activate(): () => void {keepAlive: true,}),registerOverlay({ id: "services.dialogs", component: ServicesDialogHost }),+ addFileIconProvider(composeFileIcon),+ registerEditorBanner(composeAutoDetectBanner),registerEditorContribution({ id: "services.dockerGutter", order: 56, extensions: dockerGutter }),registerDockerRunTypes(),registerActions([+ {+ id: "docker.setComposeFileOverride",+ title: "Set Docker Compose File Detection",+ category: "Docker",+ hidden: true,+ run: ({ arg }) => {+ const { path, status } = (arg ?? {}) as { path?: string; status?: string };+ if (path && (status === "kept" || status === "excluded")) return setComposeFileOverride(path, status);+ },+ },{id: "services.show",title: "Services",@@ -261,6 +285,26 @@ export function activate(): () => void {return conn ? prunePrompt(conn, typeof arg === "string" ? (arg as PruneTarget) : "system") : undefined;},},+ {+ id: "docker.composeUp",+ title: "Compose Up",+ description: "Start the service at the caret, or all services in the active Docker Compose file",+ category: "Docker",+ icon: "run",+ keywords: ["docker compose up", "start stack", "start service"],+ when: PROJECT,+ run: () => {+ const ed = activeEditor();+ if (!ed) return;+ const text = ed.view.state.doc.toString();+ if (!isComposeFile(ed.ctx.path, text)) return;+ const line = ed.view.state.doc.lineAt(ed.view.state.selection.main.head).number - 1;+ const target = composeTargetAtLine(text, line) ?? { kind: "composeAll" as const, line: 0 };+ const root = useProject.getState().project?.root ?? null;+ const [action] = gutterActions(target, ed.ctx.path, root);+ if (action) void executeAction("run.runConfig", { config: action.config, temporary: true });+ },+ },]),];return () => disposers.reverse().forEach((d) => d());diff --git a/src/features/services/services.test.ts b/src/features/services/services.test.tsindex 5bca592fc..3978fd75e 100644--- a/src/features/services/services.test.ts+++ b/src/features/services/services.test.ts@@ -1,6 +1,19 @@import { describe, expect, it } from "vitest";import type { DockerContainer, DockerSnapshot } from "@/platform/ipc";-import { composeTargets, dockerfileTargets, fileTargets, imageTag, isComposeFile, isDockerfile } from "./compose";+import { fileIconName } from "@/ui/icons";+import {+ composeFileIcon,+ composeTargetAtLine,+ composeTargets,+ dockerfileTargets,+ fileTargets,+ imageTag,+ isAutoDetectedComposeFile,+ isComposeContent,+ isComposeFile,+ isDockerfile,+ useComposeFiles,+} from "./compose";import {DOCKERFILE,DOCKER_COMPOSE,@@ -517,3 +530,137 @@ describe("phase 1: filters, cross-references and dashboard parsers", () => {expect(nInspect.containers[0]!.name).toBe("shop-db-1");});});++describe("docker compose detection and targets", () => {+ const playgroundCompose = [+ "# StarRocks local development environment",+ 'version: "3.9"',+ "",+ "networks:",+ " playground-network:",+ " driver: bridge",+ "",+ "services:",+ " starrocks:",+ " container_name: starrocks",+ " hostname: starrocks.local.com",+ " po",+ " image: starrocks/allin1-ubuntu:3.3.10",+ " restart: unless-stopped",+ " ports:",+ ' - "8030:8030"',+ " healthcheck:",+ " test: 'mysql -uroot'",+ " interval: 10s",+ " timeout: 5s",+ " retries: 3",+ " networks:",+ " playground-network:",+ "",+ " minio:",+ " container_name: minio",+ " image: minio/minio:latest",+ " depends_on:",+ " - starrocks",+ ].join("\n");++ it.each(["composeprod.yml", "mycompose.yaml", "team compose-dev.yml", "docker-compose.override.yaml"])(+ "recognises the Compose filename %s in detection and icons",+ (name) => {+ expect(isComposeFile(`/p/${name}`)).toBe(true);+ expect(fileIconName(name, `/p/${name}`)).toBe("file-docker");+ },+ );++ it.each([+ ["Kubernetes", "apiVersion: v1\nkind: Service\nservices:\n web:\n image: nginx\n"],+ ["OpenAPI", "openapi: 3.0.0\nservices:\n web:\n image: nginx\n"],+ ["Swagger", "swagger: '2.0'\nservices:\n web:\n image: nginx\n"],+ ["GitHub Actions", "on: push\njobs:\n build:\n services:\n db:\n image: postgres\n"],+ [+ "Ansible",+ "- hosts: all\n tasks:\n - name: Start services\n services:\n web:\n image: nginx\n",+ ],+ ["Helm values", "name: shop\nreplicaCount: 1\nservices:\n web:\n image: nginx\n"],+ ["mkdocs", "site_name: Docs\nservices:\n search:\n image: example\n"],+ ["unrelated service list", "name: catalog\nservices:\n web:\n url: https://example.test\n"],+ ["embedded Compose example", "example: |\n services:\n web:\n image: nginx\n"],+ ])("does not content-detect %s as Compose", (_name, content) => {+ expect(isComposeContent(content)).toBe(false);+ expect(fileTargets("/p/stack.yaml", content)).toEqual([]);+ });++ it("bounds content scanning by characters and lines", () => {+ expect(isComposeContent(`#${" ".repeat(70_000)}\nservices:\n web:\n image: nginx\n`)).toBe(false);+ expect(isComposeContent(`${"# comment\n".repeat(600)}services:\n web:\n image: nginx\n`)).toBe(false);+ });++ it("does not add run markers to extension or merge keys", () => {+ expect(+ composeTargets("services:\n x-defaults:\n image: nginx\n <<: *services\n web:\n image: nginx\n"),+ ).toEqual([+ { kind: "composeAll", line: 0 },+ { kind: "composeService", line: 4, service: "web" },+ ]);+ });++ it("adds markers for services using aliases and inline mappings", () => {+ expect(composeTargets("services:\n api: *defaults\n db: {image: postgres}\n")).toEqual([+ { kind: "composeAll", line: 0 },+ { kind: "composeService", line: 1, service: "api" },+ { kind: "composeService", line: 2, service: "db" },+ ]);+ });++ it("recognises service names beginning with an underscore", () => {+ const content = "services:\n _worker:\n image: busybox\n";+ expect(isComposeContent(content)).toBe(true);+ expect(fileTargets("/p/stack.yml", content)).toEqual([+ { kind: "composeAll", line: 0 },+ { kind: "composeService", line: 1, service: "_worker" },+ ]);+ });++ it("detects compose files by name and content, and respects Keep / Not a Compose file overrides", () => {+ expect(isComposeFile("/git/gocommon/docker/playground-compose.yml")).toBe(true);+ expect(fileIconName("playground-compose.yml", "/git/gocommon/docker/playground-compose.yml")).toBe("file-docker");+ expect(isComposeContent(playgroundCompose)).toBe(true);+ expect(isComposeFile("/git/gocommon/docker/custom-stack.yml", playgroundCompose)).toBe(true);+ expect(isComposeContent("apiVersion: v1\nkind: Service\nmetadata:\n name: my-svc\n")).toBe(false);++ const path = "/git/gocommon/docker/playground-compose.yml";+ expect(isAutoDetectedComposeFile(path, playgroundCompose)).toBe(false);+ expect(isAutoDetectedComposeFile("/p/stack.yml", playgroundCompose)).toBe(true);++ useComposeFiles.setState({ overrides: { [path]: "excluded" } });+ expect(isComposeFile(path, playgroundCompose)).toBe(false);+ expect(composeFileIcon("playground-compose.yml", path)).toBe("file-yaml");+ expect(fileTargets(path, playgroundCompose)).toEqual([]);++ useComposeFiles.setState({ overrides: { [path]: "kept" } });+ expect(isComposeFile(path)).toBe(true);+ expect(isAutoDetectedComposeFile(path, playgroundCompose)).toBe(false);+ expect(composeFileIcon("playground-compose.yml", path)).toBe("file-docker");+ useComposeFiles.setState({ overrides: {} });+ });++ it("locates compose targets per line and enclosing service at caret", () => {+ const targets = fileTargets("/git/gocommon/docker/playground-compose.yml", playgroundCompose);+ expect(targets).toEqual([+ { kind: "composeAll", line: 7 },+ { kind: "composeService", line: 8, service: "starrocks" },+ { kind: "composeService", line: 24, service: "minio" },+ ]);+ expect(composeTargetAtLine(playgroundCompose, 7)).toEqual({ kind: "composeAll", line: 7 });+ expect(composeTargetAtLine(playgroundCompose, 11)).toEqual({+ kind: "composeService",+ line: 8,+ service: "starrocks",+ });+ expect(composeTargetAtLine(playgroundCompose, 26)).toEqual({+ kind: "composeService",+ line: 24,+ service: "minio",+ });+ });+});diff --git a/src/platform/fileOps.ts b/src/platform/fileOps.tsindex 25edf6356..76658f692 100644--- a/src/platform/fileOps.ts+++ b/src/platform/fileOps.ts@@ -3,6 +3,8 @@* file templates), as opposed to changes seen by the file watcher. VCS uses* this for Settings › Version Control › Confirmation.*/+import type { FileMove } from "./ipc";+export interface FileOperation {kind: "created" | "deleted";paths: string[];@@ -25,3 +27,21 @@ export function onFileOperation(listener: Listener): () => void {listeners.add(listener);return () => listeners.delete(listener);}++const moveListeners = new Set<(moves: readonly FileMove[]) => void | Promise<void>>();++/** Explicit moves (including Undo), before editors reopen at their new paths. */+export async function notifyFilesMoved(moves: readonly FileMove[]): Promise<void> {+ for (const listener of moveListeners) {+ try {+ await listener(moves);+ } catch (e) {+ console.warn("file move listener failed", e);+ }+ }+}++export function onFilesMoved(listener: (moves: readonly FileMove[]) => void | Promise<void>): () => void {+ moveListeners.add(listener);+ return () => moveListeners.delete(listener);+}diff --git a/src/platform/locales/text/en.json b/src/platform/locales/text/en.jsonindex b687d1ff8..8d7bdeae5 100644--- a/src/platform/locales/text/en.json+++ b/src/platform/locales/text/en.json@@ -807,5 +807,12 @@"Toggle Boolean Cell": "Toggle Boolean Cell","Toggle {name}": "Toggle {name}","true": "true",- "false": "false"+ "false": "false",+ "This file was auto-detected as a Docker Compose configuration based on its content": "This file was auto-detected as a Docker Compose configuration based on its content",+ "Not a Compose file": "Not a Compose file",+ "Keep as Docker Compose": "Keep as Docker Compose",+ "Set Docker Compose File Detection": "Set Docker Compose File Detection",+ "Could not save Docker Compose file detection": "Could not save Docker Compose file detection",+ "Compose Up": "Compose Up",+ "Start the service at the caret, or all services in the active Docker Compose file": "Start the service at the caret, or all services in the active Docker Compose file"}diff --git a/src/platform/locales/text/zh.json b/src/platform/locales/text/zh.jsonindex 5ebd72d46..cb9c8cc2d 100644--- a/src/platform/locales/text/zh.json+++ b/src/platform/locales/text/zh.json@@ -7141,5 +7141,12 @@"Toggle Boolean Cell": "切换布尔单元格","Toggle {name}": "切换 {name}","true": "真",- "false": "假"+ "false": "假",+ "This file was auto-detected as a Docker Compose configuration based on its content": "根据文件内容自动识别为 Docker Compose 配置",+ "Not a Compose file": "不是 Compose 文件",+ "Keep as Docker Compose": "保留为 Docker Compose",+ "Set Docker Compose File Detection": "设置 Docker Compose 文件识别",+ "Could not save Docker Compose file detection": "无法保存 Docker Compose 文件识别设置",+ "Compose Up": "Compose 启动",+ "Start the service at the caret, or all services in the active Docker Compose file": "启动光标处的服务,或当前 Docker Compose 文件中的所有服务"}diff --git a/src/ui/icons.tsx b/src/ui/icons.tsxindex ef249bc2f..f72c6f5e4 100644--- a/src/ui/icons.tsx+++ b/src/ui/icons.tsx@@ -961,7 +961,7 @@ const FILE_NAMES = table({/** Name patterns, tried in order (lower-case names). */const NAME_PATTERNS: readonly (readonly [RegExp, IconName])[] = [[/^(dockerfile|containerfile)[.-]/, "file-docker"],- [/^(docker-)?compose([.-][\w-]+)?\.ya?ml$/, "file-docker"],+ [/^.*compose.*\.ya?ml$/, "file-docker"],[/^\.env(\.|$)/, "file-dotenv"],[/^(licen[cs]e|copying)(-[\w.-]+|\.(md|txt|rst))?$/, "file-license"],[/^requirements([.-][\w.-]*)?\.(txt|in)$/, "file-requirements"],@@ -1075,15 +1075,20 @@ export function setFileIconOverride(resolve: ((fileName: string) => IconName | n}/** Icons for particular files (plugin `fileIcons`), newest first: after the user's, before the icon theme's. */-let fileIconProviders: ReadonlyArray<(fileName: string) => string | null> = [];+let fileIconProviders: ReadonlyArray<(fileName: string, path: string | null) => string | null> = [];-/** Adds a file icon provider (an `ext:` icon name or null); the returned function removes it. */-export function addFileIconProvider(resolve: (fileName: string) => string | null): () => void {- fileIconProviders = [resolve, ...fileIconProviders];+/** Bumps the file-icon revision so mounted trees and editor tabs re-resolve icons. */+export function bumpFileIconRevision() {useFileIconRevision.setState((n) => n + 1, true);+}++/** Adds a file icon provider (an `ext:` or built-in icon name or null); the returned function removes it. */+export function addFileIconProvider(resolve: (fileName: string, path: string | null) => string | null): () => void {+ fileIconProviders = [resolve, ...fileIconProviders];+ bumpFileIconRevision();return () => {fileIconProviders = fileIconProviders.filter((p) => p !== resolve);- useFileIconRevision.setState((n) => n + 1, true);+ bumpFileIconRevision();};}@@ -1092,7 +1097,7 @@ export function fileIconName(fileName: string, path: string | null = null): Iconconst custom = iconOverride?.(fileName);if (custom) return custom;for (const provide of fileIconProviders) {- const icon = provide(fileName);+ const icon = provide(fileName, path);if (icon && iconPath(icon)) return icon as IconName;}const themed = fileIconTheme?.file(fileName, path);