Skip to content

Commit ce9cef9

Browse files
committed
refactor(compose): refine profile handling and add unit tests
Refines Compose profile behavior: - Localize user-facing shared profile indicator in container description. - Re-order command arguments in composeGroup to simplify call sites. - Use gated debug logging and prevent raw output secret exposure. - Resolve relative compose config file paths to basenames. - Add comprehensive unit tests for profile scoping and file helpers. Signed-off-by: h3110Fr13nd <vijaysinghkushwaha3737@gmail.com>
1 parent 99221c8 commit ce9cef9

6 files changed

Lines changed: 136 additions & 25 deletions

File tree

‎extensions/vscode-containers/src/commands/containers/composeGroup.ts‎

Lines changed: 24 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -23,30 +23,30 @@ export async function composeGroupLogs(context: IActionContext, node: ComposeGro
2323

2424
if (!workingDirectory) {
2525
context.errorHandling.suppressReportIssue = true;
26-
throw new Error(l10n.t('Unable to determine compose project info for container group \'{0}\'.', node.label));
26+
throw new Error(l10n.t('Unable to determine compose project info for group \'{0}\'.', getProjectLabel(node)));
2727
}
2828

2929
const folder = workspace.getWorkspaceFolder(Uri.file(workingDirectory)) ?? Uri.file(workingDirectory);
3030

3131
const composeFilesString = options.files?.map(file => `-f "${file}"`).join(' ');
3232
return selectComposeLogsCommand(context, folder, composeFilesString, options.projectName, options.environmentFile);
33-
}, node, { follow: true, tail: 1000 }, 'logs');
33+
}, node, 'logs', { follow: true, tail: 1000 });
3434
}
3535

3636
export async function composeGroupStart(context: IActionContext, node: ComposeGroupNode): Promise<void> {
37-
return composeGroup(context, (client, options) => client.start(options), node, undefined, 'start');
37+
return composeGroup(context, (client, options) => client.start(options), node, 'start');
3838
}
3939

4040
export async function composeGroupStop(context: IActionContext, node: ComposeGroupNode): Promise<void> {
41-
return composeGroup(context, (client, options) => client.stop(options), node, undefined, 'stop');
41+
return composeGroup(context, (client, options) => client.stop(options), node, 'stop');
4242
}
4343

4444
export async function composeGroupRestart(context: IActionContext, node: ComposeGroupNode): Promise<void> {
45-
return composeGroup(context, (client, options) => client.restart(options), node, undefined, 'restart');
45+
return composeGroup(context, (client, options) => client.restart(options), node, 'restart');
4646
}
4747

4848
export async function composeGroupDown(context: IActionContext, node: ComposeGroupNode): Promise<void> {
49-
return composeGroup(context, (client, options) => client.down(options), node, undefined, 'down');
49+
return composeGroup(context, (client, options) => client.down(options), node, 'down');
5050
}
5151

