Skip to content

Commit

Permalink
Add functions and don't call them for now
Browse files Browse the repository at this point in the history
  • Loading branch information
tpwo committed Nov 7, 2023
1 parent b103f4b commit 9706f76
Showing 1 changed file with 97 additions and 0 deletions.
97 changes: 97 additions & 0 deletions src/pyzet/zettel.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@
import logging
import os
import re
import subprocess
from argparse import Namespace
from datetime import datetime
from pathlib import Path
from typing import NamedTuple

import pyzet.constants as C
from pyzet.grep import parse_grep_patterns
from pyzet.utils import Config
from pyzet.utils import get_git_output


class Zettel(NamedTuple):
Expand Down Expand Up @@ -64,6 +68,99 @@ def get_zettel(path: Path) -> Zettel:
return Zettel(title=title, id_=id_, tags=tags, path=md_path)


def get_from_grep(args: Namespace, config: Config) -> Zettel:
if _patterns_empty(args.patterns):
msg = 'ERROR: provided patterns are incorrect (empty or whitespace)'
raise SystemExit(msg)
opts = ['-I', '--all-match', '--name-only']
if args.ignore_case:
opts.append('--ignore-case')
opts.extend(
[*parse_grep_patterns(args.patterns), '--', f'*/{C.ZETTEL_FILENAME}']
)
try:
out = get_git_output(config, 'grep', opts).decode()
except subprocess.CalledProcessError:
raise SystemExit('ERROR: no zettels found')

matches: dict[int, Zettel] = {}
for idx, filename in enumerate(out.splitlines(), start=1):
matches[idx] = get(Path(config.repo, filename))

confirmation_threshold = 50
if len(matches) > confirmation_threshold:
prompt = f'Found {len(matches)} matching zettels. Continue? (y/N): '
try:
if input(prompt) != 'y':
raise SystemExit('aborting')
except KeyboardInterrupt:
raise SystemExit('\naborting')

print(f'Found {len(matches)} matches:')
for idx, zet in matches.items():
print(f'[{idx}] {get_zettel_repr(zet, args)}')

try:
user_input = input('Open (press enter to cancel): ')
except KeyboardInterrupt:
raise SystemExit('\naborting')

if user_input == '':
raise SystemExit('aborting')

try:
return matches[int(user_input)]
except KeyError:
raise SystemExit('ERROR: wrong zettel ID')


def _patterns_empty(patterns: list[str]) -> bool:
"""Returns True if all provided patterns are empty str or whitespace."""
return all('' == s or s.isspace() for s in patterns)


def get_from_id(id_: str, repo: Path) -> Zettel:
"""Gets zettel from its ID given repo path."""
try:
return get_from_dir(Path(repo, C.ZETDIR, id_))
except FileNotFoundError:
raise SystemExit(f"ERROR: zettel '{id_}' doesn't exist.")


def get_last(repo: Path) -> Zettel:
"""Gets the last zettel from a given repo."""
return get_all(Path(repo, C.ZETDIR), is_reversed=True)[0]


def get_from_dir(dirpath: Path) -> Zettel:
"""Gets zettel from a directory named after its ID."""
return get(Path(dirpath, C.ZETTEL_FILENAME))


def get(path: Path) -> Zettel:
"""Gets zettel from a full path."""
if path.is_dir():
raise ValueError

title_line, tags_line = _get_first_and_last_line(path)
if title_line == '':
raise ValueError

if tags_line.startswith(4 * ' '):
tags = get_tags(tags_line.strip())
else:
tags = tuple()

id_ = path.parent.name

return Zettel(
id_=id_,
title=get_markdown_title(title_line, id_),
path=path,
tags=tags,
)


def get_zettel_repr(zet: Zettel, args: Namespace) -> str:
tags = ''
if args.tags:
Expand Down

0 comments on commit 9706f76

Please sign in to comment.