shlib.sh: add explicit INT and TERM traps
[girocco.git] / shlib.sh
blobe8d2eb56ce0d94a3c94ab6c527d43535195d6c45
1 #!/bin/sh
3 # This is generic shell library for all the scripts used by Girocco;
4 # most importantly, it introduces all the $cfg_* shell variables.
6 # SHA-1 pattern
7 octet='[0-9a-f][0-9a-f]'
8 octet4="$octet$octet$octet$octet"
9 octet19="$octet4$octet4$octet4$octet4$octet$octet$octet"
10 octet20="$octet4$octet4$octet4$octet4$octet4"
12 get_girocco_config_var_list() {
13 # Export all the variables from Girocco::Config to suitable var= lines
14 # prefixing them with 'cfg_'. E.g. $cfg_admin is admin's mail address now
15 # and also setting a 'defined_cfg_' prefix to 1 if they are not undef.
16 __girocco_conf="$GIROCCO_CONF"
17 [ -n "$__girocco_conf" ] || __girocco_conf="Girocco::Config"
18 [ -z "$basedir" ] || __girocco_extrainc="-I$basedir"
19 perl -I@basedir@ $__girocco_extrainc -M$__girocco_conf -le \
20 'foreach (sort {uc($a) cmp uc($b)} keys %Girocco::Config::) {
21 my $val = ${$Girocco::Config::{$_}}; defined($val) or $val="";
22 $val =~ s/([\\"\$\`])/\\$1/gos;
23 $val =~ s/(?:\r\n|\r|\n)$//os;
24 print "cfg_$_=\"$val\"";
25 print "defined_cfg_$_=",
26 (defined(${$Girocco::Config::{$_}})?"1":"");
30 # If basedir has been replaced, and shlib_vars.sh exists, get the config
31 # definitions from it rather than running Perl.
32 if [ "@basedir@" = '@'basedir'@' ] || ! [ -r "@basedir@/shlib_vars.sh" ]; then
33 # Import all the variables from Girocco::Config to the local environment,
34 eval "$(get_girocco_config_var_list)"
35 else
36 # Import the variables from shlib_vars.sh which avoids needlessly
37 # running another copy of Perl
38 . "@basedir@/shlib_vars.sh"
41 # Make sure we have a reproducible environment by using a controlled HOME dir
42 XDG_CONFIG_HOME="$cfg_chroot/var/empty"
43 HOME="$cfg_chroot/etc/girocco"
44 GIT_CONFIG_NOSYSTEM=1
45 GIT_ATTR_NOSYSTEM=1
46 GIT_TERMINAL_PROMPT=0
47 GIT_ASKPASS="$cfg_basedir/bin/git-askpass-password"
48 export XDG_CONFIG_HOME
49 export HOME
50 export GIT_CONFIG_NOSYSTEM
51 export GIT_ATTR_NOSYSTEM
52 export GIT_TERMINAL_PROMPT
53 export GIT_ASKPASS
54 unset GIT_USER_AGENT
55 unset GIT_HTTP_USER_AGENT
56 if [ -n "$defined_cfg_git_client_ua" ]; then
57 GIT_USER_AGENT="$cfg_git_client_ua"
58 export GIT_USER_AGENT
59 GIT_HTTP_USER_AGENT="$cfg_git_client_ua"
60 export GIT_HTTP_USER_AGENT
63 # We cannot use a git() {} or nc_openbsd() {} function to redirect git
64 # and nc_openbsd to the desired executables because when using
65 # "ENV_VAR=xxx func" the various /bin/sh implementations behave in various
66 # different and unexpected ways:
67 # a) treat "ENV_VAR=xxx" like a separate, preceding "export ENV_VAR=xxx"
68 # b) treat "ENV_VAR=xxx" like a separate, prededing "ENV_VAR=xxx"
69 # c) treat "ENV_VAR=xxx" like a temporary setting only while running func
70 # None of these are good. We want a temporary "export ENV_VAR=xxx"
71 # setting only while running func which none of the /bin/sh's do.
73 # Instead we'd like to use an alias that provides the desired behavior without
74 # any of the bad (a), (b) or (c) effects.
76 # However, unfortunately, some of the crazy /bin/sh implementations do not
77 # recognize alias expansions when preceded by variable assignments!
79 # So we are left with git() {} and nc_openbsd() {} functions and in the
80 # case of git() {} we can compensate for (b) and (c) failing to export
81 # but not (a) and (b) persisting the values so the caller will simply
82 # have to beware and explicitly unset any variables that should not persist
83 # beyond the function call itself.
85 git() (
86 [ "${GIT_DIR+set}" = "set" ] && export GIT_DIR
87 [ "${GIT_SSL_NO_VERIFY+set}" = "set" ] && export GIT_SSL_NO_VERIFY
88 [ "${GIT_TRACE_PACKET+set}" = "set" ] && export GIT_TRACE_PACKET
89 [ "${GIT_USER_AGENT+set}" = "set" ] && export GIT_USER_AGENT
90 [ "${GIT_HTTP_USER_AGENT+set}" = "set" ] && export GIT_HTTP_USER_AGENT
91 exec "$cfg_git_bin" "$@"
94 nc_openbsd() { "$cfg_nc_openbsd_bin" "$@"; }
96 _addrlist() {
97 _list=
98 for _addr in "$@"; do
99 [ -z "$_list" ] || _list="$_list, "
100 _list="$_list$_addr"
101 done
102 echo "$_list"
105 _sendmail() {
106 _mailer="${cfg_sendmail_bin:-/usr/sbin/sendmail}"
107 if [ -n "$cfg_sender" ]; then
108 "$_mailer" -i -f "$cfg_sender" "$@"
109 else
110 "$_mailer" -i "$@"
114 mail() {
115 _subject=
116 if [ "$1" = "-s" ]; then
117 shift
118 _subject="$1"
119 shift
122 echo "From: \"$cfg_name\" ($cfg_title) <$cfg_admin>"
123 echo "To: $(_addrlist "$@")"
124 [ -z "$_subject" ] || echo "Subject: $_subject"
125 echo "MIME-Version: 1.0"
126 echo "Content-Type: text/plain; charset=utf-8"
127 echo "Content-Transfer-Encoding: 8bit"
128 echo "Auto-Submitted: auto-generated"
129 echo ""
131 } | _sendmail "$@"
134 # bang CMD... will execute the command with well-defined failure mode;
135 # set bang_action to string of the failed action ('clone', 'update', ...);
136 # pre-set bang_once=1 to make sure jobs banging on a repo repeatedly will
137 # not spam the owner; re-define the bang_trap() function to do custom
138 # cleanup before bailing out
139 bang() {
140 if [ -n "$show_progress" ]; then
141 exec 3>&1
142 errcode=
143 read -r errcode <<-EOT || :
145 exec 4>&3 3>&1 1>&4 4>&-
146 { "$@" 3>&- || echo $? >&3; } 2>&1 | tee -a "$bang_log"
149 exec 3>&-
150 if [ -z "$errcode" ]; then
151 # All right. Cool.
152 return;
154 else
155 if "$@" >>"$bang_log" 2>&1; then
156 # All right. Cool.
157 return;
158 else
159 errcode="$?"
162 if ! [ -e .banged ] || [ -e .bangagain ]; then
163 rm -f .bangagain
164 bangmailok=true
165 ! [ -f HEAD -a -f config -a -d objects ] ||
166 bangmailok="$(GIT_DIR=. git config --bool gitweb.statusupdates 2>/dev/null || echo true)"
167 bangaddrs=''
168 [ "$bangmailok" = "false" -o -z "$mail" ] || bangaddrs="$mail"
169 [ -z "$cfg_admincc" -o "$cfg_admincc" = "0" -o -z "$cfg_admin" ] ||
170 if [ -z "$bangaddrs" ]; then bangaddrs="$cfg_admin"; else bangaddrs="$bangaddrs,$cfg_admin"; fi
171 [ -z "$bangaddrs" ] ||
173 echo "$* failed with error code $errcode"
174 echo ""
175 [ ! -n "$bang_once" ] || echo "you will not receive any more notifications until recovery"
176 echo "this status message may be disabled on the project admin page"
177 echo ""
178 echo "Log follows:"
179 echo ""
180 cat "$bang_log"
181 } | mail -s "[$cfg_name] $proj $bang_action failed" "$bangaddrs"
183 touch .banged
184 cat "$bang_log" > .banglog
185 bang_trap
186 exit 1
189 # bang_eval CMD... will evaluate the command with well-defined failure mode;
190 # Identical to bang CMD... except the command is eval'd instead of executed.
191 bang_eval() {
192 bang eval "$*"
195 # Default bang settings:
196 bang_setup() {
197 bang_action="lame_programmer"
198 bang_once=
199 bang_trap() { :; }
200 bang_log="$(mktemp -t repomgr-XXXXXX)"
201 trap 'rm -f "$bang_log"' EXIT
202 trap 'exit 130' INT
203 trap 'exit 143' TERM
206 # Remove banged status
207 bang_reset() {
208 rm -f .banged .bangagain .banglog
211 # Check to see if banged status
212 is_banged() {
213 [ -e .banged ]
217 # Progress report - if show_progress is set, shows the given message.
218 progress() {
219 [ ! -n "$show_progress" ] || echo "$@"
223 # Project config accessors; must be run in project directory
224 config_get() {
225 git config "gitweb.$1"
228 config_set() {
229 git config "gitweb.$1" "$2" && chgrp repo config && chmod g+w config
232 config_set_raw() {
233 git config "$1" "$2" && chgrp repo config && chmod g+w config
236 config_get_date_seconds() {
237 _dt="$(config_get "$1" || :)"
238 [ -n "$_dt" ] || return 1
239 _ds="$(perl -I@basedir@ -MGirocco::Util -e "print parse_rfc2822_date('$_dt')")"
240 [ -n "$_ds" ] || return 1
241 echo "$_ds"
244 # Tool for checking whether given number of seconds has not passed yet
245 check_interval() {
246 os="$(config_get_date_seconds "$1")" || return 1
247 ns="$(date +%s)"
248 [ $ns -lt $(($os+$2)) ]
252 # List all Git repositories, with given prefix if specified, one-per-line
253 get_repo_list() {
254 if [ -n "$1" ]; then
255 cut -d : -f 1,3 "$cfg_chroot"/etc/group | grep "^$1"
256 else
257 cut -d : -f 1,3 "$cfg_chroot"/etc/group
258 fi | while IFS=: read name id; do
259 [ $id -lt 65536 ] || echo "$name"
260 done
263 # returns empty string for non-mirrors, otherwise one of:
264 # m => normal Git mirror
265 # s => mirror from svn source
266 # d => mirror from darcs source
267 # b => mirror from bzr source
268 # h => mirror from hg source
269 # the optional passed in git dir defaults to "."
270 # will fail if the directory does not have .nofetch and gitweb.baseurl
271 # comes back empty
272 get_mirror_type() {
273 _gitdir="${1:-.}"
274 # always return empty for non-mirrors
275 [ ! -e "$_gitdir/.nofetch" ] || return 0
276 _url="$(GIT_DIR="$_gitdir" config_get baseurl 2>/dev/null || :)"
277 _url="${_url##* }"
278 case "$_url" in
280 return 1
282 svn://* | svn+http://* | svn+https://*)
283 echo 's'
285 darcs://*)
286 echo 'd'
288 bzr://*)
289 echo 'b'
291 hg+http://* | hg+https://*)
292 echo 'h'
295 echo 'm'
297 esac
298 return 0
301 # returns true if the passed in git dir (defaults to ".") is a mirror using git fast-import
302 is_gfi_mirror() {
303 case "$(get_mirror_type "$1" 2>/dev/null || :)" in
304 d|b|h)
305 # darcs, bzr and hg mirrors use git fast-import
306 return 0
309 # Don't think git-svn currently uses git fast-import
310 # And Git mirrors certainly do not
311 return 1
313 esac
314 # assume it does not use git fast-import
315 return 1
318 # returns true if the passed in git dir (defaults to ".") is a mirror using git-svn
319 is_svn_mirror() {
320 [ "$(get_mirror_type "$1" 2>/dev/null || :)" = "s" ]
323 # A well-known UTF-8 locale is required for some of the fast-import providers
324 # in order to avoid mangling characters. Ideally we could use "POSIX.UTF-8"
325 # but that is not reliably UTF-8 but rather usually US-ASCII.
326 # We parse the output of `locale -a` and select a suitable UTF-8 locale.
327 # If we cannot find one in the `locale -a` output then we just use a well-known
328 # UTF-8 locale and hope for the best. We set LC_ALL to our choice and export
329 # it. We only set this temporarily when running the fast-import providers.
330 set_utf8_locale() {
331 _guess_locale="$(locale -a | grep -viE '^(posix|c)(\..*)?$' | \
332 grep -iE '\.utf-?8$' | sed -e 's/\.[Uu][Tt][Ff]-*8$//' | \
333 sed -e '/en_US/ s/^/0 /; /en_US/ !s/^/1 /' | LC_ALL=C sort | \
334 head -n 1 | cut -d ' ' -f 2)"
335 LC_ALL="${_guess_locale:-en_US}.UTF-8"
336 export LC_ALL
339 # hg-fast-export | git fast-import with error handling in current directory GIT_DIR
340 git_hg_fetch() (
341 set_utf8_locale
342 _python="${PYTHON:-python}"
343 _err1=
344 _err2=
345 exec 3>&1
346 { read -r _err1 || :; read -r _err2 || :; } <<-EOT
348 exec 4>&3 3>&1 1>&4 4>&-
350 _e1=0
351 [ -f hg2git-marks ] || touch hg2git-marks
352 _af="$(git config hg.authorsfile || :)"
353 _cmd='GIT_DIR="$(pwd)" "$_python" "$cfg_basedir/bin/hg-fast-export.py" \
354 --repo "$(pwd)/repo.hg" \
355 --marks "$(pwd)/hg2git-marks" \
356 --mapping "$(pwd)/hg2git-mapping" \
357 --heads "$(pwd)/hg2git-heads" \
358 --status "$(pwd)/hg2git-state" \
359 -U unknown --force --flatten --hg-hash'
360 [ -z "$_af" ] || _cmd="$_cmd"' --authors "$_af"'
361 eval "$_cmd" 3>&- || _e1=$?
362 echo $_e1 >&3
363 } | \
365 _e2=0
366 rm -f hg2git-marks.new
367 git fast-import \
368 --export-marks="$(pwd)/hg2git-marks.new" \
369 --export-pack-edges="$(pwd)/gfi-packs" \
370 --force 3>&- || _e2=$?
371 echo $_e2 >&3
375 exec 3>&-
376 [ "$_err1" = 0 -a "$_err2" = 0 ] || return 1
377 if [ -f hg2git-marks ]; then
378 rm -f hg2git-marks.old
379 mv hg2git-marks hg2git-marks.old
380 else
381 touch hg2git-marks.old
383 cat hg2git-marks.old hg2git-marks.new | \
384 LC_ALL=C sort -t : -k2,2n -u | \
385 sed -ne "/^:[1-9][0-9]* $octet20\$/p" > hg2git-marks
386 rm hg2git-marks.old hg2git-marks.new
387 rm -f hg2git-heads
388 git branch --no-color | \
389 while IFS= read -r _head; do
390 echo ":${_head#??} $(git rev-parse "refs/heads/${_head#??}")"
391 done > hg2git-heads