Skip to content

refactor: split into a VS Code-free core and fix sorting, comment and command bugs - #330

Merged
pascalre merged 18 commits into
masterfrom
feat/clean-architecture-refactor
Nov 20, 2026
Merged

pascalre merged 18 commits into
masterfrom
feat/clean-architecture-refactor

Conversation

@pascalre

Copy link
Copy Markdown
Owner

No description provided.

pascalre and others added 18 commits November 20, 2026 14:18
The sources were grouped by technical role (adapter, controller, util,
processor), which hid the actual dependency direction: the yaml logic
lived next to the VS Code glue, and helpers named `util` mixed both.

Group them by layer instead:
* src/core: the yaml sorting and formatting logic (settings, text and
  document handling, js-yaml adapter, processors)
* src/vscode: everything that talks to the VS Code API (commands,
  formatter, notifications, editor access)
* src/extension.ts stays the composition root

The tests mirror this: test/unit for the core, test/integration for
the tests that need a running VS Code, including the mocha runner.
The integration runner still runs every test file, so coverage is
unchanged. The launch configuration now points to the runner's index
instead of the test folder.

This commit only moves files and updates import paths. The core still
imports VS Code through the settings and error reporting; the next
commits remove these dependencies.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Settings imported `workspace` to read the configuration, which tied
every class of the core to a running VS Code: `new Settings()` as a
default parameter read the user's configuration, so even pure text
transformations could only be tested inside VS Code.

Settings now reads any ConfigurationReader (VS Code's
WorkspaceConfiguration satisfies the interface) and falls back to
DEFAULT_CONFIGURATION for missing values, so `new Settings()` yields
the defaults. Lists are copied, so changing one snapshot no longer
changes another one.

Reading the configuration of a document moves to readSettings() in
the vscode layer, replacing Settings.forDocument().

A test compares DEFAULT_CONFIGURATION with the defaults declared in
package.json, so both cannot drift apart. The pure getCustomSortKeywords
tests move from the integration tests to the settings unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
YamlUtil caught every error, showed it in VS Code through ErrorUtil and
returned null. The document transformer and its callers then had to
treat null as "failed, already reported", and the core depended on the
VS Code API for its error handling.

The core now throws: sortYaml(), formatYaml(), sortDocuments() and
formatDocuments() return a string or throw. The vscode layer, which
already caught the validation errors, reports them, so every error is
reported exactly once, at the boundary to the user. Sorting a directory
reports the original error instead of the generic "could not be sorted".

transformDocuments() still never returns a partial result, because the
first document that cannot be transformed aborts the whole text.

The test for #65 (formatting stays silent) is no longer meaningful for
the core, which cannot show messages at all; it now checks that an
invalid document aborts formatting.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Several classes carried generic names that said nothing about their
job (YamlUtil, SortUtil, FileUtil, ErrorUtil, Controller,
ProcessorController), and one module mixed a pure file operation with
a VS Code command.

Rename them after what they do:
* YamlUtil -> YamlSorter (core/yaml-sorter.ts)
* SortUtil -> SortOrder (core/sort-order.ts)
* FileUtil -> YamlFileFinder (core/yaml-file-finder.ts)
* ProcessorController -> ProcessorPipeline (core/processor/processor-pipeline.ts)
* ErrorUtil -> ErrorReporter (vscode/error-reporter.ts)
* Controller -> EditorCommands (vscode/editor-commands.ts)

Split controller/file-sorter: sortFile() only uses node's fs and moves
to core/file-sorter.ts, the command handler that walks a directory
stays in vscode/directory-sorter.ts.

Properties and variables follow camelCase (jsYamlAdapter, vsCodeAdapter,
errorReporter). No behavior changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Every test, including the pure text transformations, could only run
inside a downloaded VS Code under xvfb. Now that the core no longer
imports VS Code, its tests run in plain node.

* npm run test:unit runs src/test/unit with mocha in about a second;
  CI runs it before the integration tests, so a broken core fails fast
* npm run test keeps running all tests inside VS Code for coverage
* dependency-cruiser fails when the core or a unit test imports VS Code
  or the vscode layer, so the split cannot erode silently
* CI installs with npm ci from the lock file and no longer installs
  yarn and vsce, which no step used
* CONTRIBUTING describes the layers and the test commands

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Fixes several problems of the editor commands:

* "Format YAML" with a selection replaced only the selected lines with
  the formatted whole document, so the rest of the document appeared
  twice. Formatting now always replaces the whole document.
* The edits were applied to whichever editor was active when they were
  applied, not to the editor the command read from.
* The success message was shown before VS Code applied the edits, and
  also when VS Code rejected them. The commands now await the edit and
  report a rejected edit as an error.
* Running a command with a key binding while no editor was open threw
  "No texteditor is active" as an unhandled error. The command now asks
  to open a yaml file.
* ErrorReporter silently ignored thrown values that are no Error. They
  are now shown as text.

EditorCommands takes the editor as a parameter (defaulting to the
active one) and returns the applied edits asynchronously. VsCodeAdapter
loses the helpers this made unused (getText, getEdits, applyEdits,
getActiveDocument); getFullDocumentRange() now takes a document and
validates the range, which the formatter shares.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
sortDocuments() checked every text for an invalid selection ending
(`:`, `|` or `>`), also whole documents. A valid document like

    b: 1
    a:

could therefore not be sorted, neither with the command, the formatter
with sortOnSave nor the directory sort, and the user was told that the
selection is invalid although nothing was selected.

Only check the ending of a selection, which can cut a value in half.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
getInlineComment() toggled its quote state on every quote character.
An apostrophe in a plain value, as in

    key: it's fine # comment

opened a "quoted value" that never closed, so the comment was not
found and got lost while sorting. An escaped double quote (\") closed
a double quoted value too early.

A quote now only starts a quoted value at the beginning of a value
(line start, after whitespace, `[`, `{` or `,`). Inside double quotes a
backslash escapes the next character, inside single quotes `''` is an
escaped quote, as defined by the yaml spec.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
The keywords of a custom sort were written by hand as `${key}: value`,
and a heuristic decided whether the dumped value belongs on the next
line. This produced

* invalid yaml for a keyword that needs quotes: `'a: b': 1` became
  `a: b: 1`
* a scalar containing a colon on its own line (`kind:\n  http://x`),
  because the heuristic took it for a mapping
* an extra trailing line break when every key was a keyword, unlike
  the default sort

Each keyword is now dumped as a single-key mapping by js-yaml, which
quotes keys and places values the same way as for all other keys. The
heuristic (isValueMultiline, transformMultilineValue) and the unused
setLeadingDashes() are removed together with their tests; the
characterization tests that recorded the trailing line break expect
none now.

dumpYaml() also no longer turns an empty mapping into an empty string:
a document `{}` became an empty document. The remaining keys of a
custom sort are skipped when there are none instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
The SpacingProcessor ran last, after the block scalars and comments
were put back. With emptyLinesUntilLevel set, it therefore

* inserted empty lines between the lines of a block scalar that look
  like keys, which changed the value of the scalar:

      a: |
        foo: bar      ->  a: |
        baz: 1                          (empty line)
                            foo: bar ...

* inserted the empty line between a comment and its key instead of
  above the comment.

The pipeline now adds the empty lines first, while block scalars are
still hidden behind their substitutes, and restores the comments
afterwards directly above their keys.

ProcessorPipeline is rewritten as an ordered list of processors that
are preprocessed in order and restored in reverse order, replacing ten
nearly identical if-blocks. CommentProcessor gets preprocess() for the
common interface. The pipeline tests check the resulting text instead
of the pipeline's private processor fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
An indented selection is sorted unindented and indented again
afterwards (#53). prependWhitespacesOnEachLine() also indented empty
lines, so every empty line of the selection, e.g. inside a block
scalar, ended up with trailing whitespaces.

Empty lines are no longer indented.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Running "Recursively sort YAML files" on a project folder also sorted
every yaml file below node_modules, i.e. it rewrote the files of
installed dependencies. It also rewrote every file, even when nothing
changed, which touches modification times and triggers file watchers,
and processed a file twice if its extension was configured twice.

* YamlFileFinder ignores node_modules and .git
* configured extensions are de-duplicated
* sortFile() only writes a file whose content changed

The README describes the skipped folders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
The OctalProcessor only protected a value like 0755 when it directly
followed `key: ` and ended the line. js-yaml loads every other 0755 as
the decimal number 755, so sorting changed

    mode: 0755 # rwxr-xr-x   ->  mode: 755 # rwxr-xr-x
    - 0755                   ->  - 755

Also match list items and values followed by a comment. A value that
only starts with such digits, like 0755-1, is still left alone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
TabsToSpacesProcessor replaced every tab of a document with spaces,
also inside values: `key: "a<TAB>b"` became `key: a  b`, which changed
the value.

Only tabs in the leading whitespace of a line are replaced, which is
what yaml forbids.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
runTest.ts caught every error of runTests() and only printed "Failed to
run tests", so a failed VS Code download or a crashed test host left no
hint in the CI log. The error is printed now. The no-op
`.then().catch()` chain is replaced by a single catch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
When sorting changes the line a comment belongs to, e.g. js-yaml drops
the quotes of `a: "x"`, the comment is placed by its key. That search
took the last occurrence of the key's name anywhere in the text, so

    # about a
    a: "x"
    data: 2

became `a: x`, `# about a`, `data: 2`: the comment moved to `data`,
which contains an `a`. Inline comments moved the same way.

Search for the last line that starts with the key and a colon, first
with the original indentation, then with any indentation. The plain
substring search stays as last resort, so a comment is rather misplaced
than lost. The line searches share findLastLine().

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
Add the user-visible fixes of the editor commands (format with a
selection, edits and success message, running without an editor) and
an internal section about the core/vscode split and the unit tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
CommentProcessor had grown beyond 200 lines and mixed two jobs:
recognizing comments in a single line and putting them back into the
sorted text. isLineComment() and getInlineComment() are pure functions
of a line and move to core/processor/yaml-comment.ts together with
their tests. The magic anchor string of a comment in the last line
becomes the named constant LAST_LINE. No behavior changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jdb5ivdJ5L75kyEDAbuvMZ
@pascalre
pascalre merged commit 06cbb70 into master Nov 20, 2026
4 of 7 checks passed
@pascalre
pascalre deleted the feat/clean-architecture-refactor branch November 20, 2026 14:38
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
3.1% Duplication on New Code (required ≤ 3%)
C Security Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

npm install
npm install -g yarn
npm install -g vsce
run: npm ci
@codacy-production

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 9 minor

Alerts:
⚠ 9 issues (≤ 0 issues of at least minor severity)

Results:
9 new issues

Category Results
CodeStyle 9 minor

View in Codacy

🟢 Metrics 539 complexity · 14 duplication

Metric Results
Complexity 539
Duplication 14

View in Codacy

NEW Get contextual insights on your PRs based on Codacy's metrics, along with PR and Jira context, without leaving GitHub. Enable AI reviewer
TIP This summary will be updated as you push new changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants