Skip to content

Commit 132d70b

Browse files
committed
chore: Tidy code
1 parent c72b407 commit 132d70b

7 files changed

+71
-111
lines changed

plugin/dir_format.py

+24-41
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,8 @@ def __enter__(self):
4444

4545
def __exit__(self, exc_type, exc_value, exc_traceback):
4646
if exc_type:
47-
class_name = self.__class__.__name__
48-
log.error('Error occurred in %s while exiting: %s\n%s', class_name, exc_value, ''.join(traceback.format_tb(exc_traceback)))
49-
return False # return True to suppress exceptions
47+
log.error('Error in %s while exiting: %s\n%s', self.__class__.__name__, exc_value, ''.join(traceback.format_tb(exc_traceback)))
48+
return False
5049

5150
def run(self):
5251
self.start_timer()
@@ -61,13 +60,12 @@ def run(self):
6160
try:
6261
cwd = self.get_current_working_directory()
6362
filelist = self.get_recursive_files(cwd)
64-
6563
self.prepare_context(cwd, filelist)
6664
self.process_files()
6765
except Exception as e:
6866
self.handle_error(e)
6967
except Exception as e:
70-
log.error('Error occurred during dir formatting: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))
68+
log.error('Error during dir formatting: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))
7169

7270
@staticmethod
7371
def stop():
@@ -96,12 +94,9 @@ def end_timer(self):
9694
if START_TIME is None:
9795
log.warning('Timer was not started.')
9896
return 'N/A'
99-
100-
end_time = perf_counter()
101-
elapsed_time = end_time - START_TIME
102-
formatted_time = self.format_elapsed_time(elapsed_time)
97+
elapsed_time = perf_counter() - START_TIME
10398
START_TIME = None
104-
return '{}'.format(formatted_time)
99+
return self.format_elapsed_time(elapsed_time)
105100

106101
def get_current_working_directory(self):
107102
return PathHandler.get_pathinfo(view=self.view, path=self.view.file_name())['cwd']
@@ -159,35 +154,32 @@ def format_next_file(self, new_view, is_ready=False):
159154

160155
def _on_format_completed(self, new_view, is_ready, is_success):
161156
self.post_dir_format(new_view, is_success)
157+
162158
if is_ready and is_success:
163159
new_view.run_command('undo') # entry_view
164160
elif self.CONTEXT['entry_view'] != new_view:
165161
new_view.set_scratch(True)
166162
new_view.close()
167163

168164
if self.CONTEXT['current_index'] == self.CONTEXT['filelist_length']:
169-
# Handle the last file
170-
self.handle_formatting_completion()
171-
172-
self.open_next_file()
165+
self.handle_formatting_completion() # handle the last file
166+
else:
167+
self.open_next_file()
173168

174169
def post_dir_format(self, new_view, is_success):
175170
new_cwd = self.get_post_format_cwd(is_success)
176-
self.show_result(is_success)
171+
self.update_status(is_success)
177172
self.save_formatted_file(new_view, new_cwd, is_success)
178173

179174
def get_post_format_cwd(self, is_success):
180175
base_directory = self.CONTEXT['cwd']
181176
sub_directory = RECURSIVE_SUCCESS_DIRECTORY if is_success else RECURSIVE_FAILURE_DIRECTORY
182177
return os.path.join(base_directory, sub_directory)
183178

184-
def show_result(self, is_success):
185-
if is_success:
186-
self.CONTEXT['success_count'] += 1
187-
log.status('🎉 Formatting successful. 🥳✨\n')
188-
else:
189-
self.CONTEXT['failure_count'] += 1
190-
log.status('❌ Formatting failed. 😢💔\n')
179+
def update_status(self, is_success):
180+
self.CONTEXT['success_count'] += is_success
181+
self.CONTEXT['failure_count'] += not is_success
182+
log.status('🎉 Formatting successful. 🥳✨\n' if is_success else '❌ Formatting failed. 😢💔\n')
191183

192184
def save_formatted_file(self, new_view, new_cwd, is_success):
193185
file_path = new_view.file_name()
@@ -244,8 +236,7 @@ def generate_status_text(self):
244236

245237
def open_console_on_failure(self):
246238
if OptionHandler.query(CONFIG, False, 'open_console_on_failure') and self.CONTEXT['failure_count'] > 0:
247-
current_view = self.get_current_view()
248-
current_view.window().run_command('show_panel', {'panel': 'console', 'toggle': True})
239+
self.get_current_view().window().run_command('show_panel', {'panel': 'console', 'toggle': True})
249240

250241
def show_completion_message(self):
251242
ok = self.CONTEXT['success_count']
@@ -269,36 +260,31 @@ def show_completion_message(self):
269260
InterfaceHandler.popup_message(message, 'INFO', dialog=True)
270261

271262
def reset_context(self):
272-
for key, value in self.CONTEXT.items():
273-
if isinstance(value, list):
274-
self.CONTEXT[key] = []
275-
elif isinstance(value, int):
276-
self.CONTEXT[key] = 0
277-
else:
278-
self.CONTEXT[key] = None
263+
for key in self.CONTEXT:
264+
self.CONTEXT[key] = [] if isinstance(self.CONTEXT[key], list) else 0 if isinstance(self.CONTEXT[key], int) else None
279265
# Reset and end
280266
CONFIG['STOP'] = True
281267

282268
@staticmethod
283269
def handle_error(error, cwd=None, file_path=None):
284-
log.error('Error occurred: %s\n%s', error, ''.join(traceback.format_tb(error.__traceback__)))
270+
log.error('Error: %s\n%s', error, ''.join(traceback.format_tb(error.__traceback__)))
285271
if cwd and (error.errno != os.errno.EEXIST):
286-
log.error('Could not create directory: %s', cwd)
287-
InterfaceHandler.popup_message('Could not create directory: %s\nError mainly appears due to a lack of necessary permissions.' % cwd, 'ERROR')
272+
log.error('Directory creation failed: %s', cwd)
273+
InterfaceHandler.popup_message('Error creating directory: %s\nPermissions issue likely.' % cwd, 'ERROR')
288274
if file_path:
289275
log.error('Could not save file: %s', file_path)
290-
InterfaceHandler.popup_message('Could not save file: %s\nError mainly appears due to a lack of necessary permissions.' % file_path, 'ERROR')
276+
InterfaceHandler.popup_message('Error saving file: %s\nPermissions issue likely.' % file_path, 'ERROR')
291277

292278

293279
class SerialFormat:
294280
@staticmethod
295281
def run(view=None, callback=None, **kwargs):
296-
is_success = False
297282
try:
298283
region = sublime.Region(0, view.size())
299284
uid = kwargs.get('uid', None)
300285
uid, syntax = SyntaxHandler.get_assigned_syntax(view=view, uid=uid, region=region, auto_format_config=None)
301286
exclude_syntaxes = OptionHandler.query(CONFIG, [], 'formatters', uid, 'dir_format', 'exclude_syntaxes')
287+
302288
if TextHandler.is_chars_limit_exceeded(view):
303289
callback(False)
304290
elif not syntax or syntax in exclude_syntaxes:
@@ -307,11 +293,8 @@ def run(view=None, callback=None, **kwargs):
307293
log.warning('Syntax out of the scope. Plugin scope: %s, UID: %s, File syntax: %s, File: %s', scope, uid, syntax, view.file_name())
308294
callback(False)
309295
else:
310-
kwargs.update({
311-
'view': view,
312-
'region': region
313-
})
296+
kwargs.update({'view': view, 'region': region})
314297
is_success = Formatter(**kwargs).run()
315298
callback(is_success)
316299
except Exception as e:
317-
log.error('Error occurred: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))
300+
log.error('Error in SerialFormat: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))

plugin/file_format.py

+18-32
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,9 @@ def __enter__(self):
2727

2828
def __exit__(self, exc_type, exc_value, exc_traceback):
2929
self.cleanup_temp_dir()
30-
3130
if exc_type:
32-
class_name = self.__class__.__name__
33-
log.error('Error occurred in %s while exiting: %s\n%s', class_name, exc_value, ''.join(traceback.format_tb(exc_traceback)))
34-
return False # return True to suppress exceptions
31+
log.error('Error in %s while exiting: %s\n%s', self.__class__.__name__, exc_value, ''.join(traceback.format_tb(exc_traceback)))
32+
return False
3533

3634
def run(self):
3735
if TextHandler.is_chars_limit_exceeded(self.view):
@@ -46,18 +44,20 @@ def run(self):
4644
for region in (self.view.sel() if self.has_selection() else [sublime.Region(0, self.view.size())]):
4745
self.kwargs.update(region=region)
4846
is_success = Formatter(**self.kwargs).run()
47+
4948
if self.is_no_operation(is_success):
5049
continue
50+
5151
self.cycles.append(is_success)
52-
self.print_status(is_success)
52+
self.update_status(is_success)
5353

5454
if any(self.cycles):
5555
self.close_console_on_success()
5656
self.handle_successful_formatting()
5757
else:
5858
self.open_console_on_failure()
5959
except Exception as e:
60-
log.error('Error occurred during file formatting: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))
60+
log.error('Error during file formatting: %s\n%s', e, ''.join(traceback.format_tb(e.__traceback__)))
6161

6262
def is_no_operation(self, is_success):
6363
if is_success is None:
@@ -75,13 +75,10 @@ def create_graphic_temp_dir(self):
7575
def has_selection(self):
7676
return any(not sel.empty() for sel in self.view.sel())
7777

78-
def print_status(self, is_success):
79-
if is_success:
80-
self.success += 1
81-
log.status('🎉 Formatting successful. 🥳✨\n')
82-
else:
83-
self.failure += 1
84-
log.status('❌ Formatting failed. 😢💔\n')
78+
def update_status(self, is_success):
79+
self.success += is_success
80+
self.failure += not is_success
81+
log.status('🎉 Formatting successful. 🥳✨\n' if is_success else '❌ Formatting failed. 😢💔\n')
8582

8683
if OptionHandler.query(CONFIG, True, 'show_statusbar'):
8784
self.set_status_bar_text()
@@ -141,25 +138,23 @@ def create_or_reuse_view(self):
141138
if dst_view:
142139
dst_view.window().focus_view(dst_view)
143140
dst_view.set_read_only(False)
144-
self.set_graphic_phantom(dst_view)
145141
else:
146142
src_window.focus_group(1)
147143
dst_view = src_window.new_file(flags=sublime.TRANSIENT, syntax=self.view.settings().get('syntax', None))
148144
dst_view.run_command('append', {'characters': ''}) # magic to assign a tab
149145
dst_view.settings().set('gfx_vref', gfx_vref)
150-
self.set_graphic_phantom(dst_view)
151146
dst_view.set_scratch(True)
152147
if path:
153148
dst_view.retarget(path)
154149

150+
self.set_graphic_phantom(dst_view)
155151
dst_view.set_read_only(True)
156152

157153
def get_extended_data(self):
158154
uid = self.kwargs.get('uid', None)
159155

160-
if ConfigHandler.is_quick_options_mode():
161-
if uid not in OptionHandler.query(CONFIG, [], 'quick_options', 'render_extended'):
162-
return {}
156+
if ConfigHandler.is_quick_options_mode() and uid not in OptionHandler.query(CONFIG, [], 'quick_options', 'render_extended'):
157+
return {}
163158

164159
try:
165160
extended_data = {}
@@ -171,7 +166,6 @@ def get_extended_data(self):
171166
if os.path.exists(image_path):
172167
with open(image_path, 'rb') as image_file:
173168
extended_data[ext] = base64.b64encode(image_file.read()).decode('utf-8')
174-
175169
return extended_data
176170
except Exception:
177171
return {}
@@ -181,9 +175,9 @@ def set_graphic_phantom(self, dst_view):
181175
image_path = os.path.join(self.temp_dir.name, GFX_OUT_NAME + '.png')
182176
with open(image_path, 'rb') as image_file:
183177
data = image_file.read()
184-
image_width, image_height = PhantomHandler.get_image_size(data)
185-
image_data = base64.b64encode(data).decode('utf-8')
186178

179+
image_width, image_height = PhantomHandler.get_image_size(data)
180+
image_data = base64.b64encode(data).decode('utf-8')
187181
fit_image_width, fit_image_height = PhantomHandler.image_scale_fit(dst_view, image_width, image_height)
188182
extended_data = self.get_extended_data()
189183

@@ -215,23 +209,15 @@ def on_navigate(href, data, dst_view):
215209
decoded_data = base64.b64decode(base64_data)
216210
with open(save_path, 'wb') as f:
217211
f.write(decoded_data)
218-
219-
InterfaceHandler.popup_message('Image successfully saved to:\n%s' % save_path, 'INFO', dialog=True)
212+
InterfaceHandler.popup_message('Image saved to:\n%s' % save_path, 'INFO', dialog=True)
220213
except Exception as e:
221214
InterfaceHandler.popup_message('Could not save file:\n%s\nError: %s' % (save_path, e), 'ERROR')
222215

223216
@staticmethod
224217
def get_layout_and_suffix(uid, mode):
225218
if mode == 'qo':
226-
return (
227-
OptionHandler.query(CONFIG, False, 'quick_options', 'layout'),
228-
OptionHandler.query(CONFIG, False, 'quick_options', 'new_file_on_format')
229-
)
230-
else:
231-
return (
232-
OptionHandler.query(CONFIG, False, 'layout', 'enable'),
233-
OptionHandler.query(CONFIG, False, 'formatters', uid, 'new_file_on_format')
234-
)
219+
return OptionHandler.query(CONFIG, False, 'quick_options', 'layout'), OptionHandler.query(CONFIG, False, 'quick_options', 'new_file_on_format')
220+
return OptionHandler.query(CONFIG, False, 'layout', 'enable'), OptionHandler.query(CONFIG, False, 'formatters', uid, 'new_file_on_format')
235221

236222
def undo_history(self):
237223
for _ in range(min(500, self.cycles.count(True))):

plugin/formatter_listener.py

+11-15
Original file line numberDiff line numberDiff line change
@@ -28,18 +28,15 @@ def start_sync_scroll(self, target_type, active_view, target_view):
2828
with self.lock:
2929
if not self.running:
3030
self.running = True
31-
self.thread = threading.Thread(
32-
target=self.sync_scroll, args=(target_type, active_view, target_view)
33-
)
31+
self.thread = threading.Thread(target=self.sync_scroll, args=(target_type, active_view, target_view))
3432
self.thread.start()
3533

3634
def stop_sync_scroll(self):
3735
with self.lock:
3836
self.running = False
3937
if self.thread and self.thread.is_alive():
4038
self.thread.join(timeout=0.4)
41-
if self.thread.is_alive():
42-
self.thread = None
39+
self.thread = None
4340

4441
def sync_scroll(self, target_type, active_view, target_view):
4542
try:
@@ -71,8 +68,7 @@ def apply_formatting(cls, view=None, action=None):
7168
@classmethod
7269
def _on_auto_format(cls, view=None, file_path=None, actkey=None):
7370
get_auto_format_args = DotFileHandler.get_auto_format_args(view=view, active_file_path=file_path)
74-
x = get_auto_format_args['auto_format_config']
75-
config = x.get('config', {})
71+
config = get_auto_format_args['auto_format_config'].get('config', {})
7672
if config and not cls._should_skip(config.get(actkey, False)):
7773
config.update({AUTO_FORMAT_ACTION_KEY: actkey})
7874
CleanupHandler.clear_console()
@@ -83,7 +79,7 @@ def _on_auto_format(cls, view=None, file_path=None, actkey=None):
8379
file_format.run()
8480
return True
8581
except Exception as e:
86-
log.error('Error occurred while auto formatting: %s', e)
82+
log.error('Error during auto formatting: %s', e)
8783

8884
return False
8985

@@ -94,12 +90,12 @@ def _on_paste_or_save(cls, view=None, actkey=None):
9490

9591
unique = OptionHandler.query(CONFIG, {}, 'format_on_priority') or OptionHandler.query(CONFIG, {}, 'format_on_unique')
9692
if unique and isinstance(unique, dict) and unique.get('enable', False):
97-
cls._on_paste_or_save__unique(view=view, unique=unique, actkey=actkey)
93+
cls._handle_unique_format(view=view, unique=unique, actkey=actkey)
9894
else:
99-
cls._on_paste_or_save__regular(view=view, actkey=actkey)
95+
cls._handle_regular_format(view=view, actkey=actkey)
10096

10197
@classmethod
102-
def _on_paste_or_save__unique(cls, view=None, unique=None, actkey=None):
98+
def _handle_unique_format(cls, view=None, unique=None, actkey=None):
10399
def are_unique_values(unique=None):
104100
flat_values = [value for key, values_list in unique.items() if key != 'enable' for value in values_list]
105101
return (len(flat_values) == len(set(flat_values)))
@@ -124,14 +120,14 @@ def are_unique_values(unique=None):
124120
with FileFormat(view=view, uid=uid, type=value.get('type', None)) as file_format:
125121
file_format.run()
126122
except Exception as e:
127-
log.error('Error occurred while priority formatting: %s', e)
123+
log.error('Error during priority formatting: %s', e)
128124
finally:
129125
break
130126
else:
131127
InterfaceHandler.popup_message('There are duplicate syntaxes in your "format_on_priority" option. Please sort them out.', 'ERROR')
132128

133129
@classmethod
134-
def _on_paste_or_save__regular(cls, view=None, actkey=None):
130+
def _handle_regular_format(cls, view=None, actkey=None):
135131
seen = set()
136132
formatters = OptionHandler.query(CONFIG, {}, 'formatters')
137133

@@ -148,7 +144,7 @@ def _on_paste_or_save__regular(cls, view=None, actkey=None):
148144
with FileFormat(view=view, uid=uid, type=value.get('type', None)) as file_format:
149145
file_format.run()
150146
except Exception as e:
151-
log.error('Error occurred while regular formatting: %s', e)
147+
log.error('Error during regular formatting: %s', e)
152148
finally:
153149
seen.add(syntax)
154150

@@ -242,7 +238,7 @@ def on_load(self, view):
242238
with DirFormat(view=view) as dir_format:
243239
dir_format.format_next_file(view, is_ready=False)
244240
except Exception as e:
245-
log.error('Error occurred while dir formatting: %s', e)
241+
log.error('Error during dir formatting: %s', e)
246242

247243
file_path = view.file_name()
248244
if file_path and file_path.endswith(PACKAGE_NAME + '.sublime-settings'):

0 commit comments

Comments
 (0)