jailsetup.sh: ensure safe.directory=* when running git
[girocco.git] / jobd / gc.sh
blobf6fccf21658a6f3bec63a472c5b04be27f78f689
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 umask 002
25 [ "$cfg_permission_control" != "Hooks" ] || umask 000
26 clean_git_env
28 # The pre-receive script creates one ref log file per push but we want them to
29 # be coalesced into one ref log file per day. We are guaranteed that any files
30 # we find to coalesce are NOT currently being written to since they are always
31 # written first as temporary files and then moved into place. We attempt to
32 # transfer the most recent modification time to the coalesced log file which
33 # would step on its mod time if it were being written to directly, but if we
34 # find per-process ref log files then it must be a push project and the only
35 # thing that would write directly to the main per-day log file would be a
36 # mirror project so there's actually no conflict.
37 # Also, if the clock is wonky (or was futzed with) we may have both YYYYMMDD
38 # and YYYYMMDD.gz present in which case combine them into YYYYMMDD
39 coalesce_reflogs() {
40 [ -d reflogs ] || return 0
41 rm -f .gc_failed
42 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 |
43 while read -r rname; do
44 if [ -e "$rname.gz" ]; then
45 if [ -s "$rname" ]; then
46 # Presumably the .gz file must have been created before the non-gz
47 # file since it had to be uncompressed at some point therefore
48 # we need to append the non-gz contents to it but keep the non-gz
49 # contents timestamp so we rename to YYYYMMDD_ which will sort first
50 # and be picked up in the next step if we are interrupted in the middle.
51 # If a YYYYMMDD_ file already exists we append to it and transfer the
52 # timestamp. Finally we transfer the YYYYMMDD_ timestamp to the result
53 # and remove the YYYYMMDD_ temporary file leaving the result uncompressed.
54 if [ -e "${rname}_" ]; then
55 cat "$rname" >>"${rname}_"
56 touch -r "$rname" "${rname}_"
57 rm -f "$rname"
58 ! [ -e "$rname" ]
59 else
60 mv "$rname" "${rname}_"
62 gzip -d "$rname.gz" </dev/null
63 [ -e "$rname" ] && ! [ -e "$rname.gz" ]
64 cat "${rname}_" >>"$rname"
65 touch -r "${rname}_" "$rname"
66 rm -f "${rname}_"
67 else
68 # Just remove the empty file to resolve the problem
69 rm -f "$rname"
72 done
73 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 |
74 while read -r rname; do
75 logname="${rname%%_*}"
76 # If someone's been futzing with the date, the file we want to
77 # append to could already have been compressed, so we just uncompress
78 # it here. The previous block guarantees we do not have both a compressed
79 # and uncompressed version present at the same time.
80 if [ -e "$logname.gz" ]; then
81 gzip -d "$logname.gz" </dev/null
82 [ -e "$logname" ] && ! [ -e "$logname.gz" ]
84 cat "$rname" >>"$logname"
85 touch -r "$rname" "$logname"
86 rm -f "$rname"
87 if [ -e "$rname" ]; then
88 >.gc_failed
89 echo "! [$proj] failed to remove $rname" >&2
90 exit 1 # will only exit subshell created by "|"
92 done
93 ! [ -e .gc_failed ]
96 # Remove any files in reflogs that are older than $cfg_reflogs_lifetime days
97 prune_reflogs() {
98 [ -d reflogs ] || return 0
99 exp="$(( ${cfg_reflogs_lifetime:-1} * 1440 ))"
100 [ $exp -gt 0 ] || exp=1440
101 [ $exp -le 43200 ] || exp=43200
102 find -L reflogs -maxdepth 1 -type f -mmin "+$exp" -exec rm -f '{}' + || :
105 # Compact any reflogs that are not today's UTC date unless a .gz version exists
106 compact_reflogs() {
107 [ -d reflogs ] || return 0
108 _td="reflogs/$(TZ=UTC date '+%Y%m%d')"
109 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 |
110 while read -r rname; do
111 [ "$rname" != "$_td" ] || continue
112 ! [ -e "$rname.gz" ] || continue
113 gzip -9 "$rname" </dev/null
114 done
117 # return true if there's more than two objects/pack-<sha>.pack files or
118 # ANY sha-1 files in objects or
119 # there's one or two packs but at least one does not have a normal pack name or
120 # there's at least one pack but not any refs
121 is_dirty() {
122 _packs="$(find -L objects/pack -name "pre-auto-gc-[12].pack" -prune -o -name "*.pack" -type f -print 2>/dev/null | head -n 3)"
123 v_cnt _packscnt $_packs
124 if [ $_packscnt -gt 2 ]; then
125 return 0
127 if [ $_packscnt -gt 0 ]; then
128 for _pack in $_packs; do
129 _pack="${_pack%.pack}"
130 _pack="${_pack#objects/pack/}"
131 case "$_pack" in
132 pack-*)
133 _pack="${_pack#pack-}"
134 if [ "${#_pack}" -lt 40 ] || [ "${_pack#*[!0-9a-fA-F]}" != "$_pack" ]; then
135 # name not exclusively 40 or more hexadecimal digits makes it dirty
136 return 0
140 # abnormal name makes it dirty
141 return 0
143 esac
144 done
146 _objs=$(find -L objects/$octet -name "$octet19*" -type f -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
147 [ $_objs -eq 0 ] || return 0
148 [ $_packscnt -gt 0 ] || return 1
149 # we do this check last because it's potentially the most expensive;
150 # at this point we know we do not have any loose objects, but we do
151 # have one or two packs that are named "normally"; empty refs => dirty
152 is_empty_refs_dir
155 # combine the input pack(s) into a new pack (or possibly packs if packSizeLimit set)
156 # input pack names are read from standard input one per line delimited by the first
157 # ':', ' ' or '\n' character on the line (which allows gfi-packs to be read directly)
158 # all arguments, if any, are passed to pack-objects as additional options
159 # returns non-zero on failure AND creates .gc_failed in that case
160 combine_packs() {
161 rm -f .gc_failed
162 combine_packs_std "$@" || {
163 >.gc_failed
164 return 1
166 return 0
169 # if the current directory is_gfi_mirror then repack all packs listed in gfi-packs
170 repack_gfi_packs() {
171 [ -n "$gfi_mirror" ] || return 0
172 [ -d objects/pack ] || { rm -f gfi-packs; return 0; }
173 progress "~ [$proj] redeltifying poor quality git fast-import packs"
174 combine_packs --ignore-missing --no-reuse-delta <gfi-packs
175 rm -f gfi-packs
176 return 0
179 # pack any existing loose objects into a new _l.pack file then run prune-packed
180 # note that prune-packed is NOT run beforehand -- the caller must do that if needed
181 # loose objects need not be part of complete commits/trees as --weak-naming is used
182 pack_loose_objects() {
183 _lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts)"
184 if [ -n "$_lpacks" ]; then
185 # We need to identify these packs later so we don't combine_packs them
186 for _objpack in $_lpacks; do
187 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
188 done
189 git prune-packed $quiet
193 # combine small packs into larger pack(s)
194 # we avoid any _[lo], keep, bndl or bitmap packs
195 # if the optional argument is non-empty even a single small pack will be redeltad
196 combine_small_packs() {
197 _didprogress=
198 _minsmallpacks=2
199 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
200 _minsmallpacks=1
202 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
203 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o --exclude-sfx _l"
204 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
205 while
206 _cnt="$(list_packs --count $_lpo)" || :
207 test "${_cnt:-0}" -ge $_minsmallpacks
209 [ -n "$_didprogress" ] || {
210 progress "~ [$proj] combining small packs into a single larger pack"
211 _didprogress=1
213 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
214 v_cnt _newc $_newp
215 # be paranoid and exit the loop if we haven't reduced the number of packs
216 [ $_newc -lt $_cnt ] || break
217 _minsmallpacks=2
218 done
219 return 0
222 # combine small _l packs into larger pack(s) using --weak-naming
223 # we avoid any non _l, keep, bndl or bitmap packs
224 # if the optional 2nd argument is non-empty even a single small pack will be redeltad
225 combine_small_loose_packs() {
226 _didprogress=
227 _minsmallpacks=2
228 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
229 _minsmallpacks=1
231 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
232 _lpo="$_lpo --exclude-no-sfx _l"
233 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
234 while
235 _cnt="$(list_packs --count $_lpo)" || :
236 test "${_cnt:-0}" -ge $_minsmallpacks
238 [ -n "$_didprogress" ] || {
239 progress "~ [$proj] combining small loose packs into a single larger pack"
240 _didprogress=1
242 _newp="$(list_packs $_lpo | combine_packs --names --weak-naming $noreusedeltaopt)"
243 # We need to identify these packs later so we don't combine_packs them
244 for _objpack in $_newp; do
245 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
246 done
247 v_cnt _newc $_newp
248 # be paranoid and exit the loop if we haven't reduced the number of packs
249 [ $_newc -lt $_cnt ] || break
250 _minsmallpacks=2
251 done
252 return 0
255 # Unfortunately, some fetch strategies (e.g. git-svn and non-smart HTTP) lack
256 # the ability to store newly fetched objects in a pack.
257 # However, the fetch code conveniently sets .needspack just before it fetches
258 # so that it's easy to find all the loose objects that have been fetched and
259 # combine them into a pack. The --no-reuse-delta option is meaningless here
260 # since everything to be packed is a loose object and therefore not a delta so
261 # deltification will always take place.
262 make_needs_pack() {
263 [ -f .needspack ] || return 0
264 rm -f .needspackgc
265 mv -f .needspack .needspackgc
266 progress "~ [$proj] combining fetched loose objects into a pack"
267 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .needspackgc -name "$octet19*" -print 2>/dev/null |
268 LC_ALL=C awk -F / '{print $2 $3}' |
269 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
270 # We used to fail gc here.
271 # Now, however, we just ignore the failure because we have
272 # another mechanism to handle loose objects and it's possible
273 # that the fetcher somehow brought in unconnected objects which
274 # would cause the above combine-packs to fail.
275 # By ignoring the failure and just removing the .needspack file
276 # the loose objects will be treated as "ordinary" loose objects
277 # and packed using the "--weak-naming" option which can handle
278 # broken connectivity.
279 # That's a better solution than just failing here or leaving
280 # .needspack behind to potentially continue to fail again and
281 # again.
282 _newp=
283 # combine-packs.sh will have output a nasty fatal message,
284 # ameliorate it with a follow up to say that all is okay
285 echo "gc: bad needs_pack connectivity, using --weak-naming: $proj" >&2
287 if [ -n "$_newp" ]; then
288 # remove the now-redundant loose objects -- this is always safe
289 # even during a concurrent push because a reprepare_packed_git
290 # will be triggered if an object that should be there is not
291 # found thereby finding it in the new pack instead
292 git prune-packed $quiet
294 rm -f .needspackgc
297 # HEADSHA="$(pack_is_complete /full/path/to/some.pack /full/path/to/packed-refs "$(cat HEAD)")"
298 pack_is_complete() {
299 # Must have a matching .idx file and a non-empty packed-refs file
300 [ -s "${1%.pack}.idx" ] || return 1
301 [ -s "$2" ] || return 1
302 _headsha=
303 case "$3" in
304 $octet20*)
305 _headsha="$3"
307 "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
308 _headmatch="${3#ref:}"
309 _headmatch="${_headmatch# }"
310 _headmatchpat="$(echo "$_headmatch" | LC_ALL=C sed -e 's/\([.$]\)/\\\1/g')"
311 _headsha="$(LC_ALL=C grep -e "^$octet20$hexdig* $_headmatchpat\$" <"$2" |
312 LC_ALL=C cut -d ' ' -f 1)"
313 case "$_headsha" in $octet20*) :;; *)
314 return 1
315 esac
318 # bad HEAD
319 return 1
320 esac
321 rm -rf pack_is_complete_test
322 mkdir pack_is_complete_test
323 mkdir pack_is_complete_test/refs
324 mkdir pack_is_complete_test/objects
325 mkdir pack_is_complete_test/objects/pack
326 echo "$_headsha" >pack_is_complete_test/HEAD
327 ln -s "$1" pack_is_complete_test/objects/pack/
328 ln -s "${1%.pack}.idx" pack_is_complete_test/objects/pack/
329 ln -s "$2" pack_is_complete_test/packed-refs
330 _count="$(git --git-dir=pack_is_complete_test rev-list --count --all 2>/dev/null)" || :
331 rm -rf pack_is_complete_test
332 [ -n "$_count" ] || return 1
333 [ "$_count" -gt 0 ] 2>/dev/null || return 1
334 echo "$_headsha"
337 # write the hexadecimal sha256 hash of stdin plus a trailing newline to stdout
338 sig_hash_stdin() {
339 "$cfg_basedir/bin/ltsha256"
342 # Compute a "signature" for the refs in the specified (default .) repository.
343 # Instead of passing --head to show-ref, the actual contents of HEAD are used
344 # to capture changes in HEAD's symbolic-ref value that would otherwise be missed.
345 # $1 => variable name to store result hash in
346 # $2 => --git-dir to use, defaults to "."
347 v_compute_refs_sighash() {
348 eval "$1="'"$({ cat "${2:-.}/HEAD"; git --git-dir="${2:-.}" show-ref; } |
349 sig_hash_stdin)"'
352 # On return a "$lockf" will have been created that must be removed when gc is done
353 lock_gc() {
354 v_lock_gc _lockresult || {
355 echo >&2 "[$proj] $_lockresult"
356 exit 1
358 lockf="$_lockresult"
361 # Create a repack subdirectory such that running repack in it will pack the
362 # same things that a pack in the normal directory would except that the pack
363 # is guaranteed to be generated in an optimized order by adding a suitable
364 # synthesized ref in the refs/tags namespace (yes, pack-objects.c really does
365 # behave differently depending on the contents of the refs/tags namespace).
366 # Before calling this, pack-refs --all MUST be performed or the wrong pack
367 # will end up being made.
369 # If a ref deletion is pushed after making the repack subdir but before the
370 # the actual repack, the discarded objects will be packed -- no big deal,
371 # they'll get discarded the next time gc runs.
373 # If a fast-forward ref update is pushed after making the repack subdir but
374 # before the actual repack, it will be picked up and the new objects packed
375 # (subject to the normal git repack race about picking such updates up).
377 # If a non-fast-forward ref update is pushed after making the repack subdir but
378 # before the actual repack, it will be picked up like a fast-forward update but
379 # the discarded objects will be included like a ref deletion (until the next
380 # scheduled gc takes place).
382 # We retain a copy of the original packed-refs file as repack/packed-refs.orig
383 # If ref deletions come in while we're repacking, the original packed-refs
384 # file will be modified, but we'll still pack the deleted ref(s).
385 # If the packed-refs.orig file is used to create the bundle header we avoid
386 # a situation where the bundle contains a ref state that never actually
387 # existed in reality (for example a new branch is pushed and then an old
388 # branch deleted afterwards -- the deletion would show up in the bundle
389 # because it will cause the original packed-refs file to be re-written, but
390 # the new branch creation will not unless we do another pack-refs which might
391 # lead to having in incomplete bundle). Therefore we want to keep a copy of
392 # the original packed-refs file around. We do the same thing for HEAD.
394 # It's possible that the "objects" subdirectory is a symbolic link.
395 # Git does support this. However, during the repacking process, new packs
396 # will be created in repack/alt/pack and then moved into objects/pack.
397 # In order for this to work seemlessly, they must both be on the same
398 # filesystem. But when objects (or even objects/pack) is a symbolic link they
399 # might not be. For this reason a "repack" subdirectory is created under
400 # objects/pack and the repack/alt/pack directory symbolicly linked to it.
402 # Git allows not just HEAD to be a symbolic-ref, but any ref anywhere in the
403 # refs namespace. We are concerned about ref name collisions and getting the
404 # right tag set to get an optimal pack. We can safely duplicate the ref space
405 # under refs/heads, refs/notes and refs/remotes without any risk of unwanted
406 # collisions and this will likely make over 99%+ of all symbolic refs found
407 # in the wild work properly. Girocco itself never creates any symbolic refs
408 # inside the refs namespace; this is a nod to simultaneously using a Girocco
409 # repository for other purposes.
410 make_repack_dir() {
411 ! [ -d repack ] || rm -rf repack
412 ! [ -d repack ] || { echo >&2 "[$proj] cannot remove repack subdirectory"; exit 1; }
413 [ -d objects/pack ] || mkdir -p objects/pack
414 ! [ -d objects/pack/repack ] || rm -rf objects/pack/repack
415 ! [ -d objects/pack/repack ] || { echo >&2 "[$proj] cannot remove objects/pack/repack subdirectory"; exit 1; }
416 mkdir repack repack/refs repack/alt objects/pack/repack
417 [ -d info ] || mkdir info
418 ln -s ../config repack/config
419 ln -s ../info repack/info
420 ln -s ../objects repack/objects
421 ln -s "$PWD/objects/pack/repack" repack/alt/pack
422 ! [ -d logs ] || ln -s ../logs repack/logs
423 ! [ -d worktrees ] || ln -s ../worktrees repack/worktrees
424 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
425 cat HEAD >repack/HEAD.orig
426 cat packed-refs >repack/packed-refs.orig
427 ln -s packed-refs.orig repack/packed-refs
428 cp repack/HEAD.orig repack/HEAD
429 v_compute_refs_sighash _rsig repack
430 rm repack/packed-refs repack/HEAD
431 ln -s ../../refs repack/refs/refs
432 echo "$_rsig" >repack/packed-refs.sighash
433 >repack/packed-refs.extra
434 _xtralines=0
435 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
436 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
437 exit 1
439 if [ "${cfg_fetch_stash_refs:-0}" = "0" ]; then
440 # migrate any refs/stash or refs/tgstash lines to repack/packed-refs.extra
441 <repack/packed-refs.orig LC_ALL=C awk -v xtra="repack/packed-refs.extra" '
442 BEGIN { peeling = 0 }
443 NR == 1 && /^#/ { print; next; }
444 peeling && /^\^/ { print >>xtra; next; }
445 /^[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]+ refs\/(stash|tgstash)(\/|$)/ {
446 peeling = 1
447 print >>xtra
448 next
450 { peeling = 0; print; }
451 ' >repack/packed-refs.new
452 _xtralines="$(( $(LC_ALL=C wc -l <repack/packed-refs.extra) + 0 ))"
453 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs.new) + 0 ))"
454 if [ "$(( $_newlines + $_xtralines ))" -ne "$_lines" ]; then
455 echo >&2 "[$proj] error: make_repack_dir failed packed-refs.extra line count sanity check"
456 exit 1
458 mv -f repack/packed-refs.new repack/packed-refs.orig
459 _lines="$_newlines"
461 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
462 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
463 nohead=
464 headref="$(git rev-parse --verify --quiet HEAD)" || :
465 if [ -n "$headref" ]; then
466 echo "$headref refs/!=/HEAD" >>repack/packed-refs
467 echo "$headref refs/heads/!" >>repack/packed-refs
468 nohead='\, refs/heads/!$,d; '
469 _lines=$(( $_lines + 2 ))
471 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
472 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
473 exit 1
475 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
476 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
477 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
478 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
479 exit 1
481 _lines="$_newlines"
482 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
483 if [ -n "$optref" ]; then
484 echo "$optref refs/tags/!" >>repack/packed-refs
485 _lines=$(( $_lines + 1 ))
486 echo "$optref" >repack/HEAD
487 else
488 cat HEAD >repack/HEAD
490 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
491 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
492 exit 1
496 # Remove any crud that's been left behind by interrupted operations
497 # that did not clean up after themselves
498 remove_crud() {
499 # Remove any existing FETCH_HEAD
500 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
501 # receiving pushes (those never create a FETCH_HEAD).
502 # And if we're fetching because we're a mirror, we know we're not fetching right
503 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
504 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
505 # there were a lot of refs.
506 rm -f FETCH_HEAD
508 # Remove any stale ref locks
509 clear_stale_ref_locks
511 # remove any existing pack_is_complete_test or repack subdirectories
512 # If either exists when this function is called it's crud
513 rm -rf pack_is_complete_test repack objects/pack/repack
515 # Remove any stale pack remnants that are more than an hour old.
516 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
517 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
518 # pack-<sha1>.idx files without their corresponding .pack files are worthless
519 # and just waste space. Normally there shouldn't be any remnants but actually
520 # this can happen when things are interrupted at just the wrong time.
521 # Note that the objects/pack directory is created by git init and should
522 # always exist.
523 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
524 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
525 while read packsha; do
526 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
527 rm -f "objects/pack/pack-$packsha".?*
528 done
530 # Remove any stale tmp reflogs files that are more than one hour old.
531 # Since they are created only while the pre-receive hook is running and
532 # all it does is process a bunch of refs passed to it on standard input
533 # it's inconceivable that it would ever take as much as an hour to run.
534 if [ -d reflogs ]; then
535 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
538 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
539 # Really these files should only exist very briefly so there shouldn't be any
540 # but things happen that can end up leaving them behind.
541 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
543 # Remove any stale pack .keep files that are more than 12 hours old.
544 # We don't do anything to create any permanent pack .keep files, so they must
545 # be remnants from some failed push or something. Removing the .keep will
546 # allow the pack to be properly repacked.
547 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
549 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
550 # that are more than 12 hours old.
551 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
552 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
553 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
554 \) -exec rm -f '{}' + || :
556 # Remove any stale incoming-* object quarantine directories that are
557 # more than 12 hours old. These are new with Git >= 2.11.0.
558 # The update script uses its own incoming-* quarantine directories as well.
559 find -L . objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
560 -exec rm -rf '{}' + || :
562 # Remove any stale shallow_* files that are more than 12 hours old.
563 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
564 # requests a shallow clone. Also discard stale .refs-temp* and
565 # .refs-new* files at the same time.
566 find -L . -maxdepth 1 -type f -mmin +720 \( \
567 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
568 \) -exec rm -f '{}' + || :
570 # Remove any stale cmbnpcks-* dirs that are more than 12 hours old.
571 # These can be left behind by abnormal exits (e.g. power failure).
572 find -L . -maxdepth 1 -type d -mmin +720 -name "cmbnpcks-?*" \
573 -exec rm -rf '{}' + || :
575 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
576 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
577 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
579 # Remove any stale *.lock files in the htmlcache area that might have been left
580 # behind after an abnormal exit during an attempt to update a cached file and
581 # are more than 1 hour old.
582 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
584 # Remove any stale git-svn temp files that are more than 12 hours old.
585 # The git-svn process creates temp files with random 10 character names
586 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
587 # prefix, so we just have to kill any files with a 10-character name. We
588 # do this only for git-svn mirrors. All characters are chosen from
589 # [A-Za-z0-9_] so we can at least check that and fortunately the only
590 # collision is 'FETCH_HEAD' but that shouldn't matter.
591 # There may also be temp files with a Git_ prefix as well.
592 if [ -n "$svn_mirror" ]; then
593 _randchar='[A-Za-z0-9_]'
594 _randchar2="$_randchar$_randchar"
595 _randchar4="$_randchar2$_randchar2"
596 _randchar10="$_randchar4$_randchar4$_randchar2"
597 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
598 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
601 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
602 if [ -n "$gfi_mirror" ]; then
603 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
606 # Remove any stale core or *.core or core.* files that are more than 3 days old.
607 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
608 -exec rm -f '{}' + || :
612 ## Garbage Collection Types
614 ## There are two kinds of possible garbage collection (gc) operations:
616 ## 1. A normal, full gc
617 ## 2. A "mini" gc
619 ## If the full garbage collection interval has expired (or gc has never been
620 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
621 ## take place if the file .needsgc exists.
623 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
624 ## doing anything unless the right conditions are present so it's not a burden
625 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
626 ## the next opportunity.
628 ## See the docs/technical/gc.txt and docs/technical/gc-mini.txt files for more
629 ## of the gory details of how garbage collection is performed.
631 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
634 proj="${1%.git}"
635 shift
636 cd "$cfg_reporoot/$proj.git"
637 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
638 mirror_url="$(get_mirror_url)" || :
639 svn_mirror=
640 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
641 gfi_mirror=
642 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
643 gfi_mirror=1
646 # If git config --bool --get girocco.redelta is explicitly false then automatic
647 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
648 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
649 # gc only, for the final repack, deltas will always be recomputed.
650 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
651 # Setting this will hurt efficiency of the affected repository.
652 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
653 noreusedeltaopt="--no-reuse-delta"
654 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
655 alwaysredelta=
656 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
658 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
659 # to be compatible with the old and new gc.sh versions and avoid ugly argument
660 # duplication in process lists at the same time
661 # Any options found will override the "girocco.redelta" setting
662 recompress=
663 idx=$#
664 while [ $idx -gt 0 ]; do
665 idx=$(( $idx - 1 ))
666 opt="$1"
667 shift
668 case "$opt" in
669 -f|--no-reuse-delta)
670 alwaysredelta=1
671 continue
673 -F|--no-reuse-object)
674 alwaysredelta=1
675 recompress=1
676 continue
678 -?*)
681 printf >&2 '%s\n' "bad non-option argument: $opt"
682 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
683 exit 1
684 esac
685 [ -z "$opt" ] || set -- "$@" "$opt"
686 done
687 if [ -n "$alwaysredelta" ]; then
688 noreusedeltaopt="--no-reuse-delta"
689 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
692 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
693 trap 'exit 130' INT
694 trap 'exit 143' TERM
696 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
697 datefmt='+%a, %d %b %Y %T %z'
699 isminigc=
700 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
701 if [ -e .needsgc ]; then
702 isminigc=1
703 else
704 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
705 exit 0
708 if [ -e .nogc ]; then
709 progress "x [$proj] garbage check disabled"
710 exit 0
712 if ! [ -e .nofetch ] && [ -e .clone_in_progress ] && ! [ -e .clone_failed ]; then
713 progress "x [$proj] garbage check disabled (clone in progress)"
714 exit 0
716 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
717 # Eligible for a full gc but .delaygc is set so it would be skipped
718 # However .needsgc is also set so transform it into a mini instead
719 isminigc=1
720 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
723 # git_pack_refs_all_prune
724 # run `git pack-refs --all --prune` in the current directory
725 # if an is_git_dir "private" refs subdirectory exists,
726 # then run `git --git-dir=private pack-refs --all --prune` too
727 # (since mini gc uses this it has to be defined before that)
728 git_pack_refs_all_prune() {
729 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
730 git pack-refs --all --prune
731 ! is_git_dir private || git --git-dir=private pack-refs --all --prune
734 if [ -n "$isminigc" ]; then
735 # Perform a "mini" gc
736 # Note that .delaygc is ignored here as that's only intended for full gc
737 lock_gc
738 rm -f .allowgc .needsgc
739 rm -f objects/pack/pack-*_[rful].keep
740 remove_crud
741 coalesce_reflogs
742 prune_reflogs
743 compact_reflogs
744 maintain_auto_gc_hack
745 generate_auto_gc_update
746 miniactive=
747 if [ -f .needspack ]; then
748 miniactive=1
749 progress "+ [$proj] mini garbage check ($(date))"
750 make_needs_pack
752 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
753 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
754 if [ -z "$miniactive" ]; then
755 miniactive=1
756 progress "+ [$proj] mini garbage check ($(date))"
758 repack_gfi_packs
760 if lotsa_loose_objects; then
761 if [ -z "$miniactive" ]; then
762 miniactive=1
763 progress "+ [$proj] mini garbage check ($(date))"
765 pack_loose_objects
767 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
768 # don't actually process them yet
769 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
770 packcnt="$(list_packs --count $lpo objects/pack)" || :
771 if [ "${packcnt:-0}" -ge 10 ]; then
772 if [ -z "$miniactive" ]; then
773 miniactive=1
774 progress "+ [$proj] mini garbage check ($(date))"
776 # if we have at least 10 packs go ahead and pack all refs now too
777 git_pack_refs_all_prune
778 if [ -n "$gfi_mirror" ]; then
779 repack_gfi_packs
780 packcnt="$(list_packs --count $lpo objects/pack)" || :
782 # if repack_gfi_packs dropped the pack count to < 10 don't combine
783 if [ "${packcnt:-0}" -ge 10 ]; then
784 combine_small_packs
785 combine_small_loose_packs
786 packcnt="$(list_packs --count $lpo objects/pack)" || :
788 # if we still have more than 10 packs trigger a full gc
789 if [ "${packcnt:-0}" -ge 10 ]; then
790 # We shouldn't be in a .delaygc state at this point, but if
791 # we are then nuke it because we really need a full gc now
792 rm -f .delaygc
793 git config --unset gitweb.lastgc || :
794 rm -f "$lockf"
795 git update-server-info # just in case
796 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
797 exit 0
800 rm -f "$lockf"
801 if [ -n "$miniactive" ]; then
802 git update-server-info
803 progress "- [$proj] mini garbage check ($(date))"
804 else
805 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
807 exit 0
810 # Avoid unnecessary garbage collections:
811 # 1. If lastreceive is set and is older than lastgc
812 # -AND-
813 # 2. We are not a fork (is_empty_alternates_file) -OR- lastparentgc is older than lastgc
815 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
816 # If we are a fork and lastparentgc is NOT set we MUST run gc
818 # If the repo is dirty after removing any crud we MUST run gc
820 gcstart="$(date "$datefmt")"
821 skipgc=
822 isfork=
823 is_empty_alternates_file objects/info/alternates || isfork=1
824 lastparentgcsecs=
825 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
826 lastreceivesecs=
827 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
828 [ "${force_gc:-0}" = "0" ] &&
829 lastgcsecs="$(config_get_date_seconds lastgc)" &&
830 [ $lastreceivesecs -lt $lastgcsecs ]; then
831 # We've run gc since we last received, so maybe we can skip,
832 # check if not fork or fork and lastparentgc < lastgc
833 if [ -n "$isfork" ]; then
834 if [ -n "$lastparentgcsecs" ] &&
835 [ $lastparentgcsecs -lt $lastgcsecs ]; then
836 # We've run gc since our parent ran gc so we can skip
837 skipgc=1
839 else
840 # We don't have any alternates (we're not a forK) so we can skip
841 skipgc=1
845 # Now check the simple signatures if $skipgc and decline to skip if they do not match
847 if [ -n "$skipgc" ]; then
848 # while we cannot actually compute the current "repack" "signature"
849 # hash yet, if there is no previous sig => must run gc
850 rpksig="$(config_get girocco.gcsig.repack)" || :
851 [ -n "$rpksig" ] || skipgc=
853 if [ -n "$skipgc" ]; then
854 # make sure the "refs" "signature" hash exists before doing anything expensive
855 # no previous "refs" "signagure" => must run gc
856 rhash="$(config_get girocco.gcsig.refs)" || :
857 [ -n "$rhash" ] || skipgc=
859 if [ -n "$skipgc" ]; then
860 # check the "packs" "signature" first, no previous sig => must run gc
861 phash="$(config_get girocco.gcsig.packs)" || :
862 [ -n "$phash" ] || skipgc=
863 if [ -n "$skipgc" ]; then
864 # a previous packs sig is available, check for a match
865 _chksig="$(list_packs -C objects/pack --exclude-no-idx --quiet . |
866 LC_ALL=C sort | sig_hash_stdin)" || :
867 [ "$phash" = "$_chksig" ] || skipgc=
870 if [ -n "$skipgc" ]; then
871 # check the refs signature second
872 # a previous refs sig is available, check for a match
873 v_compute_refs_sighash _chksig
874 [ "$rhash" = "$_chksig" ] || skipgc=
877 # Prevent any other simultaneous gc operations
878 lock_gc
880 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
881 rm -f .allowgc .gc_failed
883 # Always get rid of crud
884 remove_crud
886 # Ideally we would do this in post-receive, but that would mean duplicating the
887 # logic so it's available in the chroot jail and that's highly undesirable
888 # Instead, since the first gc will be triggered immediately following the first
889 # push, we do the check here as it's quick and harmless if HEAD is already valid
890 check_and_set_head || :
892 # Always perform reflogs maintenance
893 coalesce_reflogs
894 prune_reflogs
895 compact_reflogs
897 # Always maintain auto gc hack
898 maintain_auto_gc_hack
899 generate_auto_gc_update
901 # Run 'git svn gc' now for svn mirrors
902 if [ -n "$svn_mirror" ]; then
903 git svn gc || :
906 # Skip the actual gc if .delaygc is set
907 if [ -e .delaygc ]; then
908 progress "x [$proj] garbage check delayed (except for crud removal)"
909 rm -f "$lockf"
910 exit 0
913 # Do not skip gc if the repo is dirty
914 [ -z "$skipgc" ] || ! is_dirty || skipgc=
916 # It's safe to do this part before checking the "repack" "signature" hash because
917 # this section won't do anything unless lastparentgc and/or lastreceive is unset
918 # in which case we never skip gc anyway
919 bumptime=
920 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
921 # set lastparentgc and then update gcstart to be at least 1 second later
922 config_set lastparentgc "$gcstart"
923 bumptime=1
925 if [ -z "$lastreceivesecs" ]; then
926 # set lastreceive and then update gcstart to be at least 1 second later
927 config_set lastreceive "$gcstart"
928 bumptime=1
930 if [ -n "$bumptime" ]; then
931 sleep 1
932 gcstart="$(date "$datefmt")"
936 ## Safe Pruning In Forks
938 ## We are about to perform garbage collection. We do NOT use the "git gc" or
939 ## the "git repack" commands directly as they do not provide enough control over
940 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
941 ## collection so that a simultaneous "git gc" by an administrator will be
942 ## blocked (and similarly we refuse to start garbage collection if we cannot
943 ## create the "gc.pid" file).
945 ## When we say "gc" in the below description we are referring to our "gc.sh"
946 ## script, NOT the "git gc" command.
948 ## If the project we are running garbage collection (gc) on has any forks we
949 ## must be careful not to remove any objects that while no longer referenced by
950 ## this project (the parent) are still referenced by one or more forks (the
951 ## children) otherwise the children will become corrupt and we can't abide
952 ## corrupt children.
954 ## One way to accomplish this is to simply hard-link all currently existing
955 ## loose objects and packs in the parent into all the children that refer to the
956 ## parent (via a line in their objects/info/alternates file) before beginning
957 ## the gc operation and then relying on a subsequent gc in the child to clean up
958 ## any excess objects/packs. We used to use this strategy but it's very
959 ## inefficient because:
961 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
962 ## until all children (and their children, if any) run gc by which time
963 ## it's quite possible the topmost parent will have run gc again and
964 ## hard-linked yet another old pack down to its children (not to mention
965 ## loose objects).
967 ## 2. When using the "-A" option with "git repack", any new objects in the
968 ## parent that are not referenced by children will continually get
969 ## exploded out of the hard-linked pack in the children whenever the
970 ## children run gc.
972 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
973 ## into child forks, we must run the "mini" gc maintenance before we
974 ## perform the hard-linking into the children which provides yet another
975 ## source of inefficiency.
977 ## While we were still using the "-A" option to "git repack" (that was not
978 ## always the case) to guarantee we can access old ref values for long enough
979 ## to send out a meaningful mail.sh notification, another, more efficient,
980 ## option became available to prevent corruption of child forks that continue
981 ## to refer to objects that are no longer reachable from any ref in the parent.
983 ## The only things that need be copied (or hard-linked) into the child fork(s)
984 ## are those objects that have become unreachable from any ref in the parent.
986 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
987 ## technique, the only objects that could ever be removed were loose objects
988 ## that "git prune" determined were expired. In that case, loose objects were
989 ## all that need be hard-linked down to child forks in order to avoid
990 ## corruption of any child fork(s).
992 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
993 ## objects to child forks technique remains fundamentally sound from the
994 ## perspective of supporting simultaneous gc and push and keeping newly
995 ## unreachable objects around long enough to be sure we can send out meaningful
996 ## ref change notifications and never corrupting any child forks and never
997 ## persisting the lifetime of large old packs containing mostly duplicate or
998 ## unreachable objects as gc percolates through a project's entire fork tree.
1000 ## However, that technique suffers from one potential prodigious pitfall.
1002 ## Unreachable objects come flying out of their packs to splatter all over the
1003 ## objects subdirectories possibly creating a huge, inefficient mess.
1005 ## Often this is not an issue. Even with a lot of rebasing going on, usually
1006 ## the only objects that will splatter are some commits, trees and the odd blob
1007 ## here and there. Not enough to be overly concerned about.
1009 ## However, for the reppository that frequently experiences a lot of non-fast-
1010 ## forward updates and/or outright ref deletion, the number of objects suddenly
1011 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
1013 ## To avoid this issue we now use a four phase pack creation strategy.
1014 ## This will result in creation of up to four packs (instead of at most one).
1016 ## I. A complete pack (with bitmaps if appropriate) gets created including
1017 ## only "reachable" objects from all refs/... refs plus HEAD. This will
1018 ## also serve as the virtual bundle for the repository.
1020 ## II. A pack of recently-became-unreachable objects and friends is created.
1021 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
1022 ## Because both the pre-receive and update.sh script record all ref
1023 ## changes we can easily choose the cut off point for "recently".
1024 ## It is only the fact we maintain those logs in the reflogs subdirectory
1025 ## that allows this step to be possible.
1027 ## III. If the repository has any forks with a non-zero length alternates file,
1028 ## yet another pack of "--keep-unreachable" objects is generated that will
1029 ## not actually be kept in the parent, but hard-linked into all the forks.
1031 ## IV. Finally, after running "git prune-packed", any remaining loose objects
1032 ## are migrated into a pack of their own.
1034 ## We then remove any non-.keep packs that existed before we started the
1035 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
1036 ## race condition (see docs/technical/gc.txt).
1038 ## By using "git pack-objects" directly we are able to accomplish this with
1039 ## very little additional effort.
1041 ## The packs produced by (III) are treated almost like ".keep" packs by child
1042 ## forks in that the objects in them are never repacked into any other
1043 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
1044 ## and those phase III packs are then hard-linked into any grandchild forks.
1046 ## This avoids the space explosion that could occur if each fork level ended
1047 ## up duplicating the "--keep-unreachable" pack space by repacking those
1048 ## objects (essentially breaking the hard-link to the single copy of those
1049 ## objects).
1051 ## While it is true that each level of forks could potentially add yet another
1052 ## phase III pack to be hard-linked down to its children, such packs will only
1053 ## include unreachable objects not already in any phase III packs that were
1054 ## received from the parent.
1056 ## The space for the phase III packs will not be reclaimed until the gc
1057 ## finishes percolating through the entire "fork tree" of a project.
1059 ## This is not much different than the "git repack -A -d" situation where
1060 ## all the loose objects are hard-linked down into child forks. In that
1061 ## case forks that actually need any of those objects could gradually reduce
1062 ## the number of objects hard-linked into deeper fork levels.
1064 ## The difference with a phase III "--keep-unreachable" pack is that there
1065 ## cannot be any gradual reduction like that since it would require repacking
1066 ## the pack and breaking the hard-link thereby increasing storage space. The
1067 ## storage will instead always be reclaimed all at once when all of the
1068 ## projects in the "fork tree" complete their gc.
1070 ## However, the belief is that the huge space win by having all the
1071 ## unreachable objects packed up together far eclipses (when many objects are
1072 ## involved, the single-pack version can end up using 1/20th or less of the
1073 ## disk space compared to having them all as loose objects) any brief minor
1074 ## space savings that might occur under the "git repack -A -d" loose object
1075 ## system prior to the gc collection completing for all the projects in the
1076 ## "fork tree".
1080 ## utility functions
1083 make_packs_ugw() {
1084 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1085 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1086 } 2>/dev/null
1088 get_index_tree() {
1089 if [ -s "$1" ]; then
1090 GIT_INDEX_FILE="$1"
1091 export GIT_INDEX_FILE
1092 git write-tree 2>/dev/null || :
1093 unset GIT_INDEX_FILE
1097 get_detached_head() {
1098 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1099 case "$_head" in $octet20*)
1100 echo "$_head"
1101 esac
1105 # single argument must be a top-level GIT_DIR
1106 # output will be (one per line, zero or more lines) full hash
1107 # values (i.e. 40 or more hex digits) from possible detached head
1108 # "single level" refs (e.g. "FETCH_HEAD" "MERGE_HEAD" etc.) from
1109 # files in the specified directory that have a "suitable" name and
1110 # have a length >= 40 and <= 1000 where EVERY line in a file MUST
1111 # match a 40 digit (or longer) hex string or that file will be ignored.
1112 # In a nod to Git each line first has any tab and anything following truncated.
1113 # NO sorting NOR "uniq"ing NOR "--batch-check"ing is performed on the output.
1114 # Also note that "HEAD" is NOT EXCLUDED and if detached will be output!
1115 get_detached_friends() {
1116 if [ -n "$1" ] && [ -d "$1" ]; then
1117 LC_ALL=C find -H "$1" -maxdepth 1 -name '[A-Za-z]*[A-Za-z0-9]' \
1118 -type f -size +39c -size -1001c -exec awk '
1119 BEGIN {exit}
1120 function process(fn, fnt, hashes, hcnt, fl, hi) {
1121 fnt = fn; sub(/^.*\//, "", fnt)
1122 if (length(fnt) > 31 || fnt !~ /^[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9]$/) return;
1123 hcnt = 0;
1124 while (getline fl < fn) {
1125 sub(/\t.*$/, "", fl)
1126 if (length(fl) < 40 || fl !~ /^[0-9a-fA-F][0-9a-fA-F]*$/) {hcnt = 0; break;}
1127 hashes[++hcnt] = fl;
1129 close(fn)
1130 for (hi=1;hi<=hcnt;++hi) print tolower(hashes[hi]);
1132 END {for (idx=1;idx<ARGC;++idx) process(ARGV[idx])}
1133 ' '{}' '+' 2>/dev/null || :
1137 # get_worktrees_friends
1138 # single argument is a (possibly relative) path to a "worktrees" subdir
1139 # if omitted it defaults to "worktrees"
1140 # any "friends" found in there are output to stdout
1141 get_worktrees_friends() {
1142 if [ -d "${1:-worktrees}" ]; then
1143 find -L "${1:-worktrees}" -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1144 while read -r _lwth; do
1145 get_detached_head "$_lwth"
1146 get_detached_friends "${_lwth%HEAD}"
1147 get_index_tree "${_lwth%HEAD}index"
1148 done
1152 # compute_extra_reachables
1153 # create lines suitable for a packed-refs file mentioning all the
1154 # other refs we might like to keep.
1155 # the current directory MUST be set to the repository's --git-dir
1156 # the following are included:
1157 # * refs mentioned in repack/packed-refs.extra (if it exists)
1158 # * refs mentioned in reflogs/... files
1159 # * tree(s) created from index file(s)
1160 # * detached linked working tree heads
1161 # Resulting objects are tested for existence and uniqified then output
1162 # one per line under a refs/z* namespace
1163 compute_extra_reachables() {
1165 if [ -s repack/packed-refs.extra ]; then
1166 LC_ALL=C sed <repack/packed-refs.extra -n \
1167 -e 's/^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p' \
1168 -e 's/^\^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p'
1170 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1171 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1172 LC_ALL=C awk '{print $2; print $3}'
1173 get_detached_friends .
1174 ! [ -f index ] || get_index_tree index
1175 get_worktrees_friends
1177 is_git_dir private &&
1178 [ "$(cd objects && pwd -P)" = "$(cd private/objects && pwd -P)" ] &&
1179 [ "$(cd refs && pwd -P)" != "$(cd private/refs && pwd -P)" ]
1180 then
1181 git --git-dir=private show-ref --head --hash 2>/dev/null || :
1182 get_detached_friends private
1183 ! [ -f private/index ] || get_index_tree private/index
1184 get_worktrees_friends private/worktrees
1186 } | LC_ALL=C sort -u |
1187 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1188 LC_ALL=C awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1191 # cat_all_ref_logs
1192 # the current directory MUST be set to the repository's --git-dir
1193 # first the arguments (which must reference readable files) are cat'd if any
1194 # then the path names of all ref log files are sorted and cat'd in that order
1195 # included in output:
1196 # * the contents of the pathnames given as arguments (if any) in order
1197 # * any existing files in the logs subdirectory and any existing worktree HEAD logs
1198 # but always in sorted filename order
1199 # obviously any missing directories are silently skipped
1200 cat_all_ref_logs() {
1201 [ $# -le 0 ] || LC_ALL=C cat -- "$@"
1203 ! [ -d logs ] || find -L logs -name '.*' -prune -o -name '*.' -prune -o -type f -size +0c -print
1204 if [ -d worktrees ]; then
1205 find -L worktrees -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1206 while read -r _lwth; do
1208 [ -d "${_lwth%HEAD}logs" ] &&
1209 [ -f "${_lwth%HEAD}logs/HEAD" ]
1210 then
1211 printf '%s\n' "${_lwth%HEAD}logs/HEAD"
1213 done
1215 } | LC_ALL=C sort | LC_ALL=C sed 's/[^A-Za-z0-9._/-]/\\&/g' | xargs env LC_ALL=C cat --
1219 ## main gc logic
1222 # Everything else is more efficient if we do this first
1223 git_pack_refs_all_prune
1224 [ -e packed-refs ] || >>packed-refs # should never happen...
1226 # We didn't used to do anything about rerere or worktrees but we're
1227 # trying to make nice with linked working trees these days :)
1228 # Maybe even non-bare repositories too, but *shush* about those ;)
1230 # If we have a worktrees subdir and are running Git >= 2.5.0, prune worktrees
1231 # By doing this first we may save some work if any worktrees are pruned
1232 # Git will remove the worktrees subdir entirely when the last worktree is pruned
1233 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1234 # The value "3.months.ago" is hard-coded into gc.c rather than
1235 # having the default be in worktree.c so we must provide it if
1236 # we get nothing out of the gc.worktreePruneExpire config item
1237 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1238 # however we just always use the newer name no matter what Git version
1239 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1240 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1243 # If we have a logs directory or a worktrees directory expire the ref logs now
1244 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1245 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1247 # git rerere does it right and handles its own default/config'd expiration values
1248 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1250 make_repack_dir
1252 # if we are in a possible $skipgc situation, compute and check the final
1253 # signature hash and possibly exit without actually doing anything more
1254 # if we get this far and $skipgc is true then $rpksig must be non-empty
1255 if [ -n "$skipgc" ]; then
1256 # compute the current value of the "repack" "signature" hash
1257 # it wasn't possible to do this until `make_repack_dir` was run
1258 _chksig="$({
1259 cat repack/packed-refs
1260 compute_extra_reachables
1261 cat_all_ref_logs
1262 } | sig_hash_stdin)" || :
1263 [ "$rpksig" = "$_chksig" ] || skipgc=
1266 if [ -n "$skipgc" ]; then
1267 # remove no longer needed repack and objects/pack/repack dirs and contents
1268 # while not free to create them, it's cheaper to create and destroy
1269 # them than to do an actual full gc on anything but a tiny project
1270 rm -rf repack objects/pack/repack
1271 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
1272 config_set lastgc "$gcstart"
1273 rm -f "$lockf"
1274 exit 0
1277 progress "+ [$proj] garbage check ($(date))"
1279 newdeltas=
1280 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
1281 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
1282 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
1283 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
1284 # Don't bother with repack_gfi_packs since everything's being repacked
1285 newdeltas="--no-reuse-delta"
1288 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
1289 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
1290 # There aren't enough objects to worry about so just redelta to get the best pack
1291 newdeltas="--no-reuse-delta"
1293 if [ -z "$newdeltas" ]; then
1294 # Since we're not going to recompute deltas overall, we need to do the
1295 # "mini" maintenance so that we can get more optimal deltas
1296 [ -z "$noreusedeltaopt" ] || make_needs_pack
1297 repack_gfi_packs
1298 force_single_pack_redelta=
1299 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
1300 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
1301 [ -z "$noreusedeltaopt" ] || combine_small_loose_packs $force_single_pack_redelta
1303 ! [ -e .gc_failed ] || exit 1
1304 rm -f .gc_in_progress # make sure
1305 touch .gc_in_progress # it's truly fresh
1306 rm -f bundles/* objects/pack/pack-*.bndl
1307 # These only exist for a brief time before the packs loose their _f suffix
1308 # "Push Pack Redux" does not apply to these since they were only ever present with _f
1309 rm -f objects/pack/pack-*_f.keep
1310 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1311 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1312 # and we have garbage collection forced, there's just the barest, almost negligible,
1313 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1314 # should not be removing _r .keep files. None of the normal Girocco processing can
1315 # cause this. The second run of this script would have to use the force gc option
1316 # for it to even be possible in the first place. What's much more likely is that
1317 # the initial run of this script was somehow interrupted in the middle before it
1318 # could get rid of the _r .keep file itself in which case it's better to get rid of
1319 # it now to avoid keeping something around that would perturb our nice and neat gc
1320 rm -f objects/pack/pack-*_r.keep
1321 # We will add .keep files for _u and _l packs if and when we run phase III
1322 # Otherwise they need to not have any .keep files during phases I and II
1323 rm -f objects/pack/pack-*_[ul].keep
1325 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1326 # activity will be able to "freshen" the pack containing a pre-existing object
1327 # that's being written. This really should not be necessary as the pre-receive
1328 # hook should make sure this takes place for any incoming pushes.
1329 # However, do it here anyway just in case.
1330 make_packs_ugw objects/pack
1332 # This is only effective with Git v2.3.5 and later and it will only matter when
1333 # we are using one of the "internal_rev_list" modes of pack-objects
1334 # (the combine-packs.sh script never uses any of those modes)
1335 # The "git repack" and "git prune" commands always set this internally themselves
1336 # It makes no difference if there's no repository corruption
1337 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1339 # All of the options we might want to use with pack-objects were supported
1340 # at some point prior to Git version v1.6.6 which is the minimum version that
1341 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1342 # are "boiler plate" options we always want to use so we bundle them up here.
1343 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1344 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1345 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1346 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1347 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1348 # This is not a free check as it matches all refs against refs/tags/ then
1349 # peels all the annotated tags and checks for inclusion. The situation in
1350 # which it would add a tag that was not already included by a reachability
1351 # trace that included tag starting points can only occur if a new tag gets
1352 # pushed during gc pointing to something that would have been packed anyway.
1353 # But, it could happen and, really, compared to gc as a whole it's not that
1354 # expensive to perform (provided we do not get an unconnected pack).
1355 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1356 pkopt="$pkopt ${quiet:---progress} $packopts"
1358 # The git pack-objects command only supports bitmaps if all objects are being
1359 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1360 # Additionally, while packing, if any encountered reachable objects are
1361 # determined to be "not wanted" then no bitmap index will be written anyway.
1362 # While it is theoretically possible that a project with a non-empty alternates
1363 # file ends up packing all objects (because it does not actually use any of the
1364 # objects found in the alternates), it's very unlikely. And, in the unlikely
1365 # event that did occur, clients would see a message about only using one bitmap
1366 # because Git can only use one bitmap at a time and at least one of the
1367 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1368 # alternates file, we disable writing bitmaps which avoids the warning and any
1369 # possibility of a client warning as well. Also if we are running anything
1370 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1371 # we also always disable bitmap writing.
1372 wbmopt=
1373 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1374 # More recent versions of pack-objects have optimizations when not using the
1375 # --local option. If we do not have any alternates it's a pointless option.
1376 # If we do have alternates we need to skip writing a bitmap and we cannot
1377 # have a bundle since it must contain all objects.
1378 if [ -n "$isfork" ]; then
1379 lclopt="--local"
1380 wbmopt=
1381 makebndl=
1382 else
1383 lclopt=
1384 makebndl=1
1388 ## Phase I
1391 wbmstr=
1392 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1393 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1395 gotforks=
1396 ! has_forks_with_alternates "$proj" || gotforks=1
1398 # To avoid "Push Pack Redux" (see docs/technical/gc.txt), after collecting the
1399 # initial preexisting non-keep pack list, we rename them so that an incoming push
1400 # pack cannot possibly experience a pack name collision. Git does not require
1401 # use of the "default" pack names, simply that the proper extensions are used.
1402 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1403 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1404 # down into forks and it will have an "_u" inserted just before its extension.
1405 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1406 oldpacks=
1407 for oldpack in $packlist; do
1408 oldpack="${oldpack%.pack}"
1409 [ -f "objects/pack/$oldpack.pack" ] || {
1410 echo >&2 "[$proj] unable to list old pack files"
1411 exit 1
1413 case "$oldpack" in pre-auto-gc-[12])
1414 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1415 continue
1416 esac
1417 oldpackhex="${oldpack#pack-}"
1418 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1419 # names not exclusively hexadecimal do not need renaming
1420 case "$oldpack" in
1421 pack-$octet20*_l)
1422 # _l packs are treated like still-unpacked loose objects
1423 continue;;
1424 *_f)
1425 # _f packs can only be left over from a previously interrupted gc;
1426 # they need to be renamed to _r now so they're not confused with
1427 # any freshly generated "final" packs (and we already removed
1428 # any pre-existing *_f.keep files so we're good to go)
1431 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1432 continue;;
1433 esac
1435 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack%_f}_r" || {
1436 echo >&2 "[$proj] unable to rename old pack files"
1437 exit 1
1439 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1440 # in progress at this moment and we need to .keep the renamed pack,
1441 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1442 # In either case we're okay because if it's just finished then all ref
1443 # changes have already been made so we don't need a .keep and we will
1444 # see the ref changes and grab all the objects via a reachability trace.
1445 # If it hasn't started yet that's okay because we're done moving that
1446 # name so a complete pack will appear under the old name that we'll
1447 # leave alone.
1448 if [ -f "objects/pack/$oldpack.keep" ]; then
1449 echo "Push Pack Redux" >"objects/pack/${oldpack%_f}_r.keep"
1450 else
1451 oldpacks="${oldpacks:+$oldpacks }${oldpack%_f}_r"
1453 done
1455 # We wish to keep deltas from our last full pack so if we're not redeltaing
1456 # then make sure the .pack associated with the .bitmap has a newer mod time
1457 # (If there is no .bitmap then touch the pack with the most objects instead.)
1458 if [ -z "$newdeltas" ]; then
1459 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1460 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1461 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1462 sleep 1
1463 touch -c "$bmpack" 2>/dev/null || :
1464 # We must touch .gc_in_progress here to avoid $bmpack looking
1465 # like it's been "freshened" when redundant packs are removed
1466 # It's okay if they have the same mod time, but POSIX does not
1467 # guarantee an ordering for the "touching" that occurs which is
1468 # why this must be a separate command but needs no "sleep 1"
1469 touch .gc_in_progress
1473 # Now we need to make sure that any "freshening" that takes place will actually
1474 # result in a "newer" modification time than the .gc_in_progress file now has
1475 sleep 1
1477 # We run git pack-objects from the repack subdirectory so we can force
1478 # optimized packs to be generated even for repositories that do not have any
1479 # tagged commits
1480 packs="$(git --git-dir=repack pack-objects </dev/null \
1481 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1482 v_cnt packcnt $packs
1483 [ $packcnt -eq 1 ] || makebndl=
1486 ## Phase II
1489 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1491 # Add the "supplementary" refs
1492 compute_extra_reachables >>repack/packed-refs
1494 # Now calculate the final repack signature hash
1495 # Since we do _allow_ worktrees and we do _allow_ ref logs,
1496 # the ref logs of such must be accounted for here as well
1497 _rpksig="$(cat_all_ref_logs repack/packed-refs | sig_hash_stdin)"
1498 echo "$_rpksig" >repack/repack.sighash
1500 # Subtract the primary refs
1501 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1502 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1504 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1505 # However, if there is a "logs" subdirectory we need to use --reflog
1506 # We do add it, just in case, if the linked working trees dir is present
1507 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1508 # if it properly includes linked working tree index files or not. The
1509 # above compute_extra_reachables has already included all index trees (thereby
1510 # providing proper --indexed-objects support for all Git versions) making the
1511 # option completely unnecessary.
1512 rflopt=
1513 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1514 spacks="$(git --git-dir=repack pack-objects </dev/null \
1515 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1518 ## Phase III
1521 # There's nothing to do for Phase III unless we have forks that refer to our
1522 # project from their alternates file
1523 hlpacks=
1524 upacks=
1525 if [ -n "$gotforks" ]; then
1527 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1529 # If we are a fork, any pre-existing _u packs need to have a .keep
1530 # for this phase and be added to the hlpacks list otherwise (we are
1531 # not a fork) pre-existing _u packs are anomalies to be treated like
1532 # regular non-_u packs
1533 if [ -n "$isfork" ]; then
1534 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_[ul].pack" -print); do
1535 upack="${upack%.pack}"
1536 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1537 case "$upack" in *_l);;*)
1538 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1539 esac
1540 done
1542 # Using either --no-reuse-delta or --no-reuse-object together with the
1543 # --keep-unreachable option is a very, very, very bad idea when good
1544 # packs are the desired outcome. If newdeltas are being generated
1545 # then we pack to a temp name, and use combine-packs.sh to get a better
1546 # pack as the result to avoid making a bad --keep-unreachable pack
1547 pfx=
1548 [ -z "$newdeltas" ] || pfx="ku"
1549 upacks="$(git --git-dir=repack pack-objects </dev/null \
1550 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1551 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1552 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1553 oldupacks="$upacks"
1554 upacks="$(
1555 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1556 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1557 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1558 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1560 for upack in $upacks; do
1561 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1562 done
1563 rm -f objects/pack/pack-*_[ul].keep
1564 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1565 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1567 # We have to update the lastparentgc time in the child forks even if they do not get any
1568 # new "unreachable packs" because they need to run gc just in case the parent now has some
1569 # objects that used to only be in the child so they can be removed from the child.
1570 # For example, a "patch" might be developed first in a fork and then later accepted into
1571 # the parent in which case the objects making up the patch in the child fork are now
1572 # redundant (since they're now in the parent as well) and need to be removed from the
1573 # child fork which can only happen if the child fork runs gc.
1574 lastparentgc="$(date "$datefmt")"
1576 # It is enough to copy objects just one level down and get_repo_list
1577 # takes a regular expression (which is automatically prefixed with '^')
1578 # so we can easily match forks exactly one level down from this project
1579 forkdir="$proj"
1580 get_repo_list "$forkdir/[^/:][^/:]*:" |
1581 while read fork; do
1582 # Ignore forks that do not exist or are symbolic links
1583 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1584 continue
1585 # Or have an empty alternates file
1586 ! is_empty_alternates_file "$cfg_reporoot/$fork.git/objects/info/alternates" ||
1587 continue
1588 runupdate=
1589 # Match hlpacks in parent project if any
1590 if [ -n "$hlpacks" ]; then
1591 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1592 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1593 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1594 '"$cfg_reporoot/$fork.git/objects/pack/"'
1595 runupdate=1
1597 # Match upacks in repack/alt area if any
1598 if [ -n "$upacks" ]; then
1599 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1600 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1601 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1602 '"$cfg_reporoot/$fork.git/objects/pack/"'
1603 runupdate=1
1605 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1606 # Trigger a mini gc in the fork if it now has too many packs
1607 fpackcnt="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1608 if [ -n "$fpackcnt" ] && [ "$fpackcnt" -ge 20 ]; then
1609 >"$cfg_reporoot/$fork.git/.needsgc"
1612 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1613 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1614 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1615 done
1618 # Now move any primary/supplementary packs back into objects/pack
1619 # then drop any "unfreshened" redundant packs and clear repack/alt
1621 # First make sure the primary pack(s) have the most recent mod time
1622 if [ -n "$packs" ]; then
1623 [ -z "$spacks" ] || sleep 1
1624 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1627 # Move the packs into place but with a _f suffix and a .keep file for now
1628 for pack in $packs $spacks; do
1629 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-${pack}_f"
1630 [ -e "objects/pack/pack-${pack}_f.keep" ] ||
1631 echo "final" >"objects/pack/pack-${pack}_f.keep"
1632 done
1634 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1635 # with its .bitmap) and then got "freshened" causing us to not remove it
1636 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1637 # This can produce ugly warnings we don't want and possibly get the wrong
1638 # bitmap used since only one .bitmap file can ever be used by Git.
1639 # If this has happened, the .bitmap we want to discard will always have
1640 # an _r suffix so we can just zap any such now since it will leave the pack.
1641 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1643 # Remove the redundant packs that have not since been "freshened"
1644 # This does not completely eliminate the race condition window (Girocco's own
1645 # activites -- gc/fetch/receive are immune to the race) but it substantially
1646 # shrinks it down to just the time after the find but before the following rm
1647 >repack/oldpacks
1648 [ -z "$oldpacks" ] ||
1649 printf 'objects/pack/%s.pack\n' $oldpacks |
1650 LC_ALL=C sort >repack/oldpacks
1651 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1652 LC_ALL=C sort >repack/freshened
1653 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1654 [ -z "$deadpacks" ] ||
1655 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1657 # No need for this anymore
1658 rm -rf repack/alt objects/pack/repack
1659 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1662 ## Phase IV
1665 progress "~ [$proj] running gc prune-packed"
1667 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1668 # present while running prune-packed. We try to guarantee that any loose object
1669 # (or any object present in a pack with an _l suffix which was created by mini gc)
1670 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1671 # (not withstanding administrator interference to force earlier gc to occur).
1672 # If we were to include the redundant/keep-unreachable pack(s) when running
1673 # prune-packed and a loose unreachable object happened to be duplicated in one
1674 # of them we would end up removing it too soon and void our guarantee.
1675 git prune-packed $quiet
1677 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1679 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1680 # we MUST NOT use it for these reasons:
1681 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1682 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1683 # 3) We don't require anything more than Git v1.6.6
1684 # The only way we could see any _o pack files at this point is if one got
1685 # "freshened" while we were running gc. If that happens then it gets to live on
1686 # until the next full gc and we need to include it in the loose repack here.
1687 lpacks="$(list_packs --exclude-no-idx --exclude-no-sfx _l --exclude-no-sfx _o --quiet objects/pack |
1688 run_combine_packs --replace --names --loose --weak-naming --non-empty --honor-pack-keep \
1689 --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1691 if [ -n "$lpacks" ]; then
1692 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1693 if [ -n "$packs" ]; then
1694 sleep 1
1695 printf 'objects/pack/pack-%s_f.pack\n' $packs | xargs touch -c 2>/dev/null || :
1697 # We need to identify these packs later so we don't combine_packs them
1698 for objpack in $lpacks; do
1699 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1700 done
1703 # Polish up the final packs now
1704 rm -f objects/pack/pack-*_f.keep
1705 for pack in $packs $spacks; do
1706 rename_pack "objects/pack/pack-${pack}_f" "objects/pack/pack-$pack"
1707 done
1709 if [ -n "$lpacks" ]; then
1710 # Finally zap the corresponding loose objects
1711 progress "~ [$proj] running packed loose objects gc prune-packed"
1712 git prune-packed $quiet
1715 ! [ -e .gc_failed ] || exit 1
1716 # These, if they exist, are now meaningless and need to be removed
1717 rm -f gfi-packs .needsgc .needspack .needspackgc
1719 # Make sure this stays up to date
1720 git update-server-info
1722 # We must make loose objects group writable so that they
1723 # can be freshened by other pushers. Technically we need only do this for
1724 # push projects but to enable mirror projects to be more easily converted to
1725 # push projects, we go ahead and do it for all projects.
1726 # By the time we get here we really shouldn't have any of these, but just in case.
1727 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1729 # darcs mirrors have a xxx.log file that will grow endlessly
1730 # if this is a mirror and the file exists, shorten it to 10000 lines
1731 # also take this opportunity to optimize the darcs repo
1732 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1733 url="$(config_get baseurl)" || :
1734 case "$url" in darcs://* | darcs+http://* | darcs+https://*)
1735 if [ -n "$cfg_mirror_darcs" ]; then
1736 url="${url%/}"
1737 basedarcs="$(basename "${url#darcs*:/}")"
1738 if [ -f "$basedarcs.log" ]; then
1739 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1740 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1742 if [ -d "$basedarcs.darcs" ]; then
1744 cd "$basedarcs.darcs"
1745 # without show_progress suppress non-error output
1746 [ "${show_progress:-0}" != "0" ] || exec >/dev/null
1747 # Note that this does not optimize _darcs/inventories/ :(
1748 darcs optimize || :
1752 esac
1755 # Create a matching .bndl header file for the all-in-one pack we just created
1756 # but only if we're not a fork (otherwise the bundle would not be complete)
1757 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1758 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1759 # There should only be one pack in $packs but do some checking...
1760 # The one we just created will have a .idx and will NOT have a .keep
1761 progress "~ [$proj] creating downloadable bundle header"
1762 pkbase=
1763 pkhead=
1764 IFS= read -r curhead <repack/HEAD.orig || :
1766 [ -s "objects/pack/pack-$packs.pack" ] &&
1767 [ -s "objects/pack/pack-$packs.idx" ] &&
1768 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1769 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1770 "$PWD/repack/packed-refs.orig" "$curhead")"
1771 then
1772 pkbase="objects/pack/pack-$packs"
1774 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1776 symref=
1777 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1778 symref="${curhead#ref:}"
1779 symref="${symref# }"
1780 esac
1781 bndlurl=
1782 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1783 echo "# v2 git bundle"
1784 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1785 if [ -n "$symref" ]; then
1786 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1787 else
1788 if [ -n "$bndlurl" ]; then
1789 printf "$pkhead HEAD\0%s\n" "${bndlurl# }"
1790 else
1791 echo "$pkhead HEAD"
1794 echo ""
1795 } >"$pkbase.bndl"
1796 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1797 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1798 if [ -n "$bndletag" ]; then
1799 case "$bndlsha" in $octet20*)
1800 bndlshatrailer="${bndlsha#????????}"
1801 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1802 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1803 [ -d bundles ] || mkdir bundles
1804 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1805 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1806 ln -s -f -n "$bndlname" bundles/latest
1807 esac
1812 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1813 eval "reposizek=$(( $(
1814 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1815 LC_ALL=C awk '{print $1}') |
1816 LC_ALL=C sed -e 's/ / + /g') ))"
1817 config_set_raw girocco.reposizek "${reposizek:-0}"
1819 read -r rsighash <repack/packed-refs.sighash || :
1820 read -r repacksig <repack/repack.sighash || :
1822 # Now we're finally done with this
1823 rm -rf repack
1825 # Update various "signature" hashes used to help determine whether or
1826 # not it's okay to skip gc in the future (because there's nothing to do)
1828 psighash="$(if [ -n "$packs" ] || [ -n "$spacks" ]; then
1829 printf 'pack-%s.pack\n' $packs $spacks
1830 fi | LC_ALL=C sort | sig_hash_stdin)"
1831 config_set_raw girocco.gcsig.packs "$psighash"
1832 config_set_raw girocco.gcsig.refs "$rsighash"
1833 config_set_raw girocco.gcsig.repack "$repacksig"
1835 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1836 # and the next future gc could be incorrectly skipped if we used the current
1837 # timestamp here instead
1838 config_set lastgc "$gcstart"
1839 rm -f "$lockf"
1841 progress "- [$proj] garbage check ($(date))"