Skip to content

Commit

Permalink
bash-completion: Support spaces in note names
Browse files Browse the repository at this point in the history
This also introduces a basic test-suite for the bash completion
  • Loading branch information
Linus Wallgren committed Dec 3, 2016
1 parent b52e0b5 commit 7b1fa74
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
13 changes: 10 additions & 3 deletions notes.bash_completion
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,25 @@
_notes_complete_notes() {
local configured_dir=${NOTES_DIRECTORY%/} # Remove trailing slashes
local notes_dir="${configured_dir:-$HOME/notes}"
local items=($(compgen -f "$notes_dir/$1"))
local OLD_IFS="$IFS"
IFS=$'\n'
local items=($(compgen -f "$notes_dir/$1" | sort ))
IFS="$OLD_IFS"
for item in "${items[@]}"; do
[[ -d $item ]] && item="$item/"
local filename=${item#$notes_dir/}
COMPREPLY+=("${filename%.md}")
done
}

_notes_complete_commands() {
local valid_commands="new find grep open"
COMPREPLY=($(compgen -W "${valid_commands}" -- "${1}"))
}

_notes()
{
local cur
readonly commands="new find grep open"

COMPREPLY=() # Array variable storing the possible completions.
cur=${COMP_WORDS[COMP_CWORD]}
Expand All @@ -35,7 +42,7 @@ _notes()
esac
else
compopt +o nospace
COMPREPLY=($(compgen -W "${commands}" -- "${cur}"))
_notes_complete_commands "$cur"
fi
return 0
}
Expand Down
46 changes: 46 additions & 0 deletions test/test-bash-completion.bats
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!./libs/bats/bin/bats

load 'libs/bats-support/load'
load 'libs/bats-assert/load'
load 'helpers'

setup() {
setupNotesEnv
source notes.bash_completion
COMP_WORDS=()
}

teardown() {
teardownNotesEnv
}

@test "Should list all commands" {
touch $NOTES_DIRECTORY/note1.md
_notes_complete_commands ""
assert_equal "${COMPREPLY[0]}" 'new'
assert_equal "${COMPREPLY[1]}" 'find'
assert_equal "${COMPREPLY[2]}" 'grep'
assert_equal "${COMPREPLY[3]}" 'open'
}

@test "Should show matching note when found" {
touch $NOTES_DIRECTORY/note1.md
_notes_complete_notes "no"
assert_equal "${COMPREPLY[@]}" "note1"
}

@test "Should show multiple matching notes" {
touch $NOTES_DIRECTORY/note1.md
touch $NOTES_DIRECTORY/note2.md
_notes_complete_notes "no"
assert_equal "${COMPREPLY[0]}" 'note1'
assert_equal "${COMPREPLY[1]}" 'note2'
assert_equal 2 "${#COMPREPLY[@]}"
}

@test "Should show one completion for note with space" {
touch "$NOTES_DIRECTORY/my note.md"
_notes_complete_notes ""
assert_equal "${COMPREPLY[0]}" 'my note'
assert_equal 1 "${#COMPREPLY[@]}"
}

0 comments on commit 7b1fa74

Please sign in to comment.