diff options
Diffstat (limited to 'jtlib/plugins/finish_plugin.py')
-rw-r--r-- | jtlib/plugins/finish_plugin.py | 87 |
1 files changed, 87 insertions, 0 deletions
diff --git a/jtlib/plugins/finish_plugin.py b/jtlib/plugins/finish_plugin.py new file mode 100644 index 0000000..b443a9f --- /dev/null +++ b/jtlib/plugins/finish_plugin.py @@ -0,0 +1,87 @@ +# 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/>. + + +import cliapp +import os +import shutil +import string +import time + +import jtlib + + +class FinishCommand(cliapp.Plugin): + + def enable(self): + self.app.add_subcommand('finish', self.run, arg_synopsis='[DRAFT-ID]') + + def run(self, args): + '''Publish a draft journal entry.''' + + drafts_dir = jtlib.DraftsDirectory(self.app.drafts_dir()) + + draft_id, draft_mdwn = self.app.choose_draft(drafts_dir, args) + draft_attch = drafts_dir.get_draft_attachments_dirname(draft_id) + + title = drafts_dir.get_draft_title(draft_id) + if not title: + raise Exception("%s has no title" % draft_mdwn) + + pub_attch = os.path.join( + self._published_dir(), + self._summarise_title(title)) + pub_mdwn = pub_attch + '.mdwn' + + if os.path.exists(pub_mdwn): + raise cliapp.AppException('%s already exists' % pub_mdwn) + + self._publish_draft(draft_mdwn, draft_attch, pub_mdwn, pub_attch) + + if self.app.settings['git']: + if os.path.exists(pub_attch): + self._commit_to_git([pub_mdwn, pub_attch]) + else: + self._commit_to_git([pub_mdwn]) + if self.app.settings['push']: + self._push_git() + + def _published_dir(self): + subdir = time.strftime('notes/%Y/%m/%d', self.app.now_tuple) + return os.path.join(self.app.settings['source'], subdir) + + def _summarise_title(self, title): + basename = '' + acceptable = set(string.ascii_letters + string.digits + '-_') + for c in title.lower(): + if c in acceptable: + basename += c + elif not basename.endswith('_'): + basename += '_' + return basename + + def _publish_draft(self, draft_mdwn, draft_attch, pub_mdwn, pub_attch): + parent_dir = os.path.dirname(pub_mdwn) + if not os.path.exists(parent_dir): + os.makedirs(parent_dir) + os.rename(draft_mdwn, pub_mdwn) + if os.path.exists(draft_attch): + os.rename(draft_attch, pub_attch) + + def _commit_to_git(self, pathnames): + jtlib.commit_to_git(self.app.settings['source'], pathnames) + + def _push_git(self): + jtlib.push_git(self.app.settings['source']) |