summaryrefslogtreecommitdiff
path: root/jtlib/draftsdir.py
diff options
context:
space:
mode:
Diffstat (limited to 'jtlib/draftsdir.py')
-rw-r--r--jtlib/draftsdir.py78
1 files changed, 78 insertions, 0 deletions
diff --git a/jtlib/draftsdir.py b/jtlib/draftsdir.py
new file mode 100644
index 0000000..59eb47d
--- /dev/null
+++ b/jtlib/draftsdir.py
@@ -0,0 +1,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)
+ 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