Jekyll Skripte

07.07.2016 12:14 | keine Kommentare

In den vergangenen zwei Tagen habe ich ein wenig am Veröffentlichungsprozess von neuen Einträgen gearbeitet und zusätzlich diese "Kurzbeiträge" eingeführt. Sehr spannende Sache. Neben ein paar Zeilen Python habe ich zusätzlich auch noch einiges über Jekyll gelernt. Mein Deploy-Script zum eigentlichen Hochladen auf den Server habe ich bereits mal gezeigt, deshalb hier nur das Skript zum Verfassen der neuen Einträge sowie ein paar nützliche Aliase.

export JEKYLL_ROOT_DIR=myDir/varakh.de
alias jekyll-post='jekyll-post -D $JEKYLL_ROOT_DIR/_posts -w'
alias jekyll-post-short='jekyll-post -D $JEKYLL_ROOT_DIR/_posts -w -s'
alias jekyll-preview='chromium http://127.0.0.1:4000 && cd $JEKYLL_ROOT_DIR && jekyll s'

In einem Kurzbeitrag gibt es auch ein kleines Webcast, auch wenn sich die Optionen leicht geändert haben. Ich veröffentliche nun also einfach mit den folgenden Zeilen:

jekyll-post(-short)
Eintrag schreiben
jekyll-preview
jekyll-deploy

Kürzer geht es wohl nicht mehr. Anbei das Python Script.

#!/usr/bin/env python

"""
jekyll-post - this is a simple script that will create and initialize a new
Jekyll post file. The default is a markdown file (.md) and the yaml options
listed below will be part of the initialization.

jekyll-post [-w] [-d date] [-D dir] [-o] [-h headline]

-h      the headline of the post wrapped in es, e.g. "post headline here"
-D      the directory (relative or absolute) that the file should be written to.
-d      the default date is today's date or this option can be used to specify
        a date. The date must be specified in the format YYYY-MM-DD.
-n      the name for the post file instead of using the automatically generated one.
-t      the tags that should be added to the yaml portion of the file separated
        by spaces and the whole thing wrapped in es.
-w      this optional flag will signal the file to be opened for writing in vi.
-s      short (set short true [automated title = id will be generated])

yaml options
---
title: headline
tags:
- tag1
- tag2
- tag3
---
"""

# Import Statements
import argparse
import datetime
import subprocess
import os.path
import sys
import datetime
import os.path
import os
from random import choice
from string import digits

# helpers
def generateRandomNumericSequence(length):
    str = ''.join(choice(digits) for i in range(length))
    return str

def generateNumericTitle(length, searchDir):
    str = generateRandomNumericSequence(length)

    # search for existence
    alreadyExists = False

    while not alreadyExists:
        print("Searching for existence of " + str + " in " + searchDir + " file names.")
        foundMatching = False

        for file in os.listdir(searchDir):
            if str in file:
                print("FAILED on " + file)
                foundMatching = True
                break

        if foundMatching:
            str = generateRandomNumericSequence(length)
            print("Generating new.")
        else:
            print("OK. " + str + " is unique.")
            alreadyExists = True

        return str

DEFAULT_NUMERIC_TITLE_LENGTH = 16
DEFAULT_EXT = 'markdown'
DEFAULT_EDITOR = os.environ['EDITOR']
DEFAULT_SEARCH_POSTS_DIR = os.environ['JEKYLL_ROOT_DIR']

def main():
    # parse the arguments
    parser = argparse.ArgumentParser(description='Create a new Jekyll post.')
    parser.add_argument('-hl', '--headline', help='the headline of the post wrapped in es.')
    parser.add_argument('-D', '--Dir', help='specify the directory (relative or absolute) that the file should be written to.')
    parser.add_argument('-d', '--date', help='specify the post date in the format YYYY-MM-DD, otherwise today is the default date.')
    parser.add_argument('-s', '--short', action="store_true", help='Create short post. Automated title ID will be generated which is hidden in templates.')
    parser.add_argument('-n', '--name', help='specify the name of the post file instead of the automatically generated one. It is a best practice for the words to be separated by hyphens. Also note that the given name will be prepended with the date so as to conform to Jekyll naming requirements.')
    parser.add_argument('-t', '--tags', help='specify a set of tags for the post separated by spaces with the entire set wrapped in es (e.g. "tag1 tag2 tag3").')
    parser.add_argument('-w', '--write', action="store_true", help='signals if this file should be opened for writing after creation')
    args = parser.parse_args()

# headline/title, generate if none is given
    if not args.headline:
        title = generateNumericTitle(DEFAULT_NUMERIC_TITLE_LENGTH, DEFAULT_SEARCH_POSTS_DIR)
    else:
        title = args.headline

    # exchange spaces for dashes
    dash_title = ''
    if args.name:
        dash_title = args.name.replace(' ','-')
    else:
        dash_title = title.replace(' ','-')

    # clean up any special characters from the dash-title
    temp_title = '';
    for char in dash_title:
        if char.isalnum() or char == '-':
            temp_title += char
    dash_title = temp_title.lower()

    date = None
    if args.date:
        date = args.date
    else:
        # use today's date
        today = datetime.datetime.now()
        year = str(today.year)
        month = str(today.month)
        if len(month) == 1:
            month = '0' + month
        #month = today.month > 9 ? str(today.month) : '0' + str(today.month)
        day = str(today.day)
        if len(day) == 1:
            day = '0' + day
        #day = today.day > 9 ? str(today.day) : '0' + str(today.day)
        date = "-".join([year,month,day])

    #filename = '%s-%s.%s', date, title, DEFAULT_EXT
    filename = date + '-' + dash_title + '.' + DEFAULT_EXT

    # if Dir is specified, append to front of filename
    if args.Dir:
        filename = args.Dir + '/' + filename

    # check if the desired file already exists
    if os.path.exists(filename):
        # file already exists, abort the program
        print(filename + ' already exists.')
        print('Jekyll post NOT created.')
        sys.exit(1)

    # collect any tags included in the args
    tags = []
    if args.tags:
        tags = args.tags.split(' ')

    # collect date
    now = datetime.datetime.now()

    # try writing yaml to the post file
    try:
        f = open(filename, 'w')

        # write yaml to file
        try:
            f.write('---\n')
            f.write('title: ' + title + '\n')
            f.write('date: ' + now.strftime("%Y-%m-%d %H:%M:%S") + '\n')
            if args.short:
                f.write('short: true\n')
            if tags:
                f.write('tags:\n')
                for tag in tags:
                    f.write('- ' + tag + '\n')
            f.write('---\n\n\n')
        finally:
            f.close()
    except IOError:
        print('Issue writing to Jekyll post file.')

    # if write flag is on, then try to open file with vi
    if args.write:
        subprocess.call([DEFAULT_EDITOR, filename])

    # print confirmation statement
    print('New Jekyll post "' + title + '" has been created -- ' + filename)

if __name__ == '__main__':
    main()

Kommentare

Keine Daten vorhanden.

Mit dem Absenden des Formulars akzeptiere ich die Datenschutzbestimmungen dieses Dienstes.