0

I am using https://github.com/waiting-for-dev/front_matter_parser to parse and update values in the frontmatter of my markdown files.

The following code removes the original indentation of two spaces for array values:

require 'front_matter_parser'

class FrontMatterUpdater
  def self.run(path)
    parsed = FrontMatterParser::Parser.parse_file(path)
    front_matter = parsed.front_matter
    
    front_matter['redirect_from'] = Array(front_matter['redirect_from'])
    front_matter['redirect_from'] << 'new_entry2'
    front_matter['redirect_from'].uniq!
    
    new_content = [YAML.dump(front_matter), '---', "\n\n", parsed.content].join
    
    File.write(path, new_content)
  end
end

FrontMatterUpdater.run('test.md')

Content of my test.md file (same path):.

---
redirect_from:
  - new_entry0
  - new_entry1
--- 

Script result (indentation has been removed by the parser):

---
redirect_from:
- new_entry0
- new_entry1
- new_entry2
--- 

YAML indentation for array in hash confirms that both versions (indented and not) is valid YAML syntax.

But I'd love to keep the indentation for readability.

Do you see any option to keep the indentation of 2 spaces for the array values?

Christian
  • 4,902
  • 4
  • 24
  • 42
  • 1
    I cannot find any configuration that would provide this output. Indentation levels are controlled by the `Emitter` and the visiting of an `Array` creates a sequence which will have the same indentation level as the key. – engineersmnky Jan 03 '23 at 20:03
  • I understand. I'd need to implement my own way of reading the YAML file and parsing the front matter. Too complex for the use case, I will the output without indentation. Thanks for your comment. Learned a lot about YAML today :) – Christian Jan 03 '23 at 22:48
  • Just to let you know. I found at least a potential workaround. I could run yq in a post processing step, e.g. `find _docs -exec yq e -I2 --front-matter="process" -i '.yq_formatted = true' {} \;`, you can check the details in https://www.baeldung.com/linux/yq-utility-processing-yaml or https://mikefarah.gitbook.io/yq – Christian Jan 05 '23 at 03:43
  • Works even better by using a deletion of a non-existing YAML key: `find _docs -exec yq e -I2 --front-matter="process" -i 'del(.street_address.xyz)' {} \;` – Christian Jan 05 '23 at 03:46

0 Answers0