gc.sh: add another pack temp file pattern and optimize find
[girocco.git] / shlib.sh
blobe0fe1bad6ada26c2f237a9072e266264525765ce
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 patterns
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"
11 nullsha="0000000000000000000000000000000000000000"
12 # tab
13 tab="$(printf '\t')"
15 # set a sane umask that never excludes any user or group permissions
16 umask $(printf '0%03o' $(( $(umask) & ~0770 )) )
18 vcmp() {
19 # Compare $1 to $2 each of which must match \d+(\.\d+)*
20 # An empty string ('') for $1 or $2 is treated like 0
21 # Outputs:
22 # -1 if $1 < $2
23 # 0 if $1 = $2
24 # 1 if $1 > $2
25 # Note that `vcmp 1.8 1.8.0.0.0.0` correctly outputs 0.
26 while
27 _a="${1%%.*}"
28 _b="${2%%.*}"
29 [ -n "$_a" -o -n "$_b" ]
31 if [ "${_a:-0}" -lt "${_b:-0}" ]; then
32 echo -1
33 return
34 elif [ "${_a:-0}" -gt "${_b:-0}" ]; then
35 echo 1
36 return
38 _a2="${1#$_a}"
39 _b2="${2#$_b}"
40 set -- "${_a2#.}" "${_b2#.}"
41 done
42 echo 0
45 get_girocco_config_pm_var_list() {
46 # Export all the variables from Girocco::Config to suitable var= lines
47 # prefixing them with 'cfg_'. E.g. $cfg_admin is admin's mail address now
48 # and also setting a 'defined_cfg_' prefix to 1 if they are not undef.
49 __girocco_conf="$GIROCCO_CONF"
50 [ -n "$__girocco_conf" ] || __girocco_conf="Girocco::Config"
51 [ -z "$basedir" ] || __girocco_extrainc="-I$basedir"
52 perl -I@basedir@ $__girocco_extrainc -M$__girocco_conf -le \
53 'foreach (sort {uc($a) cmp uc($b)} keys %Girocco::Config::) {
54 my $val = ${$Girocco::Config::{$_}}; defined($val) or $val="";
55 $val =~ s/([\\"\$\`])/\\$1/gos;
56 $val =~ s/(?:\r\n|\r|\n)$//os;
57 print "cfg_$_=\"$val\"";
58 print "defined_cfg_$_=",
59 (defined(${$Girocco::Config::{$_}})?"1":"");
63 get_girocco_config_var_list() (
64 # Same as get_girocco_config_pm_var_list except that
65 # the following variables (all starting with var_) are added:
66 # var_group cfg_owning_group if defined otherwise `id -gn`
67 # var_git_ver The version number part from `git version`
68 # var_git_exec_path The result of $cfg_git_bin --exec-dir
69 # var_perl_bin Full path to the perl interpreter to use
70 # var_have_git_172 Set to 1 if git version >= 1.7.2 otherwise ''
71 # var_have_git_173 Set to 1 if git version >= 1.7.3 otherwise ''
72 # var_window_memory Value to use for repack --window-memory=
73 # var_big_file_threshold Value to use for core.bigFileThreshold
74 # var_log_window_size Value to use for git-svn --log-window-size=
75 # var_utf8_locale Value to use for a UTF-8 locale if available
76 # var_xargs_r A "-r" if xargs needs it to behave correctly
77 # var_du_exclude Option to exclude PATTERN from du if available
78 # var_du_follow Option to follow command line sym links if available
79 _cfg_vars="$(get_girocco_config_pm_var_list)"
80 eval "$_cfg_vars"
81 printf '%s\n' "$_cfg_vars"
82 printf 'var_group=%s\n' "${cfg_owning_group:-$(id -gn)}"
83 _gver="$("$cfg_git_bin" version 2>/dev/null | \
84 sed -ne 's/^[^0-9]*\([0-9][0-9]*\(\.[0-9][0-9]*\)*\).*$/\1/p')"
85 printf 'var_git_ver=%s\n' "$_gver"
86 printf 'var_git_exec_path="%s"\n' "$("$cfg_git_bin" --exec-path 2>/dev/null)"
87 printf 'var_perl_bin="%s"\n' "${cfg_perl_bin:-$(unset -f perl; command -v perl)}"
88 printf 'var_have_git_172=%s\n' "$([ $(vcmp "$_gver" 1.7.2) -ge 0 ] && echo 1)"
89 printf 'var_have_git_173=%s\n' "$([ $(vcmp "$_gver" 1.7.3) -ge 0 ] && echo 1)"
90 __girocco_conf="$GIROCCO_CONF"
91 [ -n "$__girocco_conf" ] || __girocco_conf="Girocco::Config"
92 [ -z "$basedir" ] || __girocco_extrainc="-I$basedir"
93 printf "var_window_memory=%s\n" \
94 "$(perl -I@basedir@ $__girocco_extrainc -M$__girocco_conf \
95 -MGirocco::Util -e 'print calc_windowmemory')"
96 printf "var_big_file_threshold=%s\n" \
97 "$(perl -I@basedir@ $__girocco_extrainc -M$__girocco_conf \
98 -MGirocco::Util -e 'print calc_bigfilethreshold')"
99 printf 'var_log_window_size=%s\n' "${cfg_svn_log_window_size:-250}"
100 # We parse the output of `locale -a` and select a suitable UTF-8 locale.
101 _guess_locale="$(locale -a | grep -viE '^(posix|c)(\..*)?$' | \
102 grep -iE '\.utf-?8$' | sed -e 's/\.[Uu][Tt][Ff]-*8$//' | \
103 sed -e '/en_US/ s/^/0 /; /en_US/ !s/^/1 /' | LC_ALL=C sort | \
104 head -n 1 | cut -d ' ' -f 2)"
105 [ -z "$_guess_locale" ] || printf 'var_utf8_locale=%s.UTF-8\n' "$_guess_locale"
106 # On some broken platforms running xargs without -r and empty input runs the command
107 printf 'var_xargs_r=%s\n' "$(: | command xargs echo -r)"
108 # The disk usage report produces better numbers if du has an exclude option
109 _x0="$(basename "$0")"
110 _x0="${_x0%?}?*"
111 for _duopt in --exclude -I; do
112 if _test="$(du $_duopt 's?lib.s*' $_duopt "$_x0" "$0" 2>/dev/null)" && [ -z "$_test" ]; then
113 printf 'var_du_exclude=%s\n' "$_duopt"
114 break
116 done
117 if _test="$(du -H "$0" 2>/dev/null)" && [ -n "$_test" ]; then
118 printf 'var_du_follow=%s\n' "-H"
119 break
123 # If basedir has been replaced, and shlib_vars.sh exists, get the config
124 # definitions from it rather than running Perl.
125 if [ "@basedir@" = '@'basedir'@' ] || ! [ -r "@basedir@/shlib_vars.sh" ]; then
126 # Import all the variables from Girocco::Config to the local environment,
127 eval "$(get_girocco_config_var_list)"
128 else
129 # Import the variables from shlib_vars.sh which avoids needlessly
130 # running another copy of Perl
131 . "@basedir@/shlib_vars.sh"
134 # git_add_config "some.var=value"
135 # every ' in value must be replaced with the 4-character sequence '\'' before
136 # calling this function or Git will barf. Will not be effective unless running
137 # Git version 1.7.3 or later.
138 git_add_config() {
139 GIT_CONFIG_PARAMETERS="${GIT_CONFIG_PARAMETERS:+$GIT_CONFIG_PARAMETERS }'$1'"
140 export GIT_CONFIG_PARAMETERS
143 # Make sure we have a reproducible environment by using a controlled HOME dir
144 XDG_CONFIG_HOME="$cfg_chroot/var/empty"
145 HOME="$cfg_chroot/etc/girocco"
146 GIT_CONFIG_NOSYSTEM=1
147 GIT_ATTR_NOSYSTEM=1
148 GIT_NO_REPLACE_OBJECTS=1
149 GIT_TERMINAL_PROMPT=0
150 GIT_ASKPASS="$cfg_basedir/bin/git-askpass-password"
151 export XDG_CONFIG_HOME
152 export HOME
153 export GIT_CONFIG_NOSYSTEM
154 export GIT_ATTR_NOSYSTEM
155 export GIT_NO_REPLACE_OBJECTS
156 export GIT_TERMINAL_PROMPT
157 export GIT_ASKPASS
158 unset GIT_USER_AGENT
159 unset GIT_HTTP_USER_AGENT
160 if [ -n "$defined_cfg_git_client_ua" ]; then
161 GIT_USER_AGENT="$cfg_git_client_ua"
162 export GIT_USER_AGENT
163 GIT_HTTP_USER_AGENT="$cfg_git_client_ua"
164 export GIT_HTTP_USER_AGENT
166 unset GIT_CONFIG_PARAMETERS
167 [ -z "$var_big_file_threshold" ] ||
168 git_add_config "core.bigFileThreshold=$var_big_file_threshold"
170 # We cannot use a git() {} or nc_openbsd() {} function to redirect git
171 # and nc_openbsd to the desired executables because when using
172 # "ENV_VAR=xxx func" the various /bin/sh implementations behave in various
173 # different and unexpected ways:
174 # a) treat "ENV_VAR=xxx" like a separate, preceding "export ENV_VAR=xxx"
175 # b) treat "ENV_VAR=xxx" like a separate, prededing "ENV_VAR=xxx"
176 # c) treat "ENV_VAR=xxx" like a temporary setting only while running func
177 # None of these are good. We want a temporary "export ENV_VAR=xxx"
178 # setting only while running func which none of the /bin/sh's do.
180 # Instead we'd like to use an alias that provides the desired behavior without
181 # any of the bad (a), (b) or (c) effects.
183 # However, unfortunately, some of the crazy /bin/sh implementations do not
184 # recognize alias expansions when preceded by variable assignments!
186 # So we are left with git() {} and nc_openbsd() {} functions and in the
187 # case of git() {} we can compensate for (b) and (c) failing to export
188 # but not (a) and (b) persisting the values so the caller will simply
189 # have to beware and explicitly unset any variables that should not persist
190 # beyond the function call itself.
192 git() (
193 [ "${GIT_DIR+set}" = "set" ] && export GIT_DIR
194 [ "${GIT_SSL_NO_VERIFY+set}" = "set" ] && export GIT_SSL_NO_VERIFY
195 [ "${GIT_TRACE_PACKET+set}" = "set" ] && export GIT_TRACE_PACKET
196 [ "${GIT_USER_AGENT+set}" = "set" ] && export GIT_USER_AGENT
197 [ "${GIT_HTTP_USER_AGENT+set}" = "set" ] && export GIT_HTTP_USER_AGENT
198 exec "$cfg_git_bin" "$@"
201 # see comments for git() -- callers must explicitly export all variables
202 # intended for the perl interpreter before using this function
203 perl() { command "${var_perl_bin:-perl}" "$@"; }
205 nc_openbsd() { "$cfg_nc_openbsd_bin" "$@"; }
207 list_packs() { command "$cfg_basedir/bin/list_packs" "$@"; }
209 # Some platforms' broken xargs runs the command always at least once even if
210 # there's no input unless given a special option. Automatically supply the
211 # option on those platforms by providing an xargs function.
212 xargs() { command xargs $var_xargs_r "$@"; }
214 _addrlist() {
215 _list=
216 for _addr in "$@"; do
217 [ -z "$_list" ] || _list="$_list, "
218 _list="$_list$_addr"
219 done
220 echo "$_list"
223 _sendmail() {
224 _mailer="${cfg_sendmail_bin:-/usr/sbin/sendmail}"
225 if [ -n "$cfg_sender" ]; then
226 "$_mailer" -i -f "$cfg_sender" "$@"
227 else
228 "$_mailer" -i "$@"
232 mail() {
233 _subject=
234 if [ "$1" = "-s" ]; then
235 shift
236 _subject="$1"
237 shift
240 echo "From: \"$cfg_name\" ($cfg_title) <$cfg_admin>"
241 echo "To: $(_addrlist "$@")"
242 [ -z "$_subject" ] || echo "Subject: $_subject"
243 echo "MIME-Version: 1.0"
244 echo "Content-Type: text/plain; charset=utf-8"
245 echo "Content-Transfer-Encoding: 8bit"
246 echo "Auto-Submitted: auto-generated"
247 echo ""
249 } | _sendmail "$@"
252 # bang CMD... will execute the command with well-defined failure mode;
253 # set bang_action to string of the failed action ('clone', 'update', ...);
254 # pre-set bang_once=1 to make sure jobs banging on a repo repeatedly will
255 # not spam the owner; re-define the bang_trap() function to do custom
256 # cleanup before bailing out
257 bang() {
258 if [ -n "$show_progress" ]; then
259 exec 3>&1
260 errcode=
261 read -r errcode <<-EOT || :
263 exec 4>&3 3>&1 1>&4 4>&-
264 { "$@" 3>&- || echo $? >&3; } 2>&1 | tee -a "$bang_log"
267 exec 3>&-
268 if [ -z "$errcode" ]; then
269 # All right. Cool.
270 return;
272 else
273 if "$@" >>"$bang_log" 2>&1; then
274 # All right. Cool.
275 return;
276 else
277 errcode="$?"
280 if ! [ -e .banged ] || [ -e .bangagain ]; then
281 rm -f .bangagain
282 bangmailok=true
283 ! [ -f HEAD -a -f config -a -d objects ] ||
284 bangmailok="$(GIT_DIR=. git config --bool gitweb.statusupdates 2>/dev/null || echo true)"
285 bangaddrs=''
286 [ "$bangmailok" = "false" -o -z "$mail" ] || bangaddrs="$mail"
287 [ -z "$cfg_admincc" -o "$cfg_admincc" = "0" -o -z "$cfg_admin" ] ||
288 if [ -z "$bangaddrs" ]; then bangaddrs="$cfg_admin"; else bangaddrs="$bangaddrs,$cfg_admin"; fi
289 [ -z "$bangaddrs" ] ||
291 echo "$* failed with error code $errcode"
292 echo ""
293 [ ! -n "$bang_once" ] || echo "you will not receive any more notifications until recovery"
294 echo "this status message may be disabled on the project admin page"
295 echo ""
296 echo "Log follows:"
297 echo ""
298 cat "$bang_log"
299 } | mail -s "[$cfg_name] $proj $bang_action failed" "$bangaddrs"
301 touch .banged
302 cat "$bang_log" > .banglog
303 bang_trap
304 exit 1
307 # bang_eval CMD... will evaluate the command with well-defined failure mode;
308 # Identical to bang CMD... except the command is eval'd instead of executed.
309 bang_eval() {
310 bang eval "$*"
313 # Default bang settings:
314 bang_setup() {
315 bang_action="lame_programmer"
316 bang_once=
317 bang_trap() { :; }
318 bang_log="$(mktemp -t repomgr-XXXXXX)"
319 trap 'rm -f "$bang_log"' EXIT
320 trap 'exit 130' INT
321 trap 'exit 143' TERM
324 # Remove banged status
325 bang_reset() {
326 rm -f .banged .bangagain .banglog
329 # Check to see if banged status
330 is_banged() {
331 [ -e .banged ]
335 # Progress report - if show_progress is set, shows the given message.
336 progress() {
337 [ ! -n "$show_progress" ] || echo "$@"
341 # Project config accessors; must be run in project directory
342 config_get() {
343 git config "gitweb.$1"
346 config_set() {
347 git config "gitweb.$1" "$2" && chgrp $var_group config && chmod g+w config
350 config_set_raw() {
351 git config "$1" "$2" && chgrp $var_group config && chmod g+w config
354 config_get_date_seconds() {
355 _dt="$(config_get "$1" || :)"
356 [ -n "$_dt" ] || return 1
357 _ds="$(perl -I@basedir@ -MGirocco::Util -e "print parse_rfc2822_date('$_dt')")"
358 [ -n "$_ds" ] || return 1
359 echo "$_ds"
362 # Tool for checking whether given number of seconds has not passed yet
363 check_interval() {
364 os="$(config_get_date_seconds "$1")" || return 1
365 ns="$(date +%s)"
366 [ $ns -lt $(($os+$2)) ]
369 # Check if we are running with effective root permissions
370 is_root() {
371 [ "$(id -u 2>/dev/null)" = "0" ]
374 # Check to see if the single argument is a Git directory
375 is_git_dir() {
376 # Just like Git's test except we ignore GIT_OBJECT_DIRECTORY
377 # And we are slightly more picky (must be refs/.+ not refs/.*)
378 [ -d "$1/objects" -a -x "$1/objects" ] || return 1
379 [ -d "$1/refs" -a -x "$1/refs" ] || return 1
380 if [ -L "$1/HEAD" ]; then
381 _hr="$(readlink "$1/HEAD")"
382 case "$_hr" in "refs/"?*) :;; *) return 1;; esac
384 [ -f "$1/HEAD" -a -r "$1/HEAD" ] || return 1
385 read -r _hr <"$1/HEAD" || return 1
386 case "$_hr" in
387 $octet20)
388 return 0;;
389 ref:*)
390 _hr="${_hr##ref:*[ $tab]}"
391 case "$_hr" in "refs/"?*) return 0;; esac
392 esac
393 return 1
396 # List all Git repositories, with given prefix if specified, one-per-line
397 # All project names starting with _ are always excluded from the result
398 get_repo_list() {
399 if [ -n "$1" ]; then
400 cut -d : -f 1,3 "$cfg_chroot"/etc/group | grep "^$1"
401 else
402 cut -d : -f 1,3 "$cfg_chroot"/etc/group
403 fi | while IFS=: read name id; do
404 [ $id -lt 65536 ] || case "$name" in _*) :;; ?*) echo "$name"; esac
405 done
408 # returns empty string for non-mirrors, otherwise one of:
409 # m => normal Git mirror
410 # s => mirror from svn source
411 # d => mirror from darcs source
412 # b => mirror from bzr source
413 # h => mirror from hg source
414 # the optional passed in git dir defaults to "."
415 # will fail if the directory does not have .nofetch and gitweb.baseurl
416 # comes back empty
417 get_mirror_type() {
418 _gitdir="${1:-.}"
419 # always return empty for non-mirrors
420 [ ! -e "$_gitdir/.nofetch" ] || return 0
421 _url="$(GIT_DIR="$_gitdir" config_get baseurl 2>/dev/null || :)"
422 _url="${_url##* }"
423 case "$_url" in
425 return 1
427 svn://* | svn+http://* | svn+https://*)
428 echo 's'
430 darcs://*)
431 echo 'd'
433 bzr://*)
434 echo 'b'
436 hg+http://* | hg+https://*)
437 echo 'h'
440 echo 'm'
442 esac
443 return 0
446 # returns true if the passed in git dir (defaults to ".") is a mirror using git fast-import
447 is_gfi_mirror() {
448 case "$(get_mirror_type "$1" 2>/dev/null || :)" in
449 d|b|h)
450 # darcs, bzr and hg mirrors use git fast-import
451 return 0
454 # Don't think git-svn currently uses git fast-import
455 # And Git mirrors certainly do not
456 return 1
458 esac
459 # assume it does not use git fast-import
460 return 1
463 # returns true if the passed in git dir (defaults to ".") is a mirror using git-svn
464 is_svn_mirror() {
465 [ "$(get_mirror_type "$1" 2>/dev/null || :)" = "s" ]
468 # A well-known UTF-8 locale is required for some of the fast-import providers
469 # in order to avoid mangling characters. Ideally we could use "POSIX.UTF-8"
470 # but that is not reliably UTF-8 but rather usually US-ASCII.
471 # We parse the output of `locale -a` and select a suitable UTF-8 locale at
472 # install time and store that in $var_utf8_locale if one is found.
473 # If we cannot find one in the `locale -a` output then we just use a well-known
474 # UTF-8 locale and hope for the best. We set LC_ALL to our choice and export
475 # it. We only set this temporarily when running the fast-import providers.
476 set_utf8_locale() {
477 LC_ALL="${var_utf8_locale:-en_US.UTF-8}"
478 export LC_ALL
481 # hg-fast-export | git fast-import with error handling in current directory GIT_DIR
482 git_hg_fetch() (
483 set_utf8_locale
484 _python="${PYTHON:-python}"
485 _err1=
486 _err2=
487 exec 3>&1
488 { read -r _err1 || :; read -r _err2 || :; } <<-EOT
490 exec 4>&3 3>&1 1>&4 4>&-
492 _e1=0
493 [ -f hg2git-marks ] || touch hg2git-marks
494 _af="$(git config hg.authorsfile || :)"
495 _cmd='GIT_DIR="$(pwd)" "$_python" "$cfg_basedir/bin/hg-fast-export.py" \
496 --repo "$(pwd)/repo.hg" \
497 --marks "$(pwd)/hg2git-marks" \
498 --mapping "$(pwd)/hg2git-mapping" \
499 --heads "$(pwd)/hg2git-heads" \
500 --status "$(pwd)/hg2git-state" \
501 -U unknown --force --flatten --hg-hash'
502 [ -z "$_af" ] || _cmd="$_cmd"' --authors "$_af"'
503 eval "$_cmd" 3>&- || _e1=$?
504 echo $_e1 >&3
505 } | \
507 _e2=0
508 rm -f hg2git-marks.new
509 git fast-import \
510 --export-marks="$(pwd)/hg2git-marks.new" \
511 --export-pack-edges="$(pwd)/gfi-packs" \
512 --force 3>&- || _e2=$?
513 echo $_e2 >&3
517 exec 3>&-
518 [ "$_err1" = 0 -a "$_err2" = 0 ] || return 1
519 if [ -f hg2git-marks ]; then
520 rm -f hg2git-marks.old
521 mv hg2git-marks hg2git-marks.old
522 else
523 touch hg2git-marks.old
525 cat hg2git-marks.old hg2git-marks.new | \
526 LC_ALL=C sort -t : -k2,2n -u | \
527 sed -ne "/^:[1-9][0-9]* $octet20\$/p" > hg2git-marks
528 rm hg2git-marks.old hg2git-marks.new
529 rm -f hg2git-heads
530 git branch --no-color | \
531 while IFS= read -r _head; do
532 echo ":${_head#??} $(git rev-parse "refs/heads/${_head#??}")"
533 done > hg2git-heads