Skip to content

Commit

Permalink
Merge branch 'master' of github.com:klieret/AnkiPandas
Browse files Browse the repository at this point in the history
  • Loading branch information
klieret committed Mar 14, 2021
2 parents 63cf6f0 + 9df104b commit 97a9d63
Show file tree
Hide file tree
Showing 5 changed files with 38 additions and 49 deletions.
14 changes: 6 additions & 8 deletions ankipandas/ankidf.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,12 +165,11 @@ def check_table_integrity(self):
duplicates = self.index[self.index.duplicated()].tolist()
if duplicates:
log.critical(
"Duplicated indizes in table {} discovered, so something "
"Duplicated indizes in table %s discovered, so something "
"definitely went wrong. Please don't ignore this warning. "
"These indizes appear more "
"than once: {}".format(
self._anki_table, ", ".join(map(str, duplicates))
)
"These indizes appear more than once: %s",
self._anki_table,
", ".join(map(str, duplicates)),
)

def _invalid_table(self):
Expand Down Expand Up @@ -1019,9 +1018,8 @@ def normalize(self, inplace=False, force=False):
if duplicate_ids:
log.critical(
"The following IDs occur "
"more than once: {}. Please do not use this dataframe.".format(
", ".join(map(str, duplicate_ids))
)
"more than once: %s. Please do not use this dataframe.",
", ".join(map(str, duplicate_ids)),
)
self.set_index(id_field, inplace=True)

Expand Down
37 changes: 15 additions & 22 deletions ankipandas/collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def __init__(self, path=None, user=None):
#: Path to currently loaded database
self._path = path # type: Path

log.info(f"Loaded db from {self.path}")
log.info("Loaded db from %s", self.path)

#: Opened Anki database (:class:`sqlite3.Connection`)
self._db = raw.load_db(self.path) # type: sqlite3.Connection
Expand Down Expand Up @@ -78,11 +78,7 @@ def db(self) -> sqlite3.Connection:
return self._db

def __del__(self):
log.debug(
"Closing db {db} which was loaded from {path}.".format(
db=self.db, path=self.path
)
)
log.debug("Closing db %s which was loaded from %s.", self.db, self.path)
raw.close_db(self.db)
log.debug("Closing successful")

