add a new gateway script: git-commit
[racktables] / gateways / git-commit
CommitLineData
033c2594
DO
1#!/bin/sh
2
3# This file is a part of RackTables, a datacenter and server room management
4# framework. See accompanying file "COPYING" for the full copyright and
5# licensing information.
6
7# This script implements a simple (one file at a time) one-way feed into a git
8# repository. To make a commit it takes the following PHP code:
9#
10# $params = array
11# (
12# 'racktables_pseudo_user',
13# '/path/to/repository',
14# 'path/to/file/within/the/repository',
15# 'commit message text',
16# );
17# $rc = callScript ('git-commit', $params, $file_contents, $stdout, $stderr);
18#
19# The meaning of $stdout and $stderr is the same as in queryTerminal().
20# The specified repository must exist and the specified pseudo-user must be
21# able to write to the repository and run "git pull", "git commit" and "git push"
22# without any user interaction (i.e. the git remote must be on a local
23# filesystem or be configured to use SSH keys).
24
25[ $# -eq 4 ] || {
26 echo "Usage: $0 <pseudo-user> <repo dir> <path to file> <commit message>" >&2
27 exit 1
28}
29
30SUDOUSER=$1
31REPODIR="$2"
32FILEPATH="$3"
33COMMITMSG="$4"
34
35[ `whoami` = "$SUDOUSER" ] || {
36 sudo --non-interactive --set-home --user=$SUDOUSER -- "$0" "$@"
37 exit $?
38}
39
40cd "$REPODIR"
41git pull --quiet || {
42 echo "Failed to run 'git pull' (rc=$?)" >&2
43 exit 2
44}
45
46# New file contents is on stdin.
47cat > "$FILEPATH" || {
48 echo "Failed to write new file contents, trying to roll back." >&2
49 git checkout --quiet -- "$FILEPATH" || {
50 echo "Failed to run 'git checkout' after a write error." >&2
51 exit 4
52 }
53 exit 3
54}
55
56git diff --quiet -- "$FILEPATH" || {
57 git add -- "$FILEPATH"
58 printf "update %s\n\n%s\n" "$FILEPATH" "$COMMITMSG" | git commit --quiet --file=- -- "$FILEPATH"
59 git push --quiet || {
60 echo "Failed to run 'git push' (rc=$?)" >&2
61 exit 5
62 }
63}
64
65exit 0