diff --git a/toot/commands.py b/toot/commands.py index 69c9c58..10d6ac2 100644 --- a/toot/commands.py +++ b/toot/commands.py @@ -9,7 +9,7 @@ from toot.output import (print_out, print_instance, print_account, print_acct_li print_search_results, print_timeline, print_notifications, print_tag_list) from toot.tui.utils import parse_datetime -from toot.utils import editor_input, multiline_input, EOF_KEY +from toot.utils import delete_tmp_status_file, editor_input, multiline_input, EOF_KEY def get_timeline_generator(app, user, args): @@ -111,6 +111,8 @@ def post(app, user, args): else: print_out(f"Toot posted: {response['url']}") + delete_tmp_status_file() + def _get_status_text(text, editor): isatty = sys.stdin.isatty() diff --git a/toot/utils/__init__.py b/toot/utils/__init__.py index c76e65f..d33d2d9 100644 --- a/toot/utils/__init__.py +++ b/toot/utils/__init__.py @@ -100,17 +100,52 @@ Everything below it will be ignored. """ -def editor_input(editor, initial_text): +def editor_input(editor: str, initial_text: str): """Lets user input text using an editor.""" + tmp_path = _tmp_status_path() initial_text = (initial_text or "") + EDITOR_INPUT_INSTRUCTIONS - with tempfile.NamedTemporaryFile(suffix='.toot') as f: - f.write(initial_text.encode()) - f.flush() + if not _use_existing_tmp_file(tmp_path): + with open(tmp_path, "w") as f: + f.write(initial_text) + f.flush() - subprocess.run([editor, f.name]) + subprocess.run([editor, tmp_path]) - f.seek(0) - text = f.read().decode() + with open(tmp_path) as f: + return f.read().split(EDITOR_DIVIDER)[0].strip() - return text.split(EDITOR_DIVIDER)[0].strip() + +def read_char(values, default): + values = [v.lower() for v in values] + + while True: + value = input().lower() + if value == "": + return default + if value in values: + return value + + +def delete_tmp_status_file(): + try: + os.unlink(_tmp_status_path()) + except FileNotFoundError: + pass + + +def _tmp_status_path() -> str: + tmp_dir = tempfile.gettempdir() + return f"{tmp_dir}/.status.toot" + + +def _use_existing_tmp_file(tmp_path) -> bool: + from toot.output import print_out + + if os.path.exists(tmp_path): + print_out(f"Found a draft status at: {tmp_path}") + print_out("[O]pen (default) or [D]elete? ", end="") + char = read_char(["o", "d"], "o") + return char == "o" + + return False