Порівняти коміти

...
Автор SHA1 Повідомлення Дата
l0ng-ai 0301d2407d feat(docker): run Dockerfile and Docker Image containers in the background
Dockerfile (when it runs the built image) and Docker Image run configurations get Run in
the background (-d), as Docker Compose has: the container is started detached (a previous
one of the same name is removed first) and the Run window follows docker logs. Stop ends
only the log follower, so the container keeps running. Unchecked, the command lines are
unchanged.

Fixes #7180
2026-12-01 18:05:53 +08:00
3 змінених файлів з 168 додано та 10 видалено

No files matched your search

+16
Переглянути файл
@@ -62,6 +62,22 @@ fn round_trip() {
assert!(!loaded[0].detected);
}
#[test]
fn docker_detach_round_trips_in_project_params() {
let dir = tempfile::tempdir().unwrap();
let mut configs = sample();
for (config, (kind, detach)) in configs.iter_mut().zip([("docker-dockerfile", "true"), ("docker-image", "false")]) {
config.kind = kind.into();
config.extras.params.insert("detach".into(), detach.into());
}
save_user_configs(dir.path(), &configs).unwrap();
let project = fs::read_to_string(user_configs_path(dir.path())).unwrap();
assert!(project.contains("params = { detach = \"true\" }"), "{project}");
assert!(project.contains("params = { detach = \"false\" }"), "{project}");
assert_eq!(load_user_configs(dir.path()).unwrap(), configs);
}
#[test]
fn preserves_unrelated_content() {
let dir = tempfile::tempdir().unwrap();
+137
Переглянути файл
@@ -0,0 +1,137 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { formParams, withParams } from "@/features/run/types";
import { hostOs } from "@/platform/remote";
import { dockerfileType, dockerImageType, typedConfig } from "./runTypes";
vi.mock("@/platform/remote", async (original) => ({
...(await original<typeof import("@/platform/remote")>()),
hostOs: vi.fn(),
}));
const dockerfileParams = {
dockerfile: "docker files/Dockerfile",
tag: "sample/app:latest",
target: "production",
buildArgs: "MODE=production",
buildOptions: "--no-cache",
runImage: "true",
containerName: "sample-app",
ports: "8080:80",
volumes: "./app data:/data",
containerEnv: "MODE=production",
runOptions: "--network bridge",
command: 'serve --title "Sample app"',
};
const imageParams = {
image: "registry.example.com/team/postgres:16",
pull: "true",
ports: "5432:5432",
containerEnv: "APP_NAME=Local database",
};
const foregroundSettings: Record<string, string>[] = [{}, { detach: "false" }];
describe.each([
{
os: "linux" as const,
build:
"docker build -f 'docker files/Dockerfile' -t sample/app:latest --target production --build-arg MODE=production --no-cache 'docker files'",
buildOnly: "docker build -f 'docker files/Dockerfile' -t sample/app:latest 'docker files'",
remove: ">/dev/null 2>&1;",
appArgs: "-p 8080:80 -v './app data:/data' -e MODE=production --network bridge sample/app:latest",
imageArgs: "--pull always -p 5432:5432 -e 'APP_NAME=Local database' registry.example.com/team/postgres:16",
},
{
os: "windows" as const,
build:
'docker build -f "docker files/Dockerfile" -t sample/app:latest --target production --build-arg MODE=production --no-cache "docker files"',
buildOnly: 'docker build -f "docker files/Dockerfile" -t sample/app:latest "docker files"',
remove: ">nul 2>&1 &",
appArgs: '-p 8080:80 -v "./app data:/data" -e MODE=production --network bridge sample/app:latest',
imageArgs: '--pull always -p 5432:5432 -e "APP_NAME=Local database" registry.example.com/team/postgres:16',
},
])("Docker run command lines on $os", ({ os, build, buildOnly, remove, appArgs, imageArgs }) => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue(os));
it.each(foregroundSettings)("runs a Dockerfile in the foreground with %j", (detach) => {
expect(dockerfileType.commandLine({ ...dockerfileParams, ...detach })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run --name sample-app ${appArgs} serve --title "Sample app")`,
args: [],
cwd: null,
stop: "docker stop sample-app",
});
});
it.each(foregroundSettings)("runs a Docker Image in the foreground with %j", (detach) => {
expect(dockerImageType.commandLine({ ...imageParams, ...detach })).toEqual({
command: `(docker rm -f postgres ${remove} docker run --name postgres ${imageArgs})`,
args: [],
cwd: null,
stop: "docker stop postgres",
});
});
it("runs the built image in the background and follows its logs", () => {
expect(dockerfileType.commandLine({ ...dockerfileParams, detach: "true" })).toEqual({
command: `${build} && (docker rm -f sample-app ${remove} docker run -d --name sample-app ${appArgs} serve --title "Sample app") && docker logs --tail 500 -f sample-app`,
args: [],
cwd: null,
stop: null,
});
});
it("runs a Docker Image in the background and follows logs using its derived name", () => {
expect(dockerImageType.commandLine({ ...imageParams, containerName: " ", detach: "true" })).toEqual({
command: `(docker rm -f postgres ${remove} docker run -d --name postgres ${imageArgs}) && docker logs --tail 500 -f postgres`,
args: [],
cwd: null,
stop: null,
});
});
it("builds without starting a container when Run built image is off", () => {
expect(
dockerfileType.commandLine({
dockerfile: dockerfileParams.dockerfile,
tag: dockerfileParams.tag,
detach: "true",
}),
).toEqual({ command: buildOnly, args: [], cwd: null });
});
});
describe("Docker detach setting", () => {
beforeEach(() => vi.mocked(hostOs).mockReturnValue("linux"));
it("offers the checkbox only when the configuration starts a container", () => {
const dockerfile = dockerfileType.fields.find((field) => field.key === "detach");
const image = dockerImageType.fields.find((field) => field.key === "detach");
const checkbox = { label: "Run in the background (-d)", control: "checkbox" };
expect(dockerfile).toMatchObject(checkbox);
expect(dockerfile?.visible?.({ runImage: "true" })).toBe(true);
expect(dockerfile?.visible?.({ runImage: "false" })).toBe(false);
expect(image).toMatchObject(checkbox);
expect(image?.visible).toBeUndefined();
});
it.each([
{ type: dockerfileType, params: dockerfileParams, name: "sample-app" },
{ type: dockerImageType, params: imageParams, name: "postgres" },
])("round-trips detach through saved $type.label params and the run form", ({ type, params, name }) => {
const foreground = typedConfig(type, "user:docker", "Docker", params);
expect(foreground.stopCommand).toBe(`docker stop ${name}`);
const detached = withParams(foreground, { ...params, detach: "true" }, type);
expect(detached.params?.detach).toBe("true");
expect(detached.stopCommand).toBeUndefined();
const reopened = formParams(detached, type)!;
expect(reopened.detach).toBe("true");
expect(withParams(detached, reopened, type)).toEqual(detached);
expect(withParams(detached, { ...reopened, detach: "false" }, type)).toEqual({
...foreground,
params: { ...params, detach: "false" },
});
});
});
+15 -10
Переглянути файл
@@ -3,8 +3,8 @@
* Dockerfile (build the image, then run a container from it), Docker Image (run
* a container from an image) and Docker Compose (`up` the selected services).
* They launch docker command lines in the Run tool window against the Docker
* connection chosen from the Services tool window's connections; Stop stops the
* container (`docker stop`) or takes the Compose project down.
* connection chosen from the Services tool window's connections. Stop stops the
* attached container or takes the Compose project down. Detached containers keep running.
*/
import { splitCommandLine } from "@/platform/commandLine";
import { call, commands, type RunConfig } from "@/platform/ipc";
@@ -62,21 +62,23 @@ export function containerName(p: Readonly<Record<string, string>>, image: string
}
/**
* Removes a previous container of the same name (IDEA redeploys over it), then runs
* the new one attached, so its output is the run's output.
* Redeploys a container of the same name. Detached runs follow the new container's logs.
*/
function runContainer(name: string, image: string, p: Readonly<Record<string, string>>, windows: boolean): string {
const remove = `${line(["docker", "rm", "-f", name], windows)} ${windows ? ">nul 2>&1 &" : ">/dev/null 2>&1;"}`;
const detach = on(p.detach);
const run = [
"docker",
"run",
...(detach ? ["-d"] : []),
"--name",
name,
...(on(p.pull) ? ["--pull", "always"] : []),
...containerArgs(p),
image,
];
return `${remove} ${line([...run], windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""}`;
const redeploy = `(${remove} ${line(run, windows)}${p.command?.trim() ? ` ${p.command.trim()}` : ""})`;
return detach ? `${redeploy} && ${line(["docker", "logs", "--tail", "500", "-f", name], windows)}` : redeploy;
}
/** The servers the form offers: the saved connections, else the default daemon ("Docker"). */
@@ -97,8 +99,11 @@ const connectionField = {
},
};
const detachField = { key: "detach", label: "Run in the background (-d)", control: "checkbox" } as const;
const containerFields: RunConfigTypeContribution["fields"] = [
{ key: "containerName", label: "Container name", mono: true, placeholder: "Derived from the image" },
detachField,
{ key: "ports", label: "Bind ports", mono: true, placeholder: "8080:80, 5005:5005" },
{ key: "volumes", label: "Bind mounts", mono: true, placeholder: "./data:/data; cache:/root/.cache" },
{ key: "containerEnv", label: "Container environment", mono: true, placeholder: "KEY=value; OTHER=value" },
@@ -191,10 +196,10 @@ export const dockerfileType: RunConfigTypeContribution = {
if (!on(p.runImage)) return { command: line(build, windows), args: [], cwd: null };
const name = containerName(p, tag);
return {
command: `${line(build, windows)} && (${runContainer(name, tag, p, windows)})`,
command: `${line(build, windows)} && ${runContainer(name, tag, p, windows)}`,
args: [],
cwd: null,
stop: line(["docker", "stop", name], windows),
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -221,10 +226,10 @@ export const dockerImageType: RunConfigTypeContribution = {
const image = p.image?.trim() ?? "";
const name = containerName(p, image);
return {
command: `(${runContainer(name, image, p, windows)})`,
command: runContainer(name, image, p, windows),
args: [],
cwd: null,
stop: line(["docker", "stop", name], windows),
stop: on(p.detach) ? null : line(["docker", "stop", name], windows),
};
},
prepareLaunch: withConnection,
@@ -249,7 +254,7 @@ export const dockerComposeType: RunConfigTypeContribution = {
},
{ key: "services", label: "Services", mono: true, placeholder: "All services" },
{ key: "project", label: "Project name", mono: true, placeholder: "The folder name" },
{ key: "detach", label: "Run in the background (-d)", control: "checkbox" },
detachField,
{ key: "build", label: "Build images before starting (--build)", control: "checkbox" },
{ key: "upOptions", label: "Up options", mono: true, placeholder: "e.g. --force-recreate --remove-orphans" },
],