Skip to content
This repository was archived by the owner on Apr 27, 2019. It is now read-only.

Commit b861a7c

Browse files
committed
Merge pull request #144 from StarryPy/revert-141-master
Revert "[WIP] Applied PEP8 standard on all plugins and occasionally d…
2 parents 5d3a25c + 96e923c commit b861a7c

69 files changed

Lines changed: 2045 additions & 4279 deletions

File tree

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

base_plugin.py

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,35 +1,31 @@
1-
# encoding: utf-8
2-
3-
41
class BasePlugin(object):
52
"""
6-
Defines an interface for all plugins to inherit from. Note that the
7-
__init__ method should generally not be overrode; all setup work should be
8-
done in activate() if possible. If you do override __init__, remember to
9-
super()!
3+
Defines an interface for all plugins to inherit from. Note that the __init__
4+
method should generally not be overrode; all setup work should be done in
5+
activate() if possible. If you do override __init__, remember to super()!
106
117
Note that only one instance of each plugin will be instantiated for *all*
128
connected clients. self.protocol will be changed by the plugin manager to
139
the current protocol.
1410
1511
You may access the factory if necessary via self.factory.protocols
16-
to access other clients, but this 'Is Not A Very Good Idea' (tm)
12+
to access other clients, but this "Is Not A Very Good Idea" (tm)
1713
1814
`name` *must* be defined in child classes or else the plugin manager will
1915
complain quite thoroughly.
2016
"""
2117

22-
name = 'Base Plugin'
23-
description = 'The common class for all plugins to inherit from.'
24-
version = '.1'
25-
depends = []
18+
name = "Base Plugin"
19+
description = "The common class for all plugins to inherit from."
20+
version = ".1"
21+
depends = []
2622

2723
def activate(self):
2824
"""
2925
Called when the plugins are activated, do any setup work here.
3026
"""
3127
self.active = True
32-
self.logger.debug('%s plugin object activated.', self.name)
28+
self.logger.debug("%s plugin object activated.", self.name)
3329
return True
3430

