mkpage

package module
v0.0.14 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 21, 2017 License: BSD-3-Clause Imports: 15 Imported by: 0

README

mkpage

mkpage (pronounced "make page") project is an experiment in decomposing web content management systems functionality into a series of simple command line tools -- mkpage, mkslide, mkrss, sitemapper, byline, titleline, reldocpath, slugify, and ws. This makes creating static websites simple.
Complex sites can be created with a little bit of Bash scripting.

This project started with the mkpage command.

mkpage command

The mkpage command is an experimental template engine with an embedded markdown processor. mkpage is a simple command line tool which accepts key value pairs and applies them to a Golang text/template. The key side of a pair corresponds to the template element names that will be replaced in the render version of the document. If a key was cllaed "pageContent" the template element would look like {{ .pageContent }}. The value of "pageContent" would replace {{ .pageContent }}. Go text/templates elements can do more than that but the is the core idea. On the value side of the key/value pair you have strings of one of three formats - plain text, markdown and JSON. These three formatted strings can be explicit strings, data from a file or content received from a URL. Here's a basic demonstration starting with the template.

    Date: {{ .now}}

    Hello {{ .name -}},
    
    Forecast:

    {{range .weather.data.text}}
       + {{ . }}
    {{end}}

    Thank you

    {{.signature}}

To render the template above (i.e. myformletter.tmpl) is expecting values from various data sources. This break down is as follows.

  • "now" and "name" are explicit strings
  • "weather" comes from a URL of JSON content
  • "signature" comes from a file in our local disc

Here is how we would express the key/value pairs on the command line.

    mkpage "now=text:$(date)" \
        "name=text:Little Frieda" \
        "weather=http://forecast.weather.gov/MapClick.php?lat=13.47190933300044&lon=144.74977715100056&FcstType=json" \
        signature=testdata/signature.txt \
        testdata/myformletter.tmpl

Notice the two explicit strings are prefixed with "text:" (other possible formats are "markdown:", "json:"). Values without a prefix are assumed to be file paths. We see that in testdata/signature.txt. Likewise the weather data is coming from a URL. mkpage distinguishes that by the prefixes "http://" and "https://". Since a HTTP response contains headers describing the content type (e.g. "Content-Type: text/markdown") we do not require any other prefix. Likewise a filename's extension can give us an inference of the data format it contains. ".json" is a JSON document, ".md" is a Markdown document and everything else is just plain text.

Since we are leveraging Go's text/template the template itself can be more than a simple substitution. It can contain conditional expressions, ranges for data and even include blocks from other templates.

Templates

mkpage template engine is the Go text/template package. Other template systems could be implemented but I'm keeping the experiment simple at this point.

Conditional elements

One nice feature of Go's text/template DSL is that template elements can be condition. This can be done using the "if" and "with" template functions. Here's how to show a title conditionally using the "if" function.

    {{if .title}}And the title is: {{.title}}{{end}}

or using "with"

    {{with .title}}{{ . }}{{end}}
Template blocks

Go text/templates support defining blocks and rendering them in conjuction with a main template. This is also supported by mkpage. For each template encountered on the command line it is added to an array of templates parsed by the text/template package. Collectively they are then executed which causes final results render to stdout by mkpage.

    mkpage "content=text:Hello World" testdata/page.tmpl testdata/header.tmpl testdata/footer.tmpl

Here is what page.tmpl would look like

    {{template "header" . }}

        {{.content}}

    {{template "footer" . }}

The header and footer are then defined in their own template files (though they also could be combined into one or even be defined in the main template file itself).

header.tmpl

    {{define "header"}}This is the document header{{end}}

footer.tmpl

    {{define "footer"}}This is the footer{{end}}

In this example the output would look like

    This is the document header

        Hello World

    This is the footer

Content formats and data sources

mkpage support three content formats

  • text/plain (e.g. "text:" when specifying strings and any file expect those having the extension ".md" or ".json")
  • text/markdown (e.g. "markdown:" when specifying strings, file extension ".md")
  • application/json (e.g. "json:" when specifying strings, file extension ".json")

It also supports three data sources

  • an explicit string (prefixed with a hint, e.g. "text:", "markdown:", "json:")
  • a filepath and filename
  • a URL

Content type is evaluate and if necessary transformed before going into the Go text/template.

A note about Markdown dialect

In additional to populating a template with values from data sources mkpage also includes the blackfriday markdown processor. The blackfriday.MarkdownCommon() function is envoked whenever markdown content is suggested. That means for strings that have the "markdown:" hint prefix, files ending in ".md" file extension or URL content with the content type returned as "text/markdown".

