Skip to content

Commit

Permalink
Uniformizing error message and error message formatting
Browse files Browse the repository at this point in the history
After launching GTG from flatpak I got an ill formatted error (showing `%s` instead of the proper values). It's due to a `raise ValueError` in `GTG/core/config.py`. After looking at that I started just fixing and uniformizing the error message formatting across GTG. Here's what's in the PR :
* uniformizing error message formating :
  * using the same string formatting mechanism
* raise `NotImplementedError` not `NotImplemented` which isn't an exception
```
>>> raise NotImplemented
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: exceptions must derive from BaseException
```
* do not explicitly reraise current error in an `except:` block, juste use bare `raise` statement
* raise error objects, not classes
  • Loading branch information
jaesivsm committed May 5, 2022
1 parent 188b5f6 commit d04ad6c
Show file tree
Hide file tree
Showing 15 changed files with 38 additions and 40 deletions.
2 changes: 1 addition & 1 deletion GTG/backends/backend_caldav.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ def _refresh_calendar_list(self):
BackendSignals().interaction_requested(
self.get_id(), f"{message} {error!r}",
BackendSignals().INTERACTION_INFORM, "on_continue_clicked")
raise error
raise
for calendar in principal.calendars():
self._cache.set_calendar(calendar)

Expand Down
4 changes: 2 additions & 2 deletions GTG/backends/generic_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ def cast_param_type_from_string(cls, param_value, param_type):
elif param_value == "False":
return False
else:
raise Exception(f"Unrecognized bool value '{param_type}'")
raise Exception(f"Unrecognized bool value {param_type!r}")
elif param_type == cls.TYPE_PASSWORD:
if param_value == -1:
return None
Expand All @@ -417,7 +417,7 @@ def cast_param_type_from_string(cls, param_value, param_type):
the_list = [the_list]
return the_list
else:
raise NotImplemented(f"I don't know what type is '{param_type}'")
raise NotImplementedError(f"I don't know what type is {param_type!r}")

def cast_param_type_to_string(self, param_type, param_value):
"""
Expand Down
10 changes: 5 additions & 5 deletions GTG/core/base_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def __init__(self) -> None:
# --------------------------------------------------------------------------

def new(self) -> Any:
raise NotImplemented
raise NotImplementedError()


def get(self, key: str) -> Any:
Expand All @@ -62,7 +62,7 @@ def add(self, item: Any, parent_id: UUID = None) -> None:
log.warn('Failed to add item with id %s, already added!',
item.id)

raise KeyError
raise KeyError(item.id)

if parent_id:
try:
Expand Down Expand Up @@ -156,19 +156,19 @@ def unparent(self, item_id: UUID, parent_id: UUID) -> None:
self.lookup[parent_id])
return

raise KeyError
raise KeyError()


# --------------------------------------------------------------------------
# SERIALIZING
# --------------------------------------------------------------------------

def from_xml(self, xml: Element) -> Any:
raise NotImplemented
raise NotImplementedError()


def to_xml(self) -> Element:
raise NotImplemented
raise NotImplementedError()


# --------------------------------------------------------------------------
Expand Down
7 changes: 3 additions & 4 deletions GTG/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def open_config_file(config_file):
if not os.path.exists(config_file):
open(config_file, "w").close()
if not os.access(config_file, os.R_OK | os.W_OK):
raise Exception("File " + config_file + " is a configuration file "
raise Exception(f"File {config_file} is a configuration file "
"for gtg, but it cannot be read or written. "
"Please check it")
config = configparser.ConfigParser()
Expand Down Expand Up @@ -159,9 +159,8 @@ def get(self, option):
error)

if value is None and default_value is None:
raise ValueError(
'No valid configuration value or default value was '
'found for %s in %s'.format(option, self._section_name))
raise ValueError("No valid configuration value or default value "
f"was found for {option} in {self._section_name}")
elif value is None:
return default_value
else:
Expand Down
8 changes: 4 additions & 4 deletions GTG/core/datastore2.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,13 +216,13 @@ def count_tasks(count: dict, tasklist: list):
'closed': {'all': 0, 'untagged': 0},
}

count_tasks(self.task_count['open'],
count_tasks(self.task_count['open'],
self.tasks.filter(Filter.ACTIVE))

count_tasks(self.task_count['closed'],
count_tasks(self.task_count['closed'],
self.tasks.filter(Filter.CLOSED))

count_tasks(self.task_count['actionable'],
count_tasks(self.task_count['actionable'],
self.tasks.filter(Filter.ACTIONABLE))


Expand Down Expand Up @@ -357,7 +357,7 @@ def find_and_load_file(self, path: str) -> None:
self.first_run(path)

except IOError:
raise SystemError(f'Could not write a file at {path}')
raise SystemError(f"Could not write a file at {path}")


def purge(self, max_days: int) -> None:
Expand Down
8 changes: 4 additions & 4 deletions GTG/core/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,7 @@ def __init__(self, value=None):
elif value in LOOKUP:
self.dt_value = LOOKUP[value]
if self.dt_value is None:
raise ValueError(f"Unknown value for date: '{value}'")
raise ValueError(f"Unknown value for date: {value!r}")

@staticmethod
def __parse_dt_str(string):
Expand Down Expand Up @@ -215,7 +215,7 @@ def _cast_for_operation(self, other, is_comparison: bool = True):
"""
if isinstance(other, timedelta):
if is_comparison:
raise ValueError("can't compare with %r" % other)
raise ValueError(f"can't compare with {other!r}")
return self.dt_value, other
if not isinstance(other, self.__class__):
other = self.__class__(other)
Expand Down Expand Up @@ -459,7 +459,7 @@ def parse(cls, string):
if result is not None:
return cls(result)
else:
raise ValueError(f"Can't parse date '{string}'")
raise ValueError(f"Can't parse date {string!r}")

@staticmethod
def date_in_the_next_month(mday, dt):
Expand Down Expand Up @@ -595,7 +595,7 @@ def parse_from_date(self, string, newtask=False):
if result is not None:
return Date(result)
else:
raise ValueError(f"Can't parse date '{string}'")
raise ValueError(f"Can't parse date {string!r}")

def to_readable_string(self):
""" Return nice representation of date.
Expand Down
13 changes: 7 additions & 6 deletions GTG/core/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,8 +151,8 @@ def _tokenize_query(query):
if token_type != 'space':
yield token_type, token_value
if pos != len(query):
raise InvalidQuery('tokenizer stopped at pos %r of %r left of "%s"' % (
pos, len(query), query[pos:pos + 10]))
raise InvalidQuery(f"tokenizer stopped at pos {pos!} of {len(query)} "
f"left of {query[pos:pos + 10]!r}")


def parse_search_query(query):
Expand All @@ -176,13 +176,14 @@ def parse_search_query(query):

if require_date:
if token not in ['date', 'word', 'literal']:
raise InvalidQuery(f"Unexpected token '{token}' after '{require_date}'")
raise InvalidQuery(f"Unexpected token {token!r} "
f"after {require_date!r}")

value = value.strip('"')
try:
date = Date.parse(value)
except ValueError:
raise InvalidQuery(f"Date '{value}' in wrong format")
raise InvalidQuery(f"Date {value!r} in wrong format")

cmd = (require_date, not_count % 2 == 0, date)
require_date = None
Expand Down Expand Up @@ -216,7 +217,7 @@ def parse_search_query(query):
found = True
break
if not found:
raise InvalidQuery(f"Unknown command !{value}")
raise InvalidQuery(f"Unknown command! {value!r}")

elif token == 'tag':
cmd = (token, not_count % 2 == 0, value.replace('@', ''))
Expand All @@ -238,7 +239,7 @@ def parse_search_query(query):
raise InvalidQuery("Or is not allowed at the end of query")

if require_date:
raise InvalidQuery(f"Required date after '{require_date}'")
raise InvalidQuery(f"Required date after {require_date!r}")

return {'q': commands}

Expand Down
3 changes: 1 addition & 2 deletions GTG/core/tag.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,8 +165,7 @@ def set_attribute(self, att_name, att_value):
"""
modified = False
if att_name == "name":
raise KeyError(
"The name of tag cannot be set manually")
raise KeyError("The name of tag cannot be set manually")
elif att_name == "parent":
self.add_parent(att_value)
modified = True
Expand Down
2 changes: 1 addition & 1 deletion GTG/core/task.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def __init__(self, task_id, requester, newtask=False):
# the id of this task in the project should be set
# tid is a string ! (we have to choose a type and stick to it)
if not isinstance(task_id, str):
raise ValueError("Wrong type for task_id %r", type(task_id))
raise ValueError(f"Wrong type for task_id {type(task_id)!r}")
self.tid = task_id
self.set_uuid(task_id)
self.remote_ids = {}
Expand Down
2 changes: 1 addition & 1 deletion GTG/core/tasks2.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def add_tag(self, tag: Tag2) -> None:
if tag not in self.tags:
self.tags.append(tag)
else:
raise ValueError
raise ValueError(tag)


def remove_tag(self, tag_name: str) -> None:
Expand Down
4 changes: 2 additions & 2 deletions GTG/core/timer.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,8 @@ def parse_time(self, time):
if not invalid_format:
return datetime.time(int(hour), int(minute))
else:
raise ValueError('This time value or format\
is not allowed: {0}'.format(time))
raise ValueError("This time value or format "
f"is not allowed: {time!r}")
else:
# The final attempt to parse the input
return datetime.datetime.strptime(time, '%X')
Expand Down
6 changes: 3 additions & 3 deletions GTG/core/xml.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ def task_from_element(task, element: etree.Element):
# Retrieving all dates
dates = element.find('dates')
done_date = None

# supporting old ways of salvaging fuzzy dates
for key, get_date, set_date in (
('fuzzyDue', task.get_due_date, task.set_due_date),
Expand All @@ -95,7 +95,7 @@ def task_from_element(task, element: etree.Element):
value = dates.find(key)
if value is not None and value.text:
set_date(Date(value.text))

return task


Expand Down Expand Up @@ -251,7 +251,7 @@ def open_file(xml_path: str, root_tag: str) -> etree.ElementTree:
return open_file(xml_path, root_tag)

except IOError:
raise SystemError(f'Could not write a file at {xml_path}')
raise SystemError(f"Could not write a file at {xml_path}")


def write_backups(filepath: str) -> None:
Expand Down
3 changes: 1 addition & 2 deletions GTG/gtk/errorhandler.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,9 +198,8 @@ def inner(*arg, **kwargs):
do_error_dialog(e, context, ignorable)
except Exception:
log.exception("Exception occured while trying to show it")

if reraise:
raise e
raise
else:
log.debug("Not re-raising exception because it has been explicitly disabled: %r", e)
return inner
Expand Down
2 changes: 1 addition & 1 deletion GTG/plugins/export/export.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
stderr=subprocess.DEVNULL,)
if retval != 0:
log.debug('Missing command %r', dependence)
raise ImportError(f'Missing command "{dependence}"')
raise ImportError(f"Missing command {dependence!r}")


def get_desktop_dir():
Expand Down
4 changes: 2 additions & 2 deletions tests/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@ def __init__(self, *args, **kwargs):
elif len(args) >= 2:
super().__init__(target=args[1])
else:
raise AssertionError("%s couldn't find delayed function call"
% self.__class__.__name__)
raise AssertionError(f"{self.__class__.__name__} couldn't find "
"delayed function call")

0 comments on commit d04ad6c

Please sign in to comment.