1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184
| import * as vscode from "vscode";
const COS = require("cos-nodejs-sdk-v5"); import * as path from "path"; import * as fs from "fs";
export function activate(context: vscode.ExtensionContext) { console.log('Extension "md-cos-tool" is now active!');
const hoverProvider = { provideHover(document: vscode.TextDocument, position: vscode.Position) { const linkPattern = /\[(.*?)\]\((.*?)\)/;
const line = document.lineAt(position.line).text; const match = line.match(linkPattern); const range = document.getWordRangeAtPosition(position, linkPattern);
console.log( "Matched range:", range?.start.line, range?.start.character, range?.end.character );
if (range && match) { const command = "md-cos-tool.uploadToCOS"; const filePath = match[2]; const args = JSON.stringify({ filePath }); console.log("args", args);
const content = new vscode.MarkdownString( `[上传到腾讯云](command:${command}?${args})` ); content.isTrusted = true; return new vscode.Hover(content); } }, };
const uploadCommand = vscode.commands.registerCommand( "md-cos-tool.uploadToCOS", async (args) => { try { const config = vscode.workspace.getConfiguration("md-cos-tool"); const secretId = config.get<string>("secretId"); const secretKey = config.get<string>("secretKey"); const bucket = config.get<string>("bucket"); const region = config.get<string>("region");
if (!secretId || !secretKey || !bucket || !region) { const result = await vscode.window.showErrorMessage( "请先配置腾讯云COS参数", "去配置" ); if (result === "去配置") { await vscode.commands.executeCommand( "workbench.action.openSettings", "md-cos-tool" ); } return; }
const params = args; if (!params || !params.filePath) { throw new Error("无效的文件路径参数"); } const markdownLink = params.filePath;
const relativePath = markdownLink; const activeEditor = vscode.window.activeTextEditor; if (!activeEditor) { throw new Error("没有打开的文件"); }
const currentDir = path.dirname(activeEditor.document.uri.fsPath); const absolutePath = path.resolve(currentDir, relativePath);
if (!fs.existsSync(absolutePath)) { throw new Error(`文件不存在: ${absolutePath}`); }
const cos = new COS({ SecretId: secretId, SecretKey: secretKey, });
const progressOptions = { location: vscode.ProgressLocation.Notification, title: "正在上传到COS", cancellable: true, };
const res: { statusCode: number; Location: string } = await vscode.window.withProgress( progressOptions, async (progress, token) => { return new Promise((resolve, reject) => { const fileName = path.basename(absolutePath); const key = `${new Date().getTime()}_${fileName}`;
cos.putObject( { Bucket: bucket, Region: region, Key: key, Body: fs.createReadStream(absolutePath), onProgress: (progressData: { percent: number }) => { if (token.isCancellationRequested) { reject(new Error("上传已取消")); return; } const percent = Math.round(progressData.percent * 100); progress.report({ message: `${percent}%` }); }, }, (err: Error, data: any) => { if (err) { reject(err); return; } progress.report({ message: "上传完成!" }); resolve(data); } ); }); } );
console.log("ret ", res); if (res.statusCode === 200) { const url = `https://${res.Location}`; const editor = vscode.window.activeTextEditor; if (editor) { const document = editor.document; const text = document.getText(); const position = editor.selection.active; const line = document.lineAt(position.line).text; const linkPattern = /\[(.*?)\]\((.*?)\)/; const match = line.match(linkPattern);
if (match) { const oldPath = match[2]; const newText = line.replace(oldPath, url); editor.edit((editBuilder) => { editBuilder.replace( new vscode.Range( position.line, 0, position.line, line.length ), newText ); }); } } } else { throw new Error("上传失败! StatusCode = " + res.statusCode); }
vscode.window.showInformationMessage("文件上传成功!"); } catch (error) { vscode.window.showErrorMessage(`上传失败: ${(error as Error).message}`); } } );
context.subscriptions.push( vscode.languages.registerHoverProvider("markdown", hoverProvider), uploadCommand ); }
export function deactivate() {}
|