Saturday, August 14, 2010

Batch upload script for CouchDB (using curl and jsawk)

I looked all over for something small and simple like this, but couldn't find anything.

Dependencies:
spidermonkey (required by jsawk)
libmozjs2d (required by spidermonkey)
jsawk (for parsing CouchDB response)
curl

Ubuntu doesn't include spidermonkey in the repositories (it uses rhino instead) so you'll have to grab spidermonkey from the Debian.

Copy the below script (change http://localhost:5984/cm-dev/hrothgar to your server/db/document) and save yourself a lot of clicks in Futon.


Usage: upload.sh [path containing the files to upload]

hput () {
eval hash"$1"='$2'
}

hget () {
eval echo '${hash'"$1"'#hash}'
}
hput js javascript
hput html html
hput css css

directory=$@
if [ -z "$directory" ]
then
directory="."
fi

filetypes="$directory/*.css
$directory/*.html
$directory/*.js"

for file in $filetypes
do
filename=`basename "$file"`
ext=`hget ${filename##*.}`
rev=`curl -sX GET 'http://grendel.cloudant.com/cm-dev/hrothgar/' | jsawk 'return this._rev'`
echo File : $file
echo Current revision : $rev
echo Uploading document: $filename
echo "${ext}"
echo curl : curl -X PUT http://grendel.cloudant.com/cm-dev/hrothgar/$filename?rev=$rev --data-binary @$file -H 'Content-Type: text/'$ext

curl -X PUT http://grendel.cloudant.com/cm-dev/hrothgar/$filename?rev=$rev --data-binary @$file -H 'Content-Type: text/'$ext
echo --------------------------------------------
echo
done

Thanks to Micha for jsawk.

No comments: