summaryrefslogtreecommitdiffstats
path: root/nikola/plugins/command_new_post.py
blob: 36026bea254dc1859afaf629eb09ab42b3873d09 (plain) (blame)
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
# Copyright (c) 2012 Roberto Alsina y otros.

# Permission is hereby granted, free of charge, to any
# person obtaining a copy of this software and associated
# documentation files (the "Software"), to deal in the
# Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the
# Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice
# shall be included in all copies or substantial portions of
# the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
# KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
# WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
# PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
# OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
# OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

from __future__ import unicode_literals, print_function
import codecs
import datetime
from optparse import OptionParser
import os
import sys

from nikola.plugin_categories import Command
from nikola import utils


class CommandNewPost(Command):
    """Create a new post."""

    name = "new_post"

    def run(self, *args):
        """Create a new post."""
        parser = OptionParser(usage="nikola %s [options]" % self.name)
        parser.add_option('-p', '--page', dest='is_post',
            action='store_false',
            help='Create a page instead of a blog post.')
        parser.add_option('-t', '--title', dest='title',
            help='Title for the page/post.', default=None)
        parser.add_option('--tags', dest='tags',
            help='Comma-separated tags for the page/post.',
            default='')
        parser.add_option('-1', dest='onefile',
            action='store_true',
            help='Create post with embedded metadata (single file format).',
            default=self.site.config.get('ONE_FILE_POSTS', True))
        parser.add_option('-f', '--format',
            dest='post_format',
            default='rest',
            help='Format for post (rest or markdown)')
        (options, args) = parser.parse_args(list(args))

        is_post = options.is_post
        title = options.title
        tags = options.tags
        onefile = options.onefile
        post_format = options.post_format

        # Guess where we should put this
        for path, _, _, use_in_rss in self.site.config['post_pages']:
            if use_in_rss == is_post:
                break
        else:
            path = self.site.config['post_pages'][0][0]

        print("Creating New Post")
        print("-----------------\n")
        if title is None:
            print("Enter title: ")
            title = sys.stdin.readline().decode(sys.stdin.encoding).strip()
        else:
            print("Title: ", title)
        slug = utils.slugify(title)
        date = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
        data = [
            title,
            slug,
            date,
            tags
            ]
        output_path = os.path.dirname(path)
        meta_path = os.path.join(output_path, slug + ".meta")
        pattern = os.path.basename(path)
        if pattern.startswith("*."):
            suffix = pattern[1:]
        else:
            suffix = ".txt"
        txt_path = os.path.join(output_path, slug + suffix)

        if (not onefile and os.path.isfile(meta_path)) or \
            os.path.isfile(txt_path):
            print("The title already exists!")
            exit()

        if onefile:
            if post_format not in ('rest', 'markdown'):
                print("ERROR: Unknown post format %s" % post_format)
                return
            with codecs.open(txt_path, "wb+", "utf8") as fd:
                if post_format == 'markdown':
                    fd.write('<!-- \n')
                fd.write('.. title: %s\n' % title)
                fd.write('.. slug: %s\n' % slug)
                fd.write('.. date: %s\n' % date)
                fd.write('.. tags: %s\n' % tags)
                fd.write('.. link: \n')
                fd.write('.. description: \n')
                if post_format == 'markdown':
                    fd.write('-->\n')
                fd.write("\nWrite your post here.")
        else:
            with codecs.open(meta_path, "wb+", "utf8") as fd:
                fd.write(data)
            with codecs.open(txt_path, "wb+", "utf8") as fd:
                fd.write("Write your post here.")
            print("Your post's metadata is at: ", meta_path)
        print("Your post's text is at: ", txt_path)