Skip to content

Instantly share code, notes, and snippets.

@klattimer
Created May 17, 2020 20:52
Show Gist options
  • Save klattimer/9500893dc1fbf3877bf3d1efa7156c94 to your computer and use it in GitHub Desktop.
Save klattimer/9500893dc1fbf3877bf3d1efa7156c94 to your computer and use it in GitHub Desktop.
GIT to MQTT
#!/bin/bash
#
# GIT to MQTT Publishing hook
#
# This script provides a post-update hook solution which is intended to be self-contained and simply publish to
# a mosquitto server the current most recent commit ref for each branch.
#
# Once the branch is published clients subscribed to that specific topic will be informed of their necessity to
# update.
#
# Requirements
# - mosquitto clients 1.6.8+
# - avahi-clients
# - a mosquitto server which is advertised over avahi, and not password protected*
#
# /etc/avahi/services/mqtt.service
# <?xml version="1.0" standalone='no'?><!--*-nxml-*-->
# <!DOCTYPE service-group SYSTEM "avahi-service.dtd">
# <service-group>
# <name replace-wildcards="yes">Mosquitto Service on %h</name>
# <service>
# <type>_mqtt._tcp</type>
# <port>1883</port>
# </service>
# </service-group>
#
# * Authentication can be easily added, but this is generally intended simply as notification
# on local networks for deploying code to hardware.
T=`pwd`
echo "Post update in $T"
REPO_URL=`basename $T`
REPO_NAME=${REPO_URL%.git}
REPO_CHECKOUT="$REPO_NAME.git-temp"
# Discover our local mqtt server
echo "Searching for MQTT service"
MQTT_HOST=`avahi-browse -d local _mqtt._tcp --resolve -p -t | grep '^=' | cut -d ';' -f 8 | grep -v '::'`
MQTT_PORT=`avahi-browse -d local _mqtt._tcp --resolve -p -t | grep '^=' | cut -d ';' -f 9 | grep -v '::'`
if [ "$MQTT_HOST" == "" ]; then
echo "Fatal, cannot find advertised mosquitto service _mqtt._tcp"
exit 1
fi
if [ "$MQTT_PORT" == "" ]; then
$MQTT_PORT = "1883"
fi
echo "Found mosquitto server $MQTT_HOST:$MQTT_PORT"
unset GIT_DIR
if [ -d "$REPO_CHECKOUT" ]; then
echo "Updating repository"
cd $REPO_CHECKOUT
git pull
else
echo "Cloning repository"
git clone $T $REPO_CHECKOUT
cd $REPO_CHECKOUT
fi
# Publish the newest commit ref
BRANCHES=`git branch --list -a | grep remotes/origin | grep -v HEAD`
for BRANCH_FULL in $BRANCHES; do
BRANCH=${BRANCH_FULL#"remotes/origin/"}
COMMIT_REF=`git show origin/$BRANCH | head -n 1 | cut -d ' ' -f 2`
TOPIC="/Git/$REPO_NAME/branches/$BRANCH"
# Retrieve the current value for the topic
LAST_COMMIT_REF=`mosquitto_sub -h $MQTT_HOST -t $TOPIC -C 1 -W 1`
echo "$LAST_COMMIT_REF -> $COMMIT_REF"
if [ "$LAST_COMMIT_REF" != "$COMMIT_REF" ]; then
echo "Publishing $BRANCH:$COMMIT_REF to $TOPIC"
mosquitto_pub -r -h $MQTT_HOST -t $TOPIC -m $COMMIT_REF
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment