aboutsummaryrefslogtreecommitdiff
path: root/wikijscmd/util.py
blob: e16bf85029a8975631ac33b49205e3ead9fc68af (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
from wikijscmd import graphql_queries
from wikijscmd import custom_requests
import subprocess
import re
import os

def print_item(item):
    trimmed_title = item["title"][:17]+"..." if len(item["title"]) > 20 else item["title"]
    print("| %6s | %-44s | %20s |" % (item["id"], item["path"], trimmed_title) )

def get_single_page(path):
    """
    Gets the page from the wiki with the given path
    """
    if path.startswith("/"):
        path = path[1:]
    for item in graphql_queries.get_tree()["data"]["pages"]["list"]:
        if path == item["path"]:
            page_id = int(item["id"])
            response = graphql_queries.get_single_page(page_id)
            return response["data"]["pages"]["single"]
    return None

def get_tree(regex):
    response = graphql_queries.get_tree()
    pages = []
    for item in response["data"]["pages"]["list"]:
        if not re.search(regex, item["path"]):
            continue
        pages.append(item)
    return pages

def clean_filename(pathname):
    """
    Clean the path so that it can be used as a filename
    """
    pathname = str(pathname).strip().replace('/', '_')
    pathname = re.sub(r'\W', '', pathname)
    return pathname[:200]

def open_editor(action, pathname, initial_body):
    """
    Open a page with the given pathname and intial_body in an editor, using
    action in the filename. Returns the content of the edited file.
    """
    if "VISUAL" in os.environ:
        editor = os.environ['VISUAL']
    else:
        editor = os.environ['EDITOR']
    filename = "/tmp/wikijscmd-"+action+"-"+clean_filename(pathname)+".md"
    if len(initial_body) > 0:
        with open(filename, "w") as f:
            f.write(initial_body)
    subprocess.run([editor, filename])
    with open(filename, "r") as f:
        new_body = f.read()
    os.remove(filename)
    return new_body

def args_for_date(date):
    obj = {
        "path": date.strftime("journal/%Y/%b/%d").lower(),
        "title": date.strftime("%B %-d"),
    }
    date_content_json = custom_requests.query_date(date.strftime("%Y-%m-%d"))
    if date_content_json:
        date_content = ""
        for item in date_content_json:
            if item.get("key"):
                date_content += f'{item["datatype"]}: {item["key"]}-{item["value"]}\n'
            else:
                date_content += f'{item["datatype"]}: {item["value"]}\n'
        obj["content"] = str(date_content)
    return obj