Reputation: 11
I have a YAML file ('config.yaml') with this content:
egress:
hostName: example.com
tls:
- hosts:
- example.com
How can I extend this file in groovy?
Result must be like this:
egress:
hostName: example.com
tls:
- hosts:
- example.com
tag: 1.1.1
Thanks!
Upvotes: 0
Views: 278
Reputation: 1443
It depends.
If you want to treat config.yaml
just as an ordinary text file, then you can just use common Groovy ways to work with IO:
String path = 'path/to/file'
File cfgFile = new File(path, 'config.yml')
cfgFile.withWriterAppend() { writer ->
writer.writeLine('\ntag: 1.1.1')
}
or just
new File(path, 'config.yml') << '\ntag: 1.1.1'
But if you want to build something more sophisticated and aware of YAML format of this file, then you can use SnakeYaml library:
@Grapes([
@Grab(group='org.yaml', module='snakeyaml', version='1.25')
])
import org.yaml.snakeyaml.Yaml
String path = '../data/'
File cfgFile = new File(path, 'config.yaml')
Yaml yaml = new Yaml()
Map content = [:]
cfgFile.withReader { reader ->
content = yaml.load(reader)
}
content.put('tag', '1.1.1')
cfgFile.withWriter { writer ->
yaml.dump(content, writer)
}
If you use Groovy 3.0+ then you can use built-in YamlSlurper
and YamlBuilder
instead.
(Groovy 3.0 is not released yet at the time of writing this answer)
One disadvantage here is that parsing and re-writing yaml file will get rid of comments and will reformat entire file.
Upvotes: 1