Skip to content

Commit

Permalink
enable git
Browse files Browse the repository at this point in the history
  • Loading branch information
lyu571 committed Dec 6, 2023
1 parent 265c3ed commit 08ba4f2
Show file tree
Hide file tree
Showing 4 changed files with 86 additions and 40 deletions.
2 changes: 1 addition & 1 deletion config/snippets/tiat-examples.json
Original file line number Diff line number Diff line change
Expand Up @@ -1242,7 +1242,7 @@
"example": "resource \"tencentcloud_image\" \"image_snap\" {\n image_name = \"image-snapshot-keep\"\n snapshot_ids = [\"snap-nbp3xy1d\", \"snap-nvzu3dmh\"]\n force_poweroff = true\n image_description = \"create image with snapshot\"\n}\n"
},
"tencentcloud_instance": {
"example": "data \"tencentcloud_images\" \"my_favorite_image\" {\n image_type = [\"PUBLIC_IMAGE\"]\n image_name_regex = \"Final\"\n}\n\ndata \"tencentcloud_instance_types\" \"my_favorite_instance_types\" {\n filter {\n name = \"instance-family\"\n values = [\"S1\", \"S2\", \"S3\", \"S4\", \"S5\"]\n }\n\n cpu_core_count = 2\n exclude_sold_out = true\n}\n\ndata \"tencentcloud_availability_zones\" \"my_favorite_zones\" {\n}\n\n// Create VPC resource\nresource \"tencentcloud_vpc\" \"app\" {\n cidr_block = \"10.0.0.0/16\"\n name = \"awesome_app_vpc\"\n}\n\nresource \"tencentcloud_subnet\" \"app\" {\n vpc_id = tencentcloud_vpc.app.id\n availability_zone = data.tencentcloud_availability_zones.my_favorite_zones.zones.0.name\n name = \"awesome_app_subnet\"\n cidr_block = \"10.0.1.0/24\"\n}\n\n// Create a POSTPAID_BY_HOUR CVM instance\nresource \"tencentcloud_instance\" \"cvm_postpaid\" {\n instance_name = \"cvm_postpaid\"\n availability_zone = data.tencentcloud_availability_zones.my_favorite_zones.zones.0.name\n image_id = data.tencentcloud_images.my_favorite_image.images.0.image_id\n instance_type = data.tencentcloud_instance_types.my_favorite_instance_types.instance_types.0.instance_type\n system_disk_type = \"CLOUD_PREMIUM\"\n system_disk_size = 50\n hostname = \"user\"\n project_id = 0\n vpc_id = tencentcloud_vpc.app.id\n subnet_id = tencentcloud_subnet.app.id\n\n data_disks {\n data_disk_type = \"CLOUD_PREMIUM\"\n data_disk_size = 50\n encrypt = false\n }\n\n tags = {\n tagKey = \"tagValue\"\n }\n}\n\n// Create a PREPAID CVM instance\nresource \"tencentcloud_instance\" \"cvm_prepaid\" {\n timeouts {\n create = \"30m\"\n }\n instance_name = \"cvm_prepaid\"\n availability_zone = data.tencentcloud_availability_zones.my_favorite_zones.zones.0.name\n image_id = data.tencentcloud_images.my_favorite_image.images.0.image_id\n instance_type = data.tencentcloud_instance_types.my_favorite_instance_types.instance_types.0.instance_type\n system_disk_type = \"CLOUD_PREMIUM\"\n system_disk_size = 50\n hostname = \"user\"\n project_id = 0\n vpc_id = tencentcloud_vpc.app.id\n subnet_id = tencentcloud_subnet.app.id\n instance_charge_type = \"PREPAID\"\n instance_charge_type_prepaid_period = 1\n instance_charge_type_prepaid_renew_flag = \"NOTIFY_AND_MANUAL_RENEW\"\n data_disks {\n data_disk_type = \"CLOUD_PREMIUM\"\n data_disk_size = 50\n encrypt = false\n }\n force_delete = true\n tags = {\n tagKey = \"tagValue\"\n }\n}\n"
"example": "data \"tencentcloud_images\" \"my_favorite_image\" {\n image_type = [\"PUBLIC_IMAGE\"]\n image_name_regex = \"Final\"\n}\n\ndata \"tencentcloud_instance_types\" \"my_favorite_instance_types\" {\n filter {\n name = \"instance-family\"\n values = [\"S5\"]\n }\n\n cpu_core_count = 2\n exclude_sold_out = true\n}\n\ndata \"tencentcloud_availability_zones_by_product\" \"my_favorite_zones\" {\n product = \"cvm\"\n}\n\n// Create VPC resource\nresource \"tencentcloud_vpc\" \"app\" {\n cidr_block = \"10.0.0.0/16\"\n name = \"awesome_app_vpc\"\n}\n\nresource \"tencentcloud_subnet\" \"app\" {\n vpc_id = tencentcloud_vpc.app.id\n availability_zone = data.tencentcloud_availability_zones_by_product.my_favorite_zones.zones.0.name\n name = \"awesome_app_subnet\"\n cidr_block = \"10.0.1.0/24\"\n}\n\n// Create a POSTPAID_BY_HOUR CVM instance\nresource \"tencentcloud_instance\" \"cvm_postpaid\" {\n instance_name = \"cvm_postpaid\"\n availability_zone = data.tencentcloud_availability_zones_by_product.my_favorite_zones.zones.0.name\n image_id = data.tencentcloud_images.my_favorite_image.images.0.image_id\n instance_type = data.tencentcloud_instance_types.my_favorite_instance_types.instance_types.0.instance_type\n system_disk_type = \"CLOUD_PREMIUM\"\n system_disk_size = 50\n hostname = \"user\"\n project_id = 0\n vpc_id = tencentcloud_vpc.app.id\n subnet_id = tencentcloud_subnet.app.id\n\n data_disks {\n data_disk_type = \"CLOUD_PREMIUM\"\n data_disk_size = 50\n encrypt = false\n }\n\n tags = {\n tagKey = \"tagValue\"\n }\n}\n"
},
"tencentcloud_instance_set": {
"example": "data \"tencentcloud_images\" \"my_favorite_image\" {\n image_type = [\"PUBLIC_IMAGE\"]\n os_name = \"Tencent Linux release 3.2 (Final)\"\n}\n\ndata \"tencentcloud_instance_types\" \"my_favorite_instance_types\" {\n filter {\n name = \"instance-family\"\n values = [\"S3\"]\n }\n\n cpu_core_count = 1\n memory_size = 1\n}\n\ndata \"tencentcloud_availability_zones\" \"my_favorite_zones\" {\n}\n\n// Create VPC resource\nresource \"tencentcloud_vpc\" \"app\" {\n cidr_block = \"10.0.0.0/16\"\n name = \"awesome_app_vpc\"\n}\n\nresource \"tencentcloud_subnet\" \"app\" {\n vpc_id = tencentcloud_vpc.app.id\n availability_zone = data.tencentcloud_availability_zones.my_favorite_zones.zones.0.name\n name = \"awesome_app_subnet\"\n cidr_block = \"10.0.1.0/24\"\n}\n\n// Create 10 CVM instances to host awesome_app\nresource \"tencentcloud_instance_set\" \"my_awesome_app\" {\n timeouts {\n create = \"5m\"\n read = \"20s\"\n delete = \"1h\"\n }\n\n instance_count = 10\n instance_name = \"awesome_app\"\n availability_zone = data.tencentcloud_availability_zones.my_favorite_zones.zones.0.name\n image_id = data.tencentcloud_images.my_favorite_image.images.0.image_id\n instance_type = data.tencentcloud_instance_types.my_favorite_instance_types.instance_types.0.instance_type\n system_disk_type = \"CLOUD_PREMIUM\"\n system_disk_size = 50\n hostname = \"user\"\n project_id = 0\n vpc_id = tencentcloud_vpc.app.id\n subnet_id = tencentcloud_subnet.app.id\n}\n"
Expand Down
9 changes: 9 additions & 0 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,15 @@ export async function activate(context: vscode.ExtensionContext) {
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 () => {
terraformShellManager.getShell().runTerraformCmd(TerraformerCommand.Import);
Expand Down
98 changes: 59 additions & 39 deletions src/utils/gitUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ 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;
Expand All @@ -15,44 +16,36 @@ export class GitUtils {

public async submitToGit(): Promise<any> {
console.debug("[DEBUG]#### GitUtils submitToGit begin.");
const gitRootPath = vscode.workspace.rootPath;
const activeDocumentPath = workspaceUtils.getActiveEditorPath();
const gitRootPath = path.dirname(activeDocumentPath);
if (!gitRootPath) {
vscode.window.showErrorMessage('Please open a workspace folder first!');
return;
}

while (true) {
if (fs.existsSync(path.join(gitRootPath, '.git'))) {
vscode.window.showInformationMessage('Trying to fetch from Git, please wait...');
await this.fetchFromGit();
break;
} else {
vscode.window.showInformationMessage(`You are not in a git repository yet, trying to clone from your Git repo...`);
await this.cloneFromGit();
// retry
}
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);
}

exec('git add . && git commit -m "committed by VS Code" && git push', { cwd: gitRootPath }, (error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(`Failed to submit code: ${error.message}`);
return;
}
if (stderr) {
vscode.window.showErrorMessage(`Failed to submit code: ${stderr}`);
return;
}
vscode.window.showInformationMessage('Code has been successfully submitted to Git repo!');
});
return;
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(): Promise<any> {
private async cloneFromGit(rootPath: string): Promise<any> {
console.debug("[DEBUG]#### GitUtils cloneFromGit begin.");
await vscode.window.showInputBox({ prompt: 'Please enter the Git repository URL:' }).then((url) => {
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 = vscode.workspace.rootPath ? `${vscode.workspace.rootPath}/${folderName}` : folderName || '';
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 }, () => { });
Expand All @@ -72,23 +65,50 @@ export class GitUtils {
});
}
});
return;
}

private async fetchFromGit(): Promise<any> {
private gitPush(rootPath: string): Promise<string> {
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<void> {
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<any> {
console.debug("[DEBUG]#### GitUtils fetchFromGit begin.");
const gitRootPath = vscode.workspace.rootPath;
exec('git pull', { cwd: gitRootPath }, (error, stdout, stderr) => {
if (error) {
vscode.window.showErrorMessage(`Failed to fetch code: ${error.message}`);
return;
}
if (stderr) {
vscode.window.showErrorMessage(`Failed to fetch code: ${stderr}`);
return;
}
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}`);
}
}

}
Expand Down
17 changes: 17 additions & 0 deletions src/utils/workspaceUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,20 @@ export async function selectWorkspaceFolder(): Promise<string | undefined> {
}
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 = activeDocument.uri.fsPath;
return activeDocumentPath;
}

0 comments on commit 08ba4f2

Please sign in to comment.