fix(cli): Exit CLI when trust save unsuccessful during launch (#11968)

This commit is contained in:
shrutip90
2025-11-14 11:56:39 -08:00
committed by GitHub
parent 6d83d3440c
commit d683e1c0db
7 changed files with 174 additions and 30 deletions

View File

@@ -76,11 +76,17 @@ export class LoadedTrustedFolders {
* @param location path
* @returns
*/
isPathTrusted(location: string): boolean | undefined {
isPathTrusted(
location: string,
config?: Record<string, TrustLevel>,
): boolean | undefined {
const configToUse = config ?? this.user.config;
const trustedPaths: string[] = [];
const untrustedPaths: string[] = [];
for (const rule of this.rules) {
for (const rule of Object.entries(configToUse).map(
([path, trustLevel]) => ({ path, trustLevel }),
)) {
switch (rule.trustLevel) {
case TrustLevel.TRUST_FOLDER:
trustedPaths.push(rule.path);
@@ -113,8 +119,19 @@ export class LoadedTrustedFolders {
}
setValue(path: string, trustLevel: TrustLevel): void {
const originalTrustLevel = this.user.config[path];
this.user.config[path] = trustLevel;
saveTrustedFolders(this.user);
try {
saveTrustedFolders(this.user);
} catch (e) {
// Revert the in-memory change if the save failed.
if (originalTrustLevel === undefined) {
delete this.user.config[path];
} else {
this.user.config[path] = originalTrustLevel;
}
throw e;
}
}
}
@@ -174,21 +191,17 @@ export function loadTrustedFolders(): LoadedTrustedFolders {
export function saveTrustedFolders(
trustedFoldersFile: TrustedFoldersFile,
): void {
try {
// Ensure the directory exists
const dirPath = path.dirname(trustedFoldersFile.path);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
fs.writeFileSync(
trustedFoldersFile.path,
JSON.stringify(trustedFoldersFile.config, null, 2),
{ encoding: 'utf-8', mode: 0o600 },
);
} catch (error) {
console.error('Error saving trusted folders file:', error);
// Ensure the directory exists
const dirPath = path.dirname(trustedFoldersFile.path);
if (!fs.existsSync(dirPath)) {
fs.mkdirSync(dirPath, { recursive: true });
}
fs.writeFileSync(
trustedFoldersFile.path,
JSON.stringify(trustedFoldersFile.config, null, 2),
{ encoding: 'utf-8', mode: 0o600 },
);
}
/** Is folder trust feature enabled per the current applied settings */
@@ -201,10 +214,7 @@ function getWorkspaceTrustFromLocalConfig(
trustConfig?: Record<string, TrustLevel>,
): TrustResult {
const folders = loadTrustedFolders();
if (trustConfig) {
folders.user.config = trustConfig;
}
const configToUse = trustConfig ?? folders.user.config;
if (folders.errors.length > 0) {
const errorMessages = folders.errors.map(
@@ -215,7 +225,7 @@ function getWorkspaceTrustFromLocalConfig(
);
}
const isTrusted = folders.isPathTrusted(process.cwd());
const isTrusted = folders.isPathTrusted(process.cwd(), configToUse);
return {
isTrusted,
source: isTrusted !== undefined ? 'file' : undefined,