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

Commit 5d3a25c

Browse files
committed
Merge pull request #141 from 8r2y5/master
[WIP] 8r2y5 Applied PEP8 standard on all plugins and occasionally did path.join refactorization.
2 parents 9669eb8 + 3c5d0ab commit 5d3a25c

69 files changed

Lines changed: 4279 additions & 2045 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: 24 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,31 +1,35 @@
1+
# encoding: utf-8
2+
3+
14
class BasePlugin(object):
25
"""
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()!
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()!
610
711
Note that only one instance of each plugin will be instantiated for *all*
812
connected clients. self.protocol will be changed by the plugin manager to
913
the current protocol.
1014
1115
You may access the factory if necessary via self.factory.protocols
12-
to access other clients, but this "Is Not A Very Good Idea" (tm)
16+
to access other clients, but this 'Is Not A Very Good Idea' (tm)
1317
1418
`name` *must* be defined in child classes or else the plugin manager will
1519
complain quite thoroughly.
1620
"""
1721

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

2327
def activate(self):
2428
"""
2529
Called when the plugins are activated, do any setup work here.
2630
"""
2731
self.active = True
28-
self.logger.debug("%s plugin object activated.", self.name)
32+
self.logger.debug('%s plugin object activated.', self.name)
2933
return True
3034

3135
def deactivate(self):
@@ -34,7 +38,7 @@ def deactivate(self):
3438
as it is likely that the plugin will soon be destroyed.
3539
"""
3640
self.active = False
37-
self.logger.debug("%s plugin object deactivated", self.name)
41+
self.logger.debug('%s plugin object deactivated', self.name)
3842
return True
3943

4044
def on_protocol_version(self, data):
@@ -368,7 +372,9 @@ def after_central_structure_update(self, data):
368372
return True
369373

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

373379

374380
class CommandNameError(Exception):
@@ -379,10 +385,10 @@ class CommandNameError(Exception):
379385

380386

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

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

config.py

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

810

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

1214
def __call__(cls, *args, **kwargs):
1315
if cls not in cls._instances:
14-
cls._instances[cls] = super(Singleton, cls).__call__(*args,
15-
**kwargs)
16+
cls._instances[cls] = super(Singleton, cls).__call__(
17+
*args, **kwargs
18+
)
1619
return cls._instances[cls]
1720

1821

1922
class ConfigurationManager(object):
2023
__metaclass__ = Singleton
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")
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')
2429
logfile_handle.setLevel(9)
2530
logger.addHandler(logfile_handle)
2631
logfile_handle.setFormatter(log_format)
2732

2833
def __init__(self):
29-
default_config_path = path.preauthChild("config/config.json.default")
30-
self.config_path = path.preauthChild("config/config.json")
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+
)
3140
if default_config_path.exists():
3241
try:
3342
with default_config_path.open() as default_config:
3443
default = json.load(default_config)
3544
except ValueError as e:
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." )
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+
)
3851
sys.exit()
3952
else:
40-
self.logger.critical("The configuration defaults file (config.json.default) doesn't exist! Shutting down.")
53+
self.logger.critical(
54+
'The configuration defaults file (config.json.default)'
55+
' doesn\'t exist! Shutting down.'
56+
)
4157
sys.exit()
4258

4359
if self.config_path.exists():
@@ -46,63 +62,95 @@ def __init__(self):
4662
config = json.load(c)
4763
self.config = recursive_dictionary_update(default, config)
4864
except ValueError as e:
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.")
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+
)
5171
sys.exit()
5272
else:
53-
self.logger.warning("The configuration file (config.json) doesn't exist! Creating one from defaults.")
73+
self.logger.warning(
74+
'The configuration file (config.json)'
75+
' doesn\'t exist! Creating one from defaults.'
76+
)
5477
try:
55-
with self.config_path.open("w") as f:
56-
json.dump(default, f, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii = False)
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+
)
5787
except IOError:
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...")
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...')
6094
sys.exit()
61-
self.logger.warning("StarryPy will now exit. Please examine config.json and adjust the variables appropriately.")
95+
self.logger.warning(
96+
'StarryPy will now exit. Please examine config.json '
97+
'and adjust the variables appropriately.'
98+
)
6299
sys.exit()
63100

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

67104
def save(self):
68105
try:
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))
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+
)
72117
except Exception as e:
73-
self.logger.critical("Tried to save the configuration file, failed.\n%s", str(e))
118+
self.logger.critical(
119+
'Tried to save the configuration file, failed.\n%s', str(e)
120+
)
74121
raise
75122

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

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]
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]
85131
else:
86132
return {}
87133

88134
else:
89135
if item in self.config:
90136
return self.config[item]
91137
else:
92-
self.logger.error("Couldn't find configuration option %s in configuration file.", item)
138+
self.logger.error(
139+
'Couldn\'t find configuration option %s in '
140+
'configuration file.', item
141+
)
93142
raise AttributeError
94143

95-
96144
def __setattr__(self, key, value):
97-
if key == "config":
145+
if key == 'config':
98146
super(ConfigurationManager, self).__setattr__(key, value)
99147
self.save()
100-
elif key == "config_path":
148+
elif key == 'config_path':
101149
super(ConfigurationManager, self).__setattr__(key, value)
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
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()
106154
else:
107155
self.config[key] = value
108156
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: 43 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,15 @@
66

77

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

2129
def __init__(self, protocol):
22-
self._stream = ""
30+
self._stream = ''
2331
self.id = None
2432
self.payload_size = None
2533
self.header_length = None
@@ -52,44 +60,62 @@ def start_packet(self):
5260
self.compressed = True
5361
else:
5462
self.compressed = False
55-
self.header_length = 1 + len(packets.SignedVLQ("").build(packet_header.payload_size))
63+
self.header_length = 1 + len(packets.SignedVLQ('').build(
64+
packet_header.payload_size)
65+
)
5666
self.packet_size = self.payload_size + self.header_length
5767
return True
5868
except RuntimeError:
59-
self.logger.error("Unknown error in start_packet.")
69+
self.logger.error('Unknown error in start_packet.')
6070
return False
6171

6272
def check_packet(self):
6373
try:
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:]
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:]
6680
if not self._stream:
67-
self._stream = ""
81+
self._stream = ''
6882
p_parsed = packets.packet().parse(p)
6983
if self.compressed:
7084
try:
7185
z = zlib.decompressobj()
7286
p_parsed.data = z.decompress(p_parsed.data)
7387
except zlib.error:
74-
self.logger.error("Decompression error in check_packet.")
75-
self.logger.debug("Parsed packet:")
88+
self.logger.error(
89+
'Decompression error in check_packet.'
90+
)
91+
self.logger.debug('Parsed packet:')
7692
self.logger.debug(pprint.pformat(p_parsed))
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")))
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+
)
81103
raise
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)
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+
)
84111

85112
self.compressed = False
86113
self.protocol.string_received(packet)
87114
self.reset()
88115
if self.start_packet():
89116
self.check_packet()
90117
except RuntimeError:
91-
self.logger.error("Unknown error in check_packet")
92-
#return False
118+
self.logger.error('Unknown error in check_packet')
93119

94120
def reset(self):
95121
self.id = None

0 commit comments

Comments
 (0)