Skip to content

Commit

Permalink
Code cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
AcidWeb committed Apr 13, 2024
1 parent 9ba8187 commit dfb46f0
Show file tree
Hide file tree
Showing 7 changed files with 42 additions and 43 deletions.
4 changes: 4 additions & 0 deletions .ruff.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
line-length = 120
target-version = "py312"

[lint]
select = ["A", "B", "C4", "E", "F", "I", "PIE", "RUF", "TRY", "UP", "W"]
ignore = ["I001", "TRY003"]

[format]
quote-style = "single"
13 changes: 5 additions & 8 deletions CB/Core.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def init_config(self):
if os.path.isfile(Path('WTF/CurseBreaker.cache')):
os.remove(Path('WTF/CurseBreaker.cache'))
if os.path.isfile(self.configPath):
with open(self.configPath, 'r') as f:
with open(self.configPath) as f:
try:
self.config = json.load(f)
except (StopIteration, UnicodeDecodeError, json.JSONDecodeError) as e:
Expand Down Expand Up @@ -155,7 +155,7 @@ def update_config(self):

def check_if_installed(self, url):
for addon in self.config['Addons']:
if addon['URL'] == url or addon['Name'] == url:
if url in (addon['URL'], addon['Name']):
return addon

def check_if_installed_dirs(self, directories):
Expand Down Expand Up @@ -307,10 +307,7 @@ def update_addon(self, url, update, force):
dev = self.check_if_dev(old['URL'])
blocked = self.check_if_blocked(old)
oldversion = old['Version']
if old['URL'] in self.checksumCache:
modified = self.checksumCache[old['URL']]
else:
modified = self.check_checksum(old)[1]
modified = self.checksumCache[old['URL']] if old['URL'] in self.checksumCache else self.check_checksum(old)[1]
if old['URL'].startswith(('https://www.townlong-yak.com/addons/',
'https://www.curseforge.com/wow/addons/',
'https://www.tukui.org/')):
Expand Down Expand Up @@ -454,7 +451,7 @@ def find_orphans(self):
elif directory not in ignored:
orphanedaddon.append(directory)
directories += directoriesspecial + orphanedaddon
for root, dirs, files in os.walk('WTF/', followlinks=True):
for root, _, files in os.walk('WTF/', followlinks=True):
for f in files:
if 'Blizzard_' not in f and f.endswith('.lua'):
name = os.path.splitext(f)[0]
Expand Down Expand Up @@ -684,7 +681,7 @@ def parse_file(self, target):
if f.is_file():
self.filesToHash.append(f)
if not f.name.lower().endswith('.lua'):
with open(f, 'r', encoding='utf-8', errors='ignore') as g:
with open(f, encoding='utf-8', errors='ignore') as g:
newfilestoparse = None
data = g.read()
if f.name.lower().endswith('.toc'):
Expand Down
40 changes: 20 additions & 20 deletions CB/Wago.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, accountname):
self.parse_storage()

def parse_storage(self):
with open(Path(f'WTF/Account/{self.accountName}/SavedVariables/WeakAuras.lua'), 'r', encoding='utf-8',
with open(Path(f'WTF/Account/{self.accountName}/SavedVariables/WeakAuras.lua'), encoding='utf-8',
errors='ignore') as file:
data = file.read().replace('WeakAurasSaved = {', '{')
wadata = loads(data)
Expand Down Expand Up @@ -81,7 +81,7 @@ def parse_storage_internal(self, data):
self.list[search.group(1)] = int(search.group(2))

def parse_storage(self):
with open(Path(f'WTF/Account/{self.accountName}/SavedVariables/Plater.lua'), 'r', encoding='utf-8',
with open(Path(f'WTF/Account/{self.accountName}/SavedVariables/Plater.lua'), encoding='utf-8',
errors='ignore') as file:
data = file.read()
platerdata = loads(re.search(r'PlaterDB = {\n.*?}\n', data, re.DOTALL).group().replace('PlaterDB = {', '{', 1))
Expand Down Expand Up @@ -184,24 +184,24 @@ def update_entry(self, entry, addon):

def install_data(self, wadata, platerdata):
with open(Path('Interface/AddOns/CurseBreakerCompanion/Data.lua'), 'w', newline='\n', encoding='utf-8') as out:
out.write(('CurseBreakerCompanion = {\n'
' WeakAuras = {\n'
' slugs = {\n'
f'{"".join(str(x) for x in wadata["slugs"])}'
' },\n'
' stash = {\n'
f'{"".join(str(x) for x in wadata["stash"])}'
' },\n'
' },\n'
' Plater = {\n'
' slugs = {\n'
f'{"".join(str(x) for x in platerdata["slugs"])}'
' },\n'
' stash = {\n'
f'{"".join(str(x) for x in platerdata["stash"])}'
' },\n'
' },\n'
'}'))
out.write('CurseBreakerCompanion = {\n'
' WeakAuras = {\n'
' slugs = {\n'
f'{"".join(str(x) for x in wadata["slugs"])}'
' },\n'
' stash = {\n'
f'{"".join(str(x) for x in wadata["stash"])}'
' },\n'
' },\n'
' Plater = {\n'
' slugs = {\n'
f'{"".join(str(x) for x in platerdata["slugs"])}'
' },\n'
' stash = {\n'
f'{"".join(str(x) for x in platerdata["stash"])}'
' },\n'
' },\n'
'}')

def install_companion(self, force):
target_path = Path('Interface/AddOns/CurseBreakerCompanion')
Expand Down
2 changes: 1 addition & 1 deletion CB/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ def retry(custom_error=False):
def wraps(func):
def inner(*args, **kwargs):
description = None
for i in range(2):
for _ in range(2):
try:
result = func(*args, **kwargs)
except KeyboardInterrupt:
Expand Down
20 changes: 8 additions & 12 deletions CurseBreaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ def start(self): # sourcery skip: low-code-quality
with open('PermissionTest', 'w') as _:
pass
os.remove('PermissionTest')
except IOError:
except OSError:
self.handle_shutdown('[bold red]CurseBreaker doesn\'t have write rights for the current directory.\nTry sta'
'rting it with administrative privileges.[/bold red]\n')
# Application auto update and initialization
Expand Down Expand Up @@ -272,7 +272,7 @@ def auto_update(self):
except Exception as e:
if os.path.isfile(f'{sys.executable}.old'):
shutil.move(f'{sys.executable}.old', sys.executable)
self.console.print(f'[bold red]Update failed!\n\nReason: {str(e)}[/bold red]\n')
self.console.print(f'[bold red]Update failed!\n\nReason: {e!s}[/bold red]\n')
self._auto_update_cleanup()
sys.exit(1)

Expand Down Expand Up @@ -365,9 +365,8 @@ def print_author_reminder(self):
def setup_console(self):
if self.headless:
self.console = Console(record=True)
if self.os == 'Windows':
if window := windll.kernel32.GetConsoleWindow():
windll.user32.ShowWindow(window, 0)
if self.os == 'Windows' and (window := windll.kernel32.GetConsoleWindow()):
windll.user32.ShowWindow(window, 0)
elif detect_legacy_windows():
set_terminal_size(100, 50)
windll.kernel32.SetConsoleScreenBufferSize(windll.kernel32.GetStdHandle(-11), wintypes._COORD(100, 200))
Expand Down Expand Up @@ -412,7 +411,7 @@ def setup_completer(self):
'autoupdate': None,
'autoupdate_delay': None,
'backup': None,
'channel': WordCompleter(addons + ['global'], ignore_case=True, sentence=True),
'channel': WordCompleter([*addons, 'global'], ignore_case=True, sentence=True),
'compact_mode': None,
'pinning': WordCompleter(addons, ignore_case=True, sentence=True),
'sources': None,
Expand Down Expand Up @@ -489,12 +488,12 @@ def c_install(self, args):
optignore = True
args = args.replace('-i', '', 1)
args = re.sub(r'([a-zA-Z0-9_:])( +)([a-zA-Z0-9_:])', r'\1,\3', args)
addons = [re.sub(r'[\[\]]', '', addon).strip() for addon in list(reader([args], skipinitialspace=True))[0]]
addons = [re.sub(r'[\[\]]', '', addon).strip() for addon in next(iter(reader([args], skipinitialspace=True)))]
exceptions = []
if addons:
if self.core.clientType != 'retail':
for addon in addons:
if addon.startswith('https://www.wowinterface.com/downloads/') or addon.startswith('wowi:'):
if addon.startswith(('https://www.wowinterface.com/downloads/', 'wowi:')):
self.console.print('[yellow][WARNING][/yellow] WoWInterface support for non-retail clients is l'
'imited. If the selected project offers multiple downloads this application '
'will always install the retail version of the addon.')
Expand Down Expand Up @@ -550,10 +549,7 @@ def c_uninstall(self, args):
def _c_update_process(self, addon, update, force, compact, compacted, provider): # sourcery skip: low-code-quality
name, authors, versionnew, versionold, uiversion, modified, blocked, source, sourceurl, changelog, dstate \
= self.core.update_addon(addon if isinstance(addon, str) else addon['URL'], update, force)
if source == 'Unsupported' and not provider:
additionalstatus = f' [bold red]{source.upper()}[/bold red]'
else:
additionalstatus = ''
additionalstatus = f' [bold red]{source.upper()}[/bold red]' if source == 'Unsupported' and not provider else ''
if versionold:
payload = [self.parse_link(name, sourceurl, authors=authors),
self.parse_link(versionold, changelog, dstate, uiversion=uiversion)]
Expand Down
3 changes: 2 additions & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ name = "pypi"
python-dateutil = "*"
prompt-toolkit = "*"
rich_pixels = "*"
checksumdir = {ref = "replace-pkg-resources", git = "git+https://github.com/idahogray/checksumdir"}
checksumdir = "*"
setuptools = "*"
packaging = "*"
pyperclip = "*"
markdown = "*"
Expand Down
3 changes: 2 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
python-dateutil
prompt-toolkit
rich_pixels
checksumdir @ git+https://github.com/idahogray/checksumdir@replace-pkg-resources
checksumdir
setuptools
packaging
pyperclip
markdown
Expand Down

0 comments on commit dfb46f0

Please sign in to comment.