5 ms·
So you want to programmatically edit a config file, preserving formatting and comments, without using regexes, AST visitors, or XSLT? What's left? I seriously d
by openasocket 9y ago
So you want to programmatically edit a config file, preserving formatting and comments, without using regexes, AST visitors, or XSLT? What's left? I seriously don't know of any other ways to manipulate data while preserving formatting and comments.
- _wmd 9y ago$ cat my-config.xml <root> <!-- i am a comment --> <thing attr="foo"> <!-- i am another comment --> <setting>value</setting> </thing> </root> $ cat c.py import lxml.etree doc = lxml.etree.fromstring(file('my-config.xml').read()) for setting in doc.xpath('.//thing/setting'): setting.text = 'set without screwing up the file' print lxml.etree.tostring(doc) $ python c.py <root> <!-- i am a comment --> <thing attr="foo"> <!-- i am another comment --> <setting>set without screwing up the file</setting> </thing> </root>
- openasocket 9y ago... but you just chewed someone out for suggesting XML. And you are doing tree walking here, you're just reducing some of the boilerplate with XPath. You can do the same thing with Scheme using car, cdr, cadr and friends.
- _wmd 9y agoThe suggestion was to use XSLT to transform Scheme syntax
- openasocket 9y agoMy mistake then. You can still use car, cdr, cadr etc. to accomplish more or less the same thing as XPath. S-expressions are a completely valid serialization format. You can't easily manipulate JSON or YAML data while preserving formatting and comments with any library I've used (though it is possible), that doesn't mean JSON and YAML are invalid.
- mcguire 9y agoXPath and a tree transformation? Works well.
- avar 9y agoThis isn't applicable to scheme as a config format, but some config formats are line based and have programmatic tools to manipulate them, e.g. the .ini-like format Git uses, try adding some comments to ~/.gitconfig and manipulating it with `git config --global <...>`, it'll all be preserved. You will lose any comments like this though: [user] name = My Name ; that's my name! Programming is hard in the face of arbitrary user data.