Skip to content

Commit

Permalink
Make the type hints Python 3.6-compatible.
Browse files Browse the repository at this point in the history
  • Loading branch information
joanbm committed Jul 16, 2022
1 parent ddcc758 commit 078e518
Show file tree
Hide file tree
Showing 6 changed files with 26 additions and 25 deletions.
14 changes: 7 additions & 7 deletions full_offline_backup_for_todoist/backup_attachments_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import itertools
import os
import urllib.error
from typing import Optional
from typing import Set, List, Optional
from .utils import sanitize_file_name
from .virtual_fs import VirtualFs
from .tracer import Tracer
Expand Down Expand Up @@ -49,7 +49,7 @@ def __fetch_attachment_info_from_json(json_str: str) -> Optional[TodoistAttachme
return TodoistAttachmentInfo(sanitize_file_name(json_data["file_name"]),
json_data["file_url"])

def __fetch_attachment_infos_from_csv(self, csv_string: str) -> list[TodoistAttachmentInfo]:
def __fetch_attachment_infos_from_csv(self, csv_string: str) -> List[TodoistAttachmentInfo]:
""" Fetches the information of all the attachments of a Todoist backup CSV file,
given a CSV file as a single string """
attachment_infos = []
Expand All @@ -64,7 +64,7 @@ def __fetch_attachment_infos_from_csv(self, csv_string: str) -> list[TodoistAtta

return attachment_infos

def __fetch_attachment_infos(self, vfs: VirtualFs) -> list[TodoistAttachmentInfo]:
def __fetch_attachment_infos(self, vfs: VirtualFs) -> List[TodoistAttachmentInfo]:
""" Fetches the information of all the attachment_infos
of the current Todoist backup VFS """
self.__tracer.trace("Reading VFS...")
Expand All @@ -81,7 +81,7 @@ def __fetch_attachment_infos(self, vfs: VirtualFs) -> list[TodoistAttachmentInfo
return attachment_infos

@staticmethod
def __deduplicate_file_name(original_file_name: str, file_names_to_avoid: set[str]) -> str:
def __deduplicate_file_name(original_file_name: str, file_names_to_avoid: Set[str]) -> str:
""" Modifies the given file name in order to avoid all of the file names
in the given list of file names to avoid """
name_without_ext, ext = os.path.splitext(original_file_name)
Expand All @@ -93,10 +93,10 @@ def __deduplicate_file_name(original_file_name: str, file_names_to_avoid: set[st
raise Exception('Unreachable code') # pragma: no cover

def __deduplicate_attachments_names(self,
attachment_infos: list[TodoistAttachmentInfo]) -> None:
attachment_infos: List[TodoistAttachmentInfo]) -> None:
""" Modifies the attachment names, if necessary, in order to
avoid duplicate file names """
included_attachment_names: set[str] = set()
included_attachment_names: Set[str] = set()

for attachment_info in attachment_infos:
if attachment_info.file_name in included_attachment_names:
Expand All @@ -108,7 +108,7 @@ def __deduplicate_attachments_names(self,

included_attachment_names.add(attachment_info.file_name)

def __download_and_pack_attachments(self, attachment_infos: list[TodoistAttachmentInfo],
def __download_and_pack_attachments(self, attachment_infos: List[TodoistAttachmentInfo],
vfs: VirtualFs, ignore_forbidden: bool) -> None:
""" Downloads and packs the given attachments in a folder 'attachments'
of the current Todoist backup VFS """
Expand Down
6 changes: 3 additions & 3 deletions full_offline_backup_for_todoist/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
""" Provides frontend-independent access to the functions of the interface """

from abc import ABCMeta, abstractmethod
from typing import Literal, NamedTuple, Optional, Union
from typing import NamedTuple, Optional, Union
from .tracer import Tracer
from .virtual_fs import VirtualFs
from .backup_downloader import TodoistBackupDownloader
Expand Down Expand Up @@ -43,8 +43,8 @@ class Controller:
def __init__(self, dependencies: ControllerDependencyInjector):
self.__dependencies = dependencies

def download(self, vfs: VirtualFs,
with_attachments: Union[bool, Literal['ignore-forbidden']]) -> None:
def download(self, vfs: VirtualFs, with_attachments: Union[bool, str]) -> None:
# On Python 3.8+ "Literal['ignore-forbidden']" instead of ^^^str^^^ above
""" Generates a Todoist backup ZIP from the current Todoist items """
self.__dependencies.backup_downloader.download(vfs)
if with_attachments:
Expand Down
10 changes: 5 additions & 5 deletions full_offline_backup_for_todoist/frontend.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
import os
import getpass
from pathlib import Path
from typing import Callable, Optional
from typing import Callable, List, Optional
from .virtual_fs import ZipVirtualFs
from .controller import TodoistAuth, Controller, ControllerDependencyInjector

Expand All @@ -32,7 +32,7 @@ def __add_authorization_group(parser: argparse.ArgumentParser) -> None:
token_group.add_argument("--token", type=str, help=argparse.SUPPRESS)
parser.add_argument("--password", type=str, help=argparse.SUPPRESS)

def __parse_command_line_args(self, prog: str, arguments: list[str]) -> argparse.Namespace:
def __parse_command_line_args(self, prog: str, arguments: List[str]) -> argparse.Namespace:
epilog_str = f"Example: {prog} download\n"
epilog_str += "(The necessary credentials will be asked through the command line.\n"
epilog_str += " If you wish to automate backups, credentials can be passed through the\n"
Expand All @@ -57,7 +57,7 @@ def __parse_command_line_args(self, prog: str, arguments: list[str]) -> argparse

return parser.parse_args(arguments)

def run(self, prog: str, arguments: list[str], environment: os._Environ[str]) -> None:
def run(self, prog: str, arguments: List[str], environment: os._Environ) -> None:
""" Runs the Todoist backup tool frontend with the specified command line arguments """
args = self.__parse_command_line_args(prog, arguments)
args.func(args, environment)
Expand All @@ -71,7 +71,7 @@ def __huge_warning(text: str) -> None:
pass

@staticmethod
def __get_auth(args: argparse.Namespace, environment: os._Environ[str]) -> TodoistAuth:
def __get_auth(args: argparse.Namespace, environment: os._Environ) -> TodoistAuth:
def get_credential(opt_file: Optional[str], opt_direct: Optional[str],
env_var: str, prompt: str, sensitive: bool) -> str:
if opt_file:
Expand Down Expand Up @@ -102,7 +102,7 @@ def get_credential(opt_file: Optional[str], opt_direct: Optional[str],
sensitive=True) if args.with_attachments else None
return TodoistAuth(token, email, password)

def handle_download(self, args: argparse.Namespace, environment: os._Environ[str]) -> None:
def handle_download(self, args: argparse.Namespace, environment: os._Environ) -> None:
""" Handles the download subparser with the specified command line arguments """

# Configure controller
Expand Down
3 changes: 2 additions & 1 deletion full_offline_backup_for_todoist/todoist_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
""" Provides access to a subset of the features of the Todoist API"""

import json
from typing import List
from .tracer import Tracer
from .url_downloader import URLDownloader

Expand Down Expand Up @@ -31,7 +32,7 @@ def __init__(self, api_token: str, tracer: Tracer, urldownloader: URLDownloader)
self.__tracer = tracer
self.__urldownloader = urldownloader

def get_projects(self) -> list[TodoistProjectInfo]:
def get_projects(self) -> List[TodoistProjectInfo]:
""" Obtains the list of all projects from the Todoist API """
self.__tracer.trace("Fetching projects using the Todoist API...")
project_list_json = self.__urldownloader.get(
Expand Down
8 changes: 4 additions & 4 deletions full_offline_backup_for_todoist/url_downloader.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,14 @@
import urllib.request
import urllib.parse
import http.cookiejar
from typing import cast, Optional
from typing import cast, Dict, Optional
from .tracer import Tracer

class URLDownloader(metaclass=ABCMeta):
""" Implementation of a class to download the contents of an URL """

@abstractmethod
def get(self, url: str, data: Optional[dict[str, str]]=None) -> bytes:
def get(self, url: str, data: Optional[Dict[str, str]]=None) -> bytes:
""" Download the contents of the specified URL with a GET request.
You can specify any additional data parameters to pass to the destination. """

Expand All @@ -25,7 +25,7 @@ def _build_opener_with_app_useragent(
class URLLibURLDownloader(URLDownloader):
""" Implementation of a class to download the contents of an URL through URLLib """

def get(self, url: str, data: Optional[dict[str, str]]=None) -> bytes:
def get(self, url: str, data: Optional[Dict[str, str]]=None) -> bytes:
real_url = url
if data:
real_url += "?" + urllib.parse.urlencode(data)
Expand Down Expand Up @@ -56,7 +56,7 @@ def __init__(self, tracer: Tracer, email: str, password: str):
self.__password = password
self.__opener = None

def get(self, url: str, data: Optional[dict[str, str]]=None) -> bytes:
def get(self, url: str, data: Optional[Dict[str, str]]=None) -> bytes:
if not self.__opener:
# Set up a cookie jar, to gather the login's cookies
cookiejar = http.cookiejar.CookieJar()
Expand Down
10 changes: 5 additions & 5 deletions full_offline_backup_for_todoist/virtual_fs.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import zipfile
from pathlib import Path
from types import TracebackType
from typing import IO, Optional, Type
from typing import IO, List, Optional, Type

class VirtualFs(metaclass=ABCMeta):
""" An abstract layer over the filesystem
Expand All @@ -21,7 +21,7 @@ def existed(self) -> bool:
""" Checks if the filesystem previously existed, or is newly created """

@abstractmethod
def file_list(self) -> list[str]:
def file_list(self) -> List[str]:
""" Gets the list of files in this virtual file system """

@abstractmethod
Expand Down Expand Up @@ -57,8 +57,8 @@ def __enter__(self) -> VirtualFs: # Type should be Self, but isn't well supporte

return self

def __exit__(self, exc_type: Type[BaseException] | None, exc_value: BaseException | None,
traceback: TracebackType | None) -> None:
def __exit__(self, exc_type: Optional[Type[BaseException]], exc_value: Optional[BaseException],
traceback: Optional[TracebackType]) -> None:
if self._zip_file:
self._zip_file.close()
self._zip_file = None
Expand All @@ -77,7 +77,7 @@ def existed(self) -> bool:
assert self._backing_storage
return not isinstance(self._backing_storage, io.BytesIO)

def file_list(self) -> list[str]:
def file_list(self) -> List[str]:
assert self._zip_file
return self._zip_file.namelist()

Expand Down

0 comments on commit 078e518

Please sign in to comment.