Closed ffflorian closed 2 years ago
Thanks for your nice report!
Sorting YAML files is accomplished using "js-yaml". I just asked the library authors to support preserving comments: https://github.com/nodeca/js-yaml/issues/689
Once this feature is available in "js-yaml" I will update my plugin.
Perfect, thanks!
Seems like the authors don't have the resources to implement this and we are asked to use https://github.com/eemeli/yaml instead.
The "yaml" package supports preserving comments thanks to full AST parsing but it doesn't support sorting. Luckily another user built sorting and shared how to make it work using "yaml": https://github.com/eemeli/yaml/issues/44#issuecomment-571696527
EDIT: Looks like it is part of their stable versions now -> https://github.com/eemeli/yaml/blob/6e0071179b36329a4d7c98b006c3f838269756d2/tests/doc/stringify.js#L611-L613
I tried using sortMapEntries
but to no avail. So I went ahead and used the deep sort algorithm instead and created a fix, see #2 🙂
@ffflorian are you sure that sortMapEntries
is not available? For me it seems to work:
const YAML = require('yaml');
const obj = { b: 2, a: 1, c: 3 };
console.log(YAML.stringify(obj, { sortMapEntries: true })); // "a: 1\nb: 2\nc: 3\n"
@ffflorian are you sure that
sortMapEntries
is not available?
The function is available but I wasn't able to receive a sorted Document
when using sortMapEntries: true
.
Indeed. It looks like sortMapEntries
only works when being used with plain objects (instead of Document.Parsed
or string
). This has the side effect that comments are being thrown away (because JSON objects don't have comments):
import {parseDocument, stringify} from 'yaml';
// ...
const document = parseDocument(text);
console.log(stringify(document.toJSON(), {sortMapEntries: true}));
Given I have a yaml file with unsorted lines:
I select them and run Sort Everything, I receive this:
but I was expecting to receive this:
Whitespace being removed is a bit annoying, too, but nothing serious. But I don't want to lose those precious comments! 🙂
Btw: I am using Sort Everything on a daily basis for the last few weeks and beside this bug it's been working flawlessly!