|
| 1 | +module Jekyll |
| 2 | + module Commands |
| 3 | + class Post < Command |
| 4 | + def self.init_with_program(prog) |
| 5 | + prog.command(:post) do |c| |
| 6 | + c.syntax 'post NAME' |
| 7 | + c.description 'Creates a new post with the given NAME' |
| 8 | + |
| 9 | + c.option 'type', '-t TYPE', '--type TYPE', 'Specify the content type' |
| 10 | + c.option 'layout', '-t LAYOUT', '--layout LAYOUT', 'Specify the post layout' |
| 11 | + c.option 'date', '-d DATE', '--date DATE', 'Specify the post date' |
| 12 | + c.option 'force', '-f', '--force', 'Overwrite a post if it already exists' |
| 13 | + |
| 14 | + c.action do |args, options| |
| 15 | + Jekyll::Commands::Post.process(args, options) |
| 16 | + end |
| 17 | + end |
| 18 | + end |
| 19 | + |
| 20 | + def self.process(args, options = {}) |
| 21 | + raise ArgumentError.new('You must specify a name.') if args.empty? |
| 22 | + |
| 23 | + type = options["type"].nil? ? "markdown" : options["type"] |
| 24 | + layout = options["layout"].nil? ? "post" : options["layout"] |
| 25 | + |
| 26 | + date = options["date"].nil? ? Time.now : DateTime.parse(options["date"]) |
| 27 | + |
| 28 | + title = args.shift |
| 29 | + name = title.gsub(' ', '-').downcase |
| 30 | + |
| 31 | + post_path = file_name(name, type, date) |
| 32 | + |
| 33 | + raise ArgumentError.new("A post already exists at ./#{post_path}") if File.exist?(post_path) and !options["force"] |
| 34 | + |
| 35 | + File.open(post_path, "w") do |f| |
| 36 | + f.puts(front_matter(layout, title)) |
| 37 | + end |
| 38 | + |
| 39 | + puts "New post created at ./#{post_path}.\n" |
| 40 | + end |
| 41 | + # Internal: Gets the filename of the draft to be created |
| 42 | + # |
| 43 | + # Returns the filename of the draft, as a String |
| 44 | + def self.file_name(name, ext, date) |
| 45 | + "_posts/#{date.strftime('%Y-%m-%d')}-#{name}.#{ext}" |
| 46 | + end |
| 47 | + |
| 48 | + def self.front_matter(layout, title) |
| 49 | + "--- |
| 50 | +layout: #{layout} |
| 51 | +title: #{title} |
| 52 | +---" |
| 53 | + end |
| 54 | + end |
| 55 | + end |
| 56 | +end |
0 commit comments