Options

  • -h, -help - get command line help
  • -v, -version - show mkpage version number
  • -l, -license - show mkpage license information
  • -t, -template - show mkpage's default template

Companion utilities

mkpage comes with some helper utilities that make scripting a deconstructed content management system from Bash easier.

mkslides

mkslides generates a set of HTML5 slides from a single Markdown file. It uses the same template engine as mkpage

mkrss

mkrss will scan a directory tree for Markdown files and add each markdown file with a corresponding HTML file to the RSS feed generated.

byline

byline will look inside a markdown file and return the first byline it finds or an empty string if it finds none. The byline is identified with a regular expression. This regular expression can be overriden with a command line option.

titleline

titleline will look inside a markdown file and return the first h1 exquivalent title it finds or an empty string if it finds none.

reldocpath

reldocpath is intended to simplify the calculation of relative asset paths (e.g. common css files, images, feeds) when working from a common project directory.

Example

You know the path from the source document to target document from the project root folder.

  • Source is course/week/01/readings.html
  • Target is css/site.css.

In Bash this would look like--

    # We know the paths relative to the project directory
    DOC_PATH="course/week/01/readings.html"
    CSS_PATH="css/site.css"
    echo $(reldocpath $DOC_PATH $CSS_PATH)

the output would look like

    ../../../css/site.css
slugify

slugify takes one or more command line args (e.g. a phrase like "Hello World") and return an updated version that is more friendly for filenames and URLS (e.g. "Hello-World").

Example
    slugify My thoughts on functional programming

Would yield

    My-thoughts-on-functional-programming
ws

ws is a simple static file webserver. It is suitable for viewing your local copy of your static website on your machine. It runs with minimal resources and by default will serve content out to the URL http://localhost:8000. It can also be used to host a static website and has run well on small Amazon virtual machines as well as Raspberry Pi computers acting as local private network web servers.

Example
    ws Sites/mysite.example.org

This would start the webserver up listen for browser requests on http://localhost:8000. The content viewable by your web browser would be the files inside the Sites/mysite.example.org directory.

    ws -url http://mysite.example.org:80 Sites/mysite.example.org

Assume the machine where you are running ws has the name mysite.example.org then your could point your web browser at http://mysite.example.org and see the web content you have in Site/mysite.example.org directory.

Documentation

Overview

Package mkpage is an experiment in a light weight template and markdown processor.

@author R. S. Doiel, <rsdoiel@caltech.edu>

Copyright (c) 2016, Caltech All rights not granted herein are expressly reserved by Caltech.

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Package provides the core library used by cmds/ws/ws.go

@author R. S. Doiel, <rsdoiel@caltech.edu>

Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech

Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.

2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.

3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Index

Constants

View Source
const (
	// Version of the mkpage package.
	Version = "v0.0.14"

	// LicenseText provides a string template for rendering cli license info
	LicenseText = `` /* 1530-byte string literal not displayed */

	// JSONPrefix designates a string as JSON formatted content
	JSONPrefix = "json:"
	// MarkdownPrefix designates a string as Markdown content
	MarkdownPrefix = "markdown:"
	// TextPrefix designates a string as text/plain not needed processing
	TextPrefix = "text:"

	// DefaultTemplateSource holds the default HTML provided by mkpage package, you probably want to override this...
	DefaultTemplateSource = `` /* 4707-byte string literal not displayed */

	// DateExp is the default format used by mkpage utilities for date exp
	DateExp = `[0-9][0-9][0-9][0-9]-[0-1][0-9]-[0-3][0-9]`
	// BylineExp is the default format used by mkpage utilities
	BylineExp = (`^[B|b]y\s+(\w|\s|.)+` + DateExp + "$")
	// TitleExp is the default format used by mkpage utilities
	TitleExp = `^#\s+(\w|\s|.)+$`
)

Variables

View Source
var (
	// DefaultSlideTemplateSource provides the default HTML template for mkslides package, you probably want to override this...
	DefaultSlideTemplateSource = `` /* 1847-byte string literal not displayed */

)

Functions

func Grep added in v0.0.14

func Grep(exp string, src string) string

Grep looks for the first line matching the expression in src.

func IsDotPath added in v0.0.13

func IsDotPath(p string) bool

