当vscode与--profile-temp
或--profile=myprofile
一起启动时,在扩展代码中如何获得存储配置文件所有数据的路径?
对于默认配置文件,我使用:
const dir = (process.env.VSCODE_PORTABLE ? process.env.VSCODE_PORTABLE + "/user-data" : process.env.APPDATA + "/Code") + "/User/";
它似乎适用于便携和安装版本的vscode,但是当使用概要文件时,路径是:
const dir = (process.env.VSCODE_PORTABLE ? process.env.VSCODE_PORTABLE + "/user-data" : process.env.APPDATA + "/Code") + "/User/Profiles/%profilefoldername%/"
其中%profilefoldername%
是一些随机名称。
发布于 2022-10-09 18:54:43
我的当前方法是将其中一个首选项(type = "string")的全局值更改为唯一的id
,并使用该id
搜索更新的settings.json
,该方法使用jsonc-parser
包:
npm install jsonc-parser
import { parse } from "jsonc-parser";
const profileDir = new Promise(resolve => {
let profileDir;
const extensionPrefScope = "myExtension", //myExtension.mySetting
extensionPrefName = "mySetting",
prefs = workspace.getConfiguration(extensionPrefScope),
pref = prefs.inspect(extensionPrefName), //get info about the setting
prefValue = pref.globalValue !== undefined ? pref.globalValue.replace(/ ?-profileDirID[\d.]+$/, "") : pref.globalValue,
//generate ID, in some rare circumstances previous ID could still be present, try remove it
id = (prefValue ? prefValue + " " : "") + "-profileDirID." + new Date().getTime() + performance.now(),
dir = ((process.env.VSCODE_PORTABLE ? process.env.VSCODE_PORTABLE + "/user-data" : {
windows: process.env.APPDATA + "/Code",
macos: process.env.HOME + "/Library/Application Support/Code",
linux: process.env.HOME + "/config/Code"
}[{darwin: "macos", win32: "windows" }[process.platform]||"linux"]) + "/User/")
.replace(/\//g, process.platform == "win32" ? "\\" : "/"),
watcher = workspace.createFileSystemWatcher(new RelativePattern(dir, "**/settings.json")),
watcherHandler = uri => {
if (profileDir)
return;
fs.readFile(uri.fsPath, (err, data) => {
if (profileDir)
return;
const json = parse(data.toString());
if (json[pref.key] !== id )
return;
profileDir = uri.fsPath.replace(/[^\\/]+$/, "");
watcher.dispose();
reset();
});
},
reset = () => {
console.log(id);
clearTimeout(resetTimer);
prefs.update(extensionPrefName, prefValue, true);
resolve(profileDir || dir);
};
watcher.onDidChange(watcherHandler);
watcher.onDidCreate(watcherHandler);
prefs.update(extensionPrefName, id, true);
const resetTimer = setTimeout(reset, 2000);
});
profileDir.then(console.log);
用设置范围/名称替换myExtension
和mySetting
。此方法具有故障安全,如果在2秒后未找到setting.json
,则将设置还原为原始值并返回“泛型”路径。
只在Windows上测试
https://stackoverflow.com/questions/74005539
复制相似问题