Skip to content

Commit 395daa2

Browse files
committed
Refactor code for better readability
1 parent 7aef457 commit 395daa2

File tree

1 file changed

+35
-19
lines changed

1 file changed

+35
-19
lines changed

cogs/plugins.py

Lines changed: 35 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,7 @@ async def populate_registry(self):
4949

5050
@staticmethod
5151
def _asubprocess_run(cmd):
52-
return subprocess.run(cmd, shell=True, check=True,
53-
capture_output=True)
52+
return subprocess.run(cmd, shell=True, check=True, capture_output=True)
5453

5554
@staticmethod
5655
def parse_plugin(name):
@@ -60,10 +59,12 @@ def parse_plugin(name):
6059
result[2] = '/'.join(result[2:])
6160
except IndexError:
6261
return None
62+
6363
return tuple(result)
6464

6565
async def download_initial_plugins(self):
6666
await self.bot._connected.wait()
67+
6768
for i in self.bot.config.plugins:
6869
parsed_plugin = self.parse_plugin(i)
6970

@@ -78,29 +79,29 @@ async def download_initial_plugins(self):
7879
except DownloadError as exc:
7980
msg = f'{parsed_plugin[0]}/{parsed_plugin[1]} - {exc}'
8081
logger.error(error(msg))
82+
8183
await async_all(env() for env in self.bot.extra_events.get('on_plugin_ready', []))
84+
8285
logger.debug(info('on_plugin_ready called.'))
8386

8487
async def download_plugin_repo(self, username, repo):
8588
try:
8689
cmd = f'git clone https://github.com/{username}/{repo} '
8790
cmd += f'plugins/{username}-{repo} -q'
88-
await self.bot.loop.run_in_executor(
89-
None,
90-
self._asubprocess_run,
91-
cmd
92-
)
91+
92+
await self.bot.loop.run_in_executor(None, self._asubprocess_run, cmd)
9393
# -q (quiet) so there's no terminal output unless there's an error
9494
except subprocess.CalledProcessError as exc:
9595
err = exc.stderr.decode('utf-8').strip()
96-
if not err.endswith('already exists and is '
97-
'not an empty directory.'):
96+
97+
if not err.endswith('already exists and is not an empty directory.'):
9898
# don't raise error if the plugin folder exists
9999
raise DownloadError(error) from exc
100100

