octalzeroes

Editing posts in Haste using Redis

published on 06 Oct 2014, tagged with zsh haste redis

Most people are probably familiar with services like pastebin. It is a very handy tool commonly used by programmers that want to share snippets of code. So a while back I decided to host a service like this for me and my friends. I found hastebin which is an open source alternative with features like syntax highlighting which makes code more readable.

The server allows you to use different methods of storage. I wanted to give Redis a try.

Redis is an open source, BSD licensed, advanced key-value cache and store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets, sorted sets, bitmaps and hyperloglogs.

Having run Haste for quite some time now I realized that a function to edit posts would be useful. Since I'm always connected to the machine running the application I could just easily write a shellscript to perform this task. To interact with the redis server there's a tool called redis-cli which is run in the shell. For a full list of commands one can have a look at the following page.

There's a lot of commands here but I only need the ability to SET a certain key. The key is passed as a parameter in the url. This is the function I ended up with:

function hastedit() {
  local tempfile id

  # error checking
  [[ ! -f =redis-cli ]] && return
  [[ $1 =~ "paste[^/]*/([^\.$]*)" ]] && id="$match" || { echo "invalid url"; return }
  [[ $(redis-cli -n 2 EXISTS $id) -eq 0 ]] && { echo "no such paste"; return }

  tempfile="$(mktemp)"
  redis-cli -n 2 GET "$id" > "$tempfile"
  ${EDITOR:-vim} "$tempfile"
  echo -n "$(cat $tempfile)" | redis-cli -x -n 2 SET "$id"
  rm $tempfile
}

I have 2 variables local to the function. The purpose of these are to store the path to a file and the id to the post we want to edit.

Next I needed some error checking.

  • Make sure that redis-cli is available in $PATH
  • Argument passed is the full URL to the paste. It looks something like http://paste.example.org/<id>.ext
    • using a group we extract the <id>
  • Query the redis server to check if key is valid

If we have come this far we are good to go

  • create a temporary file
  • store contents of the specified key in the file
  • use your $EDITOR (defaults to vim) to edit the file
  • at first I just sent the file to standard input but I wanted to get rid of the trailing newline, hence the -n argument to echo
  • remove temporary file