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