Skip to content

Commit

Permalink
merge cleanup (#617)
Browse files Browse the repository at this point in the history
* Added Azure Credentials Manager Singleton (#18)

* Added Azure Credentials Manager Singleton
* Added getResourceManagementClient

* Sorted Existing Create Registry ready for code review

* Added acquiring telemetry data for create registry

* broke up createnewresourcegroup method and fixed client use

Added try catch loop and awaited for resource group list again to check for duplicates with ResourceManagementClient

* Jackson esteban/unified client nit Fix (#24)

* Added Azure Credentials Manager Singleton

* Small Style Fixes

* Further Style fixes, added getResourceManagementClient

* Lazy Initialization Patches

* Enabled location selection

* Location request fixes

-Changed order of questions asked to user for better UX (location of new res group & location of new registry)
-Placeholder of location is display name view

* Refactor while loop for new res group

* Added SKU selection

* Quick fix- initializing array syntax

* Added specific error messages and comments

* Julia/delete image (#29)

* first fully functional version of delete through input bar AND right click

* refactored code to make it prettier!

* comments

* comments, added subscription function

* fixed to style guide

* style fixes, refactoring

* delete image after reviews

put my functions from azureCredentialsManager into two new files: utils/azure/acrTools.ts, and commands/utils/quick-pick-azure.ts

Edited code based on Esteban's and Bin's reviews

* One last little change to delete image

* moved repository, azureimage, and getsubscriptions to the correct places within deleteImage

* changes from PR reviews on delete image

* fixed authentication issue, got rid of azureAccount property for repository and image

**on constructor for repository, azurecredentialsmanager was being recreated and thus couldn't find the azureAccount. For this reason, I got rid of the azureAccount property of the classes Repository and AzureImage. This bug may lead to future problems (Esteban and I couldn't see why it was happening)

* minor fixes deleteImage

* delete a parentheses

* copied previous push to acr into new pull-from-azure.ts file

* Estebanreyl/dev merge fixes  (#43)

* Merge fixes to acquire latest telemetry items

* Updated to master AzureUtilityManager

* added acrbuild stuff

* added acrbuild stuff

* Update to match utility manager class

* Rutusamai/list build tasks for each registry (#37)

* tslint updates, transfered from old branch

* updated icon

* Addressed PR comments- mostly styling/code efficiency

* Changed url to aka.ms link

* changed Error window to Info message for no build tasks in your registry

* Changed default sku and unified parsing resource group into a new method, getResourceGroup in acrTools.ts

* Changed build task icon

* Added quick pick for selecting resource group and registry

* clean

* Added subscription support

* utility bug fix

* Julia/delete repository final (#49)

* deleteRepo moved over to branch off dev

* Got rid of unnecessary code, fully functioning!

* deleteRepo moved over to branch off dev

* Got rid of unnecessary code, fully functioning!

* spacing

* final commit

* Cleaned code

* Added Telemetry

* Julia/delete registry final (#47)


Delete azure registry functionality added

Delete azure registry moved to branch off dev

Reorganized stye

* Made loginCredentials method in acrTools more efficient, added Pull Image from Azure option, temporary fix for no registries

* added folder select

* Split the loginCredentials function, added docker login and docker pull and telemetry actions

* Finished pull from azure right click feature

* deleted push to azure

* removed username and password from Azure Registry Node

* Clean up

* copied previous push to acr into new pull-from-azure.ts file

* Made loginCredentials method in acrTools more efficient, added Pull Image from Azure option, temporary fix for no registries

* Split the loginCredentials function, added docker login and docker pull and telemetry actions

* Finished pull from azure right click feature

* deleted push to azure

* Clean up

* Working again after rebasing and resolving merge conflicts

* Updates and fixes

* Fixes from PR comments

-renamed loginCredentials functions
-added await to docker commands in image pull
-cleanup

* uncapitalize AzureRegistryNode

* Refactoring, prod.

* Flexible OSType

* Estebanreyl/ready for production (#55)

* began updating

* Reorganized create registry and delete azure image

* continued improvements

* Began updating login

* being credentials update

* further updates

* Finished updating, need to test functionality now

* Updated requests, things all work now

* Applied some nit fixes

* Updates to naming

* maintain UtilityManager standards

* Updated Prompts

* Updated imports and naming / standarized telemetry

* Added explorer refresh capabilities on delete/add

* Jackson/quick build dev (#46)

* added acrbuild stuff

* added acrbuild stuff

* Update to match utility manager class

* Added quick pick for selecting resource group and registry

* clean

* Added subscription support

* utility bug fix

* added folder select

* Updates and fixes

* Refactoring, prod.

* Flexible OSType

* added ID

* Move build to azure commands

* cleanup

* Relative dockerfile support

* Removed await, updating list in enumeration

* fixed chdir

* flexible ostype

* Rutusamai/Show Build Task properties (#70)

* Show build task works through input bar

* added run build task

* Right click not working on BuildTaskNode. Works through command palette

* quick fixes

* quick fix to enable context menu on buildTaskNode

* comamnd not sending via right click

* working from right click now. trying to do show in json

* Acquire properties in JSON format internally, works

* Now shows organized task jsons on right click

* import

* to do

* issues with getImagesByRepository

* try catch build step

* acrTools

* small refactor

* Show build task works through input bar

* added run build task

* Right click not working on BuildTaskNode. Works through command palette

* quick fixes

* quick fix to enable context menu on buildTaskNode

* comamnd not sending via right click

* working from right click now. trying to do show in json

* Acquire properties in JSON format internally, works

* Now shows organized task jsons on right click

* import

* to do

* issues with getImagesByRepository

* try catch build step

* acrTools

* small refactor

* Show is working- final

* removed run build task stuff

* cleanup

* addressed esteban's comments

* buildTask = context.task.name rather than label

* fixes from Bin's comments

* Merge branch 'dev' of https://github.com/AzureCR/vscode-docker into master4

* merge

* missed small changes

* Rutusamai/Run a Build Task (#71)

* Show build task works through input bar

* added run build task

* Right click not working on BuildTaskNode. Works through command palette

* quick fixes

* quick fix to enable context menu on buildTaskNode

* comamnd not sending via right click

* working from right click now. trying to do show in json

* Acquire properties in JSON format internally, works

* Now shows organized task jsons on right click

* import

* to do

* issues with getImagesByRepository

* try catch build step

* acrTools

* small refactor

* Show build task works through input bar

* added run build task

* Right click not working on BuildTaskNode. Works through command palette

* quick fixes

* quick fix to enable context menu on buildTaskNode

* comamnd not sending via right click

* working from right click now. trying to do show in json

* Acquire properties in JSON format internally, works

* Now shows organized task jsons on right click

* import

* to do

* issues with getImagesByRepository

* try catch build step

* acrTools

* small refactor

* Show is working- final

* run is working for right click

* run build task works through command pallette. added success notification

* removed show build task

* cleanup- matched quickpick buils task and tasknode withshow build task branch

* removed showTaskManager

* spacing

* outputChannel and null icon

* merge to update with dev

* Estebanreyl/build logs final (#72)

*  "Merge branch 'estebanreyl/buildlogsWithAccesibility' of https://github.com/AzureCR/vscode-docker into estebanreyl/buildlogsWithAccesibility"

This reverts commit e645cbf, reversing
changes made to fc4a477.

* Refactored and organized log view into readable components.

* moved storage

* Began incorporating icons

* Added icons

* Further standarization

* added logs

* Added download log capabilities

* Updated Copy

* Updated inner div size alignment

* Added resizing script

* header sort by is only clickable on text now

* fixed header table

* Fix minor display issues

* Identified filtering strategy

* Begin adding sorting

* Merge with dev

* Added proper filtering

* Nit loading improvements

* Added accesibility, key only behaviour

* accesibility retouches and enable right click from tasknode

* merges

* fix module name

* Adds streaming and command standarization (ext.ui) (#73)

* Adds streaming and command standarization (ext.ui)

* removed unecessary append lines

* small fixes

* Fix merge issues

* changes for ACR 3.0.0 (#80)

* This commit contains changes necessary for the
azure-arm-containerregistry 3.0.0

* Fixed PR feedback

* Run task fixed. Issue ID: 79

* missing changes added

* Fixing ACR run logs for Images

* Sajaya/top1 (#83)

* Query only 1 record for runs

* View Azure logs

* Refactoring build to run and buildTask to task

* Removed filter for top (#88)

* adding run yaml file

* Refactoring to run task file.

* fixing logs filter for images

* Last Update time Fixed

* Cleanup + refactoring delete image to untag image

* Adding delete ACR Image (delete digest)

* Changing text promt on right click to run ACR task file

* Update settings.json

* minor PR review fixes 1

* PR fixes 1

* Missed: change any to string

* merge clean up

* Schedule run code reduction + minor improvements

* ACR request Improvements

* Minor grammar fixes
  • Loading branch information
rosanch authored and StephenWeatherford committed Nov 17, 2018
1 parent 86afb81 commit 94a7ed2
Show file tree
Hide file tree
Showing 15 changed files with 375 additions and 196 deletions.
33 changes: 10 additions & 23 deletions commands/azureCommands/acr-logs-utils/tableDataManager.ts
Expand Up @@ -2,8 +2,10 @@ import ContainerRegistryManagementClient from "azure-arm-containerregistry";
import { Registry, Run, RunGetLogResult, RunListResult } from "azure-arm-containerregistry/lib/models";
import vscode = require('vscode');
import { parseError } from "vscode-azureextensionui";
import { ext } from "../../../extensionVariables";
import { acquireACRAccessTokenFromRegistry } from "../../../utils/Azure/acrTools";
import { getImageDigest } from "../../../utils/Azure/acrTools";
import { AzureImage } from "../../../utils/Azure/models/image";
import { Repository } from "../../../utils/Azure/models/repository";

/** Class to manage data and data acquisition for logs */
export class LogData {
public registry: Registry;
Expand Down Expand Up @@ -121,29 +123,14 @@ export class LogData {
parsedFilter = `TaskName eq '${filter.task}'`;
} else if (filter.image) { //Image
let items: string[] = filter.image.split(':')
const { acrAccessToken } = await acquireACRAccessTokenFromRegistry(this.registry, 'repository:' + items[0] + ':pull');
let digest = await new Promise<string>((resolve, reject) => ext.request.get('https://' + this.registry.loginServer + `/v2/${items[0]}/manifests/${items[1]}`, {
auth: {
bearer: acrAccessToken
},
headers: {
accept: 'application/vnd.docker.distribution.manifest.v2+json; 0.5, application/vnd.docker.distribution.manifest.list.v2+json; 0.6'
}
}, (err, httpResponse, body) => {
if (err) {
reject(err);
} else {
const imageDigest = httpResponse.headers['docker-content-digest'];
if (imageDigest instanceof Array) {
reject(new Error('docker-content-digest should be a string not an array.'))
} else {
resolve(imageDigest);
}
}
}));
if (items.length !== 2) {
throw new Error('Wrong format: It should be <image>:<tag>');
}
const image = new AzureImage(await Repository.Create(this.registry, items[0]), items[1]);
const imageDigest: string = await getImageDigest(image);

if (parsedFilter.length > 0) { parsedFilter += ' and '; }
parsedFilter += `contains(OutputImageManifests, '${items[0]}@${digest}')`;
parsedFilter += `contains(OutputImageManifests, '${image.repository.name}@${imageDigest}')`;
}
return parsedFilter;
}
Expand Down
71 changes: 57 additions & 14 deletions commands/azureCommands/delete-image.ts
Expand Up @@ -11,37 +11,80 @@ import { ext } from "../../extensionVariables";
import * as acrTools from '../../utils/Azure/acrTools';
import { AzureImage } from "../../utils/Azure/models/image";
import { Repository } from "../../utils/Azure/models/repository";
import { getLoginServer } from "../../utils/nonNull";
import * as quickPicks from '../utils/quick-pick-azure';

/** Function to untag an Azure hosted image
* @param context : if called through right click on AzureImageNode, the node object will be passed in. See azureRegistryNodes.ts for more info
*/
export async function untagAzureImage(context?: AzureImageTagNode): Promise<void> {
let registry: Registry;
let repo: Repository;
let image: AzureImage;

if (!context) {
registry = await quickPicks.quickPickACRRegistry();
repo = await quickPicks.quickPickACRRepository(registry, `Select the repository of the image you want to untag`);
image = await quickPicks.quickPickACRImage(repo, `Select the image you want to untag`);

} else {
registry = context.registry;
let wholeName: string[] = context.label.split(':');
repo = await Repository.Create(registry, wholeName[0]);
image = new AzureImage(repo, wholeName[1]);
}

const shouldDelete = await ext.ui.showWarningMessage(
`Are you sure you want to untag '${image.toString()}'? This does not delete the manifest referenced by the tag.`,
{ modal: true },
DialogResponses.deleteResponse,
DialogResponses.cancel);

if (shouldDelete === DialogResponses.deleteResponse) {
await acrTools.untagImage(image);
vscode.window.showInformationMessage(`Successfully untagged '${image.toString()}'`);

if (context) {
dockerExplorerProvider.refreshNode(context.parent);
} else {
dockerExplorerProvider.refreshRegistries();
}
}
}

/** Function to delete an Azure hosted image
* @param context : if called through right click on AzureImageNode, the node object will be passed in. See azureRegistryNodes.ts for more info
*/
export async function deleteAzureImage(context?: AzureImageTagNode): Promise<void> {
let registry: Registry;
let repoName: string;
let tag: string;
let repo: Repository;
let image: AzureImage;

if (!context) {
registry = await quickPicks.quickPickACRRegistry();
const repository: Repository = await quickPicks.quickPickACRRepository(registry, 'Select the repository of the image you want to delete');
repoName = repository.name;
const image: AzureImage = await quickPicks.quickPickACRImage(repository, 'Select the image you want to delete');
tag = image.tag;
repo = await quickPicks.quickPickACRRepository(registry, `Select the repository of the image you want to delete`);
image = await quickPicks.quickPickACRImage(repo, `Select the image you want to delete`);

} else {
registry = context.registry;
let wholeName: string[] = context.label.split(':');
repoName = wholeName[0];
tag = wholeName[1];
repo = await Repository.Create(registry, wholeName[0]);
image = new AzureImage(repo, wholeName[1]);
}

const shouldDelete = await ext.ui.showWarningMessage(`Are you sure you want to delete ${repoName}:${tag}? `, { modal: true }, DialogResponses.deleteResponse, DialogResponses.cancel);
const digest = await acrTools.getImageDigest(image);
const images = await acrTools.getImagesByDigest(repo, digest);
const imageList = images.join(', ');

const shouldDelete = await ext.ui.showWarningMessage(
`Are you sure you want to delete the manifest '${digest}' and the associated image(s): ${imageList}?`,
{ modal: true },
DialogResponses.deleteResponse,
DialogResponses.cancel);

if (shouldDelete === DialogResponses.deleteResponse) {
const { acrAccessToken } = await acrTools.acquireACRAccessTokenFromRegistry(registry, `repository:${repoName}:*`);
const path = `/v2/_acr/${repoName}/tags/${tag}`;
await acrTools.sendRequestToRegistry('delete', getLoginServer(registry), path, acrAccessToken);
vscode.window.showInformationMessage(`Successfully deleted image ${tag}`);
await acrTools.deleteImage(repo, digest);
vscode.window.showInformationMessage(`Successfully deleted manifest '${digest}' and the associated image(s): ${imageList}.`);

if (context) {
dockerExplorerProvider.refreshNode(context.parent);
} else {
Expand Down
16 changes: 6 additions & 10 deletions commands/azureCommands/delete-repository.ts
Expand Up @@ -8,7 +8,6 @@ import { dockerExplorerProvider } from '../../dockerExtension';
import { AzureRepositoryNode } from '../../explorer/models/azureRegistryNodes';
import * as acrTools from '../../utils/Azure/acrTools';
import { Repository } from "../../utils/Azure/models/repository";
import { getLoginServer } from "../../utils/nonNull";
import { confirmUserIntent, quickPickACRRegistry, quickPickACRRepository } from '../utils/quick-pick-azure';

/**
Expand All @@ -17,22 +16,19 @@ import { confirmUserIntent, quickPickACRRegistry, quickPickACRRepository } from
*/
export async function deleteRepository(context?: AzureRepositoryNode): Promise<void> {
let registry: Registry;
let repoName: string;
let repo: Repository;

if (context) {
repoName = context.label;
registry = context.registry;
repo = await Repository.Create(registry, context.label);
} else {
registry = await quickPickACRRegistry();
const repository: Repository = await quickPickACRRepository(registry, 'Select the repository you want to delete');
repoName = repository.name;
repo = await quickPickACRRepository(registry, 'Select the repository you want to delete');
}
const shouldDelete = await confirmUserIntent(`Are you sure you want to delete ${repoName} and its associated images?`);
const shouldDelete = await confirmUserIntent(`Are you sure you want to delete ${repo.name} and its associated images?`);
if (shouldDelete) {
const { acrAccessToken } = await acrTools.acquireACRAccessTokenFromRegistry(registry, `repository:${repoName}:*`);
const path = `/v2/_acr/${repoName}/repository`;
await acrTools.sendRequestToRegistry('delete', getLoginServer(registry), path, acrAccessToken);
vscode.window.showInformationMessage(`Successfully deleted repository ${repoName}`);
await acrTools.deleteRepository(repo);
vscode.window.showInformationMessage(`Successfully deleted repository ${repo.name}`);
if (context) {
dockerExplorerProvider.refreshNode(context.parent);
} else {
Expand Down
90 changes: 3 additions & 87 deletions commands/azureCommands/quick-build.ts
@@ -1,94 +1,10 @@
import { ContainerRegistryManagementClient } from 'azure-arm-containerregistry/lib/containerRegistryManagementClient';
import { Registry, Run, SourceUploadDefinition } from 'azure-arm-containerregistry/lib/models';
import { DockerBuildRequest } from "azure-arm-containerregistry/lib/models";
import { Subscription } from 'azure-arm-resource/lib/subscription/models';
import { BlobService, createBlobServiceWithSas } from "azure-storage";
import * as fse from 'fs-extra';
import * as os from 'os';
import * as process from 'process';
import * as tar from 'tar';
import * as url from 'url';
import * as vscode from "vscode";
import { IActionContext, IAzureQuickPickItem } from 'vscode-azureextensionui';
import { ext } from '../../extensionVariables';
import { getBlobInfo, getResourceGroupName, IBlobInfo, streamLogs } from "../../utils/Azure/acrTools";
import { AzureUtilityManager } from "../../utils/azureUtilityManager";
import { Item } from '../build-image';
import { quickPickACRRegistry, quickPickSubscription } from '../utils/quick-pick-azure';
import { quickPickDockerFileItem, quickPickImageName } from '../utils/quick-pick-image';
import { quickPickWorkspaceFolder } from '../utils/quickPickWorkspaceFolder';

const idPrecision = 6;
const vcsIgnoreList: Set<String> = new Set(['.git', '.gitignore', '.bzr', 'bzrignore', '.hg', '.hgignore', '.svn']);
const status = vscode.window.createOutputChannel('ACR Build Status');
import { IActionContext } from 'vscode-azureextensionui';
import { scheduleRunRequest } from '../utils/SourceArchiveUtility';

// Prompts user to select a subscription, resource group, then registry from drop down. If there are multiple folders in the workspace, the source folder must also be selected.
// The user is then asked to name & tag the image. A build is queued for the image in the selected registry.
// Selected source code must contain a path to the desired dockerfile.
export async function quickBuild(actionContext: IActionContext, dockerFileUri?: vscode.Uri | undefined): Promise<void> {
//Acquire information from user
let rootFolder: vscode.WorkspaceFolder = await quickPickWorkspaceFolder("To quick build Docker files you must first open a folder or workspace in VS Code.");
const dockerItem: Item = await quickPickDockerFileItem(actionContext, dockerFileUri, rootFolder);
const subscription: Subscription = await quickPickSubscription();
const registry: Registry = await quickPickACRRegistry(true);
const osPick = ['Linux', 'Windows'].map(item => <IAzureQuickPickItem<string>>{ label: item, data: item });
const osType: string = (await ext.ui.showQuickPick(osPick, { 'canPickMany': false, 'placeHolder': 'Select image base OS' })).data;
const imageName: string = await quickPickImageName(actionContext, rootFolder, dockerItem);

const resourceGroupName: string = getResourceGroupName(registry);
const tarFilePath: string = getTempSourceArchivePath();
const client: ContainerRegistryManagementClient = await AzureUtilityManager.getInstance().getContainerRegistryManagementClient(subscription);

//Begin readying build
status.show();

const uploadedSourceLocation: string = await uploadSourceCode(client, registry.name, resourceGroupName, rootFolder, tarFilePath);
status.appendLine("Uploaded Source Code to " + tarFilePath);

const runRequest: DockerBuildRequest = {
type: 'DockerBuildRequest',
imageNames: [imageName],
isPushEnabled: true,
sourceLocation: uploadedSourceLocation,
platform: { os: osType },
dockerFilePath: dockerItem.relativeFilePath
};
status.appendLine("Set up Run Request");

const run: Run = await client.registries.scheduleRun(resourceGroupName, registry.name, runRequest);
status.appendLine("Scheduled Run " + run.runId);

await streamLogs(registry, run, status, client);
await fse.unlink(tarFilePath);
}

async function uploadSourceCode(client: ContainerRegistryManagementClient, registryName: string, resourceGroupName: string, rootFolder: vscode.WorkspaceFolder, tarFilePath: string): Promise<string> {
status.appendLine(" Sending source code to temp file");
let source: string = rootFolder.uri.fsPath;
let items = await fse.readdir(source);
items = items.filter(i => !(i in vcsIgnoreList));
// tslint:disable-next-line:no-unsafe-any
tar.c({ cwd: source }, items).pipe(fse.createWriteStream(tarFilePath));

status.appendLine(" Getting Build Source Upload Url ");
let sourceUploadLocation: SourceUploadDefinition = await client.registries.getBuildSourceUploadUrl(resourceGroupName, registryName);
let upload_url: string = sourceUploadLocation.uploadUrl;
let relative_path: string = sourceUploadLocation.relativePath;

status.appendLine(" Getting blob info from Upload Url ");
// Right now, accountName and endpointSuffix are unused, but will be used for streaming logs later.
let blobInfo: IBlobInfo = getBlobInfo(upload_url);
status.appendLine(" Creating Blob Service ");
let blob: BlobService = createBlobServiceWithSas(blobInfo.host, blobInfo.sasToken);
status.appendLine(" Creating Block Blob ");
blob.createBlockBlobFromLocalFile(blobInfo.containerName, blobInfo.blobName, tarFilePath, (): void => { });
return relative_path;
}

function getTempSourceArchivePath(): string {
/* tslint:disable-next-line:insecure-random */
let id: number = Math.floor(Math.random() * Math.pow(10, idPrecision));
status.appendLine("Setting up temp file with 'sourceArchive" + id + ".tar.gz' ");
let tarFilePath: string = url.resolve(os.tmpdir(), `sourceArchive${id}.tar.gz`);
return tarFilePath;
await scheduleRunRequest(dockerFileUri, "DockerBuildRequest", actionContext);
}
7 changes: 7 additions & 0 deletions commands/azureCommands/run-task.ts
Expand Up @@ -8,6 +8,13 @@ import { TaskNode } from "../../explorer/models/taskNode";
import * as acrTools from '../../utils/Azure/acrTools';
import { AzureUtilityManager } from "../../utils/azureUtilityManager";
import { quickPickACRRegistry, quickPickSubscription, quickPickTask } from '../utils/quick-pick-azure';
import { scheduleRunRequest } from '../utils/SourceArchiveUtility';

// Runs the selected yaml file. Equivalent to az acr run -f <yaml file> <directory>
// Selected source code must contain a path to the desired dockerfile.
export async function runTaskFile(yamlFileUri?: vscode.Uri): Promise<void> {
await scheduleRunRequest(yamlFileUri, "FileTaskRunRequest");
}

export async function runTask(context?: TaskNode): Promise<void> {
let taskName: string;
Expand Down
22 changes: 11 additions & 11 deletions commands/build-image.ts
Expand Up @@ -6,22 +6,22 @@
import * as path from "path";
import * as vscode from "vscode";
import { DialogResponses, IActionContext, UserCancelledError } from "vscode-azureextensionui";
import { DOCKERFILE_GLOB_PATTERN } from '../dockerExtension';
import { DOCKERFILE_GLOB_PATTERN, YAML_GLOB_PATTERN } from '../dockerExtension';
import { delay } from "../explorer/utils/utils";
import { ext } from "../extensionVariables";
import { addImageTaggingTelemetry, getTagFromUserInput } from "./tag-image";
import { quickPickWorkspaceFolder } from "./utils/quickPickWorkspaceFolder";

async function getDockerFileUris(folder: vscode.WorkspaceFolder): Promise<vscode.Uri[]> {
return await vscode.workspace.findFiles(new vscode.RelativePattern(folder, DOCKERFILE_GLOB_PATTERN), undefined, 1000, undefined);
async function getFileUris(folder: vscode.WorkspaceFolder, globPattern: string): Promise<vscode.Uri[]> {
return await vscode.workspace.findFiles(new vscode.RelativePattern(folder, globPattern), undefined, 1000, undefined);
}

export interface Item extends vscode.QuickPickItem {
relativeFilePath: string;
relativeFolderPath: string;
}

function createDockerfileItem(rootFolder: vscode.WorkspaceFolder, uri: vscode.Uri): Item {
function createFileItem(rootFolder: vscode.WorkspaceFolder, uri: vscode.Uri): Item {
let relativeFilePath = path.join(".", uri.fsPath.substr(rootFolder.uri.fsPath.length));

return <Item>{
Expand All @@ -32,21 +32,21 @@ function createDockerfileItem(rootFolder: vscode.WorkspaceFolder, uri: vscode.Ur
};
}

export async function resolveDockerFileItem(rootFolder: vscode.WorkspaceFolder, dockerFileUri: vscode.Uri | undefined): Promise<Item | undefined> {
if (dockerFileUri) {
return createDockerfileItem(rootFolder, dockerFileUri);
export async function resolveFileItem(rootFolder: vscode.WorkspaceFolder, fileUri: vscode.Uri | undefined, globPattern: string, message: string): Promise<Item | undefined> {
if (fileUri) {
return createFileItem(rootFolder, fileUri);
}

const uris: vscode.Uri[] = await getDockerFileUris(rootFolder);
let uris: vscode.Uri[] = await getFileUris(rootFolder, globPattern);

if (!uris || uris.length === 0) {
return undefined;
} else {
let items: Item[] = uris.map(uri => createDockerfileItem(rootFolder, uri));
let items: Item[] = uris.map(uri => createFileItem(rootFolder, uri));
if (items.length === 1) {
return items[0];
} else {
const res: vscode.QuickPickItem = await ext.ui.showQuickPick(items, { placeHolder: 'Choose Dockerfile to build' });
const res: vscode.QuickPickItem = await ext.ui.showQuickPick(items, { placeHolder: message });
return <Item>res;
}
}
Expand All @@ -60,7 +60,7 @@ export async function buildImage(actionContext: IActionContext, dockerFileUri: v
let rootFolder: vscode.WorkspaceFolder = await quickPickWorkspaceFolder('To build Docker files you must first open a folder or workspace in VS Code.');

while (!dockerFileItem) {
let resolvedItem: Item | undefined = await resolveDockerFileItem(rootFolder, dockerFileUri);
let resolvedItem: Item | undefined = await resolveFileItem(rootFolder, dockerFileUri, DOCKERFILE_GLOB_PATTERN, 'Choose a Dockerfile to build the image.');
if (resolvedItem) {
dockerFileItem = resolvedItem;
} else {
Expand Down

0 comments on commit 94a7ed2

Please sign in to comment.