From 49603d2aad514bd366baaf0b1adac6a9c9f9bb0d Mon Sep 17 00:00:00 2001 From: codewithchai0605 Date: Tue, 17 Nov 2026 09:38:48 +0530 Subject: [PATCH 1/5] Add unit tests for workspace extensions and settings - Implement tests for workspaceExtensions including validation of plugin IDs, parsing of extension recommendations, and handling of hostile input. - Introduce tests for workspaceSettings covering project settings allowlist, parsing of project settings, and validation of individual settings like tabSize and formatOnSave. - Ensure both test files check for frozen results and handle edge cases such as invalid JSON and prototype pollution. --- src/lang/ar-ye.json | 5 +- src/lang/az-az.json | 5 +- src/lang/be-by.json | 5 +- src/lang/bn-bd.json | 5 +- src/lang/cs-cz.json | 5 +- src/lang/de-de.json | 5 +- src/lang/en-us.json | 5 +- src/lang/es-sv.json | 5 +- src/lang/fr-fr.json | 5 +- src/lang/he-il.json | 5 +- src/lang/hi-in.json | 5 +- src/lang/hu-hu.json | 5 +- src/lang/id-id.json | 5 +- src/lang/index.d.ts | 3 + src/lang/ir-fa.json | 5 +- src/lang/it-it.json | 5 +- src/lang/ja-jp.json | 5 +- src/lang/ko-kr.json | 5 +- src/lang/ln-ln.json | 5 +- src/lang/ml-in.json | 5 +- src/lang/mm-unicode.json | 5 +- src/lang/mm-zawgyi.json | 5 +- src/lang/pl-pl.json | 5 +- src/lang/pt-br.json | 5 +- src/lang/pu-in.json | 5 +- src/lang/ru-ru.json | 5 +- src/lang/tl-ph.json | 5 +- src/lang/tr-tr.json | 5 +- src/lang/uk-ua.json | 5 +- src/lang/uz-uz.json | 5 +- src/lang/vi-vn.json | 5 +- src/lang/zh-cn.json | 5 +- src/lang/zh-hant.json | 5 +- src/lang/zh-tw.json | 5 +- src/lib/editorManager.js | 86 +- src/lib/prettierFormatter.js | 14 +- src/lib/projectExtensions.js | 135 +++ src/lib/saveFile.js | 8 +- src/lib/workspace.js | 383 ++++++++ src/lib/workspaceExtensions.js | 123 +++ src/lib/workspaceSettings.js | 116 +++ src/main.js | 30 + tests/unit/pluginFileRestoration.test.js | 1 + tests/unit/projectExtensions.test.js | 450 ++++++++++ tests/unit/saveFileProjectSettings.test.js | 233 +++++ tests/unit/workspace.test.js | 971 +++++++++++++++++++++ tests/unit/workspaceExtensions.test.js | 293 +++++++ tests/unit/workspaceSettings.test.js | 257 ++++++ 48 files changed, 3209 insertions(+), 59 deletions(-) create mode 100644 src/lib/projectExtensions.js create mode 100644 src/lib/workspace.js create mode 100644 src/lib/workspaceExtensions.js create mode 100644 src/lib/workspaceSettings.js create mode 100644 tests/unit/projectExtensions.test.js create mode 100644 tests/unit/saveFileProjectSettings.test.js create mode 100644 tests/unit/workspace.test.js create mode 100644 tests/unit/workspaceExtensions.test.js create mode 100644 tests/unit/workspaceSettings.test.js diff --git a/src/lang/ar-ye.json b/src/lang/ar-ye.json index 237e0e00db..aa07bdc2e8 100644 --- a/src/lang/ar-ye.json +++ b/src/lang/ar-ye.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/az-az.json b/src/lang/az-az.json index 8d52f94355..80a758d7c8 100644 --- a/src/lang/az-az.json +++ b/src/lang/az-az.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/be-by.json b/src/lang/be-by.json index e35007f98f..83deb48d66 100644 --- a/src/lang/be-by.json +++ b/src/lang/be-by.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/bn-bd.json b/src/lang/bn-bd.json index 4a09aab67d..752a748434 100644 --- a/src/lang/bn-bd.json +++ b/src/lang/bn-bd.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/cs-cz.json b/src/lang/cs-cz.json index 4aff3839ca..7e1ca04aea 100644 --- a/src/lang/cs-cz.json +++ b/src/lang/cs-cz.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/de-de.json b/src/lang/de-de.json index fc6d094814..2004a25a43 100644 --- a/src/lang/de-de.json +++ b/src/lang/de-de.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/en-us.json b/src/lang/en-us.json index aaadfb66fb..7067c3a381 100644 --- a/src/lang/en-us.json +++ b/src/lang/en-us.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/es-sv.json b/src/lang/es-sv.json index ec1c72475c..2efff2ca60 100644 --- a/src/lang/es-sv.json +++ b/src/lang/es-sv.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/fr-fr.json b/src/lang/fr-fr.json index 5ee85deaf3..0535c4fcd0 100644 --- a/src/lang/fr-fr.json +++ b/src/lang/fr-fr.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/he-il.json b/src/lang/he-il.json index 140eee0cbc..007ad34022 100644 --- a/src/lang/he-il.json +++ b/src/lang/he-il.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/hi-in.json b/src/lang/hi-in.json index dd73c90588..dee9957c91 100644 --- a/src/lang/hi-in.json +++ b/src/lang/hi-in.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/hu-hu.json b/src/lang/hu-hu.json index 3a65b167ca..62b3c76211 100644 --- a/src/lang/hu-hu.json +++ b/src/lang/hu-hu.json @@ -915,5 +915,8 @@ "files saved count": "{count} fájl mentve", "files not saved count": "{count} fájl nem lett mentve", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/id-id.json b/src/lang/id-id.json index 494c3721e9..d90e9553f9 100644 --- a/src/lang/id-id.json +++ b/src/lang/id-id.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/index.d.ts b/src/lang/index.d.ts index 0820be436e..62fa178d9e 100644 --- a/src/lang/index.d.ts +++ b/src/lang/index.d.ts @@ -919,6 +919,9 @@ declare type LangStrings = { "files not saved count": string; "use native index": string; "use native index hint": string; + "project extensions title": string; + "project extensions message": string; + "review recommendations": string; }; declare var strings: LangStrings; diff --git a/src/lang/ir-fa.json b/src/lang/ir-fa.json index 8a39c355ef..7fb9f53056 100644 --- a/src/lang/ir-fa.json +++ b/src/lang/ir-fa.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/it-it.json b/src/lang/it-it.json index 2bef6cd64e..da0bb856a5 100644 --- a/src/lang/it-it.json +++ b/src/lang/it-it.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/ja-jp.json b/src/lang/ja-jp.json index 7bc5350ce0..b5f073994f 100644 --- a/src/lang/ja-jp.json +++ b/src/lang/ja-jp.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/ko-kr.json b/src/lang/ko-kr.json index 4d262e7890..aedcdac114 100644 --- a/src/lang/ko-kr.json +++ b/src/lang/ko-kr.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/ln-ln.json b/src/lang/ln-ln.json index 91aba76daa..4f44d720cb 100644 --- a/src/lang/ln-ln.json +++ b/src/lang/ln-ln.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/ml-in.json b/src/lang/ml-in.json index 4404143962..5a37557940 100644 --- a/src/lang/ml-in.json +++ b/src/lang/ml-in.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/mm-unicode.json b/src/lang/mm-unicode.json index da5651ec6e..0360798580 100644 --- a/src/lang/mm-unicode.json +++ b/src/lang/mm-unicode.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/mm-zawgyi.json b/src/lang/mm-zawgyi.json index 1a0a0d1a4c..b9094d254f 100644 --- a/src/lang/mm-zawgyi.json +++ b/src/lang/mm-zawgyi.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/pl-pl.json b/src/lang/pl-pl.json index 6df27618d1..34839e2142 100644 --- a/src/lang/pl-pl.json +++ b/src/lang/pl-pl.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/pt-br.json b/src/lang/pt-br.json index c8d10df39b..6c7a6a7eda 100644 --- a/src/lang/pt-br.json +++ b/src/lang/pt-br.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/pu-in.json b/src/lang/pu-in.json index fa9faa09eb..0fc04b2774 100644 --- a/src/lang/pu-in.json +++ b/src/lang/pu-in.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/ru-ru.json b/src/lang/ru-ru.json index 18990d3b4c..c61ad188aa 100644 --- a/src/lang/ru-ru.json +++ b/src/lang/ru-ru.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/tl-ph.json b/src/lang/tl-ph.json index bf6942d436..fdf826ee0b 100644 --- a/src/lang/tl-ph.json +++ b/src/lang/tl-ph.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/tr-tr.json b/src/lang/tr-tr.json index 588fef21a2..82aba00221 100644 --- a/src/lang/tr-tr.json +++ b/src/lang/tr-tr.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/uk-ua.json b/src/lang/uk-ua.json index 2f4104fbf4..c1cda25346 100644 --- a/src/lang/uk-ua.json +++ b/src/lang/uk-ua.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/uz-uz.json b/src/lang/uz-uz.json index e54da9d859..78c6b78e8f 100644 --- a/src/lang/uz-uz.json +++ b/src/lang/uz-uz.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/vi-vn.json b/src/lang/vi-vn.json index dfe6e920d4..3236d09975 100644 --- a/src/lang/vi-vn.json +++ b/src/lang/vi-vn.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/zh-cn.json b/src/lang/zh-cn.json index ab03b1f807..a7d4224be1 100644 --- a/src/lang/zh-cn.json +++ b/src/lang/zh-cn.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/zh-hant.json b/src/lang/zh-hant.json index 5164bc8939..beb4539e2f 100644 --- a/src/lang/zh-hant.json +++ b/src/lang/zh-hant.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lang/zh-tw.json b/src/lang/zh-tw.json index afb65dde26..5c5e70c88b 100644 --- a/src/lang/zh-tw.json +++ b/src/lang/zh-tw.json @@ -915,5 +915,8 @@ "files saved count": "Files saved: {count}", "files not saved count": "Files not saved: {count}", "use native index": "Use native index", - "use native index hint": "Search local folders faster using the native file index." + "use native index hint": "Search local folders faster using the native file index.", + "project extensions title": "Plugins recommended by {project}", + "project extensions message": "{project} recommends: {plugins}", + "review recommendations": "Review" } diff --git a/src/lib/editorManager.js b/src/lib/editorManager.js index ae95b065ca..a5a05f12fb 100644 --- a/src/lib/editorManager.js +++ b/src/lib/editorManager.js @@ -117,6 +117,8 @@ import EditorFile, { AUTO_SAVE } from "./editorFile"; import openFile from "./openFile"; import { addedFolder } from "./openFolder"; import appSettings from "./settings"; +import workspace from "./workspace"; +import { PROJECT_SETTING_KEYS } from "./workspaceSettings"; import { getSystemConfiguration, HARDKEYBOARDHIDDEN_NO, @@ -1120,8 +1122,17 @@ async function EditorManager($header, $body) { ]); } + // The settings the options are built from. While options are applied to a + // file this is the user's settings with that file's project overrides on + // top (see applyOptions); otherwise just the user's settings. Options that + // a project may override read from here, the rest from appSettings. + let optionValues = null; + function getOptionValues() { + return optionValues || appSettings?.value || {}; + } + function makeIndentExtensions() { - const { softTab = true, tabSize = 2 } = appSettings?.value || {}; + const { softTab = true, tabSize = 2 } = getOptionValues(); const unit = softTab ? " ".repeat(Math.max(1, Number(tabSize) || 2)) : "\t"; return { indentExt: indentUnit.of(unit), @@ -1401,28 +1412,46 @@ async function EditorManager($header, $body) { ]; } - function applyOptions(keys, targetEditor = null) { + /** + * @param {string[]|null} keys Settings to apply, or null for all. + * @param {object|null} targetEditor Editor to apply to, or null for every pane. + * @param {object|null} file File the options are for. Defaults to the file + * the target's pane is showing. Its project's overrides are applied. + */ + function applyOptions(keys, targetEditor = null, file = null) { const filter = keys ? new Set(keys) : null; const targetEditors = targetEditor ? [targetEditor] : panes.map((pane) => pane.editor).filter(Boolean); for (const target of targetEditors) { - for (const spec of cmOptionSpecs) { - if (filter && !spec.keys.some((k) => filter.has(k))) continue; - const built = spec.build(); - const effects = []; - if (spec.compartments.length === 1) { - effects.push(spec.compartments[0].reconfigure(built)); - } else { - const arr = Array.isArray(built) ? built : [built]; - for (let i = 0; i < spec.compartments.length; i++) { - const comp = spec.compartments[i]; - const ext = arr[i] ?? []; - effects.push(comp.reconfigure(ext)); + const targetFile = file || target.__editorPane?.activeFile; + // Restored afterwards rather than cleared, in case applying an option + // leads to another applyOptions call. + const previousOptionValues = optionValues; + optionValues = workspace.resolveSettings( + appSettings?.value || {}, + targetFile?.uri, + ); + try { + for (const spec of cmOptionSpecs) { + if (filter && !spec.keys.some((k) => filter.has(k))) continue; + const built = spec.build(); + const effects = []; + if (spec.compartments.length === 1) { + effects.push(spec.compartments[0].reconfigure(built)); + } else { + const arr = Array.isArray(built) ? built : [built]; + for (let i = 0; i < spec.compartments.length; i++) { + const comp = spec.compartments[i]; + const ext = arr[i] ?? []; + effects.push(comp.reconfigure(ext)); + } } + target.dispatch({ effects }); } - target.dispatch({ effects }); + } finally { + optionValues = previousOptionValues; } if (isCanvasView(target)) syncCanvasOptions(target); } @@ -2824,8 +2853,11 @@ async function EditorManager($header, $body) { }); } - function getEditorOptionsSignature() { - const values = appSettings?.value || {}; + function getEditorOptionsSignature(file) { + const values = workspace.resolveSettings( + appSettings?.value || {}, + file?.uri, + ); const keys = new Set(["editorTheme"]); for (const spec of cmOptionSpecs) { spec.keys.forEach((key) => keys.add(key)); @@ -2978,11 +3010,11 @@ async function EditorManager($header, $body) { const targetTouchSelectionController = targetPane?.touchSelectionController || touchSelectionController; targetTouchSelectionController?.onSessionChanged(); - const optionsSignature = getEditorOptionsSignature(); + const optionsSignature = getEditorOptionsSignature(file); if (forceOptions || file.__cmOptionsSignature !== optionsSignature) { const desiredTheme = appSettings?.value?.editorTheme; if (desiredTheme) targetEditor.setTheme(desiredTheme); - applyOptions(null, targetEditor); + applyOptions(null, targetEditor, file); file.__cmOptionsSignature = optionsSignature; } try { @@ -3590,6 +3622,22 @@ async function EditorManager($header, $body) { // Ensure initial options reflect settings applyOptions(); + // A project's settings can arrive after its files are already showing (the + // project is scanned asynchronously), change when its settings.json is + // saved, or go away with the project. Reapply them to what is showing; + // files that are not showing pick the change up when they are shown, since + // their options signature includes the project's overrides. + function reapplyProjectOptions() { + for (const pane of panes) { + const file = pane.activeFile; + if (!pane.editor || file?.type !== "editor") continue; + applyOptions(PROJECT_SETTING_KEYS, pane.editor, file); + } + } + for (const event of ["open", "settings", "close"]) { + workspace.on(event, reapplyProjectOptions); + } + $hScrollbar.onshow = $vScrollbar.onshow = updateFloatingButton.bind( {}, false, diff --git a/src/lib/prettierFormatter.js b/src/lib/prettierFormatter.js index e95014c0cf..340478d9ae 100644 --- a/src/lib/prettierFormatter.js +++ b/src/lib/prettierFormatter.js @@ -4,6 +4,7 @@ import { getDocText } from "cm/editorUtils"; import { getFormatAsMode } from "cm/modelist"; import toast from "components/toast"; import appSettings from "lib/settings"; +import workspace from "lib/workspace"; import prettierPluginBabel from "prettier/plugins/babel"; import prettierPluginEstree from "prettier/plugins/estree"; import prettierPluginGraphql from "prettier/plugins/graphql"; @@ -127,17 +128,18 @@ async function resolvePrettierConfig(file) { const overrides = appSettings?.value?.prettier || {}; const projectConfig = await loadProjectConfig(file); const result = { ...overrides, ...(projectConfig || {}) }; + // Indentation falls back to the editor's, which a project may override in + // .acode/settings.json, so formatting agrees with what the editor types. + // A prettier config file still beats both. + const editor = workspace.resolveSettings(appSettings?.value || {}, file?.uri); if (file?.eol && result.endOfLine == null) { result.endOfLine = file.eol === "windows" ? "crlf" : "lf"; } if (result.useTabs == null) { - result.useTabs = !appSettings?.value?.softTab; + result.useTabs = !editor.softTab; } - if ( - result.tabWidth == null && - typeof appSettings?.value?.tabSize === "number" - ) { - result.tabWidth = appSettings.value.tabSize; + if (result.tabWidth == null && typeof editor.tabSize === "number") { + result.tabWidth = editor.tabSize; } return result; } diff --git a/src/lib/projectExtensions.js b/src/lib/projectExtensions.js new file mode 100644 index 0000000000..45d4647a37 --- /dev/null +++ b/src/lib/projectExtensions.js @@ -0,0 +1,135 @@ +import fsOperation from "fileSystem"; +import notificationManager from "lib/notificationManager"; +import appSettings from "lib/settings"; +import workspace from "lib/workspace"; +import { isPluginId, sameRecommendations } from "./workspaceExtensions"; + +/** What was already announced this session, so the same advice is not repeated. */ +const announced = new Set(); + +/** + * Fill `{name}` placeholders in a translated string. + * @param {string} text + * @param {Record} values + * @returns {string} + */ +function format(text, values) { + return String(text || "").replace( + /\{(\w+)\}/g, + (_, key) => values[key] ?? "", + ); +} + +/** + * Pick out the plugins that are not installed yet. A plugin that is installed + * but switched off counts as installed: that was the user's choice. + * When Acode cannot tell, the plugin is left out rather than nagged about. + * @param {readonly string[]} ids + * @returns {Promise} + */ +export async function findMissing(ids) { + const missing = []; + for (const id of ids) { + // The ids were checked when the file was read. Check again, because an id + // becomes part of a file path right here. + if (!isPluginId(id)) continue; + try { + if (!(await fsOperation(PLUGIN_DIR, id).exists())) missing.push(id); + } catch (error) { + // Unknown, so say nothing. + } + } + return missing; +} + +/** + * Open the registry page of a recommended plugin. The page shows its details + * and an install button; nothing is installed unless the user presses it. + * @param {readonly string[]} ids The recommended plugins that are missing. + */ +export async function review(ids) { + let id = ids[0]; + if (ids.length > 1) { + const { default: select } = await import("dialogs/select"); + id = await select(strings.plugins, [...ids]); + } + if (!isPluginId(id)) return; + + const { openWithSearch } = await import("sidebarApps/extensions"); + openWithSearch(`id:${id}`); +} + +/** + * Tell the user, once, about plugins a workspace recommends that they lack. + * @param {import("./workspace").Workspace} ws + * @returns {Promise} Whether a notification was shown. + */ +export async function recommend(ws) { + if (appSettings.value.recommendExtensions === false) return false; + + const ids = ws.extensions?.recommendations ?? []; + if (!ids.length) return false; + + const missing = await findMissing(ids); + if (!missing.length) return false; + + // The project may have been closed or its list edited while we were looking. + const current = workspace.get(ws.url); + if (!current || !sameRecommendations(current.extensions, ws.extensions)) { + return false; + } + + const key = `${ws.url}\n${missing.join("\n")}`; + if (announced.has(key)) return false; + announced.add(key); + + const project = ws.name || ws.url; + const open = () => { + review(missing).catch((error) => { + console.warn("Failed to open recommended plugin.", error); + }); + }; + + notificationManager.pushNotification({ + title: format(strings["project extensions title"], { project }), + message: format(strings["project extensions message"], { + project, + plugins: missing.join(", "), + }), + icon: "extension", + type: "info", + action: open, + actions: [ + { + text: strings["review recommendations"], + icon: "extension", + action: open, + }, + ], + }); + return true; +} + +/** + * Start watching workspaces for plugin recommendations. + * Needs `workspace.init` to have been called. + * @returns {() => void} Stops watching and forgets what was announced. + */ +export function init() { + const onWorkspace = (ws) => { + recommend(ws).catch((error) => { + console.warn("Failed to check plugin recommendations.", error); + }); + }; + + workspace.on("open", onWorkspace); + workspace.on("extensions", onWorkspace); + + return () => { + workspace.off("open", onWorkspace); + workspace.off("extensions", onWorkspace); + announced.clear(); + }; +} + +export default { init, recommend, review, findMissing }; diff --git a/src/lib/saveFile.js b/src/lib/saveFile.js index 5ff14b853d..4e3bb54b57 100644 --- a/src/lib/saveFile.js +++ b/src/lib/saveFile.js @@ -13,6 +13,7 @@ import config from "./config"; import EditorFile from "./editorFile"; import openFolder from "./openFolder"; import appSettings from "./settings"; +import workspace from "./workspace"; /** @type {WeakMap} */ const saveTimeouts = new WeakMap(); @@ -175,7 +176,12 @@ async function saveFile( // The format command works on the active editor, so only format when the // file being saved is the one shown (bulk saves cover background tabs). - if (appSettings.value.formatOnSave && editorManager.activeFile === file) { + // A project may turn this on or off for the files inside it. + const { formatOnSave } = workspace.resolveSettings( + appSettings.value, + file.uri, + ); + if (formatOnSave && editorManager.activeFile === file) { file.markChanged = false; try { acode.exec("format", false); diff --git a/src/lib/workspace.js b/src/lib/workspace.js new file mode 100644 index 0000000000..f6d3f7ff0a --- /dev/null +++ b/src/lib/workspace.js @@ -0,0 +1,383 @@ +import fsOperation from "fileSystem"; +import Url from "utils/Url"; +import { + EXTENSIONS_FILE, + MAX_EXTENSIONS_FILE_SIZE, + NO_RECOMMENDATIONS, + parseExtensionRecommendations, + sameRecommendations, + unusableRecommendations, +} from "./workspaceExtensions"; +import { + MAX_SETTINGS_SIZE, + NO_PROJECT_SETTINGS, + parseProjectSettings, + SETTINGS_FILE, + sameProjectSettings, + unusableProjectSettings, +} from "./workspaceSettings"; + +/** Name of the directory that holds a project's Acode configuration. */ +export const WORKSPACE_DIR = ".acode"; + +/** + * @typedef {object} Workspace + * @property {string} url Url of the project root folder. + * @property {string} name Name the root was opened with. + * @property {string} configUrl Url of the root's `.acode` directory. + * @property {import("./workspaceSettings").ProjectSettings} settings What the + * project's `settings.json` says. Has no values when the file is missing. + * @property {import("./workspaceExtensions").ExtensionRecommendations} extensions + * What the project's `extensions.json` recommends. Has none when the file is missing. + */ + +/** + * @typedef {"open"|"settings"|"extensions"|"close"} WorkspaceEvent + * "open": a root with a `.acode` directory was recognised. + * "settings": a recognised root's settings changed. + * "extensions": a recognised root's plugin recommendations changed. + * "close": a recognised root was closed, or lost its `.acode` directory. + * Listeners receive the {@link Workspace}; for "settings" that is the new + * state, for "close" the state it had when it went away. + */ + +/** Open roots, configured or not, by url. @type {Map} */ +const roots = new Map(); +/** Roots that have a `.acode` directory, by url. @type {Map} */ +const workspaces = new Map(); +/** + * The scan currently running for each root. A scan whose token is no longer + * here was superseded (or its root closed) and must not touch the registry. + * @type {Map} + */ +const scans = new Map(); +/** @type {Record>} */ +const listeners = { + open: new Set(), + settings: new Set(), + extensions: new Set(), + close: new Set(), +}; + +let stopListening = null; + +/** + * Locate the `.acode` directory of a project root. + * A `.acode` that is a file, or anything that cannot be stat'ed (missing, + * unreadable, offline server), means the root has no workspace configuration. + * @param {string} rootUrl + * @returns {Promise} Url of the `.acode` directory, or null + */ +export async function detectConfigDir(rootUrl) { + try { + const configUrl = Url.join(rootUrl, WORKSPACE_DIR); + if (!configUrl) return null; + const stat = await fsOperation(configUrl)?.stat(); + return stat?.isDirectory ? configUrl : null; + } catch (error) { + return null; + } +} + +/** + * Read one of the files in `.acode`. Those files are optional, so a missing or + * unreadable one is never an error: it just means the project says nothing. + * @param {string} configUrl + * @param {string} fileName + * @param {number} maxSize + * @returns {Promise<{text: string}|{tooLarge: true}|null>} null when there is nothing to read + */ +async function readConfigFile(configUrl, fileName, maxSize) { + try { + const fs = fsOperation(Url.join(configUrl, fileName)); + const stat = await fs?.stat(); + if (!stat?.isFile) return null; + if (stat.size > maxSize) return { tooLarge: true }; + return { text: await fs.readFile("utf8") }; + } catch (error) { + return null; + } +} + +const tooLarge = (maxSize) => `File is larger than ${maxSize / 1024} KB`; + +/** + * @param {string} configUrl + * @returns {Promise} + */ +async function loadSettings(configUrl) { + const file = await readConfigFile( + configUrl, + SETTINGS_FILE, + MAX_SETTINGS_SIZE, + ); + if (!file) return NO_PROJECT_SETTINGS; + if (file.tooLarge) { + return unusableProjectSettings(tooLarge(MAX_SETTINGS_SIZE)); + } + return parseProjectSettings(file.text); +} + +/** + * @param {string} configUrl + * @returns {Promise} + */ +async function loadExtensions(configUrl) { + const file = await readConfigFile( + configUrl, + EXTENSIONS_FILE, + MAX_EXTENSIONS_FILE_SIZE, + ); + if (!file) return NO_RECOMMENDATIONS; + if (file.tooLarge) { + return unusableRecommendations(tooLarge(MAX_EXTENSIONS_FILE_SIZE)); + } + return parseExtensionRecommendations(file.text); +} + +/** + * @param {WorkspaceEvent} event + * @param {Workspace} workspace + */ +function emit(event, workspace) { + for (const listener of [...listeners[event]]) { + try { + listener(workspace); + } catch (error) { + console.error(`Workspace "${event}" listener failed:`, error); + } + } +} + +/** + * Check a root for a `.acode` directory and update the registry. + * @param {string} url + * @returns {Promise} + */ +async function scan(url) { + const token = Symbol(url); + scans.set(url, token); + + const configUrl = await detectConfigDir(url); + const [settings, extensions] = configUrl + ? await Promise.all([loadSettings(configUrl), loadExtensions(configUrl)]) + : [null, null]; + + // The root was closed or rescanned while we were waiting on the file system. + if (scans.get(url) !== token) return workspaces.get(url) ?? null; + scans.delete(url); + + const existing = workspaces.get(url); + + if (!configUrl) { + if (existing) { + workspaces.delete(url); + emit("close", existing); + } + return null; + } + + const settingsChanged = + !existing || !sameProjectSettings(existing.settings, settings); + const extensionsChanged = + !existing || !sameRecommendations(existing.extensions, extensions); + if (!settingsChanged && !extensionsChanged) return existing; + + /** @type {Workspace} */ + const workspace = Object.freeze({ + url, + name: roots.get(url), + configUrl, + settings, + extensions, + }); + workspaces.set(url, workspace); + + if (!existing) { + emit("open", workspace); + } else { + if (settingsChanged) emit("settings", workspace); + if (extensionsChanged) emit("extensions", workspace); + } + return workspace; +} + +/** + * @param {{url: string, name?: string}} folder + */ +function onAddFolder({ url, name } = {}) { + if (!url || roots.has(url)) return; + roots.set(url, name); + scan(url).catch((error) => { + console.error(`Failed to scan workspace "${url}":`, error); + }); +} + +/** + * @param {{url: string}} folder + */ +function onRemoveFolder({ url } = {}) { + if (!url || !roots.delete(url)) return; + scans.delete(url); + + const workspace = workspaces.get(url); + if (!workspace) return; + workspaces.delete(url); + emit("close", workspace); +} + +/** + * Saving a file inside a root's `.acode` directory changes what is in it, so + * look at that root again. This is what makes edits to `settings.json` take + * effect right away, and notices a `.acode` directory that was just created. + * @param {{uri?: string}} file + */ +function onSaveFile(file) { + const uri = file?.uri; + if (!uri) return; + + for (const root of roots.keys()) { + let configUrl; + try { + configUrl = Url.join(root, WORKSPACE_DIR); + } catch (error) { + continue; + } + if (!configUrl || !Url.isSameOrDescendant(uri, configUrl)) continue; + scan(root).catch((error) => { + console.error(`Failed to scan workspace "${root}":`, error); + }); + } +} + +/** + * Start tracking workspaces. Call once the editor manager exists and before + * saved folders are restored, so those are recognised as well. + * Calling it again restarts tracking from scratch. + * @param {object} manager Emits "add-folder", "remove-folder" and "save-file" like editorManager. + * @param {Array<{url: string, title?: string, name?: string}>} [openFolders] + * Folders that are already open. + * @returns {() => void} Stops tracking and forgets every workspace. + */ +export function init(manager, openFolders = []) { + stopListening?.(); + + manager.on("add-folder", onAddFolder); + manager.on("remove-folder", onRemoveFolder); + manager.on("save-file", onSaveFile); + + stopListening = () => { + manager.off("add-folder", onAddFolder); + manager.off("remove-folder", onRemoveFolder); + manager.off("save-file", onSaveFile); + roots.clear(); + workspaces.clear(); + scans.clear(); + stopListening = null; + }; + + for (const { url, title, name } of openFolders) { + onAddFolder({ url, name: name ?? title }); + } + + return stopListening; +} + +/** + * Get the workspace of a project root. + * @param {string} rootUrl + * @returns {Workspace|null} + */ +export function get(rootUrl) { + return workspaces.get(rootUrl) ?? null; +} + +/** + * Find the workspace a file or folder belongs to. When roots are nested, the + * innermost configured one wins. + * @param {string} url + * @returns {Workspace|null} + */ +export function find(url) { + if (!url) return null; + let match = null; + for (const workspace of workspaces.values()) { + if (!Url.isSameOrDescendant(url, workspace.url)) continue; + if (!match || workspace.url.length > match.url.length) match = workspace; + } + return match; +} + +/** + * The settings the project overrides for a file or folder: those of the + * innermost workspace it belongs to, or none when it is in no workspace. + * The result is frozen and is never the user's global settings. + * @param {string} url + * @returns {Readonly>} + */ +export function getSettings(url) { + return (find(url) ?? { settings: NO_PROJECT_SETTINGS }).settings.values; +} + +/** + * Combine a set of settings with the overrides of the project a file is in. + * Returns `base` itself when the file has no overrides, so files outside any + * project behave exactly as before. Otherwise returns a new object and leaves + * `base` alone: the user's global settings are never modified. + * @template {object} T + * @param {T} base Usually the user's settings. + * @param {string} [url] The file the settings are for. + * @returns {T} + */ +export function resolveSettings(base, url) { + const overrides = getSettings(url); + return Object.keys(overrides).length ? { ...base, ...overrides } : base; +} + +/** + * All configured workspaces that are currently open. + * @returns {Workspace[]} + */ +export function list() { + return [...workspaces.values()]; +} + +/** + * Check an open root again, e.g. after its `.acode` directory was created or + * deleted. Does nothing for roots that are not open. + * @param {string} rootUrl + * @returns {Promise} + */ +export function refresh(rootUrl) { + if (!roots.has(rootUrl)) return Promise.resolve(null); + return scan(rootUrl); +} + +/** + * @param {WorkspaceEvent} event + * @param {(workspace: Workspace) => void} listener + */ +export function on(event, listener) { + listeners[event]?.add(listener); +} + +/** + * @param {WorkspaceEvent} event + * @param {(workspace: Workspace) => void} listener + */ +export function off(event, listener) { + listeners[event]?.delete(listener); +} + +export default { + WORKSPACE_DIR, + init, + get, + find, + getSettings, + resolveSettings, + list, + refresh, + on, + off, +}; diff --git a/src/lib/workspaceExtensions.js b/src/lib/workspaceExtensions.js new file mode 100644 index 0000000000..c9e870b8b1 --- /dev/null +++ b/src/lib/workspaceExtensions.js @@ -0,0 +1,123 @@ +/** File inside `.acode` that holds the recommendations. */ +export const EXTENSIONS_FILE = "extensions.json"; + +/** Larger files are not read: this file is tiny, and some file systems are remote. */ +export const MAX_EXTENSIONS_FILE_SIZE = 64 * 1024; + +/** A project suggesting more than this is more likely spam than advice. */ +export const MAX_RECOMMENDATIONS = 10; + +/** What a plugin id looks like. Must never match anything path- or URL-like. */ +const PLUGIN_ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}$/; + +/** + * @typedef {object} ExtensionRecommendations + * @property {readonly string[]} recommendations Valid plugin ids, without duplicates. + * @property {readonly string[]} problems Why part or all of the file was not used. Empty when it is fine. + */ + +/** No recommendations. Shared, so it must stay frozen. @type {Readonly} */ +export const NO_RECOMMENDATIONS = Object.freeze({ + recommendations: Object.freeze([]), + problems: Object.freeze([]), +}); + +/** + * Tell whether a value is an acceptable plugin id. + * @param {unknown} id + * @returns {boolean} + */ +export function isPluginId(id) { + return typeof id === "string" && PLUGIN_ID.test(id); +} + +/** + * Read the text of an `.acode/extensions.json`. + * Never throws. A bad file yields no recommendations plus a description of what + * is wrong, and a bad entry costs only that entry, not the rest of the list. + * @param {string} text + * @returns {ExtensionRecommendations} + */ +export function parseExtensionRecommendations(text) { + if (typeof text !== "string" || !text.trim()) return NO_RECOMMENDATIONS; + + let data; + try { + data = JSON.parse(text); + } catch (error) { + return freeze([], [`Not valid JSON (${error.message})`]); + } + + if (data === null || typeof data !== "object" || Array.isArray(data)) { + return freeze([], ["Expected a JSON object"]); + } + + // Unknown keys are ignored: they may belong to a newer Acode. + if (!Object.prototype.hasOwnProperty.call(data, "recommendations")) { + return NO_RECOMMENDATIONS; + } + + const list = data.recommendations; + if (!Array.isArray(list)) { + return freeze([], ['"recommendations" must be a list of plugin ids']); + } + + const recommendations = []; + const problems = []; + + for (const entry of list) { + if (!isPluginId(entry)) { + problems.push(`${describe(entry)} is not a valid plugin id`); + continue; + } + if (recommendations.includes(entry)) continue; + if (recommendations.length >= MAX_RECOMMENDATIONS) { + problems.push(`Only the first ${MAX_RECOMMENDATIONS} plugins are used`); + break; + } + recommendations.push(entry); + } + + return freeze(recommendations, problems); +} + +/** + * A result for a file that could not be used at all, e.g. because it is too big. + * @param {string} problem + * @returns {ExtensionRecommendations} + */ +export function unusableRecommendations(problem) { + return freeze([], [problem]); +} + +/** + * Tell whether two parse results say the same thing. + * @param {ExtensionRecommendations} a + * @param {ExtensionRecommendations} b + * @returns {boolean} + */ +export function sameRecommendations(a, b) { + return ( + JSON.stringify([a.recommendations, a.problems]) === + JSON.stringify([b.recommendations, b.problems]) + ); +} + +/** + * Show an offending entry in a message without trusting its size or content. + * @param {unknown} entry + * @returns {string} + */ +function describe(entry) { + if (typeof entry !== "string") + return `A ${entry === null ? "null" : typeof entry} entry`; + const shown = entry.length > 40 ? `${entry.slice(0, 40)}…` : entry; + return `"${shown}"`; +} + +function freeze(recommendations, problems) { + return Object.freeze({ + recommendations: Object.freeze(recommendations), + problems: Object.freeze(problems), + }); +} diff --git a/src/lib/workspaceSettings.js b/src/lib/workspaceSettings.js new file mode 100644 index 0000000000..19284a51e2 --- /dev/null +++ b/src/lib/workspaceSettings.js @@ -0,0 +1,116 @@ +/** File inside `.acode` that holds the project settings. */ +export const SETTINGS_FILE = "settings.json"; + +/** Larger files are not read: settings are tiny, and some file systems are remote. */ +export const MAX_SETTINGS_SIZE = 64 * 1024; + +const hasOwn = (object, key) => + Object.prototype.hasOwnProperty.call(object, key); + +/** + * Settings a project may override, with a check for each value. + * The ranges match what Acode's own settings screen accepts. + * @type {Record boolean, expected: string}>} + */ +const schema = { + tabSize: { + check: (value) => Number.isInteger(value) && value >= 1 && value <= 8, + expected: "a whole number from 1 to 8", + }, + softTab: { + check: (value) => typeof value === "boolean", + expected: "true or false", + }, + formatOnSave: { + check: (value) => typeof value === "boolean", + expected: "true or false", + }, +}; + +/** Names of the settings a project may override. */ +export const PROJECT_SETTING_KEYS = Object.freeze(Object.keys(schema)); + +/** + * @typedef {object} ProjectSettings + * @property {Readonly>} values Valid overrides. + * @property {string[]} problems Why part or all of the file was not used. Empty when it is fine. + * @property {string[]} ignored Names of settings that are not recognised. + */ + +/** No overrides. Shared, so it must stay frozen. @type {Readonly} */ +export const NO_PROJECT_SETTINGS = Object.freeze({ + values: Object.freeze({}), + problems: Object.freeze([]), + ignored: Object.freeze([]), +}); + +/** + * Read the text of a `.acode/settings.json`. + * Never throws. A bad file yields no overrides plus a description of what is + * wrong, and a bad value costs only that value, not the rest of the file. + * @param {string} text + * @returns {ProjectSettings} + */ +export function parseProjectSettings(text) { + if (typeof text !== "string" || !text.trim()) return NO_PROJECT_SETTINGS; + + let data; + try { + data = JSON.parse(text); + } catch (error) { + return freeze({}, [`Not valid JSON (${error.message})`], []); + } + + if (data === null || typeof data !== "object" || Array.isArray(data)) { + return freeze({}, ["Expected a JSON object"], []); + } + + const values = {}; + const problems = []; + const ignored = []; + + // Own properties only, so keys like "__proto__" or "toString" mean nothing. + for (const key of Object.keys(data)) { + if (!hasOwn(schema, key)) { + ignored.push(key); + continue; + } + if (schema[key].check(data[key])) { + values[key] = data[key]; + } else { + problems.push(`"${key}" must be ${schema[key].expected}`); + } + } + + return freeze(values, problems, ignored); +} + +/** + * A result for a file that could not be used at all, e.g. because it is too big. + * @param {string} problem + * @returns {ProjectSettings} + */ +export function unusableProjectSettings(problem) { + return freeze({}, [problem], []); +} + +/** + * Tell whether two parse results say the same thing. + * @param {ProjectSettings} a + * @param {ProjectSettings} b + * @returns {boolean} + */ +export function sameProjectSettings(a, b) { + return ( + JSON.stringify([a.values, a.problems]) === + JSON.stringify([b.values, b.problems]) + ); +} + +function freeze(values, problems, ignored) { + return Object.freeze({ + values: Object.freeze(values), + problems: Object.freeze(problems), + ignored: Object.freeze(ignored), + }); +} diff --git a/src/main.js b/src/main.js index cf91423da2..24e7a477b4 100644 --- a/src/main.js +++ b/src/main.js @@ -53,6 +53,7 @@ import loadPlugins from "lib/loadPlugins"; import Logger from "lib/logger"; import notificationManager from "lib/notificationManager"; import openFolder, { addedFolder } from "lib/openFolder"; +import projectExtensions from "lib/projectExtensions"; import { registerPrettierFormatter } from "lib/registerPrettierFormatter"; import restoreFiles from "lib/restoreFiles"; import settings from "lib/settings"; @@ -61,6 +62,7 @@ import startAd, { BANNER_SUPPRESSION_REASON, setBannerSuppressed, } from "lib/startAd"; +import workspace from "lib/workspace"; import mustache from "mustache"; import themes from "theme/list"; import { initHighlighting } from "utils/codeHighlight"; @@ -770,6 +772,34 @@ async function loadApp() { toast("Failed to load theme plugins!"); } + // Before folders are restored, so reopened projects are recognised too. + workspace.init(editorManager, addedFolder); + + // A mistake in a file in .acode would otherwise just have no effect, with + // nothing to say why. Only the file that changed is reported. + const reportProblems = + (files) => + ({ name, settings, extensions }) => { + const problems = { + "settings.json": settings.problems, + "extensions.json": extensions.problems, + }; + for (const file of files) { + if (!problems[file].length) continue; + toast( + `${name || "Project"}: .acode/${file} - ${problems[file][0]}`, + 5000, + ); + return; + } + }; + workspace.on("open", reportProblems(["settings.json", "extensions.json"])); + workspace.on("settings", reportProblems(["settings.json"])); + workspace.on("extensions", reportProblems(["extensions.json"])); + + // Suggests the plugins a project recommends. Never installs anything. + projectExtensions.init(); + acode.setLoadingMessage("Loading folders..."); if (Array.isArray(folders)) { for (const folder of folders) { diff --git a/tests/unit/pluginFileRestoration.test.js b/tests/unit/pluginFileRestoration.test.js index ed12bdd3c0..8d3b1385f2 100644 --- a/tests/unit/pluginFileRestoration.test.js +++ b/tests/unit/pluginFileRestoration.test.js @@ -142,6 +142,7 @@ function setup() { "./editorFile": {}, "./openFolder": {}, "./settings": settings, + "./workspace": { resolveSettings: (values) => values }, }, { editorManager: manager, strings: {} }, ); diff --git a/tests/unit/projectExtensions.test.js b/tests/unit/projectExtensions.test.js new file mode 100644 index 0000000000..b2ae69e978 --- /dev/null +++ b/tests/unit/projectExtensions.test.js @@ -0,0 +1,450 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import english from "../../src/lang/en-us.json"; + +const PLUGIN_DIR = "file:///data/plugins"; +const PROJECT = "file:///sdcard/projects/app"; + +// One fake file system serves both the workspace scan (.acode files) and the +// "is this plugin installed" check, which is just `exists()` on a plugin folder. +const fake = vi.hoisted(() => { + const state = { + files: new Map(), + dirs: new Set(), + installed: new Set(), + existsFailing: new Set(), + existsCalls: [], + existsHolds: new Map(), + }; + state.reset = () => { + state.files.clear(); + state.dirs.clear(); + state.installed.clear(); + state.existsFailing.clear(); + state.existsCalls.length = 0; + state.existsHolds.clear(); + }; + state.fsOperation = (...parts) => { + const url = parts.length > 1 ? parts.join("/") : parts[0]; + return { + async exists() { + state.existsCalls.push(url); + await state.existsHolds.get(url); + if (state.existsFailing.has(url)) throw new Error("exists failed"); + return state.installed.has(url); + }, + async stat() { + if (state.dirs.has(url)) + return { isDirectory: true, isFile: false, size: 0 }; + if (state.files.has(url)) { + return { + isDirectory: false, + isFile: true, + size: state.files.get(url).length, + }; + } + throw new Error("ENOENT"); + }, + async readFile() { + return state.files.get(url); + }, + }; + }; + return state; +}); + +const ui = vi.hoisted(() => ({ + pushNotification: vi.fn(), + select: vi.fn(), + openPlugin: vi.fn(), + settings: { value: { recommendExtensions: true } }, +})); + +vi.mock("fileSystem", () => ({ default: fake.fsOperation })); +vi.mock("lib/notificationManager", () => ({ + default: { pushNotification: ui.pushNotification }, +})); +vi.mock("lib/settings", () => ({ default: ui.settings })); +vi.mock("dialogs/select", () => ({ default: ui.select })); +vi.mock("pages/plugin", () => ({ default: ui.openPlugin })); + +import projectExtensions, { findMissing, review } from "lib/projectExtensions"; +import workspace from "lib/workspace"; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); +const settle = async () => { + for (let i = 0; i < 6; i++) await flush(); +}; + +function createManager() { + const handlers = new Map(); + return { + on(event, fn) { + if (!handlers.has(event)) handlers.set(event, new Set()); + handlers.get(event).add(fn); + }, + off(event, fn) { + handlers.get(event)?.delete(fn); + }, + emit(event, ...args) { + for (const fn of [...(handlers.get(event) ?? [])]) fn(...args); + }, + }; +} + +describe("project plugin recommendations", () => { + let manager; + let stopWorkspace; + let stopRecommender; + + const EXTENSIONS = `${PROJECT}/.acode/extensions.json`; + const write = (value) => + fake.files.set( + EXTENSIONS, + typeof value === "string" ? value : JSON.stringify(value), + ); + const recommend = (...ids) => write({ recommendations: ids }); + const installed = (...ids) => + ids.forEach((id) => fake.installed.add(`${PLUGIN_DIR}/${id}`)); + const openProject = async (name = "app") => { + manager.emit("add-folder", { url: PROJECT, name }); + await settle(); + }; + const notification = () => ui.pushNotification.mock.calls[0]?.[0]; + + beforeEach(() => { + fake.reset(); + ui.pushNotification.mockReset(); + ui.select.mockReset(); + ui.openPlugin.mockReset(); + ui.settings.value = { recommendExtensions: true }; + globalThis.PLUGIN_DIR = PLUGIN_DIR; + globalThis.strings = { ...english }; + fake.dirs.add(`${PROJECT}/.acode`); + + manager = createManager(); + stopWorkspace = workspace.init(manager); + stopRecommender = projectExtensions.init(); + }); + + afterEach(() => { + stopRecommender(); + stopWorkspace(); + delete globalThis.PLUGIN_DIR; + delete globalThis.strings; + }); + + it("uses strings that exist in the English language file", () => { + for (const key of [ + "project extensions title", + "project extensions message", + "review recommendations", + "plugins", + ]) { + expect(english[key], key).toBeTruthy(); + } + }); + + describe("announcing", () => { + it("tells the user which project recommends which missing plugins", async () => { + recommend("a.one", "b.two"); + await openProject("my-app"); + + expect(ui.pushNotification).toHaveBeenCalledTimes(1); + const n = notification(); + expect(n.title).toBe("Plugins recommended by my-app"); + expect(n.message).toBe("my-app recommends: a.one, b.two"); + expect(n.icon).toBe("extension"); + expect(n.type).toBe("info"); + expect(n.actions).toHaveLength(1); + expect(n.actions[0].text).toBe("Review"); + }); + + it("names the project's url when it has no name", async () => { + recommend("a.one"); + await openProject(null); + expect(notification().message).toContain(PROJECT); + }); + + it("leaves out plugins that are already installed", async () => { + recommend("a.one", "b.two"); + installed("a.one"); + await openProject(); + + expect(notification().message).toBe("app recommends: b.two"); + }); + + it("stays quiet when everything is installed", async () => { + recommend("a.one", "b.two"); + installed("a.one", "b.two"); + await openProject(); + + expect(ui.pushNotification).not.toHaveBeenCalled(); + }); + + it("stays quiet when the project recommends nothing", async () => { + recommend(); + await openProject(); + expect(ui.pushNotification).not.toHaveBeenCalled(); + expect(fake.existsCalls).toEqual([]); + }); + + it("stays quiet for a project without extensions.json", async () => { + await openProject(); + expect(ui.pushNotification).not.toHaveBeenCalled(); + }); + + it("respects the user's choice to turn recommendations off, and checks nothing", async () => { + ui.settings.value.recommendExtensions = false; + recommend("a.one"); + await openProject(); + + expect(ui.pushNotification).not.toHaveBeenCalled(); + expect(fake.existsCalls).toEqual([]); + }); + + it("treats an unset preference as on, like the existing language recommendations", async () => { + delete ui.settings.value.recommendExtensions; + recommend("a.one"); + await openProject(); + expect(ui.pushNotification).toHaveBeenCalledTimes(1); + }); + + it("does not nag about a plugin it cannot check", async () => { + recommend("a.one", "b.two"); + fake.existsFailing.add(`${PLUGIN_DIR}/a.one`); + await openProject(); + + expect(notification().message).toBe("app recommends: b.two"); + }); + }); + + describe("not repeating itself", () => { + it("announces the same advice only once per session", async () => { + recommend("a.one"); + await openProject(); + await workspace.refresh(PROJECT); + await settle(); + manager.emit("save-file", { uri: EXTENSIONS }); + await settle(); + + expect(ui.pushNotification).toHaveBeenCalledTimes(1); + }); + + it("does not repeat when only the file's mistakes change", async () => { + write({ recommendations: ["a.one", "bad/id"] }); + await openProject(); + write({ recommendations: ["a.one", "other/bad"] }); + manager.emit("save-file", { uri: EXTENSIONS }); + await settle(); + + expect(ui.pushNotification).toHaveBeenCalledTimes(1); + }); + + it("announces again when the project recommends something new", async () => { + recommend("a.one"); + await openProject(); + + recommend("a.one", "b.two"); + manager.emit("save-file", { uri: EXTENSIONS }); + await settle(); + + expect(ui.pushNotification).toHaveBeenCalledTimes(2); + expect(ui.pushNotification.mock.calls[1][0].message).toBe( + "app recommends: a.one, b.two", + ); + }); + + it("forgets what it announced once stopped and restarted", async () => { + recommend("a.one"); + await openProject(); + stopRecommender(); + stopRecommender = projectExtensions.init(); + await workspace.refresh(PROJECT); + manager.emit("remove-folder", { url: PROJECT }); + await openProject(); + + expect(ui.pushNotification).toHaveBeenCalledTimes(2); + }); + + it("stops reacting once stopped", async () => { + stopRecommender(); + recommend("a.one"); + await openProject(); + expect(ui.pushNotification).not.toHaveBeenCalled(); + }); + }); + + describe("hostile input", () => { + it("never lets a path- or URL-like id near the file system", async () => { + recommend( + "https://evil.example/p.zip", + "../../x", + "file:///data/data/com.foxdebug.acode", + "a/b", + "ok.id", + ); + await openProject(); + + expect(fake.existsCalls).toEqual([`${PLUGIN_DIR}/ok.id`]); + expect(notification().message).toBe("app recommends: ok.id"); + }); + + it("checks ids again before building a path, in case a caller skips the parser", async () => { + const missing = await findMissing([ + "https://evil.example/x", + "../x", + "a/b", + "fine.id", + "", + null, + ]); + expect(fake.existsCalls).toEqual([`${PLUGIN_DIR}/fine.id`]); + expect(missing).toEqual(["fine.id"]); + }); + + it("says nothing when every id is bad", async () => { + recommend("https://evil.example/p.zip", "../x"); + await openProject(); + expect(ui.pushNotification).not.toHaveBeenCalled(); + expect(fake.existsCalls).toEqual([]); + }); + }); + + describe("races", () => { + it("says nothing if the project closed while plugins were being checked", async () => { + recommend("a.one"); + const release = (() => { + let r; + fake.existsHolds.set( + `${PLUGIN_DIR}/a.one`, + new Promise((resolve) => { + r = resolve; + }), + ); + return r; + })(); + + manager.emit("add-folder", { url: PROJECT, name: "app" }); + await settle(); + manager.emit("remove-folder", { url: PROJECT }); + release(); + await settle(); + + expect(ui.pushNotification).not.toHaveBeenCalled(); + }); + + it("says nothing if the list changed while plugins were being checked", async () => { + recommend("a.one"); + let release; + fake.existsHolds.set( + `${PLUGIN_DIR}/a.one`, + new Promise((resolve) => { + release = resolve; + }), + ); + + manager.emit("add-folder", { url: PROJECT, name: "app" }); + await settle(); + // The user removes the recommendation before the first check finishes. + recommend(); + manager.emit("save-file", { uri: EXTENSIONS }); + await settle(); + release(); + await settle(); + + expect(ui.pushNotification).not.toHaveBeenCalled(); + }); + }); + + describe("reviewing a recommendation", () => { + it("opens the plugin's page, without installing it", async () => { + recommend("a.one"); + await openProject(); + + notification().action(); + await settle(); + + expect(ui.openPlugin).toHaveBeenCalledTimes(1); + // Exactly the id: an `install` flag would install the plugin on arrival. + expect(ui.openPlugin.mock.calls[0]).toEqual([{ id: "a.one" }]); + expect(ui.select).not.toHaveBeenCalled(); + }); + + it("does the same from the Review button", async () => { + recommend("a.one"); + await openProject(); + + notification().actions[0].action(); + await settle(); + + expect(ui.openPlugin.mock.calls[0]).toEqual([{ id: "a.one" }]); + }); + + it("lets the user pick one when there are several", async () => { + recommend("a.one", "b.two", "c.three"); + await openProject(); + ui.select.mockResolvedValue("b.two"); + + notification().action(); + await settle(); + + expect(ui.select).toHaveBeenCalledWith("Plugins", [ + "a.one", + "b.two", + "c.three", + ]); + expect(ui.openPlugin.mock.calls).toEqual([[{ id: "b.two" }]]); + }); + + it("opens nothing when the user cancels the choice", async () => { + recommend("a.one", "b.two"); + await openProject(); + ui.select.mockResolvedValue(null); + + notification().action(); + await settle(); + + expect(ui.openPlugin).not.toHaveBeenCalled(); + }); + + it("refuses to open an id that is not a plain plugin id", async () => { + ui.select.mockResolvedValue("https://evil.example/p.zip"); + await review(["a.one", "b.two"]); + expect(ui.openPlugin).not.toHaveBeenCalled(); + + await review(["../x"]); + expect(ui.openPlugin).not.toHaveBeenCalled(); + }); + + it("survives a failure while opening the page", async () => { + const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); + recommend("a.one"); + await openProject(); + ui.openPlugin.mockImplementation(() => { + throw new Error("page failed"); + }); + + expect(() => notification().action()).not.toThrow(); + await settle(); + expect(warn).toHaveBeenCalled(); + warn.mockRestore(); + }); + }); + + it("never installs anything", async () => { + recommend("a.one", "b.two"); + await openProject(); + ui.select.mockResolvedValue("a.one"); + + notification().action(); + await settle(); + + // The page was opened, so the check below is not vacuous... + expect(ui.openPlugin).toHaveBeenCalledTimes(1); + // ...and it was given the id and nothing else: an `install` flag would + // install the plugin the moment the page opens. + expect(Object.keys(ui.openPlugin.mock.calls[0][0])).toEqual(["id"]); + // The plugin folders were only ever looked at, never created. + expect(fake.installed.size).toBe(0); + }); +}); diff --git a/tests/unit/saveFileProjectSettings.test.js b/tests/unit/saveFileProjectSettings.test.js new file mode 100644 index 0000000000..2c1a9e6a88 --- /dev/null +++ b/tests/unit/saveFileProjectSettings.test.js @@ -0,0 +1,233 @@ +import { Text } from "@codemirror/state"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { loadSourceModule } from "../helpers/loadSourceModule"; + +// The workspace module scans a fake `.acode` folder; saveFile itself is the real source. +const fakeFs = vi.hoisted(() => { + const files = new Map(); + const dirs = new Set(); + return { + files, + dirs, + fsOperation: (url) => ({ + async stat() { + if (dirs.has(url)) return { isDirectory: true, isFile: false, size: 0 }; + if (files.has(url)) { + return { + isDirectory: false, + isFile: true, + size: files.get(url).length, + }; + } + throw new Error("ENOENT"); + }, + async readFile() { + return files.get(url); + }, + }), + }; +}); +vi.mock("fileSystem", () => ({ default: fakeFs.fsOperation })); + +import workspace from "lib/workspace"; + +const PROJECT = "file:///sdcard/projects/app"; +const OUTSIDE = "file:///sdcard/notes"; +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function createManager() { + const handlers = new Map(); + return { + TIMEOUT_VALUE: 0, + activeFile: null, + getFile: () => null, + emit: vi.fn(), + onupdate: vi.fn(), + on(event, fn) { + if (!handlers.has(event)) handlers.set(event, new Set()); + handlers.get(event).add(fn); + }, + off(event, fn) { + handlers.get(event)?.delete(fn); + }, + fire(event, ...args) { + for (const fn of [...(handlers.get(event) ?? [])]) fn(...args); + }, + }; +} + +function setup(globalSettings) { + const manager = createManager(); + const exec = vi.fn(); + const userSettings = { ...globalSettings }; + + const { default: saveFile } = loadSourceModule( + "src/lib/saveFile.js", + { + fileSystem: { + __esModule: true, + default: () => ({ + readFile: async () => "content", + writeFile: vi.fn(async () => true), + stat: async () => ({}), + }), + hasProvider: () => true, + }, + "@codemirror/state": { Text }, + "cm/editorUtils": { getDocText: (doc) => doc.toString() }, + "components/toast": vi.fn(), + "dialogs/confirm": vi.fn(), + "dialogs/prompt": vi.fn(), + "dialogs/select": {}, + "lib/recents": { select: vi.fn(), addFolder: vi.fn(), addFile: vi.fn() }, + "pages/fileBrowser": {}, + "utils/helpers": { + getStatMtime: () => null, + error: vi.fn(), + fixFilename: (name) => name, + }, + "utils/Url": { join: (...parts) => parts.join("/") }, + "./config": {}, + "./editorFile": {}, + "./openFolder": {}, + "./settings": { value: userSettings }, + // The real workspace module, not a stub. + "./workspace": { __esModule: true, default: workspace }, + }, + { editorManager: manager, strings: {}, acode: { exec } }, + ); + + const createFile = (uri) => { + const file = { + uri, + filename: "index.js", + encoding: "utf8", + loaded: true, + loading: false, + readOnly: false, + markChanged: true, + tab: { querySelector: () => ({ textContent: "" }) }, + session: { doc: Text.of(["content"]) }, + markSaved: vi.fn(), + }; + manager.activeFile = file; + return file; + }; + + return { manager, exec, userSettings, createFile, saveFile }; +} + +describe("format on save per project", () => { + let ctx; + let stop; + + const openProject = async (settingsText) => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + if (settingsText !== undefined) { + fakeFs.files.set(`${PROJECT}/.acode/settings.json`, settingsText); + } + ctx.manager.fire("add-folder", { url: PROJECT, name: "app" }); + await flush(); + }; + + beforeEach(() => { + fakeFs.files.clear(); + fakeFs.dirs.clear(); + }); + + afterEach(() => stop?.()); + + const start = (globalSettings) => { + ctx = setup(globalSettings); + stop = workspace.init(ctx.manager); + }; + + it("formats files in a project that turns it on, though the user has it off", async () => { + start({ formatOnSave: false }); + await openProject('{"formatOnSave": true}'); + + const file = ctx.createFile(`${PROJECT}/src/index.js`); + expect(await ctx.saveFile(file)).toBe(true); + + expect(ctx.exec).toHaveBeenCalledTimes(1); + expect(ctx.exec).toHaveBeenCalledWith("format", false); + expect(file.markChanged).toBe(true); + }); + + it("does not format files in a project that turns it off, though the user has it on", async () => { + start({ formatOnSave: true }); + await openProject('{"formatOnSave": false}'); + + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + + expect(ctx.exec).not.toHaveBeenCalled(); + }); + + it("leaves files outside the project to the user's own setting", async () => { + start({ formatOnSave: false }); + await openProject('{"formatOnSave": true}'); + + await ctx.saveFile(ctx.createFile(`${OUTSIDE}/todo.js`)); + expect(ctx.exec).not.toHaveBeenCalled(); + + ctx.userSettings.formatOnSave = true; + await ctx.saveFile(ctx.createFile(`${OUTSIDE}/todo.js`)); + expect(ctx.exec).toHaveBeenCalledTimes(1); + }); + + it("uses the user's setting when the project does not mention it", async () => { + start({ formatOnSave: true }); + await openProject('{"tabSize": 4}'); + + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + + expect(ctx.exec).toHaveBeenCalledTimes(1); + }); + + it("uses the user's setting when the project's value is invalid", async () => { + start({ formatOnSave: false }); + await openProject('{"formatOnSave": "yes"}'); + + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + + expect(ctx.exec).not.toHaveBeenCalled(); + }); + + it("only formats the file being shown, even in a project that turns it on", async () => { + start({ formatOnSave: false }); + await openProject('{"formatOnSave": true}'); + + const background = ctx.createFile(`${PROJECT}/src/other.js`); + ctx.createFile(`${PROJECT}/src/index.js`); // now the active file + + await ctx.saveFile(background); + + expect(ctx.exec).not.toHaveBeenCalled(); + }); + + it("never changes the user's own settings", async () => { + start({ formatOnSave: false, tabSize: 2 }); + await openProject('{"formatOnSave": true, "tabSize": 8}'); + + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + + expect(ctx.userSettings).toEqual({ formatOnSave: false, tabSize: 2 }); + }); + + it("follows an edit to settings.json without reopening the project", async () => { + start({ formatOnSave: false }); + await openProject('{"formatOnSave": false}'); + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + expect(ctx.exec).not.toHaveBeenCalled(); + + fakeFs.files.set( + `${PROJECT}/.acode/settings.json`, + '{"formatOnSave": true}', + ); + ctx.manager.fire("save-file", { uri: `${PROJECT}/.acode/settings.json` }); + await flush(); + await ctx.saveFile(ctx.createFile(`${PROJECT}/src/index.js`)); + + expect(ctx.exec).toHaveBeenCalledTimes(1); + }); +}); diff --git a/tests/unit/workspace.test.js b/tests/unit/workspace.test.js new file mode 100644 index 0000000000..3e15906d0d --- /dev/null +++ b/tests/unit/workspace.test.js @@ -0,0 +1,971 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +// A tiny in-memory file system. `hold` lets a test keep a stat() pending to +// exercise the window between "folder opened" and "scan finished". +const fakeFs = vi.hoisted(() => { + const state = { + dirs: new Set(), + files: new Map(), + failing: new Set(), + unsupported: new Set(), + holds: new Map(), + readHolds: new Map(), + stats: [], + reads: [], + }; + + state.reset = () => { + state.dirs.clear(); + state.files.clear(); + state.failing.clear(); + state.unsupported.clear(); + state.holds.clear(); + state.readHolds.clear(); + state.stats.length = 0; + state.reads.length = 0; + }; + + state.hold = (url) => { + let release; + const gate = new Promise((resolve) => { + release = resolve; + }); + state.holds.set(url, gate); + return release; + }; + + // Delays the answer of readFile() *after* it has captured the content, like a + // slow network that already read the file but has not delivered it yet. + state.holdRead = (url) => { + let release; + state.readHolds.set( + url, + new Promise((resolve) => { + release = resolve; + }), + ); + return release; + }; + + state.fsOperation = (url) => { + if (state.unsupported.has(url)) return undefined; + return { + async stat() { + state.stats.push(url); + await state.holds.get(url); + if (state.failing.has(url)) throw new Error("stat failed"); + if (state.dirs.has(url)) { + return { url, isDirectory: true, isFile: false, size: 0 }; + } + if (state.files.has(url)) { + const content = state.files.get(url); + return { + url, + isDirectory: false, + isFile: true, + size: typeof content === "number" ? content : content.length, + }; + } + throw new Error("ENOENT"); + }, + async readFile() { + state.reads.push(url); + if (!state.files.has(url)) throw new Error("ENOENT"); + const content = state.files.get(url); + await state.readHolds.get(url); + return content; + }, + }; + }; + + return state; +}); + +vi.mock("fileSystem", () => ({ default: fakeFs.fsOperation })); + +import workspace, { detectConfigDir, WORKSPACE_DIR } from "lib/workspace"; + +const flush = () => new Promise((resolve) => setTimeout(resolve, 0)); + +function createManager() { + const handlers = new Map(); + return { + on(event, fn) { + if (!handlers.has(event)) handlers.set(event, new Set()); + handlers.get(event).add(fn); + }, + off(event, fn) { + handlers.get(event)?.delete(fn); + }, + emit(event, ...args) { + for (const fn of [...(handlers.get(event) ?? [])]) fn(...args); + }, + count(event) { + return handlers.get(event)?.size ?? 0; + }, + }; +} + +const PROJECT = "file:///sdcard/projects/app"; +const OTHER = "file:///sdcard/projects/other"; + +describe("detectConfigDir", () => { + beforeEach(() => fakeFs.reset()); + + it("uses the .acode directory name", () => { + expect(WORKSPACE_DIR).toBe(".acode"); + }); + + it("returns the url of an existing .acode directory", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + expect(await detectConfigDir(PROJECT)).toBe(`${PROJECT}/.acode`); + }); + + it("handles a root url with a trailing slash", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + expect(await detectConfigDir(`${PROJECT}/`)).toBe(`${PROJECT}/.acode`); + }); + + it("returns null when there is no .acode", async () => { + expect(await detectConfigDir(PROJECT)).toBeNull(); + }); + + it("ignores a .acode that is a file", async () => { + fakeFs.files.set(`${PROJECT}/.acode`, ""); + expect(await detectConfigDir(PROJECT)).toBeNull(); + }); + + it("returns null instead of throwing when the file system fails", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + fakeFs.failing.add(`${PROJECT}/.acode`); + expect(await detectConfigDir(PROJECT)).toBeNull(); + }); + + it("returns null when no file system supports the url", async () => { + fakeFs.unsupported.add(`${PROJECT}/.acode`); + expect(await detectConfigDir(PROJECT)).toBeNull(); + }); +}); + +describe("workspace tracking", () => { + let manager; + let stop; + let opened; + let closed; + let subscriptions; + + // Listeners live on the module, so track them and remove them after each test. + const listen = (event, fn) => { + workspace.on(event, fn); + subscriptions.push([event, fn]); + return fn; + }; + + beforeEach(() => { + fakeFs.reset(); + manager = createManager(); + opened = []; + closed = []; + subscriptions = []; + listen("open", (ws) => opened.push(ws)); + listen("close", (ws) => closed.push(ws)); + stop = workspace.init(manager); + }); + + afterEach(() => { + stop(); + for (const [event, fn] of subscriptions) workspace.off(event, fn); + }); + + const openFolder = (url, name = "app") => + manager.emit("add-folder", { url, name }); + const closeFolder = (url, name = "app") => + manager.emit("remove-folder", { url, name }); + + it("recognises a project that has a .acode directory", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT, "app"); + await flush(); + + const ws = workspace.get(PROJECT); + expect(ws).toMatchObject({ + url: PROJECT, + name: "app", + configUrl: `${PROJECT}/.acode`, + }); + expect(ws.settings.values).toEqual({}); + expect(ws.settings.problems).toEqual([]); + expect(workspace.list()).toEqual([ws]); + expect(opened).toEqual([ws]); + }); + + it("leaves projects without .acode alone", async () => { + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT)).toBeNull(); + expect(workspace.list()).toEqual([]); + expect(opened).toEqual([]); + }); + + it("forgets a workspace when its folder is closed", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + const ws = workspace.get(PROJECT); + + closeFolder(PROJECT); + + expect(workspace.get(PROJECT)).toBeNull(); + expect(workspace.list()).toEqual([]); + expect(closed).toEqual([ws]); + }); + + it("ignores the removal of a folder that was never tracked", () => { + closeFolder(OTHER); + expect(closed).toEqual([]); + }); + + it("does not register a workspace whose folder closed during the scan", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + const release = fakeFs.hold(`${PROJECT}/.acode`); + + openFolder(PROJECT); + closeFolder(PROJECT); + release(); + await flush(); + + expect(workspace.list()).toEqual([]); + expect(opened).toEqual([]); + expect(closed).toEqual([]); + }); + + it("reports a reopened folder once, even if the first scan finishes last", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + const release = fakeFs.hold(`${PROJECT}/.acode`); + + openFolder(PROJECT); + closeFolder(PROJECT); + openFolder(PROJECT); + release(); + await flush(); + + expect(workspace.list()).toHaveLength(1); + expect(opened).toHaveLength(1); + }); + + it("scans folders that were already open when tracking started", async () => { + stop(); + fakeFs.dirs.add(`${PROJECT}/.acode`); + + stop = workspace.init(manager, [ + { url: PROJECT, title: "app" }, + { url: OTHER, title: "other" }, + ]); + await flush(); + + expect(workspace.list().map((ws) => ws.url)).toEqual([PROJECT]); + expect(workspace.get(PROJECT).name).toBe("app"); + }); + + it("keeps projects isolated from each other", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + openFolder(OTHER, "other"); + await flush(); + + expect(workspace.find(`${PROJECT}/src/index.js`)?.url).toBe(PROJECT); + expect(workspace.find(`${OTHER}/src/index.js`)).toBeNull(); + }); + + describe("find", () => { + it("matches the root itself and anything below it", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + expect(workspace.find(PROJECT)?.url).toBe(PROJECT); + expect(workspace.find(`${PROJECT}/`)?.url).toBe(PROJECT); + expect(workspace.find(`${PROJECT}/a/b/c.js`)?.url).toBe(PROJECT); + }); + + it("does not match a sibling that shares the same prefix", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + expect(workspace.find(`${PROJECT}-two/file.js`)).toBeNull(); + }); + + it("prefers the innermost workspace for nested roots", async () => { + const inner = `${PROJECT}/packages/ui`; + fakeFs.dirs.add(`${PROJECT}/.acode`); + fakeFs.dirs.add(`${inner}/.acode`); + openFolder(PROJECT); + openFolder(inner, "ui"); + await flush(); + + expect(workspace.find(`${inner}/button.js`)?.url).toBe(inner); + expect(workspace.find(`${PROJECT}/README.md`)?.url).toBe(PROJECT); + }); + + it("returns null for an empty url", () => { + expect(workspace.find("")).toBeNull(); + expect(workspace.find(undefined)).toBeNull(); + }); + }); + + describe("refresh", () => { + it("picks up a .acode directory created after the folder was opened", async () => { + openFolder(PROJECT); + await flush(); + expect(workspace.get(PROJECT)).toBeNull(); + + fakeFs.dirs.add(`${PROJECT}/.acode`); + const ws = await workspace.refresh(PROJECT); + + expect(ws?.configUrl).toBe(`${PROJECT}/.acode`); + expect(opened).toHaveLength(1); + }); + + it("drops a workspace whose .acode directory was deleted", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + const ws = workspace.get(PROJECT); + + fakeFs.dirs.delete(`${PROJECT}/.acode`); + expect(await workspace.refresh(PROJECT)).toBeNull(); + + expect(workspace.list()).toEqual([]); + expect(closed).toEqual([ws]); + }); + + it("does not announce an unchanged workspace again", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + await workspace.refresh(PROJECT); + + expect(opened).toHaveLength(1); + }); + + it("does nothing for a folder that is not open", async () => { + fakeFs.dirs.add(`${OTHER}/.acode`); + expect(await workspace.refresh(OTHER)).toBeNull(); + expect(workspace.list()).toEqual([]); + }); + }); + + describe("listeners", () => { + it("keeps notifying others when a listener throws", async () => { + const error = vi.spyOn(console, "error").mockImplementation(() => {}); + const after = vi.fn(); + listen("open", () => { + throw new Error("boom"); + }); + listen("open", after); + + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + expect(after).toHaveBeenCalledTimes(1); + expect(workspace.get(PROJECT)).not.toBeNull(); + error.mockRestore(); + }); + + it("stops notifying a listener that was removed", async () => { + const listener = vi.fn(); + listen("open", listener); + workspace.off("open", listener); + + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + expect(listener).not.toHaveBeenCalled(); + }); + + it("ignores unknown event names", () => { + expect(() => workspace.on("nope", () => {})).not.toThrow(); + expect(() => workspace.off("nope", () => {})).not.toThrow(); + }); + }); + + describe("init", () => { + it("stops tracking and forgets everything when disposed", async () => { + fakeFs.dirs.add(`${PROJECT}/.acode`); + openFolder(PROJECT); + await flush(); + + stop(); + + expect(workspace.list()).toEqual([]); + expect(manager.count("add-folder")).toBe(0); + expect(manager.count("remove-folder")).toBe(0); + expect(manager.count("save-file")).toBe(0); + + openFolder(OTHER); + await flush(); + expect(workspace.list()).toEqual([]); + }); + + it("does not subscribe twice when called again", () => { + stop = workspace.init(manager); + expect(manager.count("add-folder")).toBe(1); + expect(manager.count("remove-folder")).toBe(1); + expect(manager.count("save-file")).toBe(1); + }); + }); +}); + +describe("project settings", () => { + let manager; + let stop; + let events; + let subscriptions; + + const SETTINGS = `${PROJECT}/.acode/settings.json`; + const listen = (event, fn) => { + workspace.on(event, fn); + subscriptions.push([event, fn]); + }; + const openFolder = (url, name = "app") => + manager.emit("add-folder", { url, name }); + const save = (uri) => manager.emit("save-file", { uri }); + const writeSettings = (text) => fakeFs.files.set(SETTINGS, text); + + beforeEach(() => { + fakeFs.reset(); + manager = createManager(); + events = []; + subscriptions = []; + for (const event of ["open", "settings", "close"]) { + listen(event, (ws) => events.push([event, ws])); + } + fakeFs.dirs.add(`${PROJECT}/.acode`); + stop = workspace.init(manager); + }); + + afterEach(() => { + stop(); + for (const [event, fn] of subscriptions) workspace.off(event, fn); + }); + + it("reads settings.json when the project opens", async () => { + writeSettings('{"tabSize": 4, "softTab": false}'); + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT).settings.values).toEqual({ + tabSize: 4, + softTab: false, + }); + expect(events.map(([name]) => name)).toEqual(["open"]); + // Listeners must see the settings already loaded. + expect(events[0][1].settings.values.tabSize).toBe(4); + }); + + it("is a workspace even without a settings.json", async () => { + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT)).not.toBeNull(); + expect(workspace.get(PROJECT).settings.values).toEqual({}); + expect(fakeFs.reads).toEqual([]); + }); + + it("keeps the workspace and reports a problem for an invalid file", async () => { + writeSettings("{ tabSize: 4 "); + openFolder(PROJECT); + await flush(); + + const { settings } = workspace.get(PROJECT); + expect(settings.values).toEqual({}); + expect(settings.problems).toHaveLength(1); + }); + + it("does not read a settings.json that is too large", async () => { + fakeFs.files.set(SETTINGS, 5 * 1024 * 1024); + openFolder(PROJECT); + await flush(); + + expect(fakeFs.reads).toEqual([]); + const { settings } = workspace.get(PROJECT); + expect(settings.values).toEqual({}); + expect(settings.problems[0]).toMatch(/larger than/i); + }); + + it("ignores a settings.json that is a directory", async () => { + fakeFs.dirs.add(SETTINGS); + openFolder(PROJECT); + await flush(); + + expect(fakeFs.reads).toEqual([]); + expect(workspace.get(PROJECT).settings.problems).toEqual([]); + }); + + it("treats an unreadable settings.json as no overrides", async () => { + writeSettings('{"tabSize": 4}'); + fakeFs.failing.add(SETTINGS); + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT)).not.toBeNull(); + expect(workspace.get(PROJECT).settings.values).toEqual({}); + }); + + describe("getSettings", () => { + it("returns the overrides for files inside the project", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + expect(workspace.getSettings(`${PROJECT}/src/a.js`)).toEqual({ + tabSize: 4, + }); + expect(workspace.getSettings(PROJECT)).toEqual({ tabSize: 4 }); + }); + + it("returns nothing for files outside every project", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + expect(workspace.getSettings(`${OTHER}/a.js`)).toEqual({}); + expect(workspace.getSettings(`${PROJECT}-two/a.js`)).toEqual({}); + expect(workspace.getSettings("")).toEqual({}); + expect(workspace.getSettings(undefined)).toEqual({}); + }); + + it("returns nothing for an open folder that has no .acode", async () => { + openFolder(OTHER, "other"); + await flush(); + expect(workspace.getSettings(`${OTHER}/a.js`)).toEqual({}); + }); + + it("lets the innermost project decide, without inheriting from the outer one", async () => { + const inner = `${PROJECT}/packages/ui`; + writeSettings('{"tabSize": 4, "softTab": false}'); + fakeFs.dirs.add(`${inner}/.acode`); + fakeFs.files.set(`${inner}/.acode/settings.json`, '{"tabSize": 2}'); + const bare = `${PROJECT}/packages/bare`; + fakeFs.dirs.add(`${bare}/.acode`); + + openFolder(PROJECT); + openFolder(inner, "ui"); + openFolder(bare, "bare"); + await flush(); + + expect(workspace.getSettings(`${inner}/x.js`)).toEqual({ tabSize: 2 }); + // A nested project is its own project: no softTab from the outer one. + expect(workspace.getSettings(`${bare}/x.js`)).toEqual({}); + expect(workspace.getSettings(`${PROJECT}/README.md`)).toEqual({ + tabSize: 4, + softTab: false, + }); + }); + + it("returns frozen objects, so callers cannot alter a project's settings", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + expect(Object.isFrozen(workspace.getSettings(PROJECT))).toBe(true); + expect(Object.isFrozen(workspace.getSettings(`${OTHER}/a.js`))).toBe( + true, + ); + }); + + describe("resolveSettings", () => { + const user = Object.freeze({ + tabSize: 2, + softTab: true, + fontSize: "12px", + }); + + it("puts the project's overrides on top of the user's settings", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + expect(workspace.resolveSettings(user, `${PROJECT}/a.js`)).toEqual({ + tabSize: 4, + softTab: true, + fontSize: "12px", + }); + }); + + it("never modifies the user's settings", async () => { + writeSettings('{"tabSize": 4, "softTab": false}'); + openFolder(PROJECT); + await flush(); + + const mine = { tabSize: 2, softTab: true }; + const merged = workspace.resolveSettings(mine, `${PROJECT}/a.js`); + + expect(merged).not.toBe(mine); + expect(mine).toEqual({ tabSize: 2, softTab: true }); + }); + + it("returns the very same object when there is nothing to override", async () => { + writeSettings("{}"); + openFolder(PROJECT); + openFolder(OTHER, "other"); + await flush(); + + expect(workspace.resolveSettings(user, `${PROJECT}/a.js`)).toBe(user); + expect(workspace.resolveSettings(user, `${OTHER}/a.js`)).toBe(user); + expect(workspace.resolveSettings(user, undefined)).toBe(user); + }); + + it("does not let another project's settings leak across", async () => { + writeSettings('{"tabSize": 8}'); + openFolder(PROJECT); + openFolder(OTHER, "other"); + await flush(); + + expect(workspace.resolveSettings(user, `${OTHER}/a.js`).tabSize).toBe( + 2, + ); + }); + }); + + it("stops applying once the project closes", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + manager.emit("remove-folder", { url: PROJECT }); + + expect(workspace.getSettings(`${PROJECT}/src/a.js`)).toEqual({}); + }); + }); + + describe("saving files in .acode", () => { + it("applies an edit to settings.json right away", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + writeSettings('{"tabSize": 8}'); + save(SETTINGS); + await flush(); + + expect(workspace.getSettings(PROJECT)).toEqual({ tabSize: 8 }); + expect(events.map(([name]) => name)).toEqual(["settings"]); + expect(events[0][1].settings.values.tabSize).toBe(8); + }); + + it("reports a problem when a save introduces a mistake, and recovers when fixed", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + + writeSettings('{"tabSize": 99}'); + save(SETTINGS); + await flush(); + expect(workspace.get(PROJECT).settings.problems).toHaveLength(1); + expect(workspace.getSettings(PROJECT)).toEqual({}); + + writeSettings('{"tabSize": 3}'); + save(SETTINGS); + await flush(); + expect(workspace.get(PROJECT).settings.problems).toEqual([]); + expect(workspace.getSettings(PROJECT)).toEqual({ tabSize: 3 }); + }); + + it("does not announce a save that changes nothing", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + writeSettings('{ "tabSize": 4 }'); + save(SETTINGS); + await flush(); + + expect(events).toEqual([]); + }); + + it("picks up a .acode created after the folder was opened", async () => { + fakeFs.dirs.clear(); + openFolder(PROJECT); + await flush(); + expect(workspace.get(PROJECT)).toBeNull(); + + fakeFs.dirs.add(`${PROJECT}/.acode`); + writeSettings('{"softTab": false}'); + save(SETTINGS); + await flush(); + + expect(workspace.getSettings(PROJECT)).toEqual({ softTab: false }); + expect(events.map(([name]) => name)).toEqual(["open"]); + }); + + it("drops the settings when settings.json is deleted", async () => { + writeSettings('{"tabSize": 4}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.delete(SETTINGS); + await workspace.refresh(PROJECT); + + expect(workspace.getSettings(PROJECT)).toEqual({}); + expect(events.map(([name]) => name)).toEqual(["settings"]); + }); + + it("does not touch the file system for files outside .acode", async () => { + openFolder(PROJECT); + await flush(); + fakeFs.stats.length = 0; + + save(`${PROJECT}/src/index.js`); + save(`${PROJECT}/.acodeignore`); + save(`${OTHER}/.acode/settings.json`); + save(undefined); + await flush(); + + expect(fakeFs.stats).toEqual([]); + }); + }); + + describe("races", () => { + it("does not register a workspace whose folder closed while settings were loading", async () => { + writeSettings('{"tabSize": 4}'); + const release = fakeFs.hold(SETTINGS); + + openFolder(PROJECT); + await flush(); + manager.emit("remove-folder", { url: PROJECT }); + release(); + await flush(); + + expect(workspace.list()).toEqual([]); + expect(workspace.getSettings(PROJECT)).toEqual({}); + expect(events).toEqual([]); + }); + + it("lets the newest scan win when an older one delivers late", async () => { + writeSettings('{"tabSize": 2}'); + openFolder(PROJECT); + await flush(); + + // The older scan has already read tabSize 3 but its answer is slow. + writeSettings('{"tabSize": 3}'); + const deliverOld = fakeFs.holdRead(SETTINGS); + save(SETTINGS); + await flush(); + + // A newer save is read and applied in the meantime. + fakeFs.readHolds.delete(SETTINGS); + writeSettings('{"tabSize": 6}'); + save(SETTINGS); + await flush(); + expect(workspace.getSettings(PROJECT)).toEqual({ tabSize: 6 }); + + deliverOld(); + await flush(); + + expect(workspace.getSettings(PROJECT)).toEqual({ tabSize: 6 }); + }); + }); +}); + +describe("plugin recommendations", () => { + let manager; + let stop; + let events; + let subscriptions; + + const EXTENSIONS = `${PROJECT}/.acode/extensions.json`; + const SETTINGS = `${PROJECT}/.acode/settings.json`; + const listen = (event, fn) => { + workspace.on(event, fn); + subscriptions.push([event, fn]); + }; + const openFolder = (url, name = "app") => + manager.emit("add-folder", { url, name }); + const save = (uri) => manager.emit("save-file", { uri }); + const names = () => events.map(([name]) => name); + + beforeEach(() => { + fakeFs.reset(); + manager = createManager(); + events = []; + subscriptions = []; + for (const event of ["open", "settings", "extensions", "close"]) { + listen(event, (ws) => events.push([event, ws])); + } + fakeFs.dirs.add(`${PROJECT}/.acode`); + stop = workspace.init(manager); + }); + + afterEach(() => { + stop(); + for (const [event, fn] of subscriptions) workspace.off(event, fn); + }); + + it("reads extensions.json when the project opens, before announcing it", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a.b", "c.d"]}'); + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT).extensions.recommendations).toEqual([ + "a.b", + "c.d", + ]); + expect(names()).toEqual(["open"]); + expect(events[0][1].extensions.recommendations).toEqual(["a.b", "c.d"]); + }); + + it("has no recommendations without an extensions.json", async () => { + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT).extensions.recommendations).toEqual([]); + expect(workspace.get(PROJECT).extensions.problems).toEqual([]); + }); + + it("reports a problem for an invalid file and keeps the workspace", async () => { + fakeFs.files.set(EXTENSIONS, "{ nope"); + openFolder(PROJECT); + await flush(); + + const { extensions } = workspace.get(PROJECT); + expect(extensions.recommendations).toEqual([]); + expect(extensions.problems).toHaveLength(1); + }); + + it("does not read a file that is too large", async () => { + fakeFs.files.set(EXTENSIONS, 5 * 1024 * 1024); + openFolder(PROJECT); + await flush(); + + expect(fakeFs.reads).not.toContain(EXTENSIONS); + expect(workspace.get(PROJECT).extensions.problems[0]).toMatch( + /larger than/i, + ); + }); + + it("ignores an extensions.json that is a directory", async () => { + fakeFs.dirs.add(EXTENSIONS); + openFolder(PROJECT); + await flush(); + + expect(fakeFs.reads).not.toContain(EXTENSIONS); + expect(workspace.get(PROJECT).extensions.problems).toEqual([]); + }); + + it("never hands out a hostile id", async () => { + fakeFs.files.set( + EXTENSIONS, + JSON.stringify({ + recommendations: ["https://evil.example/p.zip", "../x", "good.id"], + }), + ); + openFolder(PROJECT); + await flush(); + + expect(workspace.get(PROJECT).extensions.recommendations).toEqual([ + "good.id", + ]); + }); + + it("announces a changed list as 'extensions', and only that", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a", "b"]}'); + save(EXTENSIONS); + await flush(); + + expect(names()).toEqual(["extensions"]); + expect(events[0][1].extensions.recommendations).toEqual(["a", "b"]); + }); + + it("announces changed settings as 'settings', and only that", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.set(SETTINGS, '{"tabSize": 4}'); + save(SETTINGS); + await flush(); + + expect(names()).toEqual(["settings"]); + }); + + it("announces both when one scan changes both", async () => { + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.set(SETTINGS, '{"tabSize": 4}'); + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + await workspace.refresh(PROJECT); + + expect(names().sort()).toEqual(["extensions", "settings"]); + // Both listeners see the same, complete state. + expect(events[0][1]).toBe(events[1][1]); + }); + + it("does not announce a save that changes nothing", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.set(EXTENSIONS, '{ "recommendations": [ "a" ] }'); + save(EXTENSIONS); + await flush(); + + expect(events).toEqual([]); + }); + + it("keeps settings and recommendations independent of each other", async () => { + fakeFs.files.set(SETTINGS, '{"tabSize": 4}'); + fakeFs.files.set(EXTENSIONS, "{ broken"); + openFolder(PROJECT); + await flush(); + + const ws = workspace.get(PROJECT); + expect(ws.settings.values).toEqual({ tabSize: 4 }); + expect(ws.settings.problems).toEqual([]); + expect(ws.extensions.problems).toHaveLength(1); + }); + + it("does not register a workspace whose folder closed while extensions were loading", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + const release = fakeFs.hold(EXTENSIONS); + + openFolder(PROJECT); + await flush(); + manager.emit("remove-folder", { url: PROJECT }); + release(); + await flush(); + + expect(workspace.list()).toEqual([]); + expect(events).toEqual([]); + }); + + it("drops recommendations when extensions.json is deleted", async () => { + fakeFs.files.set(EXTENSIONS, '{"recommendations": ["a"]}'); + openFolder(PROJECT); + await flush(); + events.length = 0; + + fakeFs.files.delete(EXTENSIONS); + await workspace.refresh(PROJECT); + + expect(workspace.get(PROJECT).extensions.recommendations).toEqual([]); + expect(names()).toEqual(["extensions"]); + }); +}); diff --git a/tests/unit/workspaceExtensions.test.js b/tests/unit/workspaceExtensions.test.js new file mode 100644 index 0000000000..bd46e534b8 --- /dev/null +++ b/tests/unit/workspaceExtensions.test.js @@ -0,0 +1,293 @@ +import { + EXTENSIONS_FILE, + isPluginId, + MAX_EXTENSIONS_FILE_SIZE, + MAX_RECOMMENDATIONS, + NO_RECOMMENDATIONS, + parseExtensionRecommendations, + sameRecommendations, + unusableRecommendations, +} from "lib/workspaceExtensions"; +import { describe, expect, it } from "vitest"; + +const parse = (value) => parseExtensionRecommendations(JSON.stringify(value)); + +describe("constants", () => { + it("reads from extensions.json", () => { + expect(EXTENSIONS_FILE).toBe("extensions.json"); + expect(MAX_EXTENSIONS_FILE_SIZE).toBeGreaterThan(0); + }); +}); + +describe("isPluginId", () => { + it.each([ + "acode.plugin.extra_syntax_highlights", + "a", + "A1", + "x.y-z_w", + "com.example.plugin-2", + "a".repeat(100), + ])("accepts %s", (id) => { + expect(isPluginId(id)).toBe(true); + }); + + // An id reaches Url.join(PLUGIN_DIR, id) and installPlugin(), which treats + // anything that looks like a URL as a place to install from. + it.each([ + "https://evil.example/plugin.zip", + "http://evil.example/p", + "file:///data/data/com.foxdebug.acode/x", + "content://com.android.externalstorage.documents/x", + "javascript:alert(1)", + "../../etc/passwd", + "..", + ".", + "a/b", + "a\\b", + "/abs", + "a:b", + "a b", + " a", + "a ", + "a\n", + "a\u0000b", + ".hidden", + "-leading-dash", + "_leading_underscore", + "é", + "a%2Fb", + "a?b=c", + "a#b", + "", + "a".repeat(101), + ])("rejects %j", (id) => { + expect(isPluginId(id)).toBe(false); + }); + + it.each([ + null, + undefined, + 1, + true, + {}, + [], + ["a"], + ])("rejects the non-string %j", (value) => { + expect(isPluginId(value)).toBe(false); + }); +}); + +describe("parseExtensionRecommendations", () => { + it("accepts a list of plugin ids", () => { + const result = parse({ recommendations: ["a.b", "c-d"] }); + expect(result.recommendations).toEqual(["a.b", "c-d"]); + expect(result.problems).toEqual([]); + }); + + it.each([ + ["", "empty"], + [" \n", "blank"], + [undefined, "undefined"], + [null, "null"], + [7, "a number"], + ])("treats %j (%s) as no recommendations, without a problem", (input) => { + expect(parseExtensionRecommendations(input)).toBe(NO_RECOMMENDATIONS); + }); + + it("treats an object without the key as no recommendations", () => { + expect(parse({})).toBe(NO_RECOMMENDATIONS); + expect(parse({ somethingElse: ["a"] })).toBe(NO_RECOMMENDATIONS); + }); + + it("treats an empty list as no recommendations", () => { + const result = parse({ recommendations: [] }); + expect(result.recommendations).toEqual([]); + expect(result.problems).toEqual([]); + }); + + it("reports invalid JSON instead of throwing", () => { + const result = parseExtensionRecommendations('{"recommendations": ['); + expect(result.recommendations).toEqual([]); + expect(result.problems).toHaveLength(1); + expect(result.problems[0]).toMatch(/not valid json/i); + }); + + it.each([ + "[]", + '["a"]', + "42", + '"a"', + "true", + ])("rejects %s because it is not an object", (text) => { + const result = parseExtensionRecommendations(text); + expect(result.recommendations).toEqual([]); + expect(result.problems).toEqual(["Expected a JSON object"]); + }); + + it.each([ + "acode.plugin.x", + { 0: "a" }, + 42, + true, + null, + ])("rejects a recommendations value that is not a list: %j", (value) => { + const result = parse({ recommendations: value }); + expect(result.recommendations).toEqual([]); + expect(result.problems).toEqual([ + '"recommendations" must be a list of plugin ids', + ]); + }); + + it("keeps the valid ids when others are bad", () => { + const result = parse({ + recommendations: [ + "good.one", + "https://evil.example/x.zip", + "good.two", + 5, + ], + }); + expect(result.recommendations).toEqual(["good.one", "good.two"]); + expect(result.problems).toEqual([ + '"https://evil.example/x.zip" is not a valid plugin id', + "A number entry is not a valid plugin id", + ]); + }); + + it("never lets a path- or URL-like id through", () => { + const hostile = [ + "https://evil.example/p.zip", + "file:///x", + "content://x/y", + "../../x", + "a/b", + "a:b", + ]; + const result = parse({ recommendations: hostile }); + expect(result.recommendations).toEqual([]); + expect(result.problems).toHaveLength(hostile.length); + }); + + it("removes duplicates quietly", () => { + const result = parse({ recommendations: ["a", "b", "a", "b", "a"] }); + expect(result.recommendations).toEqual(["a", "b"]); + expect(result.problems).toEqual([]); + }); + + it("treats ids that differ only in case as different, as the file system might", () => { + expect(parse({ recommendations: ["Abc", "abc"] }).recommendations).toEqual([ + "Abc", + "abc", + ]); + }); + + it("uses only the first MAX_RECOMMENDATIONS and says so", () => { + const ids = Array.from( + { length: MAX_RECOMMENDATIONS + 5 }, + (_, i) => `p${i}`, + ); + const result = parse({ recommendations: ids }); + expect(result.recommendations).toEqual(ids.slice(0, MAX_RECOMMENDATIONS)); + expect(result.problems).toEqual([ + `Only the first ${MAX_RECOMMENDATIONS} plugins are used`, + ]); + }); + + it("does not count duplicates or bad entries against the limit", () => { + const ids = [ + ...Array.from({ length: MAX_RECOMMENDATIONS }, (_, i) => `p${i}`), + "p0", + ]; + const result = parse({ recommendations: ids }); + expect(result.recommendations).toHaveLength(MAX_RECOMMENDATIONS); + expect(result.problems).toEqual([]); + }); + + it("shortens a huge bad entry in its message", () => { + const result = parse({ recommendations: ["x/".repeat(5000)] }); + expect(result.problems).toHaveLength(1); + expect(result.problems[0].length).toBeLessThan(80); + }); + + describe("hostile input", () => { + it("ignores a __proto__ key and pollutes nothing", () => { + const result = parseExtensionRecommendations( + '{"__proto__": {"recommendations": ["evil"], "polluted": true}}', + ); + expect(result).toBe(NO_RECOMMENDATIONS); + expect({}.polluted).toBeUndefined(); + expect({}.recommendations).toBeUndefined(); + }); + + it("does not read an inherited recommendations property", () => { + // Only an own property named "recommendations" counts. + const result = parseExtensionRecommendations('{"constructor": 1}'); + expect(result).toBe(NO_RECOMMENDATIONS); + }); + + it("rejects __proto__ as an id, since ids must start with a letter or digit", () => { + const result = parse({ recommendations: ["__proto__", "constructor"] }); + // "constructor" is a plain, harmless id; "__proto__" is not a valid one. + expect(result.recommendations).toEqual(["constructor"]); + expect(result.problems).toEqual(['"__proto__" is not a valid plugin id']); + }); + }); + + it("returns frozen results that callers cannot alter", () => { + const result = parse({ recommendations: ["a"] }); + expect(Object.isFrozen(result)).toBe(true); + expect(Object.isFrozen(result.recommendations)).toBe(true); + expect(Object.isFrozen(result.problems)).toBe(true); + expect(() => { + "use strict"; + result.recommendations.push("b"); + }).toThrow(); + }); + + it("shares one frozen empty result", () => { + expect(Object.isFrozen(NO_RECOMMENDATIONS)).toBe(true); + expect(Object.isFrozen(NO_RECOMMENDATIONS.recommendations)).toBe(true); + }); +}); + +describe("unusableRecommendations", () => { + it("carries the problem and no recommendations", () => { + const result = unusableRecommendations("too big"); + expect(result.recommendations).toEqual([]); + expect(result.problems).toEqual(["too big"]); + expect(Object.isFrozen(result)).toBe(true); + }); +}); + +describe("sameRecommendations", () => { + it("compares ids and problems", () => { + const a = parse({ recommendations: ["a", "b"] }); + expect(sameRecommendations(a, parse({ recommendations: ["a", "b"] }))).toBe( + true, + ); + expect(sameRecommendations(a, parse({ recommendations: ["b", "a"] }))).toBe( + false, + ); + expect(sameRecommendations(a, NO_RECOMMENDATIONS)).toBe(false); + }); + + it("notices a newly appearing problem", () => { + expect( + sameRecommendations( + NO_RECOMMENDATIONS, + parse({ recommendations: ["a/b"] }), + ), + ).toBe(false); + }); + + it("ignores whitespace and unknown keys, which change nothing", () => { + expect( + sameRecommendations( + parseExtensionRecommendations('{"recommendations":["a"]}'), + parseExtensionRecommendations( + '{ "recommendations": [ "a" ], "other": 1 }', + ), + ), + ).toBe(true); + }); +}); diff --git a/tests/unit/workspaceSettings.test.js b/tests/unit/workspaceSettings.test.js new file mode 100644 index 0000000000..d8435c316e --- /dev/null +++ b/tests/unit/workspaceSettings.test.js @@ -0,0 +1,257 @@ +import { + MAX_SETTINGS_SIZE, + NO_PROJECT_SETTINGS, + PROJECT_SETTING_KEYS, + parseProjectSettings, + SETTINGS_FILE, + sameProjectSettings, + unusableProjectSettings, +} from "lib/workspaceSettings"; +import { describe, expect, it } from "vitest"; + +describe("project settings allowlist", () => { + it("only offers settings every reader of which can ask for the project's value", () => { + expect([...PROJECT_SETTING_KEYS].sort()).toEqual([ + "formatOnSave", + "softTab", + "tabSize", + ]); + }); + + it("reads from settings.json", () => { + expect(SETTINGS_FILE).toBe("settings.json"); + expect(MAX_SETTINGS_SIZE).toBeGreaterThan(0); + }); +}); + +describe("parseProjectSettings", () => { + it("accepts valid overrides", () => { + const result = parseProjectSettings('{"tabSize": 4, "softTab": false}'); + expect(result.values).toEqual({ tabSize: 4, softTab: false }); + expect(result.problems).toEqual([]); + expect(result.ignored).toEqual([]); + }); + + it.each([ + ["", "empty"], + [" \n\t", "blank"], + [undefined, "undefined"], + [null, "null"], + [42, "a number"], + ])("treats %j (%s) as no settings, without a problem", (input) => { + expect(parseProjectSettings(input)).toBe(NO_PROJECT_SETTINGS); + }); + + it("treats an empty object as no overrides", () => { + const result = parseProjectSettings("{}"); + expect(result.values).toEqual({}); + expect(result.problems).toEqual([]); + }); + + it("reports invalid JSON instead of throwing", () => { + const result = parseProjectSettings('{"tabSize": 4,}'); + expect(result.values).toEqual({}); + expect(result.problems).toHaveLength(1); + expect(result.problems[0]).toMatch(/not valid json/i); + }); + + it.each([ + "[]", + "[1, 2]", + "42", + '"text"', + "true", + "null", + ])("rejects %s because it is not an object", (text) => { + const result = parseProjectSettings(text); + expect(result.values).toEqual({}); + expect(result.problems).toEqual(["Expected a JSON object"]); + }); + + describe("tabSize", () => { + it.each([1, 2, 4, 8])("accepts %i", (tabSize) => { + expect(parseProjectSettings(JSON.stringify({ tabSize })).values).toEqual({ + tabSize, + }); + }); + + it.each([ + 0, + 9, + -2, + 2.5, + "4", + null, + true, + [4], + { n: 4 }, + 1e9, + ])("rejects %j", (tabSize) => { + const result = parseProjectSettings(JSON.stringify({ tabSize })); + expect(result.values).toEqual({}); + expect(result.problems).toEqual([ + '"tabSize" must be a whole number from 1 to 8', + ]); + }); + }); + + describe("formatOnSave", () => { + it.each([true, false])("accepts %s", (formatOnSave) => { + expect( + parseProjectSettings(JSON.stringify({ formatOnSave })).values, + ).toEqual({ formatOnSave }); + }); + + it.each(["true", "yes", 1, 0, null, []])("rejects %j", (formatOnSave) => { + const result = parseProjectSettings(JSON.stringify({ formatOnSave })); + expect(result.values).toEqual({}); + expect(result.problems).toEqual(['"formatOnSave" must be true or false']); + }); + }); + + describe("settings that are not offered yet", () => { + // Read from many places, or by the canvas renderer's own path, so a project + // value would disagree with the rest of Acode. See workspaceSettings.js. + it.each([ + "textWrap", + "linenumbers", + "showSpaces", + "indentGuides", + "relativeLineNumbers", + ])("ignores %s", (key) => { + const result = parseProjectSettings(JSON.stringify({ [key]: true })); + expect(result.values).toEqual({}); + expect(result.ignored).toEqual([key]); + }); + }); + + describe("softTab", () => { + it.each([true, false])("accepts %s", (softTab) => { + expect(parseProjectSettings(JSON.stringify({ softTab })).values).toEqual({ + softTab, + }); + }); + + it.each(["true", 1, 0, null, []])("rejects %j", (softTab) => { + const result = parseProjectSettings(JSON.stringify({ softTab })); + expect(result.values).toEqual({}); + expect(result.problems).toEqual(['"softTab" must be true or false']); + }); + }); + + it("keeps the valid values when another value is wrong", () => { + const result = parseProjectSettings('{"tabSize": 99, "softTab": false}'); + expect(result.values).toEqual({ softTab: false }); + expect(result.problems).toEqual([ + '"tabSize" must be a whole number from 1 to 8', + ]); + }); + + it("ignores unknown settings without calling them problems", () => { + const result = parseProjectSettings( + '{"tabSize": 2, "fontSize": "30px", "someFutureSetting": 1}', + ); + expect(result.values).toEqual({ tabSize: 2 }); + expect(result.problems).toEqual([]); + expect(result.ignored).toEqual(["fontSize", "someFutureSetting"]); + }); + + it.each([ + "formatter", + "prettier", + "excludeFolders", + "lsp", + "pluginsDisabled", + "serverPort", + "host", + "console", + ])("never honours the sensitive global setting %s", (key) => { + const result = parseProjectSettings(JSON.stringify({ [key]: {} })); + expect(result.values).toEqual({}); + expect(result.ignored).toEqual([key]); + }); + + describe("hostile input", () => { + it("does not pollute prototypes through __proto__", () => { + const result = parseProjectSettings( + '{"__proto__": {"tabSize": 3, "polluted": true}, "tabSize": 4}', + ); + + expect(result.values).toEqual({ tabSize: 4 }); + expect({}.polluted).toBeUndefined(); + expect(Object.prototype.tabSize).toBeUndefined(); + expect(result.ignored).toEqual(["__proto__"]); + }); + + it("does not treat inherited names as settings", () => { + const result = parseProjectSettings( + '{"constructor": 1, "toString": 2, "hasOwnProperty": 3}', + ); + expect(result.values).toEqual({}); + expect(result.problems).toEqual([]); + }); + + it("does not take values from the prototype chain", () => { + // A key that exists only on Object.prototype must not satisfy the schema. + const result = parseProjectSettings('{"valueOf": 4}'); + expect(result.values).toEqual({}); + }); + }); + + it("returns frozen results that cannot be altered by callers", () => { + const result = parseProjectSettings('{"tabSize": 4}'); + expect(Object.isFrozen(result)).toBe(true); + expect(Object.isFrozen(result.values)).toBe(true); + expect(Object.isFrozen(result.problems)).toBe(true); + expect(() => { + "use strict"; + result.values.tabSize = 8; + }).toThrow(); + expect(result.values.tabSize).toBe(4); + }); + + it("shares one frozen empty result", () => { + expect(Object.isFrozen(NO_PROJECT_SETTINGS)).toBe(true); + expect(Object.isFrozen(NO_PROJECT_SETTINGS.values)).toBe(true); + }); +}); + +describe("unusableProjectSettings", () => { + it("carries the problem and no values", () => { + const result = unusableProjectSettings("too big"); + expect(result.values).toEqual({}); + expect(result.problems).toEqual(["too big"]); + expect(Object.isFrozen(result)).toBe(true); + }); +}); + +describe("sameProjectSettings", () => { + it("compares values and problems", () => { + const a = parseProjectSettings('{"tabSize": 4}'); + expect(sameProjectSettings(a, parseProjectSettings('{"tabSize": 4}'))).toBe( + true, + ); + expect(sameProjectSettings(a, parseProjectSettings('{"tabSize": 2}'))).toBe( + false, + ); + expect(sameProjectSettings(a, NO_PROJECT_SETTINGS)).toBe(false); + }); + + it("notices a newly appearing problem", () => { + expect( + sameProjectSettings( + NO_PROJECT_SETTINGS, + parseProjectSettings('{"tabSize": 99}'), + ), + ).toBe(false); + }); + + it("ignores whitespace and unknown settings, which change nothing", () => { + expect( + sameProjectSettings( + parseProjectSettings('{"tabSize":4}'), + parseProjectSettings('{ "tabSize": 4, "other": 1 }'), + ), + ).toBe(true); + }); +}); From 32064f77184061d4c270650231eea86cb24907b4 Mon Sep 17 00:00:00 2001 From: codewithchai0605 Date: Tue, 17 Nov 2026 10:03:30 +0530 Subject: [PATCH 2/5] Refactor projectExtensions to open Extensions sidebar with plugin id search --- src/lib/editorManager.js | 4 +-- src/lib/projectExtensions.js | 5 ++-- tests/unit/projectExtensions.test.js | 39 ++++++++++++---------------- 3 files changed, 21 insertions(+), 27 deletions(-) diff --git a/src/lib/editorManager.js b/src/lib/editorManager.js index a5a05f12fb..d7133e903f 100644 --- a/src/lib/editorManager.js +++ b/src/lib/editorManager.js @@ -117,12 +117,12 @@ import EditorFile, { AUTO_SAVE } from "./editorFile"; import openFile from "./openFile"; import { addedFolder } from "./openFolder"; import appSettings from "./settings"; -import workspace from "./workspace"; -import { PROJECT_SETTING_KEYS } from "./workspaceSettings"; import { getSystemConfiguration, HARDKEYBOARDHIDDEN_NO, } from "./systemConfiguration"; +import workspace from "./workspace"; +import { PROJECT_SETTING_KEYS } from "./workspaceSettings"; /** * Represents an editor manager that handles multiple files and provides various editor configurations and event listeners. diff --git a/src/lib/projectExtensions.js b/src/lib/projectExtensions.js index 45d4647a37..40da233049 100644 --- a/src/lib/projectExtensions.js +++ b/src/lib/projectExtensions.js @@ -43,8 +43,7 @@ export async function findMissing(ids) { } /** - * Open the registry page of a recommended plugin. The page shows its details - * and an install button; nothing is installed unless the user presses it. + * Open the Extensions sidebar filtered to a recommended plugin. * @param {readonly string[]} ids The recommended plugins that are missing. */ export async function review(ids) { @@ -56,7 +55,7 @@ export async function review(ids) { if (!isPluginId(id)) return; const { openWithSearch } = await import("sidebarApps/extensions"); - openWithSearch(`id:${id}`); + await openWithSearch(`id:${id}`); } /** diff --git a/tests/unit/projectExtensions.test.js b/tests/unit/projectExtensions.test.js index b2ae69e978..f2a820e005 100644 --- a/tests/unit/projectExtensions.test.js +++ b/tests/unit/projectExtensions.test.js @@ -55,7 +55,7 @@ const fake = vi.hoisted(() => { const ui = vi.hoisted(() => ({ pushNotification: vi.fn(), select: vi.fn(), - openPlugin: vi.fn(), + openWithSearch: vi.fn(), settings: { value: { recommendExtensions: true } }, })); @@ -65,7 +65,9 @@ vi.mock("lib/notificationManager", () => ({ })); vi.mock("lib/settings", () => ({ default: ui.settings })); vi.mock("dialogs/select", () => ({ default: ui.select })); -vi.mock("pages/plugin", () => ({ default: ui.openPlugin })); +vi.mock("sidebarApps/extensions", () => ({ + openWithSearch: ui.openWithSearch, +})); import projectExtensions, { findMissing, review } from "lib/projectExtensions"; import workspace from "lib/workspace"; @@ -115,7 +117,7 @@ describe("project plugin recommendations", () => { fake.reset(); ui.pushNotification.mockReset(); ui.select.mockReset(); - ui.openPlugin.mockReset(); + ui.openWithSearch.mockReset(); ui.settings.value = { recommendExtensions: true }; globalThis.PLUGIN_DIR = PLUGIN_DIR; globalThis.strings = { ...english }; @@ -357,27 +359,26 @@ describe("project plugin recommendations", () => { }); describe("reviewing a recommendation", () => { - it("opens the plugin's page, without installing it", async () => { + it("opens the Extensions sidebar with the plugin id search", async () => { recommend("a.one"); await openProject(); notification().action(); await settle(); - expect(ui.openPlugin).toHaveBeenCalledTimes(1); - // Exactly the id: an `install` flag would install the plugin on arrival. - expect(ui.openPlugin.mock.calls[0]).toEqual([{ id: "a.one" }]); + expect(ui.openWithSearch).toHaveBeenCalledTimes(1); + expect(ui.openWithSearch).toHaveBeenCalledWith("id:a.one"); expect(ui.select).not.toHaveBeenCalled(); }); - it("does the same from the Review button", async () => { + it("opens the same search from the Review button", async () => { recommend("a.one"); await openProject(); notification().actions[0].action(); await settle(); - expect(ui.openPlugin.mock.calls[0]).toEqual([{ id: "a.one" }]); + expect(ui.openWithSearch).toHaveBeenCalledWith("id:a.one"); }); it("lets the user pick one when there are several", async () => { @@ -393,7 +394,7 @@ describe("project plugin recommendations", () => { "b.two", "c.three", ]); - expect(ui.openPlugin.mock.calls).toEqual([[{ id: "b.two" }]]); + expect(ui.openWithSearch).toHaveBeenCalledWith("id:b.two"); }); it("opens nothing when the user cancels the choice", async () => { @@ -404,25 +405,23 @@ describe("project plugin recommendations", () => { notification().action(); await settle(); - expect(ui.openPlugin).not.toHaveBeenCalled(); + expect(ui.openWithSearch).not.toHaveBeenCalled(); }); it("refuses to open an id that is not a plain plugin id", async () => { ui.select.mockResolvedValue("https://evil.example/p.zip"); await review(["a.one", "b.two"]); - expect(ui.openPlugin).not.toHaveBeenCalled(); + expect(ui.openWithSearch).not.toHaveBeenCalled(); await review(["../x"]); - expect(ui.openPlugin).not.toHaveBeenCalled(); + expect(ui.openWithSearch).not.toHaveBeenCalled(); }); - it("survives a failure while opening the page", async () => { + it("survives a failure while opening the sidebar search", async () => { const warn = vi.spyOn(console, "warn").mockImplementation(() => {}); recommend("a.one"); await openProject(); - ui.openPlugin.mockImplementation(() => { - throw new Error("page failed"); - }); + ui.openWithSearch.mockRejectedValue(new Error("sidebar failed")); expect(() => notification().action()).not.toThrow(); await settle(); @@ -439,11 +438,7 @@ describe("project plugin recommendations", () => { notification().action(); await settle(); - // The page was opened, so the check below is not vacuous... - expect(ui.openPlugin).toHaveBeenCalledTimes(1); - // ...and it was given the id and nothing else: an `install` flag would - // install the plugin the moment the page opens. - expect(Object.keys(ui.openPlugin.mock.calls[0][0])).toEqual(["id"]); + expect(ui.openWithSearch).toHaveBeenCalledWith("id:a.one"); // The plugin folders were only ever looked at, never created. expect(fake.installed.size).toBe(0); }); From 7222b90132c80279fea171fa86736434587d5c00 Mon Sep 17 00:00:00 2001 From: codewithchai0605 Date: Tue, 17 Nov 2026 11:06:08 +0530 Subject: [PATCH 3/5] Implement workspace.pathsChanged to handle file and directory changes in the workspace --- src/lib/editorManager.js | 8 ++- src/lib/openFolder.js | 10 ++++ src/lib/workspace.js | 34 +++++++++++ tests/unit/workspace.test.js | 112 +++++++++++++++++++++++++++++++++++ 4 files changed, 163 insertions(+), 1 deletion(-) diff --git a/src/lib/editorManager.js b/src/lib/editorManager.js index d7133e903f..99ca879120 100644 --- a/src/lib/editorManager.js +++ b/src/lib/editorManager.js @@ -3207,7 +3207,13 @@ async function EditorManager($header, $body) { markLanguageReady(file, languageSignature, true); } editor.setState(state); - applyCurrentEditorOptions(file, { targetEditor: editor }); + // The state above was built from the global settings, and the options + // signature cannot tell: it still matches the one stored from the state + // this replaces. Force the file's own (project) options onto the new state. + applyCurrentEditorOptions(file, { + targetEditor: editor, + forceOptions: true, + }); // Restore selection from previous state if available try { diff --git a/src/lib/openFolder.js b/src/lib/openFolder.js index 90b69856b6..0c575f0a45 100644 --- a/src/lib/openFolder.js +++ b/src/lib/openFolder.js @@ -25,6 +25,7 @@ import { loadFileBrowser } from "./lazyImports"; import openFile from "./openFile"; import recents from "./recents"; import appSettings from "./settings"; +import workspace from "./workspace"; const isTermuxSafUri = (value = "") => value.startsWith("content://com.termux.documents/tree/"); @@ -323,6 +324,8 @@ async function runRootAction($root, action, $button) { $button?.classList.add("spinning"); try { await getLoadedFileTree($root.$title)?.refresh(); + // Also picks up changes made outside the app (e.g. from a terminal). + await workspace.refresh(url); } finally { $button?.classList.remove("spinning"); } @@ -746,6 +749,7 @@ function execOperation(type, action, url, $target, name) { helpers.updateUriOfAllActiveFiles(url, newUrl); } FileList.rename(url, newUrl); + workspace.pathsChanged(url, newUrl); await refreshRenamedEntryInOpenFolders(url, newUrl); toast(strings.success); } @@ -774,6 +778,7 @@ function execOperation(type, action, url, $target, name) { newUrl = await helpers.createFileStructure(url, newName, false); } if (!newUrl.created) return; + workspace.pathsChanged(newUrl.uri, newUrl.parentUri); if (isNestedPath) { await refreshOpenFolder(url); @@ -835,6 +840,7 @@ function execOperation(type, action, url, $target, name) { ); appendTile($target, createFileTile(sourceStats.name, insertedFile)); FileList.append(url, insertedFile); + workspace.pathsChanged(insertedFile); } catch (error) { } finally { stopLoading(); @@ -883,6 +889,7 @@ async function deleteEntry(url, type) { } FileList.remove(url); + workspace.pathsChanged(url); return true; } @@ -1091,6 +1098,9 @@ async function pasteEntry({ url: srcUrl, type: srcType }, targetUrl, action) { return null; } + // A moved or pasted entry may be, or sit inside, a project's `.acode`. + workspace.pathsChanged(newUrl, action === "cut" ? srcUrl : null); + if (action === "cut") { if (IS_FILE) { const file = editorManager.getFile(srcUrl, "uri"); diff --git a/src/lib/workspace.js b/src/lib/workspace.js index f6d3f7ff0a..137819ef06 100644 --- a/src/lib/workspace.js +++ b/src/lib/workspace.js @@ -342,6 +342,39 @@ export function list() { return [...workspaces.values()]; } +/** + * Tell the workspaces that something was created, deleted, renamed, moved or + * pasted at these urls (the old and the new url of a rename or move, both). + * Every open root whose `.acode` directory is, is inside, or is under one of + * them is checked again, so a deleted or renamed `settings.json` stops + * applying and a new one starts to. Other roots are left alone. + * @param {...string} urls + */ +export function pathsChanged(...urls) { + const changed = urls.filter(Boolean); + if (!changed.length) return; + + for (const root of roots.keys()) { + let configUrl; + try { + configUrl = Url.join(root, WORKSPACE_DIR); + } catch (error) { + continue; + } + if (!configUrl) continue; + + const affected = changed.some( + (url) => + Url.isSameOrDescendant(url, configUrl) || + Url.isSameOrDescendant(configUrl, url), + ); + if (!affected) continue; + scan(root).catch((error) => { + console.error(`Failed to scan workspace "${root}":`, error); + }); + } +} + /** * Check an open root again, e.g. after its `.acode` directory was created or * deleted. Does nothing for roots that are not open. @@ -378,6 +411,7 @@ export default { resolveSettings, list, refresh, + pathsChanged, on, off, }; diff --git a/tests/unit/workspace.test.js b/tests/unit/workspace.test.js index 3e15906d0d..003663107e 100644 --- a/tests/unit/workspace.test.js +++ b/tests/unit/workspace.test.js @@ -969,3 +969,115 @@ describe("plugin recommendations", () => { expect(names()).toEqual(["extensions"]); }); }); + +describe("pathsChanged", () => { + let manager; + let stop; + let events; + let subscriptions; + + const CONFIG = `${PROJECT}/.acode`; + const SETTINGS = `${CONFIG}/settings.json`; + const listen = (event, fn) => { + workspace.on(event, fn); + subscriptions.push([event, fn]); + }; + const names = () => events.map(([name]) => name); + + beforeEach(async () => { + fakeFs.reset(); + manager = createManager(); + events = []; + subscriptions = []; + for (const event of ["open", "settings", "close"]) { + listen(event, (ws) => events.push([event, ws])); + } + fakeFs.dirs.add(CONFIG); + fakeFs.files.set(SETTINGS, '{"tabSize": 4}'); + stop = workspace.init(manager); + manager.emit("add-folder", { url: PROJECT, name: "app" }); + await flush(); + events.length = 0; + }); + + afterEach(() => { + stop(); + for (const [event, fn] of subscriptions) workspace.off(event, fn); + }); + + it("drops the settings when settings.json is deleted", async () => { + expect(workspace.getSettings(`${PROJECT}/a.js`)).toEqual({ tabSize: 4 }); + + fakeFs.files.delete(SETTINGS); + workspace.pathsChanged(SETTINGS); + await flush(); + + expect(workspace.getSettings(`${PROJECT}/a.js`)).toEqual({}); + expect(names()).toEqual(["settings"]); + }); + + it("drops the settings when settings.json is renamed away", async () => { + const renamed = `${CONFIG}/settings.old.json`; + fakeFs.files.set(renamed, fakeFs.files.get(SETTINGS)); + fakeFs.files.delete(SETTINGS); + workspace.pathsChanged(SETTINGS, renamed); + await flush(); + + expect(workspace.getSettings(`${PROJECT}/a.js`)).toEqual({}); + }); + + it("closes the workspace when the .acode directory is deleted", async () => { + fakeFs.files.delete(SETTINGS); + fakeFs.dirs.delete(CONFIG); + workspace.pathsChanged(CONFIG); + await flush(); + + expect(workspace.get(PROJECT)).toBeNull(); + expect(names()).toEqual(["close"]); + }); + + it("notices a directory renamed to .acode", async () => { + fakeFs.reset(); + fakeFs.dirs.add(PROJECT); + manager.emit("remove-folder", { url: PROJECT }); + manager.emit("add-folder", { url: PROJECT, name: "app" }); + await flush(); + events.length = 0; + + fakeFs.dirs.add(CONFIG); + fakeFs.files.set(SETTINGS, '{"tabSize": 8}'); + workspace.pathsChanged(`${PROJECT}/config`, CONFIG); + await flush(); + + expect(workspace.getSettings(`${PROJECT}/a.js`)).toEqual({ tabSize: 8 }); + }); + + it("rescans when a folder above .acode is removed", async () => { + fakeFs.files.delete(SETTINGS); + fakeFs.dirs.delete(CONFIG); + workspace.pathsChanged(PROJECT); + await flush(); + + expect(workspace.get(PROJECT)).toBeNull(); + }); + + it("ignores changes elsewhere in the project", async () => { + fakeFs.stats.length = 0; + workspace.pathsChanged( + `${PROJECT}/src/index.js`, + `${PROJECT}/.acodeignore`, + ); + await flush(); + + expect(fakeFs.stats).toEqual([]); + expect(events).toEqual([]); + }); + + it("ignores changes in roots that are not open", async () => { + fakeFs.stats.length = 0; + workspace.pathsChanged(`${OTHER}/.acode/settings.json`); + await flush(); + + expect(fakeFs.stats).toEqual([]); + }); +}); From 2c2742c046ac62887f97aba31835e8fad4f44a73 Mon Sep 17 00:00:00 2001 From: codewithchai0605 Date: Tue, 17 Nov 2026 11:23:28 +0530 Subject: [PATCH 4/5] Fix execOperation to call workspace.pathsChanged with a single URI --- src/lib/openFolder.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/openFolder.js b/src/lib/openFolder.js index 0c575f0a45..d77f8f0672 100644 --- a/src/lib/openFolder.js +++ b/src/lib/openFolder.js @@ -778,7 +778,7 @@ function execOperation(type, action, url, $target, name) { newUrl = await helpers.createFileStructure(url, newName, false); } if (!newUrl.created) return; - workspace.pathsChanged(newUrl.uri, newUrl.parentUri); + workspace.pathsChanged(newUrl.uri); if (isNestedPath) { await refreshOpenFolder(url); From 2acc65bf30e620b7b077b9820dd845e2a48440ff Mon Sep 17 00:00:00 2001 From: codewithchai0605 Date: Wed, 18 Nov 2026 09:30:20 +0530 Subject: [PATCH 5/5] Enhance EditorManager and workspace functionality with new URL handling and tests --- src/lib/editorManager.js | 7 + src/lib/workspace.js | 55 +++++- tests/unit/projectOptionsSignature.test.js | 191 +++++++++++++++++++++ tests/unit/workspace.test.js | 132 ++++++++++++++ 4 files changed, 379 insertions(+), 6 deletions(-) create mode 100644 tests/unit/projectOptionsSignature.test.js diff --git a/src/lib/editorManager.js b/src/lib/editorManager.js index 99ca879120..d5ce4486e9 100644 --- a/src/lib/editorManager.js +++ b/src/lib/editorManager.js @@ -3638,6 +3638,13 @@ async function EditorManager($header, $body) { const file = pane.activeFile; if (!pane.editor || file?.type !== "editor") continue; applyOptions(PROJECT_SETTING_KEYS, pane.editor, file); + // That changed the state behind the signature's back, and only for + // the project's keys, so the signature saved with the file no longer + // describes it. Left alone, a project that returns to its old values + // while the file is hidden would look unchanged when the file is + // shown again, and the state would keep the values applied here. + // Forget it: showing the file then applies every option again. + file.__cmOptionsSignature = null; } } for (const event of ["open", "settings", "close"]) { diff --git a/src/lib/workspace.js b/src/lib/workspace.js index 137819ef06..bffb963bcc 100644 --- a/src/lib/workspace.js +++ b/src/lib/workspace.js @@ -1,4 +1,5 @@ import fsOperation from "fileSystem"; +import Uri from "utils/Uri"; import Url from "utils/Url"; import { EXTENSIONS_FILE, @@ -61,6 +62,42 @@ const listeners = { let stopListening = null; +/** + * Write a url in a form that can be compared with other urls of the same + * storage. A folder added through Android's storage picker has a bare tree url + * (`content://.../tree/primary%3AProjects%2Fapp`), but the files inside it are + * `::`, so as plain strings the folder is never a + * prefix of its own files. Content urls are therefore always written as + * `::`, the form openFolder compares in. Any other url, + * including a content url that is not from a documents provider, is returned + * as it is. + * @param {string} url + * @returns {string} + */ +function comparable(url) { + if (typeof url !== "string" || Url.getProtocol(url) !== "content:") { + return url; + } + try { + let { url: bare } = Url.parse(url); + if (bare.endsWith("/")) bare = bare.slice(0, -1); + const { rootUri, docId } = Uri.parse(bare); + return Uri.format(rootUri, docId); + } catch (error) { + return url; + } +} + +/** + * Whether `url` is `parent` or is inside it, whichever shape each has. + * @param {string} url + * @param {string} parent + * @returns {boolean} + */ +function isInside(url, parent) { + return Url.isSameOrDescendant(comparable(url), comparable(parent)); +} + /** * Locate the `.acode` directory of a project root. * A `.acode` that is a file, or anything that cannot be stat'ed (missing, @@ -243,7 +280,7 @@ function onSaveFile(file) { } catch (error) { continue; } - if (!configUrl || !Url.isSameOrDescendant(uri, configUrl)) continue; + if (!configUrl || !isInside(uri, configUrl)) continue; scan(root).catch((error) => { console.error(`Failed to scan workspace "${root}":`, error); }); @@ -300,10 +337,18 @@ export function get(rootUrl) { */ export function find(url) { if (!url) return null; + const target = comparable(url); let match = null; + let matchRoot = ""; for (const workspace of workspaces.values()) { - if (!Url.isSameOrDescendant(url, workspace.url)) continue; - if (!match || workspace.url.length > match.url.length) match = workspace; + // Depth is judged on the comparable form: raw urls of the same project + // can differ in length by shape alone. + const root = comparable(workspace.url); + if (!Url.isSameOrDescendant(target, root)) continue; + if (!match || root.length > matchRoot.length) { + match = workspace; + matchRoot = root; + } } return match; } @@ -364,9 +409,7 @@ export function pathsChanged(...urls) { if (!configUrl) continue; const affected = changed.some( - (url) => - Url.isSameOrDescendant(url, configUrl) || - Url.isSameOrDescendant(configUrl, url), + (url) => isInside(url, configUrl) || isInside(configUrl, url), ); if (!affected) continue; scan(root).catch((error) => { diff --git a/tests/unit/projectOptionsSignature.test.js b/tests/unit/projectOptionsSignature.test.js new file mode 100644 index 0000000000..fc121f5fe1 --- /dev/null +++ b/tests/unit/projectOptionsSignature.test.js @@ -0,0 +1,191 @@ +import { readFileSync } from "node:fs"; +import vm from "node:vm"; +import { parse } from "@babel/parser"; +import { describe, expect, it, vi } from "vitest"; + +// The functions under test are closures inside EditorManager, so they are cut +// out of the real source and run against a small fake of what they close over. +const source = readFileSync("src/lib/editorManager.js", "utf8"); +const managerBody = parse(source, { + sourceType: "module", + plugins: ["jsx"], +}).program.body.find( + (node) => + node.type === "FunctionDeclaration" && node.id.name === "EditorManager", +).body.body; + +function sourceOf(name) { + const node = managerBody.find( + (item) => item.type === "FunctionDeclaration" && item.id.name === name, + ); + if (!node) throw new Error(`EditorManager has no function ${name}`); + return source.slice(node.start, node.end); +} + +const OPTION_KEYS = ["tabSize", "softTab"]; + +function setup(globalSettings = { tabSize: 2, softTab: true }) { + const project = { values: {} }; + const appSettings = { value: { ...globalSettings, editorTheme: "one_dark" } }; + const workspace = { + // What the real workspace does: the project's overrides win. + resolveSettings: (base, uri) => + uri?.startsWith("file:///project/") + ? { ...base, ...project.values } + : base, + }; + + // Stands in for the CodeMirror view. Its state remembers which values the + // options were last applied with, which is what a user would see. + const editor = { state: { tabSize: null }, setTheme: vi.fn() }; + const pane = { editor, activeFile: null }; + const panes = [pane]; + + // The real applyOptions resolves the file's project overrides and + // reconfigures the compartments of the keys asked for (all when null). + function applyOptions(keys, target = editor, file = null) { + const values = workspace.resolveSettings( + appSettings.value, + (file || pane.activeFile).uri, + ); + for (const key of keys || OPTION_KEYS) { + if (OPTION_KEYS.includes(key)) target.state[key] = values[key]; + } + } + + const sandbox = { + appSettings, + workspace, + editor, + panes, + applyOptions: vi.fn(applyOptions), + cmOptionSpecs: [{ keys: OPTION_KEYS }], + PROJECT_SETTING_KEYS: OPTION_KEYS, + getEditorCompatibilityPane: () => null, + touchSelectionController: { onSessionChanged() {} }, + reconfigureEditorReadOnly() {}, + readOnlyCompartment: {}, + warnRecoverable() {}, + }; + const { applyCurrentEditorOptions, reapplyProjectOptions } = + vm.runInNewContext( + `${sourceOf("getEditorOptionsSignature")} + ${sourceOf("applyCurrentEditorOptions")} + ${sourceOf("reapplyProjectOptions")} + ({ applyCurrentEditorOptions, reapplyProjectOptions })`, + sandbox, + ); + + const file = { + type: "editor", + uri: "file:///project/a.js", + editable: true, + loading: false, + }; + pane.activeFile = file; + + return { + editor, + file, + project, + sandbox, + /** Show the file: what happens when its tab is activated. */ + show() { + pane.activeFile = file; + editor.state = file.session ?? editor.state; + applyCurrentEditorOptions(file, { targetEditor: editor }); + }, + /** Show another file: the editor's state is kept on the file. */ + hide() { + file.session = editor.state; + editor.state = { tabSize: null }; + pane.activeFile = null; + }, + /** The project's settings.json changed; the workspace says so. */ + projectChanges(values) { + project.values = values; + reapplyProjectOptions(); + }, + }; +} + +describe("project options and the saved options signature", () => { + it("applies the project's options when a file is first shown", () => { + const t = setup(); + t.project.values = { tabSize: 4 }; + t.show(); + expect(t.editor.state.tabSize).toBe(4); + }); + + it("applies a change to the project while its file is visible", () => { + const t = setup(); + t.project.values = { tabSize: 4 }; + t.show(); + + t.projectChanges({ tabSize: 8 }); + expect(t.editor.state.tabSize).toBe(8); + }); + + it("does not restore old indentation when the project goes back while the file is hidden", () => { + const t = setup(); + t.project.values = { tabSize: 4 }; + t.show(); + expect(t.editor.state.tabSize).toBe(4); + + // Changed while the file is visible... + t.projectChanges({ tabSize: 8 }); + expect(t.editor.state.tabSize).toBe(8); + + // ...then the user switches away, and the project returns to its + // earlier value while the file is not showing. + t.hide(); + t.project.values = { tabSize: 4 }; + + t.show(); + expect(t.editor.state.tabSize).toBe(4); + }); + + it("does not keep project indentation after the project closes while the file is hidden", () => { + // The file is showing before its project has been scanned. + const t = setup({ tabSize: 2, softTab: true }); + t.show(); + expect(t.editor.state.tabSize).toBe(2); + + // The scan finishes: the project's settings now apply to what is showing. + t.projectChanges({ tabSize: 8 }); + expect(t.editor.state.tabSize).toBe(8); + + // The user switches away and the project closes, so the user's own + // setting applies again. That is what the file was first shown with. + t.hide(); + t.project.values = {}; + + t.show(); + expect(t.editor.state.tabSize).toBe(2); + }); + + it("follows a project that changed to a new value while the file was hidden", () => { + const t = setup(); + t.project.values = { tabSize: 4 }; + t.show(); + t.projectChanges({ tabSize: 8 }); + t.hide(); + + t.project.values = { tabSize: 6 }; + + t.show(); + expect(t.editor.state.tabSize).toBe(6); + }); + + it("still skips reapplying every option when nothing changed", () => { + const t = setup(); + t.project.values = { tabSize: 4 }; + t.show(); + t.hide(); + t.sandbox.applyOptions.mockClear(); + + t.show(); + expect(t.sandbox.applyOptions).not.toHaveBeenCalled(); + expect(t.editor.state.tabSize).toBe(4); + }); +}); diff --git a/tests/unit/workspace.test.js b/tests/unit/workspace.test.js index 003663107e..3f01df42f0 100644 --- a/tests/unit/workspace.test.js +++ b/tests/unit/workspace.test.js @@ -1081,3 +1081,135 @@ describe("pathsChanged", () => { expect(fakeFs.stats).toEqual([]); }); }); + +// A folder added through Android's storage picker has a bare tree url, while +// the files inside it are `::`. Containment must not +// depend on which of the two shapes a url has. +describe("Android storage folders", () => { + let manager; + let stop; + let events; + let subscriptions; + + const TREE = + "content://com.android.externalstorage.documents/tree/primary%3AProjects%2Fapp"; + const doc = (path) => `${TREE}::primary:Projects/app/${path}`; + const CONFIG = doc(".acode"); + const SETTINGS = doc(".acode/settings.json"); + const listen = (event, fn) => { + workspace.on(event, fn); + subscriptions.push([event, fn]); + }; + const openFolder = (url, name = "app") => + manager.emit("add-folder", { url, name }); + + beforeEach(async () => { + fakeFs.reset(); + manager = createManager(); + events = []; + subscriptions = []; + for (const event of ["open", "settings", "close"]) { + listen(event, (ws) => events.push([event, ws])); + } + fakeFs.dirs.add(CONFIG); + fakeFs.files.set(SETTINGS, '{"tabSize": 4}'); + stop = workspace.init(manager); + openFolder(TREE); + await flush(); + events.length = 0; + }); + + afterEach(() => { + stop(); + for (const [event, fn] of subscriptions) workspace.off(event, fn); + }); + + it("detects the project from its bare tree url", () => { + expect(workspace.get(TREE)?.configUrl).toBe(CONFIG); + }); + + it("finds the project of a file inside it", () => { + expect(workspace.find(doc("src/index.js"))?.url).toBe(TREE); + expect(workspace.getSettings(doc("src/index.js"))).toEqual({ tabSize: 4 }); + }); + + it("overrides settings for a file inside it", () => { + const base = { tabSize: 2, softTab: true }; + expect(workspace.resolveSettings(base, doc("src/index.js"))).toEqual({ + tabSize: 4, + softTab: true, + }); + }); + + it("finds the project of its root, with or without a query", () => { + expect(workspace.find(TREE)?.url).toBe(TREE); + expect(workspace.find(`${TREE}/`)?.url).toBe(TREE); + expect(workspace.find(`${doc("a.js")}?x=1`)?.url).toBe(TREE); + }); + + it("does not mistake a folder that only shares a name prefix for a child", () => { + const copy = `${TREE}::primary:Projects/app-copy/index.js`; + const otherTree = + "content://com.android.externalstorage.documents/tree/primary%3AProjects%2Fapp2"; + expect(workspace.find(copy)).toBeNull(); + expect( + workspace.find(`${otherTree}::primary:Projects/app2/a.js`), + ).toBeNull(); + expect(workspace.find(otherTree)).toBeNull(); + }); + + it("does not throw on content urls from other providers", () => { + expect(workspace.find("content://media/external/file/12")).toBeNull(); + }); + + it("picks the innermost project when one is nested in another", async () => { + const INNER = doc("packages/web"); + fakeFs.dirs.add(`${INNER}/.acode`); + fakeFs.files.set(`${INNER}/.acode/settings.json`, '{"tabSize": 8}'); + openFolder(INNER, "web"); + await flush(); + + expect(workspace.getSettings(doc("packages/web/main.js"))).toEqual({ + tabSize: 8, + }); + expect(workspace.getSettings(doc("packages/api/main.js"))).toEqual({ + tabSize: 4, + }); + expect(workspace.getSettings(INNER)).toEqual({ tabSize: 8 }); + }); + + it("applies an edited settings.json once it is saved", async () => { + fakeFs.files.set(SETTINGS, '{"tabSize": 8}'); + manager.emit("save-file", { uri: SETTINGS }); + await flush(); + + expect(workspace.getSettings(doc("src/index.js"))).toEqual({ tabSize: 8 }); + expect(events.map(([name]) => name)).toEqual(["settings"]); + }); + + it("closes the project when its root is removed or renamed", async () => { + fakeFs.files.delete(SETTINGS); + fakeFs.dirs.delete(CONFIG); + workspace.pathsChanged(TREE); + await flush(); + + expect(workspace.get(TREE)).toBeNull(); + expect(events.map(([name]) => name)).toEqual(["close"]); + }); + + it("works for Termux folders, whose document ids are absolute paths", async () => { + const termux = + "content://com.termux.documents/tree/%2Fdata%2Fdata%2Fcom.termux%2Ffiles%2Fhome%2Fproj"; + const file = `${termux}::/data/data/com.termux/files/home/proj/src/a.js`; + fakeFs.dirs.add(`${termux}::/data/data/com.termux/files/home/proj/.acode`); + fakeFs.files.set( + `${termux}::/data/data/com.termux/files/home/proj/.acode/settings.json`, + '{"tabSize": 3}', + ); + openFolder(termux, "proj"); + await flush(); + + expect(workspace.find(file)?.url).toBe(termux); + expect(workspace.getSettings(file)).toEqual({ tabSize: 3 }); + }); +});