Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Made Some ACR Commands Work #4027

Merged
merged 6 commits into from
Aug 9, 2023
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -486,7 +486,7 @@
},
{
"command": "vscode-docker.registries.azure.deleteRegistry",
"when": "view == dockerRegistries && viewItem == azure;DockerV2;Registry;",
"when": "view == dockerRegistries && viewItem =~ /azureContainerRegistry/i",
"group": "regs_reg_2_destructive@1"
},
{
Expand All @@ -496,7 +496,7 @@
},
{
"command": "vscode-docker.registries.azure.deleteRepository",
"when": "view == dockerRegistries && viewItem == azure;DockerV2;Repository;",
"when": "view == dockerRegistries && viewItem =~ /azureContainerRepository/i",
"group": "regs_repo_2_destructive@1"
},
{
Expand Down
160 changes: 80 additions & 80 deletions src/commands/images/buildImage.ts
Original file line number Diff line number Diff line change
@@ -1,80 +1,80 @@
// /*---------------------------------------------------------------------------------------------
// * Copyright (c) Microsoft Corporation. All rights reserved.
// * Licensed under the MIT License. See LICENSE.md in the project root for license information.
// *--------------------------------------------------------------------------------------------*/

// import { IActionContext, UserCancelledError } from "@microsoft/vscode-azext-utils";
// import * as path from "path";
// import * as vscode from "vscode";
// import { ext } from "../../extensionVariables";
// import { TaskCommandRunnerFactory } from "../../runtimes/runners/TaskCommandRunnerFactory";
// import { getOfficialBuildTaskForDockerfile } from "../../tasks/TaskHelper";
// import { getValidImageNameFromPath } from "../../utils/getValidImageName";
// import { delay } from "../../utils/promiseUtils";
// import { quickPickDockerFileItem } from "../../utils/quickPickFile";
// import { quickPickWorkspaceFolder } from "../../utils/quickPickWorkspaceFolder";
// import { selectBuildCommand } from "../selectCommandTemplate";
// import { addImageTaggingTelemetry, getTagFromUserInput } from "./tagImage";

// const tagRegex: RegExp = /\$\{tag\}/i;

// export async function buildImage(context: IActionContext, dockerFileUri: vscode.Uri | undefined): Promise<void> {
// if (!vscode.workspace.isTrusted) {
// throw new UserCancelledError('enforceTrust');
// }

// const configOptions: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('docker');
// const defaultContextPath = configOptions.get('imageBuildContextPath', '');

// let rootFolder: vscode.WorkspaceFolder;
// if (dockerFileUri) {
// rootFolder = vscode.workspace.getWorkspaceFolder(dockerFileUri);
// }

// rootFolder = rootFolder || await quickPickWorkspaceFolder(context, vscode.l10n.t('To build Docker files you must first open a folder or workspace in VS Code.'));

// const dockerFileItem = await quickPickDockerFileItem(context, dockerFileUri, rootFolder);
// const task = await getOfficialBuildTaskForDockerfile(context, dockerFileItem.absoluteFilePath, rootFolder);

// if (task) {
// await vscode.tasks.executeTask(task);
// } else {
// const contextPath: string = defaultContextPath || dockerFileItem.relativeFolderPath;

// const terminalCommand = await selectBuildCommand(
// context,
// rootFolder,
// dockerFileItem.relativeFilePath,
// contextPath
// );

// // Replace '${tag}' if needed. Tag is a special case because we don't want to prompt unless necessary, so must manually replace it.
// if (tagRegex.test(terminalCommand.command)) {
// const absFilePath: string = path.join(rootFolder.uri.fsPath, dockerFileItem.relativeFilePath);
// const dockerFileKey = `buildTag_${absFilePath}`;
// const prevImageName: string | undefined = ext.context.workspaceState.get(dockerFileKey);

// // Get imageName based previous entries, else on name of subfolder containing the Dockerfile
// const suggestedImageName = prevImageName || getValidImageNameFromPath(dockerFileItem.absoluteFolderPath, 'latest');

// // Temporary work-around for vscode bug where valueSelection can be messed up if a quick pick is followed by a showInputBox
// await delay(500);

// addImageTaggingTelemetry(context, suggestedImageName, '.before');
// const imageName: string = await getTagFromUserInput(context, suggestedImageName);
// addImageTaggingTelemetry(context, imageName, '.after');

// await ext.context.workspaceState.update(dockerFileKey, imageName);
// terminalCommand.command = terminalCommand.command.replace(tagRegex, imageName);
// }

// const client = await ext.runtimeManager.getClient();
// const taskCRF = new TaskCommandRunnerFactory({
// taskName: client.displayName,
// workspaceFolder: rootFolder,
// focus: true,
// });

// await taskCRF.getCommandRunner()(terminalCommand);
// }
// }
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { IActionContext, UserCancelledError } from "@microsoft/vscode-azext-utils";
import * as path from "path";
import * as vscode from "vscode";
import { ext } from "../../extensionVariables";
import { TaskCommandRunnerFactory } from "../../runtimes/runners/TaskCommandRunnerFactory";
import { getOfficialBuildTaskForDockerfile } from "../../tasks/TaskHelper";
import { getValidImageNameFromPath } from "../../utils/getValidImageName";
import { delay } from "../../utils/promiseUtils";
import { quickPickDockerFileItem } from "../../utils/quickPickFile";
import { quickPickWorkspaceFolder } from "../../utils/quickPickWorkspaceFolder";
import { selectBuildCommand } from "../selectCommandTemplate";
import { addImageTaggingTelemetry, getTagFromUserInput } from "./tagImage";

const tagRegex: RegExp = /\$\{tag\}/i;

export async function buildImage(context: IActionContext, dockerFileUri: vscode.Uri | undefined): Promise<void> {
if (!vscode.workspace.isTrusted) {
throw new UserCancelledError('enforceTrust');
}

const configOptions: vscode.WorkspaceConfiguration = vscode.workspace.getConfiguration('docker');
const defaultContextPath = configOptions.get('imageBuildContextPath', '');

let rootFolder: vscode.WorkspaceFolder;
if (dockerFileUri) {
rootFolder = vscode.workspace.getWorkspaceFolder(dockerFileUri);
}

rootFolder = rootFolder || await quickPickWorkspaceFolder(context, vscode.l10n.t('To build Docker files you must first open a folder or workspace in VS Code.'));

const dockerFileItem = await quickPickDockerFileItem(context, dockerFileUri, rootFolder);
const task = await getOfficialBuildTaskForDockerfile(context, dockerFileItem.absoluteFilePath, rootFolder);

if (task) {
await vscode.tasks.executeTask(task);
} else {
const contextPath: string = defaultContextPath || dockerFileItem.relativeFolderPath;

const terminalCommand = await selectBuildCommand(
context,
rootFolder,
dockerFileItem.relativeFilePath,
contextPath
);

// Replace '${tag}' if needed. Tag is a special case because we don't want to prompt unless necessary, so must manually replace it.
if (tagRegex.test(terminalCommand.command)) {
const absFilePath: string = path.join(rootFolder.uri.fsPath, dockerFileItem.relativeFilePath);
const dockerFileKey = `buildTag_${absFilePath}`;
const prevImageName: string | undefined = ext.context.workspaceState.get(dockerFileKey);

// Get imageName based previous entries, else on name of subfolder containing the Dockerfile
const suggestedImageName = prevImageName || getValidImageNameFromPath(dockerFileItem.absoluteFolderPath, 'latest');

// Temporary work-around for vscode bug where valueSelection can be messed up if a quick pick is followed by a showInputBox
await delay(500);

addImageTaggingTelemetry(context, suggestedImageName, '.before');
const imageName: string = await getTagFromUserInput(context, suggestedImageName);
addImageTaggingTelemetry(context, imageName, '.after');

await ext.context.workspaceState.update(dockerFileKey, imageName);
terminalCommand.command = terminalCommand.command.replace(tagRegex, imageName);
}

const client = await ext.runtimeManager.getClient();
const taskCRF = new TaskCommandRunnerFactory({
taskName: client.displayName,
workspaceFolder: rootFolder,
focus: true,
});

await taskCRF.getCommandRunner()(terminalCommand);
}
}
194 changes: 97 additions & 97 deletions src/commands/images/tagImage.ts
Original file line number Diff line number Diff line change
@@ -1,97 +1,97 @@
// /*---------------------------------------------------------------------------------------------
// * Copyright (c) Microsoft Corporation. All rights reserved.
// * Licensed under the MIT License. See LICENSE.md in the project root for license information.
// *--------------------------------------------------------------------------------------------*/

// import { IActionContext, TelemetryProperties } from '@microsoft/vscode-azext-utils';
// import * as vscode from 'vscode';
// import { ext } from '../../extensionVariables';
// import { ImageTreeItem } from '../../tree/images/ImageTreeItem';
// import { UnifiedRegistryItem } from '../../tree/registries/UnifiedRegistryTreeDataProvider';

// export async function tagImage(context: IActionContext, node?: ImageTreeItem, registry?: UnifiedRegistryItem<unknown>): Promise<string> {
// if (!node) {
// await ext.imagesTree.refresh(context);
// node = await ext.imagesTree.showTreeItemPicker<ImageTreeItem>(ImageTreeItem.contextValue, {
// ...context,
// noItemFoundErrorMessage: vscode.l10n.t('No images are available to tag')
// });
// }

// addImageTaggingTelemetry(context, node.fullTag, '.before');
// const newTaggedName: string = await getTagFromUserInput(context, node.fullTag, ''); // TODO: review this later
// addImageTaggingTelemetry(context, newTaggedName, '.after');

// await ext.runWithDefaults(client =>
// client.tagImage({ fromImageRef: node.imageId, toImageRef: newTaggedName })
// );

// return newTaggedName;
// }

// export async function getTagFromUserInput(context: IActionContext, fullTag: string, baseImagePath?: string): Promise<string> {
// const opt: vscode.InputBoxOptions = {
// ignoreFocusOut: true,
// prompt: vscode.l10n.t('Tag image as...'),
// };

// if (fullTag.includes('/')) {
// opt.valueSelection = [0, fullTag.lastIndexOf('/')];
// } else if (baseImagePath) {
// fullTag = `${baseImagePath}/${fullTag}`;
// opt.valueSelection = [0, fullTag.lastIndexOf('/')];
// }

// opt.value = fullTag;

// return await context.ui.showInputBox(opt);
// }

// const KnownRegistries: { type: string, regex: RegExp }[] = [
// // Like username/path
// { type: 'dockerhub-namespace', regex: /^[^.:]+\/[^.:]+$/ },

// { type: 'dockerhub-dockerio', regex: /^docker.io.*\// },
// { type: 'github', regex: /ghcr\.io.*\// },
// { type: 'gitlab', regex: /gitlab.*\// },
// { type: 'ACR', regex: /azurecr\.io.*\// },
// { type: 'GCR', regex: /gcr\.io.*\// },
// { type: 'ECR', regex: /\.ecr\..*\// },
// { type: 'localhost', regex: /localhost:.*\// },

// // Has a port, probably a private registry
// { type: 'privateWithPort', regex: /:[0-9]+\// },

// // Match anything remaining
// { type: 'other', regex: /\// }, // has a slash
// { type: 'none', regex: /./ } // no slash
// ];

// export function addImageTaggingTelemetry(context: IActionContext, fullImageName: string, propertyPostfix: '.before' | '.after' | ''): void {
// try {
// const properties: TelemetryProperties = {};

// const [, repository, tag] = /^(.*):(.*)$/.exec(fullImageName) ?? [undefined, fullImageName, ''];

// if (!!tag.match(/^[0-9.-]*(|alpha|beta|latest|edge|v|version)?[0-9.-]*$/)) {
// properties.safeTag = tag;
// }
// properties.hasTag = String(!!tag);
// properties.numSlashes = String(numberMatches(repository.match(/\//g)));

// const knownRegistry = KnownRegistries.find(kr => !!repository.match(kr.regex));
// if (knownRegistry) {
// properties.registryType = knownRegistry.type;
// }

// for (const propertyName of Object.keys(properties)) {
// context.telemetry.properties[propertyName + propertyPostfix] = properties[propertyName];
// }
// } catch (error) {
// console.error(error);
// }
// }

// function numberMatches(matches: RegExpMatchArray | null): number {
// return matches ? matches.length : 0;
// }
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import { IActionContext, TelemetryProperties } from '@microsoft/vscode-azext-utils';
import * as vscode from 'vscode';
import { ext } from '../../extensionVariables';
import { ImageTreeItem } from '../../tree/images/ImageTreeItem';
import { UnifiedRegistryItem } from '../../tree/registries/UnifiedRegistryTreeDataProvider';

export async function tagImage(context: IActionContext, node?: ImageTreeItem, registry?: UnifiedRegistryItem<unknown>): Promise<string> {
if (!node) {
await ext.imagesTree.refresh(context);
node = await ext.imagesTree.showTreeItemPicker<ImageTreeItem>(ImageTreeItem.contextValue, {
...context,
noItemFoundErrorMessage: vscode.l10n.t('No images are available to tag')
});
}

addImageTaggingTelemetry(context, node.fullTag, '.before');
const newTaggedName: string = await getTagFromUserInput(context, node.fullTag, ''); // TODO: review this later
addImageTaggingTelemetry(context, newTaggedName, '.after');

await ext.runWithDefaults(client =>
client.tagImage({ fromImageRef: node.imageId, toImageRef: newTaggedName })
);

return newTaggedName;
}

export async function getTagFromUserInput(context: IActionContext, fullTag: string, baseImagePath?: string): Promise<string> {
const opt: vscode.InputBoxOptions = {
ignoreFocusOut: true,
prompt: vscode.l10n.t('Tag image as...'),
};

if (fullTag.includes('/')) {
opt.valueSelection = [0, fullTag.lastIndexOf('/')];
} else if (baseImagePath) {
fullTag = `${baseImagePath}/${fullTag}`;
opt.valueSelection = [0, fullTag.lastIndexOf('/')];
}

opt.value = fullTag;

return await context.ui.showInputBox(opt);
}

const KnownRegistries: { type: string, regex: RegExp }[] = [
// Like username/path
{ type: 'dockerhub-namespace', regex: /^[^.:]+\/[^.:]+$/ },

{ type: 'dockerhub-dockerio', regex: /^docker.io.*\// },
{ type: 'github', regex: /ghcr\.io.*\// },
{ type: 'gitlab', regex: /gitlab.*\// },
{ type: 'ACR', regex: /azurecr\.io.*\// },
{ type: 'GCR', regex: /gcr\.io.*\// },
{ type: 'ECR', regex: /\.ecr\..*\// },
{ type: 'localhost', regex: /localhost:.*\// },

// Has a port, probably a private registry
{ type: 'privateWithPort', regex: /:[0-9]+\// },

// Match anything remaining
{ type: 'other', regex: /\// }, // has a slash
{ type: 'none', regex: /./ } // no slash
];

export function addImageTaggingTelemetry(context: IActionContext, fullImageName: string, propertyPostfix: '.before' | '.after' | ''): void {
try {
const properties: TelemetryProperties = {};

const [, repository, tag] = /^(.*):(.*)$/.exec(fullImageName) ?? [undefined, fullImageName, ''];

if (!!tag.match(/^[0-9.-]*(|alpha|beta|latest|edge|v|version)?[0-9.-]*$/)) {
properties.safeTag = tag;
}
properties.hasTag = String(!!tag);
properties.numSlashes = String(numberMatches(repository.match(/\//g)));

const knownRegistry = KnownRegistries.find(kr => !!repository.match(kr.regex));
if (knownRegistry) {
properties.registryType = knownRegistry.type;
}

for (const propertyName of Object.keys(properties)) {
context.telemetry.properties[propertyName + propertyPostfix] = properties[propertyName];
}
} catch (error) {
console.error(error);
}
}

function numberMatches(matches: RegExpMatchArray | null): number {
return matches ? matches.length : 0;
}
9 changes: 6 additions & 3 deletions src/commands/registerCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,9 @@ import { connectRegistry } from "./registries/connectRegistry";
// import { logOutOfDockerCli } from "./registries/logOutOfDockerCli";
// import { pullImageFromRepository, pullRepository } from "./registries/pullImages";
// import { reconnectRegistry } from "./registries/reconnectRegistry";
import { deleteAzureRegistry } from "./registries/azure/deleteAzureRegistry";
import { deleteAzureRepository } from "./registries/azure/deleteAzureRepository";
import { buildImageInAzure } from "./registries/azure/tasks/buildImageInAzure";
import { copyRemoteFullTag } from "./registries/copyRemoteFullTag";
import { copyRemoteImageDigest } from "./registries/copyRemoteImageDigest";
import { disconnectRegistry } from "./registries/disconnectRegistry";
Expand Down Expand Up @@ -182,10 +185,10 @@ export function registerCommands(): void {

// registerCommand('vscode-docker.registries.dockerHub.openInBrowser', openDockerHubInBrowser);

// registerWorkspaceCommand('vscode-docker.registries.azure.buildImage', buildImageInAzure);
registerWorkspaceCommand('vscode-docker.registries.azure.buildImage', buildImageInAzure);
registerCommand('vscode-docker.registries.azure.createRegistry', createAzureRegistry);
// registerCommand('vscode-docker.registries.azure.deleteRegistry', deleteAzureRegistry);
// registerCommand('vscode-docker.registries.azure.deleteRepository', deleteAzureRepository);
registerCommand('vscode-docker.registries.azure.deleteRegistry', deleteAzureRegistry);
registerCommand('vscode-docker.registries.azure.deleteRepository', deleteAzureRepository);
registerCommand('vscode-docker.registries.azure.openInPortal', openInAzurePortal);
registerCommand('vscode-docker.registries.azure.runTask', runAzureTask);
// registerWorkspaceCommand('vscode-docker.registries.azure.runFileAsTask', runFileAsAzureTask);
Expand Down
Loading