IsDotPath checks to see if a path is requested with a dot file (e.g. docs/.git/* or docs/.htaccess)

func MakePage

func MakePage(wr io.Writer, tmpl *template.Template, keyValues map[string]string) error

MakePage applies the key/value map to the template and renders to writer and returns an error if something goes wrong

func MakePageString added in v0.0.5

func MakePageString(tmpl *template.Template, keyValues map[string]string) (string, error)

MakePageString applies the key/value map to the template and renders the results to a string and error if someting goes wrong

func MakeSlide added in v0.0.12

func MakeSlide(wr io.Writer, tmpl *template.Template, slide *Slide) error

MakeSlide this takes a io.Writer, a template and slide and executes the template.

func MakeSlideFile added in v0.0.12

func MakeSlideFile(tmpl *template.Template, slide *Slide) error

MakeSlideFile this takes a template and slide and renders the results to a file.

func MakeSlideString added in v0.0.12

func MakeSlideString(tmpl *template.Template, slide *Slide) (string, error)

MakeSlideString this takes a template and slide and renders the results to a string

func NormalizeDate added in v0.0.14

func NormalizeDate(s string) (time.Time, error)

NormalizeDate takes a MySQL like date string and returns a time.Time or error

func RelativeDocPath added in v0.0.11

func RelativeDocPath(source, target string) string

RelativeDocPath calculate the relative path from source to target based on implied common base.

Example:

docPath := "docs/chapter-01/lesson-02.html"
cssPath := "css/site.css"
fmt.Printf("<link href=%q>\n", MakeRelativePath(docPath, cssPath))

Output:

<link href="../../css/site.css">

func RequestLogger added in v0.0.13

func RequestLogger(next http.Handler) http.Handler

RequestLogger logs the request based on the request object passed into it.

func ResolveData

func ResolveData(data map[string]string) (map[string]interface{}, error)

ResolveData takes a data map and reads in the files and URL sources as needed turning the data into strings to be applied to the template.

func ResponseLogger added in v0.0.13

func ResponseLogger(r *http.Request, status int, err error)

ResponseLogger logs the response based on a request, status and error message

func StaticRouter added in v0.0.13

func StaticRouter(next http.Handler) http.Handler

StaticRouter scans the request object to either add a .html extension or prevent serving a dot file path

func Walk added in v0.0.14

func Walk(startPath string, filterFn func(p string, info os.FileInfo) bool, outputFn func(s string, info os.FileInfo) error) error

Walk takes a start path and walks the file system to process Markdown files for useful elements.

Types

type Slide added in v0.0.12

type Slide struct {
	CurNo   int
	PrevNo  int
	NextNo  int
	FirstNo int
	LastNo  int
	FName   string
	Title   string
	Content string
	CSSPath string
	JSPath  string
}

Slide is the metadata about a slide to be generated.

func MarkdownToSlides added in v0.0.12

func MarkdownToSlides(fname, title, cssPath, jsPath string, mdSource []byte) []*Slide

MarkdownToSlides turns a markdown file into one or more Slide using the fname, title and cssPath provided

Directories

Path Synopsis
cmds
byline command
byline reads a Markdown file and returns the first byline encountered.
byline reads a Markdown file and returns the first byline encountered.
mkpage command
mkpage is a thought experiment in a light weight template and markdown processor @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
mkpage is a thought experiment in a light weight template and markdown processor @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
mkrss command
mkrss.go is a command line tool for generating an RSS file from a blog directory structure in the form of PATH_TO_BLOG/YYYY/MM/DD/BLOG_ARTICLES.html @Author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
mkrss.go is a command line tool for generating an RSS file from a blog directory structure in the form of PATH_TO_BLOG/YYYY/MM/DD/BLOG_ARTICLES.html @Author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
mkslides command
mkslides.go - A simple command line utility that uses Markdown to generate a sequence of HTML5 pages that can be used for presentations.
mkslides.go - A simple command line utility that uses Markdown to generate a sequence of HTML5 pages that can be used for presentations.
reldocpath command
reldocpath.go takes a source document path and a target document path with same base path returning a relative path to the target file.
reldocpath.go takes a source document path and a target document path with same base path returning a relative path to the target file.
sitemapper command
sitemapper generates a sitemap.xml file by crawling the content generate with genpages @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
sitemapper generates a sitemap.xml file by crawling the content generate with genpages @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech.
slugify command
slugify.go turn a human readable string into a URL/path friendly string @Author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2016, Caltech All rights not granted herein are expressly reserved by Caltech.
slugify.go turn a human readable string into a URL/path friendly string @Author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2016, Caltech All rights not granted herein are expressly reserved by Caltech.
titleline command
titleine reads a Markdown file and returns the first title encountered.
titleine reads a Markdown file and returns the first title encountered.
ws command
ws.go - A simple web server for static files and limit server side JavaScript @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1.
ws.go - A simple web server for static files and limit server side JavaScript @author R. S. Doiel, <rsdoiel@caltech.edu> Copyright (c) 2017, Caltech All rights not granted herein are expressly reserved by Caltech Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL