How can I preserve comments when editing an hjson file?

135 Views Asked by At

I have a configuration file in hjson format. There are a lot of values and comments in this file.

Simplified file looks like this:

{
  # Comments
  # comments
  Variants: [v1, v2, v3]

  # Comments
  # comments
  Values: { v1: ["asd"]}

  # Comments
  # comments
  Some: [p1, p2]

  # Comments
  # comments
  Name: Champion

  # Comments
  # comments
  Something: [a,b,c]

  # etc
  # ...
}

I only need to make changes to one array: Variants (I need to add values there).

The rest remains unchanged.

Now I'm doing this by parsing using serde_hjson (nu_json), working with the config as an object and writing the modified object back to the file as json.

As a result, all comments are lost.

Please tell me how to do what I need without losing the comments in the file.

Comments can be very diverse - each user has their own.

P.S.: this configuration file format was not chosen by me, this is another application.

1

There are 1 best solutions below

4
Martin del Necesario On

Update - this approach only works if no comments are inside of the array:

If performance is not an issue, you could use the following hack as a quick and dirty solution:

  1. parse the original hjson-file and writing it to a tmp-file "tmp1.hjson" without making changes
  2. parse the original hjson-file, make the changes you need and write to "tmp2.hjson"
  3. read the contents of both files and store the diff (store both oldContent and newContent, but only what has changed)
  4. In the original hjson-file, replace oldContent with newContent. Don't use serde_hjson parser for this - just read the file as text, make the replacement on the content string and overwrite the content of the file.

I am not fluent in Rust, but maybe steps 1 and 2 are possible without creating an actual file.