aboutsummaryrefslogtreecommitdiff
path: root/wiki.py
blob: 4c69f6163c2b34bb94d47147919b5669cf109204 (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
#!/usr/bin/env python3

from datetime import datetime
from glob import glob
from zoneinfo import ZoneInfo
import contextlib
import os
import os.path
import subprocess
import sys
import time

@contextlib.contextmanager
def working_directory(dir):
    old_pwd = os.getcwd()
    try:
        os.chdir(dir)
        yield
    finally:
        os.chdir(old_pwd)

WIKIROOT = '/home/hugo/wiki'

WIKI_LIST = []
for file in os.listdir(WIKIROOT):
    path = os.path.join(WIKIROOT, file)
    if 'html' in file:
        continue
    if not os.path.isdir(path):
        continue
    WIKI_LIST.append(file)


def git(*args):
    base = 'git -c color.status=always -c color.ui=always'.split(' ')
    # print('git', args)
    cmdline = base + list(args)
    # TODO subprocess can't forward stdout to our file-like object
    #      and it doesn't tell us WHAT the problem is.
    #      This probably requires us to set up a proper pipe,
    #      and something which listen on that pipe.
    #      But multithreading in Python is *HaRd*.
    cmd = subprocess.run(cmdline, stdout=sys.stdout)


def commit(wiki, *msg):
    if not msg:
        now = datetime.now(Zoneinfo(time.tzname[0]))
        msg = f'{now:%Y-%m-%d %H:%M:%S %Z}'
    else:
        msg = ' '.join(msg)
    git('add', '-A')
    git('commit', '-m', msg)

def ammend(wiki, *msg):
    if not msg:
        git('commit', '--amend')
    else:
        msg = ' '.join(msg)
        git('commit', '--amend', '-m', msg)


def grep(wiki, *args):
    git('grep', '-E', '-i', ' '.join(args))


def go(*args):
    commit(wiki, *args)
    git('push')


def echo(wiki, *rest):
    print(f'-- {wiki} --')


commands = {
        'commit': commit,
        'ammend': ammend,
        'grep': grep,
        'g': go,
        'go': go,
        'echo': echo,
}


def wiki_do(wiki, command, *args):
    cmd = commands.get(command)
    with working_directory(os.path.join(WIKIROOT, wiki)):
        if cmd:
            cmd(wiki, *args)
        else:
            git(command, *args)

class Prepender:
    def __init__(self, prefix, to):
        self.buf = []
        self.prefix = prefix
        self.to = to

    def write(self, data):
        for c in data:
            if c == '\n':
                print(self.prefix + ':' + ''.join(self.buf), file=self.to)
                self.buf = []
            else:
                self.buf.append(c)


    def flush(self):
        if self.buf:
            print(self.prefix + ':' + ''.join(self.buf), file=self.to)
            self.buf = []


    def fileno(self):
        return -1

    # def read(size=-1):
    #     pass


def main():

    args = sys.argv[1:]
    wiki_list = []
    while args:
        if args[0] == '-w' or args[0] == '--wiki':
            wiki_list.append(args[1])
            args = args[2:]
            continue
        if args[0] == '-l' or args[0] == '--list':
            print("Available Wikis:")
            print("================")
            for wiki in WIKI_LIST:
                print(f' - {wiki}')
            sys.exit()
        if args[0] == '-h' or args[0] == '--help' or args[0] == '-?':
            help = '''
                Wiki helper. Usage:
                --help | -h :: Display this help
                --list | -l :: Show available wikis
                --wiki | -w <wiki> :: specify a specific wiki for operation

                Default acts on all wikis.

                wi commit [msg] :: Create a git commit on specified wikis
                wi ammend [msg] :: Change last commit
                wi g [msg] :: wi commit [msg]; wi push
                wi [git-command] :: run git commands on wikis
                '''
            for line in help.strip().split('\n'):
                print(line.strip())
            sys.exit()
        break

    if len(args) == 0:
        index = glob(os.path.join(WIKIROOT, 
                                  (wiki_list or WIKI_LIST)[0], 
                                  'index.*'))
        subprocess.run(['vim', index[0]])
    else:
        stdout = sys.stdout
        for wiki in wiki_list or WIKI_LIST:
            # TODO threads
            sys.stdout = Prepender(wiki, stdout)
            wiki_do(wiki, *args)


if __name__ == '__main__':
    main()