Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support option to keep comments from YAML input #689

Closed
bennycode opened this issue Oct 19, 2022 · 4 comments
Closed

Support option to keep comments from YAML input #689

bennycode opened this issue Oct 19, 2022 · 4 comments

Comments

@bennycode
Copy link

bennycode commented Oct 19, 2022

It was brought to my attention that "js-yaml" removes comments from sorted YAML code. I created a little snippet which proves that: https://runkit.com/bennyn/js-yaml-comment

const yaml = require('js-yaml');
const text = `variables:
  MY_VARIABLE: 'true'    # Comment 1
  OTHER_VARIABLE: 'true' # Comment 2
  BEST_VARIABLE: 'true'  # Comment 3
`;
const doc = yaml.load(text, {sortKeys: true});
console.log(yaml.dump(doc));

Output:

"variables:\n  MY_VARIABLE: 'true'\n  OTHER_VARIABLE: 'true'\n  BEST_VARIABLE: 'true'\n"

Is there the possibility to add an option to protect comments?

@perlpunk
Copy link

You might want to try https://github.com/eemeli/yaml instead

@puzrin puzrin closed this as completed Oct 19, 2022
@bennycode
Copy link
Author

Thanks for the hint! 👍

Using "yaml" worked:

import {ParsedNode, parseDocument, YAMLMap, YAMLSeq} from 'yaml';

function sortDeep(node: ParsedNode | null): void {
  if (node instanceof YAMLMap) {
    node.items.sort((itemA, itemB) => (itemA.key < itemB.key ? -1 : itemA.key > itemB.key ? 1 : 0));
    node.items.forEach(item => sortDeep(item.value));
  } else if (node instanceof YAMLSeq) {
    node.items.forEach(item => sortDeep(item));
  }
}

const document = parseDocument(yamlString);
sortDeep(document.contents);
console.log(document.toString());

@timestee
Copy link

timestee commented Jan 9, 2023

any update on this issue?

as a basic library, "yaml" has more requirements, like: eemeli/yaml#394, it should be compatible with lower node or webpack version.

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

No branches or pull requests

4 participants