Skip to content

Instantly share code, notes, and snippets.

@cipriantarta
Created April 11, 2022 12:38
Show Gist options
  • Save cipriantarta/379d462f4b8b9e1b0f740340c5234fde to your computer and use it in GitHub Desktop.
Save cipriantarta/379d462f4b8b9e1b0f740340c5234fde to your computer and use it in GitHub Desktop.
#!/usr/bin/env bash
silent=0
up=1
down=2
direction=
PATH="$HOME/.config/nvim"
gid='99ce623d080c4162a67d97f569bd7bd4'
if [ -z "$GH_TOKEN" ] ; then
echo "github token required, use export GH_TOKEN=abc123."
exit 1
fi
if ! command -V /usr/bin/curl &> /dev/null ; then
echo 'curl is required'
exit 1
fi
if ! command -V /usr/bin/jq &> /dev/null; then
echo 'jq required.'
exit 1
fi
while getopts 'udps' flag; do
case "$flag" in
u) [ -n "$direction" ] || direction=$up ;;
d) [ -n "$direction" ] || direction=$down ;;
p) path=$flag ;;
s) silent=1 ;;
esac
done
if [ -z "$direction" ] ; then
echo 'direction required'
exit 1
fi
sync_up() {
[[ $silent -eq 0 ]] && echo "syncing from ${PATH}"
files=$(
for f in $HOME/.config/nvim/*.lua $HOME/.config/nvim/lua/*.lua ; do
/usr/bin/jq -Rs '{fn: "'${f##*/}'", content: .}' $f;
done | \
# /usr/bin/jq -n 'reduce inputs as $d (.; . + [ { fn: $d.fn, content: $d.content } ])'
/usr/bin/jq -n 'reduce inputs as $d (.; . + { ($d.fn): {language: "Lua", content: $d.content} })'
)
body='{
"files": '"${files}"'
}'
res=$(/usr/bin/curl -s -X PATCH \
-H "Accept: application/vnd.github.v3+json" \
https://${GH_TOKEN}@api.github.com/gists/${gid} \
-d "$body")
}
sync_down() {
[[ $silent -eq 0 ]] && echo "syncing into ${PATH}"
data=$(/usr/bin/curl -s \
-H "Accept: application/vnd.github.v3+json" \
https://api.github.com/gists/99ce623d080c4162a67d97f569bd7bd4)
{ readarray -t -d '' arr && wait "$!"; } < <(
set -o pipefail
echo $data | /usr/bin/jq -r '.files | map([(.filename),(.content)]) | .[] | (., "\u0000")'
)
[[ ! -d "$PATH/lua" ]] && /usr/bin/mkdir -p "$PATH/lua"
for f in "${arr[@]}"
do
fn=$(echo $f | /usr/bin/jq -r '.[0]')
if [[ "$fn" == "" ]] ; then
continue
fi
if [[ "$fn" == "init.lua" ]] ; then
echo $f | /usr/bin/jq -r '.[0]' > "$PATH/$fn"
else
echo $f | /usr/bin/jq -r '.[1]' > "$PATH/lua/$fn"
fi
done
}
[[ $silent -eq 0 ]] && echo 'neovim sync started...'
if [[ $direction -eq $up ]] ; then
sync_up
else
sync_down
fi
[[ $silent -eq 0 ]] && echo 'done.'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment