item);
- }
- }),
- input.onDidChangeSelection((items) => resolve(items[0])),
- input.onDidHide(() => {
- (async () => {
- reject(
- shouldResume && (await shouldResume())
- ? InputFlowAction.resume
- : InputFlowAction.cancel
- );
- })().catch(reject);
- })
- );
- if (this.current) {
- this.current.dispose();
- }
- this.current = input;
- this.current.show();
- });
- } finally {
- disposables.forEach((d) => d.dispose());
- }
- }
-
- async showInputBox({
- title,
- step,
- totalSteps,
- value,
- prompt,
- placeholder,
- buttons,
- validate,
- }: P) {
- const disposables: Disposable[] = [];
- try {
- return await new Promise<
- string | (P extends { buttons: (infer I)[] } ? I : never)
- >((resolve, reject) => {
- const input = window.createInputBox();
- input.title = title;
- input.step = step;
- input.totalSteps = totalSteps;
- input.value = value || "";
- input.prompt = prompt || "";
- input.placeholder = placeholder || "";
- (input.ignoreFocusOut = true),
- (input.buttons = [
- ...(this.steps.length > 1 ? [QuickInputButtons.Back] : []),
- ...(buttons || []),
- ]);
-
- let passed = false;
-
- disposables.push(
- input.onDidTriggerButton((item) => {
- if (item === QuickInputButtons.Back) {
- reject(InputFlowAction.back);
- } else {
- resolve(item);
- }
- }),
- input.onDidAccept(async () => {
- if (!passed) {
- return;
- }
-
- const value = input.value;
- input.enabled = false;
- input.busy = true;
- if (!(await validate(value))) {
- resolve(value);
- }
- input.enabled = true;
- input.busy = false;
- }),
- input.onDidChangeValue(async (text) => {
- validate(text)
- .then(() => {
- passed = true;
- input.validationMessage = undefined;
- })
- .catch((err) => {
- passed = false;
- input.validationMessage = err;
- });
- }),
- input.onDidHide(() => {
- (async () => {
- reject(
- shouldResume && (await shouldResume())
- ? InputFlowAction.resume
- : InputFlowAction.cancel
- );
- })().catch(reject);
- })
- );
- if (this.current) {
- this.current.dispose();
- }
- this.current = input;
- this.current.show();
- });
- } finally {
- disposables.forEach((d) => d.dispose());
- }
- }
-}
diff --git a/src/commons/tencent/commands.ts b/src/commons/tencent/commands.ts
deleted file mode 100644
index 8c75d97..0000000
--- a/src/commons/tencent/commands.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { commands } from "vscode";
-import user from "./user";
-
-export function registerLoginCmds() {
- commands.registerCommand(command.TENCENT_LOGIN, user.login);
-
- commands.registerCommand(command.TENCENT_LOGINOUT, user.loginOut);
-
-}
-
-export namespace command {
- // login command
- export const TENCENT_LOGIN = "tcTerraform.login";
- // logout command
- export const TENCENT_LOGINOUT = "tcTerraform.logout";
-}
diff --git a/src/commons/tencent/index.ts b/src/commons/tencent/index.ts
deleted file mode 100644
index fcc8fad..0000000
--- a/src/commons/tencent/index.ts
+++ /dev/null
@@ -1,24 +0,0 @@
-import { commands } from "vscode";
-import { registerLoginCmds, command as _command } from "./commands";
-
-import _user from "./user";
-import _tree from "./treeDataProvider";
-
-export async function regTencentCommands() {
- registerLoginCmds();
- await initialization();
-}
-
-async function initialization() {
- commands.executeCommand(
- "setContext",
- "TcTerraform.login",
- !!(await _user.getInfo())
- );
-}
-
-export namespace tencent {
- export import user = _user;
- export import tree = _tree;
- export import command = _command;
-}
diff --git a/src/commons/tencent/sdkApi.ts b/src/commons/tencent/sdkApi.ts
deleted file mode 100644
index f69fd72..0000000
--- a/src/commons/tencent/sdkApi.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import * as tencentcloud from "tencentcloud-sdk-nodejs";
-
-export interface ITencentCloudAPI {
- describeInstances(params?: any): Promise;
- getConfig(params?: any): Promise;
-}
-
diff --git a/src/commons/tencent/treeDataProvider.ts b/src/commons/tencent/treeDataProvider.ts
deleted file mode 100644
index 1d7c143..0000000
--- a/src/commons/tencent/treeDataProvider.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import { injectable } from "inversify";
-import {
- window,
- Event,
- EventEmitter,
- TreeDataProvider as BaseTreeDataProvider,
- TreeItem as BaseTreeItem,
-} from "vscode";
-import { container } from "../container";
-import { localize } from "vscode-nls-i18n";
-
-export namespace tree {
- export const TencentTreeProvider = Symbol("TencentTreeProvider");
-
- export function refreshTreeData() {
- const treeDataProvider =
- container.getAll(TencentTreeProvider);
-
- treeDataProvider.forEach((item) => item.refresh());
- window.showInformationMessage(localize("TcTerraform.refresh.success"));
- }
-
- // @ts-ignore
- @injectable()
- export abstract class TreeDataProvider
- implements BaseTreeDataProvider
- {
- private _onDidChangeTreeData: EventEmitter =
- new EventEmitter();
-
- readonly onDidChangeTreeData: Event =
- this._onDidChangeTreeData.event;
-
- refresh(): void {
- this._onDidChangeTreeData.fire(undefined);
- }
-
- getTreeItem(element: TreeItem): TreeItem | Thenable {
- return element;
- }
-
- async getChildren(element?: TreeItem | undefined): Promise {
- // if (!element && (await user.getInfo())) {
- if (!element) {
- return [new TreeItem("暂无数据")];
- }
- return [];
- }
- }
-
- export type TreeItemType = Omit;
-
- export class TreeItem extends BaseTreeItem {
- constructor(public readonly label: string, params: TreeItemType = {}) {
- super(label);
-
- Object.entries(params).forEach(([k, v]) => {
- // @ts-ignore
- this[k] = v;
- });
- }
- }
-}
-export default tree;
diff --git a/src/commons/tencent/types/api.ts b/src/commons/tencent/types/api.ts
deleted file mode 100644
index a743111..0000000
--- a/src/commons/tencent/types/api.ts
+++ /dev/null
@@ -1,142 +0,0 @@
-export namespace res {
- export interface ProductSets {
- ProductSet: ProductSet[];
- }
-
- export interface ProductSet {
- product: string;
- productDocCatID?: number;
- productName: string;
- aPIBrief?: string;
- productCNDocCatID?: number;
- productVersion?: string;
- productCNDocIntroUrl?: string;
- }
- export interface ActionSet {
- actionName: string;
- product: string;
- description: string;
- isSubscribed?: boolean;
- actionCNDocUrl: string;
- productName: string;
- productVersion: string;
- action: string;
- categoryName: string;
- icon?: string;
- }
-
- export interface ActionSets {
- ActionSet: ActionSet[];
- }
-
- export interface SDKInfo {
- SDKInfo: KeyValue[];
- }
-
- export interface KeyValue {
- Value: string;
- Key: string;
- }
-
- export interface SdkDemos {
- SdkDemoSet: SdkDemoSet[];
- }
-
- export interface SdkDemoSet {
- DemoJsonCode: string;
- TypeMapSet: TypeMapSet[];
- DemoCode: string;
- Language: string;
- }
-
- interface TypeMapSet {
- Postfix: string;
- OriginalType: string;
- SdkType: string;
- DestinationType: string;
- }
-
- interface SignDemoSet {
- SignCode: string;
- Language: string;
- ParameterCode: string;
- }
-
- export interface Parameters {
- ActionRegions: string[];
- OutputParameterSet: any[];
- ParameterSet: ParameterSet[];
- RequestId: string;
- ObjectSet: ObjectSet[];
- }
-
- interface ParameterSet {
- IsArray: boolean;
- IsPublic: boolean;
- Name: string;
- Default: string;
- Required: boolean;
- Visibility: number;
- Type: string;
- Example: string;
- ValueAllowedNull: boolean;
- Desc: string;
- }
-
- interface ObjectSet {
- ObjectId: number;
- Name: string;
- Members: Member[];
- Description: string;
- }
-
- interface Member {
- IsArray: boolean;
- IsPublic: boolean;
- Name: string;
- Default: string;
- Required: boolean;
- Visibility: number;
- Type: string;
- Example: string;
- Desc: string;
- }
-
- export interface Action {
- Document: string;
- ActionRegions: string[];
- ParameterSet: ParameterSet[];
- RequestId: string;
- ObjectSet: ObjectSet[];
- }
-}
-export namespace req {
- interface BaseParmeter {
- Version: string;
- ProductName: string;
- }
- export interface ProductParmeter extends BaseParmeter {
- ProductVersion: string;
- }
- export interface SDKInfoParmeter extends BaseParmeter {
- SDKType: string;
- }
- export interface Parmeter extends ProductParmeter {
- ProductAction: string;
- }
- export interface SdkParmeter extends BaseParmeter {
- SDKType: string;
- }
-}
-
-export interface IApiDoc {
- describeAllProducts(): Promise;
- describeProductActions(
- parame: Partial
- ): Promise;
- describeAllActions(): Promise;
- describeSdkDemos(parame: req.Parmeter): Promise;
- describeSDKInfo(parame: req.SDKInfoParmeter): Promise;
- // describeAction(): Promise;
- // describeParameters(parame?: req.Parmeter): Promise;
-}
diff --git a/src/commons/tencent/types/index.ts b/src/commons/tencent/types/index.ts
deleted file mode 100644
index 308f5ae..0000000
--- a/src/commons/tencent/types/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export * from './api';
\ No newline at end of file
diff --git a/src/commons/tencent/user/auth/credentail.ts b/src/commons/tencent/user/auth/credentail.ts
deleted file mode 100644
index c948d50..0000000
--- a/src/commons/tencent/user/auth/credentail.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-import MultiStepInput from "../../../multiStepInput";
-import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
-import { localize } from "vscode-nls-i18n";
-import constant from "../index";
-
-export async function getCredentailByInput() {
- const defaultRegion = "ap-guangzhou";
- const title = localize(constant.AKSK_TITLE);
- const regionTitle = localize("TcTerraform.pickup.region");
- async function collectInputs() {
- const state = {} as Partial & { region: string };
- await MultiStepInput.run((input) => inputSecretId(input, state));
- // return state as Required>;
- return state as Required> & { region: string };
- }
-
- async function inputSecretId(
- input: MultiStepInput,
- state: Partial & { region: string }
- ) {
- state.secretId = await input.showInputBox({
- title,
- step: 1,
- totalSteps: 3,
- value: state.secretId || "",
- placeholder: localize(constant.AKSK_PLACEHOLD, "SecretId"),
- validate: validateInput.bind({ key: "SecretId " }),
- });
- return (input: MultiStepInput) => inpuSecretKey(input, state);
- }
-
- async function inpuSecretKey(
- input: MultiStepInput,
- state: Partial & { region: string }
- ) {
- state.secretKey = await input.showInputBox({
- title,
- step: 2,
- totalSteps: 3,
- value: state.secretKey || "",
- placeholder: localize(constant.AKSK_PLACEHOLD, "SecretKey"),
- validate: validateInput.bind({ key: "SecretKey " }),
- });
- return (input: MultiStepInput) => inpuRegion(input, state);
- }
-
- async function inpuRegion(
- input: MultiStepInput,
- state: Partial & { region: string }
- ) {
-
- state.region = await input.showInputBox({
- title: regionTitle,
- step: 3,
- totalSteps: 3,
- value: state.region || "",
- placeholder: defaultRegion,
- prompt: "Input Region",
- validate: validateInput.bind({ key: "Region " }),
- });
-
- }
-
- async function validateInput(this: { key: string }, value: string) {
- if (!value) {
- return Promise.reject(localize(constant.AKSK_EMPTY, this.key));
- }
-
- return undefined;
- }
-
- return collectInputs();
-}
diff --git a/src/commons/tencent/user/auth/index.ts b/src/commons/tencent/user/auth/index.ts
deleted file mode 100644
index cbdafaf..0000000
--- a/src/commons/tencent/user/auth/index.ts
+++ /dev/null
@@ -1 +0,0 @@
-export { getCredentailByInput } from "./credentail";
diff --git a/src/commons/tencent/user/index.ts b/src/commons/tencent/user/index.ts
deleted file mode 100644
index e19a40e..0000000
--- a/src/commons/tencent/user/index.ts
+++ /dev/null
@@ -1,229 +0,0 @@
-import { localize } from "vscode-nls-i18n";
-import { ExtensionContext, workspace, ConfigurationTarget, window, ProgressLocation, MessageItem } from "vscode";
-
-import { container } from "../../container";
-import { Context } from "../../context";
-import { tree } from "../treeDataProvider";
-import { getCredentailByInput } from "./auth";
-import { AbstractClient } from "tencentcloud-sdk-nodejs/tencentcloud/common/abstract_client";
-import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
-import { getCamClient, getCommonClient, getStsClient } from "@/connectivity/client";
-import * as loginMgt from "../../../views/login/loginMgt";
-import * as settingUtils from "../../../utils/settingUtils";
-import * as context from "../../context";
-
-export namespace user {
- export interface UserInfo {
- secretId: string;
- secretKey: string;
- token?: string;
- uin: string;
- subuin?: string;
- type?: string;
- appid?: string;
- region?: string;
- arn?: string;
- }
-
- export const AKSK_TITLE = "TcTerraform.pickup.aksk";
- export const OAUTH_TITLE = "TcTerraform.pickup.oauth";
- export const AKSK_PLACEHOLD = "TcTerraform.pickup.aksk.placeholder";
- export const AKSK_EMPTY = "TcTerraform.pickup.aksk.verify.empty";
-
- const USER_INFO = "USER_INFO";
-
- export async function login() {
- const aksk = localize(AKSK_TITLE);
- const oauth = localize(OAUTH_TITLE);
- const pick = await window.showQuickPick([aksk, oauth]);
-
- // only support aksk way right now
- if (aksk === pick) {
- const credential = await getCredentailByInput();
-
- // set in system environment
- process.env.TENCENTCLOUD_SECRET_ID = credential.secretId;
- process.env.TENCENTCLOUD_SECRET_KEY = credential.secretKey;
- process.env.TENCENTCLOUD_REGION = credential.region;
-
- try {
- // query user info
- const userinfo = await queryUserInfo(credential);
- setInfo(userinfo);
-
- } catch (err) {
- console.error('[TencentCloudSDKError]', err.message);
- window.showErrorMessage('Login Failed. Reason:' + err.message);
- }
- }
- if (oauth === pick) {
- // to do
- }
- }
-
- export async function loginOut() {
- const yesBtn: MessageItem = { title: localize("TcTerraform.common.yes") };
- const action = await window.showWarningMessage(
- localize("TcTerraform.view.logout"),
- {
- modal: true,
- detail: localize("TcTerraform.view.logout.confirm")
- },
- yesBtn
- );
- if (action !== yesBtn) {
- return;
- }
-
- await clearInfo();
-
- tree.refreshTreeData();
- }
-
- async function loginBySecret(credential: Credential) {
- const client = new AbstractClient(
- "open.test.tencentcloudapi.com",
- "2018-12-25",
- {
- credential,
- profile: {
- httpProfile: {
- proxy: "http://9.135.97.58:8899",
- },
- },
- }
- );
- try {
- const res = await client.request("GetUserAuthInfo", {});
-
- const { Error: error, ...rest } = res;
-
- if (error) {
- const err = new Error(error.Message);
- err.stack = JSON.stringify(error);
-
- return Promise.reject(err);
- }
-
- return rest;
- } catch (e) {
- throw e;
- }
- }
-
- async function loginByCredentail() {
- let userInfo: UserInfo | undefined;
- const credential = await getCredentailByInput();
-
- if (credential) {
- try {
- await window.withProgress(
- {
- title: localize("login.title"),
- location: ProgressLocation.Notification,
- },
- async () => {
- const res = await loginBySecret(credential);
- if (res) {
- userInfo = {
- uin: res.Uin,
- secretId: credential.secretId,
- secretKey: credential.secretKey,
- token: res.token,
- };
- setInfo(userInfo);
- }
- }
- );
- } catch (error) {
- console.error("loginByCredentail", error);
-
- const message = error instanceof Error ? `: ${error.message}` : "";
- window.showErrorMessage(localize("login.fail", message));
- }
- }
-
- return userInfo;
- }
-
- async function setInfo(info: UserInfo) {
- const { secrets } = container.get(Context);
-
- await secrets.store(USER_INFO, JSON.stringify(info));
- tree.refreshTreeData();
- }
-
- export async function clearInfo() {
- const { secrets } = container.get(Context);
- await secrets.delete(USER_INFO);
-
- loginMgt.clearStatusBar();
- settingUtils.clearAKSKandRegion();
-
- tree.refreshTreeData();
- }
-
- export async function getInfo(): Promise {
- const { secrets } = container.get(Context);
- const userinfo = await secrets.get(USER_INFO);
-
- if (userinfo) {
- return JSON.parse(userinfo) as UserInfo;
- }
-
- return undefined;
- }
-
- export async function queryUserInfo(credential: any): Promise {
- const stsClient = await getStsClient();
- const reqCli = await context.genRequestClient(); // set ReqCli for login scenario
- stsClient.sdkVersion = reqCli;
- console.log('[DEBUG]--------------------getStsClient:', stsClient);
- // const stsClient = await getCommonClient("sts.tencentcloudapi.com", "2018-08-13");
- // const stsResp = await stsClient.request("GetCallerIdentity", req).
- const stsResp = await stsClient?.GetCallerIdentity(null).
- then(
- (result) => {
- console.debug('[DEBUG]--------------------------------GetCallerIdentity result:', result);
- if (!result) {
- throw new Error('[Warn] GetCallerIdentity result.TotalCount is 0.');
- }
- return result;
- },
- (err) => {
- throw new Error(err);
- }
- );
- // ) as stsModels.GetCallerIdentityResponse;
- const camClient = await getCamClient();
- camClient.sdkVersion = reqCli;
- console.log('[DEBUG]--------------------getCamClient:', camClient);
- const camResp = await camClient?.GetUserAppId(null).
- then(
- (result) => {
- console.debug('[DEBUG]--------------------------------GetUserAppId result:', result);
- if (!result) {
- throw new Error('[Warn] GetUserAppId result.TotalCount is 0.');
- }
- return result;
- },
- (err) => {
- throw new Error(err);
- }
- );
-
- // set user info
- let userinfo: user.UserInfo = {
- secretId: credential.secretId,
- secretKey: credential.secretKey,
- uin: stsResp.PrincipalId ?? stsResp.UserId ?? "-",
- type: stsResp.Type ?? "unknow",
- appid: String(camResp.AppId ?? "-"),
- arn: stsResp.Arn,
- region: credential.region ?? "unknow",
- };
- return userinfo;
- }
-}
-
-export default user;
\ No newline at end of file
diff --git a/src/connectivity/client.ts b/src/connectivity/client.ts
deleted file mode 100644
index f724487..0000000
--- a/src/connectivity/client.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-/* eslint-disable @typescript-eslint/naming-convention */
-"use strict";
-
-import * as vscode from "vscode";
-import { Client as CvmClient } from "tencentcloud-sdk-nodejs-cvm/tencentcloud/services/cvm/v20170312/cvm_client";
-import { Client as TkeClient } from "tencentcloud-sdk-nodejs-tke/tencentcloud/services/tke/v20180525/tke_client";
-import { Client as StsClient } from "tencentcloud-sdk-nodejs-sts/tencentcloud/services/sts/v20180813/sts_client";
-import { Client as CamClient } from "tencentcloud-sdk-nodejs-cam/tencentcloud/services/cam/v20190116/cam_client";
-import { AbstractClient } from "tencentcloud-sdk-nodejs/tencentcloud/common/abstract_client";
-import * as tencentcloud from "tencentcloud-sdk-nodejs";
-import { localize } from "vscode-nls-i18n";
-import * as settingUtils from "../utils/settingUtils";
-
-const DefaultReqCliHeader = { "X-TC-RequestClient": "Terraform-Vscode-v0.0.26" };
-
-export async function getTkeClient(): Promise {
- const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
-
- if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
- let msg = localize("TcTerraform.msg.aksk.notfound");
- console.error(msg);
- return null;
- }
-
- return new TkeClient({
- credential: {
- secretId: secretId,
- secretKey: secretKey,
- },
- region: region ?? "ap-guangzhou",
- profile: {
- signMethod: "TC3-HMAC-SHA256", // 签名方法
- httpProfile: {
- reqMethod: "POST", // 请求方法
- reqTimeout: 30, // 请求超时时间,默认60s
- headers: DefaultReqCliHeader,
- },
- },
- });
-}
-
-export async function getCvmClient(): Promise {
- const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
-
- if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
- let msg = localize("TcTerraform.msg.aksk.notfound");
- console.error(msg);
- return null;
- }
-
- return new CvmClient({
- credential: {
- secretId: secretId,
- secretKey: secretKey,
- },
- // 产品地域
- region: region ?? "ap-guangzhou",
- // 可选配置实例
- profile: {
- // signMethod: "TC3-HMAC-SHA256", // 签名方法
- httpProfile: {
- reqMethod: "POST", // 请求方法
- // reqTimeout: 60, // 请求超时时间,默认60s
- endpoint: "cvm.tencentcloudapi.com",
- headers: DefaultReqCliHeader,
- },
- },
- });
-}
-
-export async function getCommonClient(ep?, version?, reqCli?: string): Promise {
- const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
-
- if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
- let msg = localize("TcTerraform.msg.aksk.notfound");
- console.error(msg);
- return null;
- }
-
- const client = new AbstractClient(
- ep ?? "open.test.tencentcloudapi.com",
- version ?? "2018-12-25",
- {
- credential: {
- secretId: secretId,
- secretKey: secretKey,
- },
- region: region ?? "ap-guangzhou",
- profile: {
- httpProfile: {
- reqMethod: "POST", // 请求方法
- endpoint: ep ?? "open.test.tencentcloudapi.com",
- headers: DefaultReqCliHeader,
- },
- },
- }
- );
- client.sdkVersion = reqCli ?? "Terraform-1.81.61@vscode";
-
- return client;
-}
-
-export async function getStsClient(): Promise {
- const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
-
- if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
- let msg = localize("TcTerraform.msg.aksk.notfound");
- console.error(msg);
- return null;
- }
-
- return new StsClient({
- credential: {
- secretId: secretId,
- secretKey: secretKey,
- },
- region: region ?? "ap-guangzhou",
- });
-}
-
-export async function getCamClient(): Promise {
- const [secretId, secretKey, region] = settingUtils.getAKSKandRegion();
-
- if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
- let msg = localize("TcTerraform.msg.aksk.notfound");
- console.error(msg);
- return null;
- }
-
- return new CamClient({
- credential: {
- secretId: secretId,
- secretKey: secretKey,
- },
- region: region ?? "ap-guangzhou",
- });
-}
diff --git a/src/extension.ts b/src/extension.ts
deleted file mode 100644
index 2320d1d..0000000
--- a/src/extension.ts
+++ /dev/null
@@ -1,149 +0,0 @@
-// The module 'vscode' contains the VS Code extensibility API
-// Import the module and reference it with the alias vscode in your code below
-import * as vscode from 'vscode';
-import { init } from "vscode-nls-i18n";
-import { TerraformCommand, TerraformerCommand } from "./commons/customCmdRegister";
-import { terraformShellManager } from "./client/terminal/terraformShellManager";
-import { DialogOption } from "./utils/uiUtils";
-import { TerraformTipsProvider, TIPS_TRIGGER_CHARACTER } from './autocomplete/TerraformTipsProvider';
-import { TerraformResDocProvider } from './autocomplete/TerraformResDocProvider';
-import { registerExternelCommands, bindExtensionContext } from './commons';
-import { registerView } from './views';
-import { TerraformRunner } from './client/runner/terraformRunner';
-import { TerraformerRunner } from './client/runner/terraformerRunner';
-import { GitUtils } from './utils/gitUtils';
-import _ from 'lodash';
-import * as autocomplete from './autocomplete/TerraformExampleProvider';
-import * as loginMgt from './views/login/loginMgt';
-import * as context from './commons/context';
-import { Constants } from './commons/constants';
-import user from "@/commons/tencent/user/index";
-
-const TF_MODE: vscode.DocumentFilter = { language: 'terraform', scheme: 'file' };
-const COMPATIBLE_MODE: vscode.DocumentFilter = { scheme: 'file' };
-
-// This method is called when your extension is activated
-// Your extension is activated the very first time the command is executed
-export async function activate(context: vscode.ExtensionContext) {
- console.log('Congratulations, your extension "TencentCloud Terraform" is now active!');
- bindExtensionContext(context);
-
- await TerraformRunner.getInstance().checkInstalled();
- await TerraformerRunner.getInstance().checkInstalled();
-
- // set request client for all of Terminal
- await setRequestClientOnTerminal();
- // terraform cmd
- context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.apply', async () => {
- (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Apply);
- }));
-
- context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.refresh', async () => {
- (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Refresh);
- }));
-
- context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.destroy', async () => {
- (await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Destroy);
- }));
-
- // git operations
- context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.git.push', async () => {
- if (_.isEmpty(vscode.workspace.workspaceFolders)) {
- vscode.window.showInformationMessage("Please open a workspace in VS Code first.");
- return;
- }
- await GitUtils.getInstance().submitToGit();
- }));
-
- // terraformer cmd
- let disposableTferImport = vscode.commands.registerCommand('tcTerraformer.import', async () => {
- (await terraformShellManager.getShell()).runTerraformCmd(TerraformerCommand.Import);
- });
-
- context.subscriptions.push(disposableTferImport);
-
- let disposableTferPlan = vscode.commands.registerCommand('tcTerraformer.plan', async () => {
- (await terraformShellManager.getShell()).runTerraformCmd(TerraformerCommand.Plan);
- });
-
- context.subscriptions.push(disposableTferPlan);
-
- // auto-complete
- console.log('activate the auto-complete(resource and argument) feature');
- const exampleProvider = new autocomplete.TerraformExampleProvider();
- context.subscriptions.push(vscode.languages.registerCompletionItemProvider(TF_MODE, exampleProvider, autocomplete.EXAMPLE_TRIGGER_CHARACTER));
-
- // tips
- console.log('activate the tips(options and doc) feature');
- const tipsProvider = new TerraformTipsProvider(context.extensionPath);
- context.subscriptions.push(
- vscode.workspace.onDidChangeTextDocument((event) => {
- tipsProvider.handleCharacterEvent(event);
- })
- );
- context.subscriptions.push(vscode.languages.registerCompletionItemProvider(TF_MODE, tipsProvider, ...TIPS_TRIGGER_CHARACTER));
-
- context.subscriptions.push(vscode.commands.registerCommand('tcTerraform.doc.show', () => {
- const editor = vscode.window.activeTextEditor;
- if (!editor) {
- return; // no editor opening
- }
-
- // get the words under current selection
- const doc = editor.document;
- const selection = editor.selection;
- const words = doc.getWordRangeAtPosition(selection.start);
- const resType = doc.getText(words);
-
- const regex = /^tencentcloud(?:_[^\s]+)*$/;
- if (!regex.test(resType)) {
- return; // not match the regex
- }
- TerraformResDocProvider.createOrShow(context, resType);
- }));
-
- // example
- console.log('activate the auto complete(example) feature');
- let disposableExample = vscode.commands.registerCommand(autocomplete.EXAMPLE_CMD, autocomplete.handleExampleCmd());
- context.subscriptions.push(disposableExample);
-
- // import-resource
- console.log('activate the import feature');
- init(context.extensionPath);
- registerExternelCommands();
- registerView();
-
- // reg login status
- let disposableLoginStatusBar = loginMgt.createStatusBar();
- context.subscriptions.push(disposableLoginStatusBar);
-
-}
-
-async function setRequestClientOnTerminal() {
- const config = vscode.workspace.getConfiguration('terminal.integrated.env');
- const os = getOSPlatform();
- const curConfig = config[os] || {};
-
- const reqCli = await context.genRequestClient();
- const updatedConfig = { ...curConfig, [Constants.REQUEST_CLIENT]: reqCli }; // set ReqCli for all Terminal
-
- await config.update(os, updatedConfig, vscode.ConfigurationTarget.Global);
-}
-
-function getOSPlatform(): string {
- const platform = process.platform;
- switch (platform) {
- case 'win32':
- return 'windows';
- case 'darwin':
- return 'osx';
- case 'linux':
- default:
- return 'linux';
- }
-}
-
-// This method is called when your extension is deactivated
-export async function deactivate() {
- await user.clearInfo();
-}
diff --git a/src/import/cvm.ts b/src/import/cvm.ts
deleted file mode 100644
index 31796a4..0000000
--- a/src/import/cvm.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-"use strict";
-
-import * as client from "../connectivity/client";
-import { Instance } from "tencentcloud-sdk-nodejs-cvm/tencentcloud/services/cvm/v20170312/cvm_models";
-import { ITencentCloudAPI } from "../commons/tencent/sdkApi";
-import { window } from "vscode";
-
-export class CvmService implements ITencentCloudAPI {
- async getConfig(params?: any): Promise {
- return {
- 'product': 'cvm',
- 'resource': {
- 'name': "tencentcloud_instance",
- //'xxx': "yyy"
- },
- 'import': {
- 'file': 'cvm.tf'
- }
- };
- }
-
- async describeInstances(params?: any): Promise {
- const cvmClient = await client.getCvmClient();
- const res = await cvmClient?.DescribeInstances({
- // find all instances
- }).then(
- (result) => {
- // console.debug('[DEBUG]--------------------------------result:', result);
- if (result.TotalCount === 0) {
- console.warn('[Warn] DescribeInstances result.TotalCount is 0.');
- }
- return result.InstanceSet;
- },
- (err) => {
- console.error('[TencentCloudSDKError] DescribeInstances got a error from SDK.', err.message);
- return err;
- }
- );
-
- return res;
- }
-}
-
-// export async function describeInstances(params:any): Promise {
-// const res = await (await client.getCvmClient()).DescribeInstances({}).then(result => {
-// console.warn('--------------------------------result:', result);
-// if (result.TotalCount === 0) {
-// throw new Error('[Warn] DescribeInstances result.TotalCount is 0.');
-// }
-
-// return result.InstanceSet;
-// }).catch((error) => {
-// console.error(error);
-// return error;
-// });
-
-// return res;
-// }
diff --git a/src/import/mysql.ts b/src/import/mysql.ts
deleted file mode 100644
index 58c3954..0000000
--- a/src/import/mysql.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { ITencentCloudAPI } from "../commons/tencent/sdkApi";
-
-export class MysqlService implements ITencentCloudAPI {
- describeInstances(params?: any): Promise {
- throw new Error("Method not implemented.");
- }
- getConfig(params?: any): Promise {
- throw new Error("Method not implemented.");
- }
-
-}
\ No newline at end of file
diff --git a/src/import/tke.ts b/src/import/tke.ts
deleted file mode 100644
index 2205a80..0000000
--- a/src/import/tke.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { ITencentCloudAPI } from "../commons/tencent/sdkApi";
-
-export class TkeService implements ITencentCloudAPI {
- describeInstances(params?: any): Promise {
- throw new Error("Method not implemented.");
- }
- getConfig(params?: any): Promise {
- throw new Error("Method not implemented.");
- }
-}
\ No newline at end of file
diff --git a/src/utils/cpUtils.ts b/src/utils/cpUtils.ts
deleted file mode 100644
index 50cfe15..0000000
--- a/src/utils/cpUtils.ts
+++ /dev/null
@@ -1,59 +0,0 @@
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Tencent Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-"use strict";
-
-import * as cp from "child_process";
-import { terraformChannel } from "../client/terminal/terraformChannel";
-
-export async function executeCommand(command: string, args: string[], options: cp.SpawnOptions): Promise {
- return new Promise((resolve: (res: string) => void, reject: (e: Error) => void): void => {
- let result: string = "";
- const stripAnsi = require('strip-ansi');
- const childProc: cp.ChildProcess = cp.spawn(command, args, options);
-
- childProc.stdout.on("data", (raw: string | Buffer) => {
- const data = stripAnsi(raw.toString());
- console.debug("[DEBUG]#### executeCommand received data:[%s]", data);
-
- result = result.concat(data);
- terraformChannel.append(data);
- });
-
- childProc.stderr.on("data", (raw: string | Buffer) => {
- const data = stripAnsi(raw.toString());
- console.error("Error found in stderr.on: %s", data);
- terraformChannel.append(data);
- });
-
- childProc.on("error", (err: any) => {
- console.error("Error found in childProc.on error: %s", err);
- // reject(err);
- });
-
- childProc.on("close", (code: number) => {
- if (code !== 0) {
- reject(new Error(`Command "${command} ${args.toString()}" failed with exit code "${code}".`));
- } else {
- resolve(result);
- }
- });
- });
-}
-
-export async function executeCommandByExec(command: string, cwd?: string): Promise {
- return new Promise((resolve, reject) => {
- const options = {
- cwd,
- };
- cp.exec(command, options, (error, stdout, stderr) => {
- if (error) {
- reject(`child_process exec failed: error:[${error}], stderr:[${stderr}]`);
- } else {
- resolve(stdout);
- }
- });
- });
-}
diff --git a/src/utils/dotUtils.ts b/src/utils/dotUtils.ts
deleted file mode 100644
index e90db93..0000000
--- a/src/utils/dotUtils.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Tencent Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-"use strict";
-
-import { executeCommand } from "./cpUtils";
-import { openUrlHint } from "./uiUtils";
-
-export async function isDotInstalled(): Promise {
- try {
- await executeCommand("dot", ["-V"], { shell: true });
- return true;
- } catch (error) {
- openUrlHint("GraphViz is not installed, please make sure GraphViz is in the PATH environment variable.", "https://aka.ms/azTerraform-requirement");
- return false;
- }
-}
-
-export async function drawGraph(workingDirectory: string, inputFile: string): Promise {
- await executeCommand(
- "dot",
- ["-Tpng", "-o", "graph.png", inputFile],
- {
- cwd: workingDirectory,
- shell: true,
- },
- );
-}
diff --git a/src/utils/gitUtils.ts b/src/utils/gitUtils.ts
deleted file mode 100644
index 525a3a3..0000000
--- a/src/utils/gitUtils.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import * as vscode from 'vscode';
-import { exec } from 'child_process';
-import path from 'path';
-import * as fs from 'fs';
-import * as workspaceUtils from "./workspaceUtils";
-
-export class GitUtils {
- private static instance: GitUtils;
-
- public static getInstance(): GitUtils {
- if (!GitUtils.instance) {
- GitUtils.instance = new GitUtils();
- }
- return GitUtils.instance;
- }
-
- public async submitToGit(): Promise {
- console.debug("[DEBUG]#### GitUtils submitToGit begin.");
- const gitRootPath = workspaceUtils.getActiveEditorPath();
- if (!gitRootPath) {
- vscode.window.showErrorMessage('Please open a workspace folder first!');
- return;
- }
-
- if (fs.existsSync(path.join(gitRootPath, '.git'))) {
- vscode.window.showInformationMessage('Trying to fetch from Git, please wait...');
- await this.fetchFromGit(gitRootPath);
- } else {
- vscode.window.showInformationMessage(`You are not in a git repository yet, trying to clone from your Git repo...`);
- await this.cloneFromGit(gitRootPath);
- }
-
- console.debug("[DEBUG]#### GitUtils pushToGit begin.");
- try {
- const output = await this.gitPush(gitRootPath);
- vscode.window.showInformationMessage(`Code has been successfully submitted to Git repo!\nDetail:[${output}]`);
- } catch (error) {
- vscode.window.showErrorMessage(`Failed to submit code: ${error.message}`);
- }
- }
-
- private async cloneFromGit(rootPath: string): Promise {
- console.debug("[DEBUG]#### GitUtils cloneFromGit begin.");
- await vscode.window.showInputBox({ prompt: 'Please enter the Git repository URL:' }).then(async (url) => {
- if (url) {
- const folderName = url.split('/').pop()?.replace('.git', '');
- const clonePath = rootPath ? `${rootPath}/${folderName}` : folderName || '';
- if (fs.existsSync(clonePath)) {
- console.debug("[DEBUG]#### GitUtils cloneFromGit: clean and remove the clonePath before cloning the repository.");
- fs.rm(clonePath, { recursive: true }, () => { });
- }
-
- console.debug("[DEBUG]#### GitUtils cloneFromGit exec:[git clone %s %s].", url, clonePath);
- exec(`git clone ${url} ${clonePath}`, {}, (error, stdout, stderr) => {
- if (error) {
- vscode.window.showErrorMessage(`Failed to clone code: ${error.message}`);
- return;
- }
- if (stderr) {
- vscode.window.showErrorMessage(`Failed to clone code: ${stderr}`);
- return;
- }
- vscode.window.showInformationMessage('Code has been successfully cloned from Git repo!');
- });
- }
- });
- }
-
- private gitPush(rootPath: string): Promise {
- return new Promise((resolve, reject) => {
- exec('git add . && git commit -m "committed by VS Code" && git push', { cwd: rootPath }, (error, stdout, stderr) => {
- if (error) {
- reject(error);
- return;
- }
- if (stdout) {
- resolve(stdout);
- return;
- }
- if (stderr) {
- reject(new Error(stderr));
- }
- });
- });
- }
-
- private gitPull(rootPath: string): Promise {
- return new Promise((resolve, reject) => {
- exec('git pull', { cwd: rootPath }, (error, stdout, stderr) => {
- if (error) {
- reject(error);
- return;
- }
- if (stderr) {
- reject(new Error(stderr));
- return;
- }
- resolve();
- });
- });
- }
-
- private async fetchFromGit(rootPath: string): Promise {
- console.debug("[DEBUG]#### GitUtils fetchFromGit begin.");
- try {
- await this.gitPull(rootPath);
- vscode.window.showInformationMessage('Code has been successfully fetched from Git repo!');
- } catch (error) {
- vscode.window.showErrorMessage(`Failed to fetch code: ${error.message}`);
- }
- }
-
-}
-
-
diff --git a/src/utils/helper.ts b/src/utils/helper.ts
deleted file mode 100644
index 2f7c258..0000000
--- a/src/utils/helper.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-'use strict';
-
-import { Function } from "lodash";
-import { Func } from "mocha";
-
-export async function retryF(func: () => Promise<{ stdout: string, stderr: string }>): Promise {
- const command = "terraform state rm tencentcloud_instance.foo";
- const maxRetry = 3;
- let retryCount = 1;
-
- while (true) {
- try {
- const result = await func();
- console.log(result.stdout);
-
- // retry "Error acquiring the state lock"
- if (/Error acquiring the state lock/.test(result.stderr)) {
- if (retryCount < maxRetry) {
- retryCount++;
- console.log(`Retrying (${retryCount}/${maxRetry})...`);
- await new Promise(resolve => setTimeout(resolve, 500)); // wait for 5 seconds before retrying
- continue;
- } else {
- console.warn("[WARN]#### Max retry count reached.");
- return;
- }
- }
- if (/Invalid target address/.test(result.stderr) || /read-only file system/.test(result.stderr)) {
- console.log(`Invalid target address is accepted: ${result.stderr}`);
- return;
- }
- } catch (error) {
- if (/Error acquiring the state lock/.test(error.message)) {
- if (retryCount < maxRetry) {
- retryCount++;
- console.log(`An error occurred executing "${command}": ${error.message}. Retrying...`);
- await new Promise(resolve => setTimeout(resolve, 500)); // wait for 5 seconds before retrying
- continue;
- } else {
- console.warn("[WARN]#### Max retry count reached.");
- return;
- }
- } else if (/Invalid target address/.test(error.message) || /read-only file system/.test(error.message)) {
- return;
- } else {
- console.error(error);
- return;
- }
- }
- }
-}
\ No newline at end of file
diff --git a/src/utils/icons.ts b/src/utils/icons.ts
deleted file mode 100644
index ddeeaf3..0000000
--- a/src/utils/icons.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-// @ts-ignore
-import { ThemeIcon } from 'vscode';
-
-export class Icons {
- public static getIcon(id:string): ThemeIcon {
- // @ts-ignore
- return Icons.getIcon(id);
- }
-}
-
diff --git a/src/utils/settingUtils.ts b/src/utils/settingUtils.ts
deleted file mode 100644
index 4008793..0000000
--- a/src/utils/settingUtils.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Tencent Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-import * as vscode from "vscode";
-import * as cpUtils from "./cpUtils";
-import * as uiUtils from "./uiUtils";
-import exp from "constants";
-
-export function isTerminalSetToCloudShell(): boolean {
- return vscode.workspace.getConfiguration().get("tcTerraform.terminal") === "cloudshell";
-}
-
-export function getSyncFileBlobPattern(): vscode.GlobPattern {
- return vscode.workspace.getConfiguration().get("tcTerraform.files");
-}
-
-export function getPathForTest(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.test.path");
-}
-
-export function getSecretIdCmd(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.secretid.cmd");
-}
-
-export function getSecretKeyCmd(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.secretkey.cmd");
-}
-
-export function getSecretIdFromUI(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.properties.secretId");
-}
-
-export function getSecretKeyFromUI(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.properties.secretKey");
-}
-
-export function getRegionFromUI(): string {
- return vscode.workspace.getConfiguration().get("tcTerraform.properties.region");
-}
-
-export async function clearSecretId() {
- process.env.TENCENTCLOUD_SECRET_ID = undefined;
- delete process.env.TENCENTCLOUD_SECRET_ID;
- await vscode.workspace.getConfiguration().update("tcTerraform.properties.secretId", undefined, vscode.ConfigurationTarget.Global);
-}
-
-export async function clearSecretKey() {
- process.env.TENCENTCLOUD_SECRET_KEY = undefined;
- delete process.env.TENCENTCLOUD_SECRET_KEY;
- await vscode.workspace.getConfiguration().update("tcTerraform.properties.secretKey", undefined, vscode.ConfigurationTarget.Global);
-}
-
-export async function clearRegion() {
- process.env.TENCENTCLOUD_REGION = undefined;
- delete process.env.TENCENTCLOUD_REGION;
- await vscode.workspace.getConfiguration().update("tcTerraform.properties.region", undefined, vscode.ConfigurationTarget.Global);
-}
-
-export function getAKSKandRegion(): [string, string, string] {
- const secretIdConfig = getSecretIdFromUI();
- const secretKeyConfig = getSecretKeyFromUI();
- const secretIdEnv = getSecretIdFromEnv();
- const secretKeyEnv = getSecretKeyFromEnv();
- const regionConfig = getRegionFromUI();
- const regionEnv = getRegionFromEnv();
-
- return [secretIdConfig || secretIdEnv, secretKeyConfig || secretKeyEnv, regionConfig || regionEnv];
-}
-
-export function clearAKSKandRegion() {
- clearRegion();
- clearSecretId();
- clearSecretKey();
-}
-
-export function getSecretIdFromEnv(): string {
- return process.env.TENCENTCLOUD_SECRET_ID;
-}
-
-export function getSecretKeyFromEnv(): string {
- return process.env.TENCENTCLOUD_SECRET_KEY;
-}
-
-export function getRegionFromEnv(): string {
- return process.env.TENCENTCLOUD_REGION;
-}
-
-export function getCheckTCCLI(): boolean {
- return vscode.workspace.getConfiguration().get("tcTerraform.checkTCCLI");
-}
-
-export function setCheckTCCLI(checked: boolean): void {
- vscode.workspace.getConfiguration().update("tcTerraform.checkTCCLI", checked);
-}
-
-export async function checkTCCLIInstalled(): Promise {
- if (isTerminalSetToCloudShell() || !getCheckTCCLI()) {
- return;
- }
- try {
- await cpUtils.executeCommand("tccli", ["help"], { shell: true });
- } catch (error) {
- uiUtils.openUrlHintOrNotShowAgain("TCCLI is not installed, please install it before use extension.",
- "https://www.tencentcloud.com/document/product/1013/33464",
- () => {
- // setCheckTerraformCmd(false);
- });
- }
-}
-
-// export function getSecretId(): Promise {
-// if (isTerminalSetToCloudShell() || !checkTCCLIInstalled()) {
-// return;
-// }
-// let cmd=getSecretIdCmd();
-
-// try {
-// cpUtils.executeCommand(cmd, null, { shell: true });
-// } catch (error) {
-// uiUtils.openUrlHintOrNotShowAgain("Get Secret Id failed, please check your `tcTerraform.secretid.cmd` in setting.json.",
-// "./setting.json",
-// () => {
-// vscode.window.showErrorMessage("Get Secret Id failed, please check your `tcTerraform.secretid.cmd` in setting.json.")
-// });
-// }
-// }
-
-// export function getSecretKey(): Promise {
-// if (isTerminalSetToCloudShell() || !checkTCCLIInstalled()) {
-// return;
-// }
-// let cmd=getSecretIdCmd();
-
-// try {
-// cpUtils.executeCommand(cmd, null, { shell: true });
-// } catch (error) {
-// uiUtils.openUrlHintOrNotShowAgain("Get Secret Id failed, please check your `tcTerraform.secretid.cmd` in setting.json.",
-// "./setting.json",
-// () => {
-// vscode.window.showErrorMessage("Get Secret Id failed, please check your `tcTerraform.secretid.cmd` in setting.json.")
-// });
-// }
-// }
diff --git a/src/utils/uiUtils.ts b/src/utils/uiUtils.ts
deleted file mode 100644
index 802b8b6..0000000
--- a/src/utils/uiUtils.ts
+++ /dev/null
@@ -1,78 +0,0 @@
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Tencent Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-"use strict";
-
-// import * as opn from "opn";
-import opn from "opn";
-import * as vscode from "vscode";
-import { terraformChannel } from "../client/terminal/terraformChannel";
-
-export async function openUrlHintOrNotShowAgain(message: string, url: string, notShowCallback: () => void): Promise {
- const response = await vscode.window.showInformationMessage(message, DialogOption.learnMore, DialogOption.notShownAgain);
- if (response === DialogOption.learnMore && url) {
- opn(url);
- } else if (response === DialogOption.notShownAgain) {
- notShowCallback();
- }
-}
-
-export async function openUrlHint(message: string, url: string): Promise {
- const response = await vscode.window.showInformationMessage(message, DialogOption.learnMore, DialogOption.cancel);
- if (response === DialogOption.learnMore && url) {
- opn(url);
- }
-}
-
-export async function showFolderDialog(): Promise {
- const defaultUri: vscode.Uri | undefined = vscode.workspace.rootPath ? vscode.Uri.file(vscode.workspace.rootPath) : undefined;
- const options: vscode.OpenDialogOptions = {
- canSelectFiles: false,
- canSelectFolders: true,
- canSelectMany: false,
- openLabel: "Select",
- defaultUri,
- };
- const result: vscode.Uri[] | undefined = await vscode.window.showOpenDialog(options);
- if (!result || result.length === 0) {
- return undefined;
- }
- return result[0];
-}
-
-export async function promptForOpenOutputChannel(message: string, type: DialogType): Promise {
- let result: vscode.MessageItem;
- switch (type) {
- case DialogType.info:
- result = await vscode.window.showInformationMessage(message, DialogOption.open, DialogOption.cancel);
- break;
- case DialogType.warning:
- result = await vscode.window.showWarningMessage(message, DialogOption.open, DialogOption.cancel);
- break;
- case DialogType.error:
- result = await vscode.window.showErrorMessage(message, DialogOption.open, DialogOption.cancel);
- break;
- default:
- break;
- }
-
- if (result === DialogOption.open) {
- terraformChannel.show();
- }
-}
-
-export namespace DialogOption {
- export const ok: vscode.MessageItem = { title: "OK" };
- export const cancel: vscode.MessageItem = { title: "Cancel", isCloseAffordance: true };
- export const open: vscode.MessageItem = { title: "Open" };
- export const learnMore: vscode.MessageItem = { title: "Learn More" };
- export const notShownAgain: vscode.MessageItem = { title: "Don't show again" };
-}
-
-export enum DialogType {
- info = "info",
- warning = "warning",
- error = "error",
-}
diff --git a/src/utils/workspaceUtils.ts b/src/utils/workspaceUtils.ts
deleted file mode 100644
index 190da30..0000000
--- a/src/utils/workspaceUtils.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-/*---------------------------------------------------------------------------------------------
- * Copyright (c) Tencent Corporation. All rights reserved.
- * Licensed under the MIT License. See License.txt in the project root for license information.
- *--------------------------------------------------------------------------------------------*/
-
-"use strict";
-
-import * as _ from "lodash";
-import * as vscode from "vscode";
-import { DialogOption, showFolderDialog } from "./uiUtils";
-import * as path from "path";
-
-export async function selectWorkspaceFolder(): Promise {
- let folder: vscode.WorkspaceFolder;
- if (!_.isEmpty(vscode.workspace.workspaceFolders)) {
- if (vscode.workspace.workspaceFolders.length > 1) {
- folder = await vscode.window.showWorkspaceFolderPick({
- placeHolder: "Select the working directory you wish to use",
- ignoreFocusOut: true,
- });
- } else {
- folder = vscode.workspace.workspaceFolders[0];
- }
- } else {
- const response = await vscode.window.showInformationMessage(
- "There is no folder opened in current workspace, would you like to open a folder?",
- DialogOption.open,
- DialogOption.cancel,
- );
- if (response === DialogOption.open) {
- const selectedFolder: vscode.Uri = await showFolderDialog();
- if (selectedFolder) {
- /**
- * Open the selected folder in a workspace.
- * NOTE: this will restart the extension host.
- * See: https://github.com/Microsoft/vscode/issues/58
- */
- await vscode.commands.executeCommand("vscode.openFolder", selectedFolder, false /* forceNewWindow */);
- }
- }
- }
- return folder ? folder.uri.fsPath : undefined;
-}
-
-export function getActiveEditorPath(): string {
- const activeEditor = vscode.window.activeTextEditor;
- if (!activeEditor) {
- vscode.window.showInformationMessage('No active editor found.');
- return "";
- }
-
- const activeDocument = activeEditor.document;
- if (!activeDocument) {
- vscode.window.showInformationMessage('No active document found.');
- return "";
- }
-
- const activeDocumentPath = path.dirname(activeDocument.uri.fsPath);
- return activeDocumentPath;
-}
diff --git a/src/views/help/helpExplorer.ts b/src/views/help/helpExplorer.ts
deleted file mode 100644
index 3565c74..0000000
--- a/src/views/help/helpExplorer.ts
+++ /dev/null
@@ -1,58 +0,0 @@
-import { ThemeIcon } from "vscode";
-import { localize } from "vscode-nls-i18n";
-
-import { container, tencent, cmds } from "../../commons";
-
-const { tree } = tencent;
-
-const { TreeDataProvider, TreeItem } = tree;
-
-export class HelpProvider extends TreeDataProvider {
- async getChildren(element?: tencent.tree.TreeItem | undefined): Promise {
- if (!element) {
- const elements = [
- new TreeItem(localize("TcTerraform.view.help.provider"), {
- // iconPath: Icons.getIcon("tools"),
- command: {
- command: cmds.openURL,
- title: "",
- arguments: ["https://registry.terraform.io/providers/tencentcloudstack/tencentcloud/latest"],
- },
- }),
- new TreeItem(localize("TcTerraform.view.help.doc"), {
- // iconPath: Icons.getIcon("book"),
- command: {
- command: cmds.openURL,
- title: "",
- arguments: ["https://cloud.tencent.com/product/tiat"],
- },
- }),
- new TreeItem(localize("TcTerraform.view.help.repo"), {
- // iconPath: Icons.getIcon("github"),
- command: {
- command: cmds.openURL,
- title: "",
- arguments: ["https://github.com/tencentcloudstack/terraform-provider-tencentcloud"],
- },
- }),
- ];
-
- // const info = await user.getInfo();
- // if (info) {
- // elements.push(
- // new TreeItem(localize("tencent.loginout", info.uin), {
- // iconPath: Icons.getIcon("account"),
- // command: { command: tencent.command.TENCENT_LOGINOUT, title: "" },
- // })
- // );
- // }
-
- return elements;
- }
- return [];
- }
-}
-
-container.bind(HelpProvider).toSelf().inSingletonScope();
-
-container.bind(tencent.tree.TencentTreeProvider).toService(HelpProvider);
diff --git a/src/views/help/index.ts b/src/views/help/index.ts
deleted file mode 100644
index 2d95c8c..0000000
--- a/src/views/help/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { window } from "vscode";
-
-import { container } from "../../commons/container";
-import { HelpProvider } from "./helpExplorer";
-
-export function registerHelp() {
- window.registerTreeDataProvider("tcTerraform.helpExplorer", container.get(HelpProvider));
-}
\ No newline at end of file
diff --git a/src/views/index.ts b/src/views/index.ts
deleted file mode 100644
index 2e62530..0000000
--- a/src/views/index.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { registerHelp } from "./help";
-import { registerLogin } from "./login";
-import { registerResources } from "./resources";
-
-export function registerView() {
- registerHelp();
- registerResources();
- registerLogin();
-}
diff --git a/src/views/login/index.ts b/src/views/login/index.ts
deleted file mode 100644
index 70f5af6..0000000
--- a/src/views/login/index.ts
+++ /dev/null
@@ -1,8 +0,0 @@
-import { window } from "vscode";
-
-import { container } from "../../commons/container";
-import { LoginProvider } from "./loginExplorer";
-
-export function registerLogin() {
- window.registerTreeDataProvider("tcTerraform.loginExplorer", container.get(LoginProvider));
-}
\ No newline at end of file
diff --git a/src/views/login/loginExplorer.ts b/src/views/login/loginExplorer.ts
deleted file mode 100644
index db9c106..0000000
--- a/src/views/login/loginExplorer.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { localize } from "vscode-nls-i18n";
-import { window, ThemeIcon } from "vscode";
-import { container, tencent } from "../../commons";
-import { getSecretIdFromEnv, getSecretKeyFromEnv, clearAKSKandRegion } from "../../utils/settingUtils";
-import { user } from "../../commons/tencent/user/index";
-import * as loginMgt from "./loginMgt";
-
-export class LoginProvider extends tencent.tree.TreeDataProvider {
- private loggedIn = false;
-
- constructor() {
- super();
- this.loggedIn = false;
- }
-
- setLoggedIn(value: boolean) {
- this.loggedIn = value;
- }
-
- async isLoggedIn(): Promise {
- if (getSecretIdFromEnv() && getSecretKeyFromEnv()) {
- const userInfo = await user.getInfo();
- if (!userInfo || !userInfo.secretId || userInfo.secretId === '') {
- return false;
- }
- return true;
- }
- return false;
- }
-
- async getChildren(element?: tencent.tree.TreeItem | undefined): Promise {
- let items: tencent.tree.TreeItem[] = [];
- if (!element) {
- if (!await this.isLoggedIn()) {
- window.showInformationMessage(localize("TcTerraform.login.msg.need.login"));
- clearAKSKandRegion();
- return items;
- }
-
- const info = await user.getInfo();
- if (info) {
- let welcome = new tencent.tree.TreeItem(`Current Account: [${info.uin}](${info.type})`, {
- iconPath: new ThemeIcon("account"),
- });
- items.push(welcome);
- loginMgt.updateStatusBar();
-
- let logout = new tencent.tree.TreeItem(localize("TcTerraform.view.logout"), {
- iconPath: new ThemeIcon("log-out"),
- command: { command: tencent.command.TENCENT_LOGINOUT, title: "Log Out" },
- });
- items.push(logout);
- }
- }
- return items;
- }
-
-}
-
-container.bind(LoginProvider).toSelf().inSingletonScope();
-
-container.bind(tencent.tree.TencentTreeProvider).toService(LoginProvider);
diff --git a/src/views/login/loginMgt.ts b/src/views/login/loginMgt.ts
deleted file mode 100644
index ae74c99..0000000
--- a/src/views/login/loginMgt.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import * as vscode from "vscode";
-import { user } from "../../commons/tencent/user/index";
-import { localize } from "vscode-nls-i18n";
-
-let myStatusBarItem: vscode.StatusBarItem;
-
-export async function updateStatusBar(): Promise {
- const info = await user.getInfo();
- if (info) {
- myStatusBarItem.text = localize("TcTerraform.title") + ` / APPID: ${info.appid}`;
- myStatusBarItem.tooltip =
- `User Details:
-Uin: [${info.uin}]
-User type: [${info.type}]
-Region: [${info.region}]
-Arn: [${info.arn}]`;
- myStatusBarItem.show();
- } else {
- myStatusBarItem.hide();
- }
-}
-
-export function clearStatusBar() {
- myStatusBarItem.text = "";
- myStatusBarItem.hide();
-}
-
-export function createStatusBar(): vscode.StatusBarItem {
- myStatusBarItem = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100);
- myStatusBarItem.backgroundColor = new vscode.ThemeColor("statusBarItem.hoverBackground");
- // myStatusBarItem.command = TENCENT_LOGIN_STATUS;
- return myStatusBarItem;
-}
\ No newline at end of file
diff --git a/src/views/resources/index.ts b/src/views/resources/index.ts
deleted file mode 100644
index 5419113..0000000
--- a/src/views/resources/index.ts
+++ /dev/null
@@ -1,10 +0,0 @@
-import { window } from "vscode";
-
-import { container } from "../../commons/container";
-import { CvmResProvider, TkeResProvider } from "./resExplorer";
-
-export function registerResources() {
- // window.registerTreeDataProvider("tcTerraform.resourcesExplorer", container.get(CvmResProvider));
- window.registerTreeDataProvider("tcTerraform.resourcesExplorer.cvm", container.get(CvmResProvider));
- // window.registerTreeDataProvider("tcTerraform.resourcesExplorer.tke", container.get(TkeResProvider));
-}
\ No newline at end of file
diff --git a/src/views/resources/resExplorer.ts b/src/views/resources/resExplorer.ts
deleted file mode 100644
index d0adf8c..0000000
--- a/src/views/resources/resExplorer.ts
+++ /dev/null
@@ -1,110 +0,0 @@
-import { inject } from "inversify";
-import { ThemeIcon, TreeItem, TreeItemCollapsibleState, window } from "vscode";
-import { readFile } from "fs/promises";
-import { join } from "path";
-import * as vscode from "vscode";
-
-import { container, tencent, cmds } from "../../commons";
-import { res, IApiDoc } from "../../commons/tencent/types";
-import { Icons } from "../../utils/icons";
-import { CvmService } from "../../import/cvm";
-
-export const defaultResourceName = "foo";
-
-export class CvmResProvider extends tencent.tree.TreeDataProvider {
- private icons: { [key: string]: any };
-
- async getChildren(element?: tencent.tree.TreeItem | undefined): Promise {
- if (!element) {
- try {
- // TODO: replace with specified resource type
- const service = new CvmService();
- const instances = await service.describeInstances();
- const config = await service.getConfig();
- let items: tencent.tree.TreeItem[] = [];
- if (!Array.isArray(instances)) {
- return items;// return [] if instances nil
- }
-
- items = instances.length > 0
- ? instances.map(instance => ({
- label: `${instance.InstanceName}(${instance.InstanceId})`,
- id: instance.InstanceId,
- // iconPath: Icons.getIcon("book"),
- command: {
- command: cmds.executeTferImport,
- title: "",
- arguments: [{
- resource: {
- type: config.resource.name,
- name: defaultResourceName,
- id: instance.InstanceId
- },
- product: config.product,
- fileName: config.import.file,
- this: config
- }],
- },
- }))
- : [{ label: "No instance." }]; // return none tips if instance is empty
-
- return items;
- } catch (error) {
- console.error('[Error]#### getChildren got a error:[%s] from CvmService. stack:%s', error.message, error.stack);
- return [];
- }
-
- } else {
- if ("getChildren" in element) {
- return (element as ParentItem).getChildren(element);
- }
- }
-
- return [];
- }
-
- private async getFontIcons() {
- return readFile(join(__dirname, "../package.json")).then((buff) => {
- const { icons } = JSON.parse(buff.toString()).contributes;
- this.icons = icons;
- });
- }
-
- private async getIcon(name: string): Promise {
- const iconName = `${name}-icon`;
-
- return Icons.getIcon(this.icons[iconName] ? iconName : "default-icon");
- }
-}
-
-export class TkeResProvider extends tencent.tree.TreeDataProvider {
- private icons: { [key: string]: any };
- // vscode.window.showInformationMessage(`TkeResProvider is called`);
-
- async getChildren(element?: tencent.tree.TreeItem | undefined): Promise {
- vscode.window.showInformationMessage(`TkeResProvider is called`);
-
- return [];
- }
-}
-
-class ResourcesItem extends tencent.tree.TreeItem {
- constructor(private action: res.ActionSet, _iconPath: ThemeIcon) {
- // action.icon = iconPath.id;
- super(action.actionName, {
- command: {
- command: "OPEN_API_DOC",
- arguments: [action],
- title: "",
- },
- });
- }
-}
-
-interface ParentItem {
- getChildren(element: tencent.tree.TreeItem): Promise;
-}
-
-container.bind(CvmResProvider).toSelf().inSingletonScope();
-
-container.bind(tencent.tree.TencentTreeProvider).toService(CvmResProvider);
diff --git a/terraform.configuration.json b/terraform.configuration.json
deleted file mode 100644
index 341ccae..0000000
--- a/terraform.configuration.json
+++ /dev/null
@@ -1,28 +0,0 @@
-{
- "comments": {
- // symbol used for single line comment. Remove this entry if your language does not support line comments
- "lineComment": "#",
- // symbols used for start and end a block comment. Remove this entry if your language does not support block comments
- "blockComment": [ "/*", "*/" ]
- },
- // symbols used as brackets
- "brackets": [
- ["{", "}"],
- ["[", "]"],
- ["(", ")"]
- ],
- "autoClosingPairs": [
- { "open": "{", "close": "}" },
- { "open": "[", "close": "]" },
- { "open": "(", "close": ")" },
- { "open": "\"", "close": "\"", "notIn": ["string"] },
- { "open": "'", "close": "'", "notIn": ["string", "comment"] }
- ],
- "surroundingPairs": [
- ["{", "}"],
- ["[", "]"],
- ["(", ")"],
- ["\"", "\""],
- ["'", "'"]
- ]
-}
diff --git a/terraform.tfstate b/terraform.tfstate
deleted file mode 100644
index c141228..0000000
--- a/terraform.tfstate
+++ /dev/null
@@ -1,9 +0,0 @@
-{
- "version": 4,
- "terraform_version": "1.6.0",
- "serial": 1,
- "lineage": "1383ce09-0e23-874b-4a85-5e70c134da3b",
- "outputs": {},
- "resources": [],
- "check_results": null
-}
diff --git a/tool/scrape/Dockerfile b/tool/scrape/Dockerfile
deleted file mode 100644
index 309cdf0..0000000
--- a/tool/scrape/Dockerfile
+++ /dev/null
@@ -1,11 +0,0 @@
-FROM node:alpine
-COPY . /app
-COPY ../../package.json /app
-WORKDIR /app
-RUN npm i -g nodemon typescript
-RUN npm i
-RUN tsc
-RUN apk --update --no-cache add git
-RUN git clone https://github.com/tencentcloudstack/terraform-provider-tencentcloud.git
-# CMD node index.js
-ENTRYPOINT [ "node", "index.js" ]
\ No newline at end of file
diff --git a/tool/scrape/README.md b/tool/scrape/README.md
deleted file mode 100644
index 0313fd2..0000000
--- a/tool/scrape/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Terraform Scrape
-Scraping tool used to try to extract data from the terraform docs for the Visual Studio Code extension of TencentCloud IaC Terraform.
-
-## Usage
-### Build Script
-Run `./build.sh tiat/terraform-scrape:vx` to generate the `tiat-resources.json`.
-- `vx.x.x` is the docker image version want to generate.
-
-### Docker Cmd
-`docker run -it tiat/vscode-terraform-scrape`
-
-This will output any notices to stderr and output the json that needs to go in vscode-tencentcloud-terraform/xxx.json to stdout.
-- To generate resource defination, run: `docker run -it tiat/vscode-terraform-scrape > ../../config/tips/tiat-resources.json`.
diff --git a/tool/scrape/build.sh b/tool/scrape/build.sh
deleted file mode 100755
index c5cf206..0000000
--- a/tool/scrape/build.sh
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/usr/bin/env bash
-workdir=$(
- cd $(dirname $0)
- pwd
-)
-
-if [ $# == 0 ]; then # default
- echo "docker build with no params..."
- docker build -f ${workdir}/Dockerfile ${workdir}/ -t tiat/terraform-scrape:latest
-else # with image:tag
- if [ ! -n "${2}" ]; then
- echo "docker build with [specified image]...[${1}][${2}][${workdir}]"
- docker build -f ${workdir}/Dockerfile ${workdir}/ -t ${1}
-
- echo "docker run [${1}] to generate tiat-resources.json."
- docker run -it ${1} resource >../../config/tips/tiat-resources.json
-
- echo "docker run [${1}] to generate tiat-resources.json."
- docker run -it ${1} example >../../config/tips/tiat-resources.json
- else # with args
- echo "docker build with [build-arg]...[${1}][${2}][${workdir}]"
- docker build --build-arg args=${2} -f ${workdir}/Dockerfile ${workdir}/ -t ${1}
- fi
-fi
diff --git a/tool/scrape/index.ts b/tool/scrape/index.ts
deleted file mode 100644
index 2b1caba..0000000
--- a/tool/scrape/index.ts
+++ /dev/null
@@ -1,357 +0,0 @@
-/* eslint-disable no-throw-literal */
-import * as fs from "fs";
-import * as marked from "marked";
-import * as _ from "lodash";
-import { load } from "cheerio";
-import { JSDOM } from "jsdom";
-
-// ================================== INTERFACES ==================================
-
-interface ArgumentNodes {
- argumentNodes: cheerio.Cheerio[]
-}
-
-interface AttributeNodes {
- attributeNodes: cheerio.Cheerio[]
-}
-
-interface SnippetNodes {
- snippetNodes: cheerio.Cheerio[]
-}
-
-interface UrlPathNodes {
- urlPathNodes: cheerio.Cheerio[]
-}
-
-interface Resource {
- name: string;
- args: variable[];
- attrs: variable[];
- url: string;
-}
-
-interface Snippet {
- name: string;
- example: string;
-}
-
-interface variable {
- name: string;
- description: string;
-}
-
-const resourcesPath = "/Users/luoyin/Code/terraform-provider-tencentcloud/website/docs/r/";
-const dataSourcePath = "/Users/luoyin/Code/terraform-provider-tencentcloud/website/docs/d/";
-const indexPath = "/Users/luoyin/Code/terraform-provider-tencentcloud/website/tencentcloud.erb";
-// ================================== FUNCTIONS ==================================
-
-function getParsed(filename: string): Promise {
- return new Promise((resolve, reject) => {
- let file = fs.readFileSync(resourcesPath + filename) + "";
- marked(file, (err, result) => {
- if (err) {
- return reject(err);
- }
- let $ = load(result);
- resolve($);
- });
- });
-}
-
-function getAllParsed(files: string[]): Promise[] {
- return _.map(files, file => {
- return getParsed(file);
- });
-}
-
-function getNumWithArgumentReference($s: cheerio.Root[]): number {
- let result = _.map($s, $ => {
- return $("h2").filter((z, el) => {
- return $(el).text() === "Argument Reference";
- }).length;
- });
- return result.length;
-}
-
-function getNumWithAttributesReference($s: cheerio.Root[]): number {
- let result = _.map($s, $ => {
- return $("h2").filter((z, el) => {
- return $(el).text() === "Attributes Reference";
- }).length;
- });
- return result.length;
-}
-
-/**
- * Returns a list of nodes that follow the "Arguments Reference" h2
- *
- * @param {*} $ - The full page as a cheerio object
- */
-function extractArgumentsContent($: cheerio.Root): ArgumentNodes {
- let argsH2 = $("h2").filter((z, el) => {
- return $(el).text() === "Argument Reference";
- });
- if (argsH2.length !== 1) {
- throw "Didn't find correct number of h2 > Arguments Reference";
- }
- let nodes = [];
- let currentNode: any = argsH2[0];
- while (true) {
- if (!(currentNode.type === "text" && currentNode["data"] === "\n")) {
- nodes.push(currentNode);
- }
- let nextSibling = _.get(currentNode, "nextSibling");
- if (!nextSibling || _.get(nextSibling, "name") === "h2") {
- break;
- }
- currentNode = _.get(currentNode, "nextSibling");
- }
- return { argumentNodes: nodes };
-}
-
-function extractAttributesContent($: cheerio.Root): AttributeNodes {
- let argsH2 = $("h2").filter((z, el) => {
- return $(el).text() === "Attribute Reference" || $(el).text() === "Attributes Reference";
- });
- if (argsH2.length !== 1) {
- console.error(`Didn't find any attributes on ${extractResourceName($)}`);
- return { attributeNodes: [] };
- // throw `Didn't find correct number of h2 > Attributes Reference on ${extractResourceName($)}`;
- }
- let nodes = [];
- let currentNode: any = argsH2[0];
- while (true) {
- if (!(currentNode.type === "text" && currentNode["data"] === "\n")) {
- nodes.push(currentNode);
- }
- let nextSibling = _.get(currentNode, "nextSibling");
- if (!nextSibling || _.get(nextSibling, "name") === "h2") {
- break;
- }
- currentNode = _.get(currentNode, "nextSibling");
- }
- return { attributeNodes: nodes };
-}
-
-function extractExampleContent($: cheerio.Root): string {
- let expH2 = $("h2").filter((z, el) => {
- return $(el).text() === "Example Usage";
- });
- if (expH2.length !== 1) {
- console.error(`Didn't find any example on ${extractResourceName($)}`);
- return "";
- // throw "Didn't find correct number of h2 > Example Usage";
- }
- let content = "This example will be ready later.";
- let currentNode: any = expH2[0];
- while (true) {
- const nextSibling = _.get(currentNode, 'nextSibling');
- if (!nextSibling || _.get(nextSibling, 'name') === 'h2') {
- break;
- }
-
- currentNode = _.get(currentNode, 'nextSibling');
-
- // exsit multiple example
- if (currentNode.type === 'tag' && currentNode.name === 'h3') {
- currentNode = _.get(currentNode, 'nextSibling');
- continue;
- }
-
- // only extract the first one
- if (currentNode.type === 'tag' && currentNode.name === 'pre') {
- content = $(currentNode).text();
- break;
- }
- }
-
- return content;
-}
-
-function extractExamples(expNodes: SnippetNodes, $: cheerio.Root): string {
- let nodes = expNodes.snippetNodes;
-
- // const snippetText = nodes.map((nn) => $(nn).text()).join('');
- const textArray = _.map(nodes, node => {
- return $(node).text();
- });
-
- console.debug("[DEBUG]#### len:[%d], textArray:[%v]", textArray.length, textArray);
-
- const snippetTexts = textArray.join("");
- console.debug("[DEBUG]#### snippetTexts:[%s]", snippetTexts);
-
- return snippetTexts;
-}
-
-function extractArguments(argNodes: ArgumentNodes, $: cheerio.Root): variable[] {
- let nodes = argNodes.argumentNodes;
-
- // Find the first ul
- let firstUl = _.find(nodes, (o: any) => o.name === "ul");
-
- if (!firstUl) {
- // throw "Didn't find a UL when searching through arguments";
- // console.error(`Didn't find a UL when searching through arguments on ${extractResourceName($)}`);
- return [];
- }
- return _.map($(firstUl).find("li"), li => {
- let text = $(li).text();
- let regex = /([a-zA-Z0-9_]+) (.+)/;
- let result = text.match(regex);
- let name, description;
- if (!result) {
- name = text;
- //console.error(`Didn't find a description for ${text} on ${extractResourceName($)}`);
- }
- else {
- name = result[1];
- description = result[2];
- }
- return { name, description };
- });
-}
-
-function extractAttributes(argNodes: AttributeNodes, $: cheerio.Root): variable[] {
- if (argNodes.attributeNodes.length === 0) {
- return [];
- }
-
- let nodes = argNodes.attributeNodes;
- // Find the first ul
- let firstUl = _.find(nodes, (o: any) => o.name === "ul");
- if (!firstUl) {
- // console.error(`Didn't find a UL when searching through attributes on ${extractResourceName($)}`);
- return [];
- }
- return _.map($(firstUl).find("li"), li => {
- let text = $(li).text();
- let regex = /([a-zA-Z0-9_]+) (.+)/;
- let result = text.match(regex);
- let name, description;
- if (!result) {
- name = text;
- // console.error(`Didn't find a description for ${text} on ${extractResourceName($)}`);
- }
- else {
- name = result[1];
- description = result[2];
- }
- return { name, description };
- });
-}
-
-function extractResourceName($: cheerio.Root): string {
- let name = $("h1").text();
- if (!name) {
- throw "Couldn't extract name";
- }
- return name;
-}
-
-function findAnchorElementByText(doc: Document, text: string): HTMLAnchorElement | null {
- const aTags = doc.querySelectorAll("a");
-
- for (const aTag of aTags) {
- if (aTag.textContent?.trim() === text) {
- return aTag;
- }
- }
-
- return null;
-}
-
-function extractHrefToMap(aTags: HTMLAnchorElement[], hrefsMap: Map): void {
- for (const aTag of aTags) {
- const key = aTag.textContent;
- const url = aTag.getAttribute("href");
- if (key && url) {
- hrefsMap.set(key, url);
- }
- }
-}
-
-function findAllAnchorElementsByText(doc: Document, text: string): HTMLAnchorElement[] {
- const aTags = doc.querySelectorAll("a");
- return Array.from(aTags).filter((aTag) => aTag.textContent?.trim() === text);
-}
-
-function extractResourceUrl(html: string): Map {
- const dom = new JSDOM(html);
- const doc = dom.window.document;
- const hrefsMap = new Map();
-
- const dataSourcesATags = findAllAnchorElementsByText(doc, "Data Sources");
- const resourcesATags = findAllAnchorElementsByText(doc, "Resources");
-
- // process data source tags
- for (const dataSourceATag of dataSourcesATags) {
- const dataSourceUL = dataSourceATag.nextElementSibling;
- const dsLiATags = dataSourceUL?.querySelectorAll("a") || [];
- extractHrefToMap(Array.from(dsLiATags), hrefsMap);
- }
-
- // process resource tags
- for (const resourceATag of resourcesATags) {
- const resourceUL = resourceATag.nextElementSibling;
- const resLiATags = resourceUL?.querySelectorAll("a") || [];
- extractHrefToMap(Array.from(resLiATags), hrefsMap);
- }
-
- return hrefsMap;
-}
-
-// ================================== generate process ==================================
-
-const files = fs.readdirSync(resourcesPath);
-const indexHtml = fs.readFileSync(indexPath, "utf-8");
-Promise.all(getAllParsed(files)).then($s => {
- const args = process.argv.slice(2);
- let type = "";
- if (args.length > 0) {
- type = args[0];
- }
-
- let transformed: any;
- if (type === "example") {
- // example collection
- const examples: Snippet[] = _.map($s, $ => {
- const resName = extractResourceName($);
- return {
- name: resName,
- example: extractExampleContent($),
- };
- });
- transformed = _.transform(examples, (result, value) => {
- result[value.name] = {
- example: value.example
- };
- }, {});
-
- } else {
- // resource collection
- const resIndexMap = extractResourceUrl(indexHtml);
- const resources: Resource[] = _.map($s, $ => {
- const resName = extractResourceName($);
- return {
- name: resName,
- args: extractArguments(extractArgumentsContent($), $),
- attrs: extractAttributes(extractAttributesContent($), $),
- url: resIndexMap.get(resName)
- };
- });
- transformed = _.transform(resources, (result, value, key) => {
- result[value.name] = {
- args: value.args,
- attrs: value.attrs,
- url: value.url
- };
- }, {});
- }
-
- console.log(JSON.stringify(transformed));
-});
-
-function fun(v: any, i: any, array: any): (value: string, index: number, array: string[]) => void {
- throw new Error("Function not implemented.");
-}
diff --git a/tool/scrape/package.json b/tool/scrape/package.json
deleted file mode 100644
index fc41902..0000000
--- a/tool/scrape/package.json
+++ /dev/null
@@ -1,22 +0,0 @@
-{
- "name": "terraform-scrape",
- "version": "1.0.0",
- "description": "",
- "main": "index.js",
- "scripts": {
- "test": "echo \"Error: no test specified\" && exit 1",
- "watch_compile": "tsc -watch -p ./"
- },
- "author": "",
- "license": "ISC",
- "dependencies": {
- "@types/cheerio": "^0.22.33",
- "@types/lodash": "^4.14.85",
- "@types/node": "^8.0.53",
- "cheerio": "^1.0.0-rc.12",
- "fs": "^0.0.1-security",
- "lodash": "^4.17.4",
- "jsdom": "^22.1.0",
- "marked": "^0.3.6"
- }
-}
\ No newline at end of file
diff --git a/tool/scrape/tsconfig.json b/tool/scrape/tsconfig.json
deleted file mode 100644
index a72657e..0000000
--- a/tool/scrape/tsconfig.json
+++ /dev/null
@@ -1,14 +0,0 @@
-{
- "compilerOptions": {
- "target": "es2017",
- "module": "commonjs",
- "sourceMap": true
- },
- "files": [
- "index.ts"
- ],
- "exclude": [
- "node_modules",
- ".vscode-test"
- ]
-}
\ No newline at end of file
diff --git a/tsconfig.json b/tsconfig.json
deleted file mode 100644
index 4c43e2e..0000000
--- a/tsconfig.json
+++ /dev/null
@@ -1,40 +0,0 @@
-{
- "compilerOptions": {
- "experimentalDecorators": true,
- // "module": "commonjs",
- "module": "NodeNext",
- "moduleResolution": "NodeNext",
- "target": "ES2020",
- "outDir": "./out",
- "resolveJsonModule": true,
- "allowSyntheticDefaultImports" :true,
- "lib": [
- "ES2020"
- ],
- "sourceMap": true,
- "types": [
- "reflect-metadata",
- "node"
- ],
- "baseUrl": "./",
- "paths": {
- "@/*": [
- "src/*"
- ]
- },
- // "rootDir": "src",
- // "strict": true /* enable all strict type-checking options */
- /* Additional Checks */
- "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
- "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
- // "noUnusedParameters": true, /* Report errors on unused parameters. */
- },
- "exclude": [
- "tool"
- ],
- "ts-node": {
- "require": [
- "tsconfig-paths/register"
- ]
- }
-}
\ No newline at end of file
diff --git a/vsc-extension-quickstart.md b/vsc-extension-quickstart.md
deleted file mode 100644
index 04a57fc..0000000
--- a/vsc-extension-quickstart.md
+++ /dev/null
@@ -1,42 +0,0 @@
-# Welcome to your VS Code Extension
-
-## What's in the folder
-
-* This folder contains all of the files necessary for your extension.
-* `package.json` - this is the manifest file in which you declare your extension and command.
- * The sample plugin registers a command and defines its title and command name. With this information VS Code can show the command in the command palette. It doesn’t yet need to load the plugin.
-* `src/extension.ts` - this is the main file where you will provide the implementation of your command.
- * The file exports one function, `activate`, which is called the very first time your extension is activated (in this case by executing the command). Inside the `activate` function we call `registerCommand`.
- * We pass the function containing the implementation of the command as the second parameter to `registerCommand`.
-
-## Get up and running straight away
-
-* Press `F5` to open a new window with your extension loaded.
-* Run your command from the command palette by pressing (`Ctrl+Shift+P` or `Cmd+Shift+P` on Mac) and typing `Hello World`.
-* Set breakpoints in your code inside `src/extension.ts` to debug your extension.
-* Find output from your extension in the debug console.
-
-## Make changes
-
-* You can relaunch the extension from the debug toolbar after changing code in `src/extension.ts`.
-* You can also reload (`Ctrl+R` or `Cmd+R` on Mac) the VS Code window with your extension to load your changes.
-
-## Explore the API
-
-* You can open the full set of our API when you open the file `node_modules/@types/vscode/index.d.ts`.
-
-## Run tests
-
-* Open the debug viewlet (`Ctrl+Shift+D` or `Cmd+Shift+D` on Mac) and from the launch configuration dropdown pick `Extension Tests`.
-* Press `F5` to run the tests in a new window with your extension loaded.
-* See the output of the test result in the debug console.
-* Make changes to `src/test/suite/extension.test.ts` or create new test files inside the `test/suite` folder.
- * The provided test runner will only consider files matching the name pattern `**.test.ts`.
- * You can create folders inside the `test` folder to structure your tests any way you want.
-
-## Go further
-
-* [Follow UX guidelines](https://code.visualstudio.com/api/ux-guidelines/overview) to create extensions that seamlessly integrate with VS Code's native interface and patterns.
- * Reduce the extension size and improve the startup time by [bundling your extension](https://code.visualstudio.com/api/working-with-extensions/bundling-extension).
- * [Publish your extension](https://code.visualstudio.com/api/working-with-extensions/publishing-extension) on the VS Code extension marketplace.
- * Automate builds by setting up [Continuous Integration](https://code.visualstudio.com/api/working-with-extensions/continuous-integration).
pFad - Phonifier reborn
Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies:
Alternative Proxy
pFad Proxy
pFad v3 Proxy
pFad v4 Proxy