Skip to content

(Replaced by !72764) Create a utility to inject comments into YAML dumps

Janis Altherr requested to merge add-documented-yaml-creator-util into master

This MR has been replaced by !72764 (merged)

What does this MR do and why?

This is the MR to #343243 (closed)

This MR adds a Utility that will be used by a Source Editor Extension (!72499 (closed)). The utility is written in a way that allows it to be used as a standalone utility.

Similar to js-yaml, it exposes a dump() method that converts its param to YAML, supporting the injection of comments.

Usage

import dyc from '~/lib/utils/documented_yaml_creator';

const value = { foo: [bar] };
const output = dyc.dump(value)
// foo:
//   - bar

Changing settings

import dyc from '~/lib/utils/documented_yaml_creator';

const output = dyc.set({maxLineLength: 100, indentation: 1, indentationType: 'tab'}).dump(value);

Method

In Objects, a key of '#' will be converted to a comment at the top of a property. Any key follwing the pattern #|<some other key> will be placed right before <some other key>.

Example:

{
  foo: 'bar',
  '#|baz': 'I am a comment specific to the `baz` property',
  baz: 'boo',
  '#': 'I am a generic comment, I will be placed at the top'
}

will be converted to:

# I am a generic comment, I will be placed at the top
foo: bar
# I am a comment specific to the `baz` property
baz: boo

In Arrays, any string that starts with # (including the space), will be converted to a comment at the position it was in. Example:

 ['foo', 123, '# I am a comment for abc', abc]

Will be converted to:

- foo
- 123
# I am a comment for abc
- abc

Gotchas

This util is exporting an Object, so running set() modifies the imported instance. I've done this to avoid an initialisation step in order to keep the interface as simple as possible. BUT this means that when the util is used multiple times, set() will affect all usages. I'm open to feedback on how to improve this.

Related Issues

gitlab-org/incubation-engineering/jamstack/meta#7 (moved)

How to set up and validate locally

Numbered steps to set up and validate the change are strongly suggested.

This MR only includes the utility function for later use. It is not used in FE in this MR yet.

  1. Create a JS file with the below content:
import dyc from '~/lib/utils/documented_yaml_creator';

const value = { foo: ['# baz', bar] };
const output = dyc.dump(value)
console.log(output)

To validate, I recommend also looking at the test cases:

  1. View ./spec/frontend/lib/utils/documented_yaml_creator_spec.js to see various test cases/behaviours
  2. Run the tests with jest ./spec/frontend/lib/utils/documented_yaml_creator_spec.js

MR acceptance checklist

This checklist encourages us to confirm any changes have been analyzed to reduce risks in quality, performance, reliability, security, and maintainability.

Edited by Janis Altherr

Merge request reports