Edgewall Software

Ticket #9536: 9536-cleanup-finally-r10401.diff

File 9536-cleanup-finally-r10401.diff, 21.8 KB (added by cboos, 17 months ago)

use with for automatically closing files and releasing locks.

  • trac/admin/console.py

    # HG changeset patch
    # Parent 252f94e03103dec9f9ec19e2fcee898c8d172db8
    #9536: use `with` for automatically closing files and releasing locks.
    
    Also, made `trac.util.AtomicFile` a context manager.
    
    diff -r 252f94e03103 trac/admin/console.py
    a b  
    1212# individuals. For the exact contribution history, see the revision 
    1313# history and logs, available at http://trac.edgewall.org/log/. 
    1414 
     15from __future__ import with_statement 
     16 
    1517import cmd 
    1618import locale 
    1719import os.path 
    def find_readline_lib(): 
    4446    linked to the readline module. 
    4547    """ 
    4648    import readline 
    47     f = open(readline.__file__, "rb") 
    48     try: 
     49    with open(readline.__file__, "rb") as f: 
    4950        data = f.read() 
    50     finally: 
    51         f.close() 
    5251    import re 
    5352    m = re.search('\0([^\0]*libreadline[^\0]*)\0', data) 
    5453    if m: 
  • trac/admin/web_ui.py

    diff -r 252f94e03103 trac/admin/web_ui.py
    a b  
    1414# 
    1515# Author: Jonas Borgström <jonas@edgewall.com> 
    1616 
     17from __future__ import with_statement 
     18 
    1719from functools import partial 
    1820import os 
    1921import pkg_resources 
    class PluginAdminPanel(Component): 
    477479        except AttributeError: 
    478480            # OS_BINARY not available on every platform 
    479481            pass 
    480         target_file = os.fdopen(os.open(target_path, flags, 0666), 'w') 
    481         try: 
     482        with os.fdopen(os.open(target_path, flags, 0666), 'w') as target_file: 
    482483            shutil.copyfileobj(upload.file, target_file) 
    483484            self.log.info('Plugin %s installed to %s', plugin_filename, 
    484485                          target_path) 
    485         finally: 
    486             target_file.close() 
    487  
    488486        # TODO: Validate that the uploaded file is actually a valid Trac plugin 
    489487 
    490488        # Make the environment reset itself on the next request 
  • trac/attachment.py

    diff -r 252f94e03103 trac/attachment.py
    a b class Attachment(object): 
    265265        filename = unicode_quote(filename) 
    266266        path, targetfile = create_unique_file(os.path.join(self.path, 
    267267                                                           filename)) 
    268         try: 
     268        with targetfile: 
    269269            # Note: `path` is an unicode string because `self.path` was one. 
    270270            # As it contains only quoted chars and numbers, we can use `ascii` 
    271271            basename = os.path.basename(path).encode('ascii') 
    class Attachment(object): 
    281281 
    282282                self.env.log.info("New attachment: %s by %s", self.title, 
    283283                                  self.author) 
    284         finally: 
    285             targetfile.close() 
    286284 
    287285        for listener in AttachmentModule(self.env).change_listeners: 
    288286            listener.attachment_added(self) 
    class AttachmentModule(Component): 
    725723                'title': get_resource_name(self.env, attachment.resource), 
    726724                'attachment': attachment} 
    727725 
    728         fd = attachment.open() 
    729         try: 
     726        with attachment.open() as fd: 
    730727            mimeview = Mimeview(self.env) 
    731728 
    732729            # MIME type detection 
    class AttachmentModule(Component): 
    775772                os.fstat(fd.fileno()).st_size, mime_type, 
    776773                attachment.filename, raw_href, annotations=['lineno']) 
    777774            return data 
    778         finally: 
    779             fd.close() 
    780775 
    781776    def _format_link(self, formatter, ns, target, label): 
    782777        link, params, fragment = formatter.split_link(target) 
    class AttachmentAdmin(Component): 
    946941        attachment = Attachment(self.env, realm, id) 
    947942        attachment.author = author 
    948943        attachment.description = description 
    949         f = open(path, 'rb') 
    950         try: 
     944        with open(path, 'rb') as f: 
    951945            attachment.insert(os.path.basename(path), f, os.path.getsize(path)) 
    952         finally: 
    953             f.close() 
    954946     
    955947    def _do_remove(self, resource, name): 
    956948        (realm, id) = self.split_resource(resource) 
    class AttachmentAdmin(Component): 
    966958            if os.path.isfile(destination): 
    967959                raise AdminCommandError(_("File '%(name)s' exists", 
    968960                                          name=destination)) 
    969         input = attachment.open() 
    970         try: 
     961        with attachment.open() as input: 
    971962            output = (destination is None) and sys.stdout \ 
    972963                                           or open(destination, "wb") 
    973964            try: 
    class AttachmentAdmin(Component): 
    975966            finally: 
    976967                if destination is not None: 
    977968                    output.close() 
    978         finally: 
    979             input.close() 
    980969 
  • trac/config.py

    diff -r 252f94e03103 trac/config.py
    a b  
    1212# individuals. For the exact contribution history, see the revision 
    1313# history and logs, available at http://trac.edgewall.org/log/. 
    1414 
     15from __future__ import with_statement 
     16 
    1517from ConfigParser import ConfigParser 
    1618from copy import deepcopy 
    1719import os.path 
    class Configuration(object): 
    231233 
    232234        # At this point, all the strings in `sections` are UTF-8 encoded `str` 
    233235        try: 
    234             fileobj = AtomicFile(self.filename, 'w') 
    235             try: 
     236            with AtomicFile(self.filename, 'w') as fileobj: 
    236237                fileobj.write('# -*- coding: utf-8 -*-\n\n') 
    237238                for section, options in sections: 
    238239                    fileobj.write('[%s]\n' % section) 
    class Configuration(object): 
    244245                                             .replace('\n', '\n ') 
    245246                            fileobj.write('%s = %s\n' % (key_str, val_str)) 
    246247                    fileobj.write('\n') 
    247             finally: 
    248                 fileobj.close() 
    249248            self._old_sections = deepcopy(self.parser._sections) 
    250249        except Exception: 
    251250            # Revert all changes to avoid inconsistencies 
  • trac/env.py

    diff -r 252f94e03103 trac/env.py
    a b class Environment(Component, ComponentMa 
    350350    def verify(self): 
    351351        """Verify that the provided path points to a valid Trac environment 
    352352        directory.""" 
    353         fd = open(os.path.join(self.path, 'VERSION'), 'r') 
    354         try: 
     353        with open(os.path.join(self.path, 'VERSION'), 'r') as fd: 
    355354            assert fd.read(26) == 'Trac Environment Version 1' 
    356         finally: 
    357             fd.close() 
    358355 
    359356    def get_db_cnx(self): 
    360357        """Return a database connection from the connection pool  
    def open_environment(env_path=None, use_ 
    754751 
    755752    env_path = os.path.normcase(os.path.normpath(env_path)) 
    756753    if use_cache: 
    757         env_cache_lock.acquire() 
    758         try: 
     754        with env_cache_lock: 
    759755            env = env_cache.get(env_path) 
    760756            if env and env.config.parse_if_needed(): 
    761757                # The environment configuration has changed, so shut it down 
    def open_environment(env_path=None, use_ 
    769765                env = env_cache.setdefault(env_path, open_environment(env_path)) 
    770766            else: 
    771767                CacheManager(env).reset_metadata() 
    772         finally: 
    773             env_cache_lock.release() 
    774768    else: 
    775769        env = Environment(env_path) 
    776770        needs_upgrade = False 
    class EnvironmentAdmin(Component): 
    841835            template = Chrome(self.env).load_template('deploy_trac.' + script, 
    842836                                                      'text') 
    843837            stream = template.generate(**data) 
    844             out = file(dest, 'w') 
    845             try: 
     838            with open(dest, 'w') as out: 
    846839                stream.render('text', out=out) 
    847             finally: 
    848                 out.close() 
    849840 
    850841    def _do_hotcopy(self, dest, no_db=None): 
    851842        if no_db not in (None, '--no-database'): 
  • trac/tests/config.py

    diff -r 252f94e03103 trac/tests/config.py
    a b  
    1212# individuals. For the exact contribution history, see the revision 
    1313# history and logs, available at http://trac.edgewall.org/log/. 
    1414 
     15from __future__ import with_statement 
     16 
    1517import os 
    1618import tempfile 
    1719import time 
    class ConfigurationTestCase(unittest.Tes 
    3941        return Configuration(self.filename) 
    4042 
    4143    def _write(self, lines): 
    42         fileobj = open(self.filename, 'w') 
    43         try: 
     44        with open(self.filename, 'w') as fileobj: 
    4445            fileobj.write(('\n'.join(lines + [''])).encode('utf-8')) 
    45         finally: 
    46             fileobj.close() 
    4746 
    4847    def test_default(self): 
    4948        config = self._read() 
    class ConfigurationTestCase(unittest.Tes 
    433432 
    434433    def _test_with_inherit(self, testcb): 
    435434        sitename = os.path.join(tempfile.gettempdir(), 'trac-site.ini') 
    436         sitefile = open(sitename, 'w') 
    437435        try: 
    438             try: 
     436            with open(sitename, 'w') as sitefile: 
    439437                sitefile.write('[a]\noption = x\n') 
    440             finally: 
    441                 sitefile.close() 
    442438 
    443439            self._write(['[inherit]', 'file = trac-site.ini']) 
    444440            testcb() 
  • trac/util/__init__.py

    diff -r 252f94e03103 trac/util/__init__.py
    a b  
    1717# Author: Jonas Borgström <jonas@edgewall.com> 
    1818#         Matthew Good <trac@matt-good.net> 
    1919 
     20from __future__ import with_statement 
     21 
    2022import errno 
    2123import inspect 
    2224from itertools import izip, tee 
    class AtomicFile(object): 
    181183     
    182184    def __getattr__(self, name): 
    183185        return getattr(self._file, name) 
    184      
     186 
    185187    def commit(self): 
    186188        if self._file is None: 
    187189            return 
    class AtomicFile(object): 
    204206                os.unlink(self._temp) 
    205207            except: 
    206208                pass 
    207      
     209             
    208210    close = commit 
    209211    __del__ = rollback 
    210212 
     213    def __enter__(self): 
     214        return self 
     215 
     216    def __exit__(self, exc_type, exc_value, traceback): 
     217        self.close() 
     218 
     219    closed = property(lambda self: self._file is None or self._file.closed) 
     220 
    211221 
    212222def read_file(path, mode='r'): 
    213223    """Read a file and return its content.""" 
    def read_file(path, mode='r'): 
    220230 
    221231def create_file(path, data='', mode='w'): 
    222232    """Create a new file with the given data.""" 
    223     f = open(path, mode) 
    224     try: 
     233    with open(path, mode) as f: 
    225234        if data: 
    226235            f.write(data) 
    227     finally: 
    228         f.close() 
    229236 
    230237 
    231238def create_unique_file(path): 
  • trac/util/daemon.py

    diff -r 252f94e03103 trac/util/daemon.py
    a b  
    1111# individuals. For the exact contribution history, see the revision 
    1212# history and logs, available at http://trac.edgewall.org/log/. 
    1313 
     14from __future__ import with_statement 
     15 
    1416import atexit 
    1517import errno 
    1618import os 
    def daemonize(pidfile=None, progname=Non 
    2628        # process running 
    2729        pidfile = os.path.abspath(pidfile) 
    2830        if os.path.exists(pidfile): 
    29             fileobj = open(pidfile) 
    30             try: 
     31            with open(pidfile) as fileobj: 
    3132                try: 
    3233                    pid = int(fileobj.read()) 
    3334                except ValueError: 
    3435                    sys.exit('Invalid PID in file %s' % pidfile) 
    35             finally: 
    36                 fileobj.close() 
    3736 
    3837            try: # signal the process to see if it is still running 
    3938                os.kill(pid, 0) 
    def daemonize(pidfile=None, progname=Non 
    8079            if os.path.exists(pidfile): 
    8180                os.remove(pidfile) 
    8281        atexit.register(remove_pidfile) 
    83         fileobj = open(pidfile, 'w') 
    84         try: 
     82        with open(pidfile, 'w') as fileobj: 
    8583            fileobj.write(str(os.getpid())) 
    86         finally: 
    87             fileobj.close() 
    8884 
    8985 
    9086def handle_signal(signum, frame): 
  • trac/util/dist.py

    diff -r 252f94e03103 trac/util/dist.py
    a b  
    1111# individuals. For the exact contribution history, see the revision 
    1212# history and logs, available at http://trac.edgewall.org/log/. 
    1313 
     14from __future__ import with_statement 
     15 
    1416"""Extra commands for setup.py. 
    1517 
    1618In addition to providing a few extra command classes in `l10n_cmdclass`, 
    try: 
    131133                log.info('generating messages javascript %r to %r', 
    132134                         mo_file, js_file) 
    133135 
    134                 infile = open(mo_file, 'rb') 
    135                 try: 
     136                with open(mo_file, 'rb') as infile: 
    136137                    t = Translations(infile, self.domain) 
    137138                    catalog = t._catalog 
    138                 finally: 
    139                     infile.close() 
    140139 
    141                 outfile = open(js_file, 'w') 
    142                 try: 
     140                with open(js_file, 'w') as outfile: 
    143141                    write_js(outfile, catalog, self.domain, locale) 
    144                 finally: 
    145                     outfile.close() 
    146142 
    147143    def write_js(fileobj, catalog, domain, locale): 
    148144        data = {'domain': domain, 'locale': locale} 
  • trac/util/tests/__init__.py

    diff -r 252f94e03103 trac/util/tests/__init__.py
    a b  
    1111# individuals. For the exact contribution history, see the revision 
    1212# history and logs, available at http://trac.edgewall.org/log/. 
    1313 
     14from __future__ import with_statement 
     15 
    1416import doctest 
    1517import os.path 
    1618import random 
    class AtomicFileTestCase(unittest.TestCa 
    3335            pass 
    3436     
    3537    def test_non_existing(self): 
    36         f = util.AtomicFile(self.path) 
    37         try: 
     38        with util.AtomicFile(self.path) as f: 
    3839            f.write('test content') 
    39         finally: 
    40             f.close() 
     40        self.assertEqual(True, f.closed) 
    4141        self.assertEqual('test content', util.read_file(self.path)) 
    4242     
    4343    def test_existing(self): 
    4444        util.create_file(self.path, 'Some content') 
    4545        self.assertEqual('Some content', util.read_file(self.path)) 
    46         f = util.AtomicFile(self.path) 
    47         try: 
     46        with util.AtomicFile(self.path) as f: 
    4847            f.write('Some new content') 
    49         finally: 
    50             f.close() 
     48        self.assertEqual(True, f.closed) 
    5149        self.assertEqual('Some new content', util.read_file(self.path)) 
    5250     
    5351    if util.can_rename_open_file: 
    5452        def test_existing_open_for_reading(self): 
    5553            util.create_file(self.path, 'Initial file content') 
    5654            self.assertEqual('Initial file content', util.read_file(self.path)) 
    57             rf = open(self.path) 
    58             try: 
    59                 f = util.AtomicFile(self.path) 
    60                 try: 
     55            with open(self.path) as rf: 
     56                with util.AtomicFile(self.path) as f: 
    6157                    f.write('Replaced content') 
    62                 finally: 
    63                     f.close() 
    64             finally: 
    65                 rf.close() 
     58            self.assertEqual(True, rf.closed) 
     59            self.assertEqual(True, f.closed) 
    6660            self.assertEqual('Replaced content', util.read_file(self.path)) 
    6761     
    6862    # FIXME: It is currently not possible to make this test pass on all 
    class AtomicFileTestCase(unittest.TestCa 
    7367    # we require Python 3. 
    7468    def _test_unicode_path(self): 
    7569        self.path = os.path.join(tempfile.gettempdir(), u'träc-témpfilè') 
    76         f = util.AtomicFile(self.path) 
    77         try: 
     70        with util.AtomicFile(self.path) as f: 
    7871            f.write('test content') 
    79         finally: 
    80             f.close() 
     72        self.assertEqual(True, f.closed) 
    8173        self.assertEqual('test content', util.read_file(self.path)) 
    8274 
    8375 
  • trac/util/translation.py

    diff -r 252f94e03103 trac/util/translation.py
    a b  
    1111# individuals. For the exact contribution history, see the revision 
    1212# history and logs, available at http://trac.edgewall.org/log/. 
    1313 
     14from __future__ import with_statement 
     15 
    1416"""Utilities for text translation with gettext.""" 
    1517 
    1618import pkg_resources 
    try: 
    128130        # Public API 
    129131 
    130132        def add_domain(self, domain, env_path, locales_dir): 
    131             self._plugin_domains_lock.acquire() 
    132             try: 
     133            with self._plugin_domains_lock: 
    133134                if env_path not in self._plugin_domains: 
    134135                    self._plugin_domains[env_path] = [] 
    135136                self._plugin_domains[env_path].append((domain, locales_dir)) 
    136             finally: 
    137                 self._plugin_domains_lock.release() 
    138137 
    139138        def make_activable(self, get_locale, env_path=None): 
    140139            self._current.args = (get_locale, env_path) 
    try: 
    149148            if not t or t.__class__ is NullTranslations: 
    150149                t = self._null_translations 
    151150            elif env_path: 
    152                 self._plugin_domains_lock.acquire() 
    153                 try: 
     151                with self._plugin_domains_lock: 
    154152                    domains = list(self._plugin_domains.get(env_path, [])) 
    155                 finally: 
    156                     self._plugin_domains_lock.release() 
    157153                for domain, dirname in domains: 
    158154                    t.add(Translations.load(dirname, locale, domain)) 
    159155            self._current.translations = t 
  • trac/versioncontrol/api.py

    diff -r 252f94e03103 trac/versioncontrol/api.py
    a b class RepositoryManager(Component): 
    594594 
    595595    def reload_repositories(self): 
    596596        """Reload the repositories from the providers.""" 
    597         self._lock.acquire() 
    598         try: 
     597        with self._lock: 
    599598            # FIXME: trac-admin doesn't reload the environment 
    600599            self._cache = {} 
    601600            self._all_repositories = None 
    602         finally: 
    603             self._lock.release() 
    604601        self.config.touch()     # Force environment reload 
    605602  
    606603    def notify(self, event, reponame, revs): 
    class RepositoryManager(Component): 
    650647    def shutdown(self, tid=None): 
    651648        if tid: 
    652649            assert tid == threading._get_ident() 
    653             try: 
    654                 self._lock.acquire() 
     650            with self._lock: 
    655651                repositories = self._cache.pop(tid, {}) 
    656652                for reponame, repos in repositories.iteritems(): 
    657653                    repos.close() 
    658             finally: 
    659                 self._lock.release() 
    660654         
    661655    # private methods 
    662656 
  • trac/web/auth.py

    diff -r 252f94e03103 trac/web/auth.py
    a b class PasswordFileAuthentication(HTTPAut 
    265265        self._lock = threading.Lock() 
    266266 
    267267    def check_reload(self): 
    268         self._lock.acquire() 
    269         try: 
     268        with self._lock: 
    270269            mtime = os.stat(self.filename).st_mtime 
    271270            if mtime > self.mtime: 
    272271                self.mtime = mtime 
    273272                self.load(self.filename) 
    274         finally: 
    275             self._lock.release() 
    276273 
    277274 
    278275class BasicAuthentication(PasswordFileAuthentication): 
  • trac/web/chrome.py

    diff -r 252f94e03103 trac/web/chrome.py
    a b  
    1414# 
    1515# Author: Christopher Lenz <cmlenz@gmx.de> 
    1616 
     17from __future__ import with_statement 
     18 
    1719"""Content presentation for the web layer. 
    1820 
    1921The Chrome module deals with delivering and shaping content to the end user, 
    class Chrome(Component): 
    485487                os.mkdir(templates_dir) 
    486488 
    487489            site_path = os.path.join(templates_dir, 'site.html.sample') 
    488             fileobj = open(site_path, 'w') 
    489             try: 
     490            with open(site_path, 'w') as fileobj: 
    490491                fileobj.write("""\ 
    491492<html xmlns="http://www.w3.org/1999/xhtml" 
    492493      xmlns:xi="http://www.w3.org/2001/XInclude" 
    class Chrome(Component): 
    504505  --> 
    505506</html> 
    506507""") 
    507             finally: 
    508                 fileobj.close() 
    509508 
    510509    def environment_needs_upgrade(self, db): 
    511510        return False 
  • trac/web/modpython_frontend.py

    diff -r 252f94e03103 trac/web/modpython_frontend.py
    a b  
    1616# Author: Christopher Lenz <cmlenz@gmx.de> 
    1717#         Matthew Good <trac@matt-good.net> 
    1818 
     19from __future__ import with_statement 
     20 
    1921import os 
    2022import pkg_resources 
    2123import sys 
    _first_lock = threading.Lock() 
    126128             
    127129def handler(req): 
    128130    global _first 
    129     try: 
    130         _first_lock.acquire() 
     131    with _first_lock: 
    131132        if _first:  
    132133            _first = False 
    133134            options = req.get_options() 
    def handler(req): 
    141142            if egg_cache: 
    142143                pkg_resources.set_extraction_path(egg_cache) 
    143144            reload(sys.modules['trac.web']) 
    144     finally: 
    145         _first_lock.release() 
    146145    pkg_resources.require('Trac==%s' % VERSION) 
    147146    gateway = ModPythonGateway(req, req.get_options()) 
    148147    from trac.web.main import dispatch_request 
  • trac/wiki/admin.py

    diff -r 252f94e03103 trac/wiki/admin.py
    a b class WikiAdmin(Component): 
    106106                if os.path.isfile(filename): 
    107107                    raise AdminCommandError(_("File '%(name)s' exists", 
    108108                                              name=filename)) 
    109                 f = open(filename, 'w') 
    110                 try: 
     109                with open(filename, 'w') as f: 
    111110                    f.write(text.encode('utf-8')) 
    112                 finally: 
    113                     f.close() 
    114111            break 
    115112        else: 
    116113            raise AdminCommandError(_("Page '%(page)s' not found", page=page))