← All posts

Add git-blog - sdball/dotfiles

Commit e2f73fe from github.com/sdball/dotfiles

Turn my nicely written git commits into blog posts!

e2f73fe43722aeaa5bd9b9fc929f3e2c806bd7cb on sdball/dotfiles

added files

bin/git-blog

#!/usr/bin/env bash

set -Eeuo pipefail

usage() {
  cat <<EOF
Usage: $(basename "${BASH_SOURCE[0]}") COMMIT_HASH

Transforms the given COMMIT_HASH into a blog post.

Available options:

-h, --help      Print this help and exit
EOF
  exit
}


msg() {
  echo >&2 -e "${1-}"
}

die() {
  local msg=$1
  local code=${2-1} # default exit status 1
  msg "$msg"
  exit "$code"
}

parse_params() {
  while :; do
    case "${1-}" in
    -h | --help) usage ;;
    -?*) die "Unknown option: $1" ;;
    *) break ;;
    esac
    shift
  done

  args=("$@")
  if [[ ${#args[@]} -eq 0 ]]; then
    commit=$(latest-commit)
  else
    commit=$(git show "${args[0]}" --no-patch --format=e2f73fe43722aeaa5bd9b9fc929f3e2c806bd7cb)
  fi

  return 0
}

latest-commit() {
  git show --no-patch --format=e2f73fe43722aeaa5bd9b9fc929f3e2c806bd7cb
}

added-files() {
  commit=$1
  new_files=$(git show "$commit" --format="" --name-status | rg "^A" | awk '{print $2}')

  if [[ -n "$new_files" ]]; then
    echo
    echo "## added files"
    echo "$new_files" | while read -r f; do
      echo
      echo "### $f"
      echo
      echo '```'
      cat "$f"
      echo '```'
    done
  fi
}

modified-files() {
  commit=$1
  modified_files=$(git show "$commit" --format="" --name-status | rg "^M" | awk '{print $2}')

  if [[ -n "$modified_files" ]]; then
    echo
    echo "## modified files"
    echo "$modified_files" | while read -r f; do
      echo
      echo "### $f"
      echo
      echo '```diff'
      git show "$commit" --format="" --patch "$f"
      echo '```'
    done
  fi
}

blog-commit() {
  commit=$1
  git show "$commit" --format="Draft: yes
Date: 2023-01-08 14:35:35 -0500

# Add git-blog - $(repo)

Turn my nicely written git commits into blog posts!

$(commit-link "$commit")
$(added-files "$commit")
}

commit-link() {
  commit=$1
  echo "[$commit on $(repo)]($(repo-link)/commit/$commit)"
}

blog-file() {
  commit=$1
  git show "$commit" --no-patch --format="Add-git-blog.md"
}

repo() {
  git remote -v | rg fetch | awk -F: '{print $2}' | awk -F. '{print $1}'
}

repo-link() {
  git remote -v | rg fetch | awk -F: '{print $2}' | awk -F. '{print "https://github.com/" $1}'
}

main() {
  year=$(date +%Y)
  parse_params "$@"
  contents=$(blog-commit "$commit")
  filename=$(blog-file "$commit" | tr "[:upper:]" "[:lower:]")
  mkdir -p "$BLOG_DIR$year"
  msg "Writing to $BLOG_DIR$year/$filename"
  echo "$contents" > "$BLOG_DIR$year/$filename"
}

main "$@"

Commit e2f73fe from github.com/sdball/dotfiles