summaryrefslogtreecommitdiff
path: root/scripts/journal-note
blob: b3fa46673456ec1f6ad24c1ed531588cb6fa0fbe (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
172
173
174
175
176
177
178
179
180
181
182
183
#!/usr/bin/python
# Copyright 2010  Lars Wirzenius
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.


import optparse
import os
import re
import shutil
import subprocess
import sys
import tempfile
import time
import traceback


template = '''\
[[!meta title="%(title)s"]]
[[!tag ]]
[[!meta date="%(date)s"]]

'''


class AppException(Exception):

    pass


class App(object):

    def __init__(self):
        pass

    def parse_args(self):
        p = optparse.OptionParser()
        
        p.add_option('--base', default=os.path.expanduser('~/Journal'))
        
        return p.parse_args()

    def main(self):
        commands = {
            'new': self.new_entry,
            'list': self.list_entries,
            'edit': self.edit_entry,
            'attach': self.attach_entry,
            'remove': self.remove_entry,
            'finish': self.finish_entry,
        }
        
        opts, args = self.parse_args()
        if args and args[0] in commands:
            commands[args[0]](args[1:], opts)
        else:
            raise AppException('Usage: journal-note [options] cmd args...')

    def drafts(self, opts):
        return os.path.join(opts.base, 'drafts')

    def draftname(self, opts, draft_id):
        return os.path.join(opts.base, 'drafts', '%s.mdwn' % draft_id)

    def gedit_file(self, pathname):
        subprocess.check_call(['gedit', '--new-window', pathname])

    def new_entry(self, args, opts):
        if not args:
            raise AppException('Usage: journal-note new TITLE')

        for i in range(1000):
            name = self.draftname(opts, i)
            if not os.path.exists(name):
                break
        else:
            raise AppException('ERROR: too many existing drafts')

        values = {
            'title': args[0],
            'date': time.strftime('%Y-%m-%d %H:%M')
        }
        f = open(name, 'w')
        f.write(template % values)
        f.close()
        self.gedit_file(name)

    def list_entries(self, args, opts):
        drafts = self.drafts(opts)
        for name in os.listdir(drafts):
            if name.endswith('.mdwn'):
                f = open(os.path.join(drafts, name))
                for line in f:
                    m = re.match('\[\[!meta title="(?P<title>.*)("\]\])$',
                                 line)
                    if m:
                        title = m.group('title')
                        break
                else:
                    title = 'unknown title'
                f.close()
                print name[:-len('.mdwn')], title

    def edit_entry(self, args, opts):
        if not args:
            raise AppException('Usage: journal-note edit ID')
        pathname = self.draftname(opts, args[0])
        if not os.path.exists(pathname):
            raise AppException('draft %s does not exist' % args[0])
        self.gedit_file(pathname)

    def attach_entry(self, args, opts):
        if len(args) < 2:
            raise AppException('Usage: journal-note attach ID file...')
        pathname = self.draftname(opts, args[0])
        if not os.path.exists(pathname):
            raise AppException('draft %s does not exist' % args[0])
        dirname, ext = os.path.splitext(pathname)
        if not os.path.exists(dirname):
            os.mkdir(dirname)
        for filename in args[1:]:
            shutil.copy(filename, dirname)

    def remove_entry(self, args, opts):
        if not args:
            raise AppException('Usage: journal-note remove ID')
        pathname = self.draftname(opts, args[0])
        os.remove(pathname)

    def finish_entry(self, args, opts):
        if not args:
            raise AppException('Usage: journal-note finish ID')
        draft = self.draftname(opts, args[0])
        if not os.path.exists(draft):
            raise AppException('draft %s does not exist' % args[0])
        basename = time.strftime('%Y-%m-%d-%H:%M.mdwn')
        i = 0
        while True:
            finished = os.path.join(opts.base, 'src', 'notes', basename)
            if not os.path.exists(finished):
                break
            i += 1
            basename = '%s-%d.mdwn' % (time.strftime('%Y-%m-%d-%H:%M:%S-'), i)
        os.rename(draft, finished)
        
        draft_dir, ext = os.path.splitext(draft)
        if os.path.exists(draft_dir):
            finished_dir, ext = os.path.splitext(finished)
            shutil.copytree(draft_dir, finished_dir)
        
        src = os.path.join(opts.base, 'src')
        subprocess.check_call(['bzr', 'add', finished], cwd=src)
        subprocess.check_call(['bzr', 'commit', '-m', 'new note'], cwd=src)
        subprocess.check_call(['ikiwiki', '--setup', '../ikiwiki.setup',
                               '--refresh'], 
                              cwd=src)


if __name__ == '__main__':
    try:
        App().main()
    except KeyboardInterrupt:
        sys.exit(1)
    except AppException, e:
        sys.stderr.write('%s\n' % str(e))
        sys.exit(1)
    except SystemExit, e:
        sys.exit(e.code)
    except BaseException, e:
        sys.stderr.write(traceback.format_exc(e))
        sys.exit(1)