gc-util-functions.sh: extract common gc-related functions
[girocco.git] / jobd / gc.sh
blobce60cb11961d1efd1c728582a53798184f1b0519
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
8 . @basedir@/jobd/gc-util-functions.sh
10 set -e
12 if [ $# -lt 1 ]; then
13 echo "Usage: gc.sh projname [extra-repack-args]" >&2
14 exit 1
17 # Includes
18 _shlib_done=1
19 unset GIROCCO_SUPPRESS_AUTO_GC_UPDATE
20 . "$cfg_basedir/jobd/maintain-auto-gc-hack.sh"
21 . "$cfg_basedir/jobd/generate-auto-gc-update.sh"
22 GIROCCO_SUPPRESS_AUTO_GC_UPDATE=1 && export GIROCCO_SUPPRESS_AUTO_GC_UPDATE
24 # packing options
25 packopts="--depth=50 --window=50 --window-memory=${var_window_memory:-1g}"
26 quiet="-q"; [ "${show_progress:-0}" = "0" ] || quiet=
28 umask 002
29 [ "$cfg_permission_control" != "Hooks" ] || umask 000
30 clean_git_env
32 vcnt() {
33 eval "$1="'$(( $# - 1 ))'
36 pidactive() {
37 if _result="$(kill -0 "$1" 2>&1)"; then
38 # process exists and we have permission to signal it
39 return 0
41 case "$_result" in *"not permitted"*)
42 # we do not have permission to signal the process
43 return 0
44 esac
45 # process does not exist
46 return 1
49 createlock() {
50 # A .lock file should only exist for much less than a second.
51 # If we see a stale lock file (> 1h old), remove it and then,
52 # just in case, wait 30 seconds for any process whose .lock
53 # we might have just removed (it's racy) to finish doing what
54 # should take much less than a second to do.
55 _stalelock="$(find -L "$1.lock" -maxdepth 1 -mmin +60 -print 2>/dev/null)" || :
56 if [ -n "$_stalelock" ]; then
57 rm -f "$_stalelock"
58 sleep 30
60 for _try in p p n; do
61 if (set -C; >"$1.lock") 2>/dev/null; then
62 echo "$1.lock"
63 return 0
65 # delay and try again
66 [ "$_try" != "p" ] || sleep 1
67 done
68 # cannot create lock file
69 return 1
72 # The pre-receive script creates one ref log file per push but we want them to
73 # be coalesced into one ref log file per day. We are guaranteed that any files
74 # we find to coalesce are NOT currently being written to since they are always
75 # written first as temporary files and then moved into place. We attempt to
76 # transfer the most recent modification time to the coalesced log file which
77 # would step on its mod time if it were being written to directly, but if we
78 # find per-process ref log files then it must be a push project and the only
79 # thing that would write directly to the main per-day log file would be a
80 # mirror project so there's actually no conflict.
81 # Also, if the clock is wonky (or was futzed with) we may have both YYYYMMDD
82 # and YYYYMMDD.gz present in which case combine them into YYYYMMDD
83 coalesce_reflogs() {
84 [ -d reflogs ] || return 0
85 rm -f .gc_failed
86 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 |
87 while read -r rname; do
88 if [ -e "$rname.gz" ]; then
89 if [ -s "$rname" ]; then
90 # Presumably the .gz file must have been created before the non-gz
91 # file since it had to be uncompressed at some point therefore
92 # we need to append the non-gz contents to it but keep the non-gz
93 # contents timestamp so we rename to YYYYMMDD_ which will sort first
94 # and be picked up in the next step if we are interrupted in the middle.
95 # If a YYYYMMDD_ file already exists we append to it and transfer the
96 # timestamp. Finally we transfer the YYYYMMDD_ timestamp to the result
97 # and remove the YYYYMMDD_ temporary file leaving the result uncompressed.
98 if [ -e "${rname}_" ]; then
99 cat "$rname" >>"${rname}_"
100 touch -r "$rname" "${rname}_"
101 rm -f "$rname"
102 ! [ -e "$rname" ]
103 else
104 mv "$rname" "${rname}_"
106 gzip -d "$rname.gz" </dev/null
107 [ -e "$rname" ] && ! [ -e "$rname.gz" ]
108 cat "${rname}_" >>"$rname"
109 touch -r "${rname}_" "$rname"
110 rm -f "${rname}_"
111 else
112 # Just remove the empty file to resolve the problem
113 rm -f "$rname"
116 done
117 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 |
118 while read -r rname; do
119 logname="${rname%%_*}"
120 # If someone's been futzing with the date, the file we want to
121 # append to could already have been compressed, so we just uncompress
122 # it here. The previous block guarantees we do not have both a compressed
123 # and uncompressed version present at the same time.
124 if [ -e "$logname.gz" ]; then
125 gzip -d "$logname.gz" </dev/null
126 [ -e "$logname" ] && ! [ -e "$logname.gz" ]
128 cat "$rname" >>"$logname"
129 touch -r "$rname" "$logname"
130 rm -f "$rname"
131 if [ -e "$rname" ]; then
132 >.gc_failed
133 echo "! [$proj] failed to remove $rname" >&2
134 exit 1 # will only exit subshell created by "|"
136 done
137 ! [ -e .gc_failed ]
140 # Remove any files in reflogs that are older than $cfg_reflogs_lifetime days
141 prune_reflogs() {
142 [ -d reflogs ] || return 0
143 exp="$(( ${cfg_reflogs_lifetime:-1} * 1440 ))"
144 [ $exp -gt 0 ] || exp=1440
145 [ $exp -le 43200 ] || exp=43200
146 find -L reflogs -maxdepth 1 -type f -mmin "+$exp" -exec rm -f '{}' + || :
149 # Compact any reflogs that are not today's UTC date unless a .gz version exists
150 compact_reflogs() {
151 [ -d reflogs ] || return 0
152 _td="reflogs/$(TZ=UTC date '+%Y%m%d')"
153 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 |
154 while read -r rname; do
155 [ "$rname" != "$_td" ] || continue
156 ! [ -e "$rname.gz" ] || continue
157 gzip -9 "$rname" </dev/null
158 done
161 # return true if there's more than one objects/pack-<sha>.pack file or
162 # ANY sha-1 files in objects or
163 # there's one pack and it's not a normal pack name or
164 # there's one pack but not any refs
165 is_dirty() {
166 _packs="$(find -L objects/pack -name "pre-auto-gc-[12].pack" -prune -o -name "*.pack" -type f -print 2>/dev/null | head -n 2)"
167 vcnt _packscnt $_packs
168 if [ $_packscnt -gt 1 ]; then
169 return 0
171 if [ $_packscnt -eq 1 ]; then
172 # the single pack name is in $_packs
173 _packs="${_packs%.pack}"
174 _packs="${_packs#objects/pack/}"
175 case "$_packs" in
176 pack-*)
177 _packs="${_packs#pack-}"
178 if [ "${#_packs}" -lt 40 ] || [ "${_packs#*[!0-9a-fA-F]}" != "$_packs" ]; then
179 # name not exclusively 40 or more hexadecimal digits makes it dirty
180 return 0
184 # abnormal name makes it dirty
185 return 0
187 esac
189 _objs=$(find -L objects/$octet -name "$octet19*" -type f -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
190 [ $_objs -eq 0 ] || return 0
191 [ $_packscnt -eq 1 ] || return 1
192 # we do this check last because it's potentially the most expensive;
193 # at this point we know we do not have any loose objects, but we do
194 # have one pack that's named "normally"; empty refs => dirty
195 is_empty_refs_dir
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 # pack any existing loose objects into a new _l.pack file then run prune-packed
224 # note that prune-packed is NOT run beforehand -- the caller must do that if needed
225 # loose objects need not be part of complete commits/trees as --weak-naming is used
226 pack_loose_objects() {
227 _lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts)"
228 if [ -n "$_lpacks" ]; then
229 # We need to identify these packs later so we don't combine_packs them
230 for _objpack in $_lpacks; do
231 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
232 done
233 git prune-packed $quiet
237 # combine small packs into larger pack(s)
238 # we avoid any _[lo], keep, bndl or bitmap packs
239 # if the optional argument is non-empty even a single small pack will be redeltad
240 combine_small_packs() {
241 _didprogress=
242 _minsmallpacks=2
243 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
244 _minsmallpacks=1
246 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
247 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o --exclude-sfx _l"
248 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
249 while
250 _cnt="$(list_packs --count $_lpo)" || :
251 test "${_cnt:-0}" -ge $_minsmallpacks
253 [ -n "$_didprogress" ] || {
254 progress "~ [$proj] combining small packs into a single larger pack"
255 _didprogress=1
257 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
258 vcnt _newc $_newp
259 # be paranoid and exit the loop if we haven't reduced the number of packs
260 [ $_newc -lt $_cnt ] || break
261 _minsmallpacks=2
262 done
263 return 0
266 # combine small _l packs into larger pack(s) using --weak-naming
267 # we avoid any non _l, keep, bndl or bitmap packs
268 # if the optional 2nd argument is non-empty even a single small pack will be redeltad
269 combine_small_loose_packs() {
270 _didprogress=
271 _minsmallpacks=2
272 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
273 _minsmallpacks=1
275 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
276 _lpo="$_lpo --exclude-no-sfx _l"
277 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
278 while
279 _cnt="$(list_packs --count $_lpo)" || :
280 test "${_cnt:-0}" -ge $_minsmallpacks
282 [ -n "$_didprogress" ] || {
283 progress "~ [$proj] combining small loose packs into a single larger pack"
284 _didprogress=1
286 _newp="$(list_packs $_lpo | combine_packs --names --weak-naming $noreusedeltaopt)"
287 # We need to identify these packs later so we don't combine_packs them
288 for _objpack in $_newp; do
289 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
290 done
291 vcnt _newc $_newp
292 # be paranoid and exit the loop if we haven't reduced the number of packs
293 [ $_newc -lt $_cnt ] || break
294 _minsmallpacks=2
295 done
296 return 0
299 # Unfortunately, some fetch strategies (e.g. git-svn and non-smart HTTP) lack
300 # the ability to store newly fetched objects in a pack.
301 # However, the fetch code conveniently sets .needspack just before it fetches
302 # so that it's easy to find all the loose objects that have been fetched and
303 # combine them into a pack. The --no-reuse-delta option is meaningless here
304 # since everything to be packed is a loose object and therefore not a delta so
305 # deltification will always take place.
306 make_needs_pack() {
307 [ -f .needspack ] || return 0
308 rm -f .needspackgc
309 mv -f .needspack .needspackgc
310 progress "~ [$proj] combining fetched loose objects into a pack"
311 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .needspackgc -name "$octet19*" -print 2>/dev/null |
312 LC_ALL=C awk -F / '{print $2 $3}' |
313 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
314 # We used to fail gc here.
315 # Now, however, we just ignore the failure because we have
316 # another mechanism to handle loose objects and it's possible
317 # that the fetcher somehow brought in unconnected objects which
318 # would cause the above combine-packs to fail.
319 # By ignoring the failure and just removing the .needspack file
320 # the loose objects will be treated as "ordinary" loose objects
321 # and packed using the "--weak-naming" option which can handle
322 # broken connectivity.
323 # That's a better solution than just failing here or leaving
324 # .needspack behind to potentially continue to fail again and
325 # again.
326 _newp=
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 .needspackgc
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 ! [ -d logs ] || ln -s ../logs repack/logs
477 ! [ -d worktrees ] || ln -s ../worktrees repack/worktrees
478 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
479 cat HEAD >repack/HEAD.orig
480 >repack/packed-refs.extra
481 _xtralines=0
482 cat packed-refs >repack/packed-refs.orig
483 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
484 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
485 exit 1
487 if [ "${cfg_fetch_stash_refs:-0}" = "0" ]; then
488 # migrate any refs/stash or refs/tgstash lines to repack/packed-refs.extra
489 <repack/packed-refs.orig LC_ALL=C awk -v xtra="repack/packed-refs.extra" '
490 BEGIN { peeling = 0 }
491 NR == 1 && /^#/ { print; next; }
492 peeling && /^\^/ { print >>xtra; next; }
493 /^[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]+ refs\/(stash|tgstash)(\/|$)/ {
494 peeling = 1
495 print >>xtra
496 next
498 { peeling = 0; print; }
499 ' >repack/packed-refs.new
500 _xtralines="$(( $(LC_ALL=C wc -l <repack/packed-refs.extra) + 0 ))"
501 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs.new) + 0 ))"
502 if [ "$(( $_newlines + $_xtralines ))" -ne "$_lines" ]; then
503 echo >&2 "[$proj] error: make_repack_dir failed packed-refs.extra line count sanity check"
504 exit 1
506 mv -f repack/packed-refs.new repack/packed-refs.orig
507 _lines="$_newlines"
509 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
510 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
511 nohead=
512 headref="$(git rev-parse --verify --quiet HEAD)" || :
513 if [ -n "$headref" ]; then
514 echo "$headref refs/!=/HEAD" >>repack/packed-refs
515 echo "$headref refs/heads/!" >>repack/packed-refs
516 nohead='\, refs/heads/!$,d; '
517 _lines=$(( $_lines + 2 ))
519 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
520 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
521 exit 1
523 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
524 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
525 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
526 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
527 exit 1
529 _lines="$_newlines"
530 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
531 if [ -n "$optref" ]; then
532 echo "$optref refs/tags/!" >>repack/packed-refs
533 _lines=$(( $_lines + 1 ))
534 echo "$optref" >repack/HEAD
535 else
536 cat HEAD >repack/HEAD
538 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
539 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
540 exit 1
544 # Remove any crud that's been left behind by interrupted operations
545 # that did not clean up after themselves
546 remove_crud() {
547 # Remove any existing FETCH_HEAD
548 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
549 # receiving pushes (those never create a FETCH_HEAD).
550 # And if we're fetching because we're a mirror, we know we're not fetching right
551 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
552 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
553 # there were a lot of refs.
554 rm -f FETCH_HEAD
556 # remove any existing pack_is_complete_test or repack subdirectories
557 # If either exists when this function is called it's crud
558 rm -rf pack_is_complete_test repack objects/pack/repack
560 # Remove any stale pack remnants that are more than an hour old.
561 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
562 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
563 # pack-<sha1>.idx files without their corresponding .pack files are worthless
564 # and just waste space. Normally there shouldn't be any remnants but actually
565 # this can happen when things are interrupted at just the wrong time.
566 # Note that the objects/pack directory is created by git init and should
567 # always exist.
568 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
569 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
570 while read packsha; do
571 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
572 rm -f "objects/pack/pack-$packsha".?*
573 done
575 # Remove any stale tmp reflogs files that are more than one hour old.
576 # Since they are created only while the pre-receive hook is running and
577 # all it does is process a bunch of refs passed to it on standard input
578 # it's inconceivable that it would ever take as much as an hour to run.
579 if [ -d reflogs ]; then
580 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
583 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
584 # Really these files should only exist very briefly so there shouldn't be any
585 # but things happen that can end up leaving them behind.
586 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
588 # Remove any stale pack .keep files that are more than 12 hours old.
589 # We don't do anything to create any permanent pack .keep files, so they must
590 # be remnants from some failed push or something. Removing the .keep will
591 # allow the pack to be properly repacked.
592 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
594 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
595 # that are more than 12 hours old.
596 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
597 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
598 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
599 \) -exec rm -f '{}' + || :
601 # Remove any stale incoming-* object quarantine directories that are
602 # more than 12 hours old. These are new with Git >= 2.11.0.
603 find -L objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
604 -exec rm -rf '{}' + || :
606 # Remove any stale shallow_* files that are more than 12 hours old.
607 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
608 # requests a shallow clone. Also discard stale .refs-temp* and
609 # .refs-new* files at the same time.
610 find -L . -maxdepth 1 -type f -mmin +720 \( \
611 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
612 \) -exec rm -f '{}' + || :
614 # Remove any stale cmbnpcks-* dirs that are more than 12 hours old.
615 # These can be left behind by abnormal exits (e.g. power failure).
616 find -L . -maxdepth 1 -type d -mmin +720 -name "cmbnpcks-?*" \
617 -exec rm -rf '{}' + || :
619 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
620 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
621 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
623 # Remove any stale *.lock files in the htmlcache area that might have been left
624 # behind after an abnormal exit during an attempt to update a cached file and
625 # are more than 1 hour old.
626 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
628 # Remove any stale git-svn temp files that are more than 12 hours old.
629 # The git-svn process creates temp files with random 10 character names
630 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
631 # prefix, so we just have to kill any files with a 10-character name. We
632 # do this only for git-svn mirrors. All characters are chosen from
633 # [A-Za-z0-9_] so we can at least check that and fortunately the only
634 # collision is 'FETCH_HEAD' but that shouldn't matter.
635 # There may also be temp files with a Git_ prefix as well.
636 if [ -n "$svn_mirror" ]; then
637 _randchar='[A-Za-z0-9_]'
638 _randchar2="$_randchar$_randchar"
639 _randchar4="$_randchar2$_randchar2"
640 _randchar10="$_randchar4$_randchar4$_randchar2"
641 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
642 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
645 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
646 if [ -n "$gfi_mirror" ]; then
647 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
650 # Remove any stale core or *.core or core.* files that are more than 3 days old.
651 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
652 -exec rm -f '{}' + || :
656 ## Garbage Collection Types
658 ## There are two kinds of possible garbage collection (gc) operations:
660 ## 1. A normal, full gc
661 ## 2. A "mini" gc
663 ## If the full garbage collection interval has expired (or gc has never been
664 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
665 ## take place if the file .needsgc exists.
667 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
668 ## doing anything unless the right conditions are present so it's not a burden
669 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
670 ## the next opportunity.
672 ## See the docs/technical/gc.txt and docs/technical/gc-mini.txt files for more
673 ## of the gory details of how garbage collection is performed.
675 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
678 proj="${1%.git}"
679 shift
680 cd "$cfg_reporoot/$proj.git"
681 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
682 mirror_url="$(get_mirror_url)" || :
683 svn_mirror=
684 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
685 gfi_mirror=
686 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
687 gfi_mirror=1
690 # If git config --bool --get girocco.redelta is explicitly false then automatic
691 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
692 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
693 # gc only, for the final repack, deltas will always be recomputed.
694 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
695 # Setting this will hurt efficiency of the affected repository.
696 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
697 noreusedeltaopt="--no-reuse-delta"
698 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
699 alwaysredelta=
700 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
702 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
703 # to be compatible with the old and new gc.sh versions and avoid ugly argument
704 # duplication in process lists at the same time
705 # Any options found will override the "girocco.redelta" setting
706 recompress=
707 idx=$#
708 while [ $idx -gt 0 ]; do
709 idx=$(( $idx - 1 ))
710 opt="$1"
711 shift
712 case "$opt" in
713 -f|--no-reuse-delta)
714 alwaysredelta=1
715 continue
717 -F|--no-reuse-object)
718 alwaysredelta=1
719 recompress=1
720 continue
722 -?*)
725 printf >&2 '%s\n' "bad non-option argument: $opt"
726 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
727 exit 1
728 esac
729 [ -z "$opt" ] || set -- "$@" "$opt"
730 done
731 if [ -n "$alwaysredelta" ]; then
732 noreusedeltaopt="--no-reuse-delta"
733 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
736 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
737 trap 'exit 130' INT
738 trap 'exit 143' TERM
740 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
741 datefmt='+%a, %d %b %Y %T %z'
743 isminigc=
744 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
745 if [ -e .needsgc ]; then
746 isminigc=1
747 else
748 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
749 exit 0
752 if [ -e .nogc ]; then
753 progress "x [$proj] garbage check disabled"
754 exit 0
756 if ! [ -e .nofetch ] && [ -e .clone_in_progress ] && ! [ -e .clone_failed ]; then
757 progress "x [$proj] garbage check disabled (clone in progress)"
758 exit 0
760 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
761 # Eligible for a full gc but .delaygc is set so it would be skipped
762 # However .needsgc is also set so transform it into a mini instead
763 isminigc=1
764 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
767 if [ -n "$isminigc" ]; then
768 # Perform a "mini" gc
769 # Note that .delaygc is ignored here as that's only intended for full gc
770 lock_gc
771 rm -f .allowgc .needsgc
772 rm -f objects/pack/pack-*_[rful].keep
773 remove_crud
774 coalesce_reflogs
775 prune_reflogs
776 compact_reflogs
777 maintain_auto_gc_hack
778 generate_auto_gc_update
779 miniactive=
780 if [ -f .needspack ]; then
781 miniactive=1
782 progress "+ [$proj] mini garbage check ($(date))"
783 make_needs_pack
785 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
786 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
787 if [ -z "$miniactive" ]; then
788 miniactive=1
789 progress "+ [$proj] mini garbage check ($(date))"
791 repack_gfi_packs
793 if lotsa_loose_objects; then
794 if [ -z "$miniactive" ]; then
795 miniactive=1
796 progress "+ [$proj] mini garbage check ($(date))"
798 pack_loose_objects
800 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
801 # don't actually process them yet
802 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
803 packcnt="$(list_packs --count $lpo objects/pack)" || :
804 if [ "${packcnt:-0}" -ge 10 ]; then
805 if [ -z "$miniactive" ]; then
806 miniactive=1
807 progress "+ [$proj] mini garbage check ($(date))"
809 # if we have at least 10 packs go ahead and pack all refs now too
810 git pack-refs --all --prune
811 if [ -n "$gfi_mirror" ]; then
812 repack_gfi_packs
813 packcnt="$(list_packs --count $lpo objects/pack)" || :
815 # if repack_gfi_packs dropped the pack count to < 10 don't combine
816 if [ "${packcnt:-0}" -ge 10 ]; then
817 combine_small_packs
818 combine_small_loose_packs
819 packcnt="$(list_packs --count $lpo objects/pack)" || :
821 # if we still have more than 10 packs trigger a full gc
822 if [ "${packcnt:-0}" -ge 10 ]; then
823 # We shouldn't be in a .delaygc state at this point, but if
824 # we are then nuke it because we really need a full gc now
825 rm -f .delaygc
826 git config --unset gitweb.lastgc
827 rm -f "$lockf"
828 git update-server-info # just in case
829 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
830 exit 0
833 rm -f "$lockf"
834 if [ -n "$miniactive" ]; then
835 git update-server-info
836 progress "- [$proj] mini garbage check ($(date))"
837 else
838 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
840 exit 0
843 # Avoid unnecessary garbage collections:
844 # 1. If lastreceive is set and is older than lastgc
845 # -AND-
846 # 2. We are not a fork (is_empty_alternates_file) -OR- lastparentgc is older than lastgc
848 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
849 # If we are a fork and lastparentgc is NOT set we MUST run gc
851 # If the repo is dirty after removing any crud we MUST run gc
853 gcstart="$(date "$datefmt")"
854 skipgc=
855 isfork=
856 is_empty_alternates_file objects/info/alternates || isfork=1
857 lastparentgcsecs=
858 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
859 lastreceivesecs=
860 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
861 [ "${force_gc:-0}" = "0" ] &&
862 lastgcsecs="$(config_get_date_seconds lastgc)" &&
863 [ $lastreceivesecs -lt $lastgcsecs ]; then
864 # We've run gc since we last received, so maybe we can skip,
865 # check if not fork or fork and lastparentgc < lastgc
866 if [ -n "$isfork" ]; then
867 if [ -n "$lastparentgcsecs" ] &&
868 [ $lastparentgcsecs -lt $lastgcsecs ]; then
869 # We've run gc since our parent ran gc so we can skip
870 skipgc=1
872 else
873 # We don't have any alternates (we're not a forK) so we can skip
874 skipgc=1
878 # Prevent any other simultaneous gc operations
879 lock_gc
881 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
882 rm -f .allowgc .gc_failed
884 # Ideally we would do this in post-receive, but that would mean duplicating the
885 # logic so it's available in the chroot jail and that's highly undesirable
886 # Instead, since the first gc will be triggered immediately following the first
887 # push, we do the check here as it's quick and harmless if HEAD is already valid
888 check_and_set_head || :
890 # Always get rid of crud
891 remove_crud
893 # Always perform reflogs maintenance
894 coalesce_reflogs
895 prune_reflogs
896 compact_reflogs
898 # Always maintain auto gc hack
899 maintain_auto_gc_hack
900 generate_auto_gc_update
902 # Run 'git svn gc' now for svn mirrors
903 if [ -n "$svn_mirror" ]; then
904 git svn gc || :
907 # Skip the actual gc if .delaygc is set
908 if [ -e .delaygc ]; then
909 progress "x [$proj] garbage check delayed (except for crud removal)"
910 rm -f "$lockf"
911 exit 0
914 # Do not skip gc if the repo is dirty
915 if [ -n "$skipgc" ] && ! is_dirty; then
916 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
917 config_set lastgc "$gcstart"
918 rm -f "$lockf"
919 exit 0
922 bumptime=
923 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
924 # set lastparentgc and then update gcstart to be at least 1 second later
925 config_set lastparentgc "$gcstart"
926 bumptime=1
928 if [ -z "$lastreceivesecs" ]; then
929 # set lastreceive and then update gcstart to be at least 1 second later
930 config_set lastreceive "$gcstart"
931 bumptime=1
933 if [ -n "$bumptime" ]; then
934 sleep 1
935 gcstart="$(date "$datefmt")"
938 progress "+ [$proj] garbage check ($(date))"
940 newdeltas=
941 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
942 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
943 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
944 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
945 # Don't bother with repack_gfi_packs since everything's being repacked
946 newdeltas="--no-reuse-delta"
949 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
950 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
951 # There aren't enough objects to worry about so just redelta to get the best pack
952 newdeltas="--no-reuse-delta"
954 if [ -z "$newdeltas" ]; then
955 # Since we're not going to recompute deltas overall, we need to do the
956 # "mini" maintenance so that we can get more optimal deltas
957 [ -z "$noreusedeltaopt" ] || make_needs_pack
958 repack_gfi_packs
959 force_single_pack_redelta=
960 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
961 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
962 [ -z "$noreusedeltaopt" ] || combine_small_loose_packs $force_single_pack_redelta
966 ## Safe Pruning In Forks
968 ## We are about to perform garbage collection. We do NOT use the "git gc" or
969 ## the "git repack" commands directly as they do not provide enough control over
970 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
971 ## collection so that a simultaneous "git gc" by an administrator will be
972 ## blocked (and similarly we refuse to start garbage collection if we cannot
973 ## create the "gc.pid" file).
975 ## When we say "gc" in the below description we are referring to our "gc.sh"
976 ## script, NOT the "git gc" command.
978 ## If the project we are running garbage collection (gc) on has any forks we
979 ## must be careful not to remove any objects that while no longer referenced by
980 ## this project (the parent) are still referenced by one or more forks (the
981 ## children) otherwise the children will become corrupt and we can't abide
982 ## corrupt children.
984 ## One way to accomplish this is to simply hard-link all currently existing
985 ## loose objects and packs in the parent into all the children that refer to the
986 ## parent (via a line in their objects/info/alternates file) before beginning
987 ## the gc operation and then relying on a subsequent gc in the child to clean up
988 ## any excess objects/packs. We used to use this strategy but it's very
989 ## inefficient because:
991 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
992 ## until all children (and their children, if any) run gc by which time
993 ## it's quite possible the topmost parent will have run gc again and
994 ## hard-linked yet another old pack down to its children (not to mention
995 ## loose objects).
997 ## 2. When using the "-A" option with "git repack", any new objects in the
998 ## parent that are not referenced by children will continually get
999 ## exploded out of the hard-linked pack in the children whenever the
1000 ## children run gc.
1002 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
1003 ## into child forks, we must run the "mini" gc maintenance before we
1004 ## perform the hard-linking into the children which provides yet another
1005 ## source of inefficiency.
1007 ## While we were still using the "-A" option to "git repack" (that was not
1008 ## always the case) to guarantee we can access old ref values for long enough
1009 ## to send out a meaningful mail.sh notification, another, more efficient,
1010 ## option became available to prevent corruption of child forks that continue
1011 ## to refer to objects that are no longer reachable from any ref in the parent.
1013 ## The only things that need be copied (or hard-linked) into the child fork(s)
1014 ## are those objects that have become unreachable from any ref in the parent.
1016 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
1017 ## technique, the only objects that could ever be removed were loose objects
1018 ## that "git prune" determined were expired. In that case, loose objects were
1019 ## all that need be hard-linked down to child forks in order to avoid
1020 ## corruption of any child fork(s).
1022 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
1023 ## objects to child forks technique remains fundamentally sound from the
1024 ## perspective of supporting simultaneous gc and push and keeping newly
1025 ## unreachable objects around long enough to be sure we can send out meaningful
1026 ## ref change notifications and never corrupting any child forks and never
1027 ## persisting the lifetime of large old packs containing mostly duplicate or
1028 ## unreachable objects as gc percolates through a project's entire fork tree.
1030 ## However, that technique suffers from one potential prodigious pitfall.
1032 ## Unreachable objects come flying out of their packs to splatter all over the
1033 ## objects subdirectories possibly creating a huge, inefficient mess.
1035 ## Often this is not an issue. Even with a lot of rebasing going on, usually
1036 ## the only objects that will splatter are some commits, trees and the odd blob
1037 ## here and there. Not enough to be overly concerned about.
1039 ## However, for the reppository that frequently experiences a lot of non-fast-
1040 ## forward updates and/or outright ref deletion, the number of objects suddenly
1041 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
1043 ## To avoid this issue we now use a four phase pack creation strategy.
1044 ## This will result in creation of up to four packs (instead of at most one).
1046 ## I. A complete pack (with bitmaps if appropriate) gets created including
1047 ## only "reachable" objects from all refs/... refs plus HEAD. This will
1048 ## also serve as the virtual bundle for the repository.
1050 ## II. A pack of recently-became-unreachable objects and friends is created.
1051 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
1052 ## Because both the pre-receive and update.sh script record all ref
1053 ## changes we can easily choose the cut off point for "recently".
1054 ## It is only the fact we maintain those logs in the reflogs subdirectory
1055 ## that allows this step to be possible.
1057 ## III. If the repository has any forks with a non-zero length alternates file,
1058 ## yet another pack of "--keep-unreachable" objects is generated that will
1059 ## not actually be kept in the parent, but hard-linked into all the forks.
1061 ## IV. Finally, after running "git prune-packed", any remaining loose objects
1062 ## are migrated into a pack of their own.
1064 ## We then remove any non-.keep packs that existed before we started the
1065 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
1066 ## race condition (see docs/technical/gc.txt).
1068 ## By using "git pack-objects" directly we are able to accomplish this with
1069 ## very little additional effort.
1071 ## The packs produced by (III) are treated almost like ".keep" packs by child
1072 ## forks in that the objects in them are never repacked into any other
1073 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
1074 ## and those phase III packs are then hard-linked into any grandchild forks.
1076 ## This avoids the space explosion that could occur if each fork level ended
1077 ## up duplicating the "--keep-unreachable" pack space by repacking those
1078 ## objects (essentially breaking the hard-link to the single copy of those
1079 ## objects).
1081 ## While it is true that each level of forks could potentially add yet another
1082 ## phase III pack to be hard-linked down to its children, such packs will only
1083 ## include unreachable objects not already in any phase III packs that were
1084 ## received from the parent.
1086 ## The space for the phase III packs will not be reclaimed until the gc
1087 ## finishes percolating through the entire "fork tree" of a project.
1089 ## This is not much different than the "git repack -A -d" situation where
1090 ## all the loose objects are hard-linked down into child forks. In that
1091 ## case forks that actually need any of those objects could gradually reduce
1092 ## the number of objects hard-linked into deeper fork levels.
1094 ## The difference with a phase III "--keep-unreachable" pack is that there
1095 ## cannot be any gradual reduction like that since it would require repacking
1096 ## the pack and breaking the hard-link thereby increasing storage space. The
1097 ## storage will instead always be reclaimed all at once when all of the
1098 ## projects in the "fork tree" complete their gc.
1100 ## However, the belief is that the huge space win by having all the
1101 ## unreachable objects packed up together far eclipses (when many objects are
1102 ## involved, the single-pack version can end up using 1/20th or less of the
1103 ## disk space compared to having them all as loose objects) any brief minor
1104 ## space savings that might occur under the "git repack -A -d" loose object
1105 ## system prior to the gc collection completing for all the projects in the
1106 ## "fork tree".
1110 ## utility functions
1113 make_packs_ugw() {
1114 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1115 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1116 } 2>/dev/null
1118 get_index_tree() {
1119 if [ -s "$1" ]; then
1120 GIT_INDEX_FILE="$1"
1121 export GIT_INDEX_FILE
1122 git write-tree 2>/dev/null || :
1123 unset GIT_INDEX_FILE
1127 get_detached_head() {
1128 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1129 case "$_head" in $octet20*)
1130 echo "$_head"
1131 esac
1135 # single argument must be a top-level GIT_DIR
1136 # output will be (one per line, zero or more lines) full hash
1137 # values (i.e. 40 or more hex digits) from possible detached head
1138 # "single level" refs (e.g. "FETCH_HEAD" "MERGE_HEAD" etc.) from
1139 # files in the specified directory that have a "suitable" name and
1140 # have a length >= 40 and <= 1000 where EVERY line in a file MUST
1141 # match a 40 digit (or longer) hex string or that file will be ignored.
1142 # In a nod to Git each line first has any tab and anything following truncated.
1143 # NO sorting NOR "uniq"ing NOR "--batch-check"ing is performed on the output.
1144 # Also note that "HEAD" is NOT EXCLUDED and if detached will be output!
1145 get_detached_friends() {
1146 if [ -n "$1" ] && [ -d "$1" ]; then
1147 LC_ALL=C find -H "$1" -maxdepth 1 -name '[A-Za-z]*[A-Za-z0-9]' \
1148 -type f -size +39c -size -1001c -exec awk '
1149 BEGIN {exit}
1150 function process(fn, fnt, hashes, hcnt, fl, hi) {
1151 fnt = fn; sub(/^.*\//, "", fnt)
1152 if (length(fnt) > 31 || fnt !~ /^[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9]$/) return;
1153 hcnt = 0;
1154 while (getline fl < fn) {
1155 sub(/\t.*$/, "", fl)
1156 if (length(fl) < 40 || fl !~ /^[0-9a-fA-F][0-9a-fA-F]*$/) {hcnt = 0; break;}
1157 hashes[++hcnt] = fl;
1159 close(fn)
1160 for (hi=1;hi<=hcnt;++hi) print tolower(hashes[hi]);
1162 END {for (idx=1;idx<ARGC;++idx) process(ARGV[idx])}
1163 ' '{}' '+' 2>/dev/null || :
1167 # get_worktrees_friends
1168 # single argument is a (possibly relative) path to a "worktrees" subdir
1169 # if omitted it defaults to "worktrees"
1170 # any "friends" found in there are output to stdout
1171 get_worktrees_friends() {
1172 if [ -d "${1:-worktrees}" ]; then
1173 find -L "${1:-worktrees}" -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1174 while read -r _lwth; do
1175 get_detached_head "$_lwth"
1176 get_detached_friends "${_lwth%HEAD}"
1177 get_index_tree "${_lwth%HEAD}index"
1178 done
1182 # compute_extra_reachables
1183 # create lines suitable for a packed-refs file mentioning all the
1184 # other refs we might like to keep.
1185 # the current directory MUST be set to the repository's --git-dir
1186 # the following are included:
1187 # * refs mentioned in repack/packed-refs.extra (if it exists)
1188 # * refs mentioned in reflogs/... files
1189 # * tree(s) created from index file(s)
1190 # * detached linked working tree heads
1191 # Resulting objects are tested for existence and uniqified then output
1192 # one per line under a refs/z* namespace
1193 compute_extra_reachables() {
1195 if [ -s repack/packed-refs.extra ]; then
1196 LC_ALL=C sed <repack/packed-refs.extra -n \
1197 -e 's/^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p' \
1198 -e 's/^\^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p'
1200 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1201 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1202 LC_ALL=C awk '{print $2; print $3}'
1203 get_detached_friends .
1204 ! [ -f index ] || get_index_tree index
1205 get_worktrees_friends
1207 is_git_dir private &&
1208 [ "$(cd objects && pwd -P)" = "$(cd private/objects && pwd -P)" ] &&
1209 [ "$(cd refs && pwd -P)" != "$(cd private/refs && pwd -P)" ]
1210 then
1211 git --git-dir=private show-ref --head --hash 2>/dev/null || :
1212 get_detached_friends private
1213 ! [ -f private/index ] || get_index_tree private/index
1214 get_worktrees_friends private/worktrees
1216 } | LC_ALL=C sort -u |
1217 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1218 LC_ALL=C awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1222 ## main gc logic
1225 # Everything else is more efficient if we do this first
1226 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
1227 git pack-refs --all --prune
1228 [ -e packed-refs ] || >>packed-refs # should never happen...
1230 # If we have a logs directory or a worktrees directory expire the ref logs now
1231 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1232 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1234 make_repack_dir
1235 ! [ -e .gc_failed ] || exit 1
1236 rm -f .gc_in_progress # make sure
1237 touch .gc_in_progress # it's truly fresh
1238 rm -f bundles/* objects/pack/pack-*.bndl
1239 # These only exist for a brief time before the packs loose their _f suffix
1240 # "Push Pack Redux" does not apply to these since they were only ever present with _f
1241 rm -f objects/pack/pack-*_f.keep
1242 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1243 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1244 # and we have garbage collection forced, there's just the barest, almost negligible,
1245 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1246 # should not be removing _r .keep files. None of the normal Girocco processing can
1247 # cause this. The second run of this script would have to use the force gc option
1248 # for it to even be possible in the first place. What's much more likely is that
1249 # the initial run of this script was somehow interrupted in the middle before it
1250 # could get rid of the _r .keep file itself in which case it's better to get rid of
1251 # it now to avoid keeping something around that would perturb our nice and neat gc
1252 rm -f objects/pack/pack-*_r.keep
1253 # We will add .keep files for _u and _l packs if and when we run phase III
1254 # Otherwise they need to not have any .keep files during phases I and II
1255 rm -f objects/pack/pack-*_[ul].keep
1257 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1258 # activity will be able to "freshen" the pack containing a pre-existing object
1259 # that's being written. This really should not be necessary as the pre-receive
1260 # hook should make sure this takes place for any incoming pushes.
1261 # However, do it here anyway just in case.
1262 make_packs_ugw objects/pack
1264 # This is only effective with Git v2.3.5 and later and it will only matter when
1265 # we are using one of the "internal_rev_list" modes of pack-objects
1266 # (the combine-packs.sh script never uses any of those modes)
1267 # The "git repack" and "git prune" commands always set this internally themselves
1268 # It makes no difference if there's no repository corruption
1269 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1271 # All of the options we might want to use with pack-objects were supported
1272 # at some point prior to Git version v1.6.6 which is the minimum version that
1273 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1274 # are "boiler plate" options we always want to use so we bundle them up here.
1275 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1276 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1277 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1278 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1279 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1280 # This is not a free check as it matches all refs against refs/tags/ then
1281 # peels all the annotated tags and checks for inclusion. The situation in
1282 # which it would add a tag that was not already included by a reachability
1283 # trace that included tag starting points can only occur if a new tag gets
1284 # pushed during gc pointing to something that would have been packed anyway.
1285 # But, it could happen and, really, compared to gc as a whole it's not that
1286 # expensive to perform (provided we do not get an unconnected pack).
1287 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1288 pkopt="$pkopt ${quiet:---progress} $packopts"
1290 # The git pack-objects command only supports bitmaps if all objects are being
1291 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1292 # Additionally, while packing, if any encountered reachable objects are
1293 # determined to be "not wanted" then no bitmap index will be written anyway.
1294 # While it is theoretically possible that a project with a non-empty alternates
1295 # file ends up packing all objects (because it does not actually use any of the
1296 # objects found in the alternates), it's very unlikely. And, in the unlikely
1297 # event that did occur, clients would see a message about only using one bitmap
1298 # because Git can only use one bitmap at a time and at least one of the
1299 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1300 # alternates file, we disable writing bitmaps which avoids the warning and any
1301 # possibility of a client warning as well. Also if we are running anything
1302 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1303 # we also always disable bitmap writing.
1304 wbmopt=
1305 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1306 # More recent versions of pack-objects have optimizations when not using the
1307 # --local option. If we do not have any alternates it's a pointless option.
1308 # If we do have alternates we need to skip writing a bitmap and we cannot
1309 # have a bundle since it must contain all objects.
1310 if [ -n "$isfork" ]; then
1311 lclopt="--local"
1312 wbmopt=
1313 makebndl=
1314 else
1315 lclopt=
1316 makebndl=1
1320 ## Phase I
1323 wbmstr=
1324 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1325 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1327 gotforks=
1328 ! has_forks_with_alternates "$proj" || gotforks=1
1330 # To avoid "Push Pack Redux" (see docs/technical/gc.txt), after collecting the
1331 # initial preexisting non-keep pack list, we rename them so that an incoming push
1332 # pack cannot possibly experience a pack name collision. Git does not require
1333 # use of the "default" pack names, simply that the proper extensions are used.
1334 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1335 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1336 # down into forks and it will have an "_u" inserted just before its extension.
1337 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1338 oldpacks=
1339 for oldpack in $packlist; do
1340 oldpack="${oldpack%.pack}"
1341 [ -f "objects/pack/$oldpack.pack" ] || {
1342 echo >&2 "[$proj] unable to list old pack files"
1343 exit 1
1345 case "$oldpack" in pre-auto-gc-[12])
1346 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1347 continue
1348 esac
1349 oldpackhex="${oldpack#pack-}"
1350 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1351 # names not exclusively hexadecimal do not need renaming
1352 case "$oldpack" in
1353 pack-$octet20*_l)
1354 # _l packs are treated like still-unpacked loose objects
1355 continue;;
1356 *_f)
1357 # _f packs can only be left over from a previously interrupted gc;
1358 # they need to be renamed to _r now so they're not confused with
1359 # any freshly generated "final" packs (and we already removed
1360 # any pre-existing *_f.keep files so we're good to go)
1363 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1364 continue;;
1365 esac
1367 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack%_f}_r" || {
1368 echo >&2 "[$proj] unable to rename old pack files"
1369 exit 1
1371 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1372 # in progress at this moment and we need to .keep the renamed pack,
1373 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1374 # In either case we're okay because if it's just finished then all ref
1375 # changes have already been made so we don't need a .keep and we will
1376 # see the ref changes and grab all the objects via a reachability trace.
1377 # If it hasn't started yet that's okay because we're done moving that
1378 # name so a complete pack will appear under the old name that we'll
1379 # leave alone.
1380 if [ -f "objects/pack/$oldpack.keep" ]; then
1381 echo "Push Pack Redux" >"objects/pack/${oldpack%_f}_r.keep"
1382 else
1383 oldpacks="${oldpacks:+$oldpacks }${oldpack%_f}_r"
1385 done
1387 # We wish to keep deltas from our last full pack so if we're not redeltaing
1388 # then make sure the .pack associated with the .bitmap has a newer mod time
1389 # (If there is no .bitmap then touch the pack with the most objects instead.)
1390 if [ -z "$newdeltas" ]; then
1391 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1392 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1393 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1394 sleep 1
1395 touch -c "$bmpack" 2>/dev/null || :
1396 # We must touch .gc_in_progress here to avoid $bmpack looking
1397 # like it's been "freshened" when redundant packs are removed
1398 # It's okay if they have the same mod time, but POSIX does not
1399 # guarantee an ordering for the "touching" that occurs which is
1400 # why this must be a separate command but needs no "sleep 1"
1401 touch .gc_in_progress
1405 # Now we need to make sure that any "freshening" that takes place will actually
1406 # result in a "newer" modification time than the .gc_in_progress file now has
1407 sleep 1
1409 # We run git pack-objects from the repack subdirectory so we can force
1410 # optimized packs to be generated even for repositories that do not have any
1411 # tagged commits
1412 packs="$(git --git-dir=repack pack-objects </dev/null \
1413 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1414 vcnt packcnt $packs
1415 [ $packcnt -eq 1 ] || makebndl=
1418 ## Phase II
1421 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1423 # Add the "supplementary" refs
1424 compute_extra_reachables >>repack/packed-refs
1426 # Subtract the primary refs
1427 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1428 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1430 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1431 # However, if there is a "logs" subdirectory we need to use --reflog
1432 # We do add it, just in case, if the linked working trees dir is present
1433 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1434 # if it properly includes linked working tree index files or not. The
1435 # above compute_extra_reachables has already included all index trees (thereby
1436 # providing proper --indexed-objects support for all Git versions) making the
1437 # option completely unnecessary.
1438 rflopt=
1439 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1440 spacks="$(git --git-dir=repack pack-objects </dev/null \
1441 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1444 ## Phase III
1447 # There's nothing to do for Phase III unless we have forks that refer to our
1448 # project from their alternates file
1449 hlpacks=
1450 upacks=
1451 if [ -n "$gotforks" ]; then
1453 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1455 # If we are a fork, any pre-existing _u packs need to have a .keep
1456 # for this phase and be added to the hlpacks list otherwise (we are
1457 # not a fork) pre-existing _u packs are anomalies to be treated like
1458 # regular non-_u packs
1459 if [ -n "$isfork" ]; then
1460 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_[ul].pack" -print); do
1461 upack="${upack%.pack}"
1462 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1463 case "$upack" in *_l);;*)
1464 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1465 esac
1466 done
1468 # Using either --no-reuse-delta or --no-reuse-object together with the
1469 # --keep-unreachable option is a very, very, very bad idea when good
1470 # packs are the desired outcome. If newdeltas are being generated
1471 # then we pack to a temp name, and use combine-packs.sh to get a better
1472 # pack as the result to avoid making a bad --keep-unreachable pack
1473 pfx=
1474 [ -z "$newdeltas" ] || pfx="ku"
1475 upacks="$(git --git-dir=repack pack-objects </dev/null \
1476 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1477 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1478 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1479 oldupacks="$upacks"
1480 upacks="$(
1481 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1482 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1483 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1484 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1486 for upack in $upacks; do
1487 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1488 done
1489 rm -f objects/pack/pack-*_[ul].keep
1490 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1491 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1493 # We have to update the lastparentgc time in the child forks even if they do not get any
1494 # new "unreachable packs" because they need to run gc just in case the parent now has some
1495 # objects that used to only be in the child so they can be removed from the child.
1496 # For example, a "patch" might be developed first in a fork and then later accepted into
1497 # the parent in which case the objects making up the patch in the child fork are now
1498 # redundant (since they're now in the parent as well) and need to be removed from the
1499 # child fork which can only happen if the child fork runs gc.
1500 lastparentgc="$(date "$datefmt")"
1502 # It is enough to copy objects just one level down and get_repo_list
1503 # takes a regular expression (which is automatically prefixed with '^')
1504 # so we can easily match forks exactly one level down from this project
1505 forkdir="$proj"
1506 get_repo_list "$forkdir/[^/:][^/:]*:" |
1507 while read fork; do
1508 # Ignore forks that do not exist or are symbolic links
1509 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1510 continue
1511 # Or have an empty alternates file
1512 ! is_empty_alternates_file "$cfg_reporoot/$fork.git/objects/info/alternates" ||
1513 continue
1514 runupdate=
1515 # Match hlpacks in parent project if any
1516 if [ -n "$hlpacks" ]; then
1517 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1518 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1519 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1520 '"$cfg_reporoot/$fork.git/objects/pack/"'
1521 runupdate=1
1523 # Match upacks in repack/alt area if any
1524 if [ -n "$upacks" ]; then
1525 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1526 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1527 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1528 '"$cfg_reporoot/$fork.git/objects/pack/"'
1529 runupdate=1
1531 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1532 # Trigger a mini gc in the fork if it now has too many packs
1533 packs="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1534 if [ -n "$packs" ] && [ "$packs" -ge 20 ]; then
1535 >"$cfg_reporoot/$fork.git/.needsgc"
1538 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1539 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1540 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1541 done
1544 # Now move any primary/supplementary packs back into objects/pack
1545 # then drop any "unfreshened" redundant packs and clear repack/alt
1547 # First make sure the primary pack(s) have the most recent mod time
1548 if [ -n "$packs" ]; then
1549 [ -z "$spacks" ] || sleep 1
1550 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1553 # Move the packs into place but with a _f suffix and a .keep file for now
1554 for pack in $packs $spacks; do
1555 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-${pack}_f"
1556 [ -e "objects/pack/pack-${pack}_f.keep" ] ||
1557 echo "final" >"objects/pack/pack-${pack}_f.keep"
1558 done
1560 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1561 # with its .bitmap) and then got "freshened" causing us to not remove it
1562 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1563 # This can produce ugly warnings we don't want and possibly get the wrong
1564 # bitmap used since only one .bitmap file can ever be used by Git.
1565 # If this has happened, the .bitmap we want to discard will always have
1566 # an _r suffix so we can just zap any such now since it will leave the pack.
1567 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1569 # Remove the redundant packs that have not since been "freshened"
1570 # This does not completely eliminate the race condition window (Girocco's own
1571 # activites -- gc/fetch/receive are immune to the race) but it substantially
1572 # shrinks it down to just the time after the find but before the following rm
1573 >repack/oldpacks
1574 [ -z "$oldpacks" ] ||
1575 printf 'objects/pack/%s.pack\n' $oldpacks |
1576 LC_ALL=C sort >repack/oldpacks
1577 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1578 LC_ALL=C sort >repack/freshened
1579 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1580 [ -z "$deadpacks" ] ||
1581 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1583 # No need for this anymore
1584 rm -rf repack/alt objects/pack/repack
1585 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1588 ## Phase IV
1591 progress "~ [$proj] running gc prune-packed"
1593 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1594 # present while running prune-packed. We try to guarantee that any loose object
1595 # (or any object present in a pack with an _l suffix which was created by mini gc)
1596 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1597 # (not withstanding administrator interference to force earlier gc to occur).
1598 # If we were to include the redundant/keep-unreachable pack(s) when running
1599 # prune-packed and a loose unreachable object happened to be duplicated in one
1600 # of them we would end up removing it too soon and void our guarantee.
1601 git prune-packed $quiet
1603 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1605 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1606 # we MUST NOT use it for these reasons:
1607 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1608 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1609 # 3) We don't require anything more than Git v1.6.6
1610 # The only way we could see any _o pack files at this point is if one got
1611 # "freshened" while we were running gc. If that happens then it gets to live on
1612 # until the next full gc and we need to include it in the loose repack here.
1613 lpacks="$(list_packs --exclude-no-idx --exclude-no-sfx _l --exclude-no-sfx _o --quiet objects/pack |
1614 run_combine_packs --replace --names --loose --weak-naming --non-empty --honor-pack-keep \
1615 --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1617 if [ -n "$lpacks" ]; then
1618 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1619 if [ -n "$packs" ]; then
1620 sleep 1
1621 printf 'objects/pack/pack-%s_f.pack\n' $packs | xargs touch -c 2>/dev/null || :
1623 # We need to identify these packs later so we don't combine_packs them
1624 for objpack in $lpacks; do
1625 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1626 done
1629 # Polish up the final packs now
1630 rm -f objects/pack/pack-*_f.keep
1631 for pack in $packs $spacks; do
1632 rename_pack "objects/pack/pack-${pack}_f" "objects/pack/pack-$pack"
1633 done
1635 if [ -n "$lpacks" ]; then
1636 # Finally zap the corresponding loose objects
1637 progress "~ [$proj] running packed loose objects gc prune-packed"
1638 git prune-packed $quiet
1641 ! [ -e .gc_failed ] || exit 1
1642 # These, if they exist, are now meaningless and need to be removed
1643 rm -f gfi-packs .needsgc .needspack .needspackgc
1645 # Make sure this stays up to date
1646 git update-server-info
1648 # We must make loose objects group writable so that they
1649 # can be freshened by other pushers. Technically we need only do this for
1650 # push projects but to enable mirror projects to be more easily converted to
1651 # push projects, we go ahead and do it for all projects.
1652 # By the time we get here we really shouldn't have any of these, but just in case.
1653 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1655 # darcs mirrors have a xxx.log file that will grow endlessly
1656 # if this is a mirror and the file exists, shorten it to 10000 lines
1657 # also take this opportunity to optimize the darcs repo
1658 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1659 url="$(config_get baseurl)" || :
1660 case "$url" in darcs://* | darcs+http://* | darcs+https://*)
1661 if [ -n "$cfg_mirror_darcs" ]; then
1662 url="${url%/}"
1663 basedarcs="$(basename "${url#darcs*:/}")"
1664 if [ -f "$basedarcs.log" ]; then
1665 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1666 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1668 if [ -d "$basedarcs.darcs" ]; then
1670 cd "$basedarcs.darcs"
1671 # without show_progress suppress non-error output
1672 [ "${show_progress:-0}" != "0" ] || exec >/dev/null
1673 # Note that this does not optimize _darcs/inventories/ :(
1674 darcs optimize || :
1678 esac
1681 # Create a matching .bndl header file for the all-in-one pack we just created
1682 # but only if we're not a fork (otherwise the bundle would not be complete)
1683 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1684 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1685 # There should only be one pack in $packs but do some checking...
1686 # The one we just created will have a .idx and will NOT have a .keep
1687 progress "~ [$proj] creating downloadable bundle header"
1688 pkbase=
1689 pkhead=
1690 IFS= read -r curhead <repack/HEAD.orig || :
1692 [ -s "objects/pack/pack-$packs.pack" ] &&
1693 [ -s "objects/pack/pack-$packs.idx" ] &&
1694 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1695 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1696 "$PWD/repack/packed-refs.orig" "$curhead")"
1697 then
1698 pkbase="objects/pack/pack-$packs"
1700 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1702 symref=
1703 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1704 symref="${curhead#ref:}"
1705 symref="${symref# }"
1706 esac
1707 bndlurl=
1708 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1709 echo "# v2 git bundle"
1710 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1711 if [ -n "$symref" ]; then
1712 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1713 else
1714 if [ -n "$bndlurl" ]; then
1715 printf "$pkhead HEAD\0%s\n" "${bndlurl# }"
1716 else
1717 echo "$pkhead HEAD"
1720 echo ""
1721 } >"$pkbase.bndl"
1722 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1723 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1724 if [ -n "$bndletag" ]; then
1725 case "$bndlsha" in $octet20*)
1726 bndlshatrailer="${bndlsha#????????}"
1727 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1728 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1729 [ -d bundles ] || mkdir bundles
1730 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1731 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1732 ln -s -f -n "$bndlname" bundles/latest
1733 esac
1738 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1739 eval "reposizek=$(( $(
1740 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1741 LC_ALL=C awk '{print $1}') |
1742 LC_ALL=C sed -e 's/ / + /g') ))"
1743 config_set_raw girocco.reposizek "${reposizek:-0}"
1745 # Now we're finally done with this
1746 rm -rf repack
1748 # We didn't used to do anything about rerere or worktrees but we're
1749 # trying to make nice with linked working trees these days :)
1750 # Maybe even non-bare repositories too, but *shush* about those ;)
1751 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1752 # The value "3.months.ago" is hard-coded into gc.c rather than
1753 # having the default be in worktree.c so we must provide it if
1754 # we get nothing out of the gc.worktreePruneExpire config item
1755 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1756 # however we just always use the newer name no matter what Git version
1757 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1758 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1760 # git rerere does it right and handles its own default/config'd expiration values
1761 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1763 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1764 # and the next future gc could be incorrectly skipped if we used the current
1765 # timestamp here instead
1766 config_set lastgc "$gcstart"
1767 rm -f "$lockf"
1769 progress "- [$proj] garbage check ($(date))"