Skip to content

Instantly share code, notes, and snippets.

@grokdatum
Forked from scttnlsn/README.md
Created July 29, 2020 04:54
Show Gist options
  • Select an option

  • Save grokdatum/012e9dc123839b7d0da8148e131bdedd to your computer and use it in GitHub Desktop.

Select an option

Save grokdatum/012e9dc123839b7d0da8148e131bdedd to your computer and use it in GitHub Desktop.
Git as a key/value store

git-store

$ git init mystore
$ cd mystore

$ git store set foo "this is foo"
$ git store get foo
this is foo

$ echo "this is bar" | git store set bar
$ git store get bar
this is bar

$ git store keys
bar
foo

$ git store delete bar
$ git store keys
foo

$ git store clear
$ git store keys
#!/usr/bin/env bash
function _git_store_set() {
key=$1
shift
value=$@
if [ -z "$value" ]; then
value=$(cat)
fi
blob=$(echo "$value" | git hash-object -w --stdin)
git update-index --add --cacheinfo 100644 $blob $key
_git_store_save "set '$key'"
}
function _git_store_get() {
key=$1
value=$(git show master:$1 2> /dev/null)
if [ $? -eq 0 ]; then
echo "$value"
fi
}
function _git_store_delete() {
key=$1
git update-index --remove $key
_git_store_save "delete '$key'"
}
function _git_store_keys() {
git ls-tree --name-only master
}
function _git_store_clear() {
keys=$(_git_store_keys)
for key in $keys; do
git update-index --remove $key
done
_git_store_save "clear"
}
function _git_store_save() {
message=$1
tree=$(git write-tree)
master=$(git show-ref refs/heads/master | cut -d ' ' -f 1)
if [ -z $master ]; then
commit=$(echo $message | git commit-tree $tree)
else
commit=$(echo $message | git commit-tree $tree -p $master)
fi
git update-ref refs/heads/master $commit
}
eval "_git_store_$@"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment