TODO in the terminal with git for synchronization


Today I cobbled together this bash script (thanks StackOverflow):


#!/usr/bin/env bash
# todo.sh

if ! [[ $0 != $BASH_SOURCE ]]
then
  echo "This script should be sourced, not ran."
  exit 1
fi

SCRIPT_DIR=$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )
todo() {
  GIT="git --git-dir=$SCRIPT_DIR/.git --work-tree=$SCRIPT_DIR"

  merge() {
    # Merge from repository
    $GIT fetch
    $GIT merge

    # Resolve conflicts if any
    CONFLICTS=$($GIT ls-files -u | wc -l)
    if [ "$CONFLICTS" -gt 0 ] ; then
      bash --init-file <(echo ". \"$HOME/.bashrc\"; echo \"There are merge conflicts in the git repository.\nPlease resolve these merge conflicts and exit this subshell when ready.\"; cd \"$SCRIPT_DIR\"; git status")
    fi
    CONFLICTS=$($GIT ls-files -u | wc -l)
    if [ "$CONFLICTS" -gt 0 ] ; then
       echo "The merge conflict was not resolved. Aborting"
       $GIT merge --abort
       exit 1
    fi
  }
  merge
  
  # Determine editor
  EDITOR="$(command -v sensible-editor)"
  EDITOR=${EDITOR:-${FCEDIT:-${VISUAL:-${EDITOR:-vi}}}}

  # Edit ToDo file
  "$EDITOR" "$SCRIPT_DIR/todo.txt"

  # Commit & push changes, if any
  if [[ `$GIT status --porcelain` ]]; then
    $GIT add "$SCRIPT_DIR"
    $GIT commit -m "todo update: $(date +%s)"
    if ! $GIT push
    then
      # Something went wrong with the push, probably a merge conflict on the
      #  other end. Merge and resolve conflicts.
      merge
      $GIT push
    fi
  fi
}

To use it:


Now you can run `todo` from the shell to open a TODO file, whose changes are automatically committed and pushed.


User beware: this is reasonably untested, I may come back to update this.



/gemlog/