3531
def deactivate(self):
@@ -38,7 +34,7 @@ def deactivate(self):
3834
as it is likely that the plugin will soon be destroyed.
3935
"""
4036
self.active = False
41-
self.logger.debug('%s plugin object deactivated', self.name)
37+
self.logger.debug("%s plugin object deactivated", self.name)
4238
return True
4339

4440
def on_protocol_version(self, data):
@@ -372,9 +368,7 @@ def after_central_structure_update(self, data):
372368
return True
373369

374370
def __repr__(self):
375-
return '<Plugin instance: {} (version {})>'.format(
376-
self.name, self.version
377-
)
371+
return "<Plugin instance: %s (version %s)>" % (self.name, self.version)
378372

379373

380374
class CommandNameError(Exception):
@@ -385,10 +379,10 @@ class CommandNameError(Exception):
385379

386380

387381
class SimpleCommandPlugin(BasePlugin):
388-
name = 'simple_command_plugin'
389-
description = 'Provides a simple parent class to define chat commands.'
390-
version = '0.1'
391-
depends = ['command_plugin']
382+
name = "simple_command_plugin"
383+
description = "Provides a simple parent class to define chat commands."
384+
version = "0.1"
385+
depends = ["command_plugin"]
392386
commands = []
393387
command_aliases = {}
394388

@@ -397,9 +391,7 @@ def activate(self):
397391
for command in self.commands:
398392
f = getattr(self, command)
399393
if not callable(f):
400-
raise CommandNameError(
401-
'Could not find a method called {}'.format(command)
402-
)
394+
raise CommandNameError("Could not find a method called %s" % command)
403395
self.plugins['command_plugin'].register(f, command)
404396
for command, alias_list in self.command_aliases.iteritems():
405397
for alias in alias_list:

config.py

Lines changed: 37 additions & 85 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,6 @@
33
import logging
44
import inspect
55
import sys
6-
import os
7-
86
from utility_functions import recursive_dictionary_update, path
97

108

@@ -13,47 +11,33 @@ class Singleton(type):
1311

1412
def __call__(cls, *args, **kwargs):
1513
if cls not in cls._instances:
16-
cls._instances[cls] = super(Singleton, cls).__call__(
17-
*args, **kwargs
18-
)
14+
cls._instances[cls] = super(Singleton, cls).__call__(*args,
15+
**kwargs)
1916
return cls._instances[cls]
2017

2118

2219
class ConfigurationManager(object):
2320
__metaclass__ = Singleton
24-
logger = logging.getLogger('starrypy.config.ConfigurationManager')
25-
log_format = logging.Formatter(
26-
'%(asctime)s - %(levelname)s - %(name)s # %(message)s'
27-
)
28-
logfile_handle = logging.FileHandler('config.log')
21+
logger = logging.getLogger("starrypy.config.ConfigurationManager")
22+
log_format = logging.Formatter('%(asctime)s - %(levelname)s - %(name)s # %(message)s')
23+
logfile_handle = logging.FileHandler("config.log")
2924
logfile_handle.setLevel(9)
3025
logger.addHandler(logfile_handle)
3126
logfile_handle.setFormatter(log_format)
3227

3328
def __init__(self):
34-
default_config_path = path.preauthChild(
35-
os.path.join('config', 'config.json.default')
36-
)
37-
self.config_path = path.preauthChild(
38-
os.path.join('config', 'config.json')
39-
)
29+
default_config_path = path.preauthChild("config/config.json.default")
30+
self.config_path = path.preauthChild("config/config.json")
4031
if default_config_path.exists():
4132
try:
4233
with default_config_path.open() as default_config:
4334
default = json.load(default_config)
4435
except ValueError as e:
45-
print 'Error: %s' % e
46-
self.logger.critical(
47-
'The configuration defaults file (config.json.default) '
48-
'contains invalid JSON. Please run it against a JSON '
49-
'linter, such as http://jsonlint.com. Shutting down.'
50-
)
36+
print "Error: %s" % e
37+
self.logger.critical("The configuration defaults file (config.json.default) contains invalid JSON. Please run it against a JSON linter, such as http://jsonlint.com. Shutting down." )
5138
sys.exit()
5239
else:
53-
self.logger.critical(
54-
'The configuration defaults file (config.json.default)'
55-
' doesn\'t exist! Shutting down.'
56-
)
40+
self.logger.critical("The configuration defaults file (config.json.default) doesn't exist! Shutting down.")
5741
sys.exit()
5842

5943
if self.config_path.exists():
@@ -62,95 +46,63 @@ def __init__(self):
6246
config = json.load(c)
6347
self.config = recursive_dictionary_update(default, config)
6448
except ValueError as e:
65-
print 'Error: %s' % e
66-
self.logger.critical(
67-
'The configuration file (config.json) contains invalid '
68-
'JSON. Please run it against a JSON linter, such as '
69-
'http://jsonlint.com. Shutting down.'
70-
)
49+
print "Error: %s" % e
50+
self.logger.critical("The configuration file (config.json) contains invalid JSON. Please run it against a JSON linter, such as http://jsonlint.com. Shutting down.")
7151
sys.exit()
7252
else:
73-
self.logger.warning(
74-
'The configuration file (config.json)'
75-
' doesn\'t exist! Creating one from defaults.'
76-
)
53+
self.logger.warning("The configuration file (config.json) doesn't exist! Creating one from defaults.")
7754
try:
78-
with self.config_path.open('w') as f:
79-
json.dump(
80-
default,
81-
f,
82-
indent=4,
83-
separators=(',', ': '),
84-
sort_keys=True,
85-
ensure_ascii=False
86-
)
55+
with self.config_path.open("w") as f:
56+
json.dump(default, f, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii = False)
8757
except IOError:
88-
self.logger.critical(
89-
'Couldn\'t write a default configuration file. '
90-
'Please check that StarryPy has write access in the '
91-
'config/ directory.'
92-
)
93-
self.logger.critical('Exiting...')
58+
self.logger.critical("Couldn't write a default configuration file. Please check that StarryPy has write access in the config/ directory.")
59+
self.logger.critical("Exiting...")
9460
sys.exit()
95-
self.logger.warning(
96-
'StarryPy will now exit. Please examine config.json '
97-
'and adjust the variables appropriately.'
98-
)
61+
self.logger.warning("StarryPy will now exit. Please examine config.json and adjust the variables appropriately.")
9962
sys.exit()
10063

101-
self.logger.debug('Created configuration manager.')
64+
self.logger.debug("Created configuration manager.")
10265
self.save()
10366

10467
def save(self):
10568
try:
106-
with io.open(self.config_path.path, 'w') as config:
107-
self.logger.debug('Writing configuration file.')
108-
config.write(
109-
json.dumps(
110-
self.config,
111-
indent=4,
112-
separators=(',', ': '),
113-
sort_keys=True,
114-
ensure_ascii=False
115-
)
116-
)
69+
with io.open(self.config_path.path, "w", encoding="utf-8") as config:
70+
self.logger.debug("Writing configuration file.")
71+
config.write(json.dumps(self.config, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii=False))
11772
except Exception as e:
118-
self.logger.critical(
119-
'Tried to save the configuration file, failed.\n%s', str(e)
120-
)
73+
self.logger.critical("Tried to save the configuration file, failed.\n%s", str(e))
12174
raise
12275

12376
def __getattr__(self, item):
124-
if item in ['config', 'config_path']:
77+
if item in ["config", "config_path"]:
12578
return super(ConfigurationManager, self).__getattribute__(item)
12679

127-
elif item == 'plugin_config':
128-
caller = inspect.stack()[1][0].f_locals['self'].__class__.name
129-
if caller in self.config['plugin_config']:
130-
return self.config['plugin_config'][caller]
80+
81+
elif item == "plugin_config":
82+
caller = inspect.stack()[1][0].f_locals["self"].__class__.name
83+
if caller in self.config["plugin_config"]:
84+
return self.config["plugin_config"][caller]
13185
else:
13286
return {}
13387

13488
else:
13589
if item in self.config:
13690
return self.config[item]
13791
else:
138-
self.logger.error(
139-
'Couldn\'t find configuration option %s in '
140-
'configuration file.', item
141-
)
92+
self.logger.error("Couldn't find configuration option %s in configuration file.", item)
14293
raise AttributeError
14394

95+
14496
def __setattr__(self, key, value):
145-
if key == 'config':
97+
if key == "config":
14698
super(ConfigurationManager, self).__setattr__(key, value)
14799
self.save()
148-
elif key == 'config_path':
100+
elif key == "config_path":
149101
super(ConfigurationManager, self).__setattr__(key, value)
150-
elif key == 'plugin_config':
151-
caller = inspect.stack()[1][0].f_locals['self'].__class__.name
152-
self.config['plugin_config'][caller] = value
153-
self.save()
102+
elif key == "plugin_config":
103+
caller = inspect.stack()[1][0].f_locals["self"].__class__.name
104+
self.config["plugin_config"][caller] = value
105+
self.save
154106
else:
155107
self.config[key] = value
156108
self.save()

config/config.json.default

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
2-
"backup_db": ["backups", "backups.db"],
2+
"backup_db": "backups/backups.db",
33
"bind_address": "",
44
"bind_port": 21025,
55
"chat_prefix": "#",

packet_stream.py

Lines changed: 17 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,7 @@
66

77

88
class Packet(object):
9-
def __init__(
10-
self,
11-
packet_id,
12-
payload_size,
13-
data,
14-
original_data,
15-
direction,
16-
compressed=False
17-
):
9+
def __init__(self, packet_id, payload_size, data, original_data, direction, compressed=False):
1810
self.id = packet_id
1911
self.payload_size = payload_size
2012
self.data = data
@@ -27,7 +19,7 @@ class PacketStream(object):
2719
logger = logging.getLogger('starrypy.packet_stream.PacketStream')
2820

2921
def __init__(self, protocol):
30-
self._stream = ''
22+
self._stream = ""
3123
self.id = None
3224
self.payload_size = None
3325
self.header_length = None
@@ -60,62 +52,44 @@ def start_packet(self):
6052
self.compressed = True
6153
else:
6254
self.compressed = False
63-
self.header_length = 1 + len(packets.SignedVLQ('').build(
64-
packet_header.payload_size)
65-
)
55+
self.header_length = 1 + len(packets.SignedVLQ("").build(packet_header.payload_size))
6656
self.packet_size = self.payload_size + self.header_length
6757
return True
6858
except RuntimeError:
69-
self.logger.error('Unknown error in start_packet.')
59+
self.logger.error("Unknown error in start_packet.")
7060
return False
7161

7262
def check_packet(self):
7363
try:
74-
if (
75-
self.packet_size is not None and
76-
len(self._stream) >= self.packet_size
77-
):
78-
p = self._stream[:self.packet_size]
79-
self._stream = self._stream[self.packet_size:]
64+
if self.packet_size is not None and len(self._stream) >= self.packet_size:
65+
p, self._stream = self._stream[:self.packet_size], self._stream[self.packet_size:]
8066
if not self._stream:
81-
self._stream = ''
67+
self._stream = ""
8268
p_parsed = packets.packet().parse(p)
8369
if self.compressed:
8470
try:
8571
z = zlib.decompressobj()
8672
p_parsed.data = z.decompress(p_parsed.data)
8773
except zlib.error:
88-
self.logger.error(
89-
'Decompression error in check_packet.'
90-
)
91-
self.logger.debug('Parsed packet:')
74+
self.logger.error("Decompression error in check_packet.")
75+
self.logger.debug("Parsed packet:")
9276
self.logger.debug(pprint.pformat(p_parsed))
93-
self.logger.debug('Packet data:')
94-
self.logger.debug(
95-
pprint.pformat(
96-
p_parsed.original_data.encode('hex')
97-
)
98-
)
99-
self.logger.debug('Following packet data:')
100-
self.logger.debug(
101-
pprint.pformat(self._stream.encode('hex'))
102-
)
77+
self.logger.debug("Packet data:")
78+
self.logger.debug(pprint.pformat(p_parsed.original_data.encode("hex")))
79+
self.logger.debug("Following packet data:")
80+
self.logger.debug(pprint.pformat(self._stream.encode("hex")))
10381
raise
104-
packet = Packet(
105-
packet_id=p_parsed.id,
106-
payload_size=p_parsed.payload_size,
107-
data=p_parsed.data,
108-
original_data=p,
109-
direction=self.direction
110-
)
82+
packet = Packet(packet_id=p_parsed.id, payload_size=p_parsed.payload_size, data=p_parsed.data,
83+
original_data=p, direction=self.direction)
11184

11285
self.compressed = False
11386
self.protocol.string_received(packet)
11487
self.reset()
11588
if self.start_packet():
11689
self.check_packet()
11790
except RuntimeError:
118-
self.logger.error('Unknown error in check_packet')
91+
self.logger.error("Unknown error in check_packet")
92+
#return False
11993

12094
def reset(self):
12195
self.id = None

0 commit comments

Comments
 (0)