haxsaw/hikaru

deserialize/serialize yaml preserving comments and formatting

Opened this issue · 1 comments

test1 = hikaru.load_full_yaml(path='./hikaru_test/1.yaml')
print(hikaru.get_yaml(test1[0]))

1.yaml

---
apiVersion: v1
kind: Pod
metadata:
  name: hello-kiamol-3
spec:
  containers:
  # test_comment
    - name: web # test_comment_2
      image: kiamol/ch02-hello-kiamol

output

---
apiVersion: v1
kind: Pod
metadata: {name: hello-kiamol-3}
spec:
  containers:
  - {image: kiamol/ch02-hello-kiamol, name: web}

Is it possible to preserve comments and formattion (using ruamel.yaml CommentedMap or something similar)? The use case here is quite straightforward - to be able to load, modify and dump k8s objects back to their original storage (which is yaml file in git)

Hi there--

So I looked at supporting comments initially and found it was fairly hard to do. I can't entirely re-create what I found at the moment, but there was something involved in what was available in ruamel.yaml that didn't work as needed. Further, it's kind of a thorny problem-- there's no connection between the original YAML and the Hikaru representation, and given that we'd have to try to come up with a way to essentially decorate the Hikaru objects and have them turn back into commented YAML. This all starts getting quite complex and involves a lot of lower level programming in the generation of YAML; currently, Hikaru simply turns it's representation into a dict which ruamel.yaml knows how to turn into YAML. Trying to retain comments clearly has value, but I'm currently looking into CRD support and my view is that people would get more value out of that (I know you asked about that as well and will respond to that in the relevant issue). Current time constraints a forcing me to choose one or the other.

I seem to recall some available switches regarding the supported style of YAML ruamel.yaml can output, so it might be possible to expose some new options that would allow you to choose how to have it format code. Alternatively, PyYAML does appear to cover my use cases now so it might offer a way to get the formatting done.

I'm currently working on getting 1.23 client support out the door, so I can spend a bit of time looking at this after that.