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
|
# Copyright 2010-2015 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/>.
#
# =*= License: GPL-3+ =*=
import os
import re
class DraftsDirectory(object):
def __init__(self, dirname):
self.dirname = dirname
def create_if_missing(self):
if not os.path.exists(self.dirname):
os.mkdir(self.dirname)
def get_draft_pathname(self, draft_id):
return os.path.join(self.dirname, '%s.mdwn' % draft_id)
def get_draft_attachments_dirname(self, draft_id):
return os.path.join(self.dirname, '%s' % draft_id)
def create_draft(self, content):
draft_id = self._pick_available_draft_id()
pathname = self.get_draft_pathname(draft_id)
with open(pathname, 'w') as f:
f.write(content.encode('utf8'))
return draft_id
def _pick_available_draft_id(self):
for i in range(1000):
pathname = self.get_draft_pathname(i)
if not os.path.exists(pathname):
return i
raise cliapp.AppException('ERROR: too many existing drafts')
def get_drafts(self):
for basename in os.listdir(self.dirname):
# .# is what Emacs autosave files start with.
if basename.endswith('.mdwn') and not basename.startswith('.#'):
suffixless = basename[:-len('.mdwn')]
pathname = os.path.join(self.dirname, basename)
yield suffixless, pathname
def remove_draft(self, draft_id):
filename = self.get_draft_pathname(draft_id)
os.remove(filename)
dirname = self.get_draft_attachments_dirname(draft_id)
if os.path.exists(dirname):
shutil.rmtree(dirname)
def get_draft_title(self, draft_id):
pathname = self.get_draft_pathname(draft_id)
with open(pathname) as f:
return self._get_title_from_open_file(f)
def _get_title_from_open_file(self, f):
for line in f:
m = re.match(r'\[\[!meta title="(?P<title>.*)("\]\])$', line)
if m:
return m.group('title')
return None
|