Skip to content

Commit 435fb27

Browse files
committed
1.introduce the context to get ext version and provider version.
2.adjust the getShell and getIntegratedShell to async to get the reqcli with provider version. 3.refactor the queryUserInfo method. 4.deactivate clear user when close vscode. 5.add warn msg when use without login. 6.reset terminal env when aksk is null.
1 parent 319dbeb commit 435fb27

File tree

12 files changed

+176
-164
lines changed

12 files changed

+176
-164
lines changed

package.nls.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
"TcTerraform.pickup.aksk.placeholder": "Tencent Cloud {0}",
2121
"TcTerraform.pickup.aksk.verify.empty": "{0} can not be empty",
2222
"TcTerraform.welcome": "Welcome to use Tencent Cloud Terraform extension, please wait for the page loading...",
23-
"TcTerraform.msg.aksk.notfound": "Cannot find TENCENTCLOUD_SECRET_ID and TENCENTCLOUD_SECRET_KEY, please sign in first!",
23+
"TcTerraform.msg.aksk.notfound": "Cannot find user info, please sign in first!",
2424
"TcTerraform.login": "Login Tencent Cloud...",
2525
"TcTerraform.login.msg.success": "Logged into Tencent Cloud successfully.",
2626
"TcTerraform.login.msg.need.login": "Please log in Tencent Cloud first.",

src/autocomplete/TerraformTipsProvider.ts

Lines changed: 3 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,10 @@ import { CompletionItemProvider, TextDocument, Position, CancellationToken, Comp
22
// import resources from '../../config/tips/tiat-resources.json';
33
import * as _ from "lodash";
44
import * as vscode from 'vscode';
5-
import { executeCommandByExec } from "@/utils/cpUtils";
65
import * as fs from "fs";
76
import * as path from "path";
8-
import * as workspaceUtils from "@/utils/workspaceUtils";
9-
import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";
7+
import * as context from "@/commons/context";
108

11-
const LATEST_VERSION = "latest";
129
const versionPattern = /^v\d+(\.\d+){2}\.json$/;
1310
let topLevelTypes = ["output", "provider", "resource", "variable", "data"];
1411
let topLevelRegexes = topLevelTypes.map(o => {
@@ -422,26 +419,7 @@ function compareVersions(a, b) {
422419

423420
// load resource config from json files based on the appropriate version
424421
async function loadResource(extPath: string): Promise<Tips> {
425-
let tfVersion: string;
426-
const cwd = workspaceUtils.getActiveEditorPath();
427-
if (!cwd) {
428-
TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
429-
console.error(`can not get path from active editor`);
430-
}
431-
432-
await executeCommandByExec("terraform version", cwd).then(output => {
433-
let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);
434-
435-
if (match) {
436-
tfVersion = match[1];
437-
} else {
438-
// gives the latest JSON if not tf provider version found
439-
tfVersion = LATEST_VERSION;
440-
}
441-
console.log(`tf provider version:[${tfVersion}], cwd:[${cwd}]`);
442-
}).catch(error => {
443-
console.error(`execute terraform version failed: ${error}`);
444-
});
422+
const tfVersion = await context.getTfVersion();
445423

446424
let result: Tips | null = null;
447425
const tipsDir = path.join(extPath, 'config', 'tips');
@@ -461,4 +439,4 @@ async function loadResource(extPath: string): Promise<Tips> {
461439
// vscode.window.showInformationMessage(`Loaded json. tf version:[${tfVersion}], json version:[${result.version}]`);
462440

463441
return result;
464-
}
442+
}

src/client/runner/terraformRunner.ts

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import { terraformShellManager } from "../terminal/terraformShellManager";
1313
import { executeCommand } from "../../utils/cpUtils";
1414
import * as settingUtils from "../../utils/settingUtils";
1515
import { openUrlHintOrNotShowAgain } from "../../utils/uiUtils";
16+
import { localize } from "vscode-nls-i18n";
1617

1718

1819
export class TerraformRunner extends BaseRunner {
@@ -32,20 +33,24 @@ export class TerraformRunner extends BaseRunner {
3233
public async init(): Promise<any> {
3334
console.debug("[DEBUG]#### TerraformRunner init begin.");
3435

35-
// this.setAKSK();
36+
if (!checkAKSK()) {
37+
return "plan abort";
38+
}
3639

37-
terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Version);
38-
terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Init);
40+
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Version);
41+
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Init);
3942

4043
return "init success";
4144
}
4245

4346
public async executePlan(cwd: string, args: any): Promise<string> {
4447
console.debug("[DEBUG]#### TerraformRunner executePlan begin.");
4548

46-
// this.setAKSK();
49+
if (!checkAKSK()) {
50+
return "plan abort";
51+
}
4752

48-
terraformShellManager.getShell().runTerraformCmd(TerraformCommand.Plan);
53+
(await terraformShellManager.getShell()).runTerraformCmd(TerraformCommand.Plan);
4954

5055
return "plan success";
5156
}
@@ -112,7 +117,6 @@ export class TerraformRunner extends BaseRunner {
112117
setCheckTerraformCmd(false);
113118
});
114119
}
115-
return;
116120
}
117121

