On Fri, Jun 29, 2012 at 03:27:08PM -0400, Will Woods wrote:
The concept is fine, but there's a couple bugs. See comments below.
+class EditConfig(object):
Kind of a weird class name. Maybe ShellConfig, or maybe we should just replace SimpleConfig?
No, it Edits a Config file. Nothing more. It isn't used to create config files or add/delete from them. Just edits the values.
- def read(self):
""" Read the config file and store the key/value pairs"""with open(self.filename) as f:for line in f:if len(line)>0 and line[0] in '#";':continueBug. len(line) will never be 0, because empty lines will come out as "\n". readline() is tricky like that.
Well, not a bug, just not needed.
Also, this line won't be considered a comment: ' #blah=funk\n'
Add a 'line = line.strip()' first?
Probably so.
(key, sep, var) = [x.strip() for x in line.partition("=")](With the strip happening above, you wouldn't need it here.)
This strip also removes spaces from around var.
if sep == '=' and key:
Either way would be clearer, I think.
Swapping them makes it a bit clearer.
self.values[key] = varThis is going to leave any quoting that's in var, so if quotes are used the value will be something like: '"fun"'. Conversely, in write(), we're not adding quotes if the value has spaces, so if you change a value to 'something with spaces in it', it's not gonna be quoted in the resulting file, which will cause problems if the parser expects that.
Do we care about that stuff?
That was on purpose, if the variable needs to be quoted then reading should leave them in and changing it should make sure it has quotes.
- def write(self):
""" Rewrite the file with the new key/value pairspass-thru comments and lines without ="""tmpf = tempfile.NamedTemporaryFile(mode="w", delete=False)with open(self.filename) as f:We're reopening the file here? What if the file has been changed/removed since it was read, or we want to read the config from a string?
It might be a good idea to save the lines in an array on read(), and just iterate over the saved lines in write().
I actually wrote a ConfigParser-style thingy for this out of curiosity - I'll send it along for discussion.
If you hold a copy in memory and re-write it you may end up stomping on top of changes from something else. If you have two things fighting over the same file you're going to lose one way or the other. My primary goal for this class was to make a minimum of changes to the file in order to change a variable, not provide a full-featured configuration editing class.
It could be slightly improved by only writing variables that have been changed, but for our limited needs in Anaconda I don't think it needs it.