101101
async def load_plugin(self, username, repo, plugin_name):
102102
ext = f'plugins.{username}-{repo}.{plugin_name}.{plugin_name}'
103103
dirname = f'plugins/{username}-{repo}/{plugin_name}'
104+
104105
if 'requirements.txt' in os.listdir(dirname):
105106
# Install PIP requirements
106107
try:
@@ -113,6 +114,7 @@ async def load_plugin(self, username, repo, plugin_name):
113114
# so there's no terminal output unless there's an error
114115
except subprocess.CalledProcessError as exc:
115116
err = exc.stderr.decode('utf8').strip()
117+
116118
if err:
117119
raise DownloadError(
118120
f'Unable to download requirements: ```\n{error}\n```'
@@ -135,28 +137,33 @@ async def load_plugin(self, username, repo, plugin_name):
135137
@checks.has_permissions(PermissionLevel.OWNER)
136138
async def plugin(self, ctx):
137139
"""Plugin handler. Controls the plugins in the bot."""
140+
138141
await ctx.send_help(ctx.command)
139142

140143
@plugin.command(name='add', aliases=['install'])
141144
@checks.has_permissions(PermissionLevel.OWNER)
142145
async def plugin_add(self, ctx, *, plugin_name: str):
143146
"""Add a plugin."""
147+
144148
if plugin_name in self.registry:
145149
info = self.registry[plugin_name]
146150
plugin_name = info['repository'] + '/' + plugin_name
147151
required_version = info['bot_version']
152+
148153
if parse_version(self.bot.version) < parse_version(required_version):
149154
em = discord.Embed(
150155
description=f'Your bot\'s version is too low. This plugin requires version `{required_version}`.',
151156
color=self.bot.main_color
152157
)
153158
return await ctx.send(embed=em)
159+
154160
if plugin_name in self.bot.config.plugins:
155161
em = discord.Embed(
156162
description='This plugin is already installed.',
157163
color=self.bot.main_color
158164
)
159165
return await ctx.send(embed=em)
166+
160167
if plugin_name in self.bot.cogs.keys():
161168
# another class with the same name
162169
em = discord.Embed(
@@ -170,6 +177,7 @@ async def plugin_add(self, ctx, *, plugin_name: str):
170177
color=self.bot.main_color
171178
)
172179
message = await ctx.send(embed=em)
180+
173181
async with ctx.typing():
174182
if len(plugin_name.split('/')) >= 3:
175183
parsed_plugin = self.parse_plugin(plugin_name)
@@ -184,6 +192,7 @@ async def plugin_add(self, ctx, *, plugin_name: str):
184192
return await ctx.send(embed=em)
185193

186194
importlib.invalidate_caches()
195+
187196
try:
188197
await self.load_plugin(*parsed_plugin)
189198
except DownloadError as exc:
@@ -216,15 +225,16 @@ async def plugin_add(self, ctx, *, plugin_name: str):
216225
@checks.has_permissions(PermissionLevel.OWNER)
217226
async def plugin_remove(self, ctx, *, plugin_name: str):
218227
"""Remove a plugin."""
228+
219229
if plugin_name in self.registry:
220230
info = self.registry[plugin_name]
221231
plugin_name = info['repository'] + '/' + plugin_name
232+
222233
if plugin_name in self.bot.config.plugins:
223234
try:
224235
username, repo, name = self.parse_plugin(plugin_name)
225-
self.bot.unload_extension(
226-
f'plugins.{username}-{repo}.{name}.{name}'
227-
)
236+
237+
self.bot.unload_extension(f'plugins.{username}-{repo}.{name}.{name}')
228238
except Exception:
229239
pass
230240

@@ -240,14 +250,14 @@ def onerror(func, path, exc_info): # pylint: disable=W0613
240250
os.chmod(path, stat.S_IWUSR)
241251
func(path)
242252

243-
shutil.rmtree(f'plugins/{username}-{repo}',
244-
onerror=onerror)
253+
shutil.rmtree(f'plugins/{username}-{repo}', onerror=onerror)
245254
except Exception as exc:
246255
logger.error(str(exc))
247256
self.bot.config.plugins.append(plugin_name)
248257
raise exc
249258

250259
await self.bot.config.update()
260+
251261
em = discord.Embed(
252262
description='The plugin is uninstalled and all it\'s data is erased.',
253263
color=self.bot.main_color
@@ -264,9 +274,11 @@ def onerror(func, path, exc_info): # pylint: disable=W0613
264274
@checks.has_permissions(PermissionLevel.OWNER)
265275
async def plugin_update(self, ctx, *, plugin_name: str):
266276
"""Update a plugin."""
277+
267278
if plugin_name in self.registry:
268279
info = self.registry[plugin_name]
269280
plugin_name = info['repository'] + '/' + plugin_name
281+
270282
if plugin_name not in self.bot.config.plugins:
271283
em = discord.Embed(
272284
description='That plugin is not installed.',
@@ -276,22 +288,22 @@ async def plugin_update(self, ctx, *, plugin_name: str):
276288

277289
async with ctx.typing():
278290
username, repo, name = self.parse_plugin(plugin_name)
291+
279292
try:
280293
cmd = f'cd plugins/{username}-{repo} && git pull'
281-
cmd = await self.bot.loop.run_in_executor(
282-
None,
283-
self._asubprocess_run,
284-
cmd
285-
)
294+
cmd = await self.bot.loop.run_in_executor(None, self._asubprocess_run, cmd)
286295
except subprocess.CalledProcessError as exc:
287296
err = exc.stderr.decode('utf8').strip()
297+
288298
em = discord.Embed(
289299
description=f'An error occured while updating: {err}.',
290300
color=self.bot.main_color
291301
)
292302
await ctx.send(embed=em)
303+
293304
else:
294305
output = cmd.stdout.decode('utf8').strip()
306+
295307
em = discord.Embed(
296308
description='```\n{output}\n```',
297309
color=self.bot.main_color
@@ -302,6 +314,7 @@ async def plugin_update(self, ctx, *, plugin_name: str):
302314
# repo was updated locally, now perform the cog reload
303315
ext = f'plugins.{username}-{repo}.{name}.{name}'
304316
self.bot.unload_extension(ext)
317+
305318
try:
306319
await self.load_plugin(username, repo, name)
307320
except DownloadError as exc:
@@ -315,6 +328,7 @@ async def plugin_update(self, ctx, *, plugin_name: str):
315328
@checks.has_permissions(PermissionLevel.OWNER)
316329
async def plugin_enabled(self, ctx):
317330
"""Shows a list of currently enabled plugins."""
331+
318332
if self.bot.config.plugins:
319333
msg = '```\n' + '\n'.join(self.bot.config.plugins) + '\n```'
320334
em = discord.Embed(
@@ -358,8 +372,10 @@ def find_index(name):
358372
)
359373

360374
matches = get_close_matches(plugin_name, self.registry.keys())
375+
361376
if matches:
362377
em.add_field(name='Perhaps you meant', value='\n'.join(f'`{m}`' for m in matches))
378+
363379
return await ctx.send(embed=em)
364380

365381
for name, info in registry:

0 commit comments

Comments
 (0)