Skip to content

Instantly share code, notes, and snippets.

@simias
Created September 4, 2020 20:11
Show Gist options
  • Save simias/d23c057048ee81ab130c116f9f345649 to your computer and use it in GitHub Desktop.
Save simias/d23c057048ee81ab130c116f9f345649 to your computer and use it in GitHub Desktop.
#!/bin/sh
umask 077
# File extension for the notes
note_ext="md"
# Enable colors if stdout is a tty
if [ -t 1 ]
then
col_info=$(tput setaf 4)
col_warn=$(tput setaf 3)
col_error=$(tput setaf 1)
col_rst=$(tput sgr0)
fi
# Interactive if stdin is a tty
if [ -t 0 ]
then
interactive=1
else
interactive=0
fi
error() {
echo "${col_error}Error:${col_rst} $@" >&2
}
abort() {
error "$@"
exit 1
}
if [ "$NOTES_DIR" = '' ]
then
NOTES_DIR=$HOME/.notes
fi
if [ ! -d "$NOTES_DIR" ]
then
error "'$NOTES_DIR' does not exist or isn't a directory"
error "Create the directory or set NOTES_DIR in the environment"
exit 1
fi
while getopts 'h' opt
do
case $opt in
*)
echo "Usage: note [note-name]"
echo ""
echo "Note dir: $NOTES_DIR"
echo ""
echo "Set NOTE_DIR in your environment to change this path."
echo
echo "When called without an argument 'note' will start a full text"
echo "search through all available notes using fzf"
exit 1
;;
esac
done
exec_open_note() {
file="$NOTES_DIR/$1.$note_ext"
if [ "$interactive" -eq 1 ]
then
exec $EDITOR "$NOTES_DIR/$1.$note_ext"
else
# Non interactive use, redirect stdin
exec cat >> "$file"
fi
}
dump_notes() {
col_file=$(tput setaf 6)
col_rst=$(tput sgr0)
# Dump notes by modification time (more recent first)
ls -tr "$NOTES_DIR" | while read file
do
clean_file=$(echo $file | sed "s/\.$note_ext\$//")
full_file="$NOTES_DIR/$file"
cat "$full_file" | sed "s,^,${col_file}${clean_file}${col_rst}: ,"
done
}
if [ -n "$1" ]
then
# We got a note name as argument, create or open it
exec_open_note "$1"
else
# No argument, start FZF to search through existing notes
if [ "$interactive" -eq "1" ]
then
choice=$(dump_notes | fzf --ansi +m --height '50%' \
--prompt="Search notes > ")
if [ -z "$choice" ]
then
exit 1
fi
note=$(echo "$choice" | sed 's/: .*//')
exec_open_note "$note"
else
abort "note without arguments when the input isn't a terminal"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment