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

Update ⬆️ to newest Azure Storage SDK for file shares 🗂 #558

Merged
merged 5 commits into from
Jan 11, 2020
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
32 changes: 32 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,7 @@
],
"dependencies": {
"@azure/storage-blob": "^12.0.0",
"@azure/storage-file-share": "^12.0.0",
"@types/mime": "^2.0.1",
"azure-arm-resource": "^3.1.1-preview",
"azure-arm-storage": "^5.1.1-preview",
Expand Down
31 changes: 12 additions & 19 deletions src/AzureStorageFS.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import { BlobClient, BlobDownloadResponseModel } from "@azure/storage-blob";
import * as azureStorage from "azure-storage";
import { FileDownloadResponseModel, ShareFileClient } from "@azure/storage-file-share";
import * as path from "path";
import * as querystring from "querystring";
import * as vscode from "vscode";
Expand All @@ -18,6 +18,7 @@ import { FileShareTreeItem, IFileShareCreateChildContext } from "./tree/fileShar
import { FileTreeItem } from "./tree/fileShare/FileTreeItem";
import { createBlobClient, createBlockBlob, doesBlobExist, IBlobContainerCreateChildContext } from './utils/blobUtils';
import { doesFileExist, updateFileFromText } from "./utils/fileUtils";
import { createFileClient } from './utils/fileUtils';
import { localize } from "./utils/localize";
import { validateDirectoryName } from "./utils/validateNames";

Expand Down Expand Up @@ -64,9 +65,9 @@ export class AzureStorageFS implements vscode.FileSystemProvider {
let result: [string, vscode.FileType][] = [];
for (const child of children) {
if (child instanceof FileTreeItem) {
result.push([child.file.name, vscode.FileType.File]);
result.push([child.fileName, vscode.FileType.File]);
} else if (child instanceof DirectoryTreeItem) {
result.push([child.directory.name, vscode.FileType.Directory]);
result.push([child.directoryName, vscode.FileType.Directory]);
} else if (child instanceof BlobTreeItem) {
result.push([path.basename(child.blob.name), vscode.FileType.File]);
} else if (child instanceof BlobDirectoryTreeItem) {
Expand Down Expand Up @@ -129,6 +130,8 @@ export class AzureStorageFS implements vscode.FileSystemProvider {
}

async readFile(uri: vscode.Uri): Promise<Uint8Array> {
let client: ShareFileClient | BlobClient;
let downloaded: FileDownloadResponseModel | BlobDownloadResponseModel;
return await callWithTelemetryAndErrorHandling('readFile', async (context) => {
context.telemetry.suppressIfSuccessful = true;
context.errorHandling.rethrow = true;
Expand All @@ -140,22 +143,12 @@ export class AzureStorageFS implements vscode.FileSystemProvider {

try {
if (treeItem instanceof FileShareTreeItem) {
let service: azureStorage.FileService = treeItem.root.createFileService();
let shareName: string = treeItem.share.name;
result = await new Promise<string | undefined>((resolve, reject) => {
service.getFileToText(shareName, parsedUri.parentDirPath, parsedUri.baseName, (error?: Error, text?: string) => {
if (!!error) {
reject(error);
} else {
resolve(text);
}
});
});
client = createFileClient(treeItem.root, treeItem.shareName, parsedUri.parentDirPath, parsedUri.baseName);
} else {
const blobClient: BlobClient = createBlobClient(treeItem.root, treeItem.container.name, parsedUri.filePath);
let downloaded: BlobDownloadResponseModel = await blobClient.download();
result = await this.streamToString(downloaded.readableStreamBody);
client = createBlobClient(treeItem.root, treeItem.container.name, parsedUri.filePath);
}
downloaded = await client.download();
result = await this.streamToString(downloaded.readableStreamBody);
} catch (error) {
let pe = parseError(error);
if (pe.errorType === 'BlobNotFound' || pe.errorType === 'ResourceNotFound') {
Expand Down Expand Up @@ -190,7 +183,7 @@ export class AzureStorageFS implements vscode.FileSystemProvider {

let childExistsRemote: boolean;
if (treeItem instanceof FileShareTreeItem) {
childExistsRemote = await doesFileExist(parsedUri.baseName, treeItem, parsedUri.parentDirPath, treeItem.share);
childExistsRemote = await doesFileExist(parsedUri.baseName, treeItem, parsedUri.parentDirPath, treeItem.shareName);
} else {
childExistsRemote = await doesBlobExist(treeItem, parsedUri.filePath);
}
Expand All @@ -210,7 +203,7 @@ export class AzureStorageFS implements vscode.FileSystemProvider {
progress.report({ message: `Saving ${writeToFileShare ? 'file' : 'blob'} ${parsedUri.filePath}` });

if (treeItem instanceof FileShareTreeItem) {
await updateFileFromText(parsedUri.parentDirPath, parsedUri.baseName, treeItem.share, treeItem.root, content.toString());
await updateFileFromText(parsedUri.parentDirPath, parsedUri.baseName, treeItem.shareName, treeItem.root, content.toString());
} else {
await createBlockBlob(treeItem, parsedUri.filePath, content.toString());

Expand Down
2 changes: 1 addition & 1 deletion src/commands/fileShare/fileShareActionHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ async function openFileShareInStorageExplorer(_context: IActionContext, treeItem
let accountId = treeItem.root.storageAccount.id;
let subscriptionid = treeItem.root.subscriptionId;
const resourceType = 'Azure.FileShare';
let resourceName = treeItem.share.name;
let resourceName = treeItem.shareName;

await storageExplorerLauncher.openResource(accountId, subscriptionid, resourceType, resourceName);
}
20 changes: 6 additions & 14 deletions src/editors/FileFileHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,34 +3,26 @@
* Licensed under the MIT License. See License.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as azureStorage from "azure-storage";
import { FileTreeItem } from "../tree/fileShare/FileTreeItem";
import { updateFileFromLocalFile } from '../utils/fileUtils';
import { createFileClient } from '../utils/fileUtils';
import { IRemoteFileHandler } from './IRemoteFileHandler';

export class FileFileHandler implements IRemoteFileHandler<FileTreeItem> {
async getSaveConfirmationText(treeItem: FileTreeItem): Promise<string> {
return `Saving '${treeItem.file.name}' will update the file "${treeItem.file.name}" in File Share "${treeItem.share.name}"`;
return `Saving '${treeItem.fileName}' will update the file "${treeItem.fileName}" in File Share "${treeItem.shareName}"`;
}

async getFilename(treeItem: FileTreeItem): Promise<string> {
return treeItem.file.name;
return treeItem.fileName;
}

async downloadFile(treeItem: FileTreeItem, filePath: string): Promise<void> {
let fileService = treeItem.root.createFileService();
await new Promise<void>((resolve, reject) => {
fileService.getFileToLocalFile(treeItem.share.name, treeItem.directoryPath, treeItem.file.name, filePath, (error?: Error, _result?: azureStorage.FileService.FileResult, _response?: azureStorage.ServiceResponse) => {
if (!!error) {
reject(error);
} else {
resolve();
}
});
});
const fileClient = createFileClient(treeItem.root, treeItem.shareName, treeItem.directoryPath, treeItem.fileName);
await fileClient.downloadToFile(filePath);
}

async uploadFile(treeItem: FileTreeItem, filePath: string): Promise<void> {
await updateFileFromLocalFile(treeItem.directoryPath, treeItem.file.name, treeItem.share, treeItem.root, filePath);
await updateFileFromLocalFile(treeItem.directoryPath, treeItem.fileName, treeItem.shareName, treeItem.root, filePath);
}
}
3 changes: 2 additions & 1 deletion src/tree/IStorageRoot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@
*--------------------------------------------------------------------------------------------*/

import * as azureStorageBlob from "@azure/storage-blob";
import * as azureStorageShare from "@azure/storage-file-share";
import * as azureStorage from "azure-storage";
import { ISubscriptionContext } from "vscode-azureextensionui";
import { StorageAccountWrapper } from "../utils/storageWrappers";

export interface IStorageRoot extends ISubscriptionContext {
storageAccount: StorageAccountWrapper;
createBlobServiceClient(): azureStorageBlob.BlobServiceClient;
createFileService(): azureStorage.FileService;
createShareServiceClient(): azureStorageShare.ShareServiceClient;
createQueueService(): azureStorage.QueueService;
createTableService(): azureStorage.TableService;
}
6 changes: 4 additions & 2 deletions src/tree/StorageAccountTreeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
*--------------------------------------------------------------------------------------------*/

import * as azureStorageBlob from '@azure/storage-blob';
import * as azureStorageShare from '@azure/storage-file-share';
import { StorageManagementClient } from 'azure-arm-storage';
import { StorageAccountKey } from 'azure-arm-storage/lib/models';
import * as azureStorage from "azure-storage";
Expand Down Expand Up @@ -162,8 +163,9 @@ export class StorageAccountTreeItem extends AzureParentTreeItem<IStorageRoot> {
const credential = new azureStorageBlob.StorageSharedKeyCredential(this.storageAccount.name, this.key.value);
return new azureStorageBlob.BlobServiceClient(this.storageAccount.primaryEndpoints.blob || `https://${this.storageAccount.name}.blob.core.windows.net`, credential);
},
createFileService: () => {
return azureStorage.createFileService(this.storageAccount.name, this.key.value, this.storageAccount.primaryEndpoints.file).withFilter(new azureStorage.ExponentialRetryPolicyFilter());
createShareServiceClient: () => {
const credential = new azureStorageShare.StorageSharedKeyCredential(this.storageAccount.name, this.key.value);
return new azureStorageShare.ShareServiceClient(this.storageAccount.primaryEndpoints.file || `https://${this.storageAccount.name}.file.core.windows.net`, credential);
ejizba marked this conversation as resolved.
Show resolved Hide resolved
},
createQueueService: () => {
return azureStorage.createQueueService(this.storageAccount.name, this.key.value, this.storageAccount.primaryEndpoints.queue).withFilter(new azureStorage.ExponentialRetryPolicyFilter());
Expand Down
1 change: 0 additions & 1 deletion src/tree/blob/BlobContainerTreeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,6 @@ export class BlobContainerTreeItem extends AzureParentTreeItem<IStorageRoot> imp
}

private async listAllBlobs(cancellationToken?: vscode.CancellationToken, properties?: TelemetryProperties): Promise<azureStorageBlob.BlobItem[]> {
// tslint:disable-next-line:no-any
let currentToken: string | undefined;
let response: AsyncIterableIterator<azureStorageBlob.ContainerListBlobFlatSegmentResponse>;
let responseValue: azureStorageBlob.ListBlobsFlatSegmentResponse;
Expand Down
44 changes: 23 additions & 21 deletions src/tree/fileShare/DirectoryTreeItem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,15 @@
* Licensed under the MIT License. See License.md in the project root for license information.
*--------------------------------------------------------------------------------------------*/

import * as azureStorage from "azure-storage";
import * as azureStorageShare from '@azure/storage-file-share';
import * as path from 'path';
import * as vscode from 'vscode';
import { MessageItem, Uri, window } from 'vscode';
import { AzureParentTreeItem, DialogResponses, IActionContext, ICreateChildImplContext, UserCancelledError } from 'vscode-azureextensionui';
import { getResourcesPath } from "../../constants";
import { ext } from "../../extensionVariables";
import { askAndCreateChildDirectory, deleteDirectoryAndContents, listFilesInDirectory } from '../../utils/directoryUtils';
import { askAndCreateEmptyTextFile } from '../../utils/fileUtils';
import { askAndCreateEmptyTextFile, createDirectoryClient } from '../../utils/fileUtils';
import { ICopyUrl } from '../ICopyUrl';
import { IStorageRoot } from "../IStorageRoot";
import { IFileShareCreateChildContext } from "./FileShareTreeItem";
Expand All @@ -21,13 +21,13 @@ export class DirectoryTreeItem extends AzureParentTreeItem<IStorageRoot> impleme
constructor(
parent: AzureParentTreeItem,
public readonly parentPath: string,
public readonly directory: azureStorage.FileService.DirectoryResult, // directory.name should not include parent path
public readonly share: azureStorage.FileService.ShareResult) {
public readonly directoryName: string, // directoryName should not include parent path
public readonly shareName: string) {
super(parent);
}

private _continuationToken: azureStorage.common.ContinuationToken | undefined;
public label: string = this.directory.name;
private _continuationToken: string | undefined;
public label: string = this.directoryName;
public static contextValue: string = 'azureFileShareDirectory';
public contextValue: string = DirectoryTreeItem.contextValue;
public iconPath: { light: string | Uri; dark: string | Uri } = {
Expand All @@ -36,7 +36,7 @@ export class DirectoryTreeItem extends AzureParentTreeItem<IStorageRoot> impleme
};

private get fullPath(): string {
return path.posix.join(this.parentPath, this.directory.name);
return path.posix.join(this.parentPath, this.directoryName);
}

hasMoreChildrenImpl(): boolean {
Expand All @@ -48,38 +48,40 @@ export class DirectoryTreeItem extends AzureParentTreeItem<IStorageRoot> impleme
this._continuationToken = undefined;
}

// tslint:disable-next-line:no-non-null-assertion // currentToken argument typed incorrectly in SDK
let fileResults = await this.listFiles(<azureStorage.common.ContinuationToken>this._continuationToken!);
let { entries, continuationToken } = fileResults;
let { files, directories, continuationToken }: { files: azureStorageShare.FileItem[]; directories: azureStorageShare.DirectoryItem[]; continuationToken: string; } = await this.listFiles(this._continuationToken);
this._continuationToken = continuationToken;

return (<(DirectoryTreeItem | FileTreeItem)[]>[])
.concat(entries.directories.map((directory: azureStorage.FileService.DirectoryResult) => {
return new DirectoryTreeItem(this, this.fullPath, directory, this.share);
.concat(files.map((file: azureStorageShare.FileItem) => {
return new FileTreeItem(this, file.name, this.fullPath, this.shareName);
}))
.concat(entries.files.map((file: azureStorage.FileService.FileResult) => {
return new FileTreeItem(this, file, this.fullPath, this.share);
.concat(directories.map((directory: azureStorageShare.DirectoryItem) => {
return new DirectoryTreeItem(this, this.fullPath, directory.name, this.shareName);
}));
}

public async copyUrl(): Promise<void> {
let fileService = this.root.createFileService();
let url = fileService.getUrl(this.share.name, this.fullPath);
// Use this.fullPath here instead of this.directoryName. Otherwise only the leaf directory is displayed in the URL
let directoryClient: azureStorageShare.ShareDirectoryClient = createDirectoryClient(this.root, this.shareName, this.fullPath);

// URLs for nested directories aren't automatically decoded properly
ejizba marked this conversation as resolved.
Show resolved Hide resolved
const url = decodeURIComponent(directoryClient.url);

await vscode.env.clipboard.writeText(url);
ext.outputChannel.show();
ext.outputChannel.appendLine(`Directory URL copied to clipboard: ${url}`);
}

// tslint:disable-next-line:promise-function-async // Grandfathered in
listFiles(currentToken: azureStorage.common.ContinuationToken): Promise<azureStorage.FileService.ListFilesAndDirectoriesResult> {
return listFilesInDirectory(this.fullPath, this.share.name, this.root, currentToken);
listFiles(currentToken: string | undefined): Promise<{ files: azureStorageShare.FileItem[], directories: azureStorageShare.DirectoryItem[], continuationToken: string }> {
return listFilesInDirectory(this.fullPath, this.shareName, this.root, currentToken);
}

public async createChildImpl(context: ICreateChildImplContext & IFileShareCreateChildContext): Promise<FileTreeItem | DirectoryTreeItem> {
if (context.childType === FileTreeItem.contextValue) {
return askAndCreateEmptyTextFile(this, this.fullPath, this.share, context);
return askAndCreateEmptyTextFile(this, this.fullPath, this.shareName, context);
} else {
return askAndCreateChildDirectory(this, this.fullPath, this.share, context);
return askAndCreateChildDirectory(this, this.fullPath, this.shareName, context);
}
}

Expand All @@ -95,7 +97,7 @@ export class DirectoryTreeItem extends AzureParentTreeItem<IStorageRoot> impleme

if (result === DialogResponses.deleteResponse) {
ext.outputChannel.show();
await deleteDirectoryAndContents(this.fullPath, this.share.name, this.root);
await deleteDirectoryAndContents(this.fullPath, this.shareName, this.root);
} else {
throw new UserCancelledError();
}
Expand Down
Loading