[Pkg-privacy-commits] [txtorcon] 07/96: pep8, flakes, readability improvements

Jérémy Bobbio lunar at moszumanska.debian.org
Sun Sep 6 18:33:32 UTC 2015


This is an automated email from the git hooks/post-receive script.

lunar pushed a commit to branch master
in repository txtorcon.

commit 78ae195d76ca5791f007a4b748294e4d04b35b46
Author: Kali Kaneko <kali at futeisha.org>
Date:   Sun Sep 14 11:56:03 2014 -0500

    pep8, flakes, readability improvements
    
    * remove unused imports
    * shorten lines
    * minor readability improvements on some conditionals
---
 txtorcon/torconfig.py | 138 +++++++++++++++++++++++++++++---------------------
 1 file changed, 81 insertions(+), 57 deletions(-)

diff --git a/txtorcon/torconfig.py b/txtorcon/torconfig.py
index e5c76ab..fe5ef67 100644
--- a/txtorcon/torconfig.py
+++ b/txtorcon/torconfig.py
@@ -5,7 +5,6 @@ import sys
 import string
 import types
 import functools
-import random
 import tempfile
 from StringIO import StringIO
 import shlex
@@ -14,20 +13,9 @@ if sys.platform in ('linux2', 'darwin'):
 
 from twisted.python import log
 from twisted.internet import defer, error, protocol
-from twisted.internet.interfaces import IStreamServerEndpoint, IReactorTime
-from twisted.internet.endpoints import TCP4ClientEndpoint, TCP4ServerEndpoint
-from twisted.internet.endpoints import clientFromString
-from zope.interface import implements
-from zope.interface import implementer
-from zope.interface import Interface, Attribute
-from twisted.internet.interfaces import IProtocolFactory, IListeningPort, IAddress
-from twisted.python.util import FancyEqMixin
-from twisted.plugin import IPlugin
-from twisted.internet.interfaces import IStreamServerEndpointStringParser
-from twisted.internet.endpoints import serverFromString
-from twisted.python.usage import UsageError
-
-import txtorcon
+from twisted.internet.interfaces import IReactorTime
+from twisted.internet.endpoints import TCP4ClientEndpoint
+
 from txtorcon.torcontrolprotocol import parse_keywords, TorProtocolFactory
 from txtorcon.util import delete_file_or_tree, find_keywords, find_tor_binary
 from txtorcon.log import txtorlog
@@ -63,7 +51,9 @@ class TorProcessProtocol(protocol.ProcessProtocol):
         :api:`twisted.internet.endpoints.TCP4ClientEndpoint`
 
         :param connection_creator: A no-parameter callable which
-            returns a Deferred which promises a :api:`twisted.internet.interfaces.IStreamClientEndpoint <IStreamClientEndpoint>`
+            returns a Deferred which promises a
+            :api:`twisted.internet.interfaces.IStreamClientEndpoint
+            <IStreamClientEndpoint>`
 
         :param progress_updates: A callback which received progress
             updates with three args: percent, tag, summary
@@ -91,7 +81,8 @@ class TorProcessProtocol(protocol.ProcessProtocol):
             Anything subprocess writes to stderr is sent to .write() on this
 
         :ivar tor_protocol: The TorControlProtocol instance connected
-            to the Tor this :api:`twisted.internet.protocol.ProcessProtocol <ProcessProtocol>`` is speaking to. Will be valid
+            to the Tor this :api:`twisted.internet.protocol.ProcessProtocol
+            <ProcessProtocol>`` is speaking to. Will be valid
             when the `connected_cb` callback runs.
 
         :ivar connected_cb: Triggered when the Tor process we
@@ -118,9 +109,12 @@ class TorProcessProtocol(protocol.ProcessProtocol):
         self._timeout_delayed_call = None
         if timeout:
             if not ireactortime:
-                raise RuntimeError('Must supply an IReactorTime object when supplying a timeout')
+                raise RuntimeError(
+                    'Must supply an IReactorTime object when supplying a '
+                    'timeout')
             ireactortime = IReactorTime(ireactortime)
-            self._timeout_delayed_call = ireactortime.callLater(timeout, self.timeout_expired)
+            self._timeout_delayed_call = ireactortime.callLater(
+                timeout, self.timeout_expired)
 
     def outReceived(self, data):
         """
@@ -165,7 +159,8 @@ class TorProcessProtocol(protocol.ProcessProtocol):
 
         if self.kill_on_stderr:
             self.transport.loseConnection()
-            raise RuntimeError("Received stderr output from slave Tor process: " + data)
+            raise RuntimeError(
+                "Received stderr output from slave Tor process: " + data)
 
     def cleanup(self):
         """
@@ -182,16 +177,19 @@ class TorProcessProtocol(protocol.ProcessProtocol):
 
         self.cleanup()
 
-        if isinstance(status.value, error.ProcessDone) and not self._did_timeout:
+        if isinstance(status.value,
+                      error.ProcessDone) and not self._did_timeout:
             return
 
         if status.value.exitCode is None:
             if self._did_timeout:
                 err = RuntimeError("Timeout waiting for Tor launch..")
             else:
-                err = RuntimeError("Tor was killed (%s)." % status.value.signal)
+                err = RuntimeError(
+                    "Tor was killed (%s)." % status.value.signal)
         else:
-            err = RuntimeError("Tor exited with error-code %d" % status.value.exitCode)
+            err = RuntimeError(
+                "Tor exited with error-code %d" % status.value.exitCode)
 
         log.err(err)
         if self.connected_cb:
@@ -242,12 +240,15 @@ class TorProcessProtocol(protocol.ProcessProtocol):
         if self.config is not None:
             self.config._update_proto(proto)
         self.tor_protocol.is_owned = self.transport.pid
-        self.tor_protocol.post_bootstrap.addCallback(self.protocol_bootstrapped).addErrback(self.tor_connection_failed)
+        self.tor_protocol.post_bootstrap.addCallback(
+            self.protocol_bootstrapped).addErrback(
+                self.tor_connection_failed)
 
     def protocol_bootstrapped(self, proto):
         txtorlog.msg("Protocol is bootstrapped")
 
-        self.tor_protocol.add_event_listener('STATUS_CLIENT', self.status_client)
+        self.tor_protocol.add_event_listener(
+            'STATUS_CLIENT', self.status_client)
 
         ## FIXME: should really listen for these to complete as well
         ## as bootstrap etc. For now, we'll be optimistic.
@@ -288,7 +289,8 @@ def launch_tor(config, reactor,
     :param connection_creator: is mostly available to ease testing, so
         you probably don't want to supply this. If supplied, it is a
         callable that should return a Deferred that delivers an
-        :api:`twisted.internet.interfaces.IProtocol <IProtocol>` or ConnectError.
+        :api:`twisted.internet.interfaces.IProtocol <IProtocol>` or
+        ConnectError.
         See :api:`twisted.internet.interfaces.IStreamClientEndpoint`.connect
 
     :param stdout: a file-like object to which we write anything that
@@ -301,10 +303,12 @@ def launch_tor(config, reactor,
 
     :return: a Deferred which callbacks with a TorProcessProtocol
         connected to the fully-bootstrapped Tor; this has a
-        :class:`txtorcon.TorControlProtocol` instance as `.tor_protocol`. In Tor,
-        ``__OwningControllerProcess`` will be set and TAKEOWNERSHIP will have
-        been called, so if you close the TorControlProtocol the Tor should
-        exit also (see `control-spec <https://gitweb.torproject.org/torspec.git/blob/HEAD:/control-spec.txt>`_ 3.23).
+        :class:`txtorcon.TorControlProtocol` instance as `.tor_protocol`. In
+        Tor, ``__OwningControllerProcess`` will be set and TAKEOWNERSHIP will
+        have been called, so if you close the TorControlProtocol the Tor should
+        exit also (see `control-spec
+        <https://gitweb.torproject.org/torspec.git/blob/HEAD:/control-spec.txt>`_
+        3.23).
 
     HACKS:
 
@@ -344,7 +348,8 @@ def launch_tor(config, reactor,
     # kwargs
     for arg in [stderr, stdout]:
         if arg and not getattr(arg, "write"):
-            raise RuntimeError('File-like object needed for stdout or stderr args.')
+            raise RuntimeError(
+                'File-like object needed for stdout or stderr args.')
 
     try:
         data_directory = config.DataDirectory
@@ -381,8 +386,9 @@ def launch_tor(config, reactor,
     # txtorlog.msg('Running with config:\n', open(torrc, 'r').read())
 
     if connection_creator is None:
-        connection_creator = functools.partial(TCP4ClientEndpoint(reactor, 'localhost', control_port).connect,
-                                               TorProtocolFactory())
+        connection_creator = functools.partial(
+            TCP4ClientEndpoint(reactor, 'localhost', control_port).connect,
+            TorProtocolFactory())
     process_protocol = TorProcessProtocol(connection_creator, progress_updates,
                                           config, reactor, timeout,
                                           kill_on_stderr,
@@ -414,7 +420,7 @@ def launch_tor(config, reactor,
                                          args=(tor_binary, '-f', torrc),
                                          env={'HOME': data_directory},
                                          path=data_directory)
-        #FIXME? don't need rest of the args: uid, gid, usePTY, childFDs)
+        # FIXME? don't need rest of the args: uid, gid, usePTY, childFDs)
         transport.closeStdin()
 
     except RuntimeError, e:
@@ -531,7 +537,8 @@ class LineList(TorConfigType):
     def validate(self, obj, instance, name):
         if not isinstance(obj, types.ListType):
             raise ValueError("Not valid for %s: %s" % (self.__class__, obj))
-        return _ListWrapper(obj, functools.partial(instance.mark_unsaved, name))
+        return _ListWrapper(
+            obj, functools.partial(instance.mark_unsaved, name))
 
 config_types = [Boolean, Boolean_Auto, LineList, Integer, SignedInteger, Port,
                 TimeInterval, TimeMsecInterval,
@@ -592,7 +599,8 @@ class HiddenService(object):
     To create an additional hidden service, append a new instance of
     this class to the config (ignore the conf argument)::
 
-    state.hiddenservices.append(HiddenService('/path/to/dir', ['80 127.0.0.1:1234']))
+    state.hiddenservices.append(HiddenService('/path/to/dir', ['80
+    127.0.0.1:1234']))
     """
 
     def __init__(self, config, thedir, ports, auth=None, ver=2):
@@ -622,8 +630,8 @@ class HiddenService(object):
 
         if not isinstance(ports, types.ListType):
             ports = [ports]
-        self.ports = _ListWrapper(ports, functools.partial(self.conf.mark_unsaved,
-                                                           'HiddenServices'))
+        self.ports = _ListWrapper(ports, functools.partial(
+            self.conf.mark_unsaved, 'HiddenServices'))
 
     def __setattr__(self, name, value):
         """
@@ -631,12 +639,12 @@ class HiddenService(object):
         HiddenServices as unsaved in our TorConfig object if anything
         is changed.
         """
-
-        if name in ['dir', 'version', 'authorize_client', 'ports'] and self.conf:
+        watched_params = ['dir', 'version', 'authorize_client', 'ports']
+        if name in watched_params and self.conf:
             self.conf.mark_unsaved('HiddenServices')
         if isinstance(value, types.ListType):
-            value = _ListWrapper(value, functools.partial(self.conf.mark_unsaved,
-                                                          'HiddenServices'))
+            value = _ListWrapper(value, functools.partial(
+                self.conf.mark_unsaved, 'HiddenServices'))
         self.__dict__[name] = value
 
     def __getattr__(self, name):
@@ -712,7 +720,8 @@ class TorConfig(object):
         if control is None:
             self._protocol = None
             self.__dict__['_slutty_'] = None
-            self.__dict__['config']['HiddenServices'] = _ListWrapper([], functools.partial(self.mark_unsaved, 'HiddenServices'))
+            self.__dict__['config']['HiddenServices'] = _ListWrapper(
+                [], functools.partial(self.mark_unsaved, 'HiddenServices'))
 
         else:
             self._protocol = ITorControlProtocol(control)
@@ -726,7 +735,8 @@ class TorConfig(object):
         self.post_bootstrap = defer.Deferred()
         if self.protocol:
             if self.protocol.post_bootstrap:
-                self.protocol.post_bootstrap.addCallback(self.bootstrap).addErrback(log.err)
+                self.protocol.post_bootstrap.addCallback(
+                    self.bootstrap).addErrback(log.err)
             else:
                 self.bootstrap()
 
@@ -766,7 +776,8 @@ class TorConfig(object):
 
     def _update_proto(self, proto):
         """
-        internal method, used by launch_tor to update the protocol after we're set up.
+        internal method, used by launch_tor to update the protocol after we're
+        set up.
         """
         self.__dict__['_protocol'] = proto
 
@@ -779,13 +790,17 @@ class TorConfig(object):
         attributes we need in the constructor without uusing __dict__
         all over the place.
         """
+        has_setup_attr = lambda o: '_setup_' in o.__dict__
+        has_slutty_attr = lambda o: '_slutty_' in o.__dict__
+        is_hidden_services = lambda s: s.lower() == "hiddenservices"
 
-        if '_setup_' in self.__dict__:
+        if has_setup_attr(self):
             name = self._find_real_name(name)
-            if '_slutty_' not in self.__dict__ and name.lower() != 'hiddenservices':
+            if not has_slutty_attr(self) and not is_hidden_services(name):
                 value = self.parsers[name].validate(value, self, name)
             if isinstance(value, types.ListType):
-                value = _ListWrapper(value, functools.partial(self.mark_unsaved, name))
+                value = _ListWrapper(
+                    value, functools.partial(self.mark_unsaved, name))
 
             name = self._find_real_name(name)
             self.unsaved[name] = value
@@ -845,9 +860,10 @@ class TorConfig(object):
              MidReplyLine = "650-" KEYWORD ["=" VALUE] CRLF
              EndReplyLine = "650 OK"
 
-          Tor configuration options have changed (such as via a SETCONF or RELOAD
-          signal). KEYWORD and VALUE specify the configuration option that was changed.
-          Undefined configuration options contain only the KEYWORD.
+          Tor configuration options have changed (such as via a SETCONF or
+          RELOAD signal). KEYWORD and VALUE specify the configuration option
+          that was changed.  Undefined configuration options contain only the
+          KEYWORD.
         """
 
         conf = parse_keywords(arg, multiline_values=False)
@@ -862,11 +878,14 @@ class TorConfig(object):
         pass an arg, it is ignored.
         '''
         try:
-            self.protocol.add_event_listener('CONF_CHANGED', self._conf_changed)
+            self.protocol.add_event_listener(
+                'CONF_CHANGED', self._conf_changed)
         except RuntimeError:
             ## for Tor versions which don't understand CONF_CHANGED
             ## there's nothing we can really do.
-            log.msg("Can't listen for CONF_CHANGED event; won't stay up-to-date with other clients.")
+            log.msg(
+                "Can't listen for CONF_CHANGED event; won't stay up-to-date "
+                "with other clients.")
         d = self.protocol.get_info_raw("config/names")
         d.addCallbacks(self._do_setup, log.err)
         d.addCallback(self.do_post_bootstrap)
@@ -964,7 +983,8 @@ class TorConfig(object):
             (name, value) = line.split()
             if name == 'HiddenServiceOptions':
                 ## set up the "special-case" hidden service stuff
-                servicelines = yield self.protocol.get_conf_raw('HiddenServiceOptions')
+                servicelines = yield self.protocol.get_conf_raw(
+                    'HiddenServiceOptions')
                 self._setup_hidden_services(servicelines)
                 continue
 
@@ -991,10 +1011,13 @@ class TorConfig(object):
             if value == 'LineList':
                 ## FIXME should move to the parse() method, but it
                 ## doesn't have access to conf object etc.
-                self.config[self._find_real_name(name)] = _ListWrapper(self.parsers[name].parse(v), functools.partial(self.mark_unsaved, name))
+                self.config[self._find_real_name(name)] = _ListWrapper(
+                    self.parsers[name].parse(v), functools.partial(
+                        self.mark_unsaved, name))
 
             else:
-                self.config[self._find_real_name(name)] = self.parsers[name].parse(v)
+                self.config[
+                    self._find_real_name(name)] = self.parsers[name].parse(v)
 
         # can't just return in @inlineCallbacks-decorated methods
         defer.returnValue(self)
@@ -1036,7 +1059,8 @@ class TorConfig(object):
             hs.append(HiddenService(self, directory, ports, auth, ver))
 
         name = 'HiddenServices'
-        self.config[name] = _ListWrapper(hs, functools.partial(self.mark_unsaved, name))
+        self.config[name] = _ListWrapper(
+            hs, functools.partial(self.mark_unsaved, name))
 
     def create_torrc(self):
         rtn = StringIO()

-- 
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/pkg-privacy/packages/txtorcon.git



More information about the Pkg-privacy-commits mailing list