Browse Source

Minor cleanup

Nathan Beals 4 years ago
parent
commit
799cb932fc
5 changed files with 68 additions and 24 deletions
  1. 2 0
      keep_exporter/__init__.py
  2. 5 2
      keep_exporter/__main__.py
  3. 23 16
      keep_exporter/cli.py
  4. 37 5
      keep_exporter/export.py
  5. 1 1
      pyproject.toml

+ 2 - 0
keep_exporter/__init__.py

@@ -1 +1,3 @@
+#!/usr/bin/env python3
+"""A command line utility to export Google Keep notes to markdown files with metadata stored as a frontmatter header."""
 from keep_exporter.cli import main

+ 5 - 2
keep_exporter/__main__.py

@@ -1,4 +1,7 @@
+#!/usr/bin/env python3
+"""A command line utility to export Google Keep notes to markdown files with metadata stored as a frontmatter header."""
 from keep_exporter import main
 
-if __name__ == '__main__':
-    main()
+if __name__ == "__main__":
+    # pylint: disable=no-value-for-parameter
+    main()

+ 23 - 16
keep_exporter/cli.py

@@ -1,20 +1,12 @@
 #!/usr/bin/env python3
 """keep_exporter command line interface module. Provides the actual user interactions to `export.py`."""
-__version__ = "2.0.0"
-__author__ = "Nathan Beals, Matthew Bafford"
-
-APP_NAME = "Keep Exporter"
-
 import pathlib
-from typing import Any, Optional, Tuple, Union
+from typing import Any, Optional, Union
 
 import click
 import click_config_file
-import frontmatter
 import gkeepapi
 from configobj import ConfigObj
-
-
 from keep_exporter.export import (
     LocalNote,
     build_markdown,
@@ -26,6 +18,11 @@ from keep_exporter.export import (
     write_note,
 )
 
+__version__ = "2.0.1"
+__author__ = "Nathan Beals, Matthew Bafford"
+
+APP_NAME = "Keep Exporter"
+
 
 def login(
     user_email: str, password: Optional[str], token: Optional[str] = None
@@ -62,7 +59,7 @@ def login(
         except gkeepapi.exception.LoginException as ex:
             raise click.BadParameter(f"Password login failed: {str(ex)}")
 
-    raise click.BadParameter(f"Neither password nor token provided to login.")
+    raise click.BadParameter("Neither password nor token provided to login.")
 
 
 def get_click_supplied_value(ctx: click.core.Context, param_name: str) -> Any:
@@ -88,7 +85,7 @@ def get_click_supplied_value(ctx: click.core.Context, param_name: str) -> Any:
 
 def token_callback_password_or_token(
     ctx: click.core.Context,
-    param: Union[click.core.Option, click.core.Parameter],
+    _param: Union[click.core.Option, click.core.Parameter],
     value: Any,
 ) -> Any:
     """
@@ -115,6 +112,16 @@ def date_format_handler(
     param: Union[click.core.Option, click.core.Parameter],
     value: Any,
 ) -> str:
+    """handles the various flags that modify `date_format`
+
+    Args:
+        ctx (click.core.Context): App context
+        param (Union[click.core.Option, click.core.Parameter]): the current flag/option modifying date format
+        value (Any): The value of said option, not really used
+
+    Returns:
+        str: the option value to set
+    """
 
     if param.name == "date_format":
         if (
@@ -203,7 +210,7 @@ def date_format_handler(
 )
 @click.option(
     "--iso8601",
-    metavar="%Y-%m-%dT%H:%M:%S",  # use `metavar` for the format instead of default or flag_value, hack around click stuff
+    metavar="%Y-%m-%dT%H:%M:%S",  # use `metavar` for the format instead of default or flag_value, hack
     default=False,
     is_flag=True,
     help="Format dates in ISO8601 format.",
@@ -226,11 +233,11 @@ def main(
     rename_local: bool,
     date_format: str,
     skip_existing_media: bool,
-    iso8601: Any,
-    config: str,  # required to be here, despite being as-of-yet unused.
+    # iso8601: Any,
+    # config: str,  # required to be here, despite being as-of-yet unused.
+    **_kwargs,
 ):
     """A simple utility to export google keep notes to markdown files with metadata stored as a frontmatter header."""
-
     notepath = pathlib.Path(directory).resolve()
     mediapath = notepath.joinpath("media/")
     if ctx.invoked_subcommand is not None:
@@ -303,7 +310,7 @@ def main(
 @click.pass_context
 def savetoken(ctx):
     """Saves the master token to your configuration file. Avoids re-logging in every time an export happens."""
-    user, password, token = (
+    user, password, _token = (
         ctx.parent.params.get("user", ""),
         ctx.parent.params.get("password", ""),
         ctx.parent.params.get("token", ""),

+ 37 - 5
keep_exporter/export.py

@@ -1,4 +1,5 @@
 #!/usr/bin/env python3
+"""Library functions that do the heavy lifting of this package."""
 # pylint: disable=protected-access
 import datetime
 import mimetypes
@@ -34,6 +35,17 @@ def download_media(
     mediapath: pathlib.Path,
     skip_existing: bool,
 ) -> Tuple[List[pathlib.Path], int]:
+    """Downloads media files from keep
+
+    Args:
+        keep (gkeepapi.Keep): keep instance
+        note (gkeepapi._node.Note): specific note to download media from
+        mediapath (pathlib.Path): path to put media
+        skip_existing (bool): skip existing media?
+
+    Returns:
+        Tuple[List[pathlib.Path], int]: List of paths where media was put
+    """
 
     note_media = all_note_media(note)
     if not note_media:
@@ -97,6 +109,15 @@ def download_media(
 
 
 def build_frontmatter(note: gkeepapi._node.Note, markdown: str) -> frontmatter.Post:
+    """Builds the frontmatter header put at the top of notes
+
+    Args:
+        note (gkeepapi._node.Note): Note to build header from
+        markdown (str): markdown body
+
+    Returns:
+        frontmatter.Post: Completed header + body
+    """
     metadata = {
         "title": note.title,
         "url": note.url,
@@ -128,6 +149,15 @@ def build_frontmatter(note: gkeepapi._node.Note, markdown: str) -> frontmatter.P
 
 
 def build_markdown(note: gkeepapi._node.Note, images: List[pathlib.Path]) -> str:
+    """builds the markdown body from a given note
+
+    Args:
+        note (gkeepapi._node.Note): Note to build body out of
+        images (List[pathlib.Path]): Images embedded in body
+
+    Returns:
+        str: string representation of the body contents
+    """
     doc = MdUtils(
         ""
     )  # mdutils requires a string file name. We're not using it to write files, ignore it.
@@ -223,10 +253,10 @@ def index_existing_files(directory: pathlib.Path) -> Dict[str, LocalNote]:
         # markdown file
         if file.name.endswith(".md"):
             try:
-                with open(file, "r") as file_handle:
-                    fm = frontmatter.load(file_handle)
+                with file.open("rt") as file_handle:
+                    note_frontmatter = frontmatter.load(file_handle)
 
-                    google_keep_id: str = fm.metadata.get("google_keep_id")
+                    google_keep_id: str = note_frontmatter.metadata.get("google_keep_id")
                     if google_keep_id:
                         if google_keep_id in index and index[google_keep_id].path:
                             click.echo(
@@ -240,7 +270,7 @@ def index_existing_files(directory: pathlib.Path) -> Dict[str, LocalNote]:
                         index.setdefault(google_keep_id, LocalNote(google_keep_id))
 
                         updated: datetime.datetime = datetime.datetime.fromtimestamp(
-                            fm.metadata.get("timestamps", {}).get("updated")
+                            note_frontmatter.metadata.get("timestamps", {}).get("updated")
                         )
 
                         index[google_keep_id].timestamp_updated = updated
@@ -288,6 +318,7 @@ def try_rename_note(note: LocalNote, target_file: pathlib.Path) -> pathlib.Path:
     try:
         note.path.rename(target_file)
         return target_file
+    # pylint: disable=broad-except
     except Exception as ex:
         click.echo(f"Unable to rename note. Using existing name: {ex}", err=True)
         return note.path
@@ -299,8 +330,9 @@ def build_note_unique_path(
     date_format: str,
     local_index: Dict[str, LocalNote],
 ) -> pathlib.Path:
+
     title = note.title.strip()
-    if not len(title):
+    if len(title) < 1:
         title = "untitled"
 
     date_str = note.timestamps.created.strftime(date_format)

+ 1 - 1
pyproject.toml

@@ -1,6 +1,6 @@
 [tool.poetry]
 name = "keep_exporter"
-version = "2.0.0"
+version = "2.0.1"
 description = "Google Keep note exporter utility"
 authors = ["Nathan Beals <ndbeals@users.noreply.github.com>"]
 license = "BSD-3-Clause"