Public
Snippet $11208 authored by Andrea Scarpino

A script to export posts from Ghost to Markdown/HTML files

Edited
ghost2nanoc
#!/bin/sh
#
# A script to export posts from Ghost to HTML or Markdown format.
#
# Author: Andrea Scarpino <me@andreascarpino.it>

DBPATH="${1}"
FORMAT="${2}"

SQLITE="/usr/bin/sqlite3"

SQLCMD="${SQLITE} ${DBPATH}"
TMPDIR="$(mktemp --directory)"

usage() {
  echo "Exports posts from Ghost database to either Markdown or HTML format"
  echo
  echo "Usage: $(basename $0) <path to ghost db> [--format]"
  echo
  echo "  --format: either HTML or MARKDOWN (default)"
  echo
}

error()
{
  echo "ERROR: ${1}"
  exit 1
}

get_slug()
{
  unset slug
  slug="$($SQLCMD "SELECT slug FROM posts WHERE id=${1}")" || error "Cannot read slug!"
}

get_title()
{
  unset title
  title="$($SQLCMD "SELECT title FROM posts WHERE id=${1}")" || error "Cannot read title!"
}

get_date()
{
  unset date
  local ts="$($SQLCMD "SELECT published_at FROM posts WHERE id=${1}")" || error "Cannot read created_at!"
  date="$(date -d @$(expr ${ts} / 1000) +'%Y-%m-%d')"
}

get_text()
{
  unset text
  if [ "${FORMAT}" == "md" ]; then
    text="$(${SQLCMD} "SELECT markdown FROM posts WHERE id=${1}")" || error "Cannot read MD text!"
  else
    text="$(${SQLCMD} "SELECT html FROM posts WHERE id=${1}")" || error "Cannot read HTML text!"
  fi
}

get_tags()
{
  unset tags

  tag_ids="$(${SQLCMD} "SELECT tag_id FROM posts_tags WHERE post_id=${1}")" || error "Cannot read tags!"

  for tag in ${tag_ids[@]}; do
    local tagname="$(${SQLCMD} "SELECT name FROM tags WHERE id=${tag}")" || error "Cannot read tags!"
    if [ -z "${tags}" ]; then
      tags="'${tagname}'"
    else
      tags="${tags}, '${tagname}'"
    fi
  done
}

main()
{
  if [ "$#" -lt "1" ]; then
    usage
    exit 1
  fi

  ids="$(${SQLCMD} "SELECT id FROM posts WHERE status='published'")"
  [ "$?" -ne 0 ] && error "Cannot read posts!"

  if [ "${FORMAT,,}" != "html" ]; then
    FORMAT="md"
  else
    FORMAT="html"
  fi

  for id in ${ids[@]}; do

    get_slug "${id}"
    get_title "${id}"
    get_date "${id}"
    get_text "${id}"
    get_tags "${id}"

    echo -e "\tProcessing: ${title}"

    filename="$TMPDIR/${slug}.${FORMAT}"

    touch "${filename}" || error "Cannot save post!"
    echo "---" >> "${filename}"
    echo "kind: article" >> "${filename}"
    echo "title: ${title}" >> "${filename}"
    echo "tags: [${tags}]" >> "${filename}"
    echo "created_at: ${date}" >> "${filename}"
    echo "---" >> "${filename}"
    echo "${text}" >> "${filename}"
  done

  echo "Saved $(ls ${TMPDIR}/*.${FORMAT} | wc -l) posts as ${FORMAT^^} files to ${TMPDIR}!"
}

main $@

exit 0