Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature cat 5 #12

Merged
merged 2 commits into from
Nov 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions macnotesapp/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
"""Python to AppleScript bridge for automating Notes.app on macOS"""

from datetime import datetime
from typing import List, Optional
from __future__ import annotations

from .script_loader import run_script
from datetime import datetime
from typing import Any, Dict, List, Optional

from ._version import __version__
from .script_loader import run_script


class AppleScriptError(Exception):
Expand Down Expand Up @@ -270,6 +271,23 @@ def show(self):
"""Show note in Notes.app UI"""
self._run_script("noteShow")

def asdict(self, body="html") -> Dict[str, Any]:
"""Return dict representation of note

Args:
body: "html" or "plaintext" to return body of note in that format
"""
return {
"account": self.account,
"id": self.id,
"name": self.name,
"body": self.body if body == "html" else self.plaintext,
"creation_date": self.creation_date,
"modification_date": self.modification_date,
"password_protected": self.password_protected,
"folder": self.folder,
}

def _run_script(self, script, *args):
return run_script(script, self._account, self._id, *args)

Expand Down
87 changes: 82 additions & 5 deletions macnotesapp/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@
import markdown2
import questionary
from applescript import ScriptError
from markdownify import markdownify as html2md
from rich.console import Console
from rich.markdown import Markdown

import macnotesapp
from macnotesapp import __version__
Expand Down Expand Up @@ -223,7 +225,7 @@ def list_notes(account_name, text):
notesapp = macnotesapp.NotesApp()
if not account_name and not text:
# list all notes
print_notes(notesapp)
print_notes_list(notesapp)
return

account_name = account_name or notesapp.accounts
Expand All @@ -241,7 +243,44 @@ def list_notes(account_name, text):
else:
notes += account.notes
notes = list(set(notes))
print_notes(notes)
print_notes_list(notes)


@click.command(name="cat")
@click.option("--plaintext", "-p", is_flag=True, help="Output note as plain text.")
@click.option("--markdown", "-m", is_flag=True, help="Output note as Markdown.")
@click.option("--html", "-h", is_flag=True, help="Output note as HTML.")
@click.option(
"--json",
"-j",
"json_",
is_flag=True,
help="Output note as JSON. "
"The default format for the note body in JSON is HTML "
"(this is how the note is stored in Notes). "
"If --plaintext or --markdown is also specified, "
"the note body in the resulting JSON will be in the specified format.",
)
@click.argument("name", metavar="NOTE_NAME", required=True)
def cat_notes(name, plaintext, markdown, html, json_):
"""Print one or more notes to STDOUT"""
notesapp = macnotesapp.NotesApp()
notes = notesapp.find_notes(name=name)
output = (
"plaintext"
if plaintext
else "markdown"
if markdown
else "html"
if html
else "rich"
)

if json_:
print_notes_as_json(notes, plaintext=plaintext)
else:
for note in notes:
print_note(note, output=output)


@click.command(name="config")
Expand Down Expand Up @@ -323,7 +362,7 @@ def cli_main(ctx, debug):
ctx.obj = CLI_Obj(group=cli_main)


for command in [accounts, add_note, config, list_notes, help]:
for command in [accounts, add_note, cat_notes, config, list_notes, help]:
cli_main.add_command(command)


Expand All @@ -343,8 +382,8 @@ def get_account_data() -> Dict:
return account_data


def print_notes(notes: Iterable[macnotesapp.Note]):
"""Print notes to the screen"""
def print_notes_list(notes: Iterable[macnotesapp.Note]):
"""Print note list to STDOUT"""
notesapp = macnotesapp.NotesApp()
accounts = notesapp.accounts
account_len = max(len(a) for a in accounts)
Expand Down Expand Up @@ -376,3 +415,41 @@ def print_notes(notes: Iterable[macnotesapp.Note]):
f"{body[:body_len-padding]}.." if len(body) > (body_len - padding) else body
)
print(format_str.format(account, folder, name, body))


def print_note(note: macnotesapp.Note, output: str):
"""Print a note to STDOUT

Args:
note: Note to print
output: Output format (plaintext, markdown, html, rich)
"""

console = Console()
# print note, not JSON
if output == "plaintext":
console.print(note.plaintext)
elif output == "rich":
console.print(Markdown(html2md(note.body)))
elif output == "markdown":
console.print(html2md(note.body))
elif output == "html":
console.print(note.body)


def print_notes_as_json(notes: Iterable[macnotesapp.Note], plaintext: bool = False):
"""Print notes as JSON to STDOUT

Args:
notes: Notes to print
plaintext: If True, print plaintext of note body instead of HTML
"""

json_list = []
for note in notes:
json_data = note.asdict(body="html" if not plaintext else "plaintext")
json_data["creation_date"] = json_data["creation_date"].isoformat()
json_data["modification_date"] = json_data["modification_date"].isoformat()
json_list.append(json_data)
console = Console()
console.print(json.dumps(json_list, indent=4))
Loading