7fd1738b0ff4e19e0b7aaf4c950df142644547ee
[racktables] / gateways / git-commit
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 # This script uses sudo to switch between the pseudo-users and requires an
26 # entry in sudoers along the following lines:
27 # httpduser ALL=(racktablesuser) NOPASSWD:/path/to/racktables/gateways/git-commit
28
29 [ $# -eq 4 ] || {
30 echo "Usage: $0 <pseudo-user> <repo dir> <path to file> <commit message>" >&2
31 exit 1
32 }
33
34 SUDOUSER=$1
35 REPODIR="$2"
36 FILEPATH="$3"
37 COMMITMSG="$4"
38
39 [ `whoami` = "$SUDOUSER" ] || {
40 sudo --non-interactive --set-home --user=$SUDOUSER -- "$0" "$@"
41 exit $?
42 }
43
44 cd "$REPODIR"
45 git pull --quiet || {
46 echo "Failed to run 'git pull' (rc=$?)" >&2
47 exit 2
48 }
49
50 # New file contents is on stdin.
51 cat > "$FILEPATH" || {
52 echo "Failed to write new file contents, trying to roll back." >&2
53 git checkout --quiet -- "$FILEPATH" || {
54 echo "Failed to run 'git checkout' after a write error." >&2
55 exit 4
56 }
57 exit 3
58 }
59
60 git diff --quiet -- "$FILEPATH" || {
61 git add -- "$FILEPATH"
62 printf "update %s\n\n%s\n" "$FILEPATH" "$COMMITMSG" | git commit --quiet --file=- -- "$FILEPATH"
63 git push --quiet || {
64 echo "Failed to run 'git push' (rc=$?)" >&2
65 exit 5
66 }
67 }
68
69 exit 0