Expand Down Expand Up @@ -179,7 +175,7 @@ def _prepare_write_data(
prepared = {}
for key, value in self.__items.items():
if value is None:
log.debug(f"Write: Skipping {key}, because it's None.")
log.debug("Write: Skipping %s, because it's None.", key)
continue
if key in ["notes", "cards", "revs"]:
ndeleted = len(value.was_deleted())
Expand All @@ -204,8 +200,9 @@ def _prepare_write_data(

if not ndeleted and not nmodified and not nadded:
log.debug(
"Skipping table {key} for writing, because nothing "
"seemed to have changed".format(key=key)
"Skipping table %s for writing, because nothing "
"seemed to have changed",
key,
)
continue

Expand All @@ -214,11 +211,7 @@ def _prepare_write_data(
mode = "update"
if add and not modify and not delete:
mode = "append"
log.debug(
"Will update table {key} with mode {mode}".format(
key=key, mode=mode
)
)
log.debug("Will update table %s with mode %s", key, mode)
value.check_table_integrity()
raw_table = value.raw()
prepared[key] = {"raw": raw_table, "mode": mode}
Expand Down Expand Up @@ -322,7 +315,7 @@ def write(
backup_path = ankipandas.paths.backup_db(
self.path, backup_folder=backup_folder
)
log.info(f"Backup created at {backup_path.resolve()}.")
log.info("Backup created at %s", backup_path.resolve())
log.warning(
"Currently AnkiPandas might not be able to tell Anki to"
" sync its database. "
Expand All @@ -340,26 +333,26 @@ def write(
log.debug("Now actually writing to database.")
try:
for table, values in prepared.items():
log.debug(f"Now setting table {table}.")
log.debug("Now setting table %s.", table)
raw.set_table(
self.db, values["raw"], table=table, mode=values["mode"]
)
log.debug(f"Setting table {table} successful.")
log.debug("Setting table %s successful.", table)
# log.debug("Now setting info")
# raw.set_info(self.db, info)
# log.debug("Setting info successful.")
except Exception as e:
log.critical(
"Error while writing data to database at {path}"
"Error while writing data to database at %s. "
"This means that your database might have become corrupted. "
"It's STRONGLY advised that you manually restore the database "
"by replacing it with the backup from {backup_path} and restart"
"by replacing it with the backup from %s and restart"
" from scratch. "
"Please also open a bug report at "
"https://github.com/klieret/AnkiPandas/issues/, as errors "
"during the actual writing process should never occur!".format(
path=self.path.resolve(), backup_path=backup_path.resolve()
)
"during the actual writing process should never occur!",
self.path.resolve(),
backup_path.resolve(),
)
raise e
# This is important, because we have written to the database but still
Expand Down
26 changes: 14 additions & 12 deletions ankipandas/paths.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,10 +39,7 @@ def _find_db(
"""
search_path = Path(search_path)
if not search_path.exists():
log.debug(
"_find_db: Search path '{}' does not "
"exist.".format(str(search_path))
)
log.debug("_find_db: Search path %r does not exist.", str(search_path))
return collections.defaultdict(list)
if search_path.is_file():
if search_path.name == filename:
Expand All @@ -51,8 +48,10 @@ def _find_db(
)
else:
log.warning(
"_find_db: Search path '{}' is a file, but filename does not "
"match that of '{}'.".format(str(search_path), filename)
"_find_db: Search path %r is a file, but filename does not "
"match that of %r.",
str(search_path),
filename,
)
return collections.defaultdict(list)
found = collections.defaultdict(list) # type: DefaultDict[str, List[Path]]
Expand All @@ -68,8 +67,9 @@ def _find_db(
depth = len(Path(root).relative_to(search_path).parts)
if maxdepth and depth >= maxdepth:
# log.debug(
# "_find_db: Abort search at '{}'. "
# "Max depth exceeded.".format(str(root))
# "_find_db: Abort search at %r. "
# "Max depth exceeded.",
# str(root)
# )
del dirs[:]
return found
Expand Down Expand Up @@ -177,7 +177,7 @@ def find_db(

assert len(results_user) == 1
final_result = results_user[0]
log.debug(f"Database found at '{final_result}'.")
log.debug("Database found at %r.", final_result)
return final_result


Expand Down Expand Up @@ -209,13 +209,15 @@ def db_path_input(path: Union[str, PurePath] = None, user: str = None) -> Path:
"db_path_input: File '{}' does not exist.".format(str(path))
)
if path.is_file():
log.debug(f"db_path_input: Database explicitly set to '{path}'.")
log.debug(
"db_path_input: Database explicitly set to %r.", str(path)
)
result = path
else:
result = find_db(
search_paths=(path,), user=user, break_on_first=False
)
log.info(f"Database found at '{result}'.")
log.info("Database found at %r.", str(result))
if result:
return result
else:
Expand Down Expand Up @@ -271,7 +273,7 @@ def backup_db(
if backup_folder:
backup_folder = Path(backup_folder)
if not backup_folder.is_dir():
log.debug("Creating backup directory {}".format(str(backup_folder)))
log.debug("Creating backup directory %s.", backup_folder)
backup_folder.mkdir(parents=True)
else:
backup_folder = get_anki_backup_folder(db_path, nexist="raise")
Expand Down
6 changes: 1 addition & 5 deletions ankipandas/util/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,7 @@ def _sync_metadata(df_ret: pd.DataFrame, df_old: pd.DataFrame) -> None:
if hasattr(df_old, "_metadata"):
for key in df_old._metadata:
value = getattr(df_old, key)
log.debug(
"Setting metadata attribute {key} to {value}".format(
key=key, value=value
)
)
log.debug("Setting metadata attribute %s to %s", key, value)
setattr(df_ret, key, value)


Expand Down
4 changes: 2 additions & 2 deletions doc/examples/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,13 @@ def get_examples(self):
return examples

def run_example(self, path: Path, save=True):
self.log.info("Running example {}".format(path))
self.log.info("Running example %s", path)
col = ankipandas.Collection(self.col_path) # noqa F841
with path.open("r") as example_file:
exec(example_file.read())
if save:
out = self.output_dir.resolve() / (path.resolve().stem + ".png")
self.log.info("Plotting to {}".format(out))
self.log.info("Plotting to %s", out)
plt.savefig(out, bbox_inches="tight", transparent=True, dpi=75)
plt.cla()
plt.clf()
Expand Down

0 comments on commit 97a9d63

Please sign in to comment.