gc.sh: disable gc for in-progress clones
[girocco/readme.git] / jobd / gc.sh
blobdbe46665cf254092c2106f10583758296930fc68
1 #!/bin/sh
3 # NOTE: additional options can be passed to git repack by specifying
4 # them after the project name, for example:
5 # gc.sh my-project -f
7 . @basedir@/shlib.sh
9 set -e
11 if [ $# -lt 1 ]; then
12 echo "Usage: gc.sh projname [extra-repack-args]" >&2
13 exit 1
16 # Includes
17 _shlib_done=1
18 unset GIROCCO_SUPPRESS_AUTO_GC_UPDATE
19 . "$cfg_basedir/jobd/maintain-auto-gc-hack.sh"
20 . "$cfg_basedir/jobd/generate-auto-gc-update.sh"
21 GIROCCO_SUPPRESS_AUTO_GC_UPDATE=1 && export GIROCCO_SUPPRESS_AUTO_GC_UPDATE
23 # packing options
24 packopts="--depth=50 --window=50 --window-memory=${var_window_memory:-1g}"
25 quiet="-q"; [ "${show_progress:-0}" = "0" ] || quiet=
27 umask 002
28 [ "$cfg_permission_control" != "Hooks" ] || umask 000
29 clean_git_env
31 vcnt() {
32 eval "$1="'$(( $# - 1 ))'
35 pidactive() {
36 if _result="$(kill -0 "$1" 2>&1)"; then
37 # process exists and we have permission to signal it
38 return 0
40 case "$_result" in *"not permitted"*)
41 # we do not have permission to signal the process
42 return 0
43 esac
44 # process does not exist
45 return 1
48 createlock() {
49 # A .lock file should only exist for much less than a second.
50 # If we see a stale lock file (> 1h old), remove it and then,
51 # just in case, wait 30 seconds for any process whose .lock
52 # we might have just removed (it's racy) to finish doing what
53 # should take much less than a second to do.
54 _stalelock="$(find -L "$1.lock" -maxdepth 1 -mmin +60 -print 2>/dev/null)" || :
55 if [ -n "$_stalelock" ]; then
56 rm -f "$_stalelock"
57 sleep 30
59 for _try in p p n; do
60 if (set -C; >"$1.lock") 2>/dev/null; then
61 echo "$1.lock"
62 return 0
64 # delay and try again
65 [ "$_try" != "p" ] || sleep 1
66 done
67 # cannot create lock file
68 return 1
71 # The pre-receive script creates one ref log file per push but we want them to
72 # be coalesced into one ref log file per day. We are guaranteed that any files
73 # we find to coalesce are NOT currently being written to since they are always
74 # written first as temporary files and then moved into place. We attempt to
75 # transfer the most recent modification time to the coalesced log file which
76 # would step on its mod time if it were being written to directly, but if we
77 # find per-process ref log files then it must be a push project and the only
78 # thing that would write directly to the main per-day log file would be a
79 # mirror project so there's actually no conflict.
80 # Also, if the clock is wonky (or was futzed with) we may have both YYYYMMDD
81 # and YYYYMMDD.gz present in which case combine them into YYYYMMDD
82 coalesce_reflogs() {
83 [ -d reflogs ] || return 0
84 rm -f .gc_failed
85 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -print |
86 while read -r rname; do
87 if [ -e "$rname.gz" ]; then
88 if [ -s "$rname" ]; then
89 # Presumably the .gz file must have been created before the non-gz
90 # file since it had to be uncompressed at some point therefore
91 # we need to append the non-gz contents to it but keep the non-gz
92 # contents timestamp so we rename to YYYYMMDD_ which will sort first
93 # and be picked up in the next step if we are interrupted in the middle.
94 # If a YYYYMMDD_ file already exists we append to it and transfer the
95 # timestamp. Finally we transfer the YYYYMMDD_ timestamp to the result
96 # and remove the YYYYMMDD_ temporary file leaving the result uncompressed.
97 if [ -e "${rname}_" ]; then
98 cat "$rname" >>"${rname}_"
99 touch -r "$rname" "${rname}_"
100 rm -f "$rname"
101 ! [ -e "$rname" ]
102 else
103 mv "$rname" "${rname}_"
105 gzip -d "$rname.gz" </dev/null
106 [ -e "$rname" ] && ! [ -e "$rname.gz" ]
107 cat "${rname}_" >>"$rname"
108 touch -r "${rname}_" "$rname"
109 rm -f "${rname}_"
110 else
111 # Just remove the empty file to resolve the problem
112 rm -f "$rname"
115 done
116 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]_*" -print | LC_ALL=C sort |
117 while read -r rname; do
118 logname="${rname%%_*}"
119 # If someone's been futzing with the date, the file we want to
120 # append to could already have been compressed, so we just uncompress
121 # it here. The previous block guarantees we do not have both a compressed
122 # and uncompressed version present at the same time.
123 if [ -e "$logname.gz" ]; then
124 gzip -d "$logname.gz" </dev/null
125 [ -e "$logname" ] && ! [ -e "$logname.gz" ]
127 cat "$rname" >>"$logname"
128 touch -r "$rname" "$logname"
129 rm -f "$rname"
130 if [ -e "$rname" ]; then
131 >.gc_failed
132 echo "! [$proj] failed to remove $rname" >&2
133 exit 1 # will only exit subshell created by "|"
135 done
136 ! [ -e .gc_failed ]
139 # Remove any files in reflogs that are older than $cfg_reflogs_lifetime days
140 prune_reflogs() {
141 [ -d reflogs ] || return 0
142 exp="$(( ${cfg_reflogs_lifetime:-1} * 1440 ))"
143 [ $exp -gt 0 ] || exp=1440
144 [ $exp -le 43200 ] || exp=43200
145 find -L reflogs -maxdepth 1 -type f -mmin "+$exp" -exec rm -f '{}' + || :
148 # Compact any reflogs that are not today's UTC date unless a .gz version exists
149 compact_reflogs() {
150 [ -d reflogs ] || return 0
151 _td="reflogs/$(TZ=UTC date '+%Y%m%d')"
152 find -L reflogs -maxdepth 1 -type f -name "[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]" -print |
153 while read -r rname; do
154 [ "$rname" != "$_td" ] || continue
155 ! [ -e "$rname.gz" ] || continue
156 gzip -9 "$rname" </dev/null
157 done
160 # return true if there's more than one objects/pack-<sha>.pack file or
161 # ANY sha-1 files in objects or
162 # there's one pack and it's not a normal pack name or
163 # there's one pack but not any refs
164 is_dirty() {
165 _packs="$(find -L objects/pack -name "pre-auto-gc-[12].pack" -prune -o -name "*.pack" -type f -print 2>/dev/null | head -n 2)"
166 vcnt _packscnt $_packs
167 if [ $_packscnt -gt 1 ]; then
168 return 0
170 if [ $_packscnt -eq 1 ]; then
171 # the single pack name is in $_packs
172 _packs="${_packs%.pack}"
173 _packs="${_packs#objects/pack/}"
174 case "$_packs" in
175 pack-*)
176 _packs="${_packs#pack-}"
177 if [ "${#_packs}" -lt 40 ] || [ "${_packs#*[!0-9a-fA-F]}" != "$_packs" ]; then
178 # name not exclusively 40 or more hexadecimal digits makes it dirty
179 return 0
183 # abnormal name makes it dirty
184 return 0
186 esac
188 _objs=$(find -L objects/$octet -name "$octet19*" -type f -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
189 [ $_objs -eq 0 ] || return 0
190 [ $_packscnt -eq 1 ] || return 1
191 # we do this check last because it's potentially the most expensive;
192 # at this point we know we do not have any loose objects, but we do
193 # have one pack that's named "normally"; empty refs => dirty
194 is_empty_refs_dir
197 # make sure combine-packs uses the correct Git executable
198 run_combine_packs() {
199 PATH="$var_git_exec_path:$cfg_basedir/bin:$PATH" @basedir@/jobd/combine-packs.sh "$@"
202 # duplicate the first file to the name given by the second file making sure that
203 # the second file appears atomically all-at-once after the copy has been completed
204 # and does not appear at all if the copy fails (in which case this function fails)
205 # if the second file already exists this function fails with status 1
206 # if the file names are the same this function returns immediately with success
207 dupe_file() {
208 [ "$1" != "$2" ] || return 0
209 ! [ -e "$2" ] || return 1
210 case "$2" in
211 *?/?*) _tmpdir="${2%/*}";;
212 *) _tmpdir=".";;
213 esac
214 _tmpfile="$(mktemp "${_tmpdir:-.}/packtmp-XXXXXX")" || return 1
215 cp -fp "$1" "$_tmpfile" || return 1
216 mv -f "$_tmpfile" "$2"
219 # rename_pack oldnamepath newnamepath
220 # note that .keep and .bndl files are left untouched and not moved at all!
221 rename_pack() {
222 [ $# -eq 2 ] && [ "$1" != "$2" ] || {
223 echo >&2 "[$proj] incorrect use of rename_pack function"
224 exit 1
226 # Git assumes that if the destination of the rename already exists
227 # that it is, in fact, a copy of the same bytes so silently succeeds
228 # without doing anything. We duplicate that logic here.
229 # Git checks for the .idx file first before even trying to use a pack
230 # so it should be the last moved and the first removed.
231 for ext in pack bitmap idx; do
232 [ -f "$1.$ext" ] || continue
233 ln "$1.$ext" "$2.$ext" >/dev/null 2>&1 ||
234 dupe_file "$1.$ext" "$2.$ext" >/dev/null 2>&1 ||
235 [ -f "$2.$ext" ] || {
236 echo >&2 "[$proj] unable to move $1.$ext to $2.$ext"
237 exit 1
239 done
240 for ext in idx pack bitmap; do
241 rm -f "$1.$ext"
242 done
243 return 0
246 # combine the input pack(s) into a new pack (or possibly packs if packSizeLimit set)
247 # input pack names are read from standard input one per line delimited by the first
248 # ':', ' ' or '\n' character on the line (which allows gfi-packs to be read directly)
249 # all arguments, if any, are passed to pack-objects as additional options
250 # returns non-zero on failure AND creates .gc_failed in that case
251 combine_packs() {
252 rm -f .gc_failed
253 find -L objects/pack -maxdepth 1 -type f -name '*.zap*' -exec rm -f '{}' + || :
254 run_combine_packs --replace "$@" $packopts --all-progress-implied $quiet --non-empty || {
255 >.gc_failed
256 return 1
258 return 0
261 # if the current directory is_gfi_mirror then repack all packs listed in gfi-packs
262 repack_gfi_packs() {
263 [ -n "$gfi_mirror" ] || return 0
264 [ -d objects/pack ] || { rm -f gfi-packs; return 0; }
265 progress "~ [$proj] redeltifying poor quality git fast-import packs"
266 combine_packs --ignore-missing --no-reuse-delta <gfi-packs
267 rm -f gfi-packs
268 return 0
271 # see if there are "lotsa" loose objects
272 # "lotsa" is defined as the 17, 68, 71 and 86 object directories existing
273 # and there being at least 5 total objects between them which corresponds
274 # to an approximate average of 320 loose objects before this function starts
275 # returning true and triggering a "mini" gc to pack up loose objects
276 lotsa_loose_objects() {
277 [ -d objects/17 ] && [ -d objects/68 ] && [ -d objects/71 ] && [ -d objects/86 ] || return 1
278 _objs=$(( $(find -L objects/17 objects/68 objects/71 objects/86 -maxdepth 1 -name "$octet19*" -type f -print 2>/dev/null | LC_ALL=C wc -l) ))
279 [ ${_objs:-0} -ge 5 ]
282 # pack any existing loose objects into a new _l.pack file then run prune-packed
283 # note that prune-packed is NOT run beforehand -- the caller must do that if needed
284 # loose objects need not be part of complete commits/trees as --weak-naming is used
285 pack_loose_objects() {
286 _lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts)"
287 if [ -n "$_lpacks" ]; then
288 # We need to identify these packs later so we don't combine_packs them
289 for _objpack in $_lpacks; do
290 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
291 done
292 git prune-packed $quiet
296 # combine small packs into larger pack(s)
297 # we avoid any _[lo], keep, bndl or bitmap packs
298 # if the optional argument is non-empty even a single small pack will be redeltad
299 combine_small_packs() {
300 _didprogress=
301 _minsmallpacks=2
302 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
303 _minsmallpacks=1
305 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
306 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o --exclude-sfx _l"
307 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
308 while
309 _cnt="$(list_packs --count $_lpo)" || :
310 test "${_cnt:-0}" -ge $_minsmallpacks
312 [ -n "$_didprogress" ] || {
313 progress "~ [$proj] combining small packs into a single larger pack"
314 _didprogress=1
316 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
317 vcnt _newc $_newp
318 # be paranoid and exit the loop if we haven't reduced the number of packs
319 [ $_newc -lt $_cnt ] || break
320 _minsmallpacks=2
321 done
322 return 0
325 # combine small _l packs into larger pack(s) using --weak-naming
326 # we avoid any non _l, keep, bndl or bitmap packs
327 # if the optional 2nd argument is non-empty even a single small pack will be redeltad
328 combine_small_loose_packs() {
329 _didprogress=
330 _minsmallpacks=2
331 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
332 _minsmallpacks=1
334 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
335 _lpo="$_lpo --exclude-no-sfx _l"
336 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
337 while
338 _cnt="$(list_packs --count $_lpo)" || :
339 test "${_cnt:-0}" -ge $_minsmallpacks
341 [ -n "$_didprogress" ] || {
342 progress "~ [$proj] combining small loose packs into a single larger pack"
343 _didprogress=1
345 _newp="$(list_packs $_lpo | combine_packs --names --weak-naming $noreusedeltaopt)"
346 # We need to identify these packs later so we don't combine_packs them
347 for _objpack in $_newp; do
348 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
349 done
350 vcnt _newc $_newp
351 # be paranoid and exit the loop if we haven't reduced the number of packs
352 [ $_newc -lt $_cnt ] || break
353 _minsmallpacks=2
354 done
355 return 0
358 # Unfortunately, some fetch strategies (e.g. git-svn and non-smart HTTP) lack
359 # the ability to store newly fetched objects in a pack.
360 # However, the fetch code conveniently sets .needspack just before it fetches
361 # so that it's easy to find all the loose objects that have been fetched and
362 # combine them into a pack. The --no-reuse-delta option is meaningless here
363 # since everything to be packed is a loose object and therefore not a delta so
364 # deltification will always take place.
365 make_needs_pack() {
366 [ -f .needspack ] || return 0
367 rm -f .needspackgc
368 mv -f .needspack .needspackgc
369 progress "~ [$proj] combining fetched loose objects into a pack"
370 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .needspackgc -name "$octet19*" -print 2>/dev/null |
371 LC_ALL=C awk -F / '{print $2 $3}' |
372 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
373 # We used to fail gc here.
374 # Now, however, we just ignore the failure because we have
375 # another mechanism to handle loose objects and it's possible
376 # that the fetcher somehow brought in unconnected objects which
377 # would cause the above combine-packs to fail.
378 # By ignoring the failure and just removing the .needspack file
379 # the loose objects will be treated as "ordinary" loose objects
380 # and packed using the "--weak-naming" option which can handle
381 # broken connectivity.
382 # That's a better solution than just failing here or leaving
383 # .needspack behind to potentially continue to fail again and
384 # again.
385 _newp=
387 if [ -n "$_newp" ]; then
388 # remove the now-redundant loose objects -- this is always safe
389 # even during a concurrent push because a reprepare_packed_git
390 # will be triggered if an object that should be there is not
391 # found thereby finding it in the new pack instead
392 git prune-packed $quiet
394 rm -f .needspackgc
397 # HEADSHA="$(pack_is_complete /full/path/to/some.pack /full/path/to/packed-refs "$(cat HEAD)")"
398 pack_is_complete() {
399 # Must have a matching .idx file and a non-empty packed-refs file
400 [ -s "${1%.pack}.idx" ] || return 1
401 [ -s "$2" ] || return 1
402 _headsha=
403 case "$3" in
404 $octet20*)
405 _headsha="$3"
407 "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
408 _headmatch="${3#ref:}"
409 _headmatch="${_headmatch# }"
410 _headmatchpat="$(echo "$_headmatch" | LC_ALL=C sed -e 's/\([.$]\)/\\\1/g')"
411 _headsha="$(LC_ALL=C grep -e "^$octet20$hexdig* $_headmatchpat\$" <"$2" |
412 LC_ALL=C cut -d ' ' -f 1)"
413 case "$_headsha" in $octet20*) :;; *)
414 return 1
415 esac
418 # bad HEAD
419 return 1
420 esac
421 rm -rf pack_is_complete_test
422 mkdir pack_is_complete_test
423 mkdir pack_is_complete_test/refs
424 mkdir pack_is_complete_test/objects
425 mkdir pack_is_complete_test/objects/pack
426 echo "$_headsha" >pack_is_complete_test/HEAD
427 ln -s "$1" pack_is_complete_test/objects/pack/
428 ln -s "${1%.pack}.idx" pack_is_complete_test/objects/pack/
429 ln -s "$2" pack_is_complete_test/packed-refs
430 _count="$(git --git-dir=pack_is_complete_test rev-list --count --all 2>/dev/null)" || :
431 rm -rf pack_is_complete_test
432 [ -n "$_count" ] || return 1
433 [ "$_count" -gt 0 ] 2>/dev/null || return 1
434 echo "$_headsha"
437 # On return a "$lockf" will have been created that must be removed when gc is done
438 lock_gc() {
439 # be compatibile with gc.pid file from newer Git releases
440 lockf=gc.pid
441 hn="$(hostname)"
442 active=
443 if [ "$(createlock "$lockf")" ]; then
444 # If $lockf is:
445 # 1) less than 12 hours old
446 # 2) contains two fields (pid hostname) NO trailing NL
447 # 3) the hostname is different OR the pid is still alive
448 # then we exit as another active process is holding the lock
449 if [ "$(find -L "$lockf" -maxdepth 1 -mmin -720 -print 2>/dev/null)" ]; then
450 apid=
451 ahost=
452 read -r apid ahost ajunk <"$lockf" || :
453 if [ "$apid" ] && [ "$ahost" ]; then
454 if [ "$ahost" != "$hn" ] || pidactive "$apid"; then
455 active=1
459 else
460 echo >&2 "[$proj] unable to create gc.pid.lock file"
461 exit 1
463 if [ -n "$active" ]; then
464 rm -f "$lockf.lock"
465 echo >&2 "[$proj] gc already running on machine '$ahost' pid '$apid'"
466 exit 1
468 printf "%s %s" "$$" "$hn" >"$lockf.lock"
469 chmod 0664 "$lockf.lock"
470 mv -f "$lockf.lock" "$lockf"
473 # Create a repack subdirectory such that running repack in it will pack the
474 # same things that a pack in the normal directory would except that the pack
475 # is guaranteed to be generated in an optimized order by adding a suitable
476 # synthesized ref in the refs/tags namespace (yes, pack-objects.c really does
477 # behave differently depending on the contents of the refs/tags namespace).
478 # Before calling this, pack-refs --all MUST be performed or the wrong pack
479 # will end up being made.
481 # If a ref deletion is pushed after making the repack subdir but before the
482 # the actual repack, the discarded objects will be packed -- no big deal,
483 # they'll get discarded the next time gc runs.
485 # If a fast-forward ref update is pushed after making the repack subdir but
486 # before the actual repack, it will be picked up and the new objects packed
487 # (subject to the normal git repack race about picking such updates up).
489 # If a non-fast-forward ref update is pushed after making the repack subdir but
490 # before the actual repack, it will be picked up like a fast-forward update but
491 # the discarded objects will be included like a ref deletion (until the next
492 # scheduled gc takes place).
494 # We retain a copy of the original packed-refs file as repack/packed-refs.orig
495 # If ref deletions come in while we're repacking, the original packed-refs
496 # file will be modified, but we'll still pack the deleted ref(s).
497 # If the packed-refs.orig file is used to create the bundle header we avoid
498 # a situation where the bundle contains a ref state that never actually
499 # existed in reality (for example a new branch is pushed and then an old
500 # branch deleted afterwards -- the deletion would show up in the bundle
501 # because it will cause the original packed-refs file to be re-written, but
502 # the new branch creation will not unless we do another pack-refs which might
503 # lead to having in incomplete bundle). Therefore we want to keep a copy of
504 # the original packed-refs file around. We do the same thing for HEAD.
506 # It's possible that the "objects" subdirectory is a symbolic link.
507 # Git does support this. However, during the repacking process, new packs
508 # will be created in repack/alt/pack and then moved into objects/pack.
509 # In order for this to work seemlessly, they must both be on the same
510 # filesystem. But when objects (or even objects/pack) is a symbolic link they
511 # might not be. For this reason a "repack" subdirectory is created under
512 # objects/pack and the repack/alt/pack directory symbolicly linked to it.
514 # Git allows not just HEAD to be a symbolic-ref, but any ref anywhere in the
515 # refs namespace. We are concerned about ref name collisions and getting the
516 # right tag set to get an optimal pack. We can safely duplicate the ref space
517 # under refs/heads, refs/notes and refs/remotes without any risk of unwanted
518 # collisions and this will likely make over 99%+ of all symbolic refs found
519 # in the wild work properly. Girocco itself never creates any symbolic refs
520 # inside the refs namespace; this is a nod to simultaneously using a Girocco
521 # repository for other purposes.
522 make_repack_dir() {
523 ! [ -d repack ] || rm -rf repack
524 ! [ -d repack ] || { echo >&2 "[$proj] cannot remove repack subdirectory"; exit 1; }
525 [ -d objects/pack ] || mkdir -p objects/pack
526 ! [ -d objects/pack/repack ] || rm -rf objects/pack/repack
527 ! [ -d objects/pack/repack ] || { echo >&2 "[$proj] cannot remove objects/pack/repack subdirectory"; exit 1; }
528 mkdir repack repack/refs repack/alt objects/pack/repack
529 [ -d info ] || mkdir info
530 ln -s ../config repack/config
531 ln -s ../info repack/info
532 ln -s ../objects repack/objects
533 ln -s "$PWD/objects/pack/repack" repack/alt/pack
534 ln -s ../../refs repack/refs/refs
535 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
536 cat HEAD >repack/HEAD.orig
537 >repack/packed-refs.extra
538 _xtralines=0
539 cat packed-refs >repack/packed-refs.orig
540 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
541 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
542 exit 1
544 if [ "${cfg_fetch_stash_refs:-0}" = "0" ]; then
545 # migrate any refs/stash or refs/tgstash lines to repack/packed-refs.extra
546 <repack/packed-refs.orig awk -v xtra="repack/packed-refs.extra" '
547 BEGIN { peeling = 0 }
548 NR == 1 && /^#/ { print; next; }
549 peeling && /^\^/ { print >>xtra; next; }
550 /^[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]+ refs\/(stash|tgstash)(\/|$)/ {
551 peeling = 1
552 print >>xtra
553 next
555 { peeling = 0; print; }
556 ' >repack/packed-refs.new
557 _xtralines="$(( $(LC_ALL=C wc -l <repack/packed-refs.extra) + 0 ))"
558 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs.new) + 0 ))"
559 if [ "$(( $_newlines + $_xtralines ))" -ne "$_lines" ]; then
560 echo >&2 "[$proj] error: make_repack_dir failed packed-refs.extra line count sanity check"
561 exit 1
563 mv -f repack/packed-refs.new repack/packed-refs.orig
564 _lines="$_newlines"
566 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
567 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
568 nohead=
569 headref="$(git rev-parse --verify --quiet HEAD)" || :
570 if [ -n "$headref" ]; then
571 echo "$headref refs/!=/HEAD" >>repack/packed-refs
572 echo "$headref refs/heads/!" >>repack/packed-refs
573 nohead='\, refs/heads/!$,d; '
574 _lines=$(( $_lines + 2 ))
576 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
577 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
578 exit 1
580 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
581 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
582 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
583 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
584 exit 1
586 _lines="$_newlines"
587 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
588 if [ -n "$optref" ]; then
589 echo "$optref refs/tags/!" >>repack/packed-refs
590 _lines=$(( $_lines + 1 ))
591 echo "$optref" >repack/HEAD
592 else
593 cat HEAD >repack/HEAD
595 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
596 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
597 exit 1
601 # Remove any crud that's been left behind by interrupted operations
602 # that did not clean up after themselves
603 remove_crud() {
604 # Remove any existing FETCH_HEAD
605 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
606 # receiving pushes (those never create a FETCH_HEAD).
607 # And if we're fetching because we're a mirror, we know we're not fetching right
608 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
609 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
610 # there were a lot of refs.
611 rm -f FETCH_HEAD
613 # remove any existing pack_is_complete_test or repack subdirectories
614 # If either exists when this function is called it's crud
615 rm -rf pack_is_complete_test repack objects/pack/repack
617 # Remove any stale pack remnants that are more than an hour old.
618 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
619 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
620 # pack-<sha1>.idx files without their corresponding .pack files are worthless
621 # and just waste space. Normally there shouldn't be any remnants but actually
622 # this can happen when things are interrupted at just the wrong time.
623 # Note that the objects/pack directory is created by git init and should
624 # always exist.
625 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
626 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
627 while read packsha; do
628 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
629 rm -f "objects/pack/pack-$packsha".?*
630 done
632 # Remove any stale tmp reflogs files that are more than one hour old.
633 # Since they are created only while the pre-receive hook is running and
634 # all it does is process a bunch of refs passed to it on standard input
635 # it's inconceivable that it would ever take as much as an hour to run.
636 if [ -d reflogs ]; then
637 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
640 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
641 # Really these files should only exist very briefly so there shouldn't be any
642 # but things happen that can end up leaving them behind.
643 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
645 # Remove any stale pack .keep files that are more than 12 hours old.
646 # We don't do anything to create any permanent pack .keep files, so they must
647 # be remnants from some failed push or something. Removing the .keep will
648 # allow the pack to be properly repacked.
649 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
651 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
652 # that are more than 12 hours old.
653 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
654 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
655 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
656 \) -exec rm -f '{}' + || :
658 # Remove any stale incoming-* object quarantine directories that are
659 # more than 12 hours old. These are new with Git >= 2.11.0.
660 find -L objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
661 -exec rm -rf '{}' + || :
663 # Remove any stale shallow_* files that are more than 12 hours old.
664 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
665 # requests a shallow clone. Also discard stale .refs-temp* and
666 # .refs-new* files at the same time.
667 find -L . -maxdepth 1 -type f -mmin +720 \( \
668 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
669 \) -exec rm -f '{}' + || :
671 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
672 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
673 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
675 # Remove any stale *.lock files in the htmlcache area that might have been left
676 # behind after an abnormal exit during an attempt to update a cached file and
677 # are more than 1 hour old.
678 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
680 # Remove any stale git-svn temp files that are more than 12 hours old.
681 # The git-svn process creates temp files with random 10 character names
682 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
683 # prefix, so we just have to kill any files with a 10-character name. We
684 # do this only for git-svn mirrors. All characters are chosen from
685 # [A-Za-z0-9_] so we can at least check that and fortunately the only
686 # collision is 'FETCH_HEAD' but that shouldn't matter.
687 # There may also be temp files with a Git_ prefix as well.
688 if [ -n "$svn_mirror" ]; then
689 _randchar='[A-Za-z0-9_]'
690 _randchar2="$_randchar$_randchar"
691 _randchar4="$_randchar2$_randchar2"
692 _randchar10="$_randchar4$_randchar4$_randchar2"
693 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
694 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
697 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
698 if [ -n "$gfi_mirror" ]; then
699 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
702 # Remove any stale core or *.core or core.* files that are more than 3 days old.
703 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
704 -exec rm -f '{}' + || :
708 ## Garbage Collection Types
710 ## There are two kinds of possible garbage collection (gc) operations:
712 ## 1. A normal, full gc
713 ## 2. A "mini" gc
715 ## If the full garbage collection interval has expired (or gc has never been
716 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
717 ## take place if the file .needsgc exists.
719 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
720 ## doing anything unless the right conditions are present so it's not a burden
721 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
722 ## the next opportunity.
724 ## See the docs/technical/gc.txt and docs/technical/gc-mini.txt files for more
725 ## of the gory details of how garbage collection is performed.
727 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
730 proj="${1%.git}"
731 shift
732 cd "$cfg_reporoot/$proj.git"
733 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
734 mirror_url="$(get_mirror_url)" || :
735 svn_mirror=
736 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
737 gfi_mirror=
738 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
739 gfi_mirror=1
742 # If git config --bool --get girocco.redelta is explicitly false then automatic
743 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
744 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
745 # gc only, for the final repack, deltas will always be recomputed.
746 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
747 # Setting this will hurt efficiency of the affected repository.
748 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
749 noreusedeltaopt="--no-reuse-delta"
750 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
751 alwaysredelta=
752 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
754 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
755 # to be compatible with the old and new gc.sh versions and avoid ugly argument
756 # duplication in process lists at the same time
757 # Any options found will override the "girocco.redelta" setting
758 recompress=
759 idx=$#
760 while [ $idx -gt 0 ]; do
761 idx=$(( $idx - 1 ))
762 opt="$1"
763 shift
764 case "$opt" in
765 -f|--no-reuse-delta)
766 alwaysredelta=1
767 continue
769 -F|--no-reuse-object)
770 alwaysredelta=1
771 recompress=1
772 continue
774 -?*)
777 printf >&2 '%s\n' "bad non-option argument: $opt"
778 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
779 exit 1
780 esac
781 [ -z "$opt" ] || set -- "$@" "$opt"
782 done
783 if [ -n "$alwaysredelta" ]; then
784 noreusedeltaopt="--no-reuse-delta"
785 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
788 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
789 trap 'exit 130' INT
790 trap 'exit 143' TERM
792 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
793 datefmt='+%a, %d %b %Y %T %z'
795 isminigc=
796 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
797 if [ -e .needsgc ]; then
798 isminigc=1
799 else
800 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
801 exit 0
804 if [ -e .nogc ]; then
805 progress "x [$proj] garbage check disabled"
806 exit 0
808 if ! [ -e .nofetch ] && [ -e .clone_in_progress ] && ! [ -e .clone_failed ]; then
809 progress "x [$proj] garbage check disabled (clone in progress)"
810 exit 0
812 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
813 # Eligible for a full gc but .delaygc is set so it would be skipped
814 # However .needsgc is also set so transform it into a mini instead
815 isminigc=1
816 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
819 if [ -n "$isminigc" ]; then
820 # Perform a "mini" gc
821 # Note that .delaygc is ignored here as that's only intended for full gc
822 lock_gc
823 rm -f .allowgc .needsgc
824 rm -f objects/pack/pack-*_[rful].keep
825 remove_crud
826 coalesce_reflogs
827 prune_reflogs
828 compact_reflogs
829 maintain_auto_gc_hack
830 generate_auto_gc_update
831 miniactive=
832 if [ -f .needspack ]; then
833 miniactive=1
834 progress "+ [$proj] mini garbage check ($(date))"
835 make_needs_pack
837 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
838 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
839 if [ -z "$miniactive" ]; then
840 miniactive=1
841 progress "+ [$proj] mini garbage check ($(date))"
843 repack_gfi_packs
845 if lotsa_loose_objects; then
846 if [ -z "$miniactive" ]; then
847 miniactive=1
848 progress "+ [$proj] mini garbage check ($(date))"
850 pack_loose_objects
852 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
853 # don't actually process them yet
854 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
855 packcnt="$(list_packs --count $lpo objects/pack)" || :
856 if [ "${packcnt:-0}" -ge 10 ]; then
857 if [ -z "$miniactive" ]; then
858 miniactive=1
859 progress "+ [$proj] mini garbage check ($(date))"
861 if [ -n "$gfi_mirror" ]; then
862 repack_gfi_packs
863 packcnt="$(list_packs --count $lpo objects/pack)" || :
865 # if repack_gfi_packs dropped the pack count to < 10 don't combine
866 if [ "${packcnt:-0}" -ge 10 ]; then
867 combine_small_packs
868 combine_small_loose_packs
869 packcnt="$(list_packs --count $lpo objects/pack)" || :
871 # if we still have more than 10 packs trigger a full gc
872 if [ "${packcnt:-0}" -ge 10 ]; then
873 # We shouldn't be in a .delaygc state at this point, but if
874 # we are then nuke it because we really need a full gc now
875 rm -f .delaygc
876 git config --unset gitweb.lastgc
877 rm -f "$lockf"
878 git update-server-info # just in case
879 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
880 exit 0
883 rm -f "$lockf"
884 if [ -n "$miniactive" ]; then
885 git update-server-info
886 progress "- [$proj] mini garbage check ($(date))"
887 else
888 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
890 exit 0
893 # Avoid unnecessary garbage collections:
894 # 1. If lastreceive is set and is older than lastgc
895 # -AND-
896 # 2. We are not a fork (! -s alternates) -OR- lastparentgc is older than lastgc
898 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
899 # If we are a fork and lastparentgc is NOT set we MUST run gc
901 # If the repo is dirty after removing any crud we MUST run gc
903 gcstart="$(date "$datefmt")"
904 skipgc=
905 isfork=
906 ! [ -s objects/info/alternates ] || isfork=1
907 lastparentgcsecs=
908 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
909 lastreceivesecs=
910 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
911 [ "${force_gc:-0}" = "0" ] &&
912 lastgcsecs="$(config_get_date_seconds lastgc)" &&
913 [ $lastreceivesecs -lt $lastgcsecs ]; then
914 # We've run gc since we last received, so maybe we can skip,
915 # check if not fork or fork and lastparentgc < lastgc
916 if [ -n "$isfork" ]; then
917 if [ -n "$lastparentgcsecs" ] &&
918 [ $lastparentgcsecs -lt $lastgcsecs ]; then
919 # We've run gc since our parent ran gc so we can skip
920 skipgc=1
922 else
923 # We don't have any alternates (we're not a forK) so we can skip
924 skipgc=1
928 # Prevent any other simultaneous gc operations
929 lock_gc
931 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
932 rm -f .allowgc .gc_failed
934 # Ideally we would do this in post-receive, but that would mean duplicating the
935 # logic so it's available in the chroot jail and that's highly undesirable
936 # Instead, since the first gc will be triggered immediately following the first
937 # push, we do the check here as it's quick and harmless if HEAD is already valid
938 check_and_set_head || :
940 # Always get rid of crud
941 remove_crud
943 # Always perform reflogs maintenance
944 coalesce_reflogs
945 prune_reflogs
946 compact_reflogs
948 # Always maintain auto gc hack
949 maintain_auto_gc_hack
950 generate_auto_gc_update
952 # Run 'git svn gc' now for svn mirrors
953 if [ -n "$svn_mirror" ]; then
954 git svn gc || :
957 # Skip the actual gc if .delaygc is set
958 if [ -e .delaygc ]; then
959 progress "x [$proj] garbage check delayed (except for crud removal)"
960 rm -f "$lockf"
961 exit 0
964 # Do not skip gc if the repo is dirty
965 if [ -n "$skipgc" ] && ! is_dirty; then
966 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
967 config_set lastgc "$gcstart"
968 rm -f "$lockf"
969 exit 0
972 bumptime=
973 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
974 # set lastparentgc and then update gcstart to be at least 1 second later
975 config_set lastparentgc "$gcstart"
976 bumptime=1
978 if [ -z "$lastreceivesecs" ]; then
979 # set lastreceive and then update gcstart to be at least 1 second later
980 config_set lastreceive "$gcstart"
981 bumptime=1
983 if [ -n "$bumptime" ]; then
984 sleep 1
985 gcstart="$(date "$datefmt")"
988 progress "+ [$proj] garbage check ($(date))"
990 newdeltas=
991 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
992 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
993 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
994 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
995 # Don't bother with repack_gfi_packs since everything's being repacked
996 newdeltas="--no-reuse-delta"
999 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
1000 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
1001 # There aren't enough objects to worry about so just redelta to get the best pack
1002 newdeltas="--no-reuse-delta"
1004 if [ -z "$newdeltas" ]; then
1005 # Since we're not going to recompute deltas overall, we need to do the
1006 # "mini" maintenance so that we can get more optimal deltas
1007 [ -z "$noreusedeltaopt" ] || make_needs_pack
1008 repack_gfi_packs
1009 force_single_pack_redelta=
1010 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
1011 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
1012 [ -z "$noreusedeltaopt" ] || combine_small_loose_packs $force_single_pack_redelta
1016 ## Safe Pruning In Forks
1018 ## We are about to perform garbage collection. We do NOT use the "git gc" or
1019 ## the "git repack" commands directly as they do not provide enough control over
1020 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
1021 ## collection so that a simultaneous "git gc" by an administrator will be
1022 ## blocked (and similarly we refuse to start garbage collection if we cannot
1023 ## create the "gc.pid" file).
1025 ## When we say "gc" in the below description we are referring to our "gc.sh"
1026 ## script, NOT the "git gc" command.
1028 ## If the project we are running garbage collection (gc) on has any forks we
1029 ## must be careful not to remove any objects that while no longer referenced by
1030 ## this project (the parent) are still referenced by one or more forks (the
1031 ## children) otherwise the children will become corrupt and we can't abide
1032 ## corrupt children.
1034 ## One way to accomplish this is to simply hard-link all currently existing
1035 ## loose objects and packs in the parent into all the children that refer to the
1036 ## parent (via a line in their objects/info/alternates file) before beginning
1037 ## the gc operation and then relying on a subsequent gc in the child to clean up
1038 ## any excess objects/packs. We used to use this strategy but it's very
1039 ## inefficient because:
1041 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
1042 ## until all children (and their children, if any) run gc by which time
1043 ## it's quite possible the topmost parent will have run gc again and
1044 ## hard-linked yet another old pack down to its children (not to mention
1045 ## loose objects).
1047 ## 2. When using the "-A" option with "git repack", any new objects in the
1048 ## parent that are not referenced by children will continually get
1049 ## exploded out of the hard-linked pack in the children whenever the
1050 ## children run gc.
1052 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
1053 ## into child forks, we must run the "mini" gc maintenance before we
1054 ## perform the hard-linking into the children which provides yet another
1055 ## source of inefficiency.
1057 ## While we were still using the "-A" option to "git repack" (that was not
1058 ## always the case) to guarantee we can access old ref values for long enough
1059 ## to send out a meaningful mail.sh notification, another, more efficient,
1060 ## option became available to prevent corruption of child forks that continue
1061 ## to refer to objects that are no longer reachable from any ref in the parent.
1063 ## The only things that need be copied (or hard-linked) into the child fork(s)
1064 ## are those objects that have become unreachable from any ref in the parent.
1066 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
1067 ## technique, the only objects that could ever be removed were loose objects
1068 ## that "git prune" determined were expired. In that case, loose objects were
1069 ## all that need be hard-linked down to child forks in order to avoid
1070 ## corruption of any child fork(s).
1072 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
1073 ## objects to child forks technique remains fundamentally sound from the
1074 ## perspective of supporting simultaneous gc and push and keeping newly
1075 ## unreachable objects around long enough to be sure we can send out meaningful
1076 ## ref change notifications and never corrupting any child forks and never
1077 ## persisting the lifetime of large old packs containing mostly duplicate or
1078 ## unreachable objects as gc percolates through a project's entire fork tree.
1080 ## However, that technique suffers from one potential prodigious pitfall.
1082 ## Unreachable objects come flying out of their packs to splatter all over the
1083 ## objects subdirectories possibly creating a huge, inefficient mess.
1085 ## Often this is not an issue. Even with a lot of rebasing going on, usually
1086 ## the only objects that will splatter are some commits, trees and the odd blob
1087 ## here and there. Not enough to be overly concerned about.
1089 ## However, for the reppository that frequently experiences a lot of non-fast-
1090 ## forward updates and/or outright ref deletion, the number of objects suddenly
1091 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
1093 ## To avoid this issue we now use a four phase pack creation strategy.
1094 ## This will result in creation of up to four packs (instead of at most one).
1096 ## I. A complete pack (with bitmaps if appropriate) gets created including
1097 ## only "reachable" objects from all refs/... refs plus HEAD. This will
1098 ## also serve as the virtual bundle for the repository.
1100 ## II. A pack of recently-became-unreachable objects and friends is created.
1101 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
1102 ## Because both the pre-receive and update.sh script record all ref
1103 ## changes we can easily choose the cut off point for "recently".
1104 ## It is only the fact we maintain those logs in the reflogs subdirectory
1105 ## that allows this step to be possible.
1107 ## III. If the repository has any forks with a non-zero length alternates file,
1108 ## yet another pack of "--keep-unreachable" objects is generated that will
1109 ## not actually be kept in the parent, but hard-linked into all the forks.
1111 ## IV. Finally, after running "git prune-packed", any remaining loose objects
1112 ## are migrated into a pack of their own.
1114 ## We then remove any non-.keep packs that existed before we started the
1115 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
1116 ## race condition (see docs/technical/gc.txt).
1118 ## By using "git pack-objects" directly we are able to accomplish this with
1119 ## very little additional effort.
1121 ## The packs produced by (III) are treated almost like ".keep" packs by child
1122 ## forks in that the objects in them are never repacked into any other
1123 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
1124 ## and those phase III packs are then hard-linked into any grandchild forks.
1126 ## This avoids the space explosion that could occur if each fork level ended
1127 ## up duplicating the "--keep-unreachable" pack space by repacking those
1128 ## objects (essentially breaking the hard-link to the single copy of those
1129 ## objects).
1131 ## While it is true that each level of forks could potentially add yet another
1132 ## phase III pack to be hard-linked down to its children, such packs will only
1133 ## include unreachable objects not already in any phase III packs that were
1134 ## received from the parent.
1136 ## The space for the phase III packs will not be reclaimed until the gc
1137 ## finishes percolating through the entire "fork tree" of a project.
1139 ## This is not much different than the "git repack -A -d" situation where
1140 ## all the loose objects are hard-linked down into child forks. In that
1141 ## case forks that actually need any of those objects could gradually reduce
1142 ## the number of objects hard-linked into deeper fork levels.
1144 ## The difference with a phase III "--keep-unreachable" pack is that there
1145 ## cannot be any gradual reduction like that since it would require repacking
1146 ## the pack and breaking the hard-link thereby increasing storage space. The
1147 ## storage will instead always be reclaimed all at once when all of the
1148 ## projects in the "fork tree" complete their gc.
1150 ## However, the belief is that the huge space win by having all the
1151 ## unreachable objects packed up together far eclipses (when many objects are
1152 ## involved, the single-pack version can end up using 1/20th or less of the
1153 ## disk space compared to having them all as loose objects) any brief minor
1154 ## space savings that might occur under the "git repack -A -d" loose object
1155 ## system prior to the gc collection completing for all the projects in the
1156 ## "fork tree".
1160 ## utility functions
1163 make_packs_ugw() {
1164 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1165 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1166 } 2>/dev/null
1168 get_index_tree() {
1169 if [ -s "$1" ]; then
1170 GIT_INDEX_FILE="$1"
1171 export GIT_INDEX_FILE
1172 git write-tree 2>/dev/null || :
1173 unset GIT_INDEX_FILE
1177 get_detached_head() {
1178 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1179 case "$_head" in $octet20*)
1180 echo "$_head"
1181 esac
1185 # compute_extra_reachables
1186 # create lines suitable for a packed-refs file mentioning all the
1187 # other refs we might like to keep.
1188 # the current directory MUST be set to the repository's --git-dir
1189 # the following are included:
1190 # * refs mentioned in repack/packed-refs.extra (if it exists)
1191 # * refs mentioned in reflogs/... files
1192 # * tree(s) created from index file(s)
1193 # * detached linked working tree heads
1194 # Resulting objects are tested for existence and uniqified then output
1195 # one per line under a refs/z* namespace
1196 compute_extra_reachables() {
1198 if [ -s repack/packed-refs.extra ]; then
1199 LC_ALL=C sed <repack/packed-refs.extra -n \
1200 -e 's/^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p' \
1201 -e 's/^\^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p'
1203 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1204 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1205 awk '{print $2; print $3}'
1206 ! [ -f index ] || get_index_tree index
1207 if [ -d worktrees ]; then
1208 find -L worktrees -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1209 while read -r lwth; do
1210 get_detached_head "$lwth"
1211 get_index_tree "${lwth%HEAD}index"
1212 done
1214 } | LC_ALL=C sort -u |
1215 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1216 awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1220 ## main gc logic
1223 # Everything else is more efficient if we do this first
1224 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
1225 git pack-refs --all --prune
1226 [ -e packed-refs ] || >>packed-refs # should never happen...
1228 # If we have a logs directory or a worktrees directory expire the ref logs now
1229 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1230 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1232 make_repack_dir
1233 ! [ -e .gc_failed ] || exit 1
1234 rm -f .gc_in_progress # make sure
1235 touch .gc_in_progress # it's truly fresh
1236 rm -f bundles/* objects/pack/pack-*.bndl
1237 # These only exist for a brief time before the packs loose their _f suffix
1238 # "Push Pack Redux" does not apply to these since they were only ever present with _f
1239 rm -f objects/pack/pack-*_f.keep
1240 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1241 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1242 # and we have garbage collection forced, there's just the barest, almost negligible,
1243 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1244 # should not be removing _r .keep files. None of the normal Girocco processing can
1245 # cause this. The second run of this script would have to use the force gc option
1246 # for it to even be possible in the first place. What's much more likely is that
1247 # the initial run of this script was somehow interrupted in the middle before it
1248 # could get rid of the _r .keep file itself in which case it's better to get rid of
1249 # it now to avoid keeping something around that would perturb our nice and neat gc
1250 rm -f objects/pack/pack-*_r.keep
1251 # We will add .keep files for _u and _l packs if and when we run phase III
1252 # Otherwise they need to not have any .keep files during phases I and II
1253 rm -f objects/pack/pack-*_[ul].keep
1255 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1256 # activity will be able to "freshen" the pack containing a pre-existing object
1257 # that's being written. This really should not be necessary as the pre-receive
1258 # hook should make sure this takes place for any incoming pushes.
1259 # However, do it here anyway just in case.
1260 make_packs_ugw objects/pack
1262 # This is only effective with Git v2.3.5 and later and it will only matter when
1263 # we are using one of the "internal_rev_list" modes of pack-objects
1264 # (the combine-packs.sh script never uses any of those modes)
1265 # The "git repack" and "git prune" commands always set this internally themselves
1266 # It makes no difference if there's no repository corruption
1267 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1269 # All of the options we might want to use with pack-objects were supported
1270 # at some point prior to Git version v1.6.6 which is the minimum version that
1271 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1272 # are "boiler plate" options we always want to use so we bundle them up here.
1273 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1274 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1275 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1276 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1277 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1278 # This is not a free check as it matches all refs against refs/tags/ then
1279 # peels all the annotated tags and checks for inclusion. The situation in
1280 # which it would add a tag that was not already included by a reachability
1281 # trace that included tag starting points can only occur if a new tag gets
1282 # pushed during gc pointing to something that would have been packed anyway.
1283 # But, it could happen and, really, compared to gc as a whole it's not that
1284 # expensive to perform (provided we do not get an unconnected pack).
1285 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1286 pkopt="$pkopt ${quiet:---progress} $packopts"
1288 # The git pack-objects command only supports bitmaps if all objects are being
1289 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1290 # Additionally, while packing, if any encountered reachable objects are
1291 # determined to be "not wanted" then no bitmap index will be written anyway.
1292 # While it is theoretically possible that a project with a non-empty alternates
1293 # file ends up packing all objects (because it does not actually use any of the
1294 # objects found in the alternates), it's very unlikely. And, in the unlikely
1295 # event that did occur, clients would see a message about only using one bitmap
1296 # because Git can only use one bitmap at a time and at least one of the
1297 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1298 # alternates file, we disable writing bitmaps which avoids the warning and any
1299 # possibility of a client warning as well. Also if we are running anything
1300 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1301 # we also always disable bitmap writing.
1302 wbmopt=
1303 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1304 # More recent versions of pack-objects have optimizations when not using the
1305 # --local option. If we do not have any alternates it's a pointless option.
1306 # If we do have alternates we need to skip writing a bitmap and we cannot
1307 # have a bundle since it must contain all objects.
1308 if [ -n "$isfork" ]; then
1309 lclopt="--local"
1310 wbmopt=
1311 makebndl=
1312 else
1313 lclopt=
1314 makebndl=1
1318 ## Phase I
1321 wbmstr=
1322 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1323 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1325 gotforks=
1326 ! has_forks_with_alternates "$proj" || gotforks=1
1328 # To avoid "Push Pack Redux" (see docs/technical/gc.txt), after collecting the
1329 # initial preexisting non-keep pack list, we rename them so that an incoming push
1330 # pack cannot possibly experience a pack name collision. Git does not require
1331 # use of the "default" pack names, simply that the proper extensions are used.
1332 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1333 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1334 # down into forks and it will have an "_u" inserted just before its extension.
1335 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1336 oldpacks=
1337 for oldpack in $packlist; do
1338 oldpack="${oldpack%.pack}"
1339 [ -f "objects/pack/$oldpack.pack" ] || {
1340 echo >&2 "[$proj] unable to list old pack files"
1341 exit 1
1343 case "$oldpack" in pre-auto-gc-[12])
1344 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1345 continue
1346 esac
1347 oldpackhex="${oldpack#pack-}"
1348 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1349 # names not exclusively hexadecimal do not need renaming
1350 case "$oldpack" in
1351 pack-$octet20*_l)
1352 # _l packs are treated like still-unpacked loose objects
1353 continue;;
1354 *_f)
1355 # _f packs can only be left over from a previously interrupted gc;
1356 # they need to be renamed to _r now so they're not confused with
1357 # any freshly generated "final" packs (and we already removed
1358 # any pre-existing *_f.keep files so we're good to go)
1361 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1362 continue;;
1363 esac
1365 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack%_f}_r" || {
1366 echo >&2 "[$proj] unable to rename old pack files"
1367 exit 1
1369 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1370 # in progress at this moment and we need to .keep the renamed pack,
1371 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1372 # In either case we're okay because if it's just finished then all ref
1373 # changes have already been made so we don't need a .keep and we will
1374 # see the ref changes and grab all the objects via a reachability trace.
1375 # If it hasn't started yet that's okay because we're done moving that
1376 # name so a complete pack will appear under the old name that we'll
1377 # leave alone.
1378 if [ -f "objects/pack/$oldpack.keep" ]; then
1379 echo "Push Pack Redux" >"objects/pack/${oldpack%_f}_r.keep"
1380 else
1381 oldpacks="${oldpacks:+$oldpacks }${oldpack%_f}_r"
1383 done
1385 # We wish to keep deltas from our last full pack so if we're not redeltaing
1386 # then make sure the .pack associated with the .bitmap has a newer mod time
1387 # (If there is no .bitmap then touch the pack with the most objects instead.)
1388 if [ -z "$newdeltas" ]; then
1389 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1390 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1391 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1392 sleep 1
1393 touch -c "$bmpack" 2>/dev/null || :
1394 # We must touch .gc_in_progress here to avoid $bmpack looking
1395 # like it's been "freshened" when redundant packs are removed
1396 # It's okay if they have the same mod time, but POSIX does not
1397 # guarantee an ordering for the "touching" that occurs which is
1398 # why this must be a separate command but needs no "sleep 1"
1399 touch .gc_in_progress
1403 # Now we need to make sure that any "freshening" that takes place will actually
1404 # result in a "newer" modification time than the .gc_in_progress file now has
1405 sleep 1
1407 # We run git pack-objects from the repack subdirectory so we can force
1408 # optimized packs to be generated even for repositories that do not have any
1409 # tagged commits
1410 packs="$(git --git-dir=repack pack-objects </dev/null \
1411 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1412 vcnt packcnt $packs
1413 [ $packcnt -eq 1 ] || makebndl=
1416 ## Phase II
1419 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1421 # Add the "supplementary" refs
1422 compute_extra_reachables >>repack/packed-refs
1424 # Subtract the primary refs
1425 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1426 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1428 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1429 # However, if there is a "logs" subdirectory we need to use --reflog
1430 # We do add it, just in case, if the linked working trees dir is present
1431 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1432 # if it properly includes linked working tree index files or not. The
1433 # above compute_extra_reachables has already included all index trees (thereby
1434 # providing proper --indexed-objects support for all Git versions) making the
1435 # option completely unnecessary.
1436 rflopt=
1437 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1438 spacks="$(git --git-dir=repack pack-objects </dev/null \
1439 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1442 ## Phase III
1445 # There's nothing to do for Phase III unless we have forks that refer to our
1446 # project from their alternates file
1447 hlpacks=
1448 upacks=
1449 if [ -n "$gotforks" ]; then
1451 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1453 # If we are a fork, any pre-existing _u packs need to have a .keep
1454 # for this phase and be added to the hlpacks list otherwise (we are
1455 # not a fork) pre-existing _u packs are anomalies to be treated like
1456 # regular non-_u packs
1457 if [ -n "$isfork" ]; then
1458 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_[ul].pack" -print); do
1459 upack="${upack%.pack}"
1460 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1461 case "$upack" in *_l);;*)
1462 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1463 esac
1464 done
1466 # Using either --no-reuse-delta or --no-reuse-object together with the
1467 # --keep-unreachable option is a very, very, very bad idea when good
1468 # packs are the desired outcome. If newdeltas are being generated
1469 # then we pack to a temp name, and use combine-packs.sh to get a better
1470 # pack as the result to avoid making a bad --keep-unreachable pack
1471 pfx=
1472 [ -z "$newdeltas" ] || pfx="ku"
1473 upacks="$(git --git-dir=repack pack-objects </dev/null \
1474 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1475 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1476 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1477 oldupacks="$upacks"
1478 upacks="$(
1479 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1480 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1481 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1482 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1484 for upack in $upacks; do
1485 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1486 done
1487 rm -f objects/pack/pack-*_[ul].keep
1488 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1489 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1491 # We have to update the lastparentgc time in the child forks even if they do not get any
1492 # new "unreachable packs" because they need to run gc just in case the parent now has some
1493 # objects that used to only be in the child so they can be removed from the child.
1494 # For example, a "patch" might be developed first in a fork and then later accepted into
1495 # the parent in which case the objects making up the patch in the child fork are now
1496 # redundant (since they're now in the parent as well) and need to be removed from the
1497 # child fork which can only happen if the child fork runs gc.
1498 lastparentgc="$(date "$datefmt")"
1500 # It is enough to copy objects just one level down and get_repo_list
1501 # takes a regular expression (which is automatically prefixed with '^')
1502 # so we can easily match forks exactly one level down from this project
1503 forkdir="$proj"
1504 get_repo_list "$forkdir/[^/:][^/:]*:" |
1505 while read fork; do
1506 # Ignore forks that do not exist or are symbolic links
1507 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1508 continue
1509 # Or do not have a non-zero length alternates file
1510 [ -s "$cfg_reporoot/$fork.git/objects/info/alternates" ] ||
1511 continue
1512 runupdate=
1513 # Match hlpacks in parent project if any
1514 if [ -n "$hlpacks" ]; then
1515 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1516 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1517 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1518 '"$cfg_reporoot/$fork.git/objects/pack/"'
1519 runupdate=1
1521 # Match upacks in repack/alt area if any
1522 if [ -n "$upacks" ]; then
1523 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1524 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1525 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1526 '"$cfg_reporoot/$fork.git/objects/pack/"'
1527 runupdate=1
1529 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1530 # Trigger a mini gc in the fork if it now has too many packs
1531 packs="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1532 if [ -n "$packs" ] && [ "$packs" -ge 20 ]; then
1533 >"$cfg_reporoot/$fork.git/.needsgc"
1536 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1537 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1538 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1539 done
1542 # Now move any primary/supplementary packs back into objects/pack
1543 # then drop any "unfreshened" redundant packs and clear repack/alt
1545 # First make sure the primary pack(s) have the most recent mod time
1546 if [ -n "$packs" ]; then
1547 [ -z "$spacks" ] || sleep 1
1548 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1551 # Move the packs into place but with a _f suffix and a .keep file for now
1552 for pack in $packs $spacks; do
1553 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-${pack}_f"
1554 [ -e "objects/pack/pack-${pack}_f.keep" ] ||
1555 echo "final" >"objects/pack/pack-${pack}_f.keep"
1556 done
1558 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1559 # with its .bitmap) and then got "freshened" causing us to not remove it
1560 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1561 # This can produce ugly warnings we don't want and possibly get the wrong
1562 # bitmap used since only one .bitmap file can ever be used by Git.
1563 # If this has happened, the .bitmap we want to discard will always have
1564 # an _r suffix so we can just zap any such now since it will leave the pack.
1565 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1567 # Remove the redundant packs that have not since been "freshened"
1568 # This does not completely eliminate the race condition window (Girocco's own
1569 # activites -- gc/fetch/receive are immune to the race) but it substantially
1570 # shrinks it down to just the time after the find but before the following rm
1571 >repack/oldpacks
1572 [ -z "$oldpacks" ] ||
1573 printf 'objects/pack/%s.pack\n' $oldpacks |
1574 LC_ALL=C sort >repack/oldpacks
1575 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1576 LC_ALL=C sort >repack/freshened
1577 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1578 [ -z "$deadpacks" ] ||
1579 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1581 # No need for this anymore
1582 rm -rf repack/alt objects/pack/repack
1583 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1586 ## Phase IV
1589 progress "~ [$proj] running gc prune-packed"
1591 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1592 # present while running prune-packed. We try to guarantee that any loose object
1593 # (or any object present in a pack with an _l suffix which was created by mini gc)
1594 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1595 # (not withstanding administrator interference to force earlier gc to occur).
1596 # If we were to include the redundant/keep-unreachable pack(s) when running
1597 # prune-packed and a loose unreachable object happened to be duplicated in one
1598 # of them we would end up removing it too soon and void our guarantee.
1599 git prune-packed $quiet
1601 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1603 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1604 # we MUST NOT use it for these reasons:
1605 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1606 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1607 # 3) We don't require anything more than Git v1.6.6
1608 # The only way we could see any _o pack files at this point is if one got
1609 # "freshened" while we were running gc. If that happens then it gets to live on
1610 # until the next full gc and we need to include it in the loose repack here.
1611 lpacks="$(list_packs --exclude-no-idx --exclude-no-sfx _l --exclude-no-sfx _o --quiet objects/pack |
1612 run_combine_packs --replace --names --loose --weak-naming --non-empty --honor-pack-keep \
1613 --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1615 if [ -n "$lpacks" ]; then
1616 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1617 if [ -n "$packs" ]; then
1618 sleep 1
1619 printf 'objects/pack/pack-%s_f.pack\n' $packs | xargs touch -c 2>/dev/null || :
1621 # We need to identify these packs later so we don't combine_packs them
1622 for objpack in $lpacks; do
1623 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1624 done
1627 # Polish up the final packs now
1628 rm -f objects/pack/pack-*_f.keep
1629 for pack in $packs $spacks; do
1630 rename_pack "objects/pack/pack-${pack}_f" "objects/pack/pack-$pack"
1631 done
1633 if [ -n "$lpacks" ]; then
1634 # Finally zap the corresponding loose objects
1635 progress "~ [$proj] running packed loose objects gc prune-packed"
1636 git prune-packed $quiet
1639 ! [ -e .gc_failed ] || exit 1
1640 # These, if they exist, are now meaningless and need to be removed
1641 rm -f gfi-packs .needsgc .needspack .needspackgc
1643 # Make sure this stays up to date
1644 git update-server-info
1646 # We must make loose objects group writable so that they
1647 # can be freshened by other pushers. Technically we need only do this for
1648 # push projects but to enable mirror projects to be more easily converted to
1649 # push projects, we go ahead and do it for all projects.
1650 # By the time we get here we really shouldn't have any of these, but just in case.
1651 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1653 # darcs:// mirrors have a xxx.log file that will grow endlessly
1654 # if this is a mirror and the file exists, shorten it to 10000 lines
1655 # also take this opportunity to optimize the darcs repo
1656 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1657 url="$(config_get baseurl)" || :
1658 case "$url" in darcs://*)
1659 if [ -n "$cfg_mirror_darcs" ]; then
1660 url="${url%/}"
1661 basedarcs="$(basename "${url#darcs:/}")"
1662 if [ -f "$basedarcs.log" ]; then
1663 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1664 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1666 if [ -d "$basedarcs.darcs" ]; then
1668 cd "$basedarcs.darcs"
1669 # without show_progress suppress non-error output
1670 [ "${show_progress:-0}" != "0" ] || exec >/dev/null
1671 # Note that this does not optimize _darcs/inventories/ :(
1672 darcs optimize || :
1676 esac
1679 # Create a matching .bndl header file for the all-in-one pack we just created
1680 # but only if we're not a fork (otherwise the bundle would not be complete)
1681 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1682 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1683 # There should only be one pack in $packs but do some checking...
1684 # The one we just created will have a .idx and will NOT have a .keep
1685 progress "~ [$proj] creating downloadable bundle header"
1686 pkbase=
1687 pkhead=
1688 IFS= read -r curhead <repack/HEAD.orig || :
1690 [ -s "objects/pack/pack-$packs.pack" ] &&
1691 [ -s "objects/pack/pack-$packs.idx" ] &&
1692 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1693 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1694 "$PWD/repack/packed-refs.orig" "$curhead")"
1695 then
1696 pkbase="objects/pack/pack-$packs"
1698 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1700 symref=
1701 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1702 symref="${curhead#ref:}"
1703 symref="${symref# }"
1704 esac
1705 bndlurl=
1706 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1707 echo "# v2 git bundle"
1708 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1709 if [ -n "$symref" ]; then
1710 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1711 else
1712 if [ -n "$bndlurl" ]; then
1713 printf "$pkhead HEAD\0%s\n" "${bndlurl:# }"
1714 else
1715 echo "$pkhead HEAD"
1718 echo ""
1719 } >"$pkbase.bndl"
1720 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1721 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1722 if [ -n "$bndletag" ]; then
1723 case "$bndlsha" in $octet20*)
1724 bndlshatrailer="${bndlsha#????????}"
1725 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1726 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1727 [ -d bundles ] || mkdir bundles
1728 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1729 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1730 ln -s -f -n "$bndlname" bundles/latest
1731 esac
1736 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1737 eval "reposizek=$(( $(
1738 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1739 LC_ALL=C awk '{print $1}') |
1740 LC_ALL=C sed -e 's/ / + /g') ))"
1741 config_set_raw girocco.reposizek "${reposizek:-0}"
1743 # Now we're finally done with this
1744 rm -rf repack
1746 # We didn't used to do anything about rerere or worktrees but we're
1747 # trying to make nice with linked working trees these days :)
1748 # Maybe even non-bare repositories too, but *shush* about those ;)
1749 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1750 # The value "3.months.ago" is hard-coded into gc.c rather than
1751 # having the default be in worktree.c so we must provide it if
1752 # we get nothing out of the gc.worktreePruneExpire config item
1753 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1754 # however we just always use the newer name no matter what Git version
1755 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1756 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1758 # git rerere does it right and handles its own default/config'd expiration values
1759 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1761 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1762 # and the next future gc could be incorrectly skipped if we used the current
1763 # timestamp here instead
1764 config_set lastgc "$gcstart"
1765 rm -f "$lockf"
1767 progress "- [$proj] garbage check ($(date))"