118122
private async resetFileContent(tfFile: string, defaultContents: string) {
@@ -126,15 +130,9 @@ export class TerraformRunner extends BaseRunner {
126130
public async resetTFState(resAddress: string) {
127131
console.debug("[DEBUG]#### TerraformRunner resetTFState begin.");
128132

129-
await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())
133+
await (await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()))
130134
.runTerraformCmd(TerraformCommand.State, ['rm', '-lock=false', resAddress]);
131135
}
132-
133-
private setAKSK(runner?: any) {
134-
const [ak, sk, region] = settingUtils.getAKSKandRegion();
135-
terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_ID=" + ak);
136-
terraformShellManager.getIntegratedShell(runner).runNormalCmd("export TENCENTCLOUD_SECRET_KEY=" + sk);
137-
}
138136
}
139137

140138
export function getCheckTerraformCmd(): boolean {
@@ -144,3 +142,15 @@ export function getCheckTerraformCmd(): boolean {
144142
export function setCheckTerraformCmd(checked: boolean): void {
145143
vscode.workspace.getConfiguration().update("tcTerraform.checkTerraformCmd", checked);
146144
}
145+
146+
export function checkAKSK(): boolean {
147+
const [secretId, secretKey, _] = settingUtils.getAKSKandRegion();
148+
149+
if (secretId === undefined || secretKey === undefined || secretId === null || secretKey === null || secretId === '' || secretKey === '') {
150+
let msg = localize("TcTerraform.msg.aksk.notfound");
151+
console.error(msg);
152+
vscode.window.showInformationMessage(msg);
153+
return false;
154+
}
155+
return true;
156+
}

src/client/terminal/integratedShell.ts

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,10 @@ export class IntegratedShell extends BaseShell {
3737
this.env = ee;
3838
}
3939

40+
public getEnv() {
41+
return this.env;
42+
}
43+
4044
// Creates a png of terraform resource graph to visualize the resources under management.
4145
public async visualize(): Promise<void> {
4246
console.debug("[DEBUG]#### IntegratedShell visualize begin.");

src/client/terminal/terraformShellManager.ts

Lines changed: 26 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -16,19 +16,17 @@ import * as settingUtils from "../../utils/settingUtils";
1616
import { Constants } from "../../commons/constants";
1717

1818
export interface ITerraformShellManager {
19-
getShell(): BaseShell;
19+
getShell(): Promise<BaseShell>;
2020
// getCloudShell(): TCCloudShell;
21-
getIntegratedShell(runner?: any): IntegratedShell;
21+
getIntegratedShell(runner?: any): Promise<IntegratedShell>;
2222
dispose(): void;
2323
}
2424

25-
26-
2725
class TerraformShellManager implements ITerraformShellManager {
2826
private static cloudShell = new TencentCloudShell();
2927
private static integratedShell: IntegratedShell;
3028

31-
public getShell(): BaseShell {
29+
public async getShell(): Promise<BaseShell> {
3230
const isCloudShell: boolean = isTerminalSetToCloudShell();
3331

3432
TelemetryWrapper.addContextProperty("isCloudShell", isCloudShell.toString());
@@ -42,26 +40,36 @@ class TerraformShellManager implements ITerraformShellManager {
4240
return TerraformShellManager.cloudShell;
4341
}
4442

45-
public getIntegratedShell(runner?: any): IntegratedShell {
43+
public async getIntegratedShell(runner?: any): Promise<IntegratedShell> {
4644
if (!TerraformShellManager.integratedShell) {
4745
// set TencentCloud AKSK, Region and Client info
48-
const [ak, sk, region] = settingUtils.getAKSKandRegion();
49-
const tfEnv = {
50-
[Constants.REQUEST_CLIENT]: context.genRequestClient(),
51-
[Constants.TENCENTCLOUD_SECRET_ID]: ak,
52-
[Constants.TENCENTCLOUD_SECRET_KEY]: sk,
53-
[Constants.TENCENTCLOUD_REGION]: region,
54-
};
55-
// default runner is Terraformer
56-
TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
57-
// specify runner
58-
if (runner) {
59-
TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
46+
await this.initIntegratedShell(runner);
47+
} else {
48+
const curEnv = TerraformShellManager.integratedShell.getEnv();
49+
// need to be reset if the current AKSK is undefined
50+
if (!curEnv[Constants.TENCENTCLOUD_SECRET_ID] || !curEnv[Constants.TENCENTCLOUD_SECRET_KEY]) {
51+
await this.initIntegratedShell(runner);
6052
}
6153
}
6254
return TerraformShellManager.integratedShell;
6355
}
6456

57+
private async initIntegratedShell(runner: any) {
58+
const [ak, sk, region] = settingUtils.getAKSKandRegion();
59+
const reqCli = await context.genRequestClient();
60+
const tfEnv = {
61+
[Constants.REQUEST_CLIENT]: reqCli, // set ReqCli for TIC Terminal
62+
[Constants.TENCENTCLOUD_SECRET_ID]: ak,
63+
[Constants.TENCENTCLOUD_SECRET_KEY]: sk,
64+
[Constants.TENCENTCLOUD_REGION]: region,
65+
};
66+
// default runner is Terraformer
67+
TerraformShellManager.integratedShell = new IntegratedShell(TerraformerRunner.getInstance(), tfEnv);
68+
if (runner) {
69+
TerraformShellManager.integratedShell = new IntegratedShell(runner, tfEnv);
70+
}
71+
}
72+
6573
public dispose(): void {
6674
TerraformShellManager.cloudShell.dispose();
6775
TerraformShellManager.integratedShell.dispose();

src/commons/context.ts

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1+
/* eslint-disable @typescript-eslint/naming-convention */
12
import { container } from './container';
23
import * as vscode from 'vscode';
4+
import * as workspaceUtils from "@/utils/workspaceUtils";
5+
import * as cpUtils from "@/utils/cpUtils";
6+
import * as TelemetryWrapper from "vscode-extension-telemetry-wrapper";
37

48
export const Context = Symbol('ExtensionContext');
5-
export const REQUEST_CLIENT_PREFIX = "Terraform-Vscode-";//Terraform-1.81.61@vscode";
9+
export const REQUEST_CLIENT_PREFIX = "Terraform-";//Terraform-1.81.61@vscode";
10+
const LATEST_VERSION = "latest";
611

712
export function bindExtensionContext(ctx: vscode.ExtensionContext) {
813
container.bind(Context).toConstantValue(ctx);
@@ -14,8 +19,33 @@ export function getExtensionVersion(): string {
1419
return currentVersion;
1520
}
1621

17-
export function genRequestClient(): string {
18-
const currentVersion = getExtensionVersion();
19-
const reqCli = `${REQUEST_CLIENT_PREFIX}v${currentVersion}`;
22+
export async function genRequestClient(): Promise<string> {
23+
const extVersion = getExtensionVersion();
24+
const tfVersion = await getTfVersion() || LATEST_VERSION;
25+
const reqCli = `${REQUEST_CLIENT_PREFIX}${tfVersion}@vscode-v${extVersion}`;
2026
return reqCli;
27+
}
28+
29+
export async function getTfVersion(): Promise<string> {
30+
let tfVersion = '';
31+
const cwd = workspaceUtils.getActiveEditorPath();
32+
if (!cwd) {
33+
TelemetryWrapper.sendError(Error("noWorkspaceSelected"));
34+
console.error(`can not get path from active editor`);
35+
}
36+
37+
await cpUtils.executeCommandByExec("terraform version", cwd).then(output => {
38+
let match = RegExp(/tencentcloudstack\/tencentcloud (v\d+\.\d+\.\d+)/).exec(output);
39+
40+
if (match) {
41+
tfVersion = match[1];
42+
} else {
43+
// gives the latest JSON if not tf provider version found
44+
tfVersion = LATEST_VERSION;
45+
}
46+
console.log(`[DEBUG]getTfVersion tf provider version:[${tfVersion}], cwd:[${cwd}]`);
47+
}).catch(error => {
48+
console.error(`execute terraform version failed: ${error}`);
49+
});
50+
return tfVersion;
2151
}

src/commons/customCmdRegister.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,16 +42,16 @@ export function regHelpCommands() {
4242
}
4343

4444
export function regResourceRelatedCommands() {
45-
commands.registerCommand(cmds.executeTferImport, function (param: any) {
46-
terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance()).import(param, param.fileName);
45+
commands.registerCommand(cmds.executeTferImport, async function (param: any) {
46+
(await terraformShellManager.getIntegratedShell(TerraformerRunner.getInstance())).import(param, param.fileName);
4747
});
4848

49-
commands.registerCommand("tcTerraform.init", function (param: any) {
50-
terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).init();
49+
commands.registerCommand("tcTerraform.init", async function (param: any) {
50+
(await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).init();
5151
});
5252

53-
commands.registerCommand("tcTerraform.plan", function (param: any) {
54-
terraformShellManager.getIntegratedShell(TerraformRunner.getInstance()).plan(param);
53+
commands.registerCommand("tcTerraform.plan", async function (param: any) {
54+
(await terraformShellManager.getIntegratedShell(TerraformRunner.getInstance())).plan(param);
5555
});
5656

5757
commands.registerCommand(resourceRefresh, function (param: any) {

src/commons/tencent/user/auth/credentail.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ import MultiStepInput from "../../../multiStepInput";
22
import { Credential } from "tencentcloud-sdk-nodejs/tencentcloud/common/interface";
33
import { localize } from "vscode-nls-i18n";
44
import constant from "../index";
5-
import * as vscode from "vscode";
65

76
export async function getCredentailByInput() {
87
const defaultRegion = "ap-guangzhou";

0 commit comments

Comments
 (0)