jrnl.editor   A
last analyzed

Complexity

Total Complexity 9

Size/Duplication

Total Lines 58
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 41
dl 0
loc 58
rs 10
c 0
b 0
f 0
wmc 9

2 Functions

Rating   Name   Duplication   Size   Complexity  
A get_text_from_stdin() 0 14 3
B get_text_from_editor() 0 28 6
1
import logging
2
import os
3
import shlex
4
import subprocess
5
import sys
6
import tempfile
7
import textwrap
8
9
from .color import ERROR_COLOR
10
from .color import RESET_COLOR
11
from .os_compat import on_windows
12
13
14
def get_text_from_editor(config, template=""):
15
    filehandle, tmpfile = tempfile.mkstemp(prefix="jrnl", text=True, suffix=".txt")
16
    os.close(filehandle)
17
18
    with open(tmpfile, "w", encoding="utf-8") as f:
19
        if template:
20
            f.write(template)
21
22
    try:
23
        subprocess.call(shlex.split(config["editor"], posix=on_windows) + [tmpfile])
24
    except Exception as e:
25
        error_msg = f"""
26
        {ERROR_COLOR}{str(e)}{RESET_COLOR}
27
28
        Please check the 'editor' key in your config file for errors:
29
            {repr(config['editor'])}
30
        """
31
        print(textwrap.dedent(error_msg).strip(), file=sys.stderr)
32
        exit(1)
33
34
    with open(tmpfile, "r", encoding="utf-8") as f:
35
        raw = f.read()
36
    os.remove(tmpfile)
37
38
    if not raw:
39
        print("[Nothing saved to file]", file=sys.stderr)
40
41
    return raw
42
43
44
def get_text_from_stdin():
45
    _how_to_quit = "Ctrl+z and then Enter" if on_windows else "Ctrl+d"
46
    print(
47
        f"[Writing Entry; on a blank line, press {_how_to_quit} to finish writing]\n",
48
        file=sys.stderr,
49
    )
50
    try:
51
        raw = sys.stdin.read()
52
    except KeyboardInterrupt:
53
        logging.error("Write mode: keyboard interrupt")
54
        print("[Entry NOT saved to journal]", file=sys.stderr)
55
        sys.exit(0)
56
57
    return raw
58