5252
type AdditionalOptions<TOptions extends CommonOrchestratorCommandOptions> = Omit<TOptions, keyof CommonOrchestratorCommandOptions>;
@@ -55,8 +55,8 @@ async function composeGroup<TOptions extends CommonOrchestratorCommandOptions>(
5555
context: IActionContext,
5656
composeCommandCallback: (client: IContainerOrchestratorClient, options: TOptions) => Promise<VoidCommandResponse>,
5757
node: ComposeGroupNode,
58-
additionalOptions?: AdditionalOptions<TOptions>,
59-
commandName: string = '<command>'
58+
commandName: string = '<command>',
59+
additionalOptions?: AdditionalOptions<TOptions>
6060
): Promise<void> {
6161
if (!node) {
6262
await ext.containersTree.refresh(context);
@@ -75,7 +75,7 @@ async function composeGroup<TOptions extends CommonOrchestratorCommandOptions>(
7575

7676
if (!workingDirectory || !orchestratorFiles || !projectName) {
7777
context.errorHandling.suppressReportIssue = true;
78-
throw new Error(l10n.t('Unable to determine compose project info for container group \'{0}\'.', node.label));
78+
throw new Error(l10n.t('Unable to determine compose project info for group \'{0}\'.', getProjectLabel(node)));
7979
}
8080

8181
let profileArg: string[] | undefined;
@@ -130,7 +130,16 @@ async function composeGroup<TOptions extends CommonOrchestratorCommandOptions>(
130130
* parsing, so we can still locate a container in the group from the list labels, but we
131131
* must `inspect` it to recover the accurate, verbatim label values (compose files, etc).
132132
*/
133-
async function getComposeGroupLabels(node: ComposeGroupNode): Promise<{ [key: string]: string } | undefined> {
133+
// Exported only for unit testing; not intended to be called outside this module.
134+
export function getProjectLabel(node: ComposeGroupNode): string {
135+
if (node instanceof ComposeProfileGroupTreeItem && node.parent?.label) {
136+
return node.parent.label;
137+
}
138+
return node.label;
139+
}
140+
141+
// Exported only for unit testing; not intended to be called outside this module.
142+
export function findContainerWithComposeConfig(node: ComposeGroupNode): ContainerTreeItem | undefined {
134143
// Find a container in the group that carries the compose project config files label.
135144
// For ComposeProfileGroupTreeItem the direct children are ContainerTreeItem instances.
136145
// For ContainerGroupTreeItem with profile sub-groups the direct children may be
@@ -151,6 +160,11 @@ async function getComposeGroupLabels(node: ComposeGroupNode): Promise<{ [key: st
151160
}
152161
}
153162

163+
return container;
164+
}
165+
166+
async function getComposeGroupLabels(node: ComposeGroupNode): Promise<{ [key: string]: string } | undefined> {
167+
const container = findContainerWithComposeConfig(node);
154168
if (!container) {
155169
return undefined;
156170
}

‎extensions/vscode-containers/src/test/commands/composeGroup.test.ts‎

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,10 @@
44
*--------------------------------------------------------------------------------------------*/
55

66
import { expect } from 'chai';
7-
import { getComposeEnvFile, getComposeFiles, getComposeProjectName, getComposeWorkingDirectory } from '../../commands/containers/composeGroup';
7+
import { findContainerWithComposeConfig, getComposeEnvFile, getComposeFiles, getComposeProjectName, getComposeWorkingDirectory, getProjectLabel } from '../../commands/containers/composeGroup';
8+
import { ComposeProfileGroupTreeItem } from '../../tree/containers/ComposeProfileGroupTreeItem';
9+
import { ContainerGroupTreeItem } from '../../tree/containers/ContainerGroupTreeItem';
10+
import { ContainerTreeItem } from '../../tree/containers/ContainerTreeItem';
811

912
suite("(unit) composeGroup", () => {
1013
suite("getComposeFiles", () => {
@@ -123,4 +126,37 @@ suite("(unit) composeGroup", () => {
123126
expect(getComposeEnvFile({})).to.be.undefined;
124127
});
125128
});
129+
130+
suite("profile sub-group utilities", () => {
131+
test("getProjectLabel returns parent label for ComposeProfileGroupTreeItem", () => {
132+
const parent = Object.create(ContainerGroupTreeItem.prototype) as ContainerGroupTreeItem;
133+
Object.defineProperty(parent, 'label', { value: 'my-compose-project' });
134+
135+
const profileNode = Object.create(ComposeProfileGroupTreeItem.prototype) as ComposeProfileGroupTreeItem;
136+
Object.defineProperty(profileNode, 'label', { value: 'dev-profile' });
137+
Object.defineProperty(profileNode, 'parent', { value: parent });
138+
139+
expect(getProjectLabel(profileNode)).to.equal('my-compose-project');
140+
expect(getProjectLabel(parent)).to.equal('my-compose-project');
141+
});
142+
143+
test("findContainerWithComposeConfig searches direct children and profile sub-groups", () => {
144+
const containerWithLabels = Object.create(ContainerTreeItem.prototype) as ContainerTreeItem;
145+
Object.defineProperty(containerWithLabels, 'labels', {
146+
value: { 'com.docker.compose.project.config_files': '/path/to/docker-compose.yml' }
147+
});
148+
149+
const containerWithoutLabels = Object.create(ContainerTreeItem.prototype) as ContainerTreeItem;
150+
Object.defineProperty(containerWithoutLabels, 'labels', { value: {} });
151+
152+
const profileGroup = Object.create(ComposeProfileGroupTreeItem.prototype) as ComposeProfileGroupTreeItem;
153+
Object.defineProperty(profileGroup, 'ChildTreeItems', { value: [containerWithoutLabels, containerWithLabels] });
154+
155+
const rootGroup = Object.create(ContainerGroupTreeItem.prototype) as ContainerGroupTreeItem;
156+
Object.defineProperty(rootGroup, 'ChildTreeItems', { value: [profileGroup] });
157+
158+
const result = findContainerWithComposeConfig(rootGroup);
159+
expect(result).to.equal(containerWithLabels);
160+
});
161+
});
126162
});
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
/*---------------------------------------------------------------------------------------------
2+
* Copyright (c) Microsoft Corporation. All rights reserved.
3+
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
4+
*--------------------------------------------------------------------------------------------*/
5+
6+
import { expect } from 'chai';
7+
import { getComposeProfilesForContainer, getComposeSourceFiles } from '../../tree/containers/composeProfiles';
8+
import { ContainerTreeItem } from '../../tree/containers/ContainerTreeItem';
9+
10+
suite("(unit) composeProfiles", () => {
11+
suite("getComposeSourceFiles", () => {
12+
test("Reduces relative paths to their basename", () => {
13+
const labels = {
14+
'com.docker.compose.project.config_files': 'subdir/docker-compose.base.yml,subdir/docker-compose.local.yml',
15+
};
16+
17+
const result = getComposeSourceFiles(labels);
18+
expect(result).to.deep.equal(['docker-compose.base.yml', 'docker-compose.local.yml']);
19+
});
20+
21+
test("Returns absolute paths unchanged", () => {
22+
const labels = {
23+
'com.docker.compose.project.config_files': '/abs/docker-compose.yml',
24+
};
25+
26+
const result = getComposeSourceFiles(labels);
27+
expect(result).to.deep.equal(['/abs/docker-compose.yml']);
28+
});
29+
});
30+
31+
suite("getComposeProfilesForContainer", () => {
32+
test("Returns profiles assigned to the container service", () => {
33+
const container = Object.create(ContainerTreeItem.prototype) as ContainerTreeItem;
34+
Object.defineProperty(container, 'labels', {
35+
value: { 'com.docker.compose.service': 'web' }
36+
});
37+
38+
const serviceProfiles = new Map<string, string[]>([
39+
['web', ['frontend', 'debug']],
40+
['db', ['backend']]
41+
]);
42+
43+
const profiles = getComposeProfilesForContainer(container, serviceProfiles);
44+
expect(profiles).to.deep.equal(['frontend', 'debug']);
45+
});
46+
47+
test("Returns empty array when service has no assigned profiles", () => {
48+
const container = Object.create(ContainerTreeItem.prototype) as ContainerTreeItem;
49+
Object.defineProperty(container, 'labels', {
50+
value: { 'com.docker.compose.service': 'cache' }
51+
});
52+
53+
const serviceProfiles = new Map<string, string[]>([
54+
['web', ['frontend']]
55+
]);
56+
57+
const profiles = getComposeProfilesForContainer(container, serviceProfiles);
58+
expect(profiles).to.deep.equal([]);
59+
});
60+
});
61+
});

‎extensions/vscode-containers/src/tree/containers/ContainerGroupTreeItem.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ export class ContainerGroupTreeItem extends LocalGroupTreeItemBase<DockerContain
7777
const composeFiles = labels ? getComposeSourceFiles(labels) : undefined;
7878
const projectName = labels?.['com.docker.compose.project'];
7979

80-
ext.outputChannel.appendLine(`[DEBUG] ContainerGroupTreeItem: workingDirectory=${workingDirectory}, composeFiles=${JSON.stringify(composeFiles)}`);
80+
ext.outputChannel.debug(`ContainerGroupTreeItem: workingDirectory=${workingDirectory}, composeFiles=${JSON.stringify(composeFiles)}`);
8181

8282
if (!workingDirectory || !composeFiles?.length) {
8383
return super.loadMoreChildrenImpl(clearCache);
@@ -99,11 +99,9 @@ export class ContainerGroupTreeItem extends LocalGroupTreeItemBase<DockerContain
9999
}
100100

101101
for (const profile of profiles) {
102-
if (!profileContainers.has(profile)) {
103-
profileContainers.set(profile, [container.containerItem as DockerContainerInfo]);
104-
} else {
105-
profileContainers.set(profile, [...profileContainers.get(profile)!, container.containerItem as DockerContainerInfo]);
106-
}
102+
const existing = profileContainers.get(profile) ?? [];
103+
existing.push(container.containerItem as DockerContainerInfo);
104+
profileContainers.set(profile, existing);
107105
}
108106
}
109107

‎extensions/vscode-containers/src/tree/containers/ContainerTreeItem.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ export class ContainerTreeItem extends ToolTipParentTreeItem implements MultiSel
7171
public get description(): string | undefined {
7272
let desc = ext.containersRoot.getTreeItemDescription(this._item);
7373
if (this.composeProfiles.length > 1) {
74-
desc = desc ? `${desc} (Shared)` : '(Shared)';
74+
desc = desc ? vscode.l10n.t('{0} (Shared)', desc) : vscode.l10n.t('(Shared)');
7575
}
7676
return desc;
7777
}

‎extensions/vscode-containers/src/tree/containers/composeProfiles.ts‎

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
44
*--------------------------------------------------------------------------------------------*/
55

6+
import * as path from 'path';
67
import { CommandLineArgs, ShellQuoting } from '@microsoft/vscode-processutils';
78
import { ext } from '../../extensionVariables';
89
import { isComposeV2ableOrchestratorClient } from '../../runtimes/OrchestratorRuntimeManager';
@@ -17,6 +18,7 @@ import { ContainerTreeItem } from './ContainerTreeItem';
1718
export function getComposeSourceFiles(labels: { [key: string]: string }): string[] | undefined {
1819
return labels['com.docker.compose.project.config_files']
1920
?.split(',')
21+
?.map(f => path.isAbsolute(f) ? f : path.parse(f).base)
2022
?.filter(file => !!file);
2123
}
2224

@@ -64,24 +66,24 @@ export async function getComposeServiceProfiles(
6466
'json',
6567
];
6668

67-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles args: ${client.commandName} ${JSON.stringify(args)} in cwd: ${workingDirectory}`);
69+
ext.outputChannel.debug(`getComposeServiceProfiles args: ${client.commandName} ${JSON.stringify(args)} in cwd: ${workingDirectory}`);
6870

6971
const { stdout } = await execAsync(client.commandName, args, {
7072
cwd: workingDirectory,
7173
allowUnsafeExecutablePath: true,
7274
});
7375

74-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles stdout: ${stdout?.substring(0, 200)}...`);
76+
ext.outputChannel.debug(`getComposeServiceProfiles stdout length: ${stdout?.length ?? 0}`);
7577

7678
if (!stdout) {
77-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles stdout was empty.`);
79+
ext.outputChannel.debug('getComposeServiceProfiles stdout was empty.');
7880
return undefined;
7981
}
8082

8183
// Extract JSON to avoid SyntaxError if docker compose prints warnings (like 'Found orphan containers') to stdout
8284
const jsonMatch = stdout.match(/\{[\s\S]*\}/);
8385
if (!jsonMatch) {
84-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles failed to find JSON in stdout.`);
86+
ext.outputChannel.debug('getComposeServiceProfiles failed to find JSON in stdout.');
8587
return undefined;
8688
}
8789

@@ -94,7 +96,7 @@ export async function getComposeServiceProfiles(
9496
};
9597

9698
if (!config.services) {
97-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles JSON did not contain 'services' property.`);
99+
ext.outputChannel.debug('getComposeServiceProfiles JSON did not contain \'services\' property.');
98100
return undefined;
99101
}
100102

@@ -109,10 +111,10 @@ export async function getComposeServiceProfiles(
109111
}
110112
}
111113

112-
ext.outputChannel.appendLine(`[DEBUG] getComposeServiceProfiles foundProfiles: ${foundProfiles}`);
114+
ext.outputChannel.debug(`getComposeServiceProfiles foundProfiles: ${foundProfiles}`);
113115
return foundProfiles ? serviceProfiles : undefined;
114116
} catch (err) {
115-
ext.outputChannel.error(`getComposeServiceProfiles failed: ${err}`);
117+
ext.outputChannel.debug(`getComposeServiceProfiles failed: ${String(err)}`);
116118
// The `--format json` flag requires Docker Compose v2.15+; if it fails (older versions,
117119
// unsupported runtimes, JSON parse errors, etc.) we fall back to flat service listing
118120
// with no profile grouping.

0 commit comments

Comments
 (0)