From c236046a73533f54fb4c4cc34704125172ca2538 Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Thu, 14 May 2015 14:48:29 +0200 Subject: [PATCH] Avoid double-opening LineParser. Hopefully helps with diagnosing #670. --- qutebrowser/misc/lineparser.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/qutebrowser/misc/lineparser.py b/qutebrowser/misc/lineparser.py index 5ae90aa8a..5cd6304f5 100644 --- a/qutebrowser/misc/lineparser.py +++ b/qutebrowser/misc/lineparser.py @@ -53,12 +53,14 @@ class BaseLineParser(QObject): configdir: Directory to read the config from. fname: Filename of the config file. binary: Whether to open the file in binary mode. + _opened: Whether the underlying file is open """ super().__init__(parent) self._configdir = configdir self._configfile = os.path.join(self._configdir, fname) self._fname = fname self._binary = binary + self._opened = False def __repr__(self): return utils.get_repr(self, constructor=True, @@ -71,16 +73,23 @@ class BaseLineParser(QObject): if not os.path.exists(self._configdir): os.makedirs(self._configdir, 0o755) + @contextlib.contextmanager def _open(self, mode): """Open self._configfile for reading. Args: mode: The mode to use ('a'/'r'/'w') """ + if self._opened: + raise IOError("Refusing to double-open AppendLineParser.") + self._opened = True if self._binary: - return open(self._configfile, mode + 'b') + with open(self._configfile, mode + 'b') as f: + yield f else: - return open(self._configfile, mode, encoding='utf-8') + with open(self._configfile, mode, encoding='utf-8') as f: + yield f + self._opened = False def _write(self, fp, data): """Write the data to a file. @@ -195,9 +204,13 @@ class LineParser(BaseLineParser): def save(self): """Save the config file.""" + if self._opened: + raise IOError("Refusing to double-open AppendLineParser.") + self._opened = True self._prepare_save() with qtutils.savefile_open(self._configfile, self._binary) as f: self._write(f, self.data) + self._opened = False class LimitLineParser(LineParser):