apache.conf.in: use @@certsdir@@ not @@webroot@@/../certs
[girocco.git] / jobd / gc.sh
blob58702b7a074ee07391dcbe2b105ca15625422400
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 one objects/pack-<sha>.pack file or
118 # ANY sha-1 files in objects or
119 # there's one pack and it's not a normal pack name or
120 # there's 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 2)"
123 v_cnt _packscnt $_packs
124 if [ $_packscnt -gt 1 ]; then
125 return 0
127 if [ $_packscnt -eq 1 ]; then
128 # the single pack name is in $_packs
129 _packs="${_packs%.pack}"
130 _packs="${_packs#objects/pack/}"
131 case "$_packs" in
132 pack-*)
133 _packs="${_packs#pack-}"
134 if [ "${#_packs}" -lt 40 ] || [ "${_packs#*[!0-9a-fA-F]}" != "$_packs" ]; 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
145 _objs=$(find -L objects/$octet -name "$octet19*" -type f -print 2>/dev/null | head -n 1 | LC_ALL=C wc -l)
146 [ $_objs -eq 0 ] || return 0
147 [ $_packscnt -eq 1 ] || return 1
148 # we do this check last because it's potentially the most expensive;
149 # at this point we know we do not have any loose objects, but we do
150 # have one pack that's named "normally"; empty refs => dirty
151 is_empty_refs_dir
154 # combine the input pack(s) into a new pack (or possibly packs if packSizeLimit set)
155 # input pack names are read from standard input one per line delimited by the first
156 # ':', ' ' or '\n' character on the line (which allows gfi-packs to be read directly)
157 # all arguments, if any, are passed to pack-objects as additional options
158 # returns non-zero on failure AND creates .gc_failed in that case
159 combine_packs() {
160 rm -f .gc_failed
161 combine_packs_std "$@" || {
162 >.gc_failed
163 return 1
165 return 0
168 # if the current directory is_gfi_mirror then repack all packs listed in gfi-packs
169 repack_gfi_packs() {
170 [ -n "$gfi_mirror" ] || return 0
171 [ -d objects/pack ] || { rm -f gfi-packs; return 0; }
172 progress "~ [$proj] redeltifying poor quality git fast-import packs"
173 combine_packs --ignore-missing --no-reuse-delta <gfi-packs
174 rm -f gfi-packs
175 return 0
178 # pack any existing loose objects into a new _l.pack file then run prune-packed
179 # note that prune-packed is NOT run beforehand -- the caller must do that if needed
180 # loose objects need not be part of complete commits/trees as --weak-naming is used
181 pack_loose_objects() {
182 _lpacks="$(run_combine_packs </dev/null --names --loose --weak-naming --non-empty --all-progress-implied ${quiet:---progress} $packopts)"
183 if [ -n "$_lpacks" ]; then
184 # We need to identify these packs later so we don't combine_packs them
185 for _objpack in $_lpacks; do
186 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
187 done
188 git prune-packed $quiet
192 # combine small packs into larger pack(s)
193 # we avoid any _[lo], keep, bndl or bitmap packs
194 # if the optional argument is non-empty even a single small pack will be redeltad
195 combine_small_packs() {
196 _didprogress=
197 _minsmallpacks=2
198 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
199 _minsmallpacks=1
201 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
202 _lpo="$_lpo --exclude-sfx _u --exclude-sfx _o --exclude-sfx _l"
203 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
204 while
205 _cnt="$(list_packs --count $_lpo)" || :
206 test "${_cnt:-0}" -ge $_minsmallpacks
208 [ -n "$_didprogress" ] || {
209 progress "~ [$proj] combining small packs into a single larger pack"
210 _didprogress=1
212 _newp="$(list_packs $_lpo | combine_packs --names $noreusedeltaopt)"
213 v_cnt _newc $_newp
214 # be paranoid and exit the loop if we haven't reduced the number of packs
215 [ $_newc -lt $_cnt ] || break
216 _minsmallpacks=2
217 done
218 return 0
221 # combine small _l packs into larger pack(s) using --weak-naming
222 # we avoid any non _l, keep, bndl or bitmap packs
223 # if the optional 2nd argument is non-empty even a single small pack will be redeltad
224 combine_small_loose_packs() {
225 _didprogress=
226 _minsmallpacks=2
227 if [ -n "$1" ] && [ -n "$noreusedeltaopt" ]; then
228 _minsmallpacks=1
230 _lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl"
231 _lpo="$_lpo --exclude-no-sfx _l"
232 _lpo="$_lpo --quiet --object-limit $var_redelta_threshold objects/pack"
233 while
234 _cnt="$(list_packs --count $_lpo)" || :
235 test "${_cnt:-0}" -ge $_minsmallpacks
237 [ -n "$_didprogress" ] || {
238 progress "~ [$proj] combining small loose packs into a single larger pack"
239 _didprogress=1
241 _newp="$(list_packs $_lpo | combine_packs --names --weak-naming $noreusedeltaopt)"
242 # We need to identify these packs later so we don't combine_packs them
243 for _objpack in $_newp; do
244 rename_pack "objects/pack/pack-$_objpack" "objects/pack/pack-${_objpack}_l" || :
245 done
246 v_cnt _newc $_newp
247 # be paranoid and exit the loop if we haven't reduced the number of packs
248 [ $_newc -lt $_cnt ] || break
249 _minsmallpacks=2
250 done
251 return 0
254 # Unfortunately, some fetch strategies (e.g. git-svn and non-smart HTTP) lack
255 # the ability to store newly fetched objects in a pack.
256 # However, the fetch code conveniently sets .needspack just before it fetches
257 # so that it's easy to find all the loose objects that have been fetched and
258 # combine them into a pack. The --no-reuse-delta option is meaningless here
259 # since everything to be packed is a loose object and therefore not a delta so
260 # deltification will always take place.
261 make_needs_pack() {
262 [ -f .needspack ] || return 0
263 rm -f .needspackgc
264 mv -f .needspack .needspackgc
265 progress "~ [$proj] combining fetched loose objects into a pack"
266 _newp="$(find -L objects/$octet -maxdepth 1 -type f -newer .needspackgc -name "$octet19*" -print 2>/dev/null |
267 LC_ALL=C awk -F / '{print $2 $3}' |
268 run_combine_packs --objects --names $packopts --incremental --all-progress-implied $quiet --non-empty)" || {
269 # We used to fail gc here.
270 # Now, however, we just ignore the failure because we have
271 # another mechanism to handle loose objects and it's possible
272 # that the fetcher somehow brought in unconnected objects which
273 # would cause the above combine-packs to fail.
274 # By ignoring the failure and just removing the .needspack file
275 # the loose objects will be treated as "ordinary" loose objects
276 # and packed using the "--weak-naming" option which can handle
277 # broken connectivity.
278 # That's a better solution than just failing here or leaving
279 # .needspack behind to potentially continue to fail again and
280 # again.
281 _newp=
283 if [ -n "$_newp" ]; then
284 # remove the now-redundant loose objects -- this is always safe
285 # even during a concurrent push because a reprepare_packed_git
286 # will be triggered if an object that should be there is not
287 # found thereby finding it in the new pack instead
288 git prune-packed $quiet
290 rm -f .needspackgc
293 # HEADSHA="$(pack_is_complete /full/path/to/some.pack /full/path/to/packed-refs "$(cat HEAD)")"
294 pack_is_complete() {
295 # Must have a matching .idx file and a non-empty packed-refs file
296 [ -s "${1%.pack}.idx" ] || return 1
297 [ -s "$2" ] || return 1
298 _headsha=
299 case "$3" in
300 $octet20*)
301 _headsha="$3"
303 "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
304 _headmatch="${3#ref:}"
305 _headmatch="${_headmatch# }"
306 _headmatchpat="$(echo "$_headmatch" | LC_ALL=C sed -e 's/\([.$]\)/\\\1/g')"
307 _headsha="$(LC_ALL=C grep -e "^$octet20$hexdig* $_headmatchpat\$" <"$2" |
308 LC_ALL=C cut -d ' ' -f 1)"
309 case "$_headsha" in $octet20*) :;; *)
310 return 1
311 esac
314 # bad HEAD
315 return 1
316 esac
317 rm -rf pack_is_complete_test
318 mkdir pack_is_complete_test
319 mkdir pack_is_complete_test/refs
320 mkdir pack_is_complete_test/objects
321 mkdir pack_is_complete_test/objects/pack
322 echo "$_headsha" >pack_is_complete_test/HEAD
323 ln -s "$1" pack_is_complete_test/objects/pack/
324 ln -s "${1%.pack}.idx" pack_is_complete_test/objects/pack/
325 ln -s "$2" pack_is_complete_test/packed-refs
326 _count="$(git --git-dir=pack_is_complete_test rev-list --count --all 2>/dev/null)" || :
327 rm -rf pack_is_complete_test
328 [ -n "$_count" ] || return 1
329 [ "$_count" -gt 0 ] 2>/dev/null || return 1
330 echo "$_headsha"
333 # On return a "$lockf" will have been created that must be removed when gc is done
334 lock_gc() {
335 v_lock_gc _lockresult || {
336 echo >&2 "[$proj] $_lockresult"
337 exit 1
339 lockf="$_lockresult"
342 # Create a repack subdirectory such that running repack in it will pack the
343 # same things that a pack in the normal directory would except that the pack
344 # is guaranteed to be generated in an optimized order by adding a suitable
345 # synthesized ref in the refs/tags namespace (yes, pack-objects.c really does
346 # behave differently depending on the contents of the refs/tags namespace).
347 # Before calling this, pack-refs --all MUST be performed or the wrong pack
348 # will end up being made.
350 # If a ref deletion is pushed after making the repack subdir but before the
351 # the actual repack, the discarded objects will be packed -- no big deal,
352 # they'll get discarded the next time gc runs.
354 # If a fast-forward ref update is pushed after making the repack subdir but
355 # before the actual repack, it will be picked up and the new objects packed
356 # (subject to the normal git repack race about picking such updates up).
358 # If a non-fast-forward ref update is pushed after making the repack subdir but
359 # before the actual repack, it will be picked up like a fast-forward update but
360 # the discarded objects will be included like a ref deletion (until the next
361 # scheduled gc takes place).
363 # We retain a copy of the original packed-refs file as repack/packed-refs.orig
364 # If ref deletions come in while we're repacking, the original packed-refs
365 # file will be modified, but we'll still pack the deleted ref(s).
366 # If the packed-refs.orig file is used to create the bundle header we avoid
367 # a situation where the bundle contains a ref state that never actually
368 # existed in reality (for example a new branch is pushed and then an old
369 # branch deleted afterwards -- the deletion would show up in the bundle
370 # because it will cause the original packed-refs file to be re-written, but
371 # the new branch creation will not unless we do another pack-refs which might
372 # lead to having in incomplete bundle). Therefore we want to keep a copy of
373 # the original packed-refs file around. We do the same thing for HEAD.
375 # It's possible that the "objects" subdirectory is a symbolic link.
376 # Git does support this. However, during the repacking process, new packs
377 # will be created in repack/alt/pack and then moved into objects/pack.
378 # In order for this to work seemlessly, they must both be on the same
379 # filesystem. But when objects (or even objects/pack) is a symbolic link they
380 # might not be. For this reason a "repack" subdirectory is created under
381 # objects/pack and the repack/alt/pack directory symbolicly linked to it.
383 # Git allows not just HEAD to be a symbolic-ref, but any ref anywhere in the
384 # refs namespace. We are concerned about ref name collisions and getting the
385 # right tag set to get an optimal pack. We can safely duplicate the ref space
386 # under refs/heads, refs/notes and refs/remotes without any risk of unwanted
387 # collisions and this will likely make over 99%+ of all symbolic refs found
388 # in the wild work properly. Girocco itself never creates any symbolic refs
389 # inside the refs namespace; this is a nod to simultaneously using a Girocco
390 # repository for other purposes.
391 make_repack_dir() {
392 ! [ -d repack ] || rm -rf repack
393 ! [ -d repack ] || { echo >&2 "[$proj] cannot remove repack subdirectory"; exit 1; }
394 [ -d objects/pack ] || mkdir -p objects/pack
395 ! [ -d objects/pack/repack ] || rm -rf objects/pack/repack
396 ! [ -d objects/pack/repack ] || { echo >&2 "[$proj] cannot remove objects/pack/repack subdirectory"; exit 1; }
397 mkdir repack repack/refs repack/alt objects/pack/repack
398 [ -d info ] || mkdir info
399 ln -s ../config repack/config
400 ln -s ../info repack/info
401 ln -s ../objects repack/objects
402 ln -s "$PWD/objects/pack/repack" repack/alt/pack
403 ln -s ../../refs repack/refs/refs
404 ! [ -d logs ] || ln -s ../logs repack/logs
405 ! [ -d worktrees ] || ln -s ../worktrees repack/worktrees
406 _lines=$(( $(LC_ALL=C wc -l <packed-refs) ))
407 cat HEAD >repack/HEAD.orig
408 >repack/packed-refs.extra
409 _xtralines=0
410 cat packed-refs >repack/packed-refs.orig
411 if [ $(LC_ALL=C wc -l <repack/packed-refs.orig) -ne "$_lines" ]; then
412 echo >&2 "[$proj] error: make_repack_dir failed original packed-refs line count sanity check"
413 exit 1
415 if [ "${cfg_fetch_stash_refs:-0}" = "0" ]; then
416 # migrate any refs/stash or refs/tgstash lines to repack/packed-refs.extra
417 <repack/packed-refs.orig LC_ALL=C awk -v xtra="repack/packed-refs.extra" '
418 BEGIN { peeling = 0 }
419 NR == 1 && /^#/ { print; next; }
420 peeling && /^\^/ { print >>xtra; next; }
421 /^[0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f]+ refs\/(stash|tgstash)(\/|$)/ {
422 peeling = 1
423 print >>xtra
424 next
426 { peeling = 0; print; }
427 ' >repack/packed-refs.new
428 _xtralines="$(( $(LC_ALL=C wc -l <repack/packed-refs.extra) + 0 ))"
429 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs.new) + 0 ))"
430 if [ "$(( $_newlines + $_xtralines ))" -ne "$_lines" ]; then
431 echo >&2 "[$proj] error: make_repack_dir failed packed-refs.extra line count sanity check"
432 exit 1
434 mv -f repack/packed-refs.new repack/packed-refs.orig
435 _lines="$_newlines"
437 # Note: Git v1.5.0 introduced the "# pack-refs with:" header line for the packed-refs file
438 sed '/^# pack-refs/d; s, refs/, refs/!/,' <repack/packed-refs.orig >repack/packed-refs
439 nohead=
440 headref="$(git rev-parse --verify --quiet HEAD)" || :
441 if [ -n "$headref" ]; then
442 echo "$headref refs/!=/HEAD" >>repack/packed-refs
443 echo "$headref refs/heads/!" >>repack/packed-refs
444 nohead='\, refs/heads/!$,d; '
445 _lines=$(( $_lines + 2 ))
447 if [ $(( $(LC_ALL=C wc -l <repack/packed-refs) + 1 )) -ne "$_lines" ]; then
448 echo >&2 "[$proj] error: make_repack_dir failed packed-refs initial line count sanity check"
449 exit 1
451 sed -n "$nohead"'\, refs/heads/,p; \, refs/notes/,p; \, refs/remotes/,p' <repack/packed-refs.orig >>repack/packed-refs
452 _newlines="$(( $(LC_ALL=C wc -l <repack/packed-refs) ))"
453 if [ $(( $_newlines + 1 )) -lt "$_lines" ]; then
454 echo >&2 "[$proj] error: make_repack_dir failed packed-refs extra line count sanity check"
455 exit 1
457 _lines="$_newlines"
458 optref="$(git rev-list -n 1 --all 2>/dev/null)" || :
459 if [ -n "$optref" ]; then
460 echo "$optref refs/tags/!" >>repack/packed-refs
461 _lines=$(( $_lines + 1 ))
462 echo "$optref" >repack/HEAD
463 else
464 cat HEAD >repack/HEAD
466 if [ $(LC_ALL=C wc -l <repack/packed-refs) -ne "$_lines" ]; then
467 echo >&2 "[$proj] error: make_repack_dir failed packed-refs line count sanity check"
468 exit 1
472 # Remove any crud that's been left behind by interrupted operations
473 # that did not clean up after themselves
474 remove_crud() {
475 # Remove any existing FETCH_HEAD
476 # There can only be a FETCH_HEAD if we've been fetching, not if we've been
477 # receiving pushes (those never create a FETCH_HEAD).
478 # And if we're fetching because we're a mirror, we know we're not fetching right
479 # now since jobd.pl never runs a project's fetch simultaneously with its gc.
480 # Therefore any existing FETCH_HEAD is junk. And it may be many megabytes if
481 # there were a lot of refs.
482 rm -f FETCH_HEAD
484 # Remove any stale ref locks
485 clear_stale_ref_locks
487 # remove any existing pack_is_complete_test or repack subdirectories
488 # If either exists when this function is called it's crud
489 rm -rf pack_is_complete_test repack objects/pack/repack
491 # Remove any stale pack remnants that are more than an hour old.
492 # Stale pack fragments are defined as any pack-<sha1>.ext where .ext is NOT
493 # .pack AND the corresponding .pack DOES NOT exist. A bunch of stale
494 # pack-<sha1>.idx files without their corresponding .pack files are worthless
495 # and just waste space. Normally there shouldn't be any remnants but actually
496 # this can happen when things are interrupted at just the wrong time.
497 # Note that the objects/pack directory is created by git init and should
498 # always exist.
499 find -L objects/pack -maxdepth 1 -type f -mmin +60 -name "pack-$octet20*.?*" -print |
500 LC_ALL=C sed -e 's/^objects\/pack\/pack-//; s/\..*$//' | LC_ALL=C sort -u |
501 while read packsha; do
502 ! [ -e "objects/pack/pack-$packsha.pack" ] || continue
503 rm -f "objects/pack/pack-$packsha".?*
504 done
506 # Remove any stale tmp reflogs files that are more than one hour old.
507 # Since they are created only while the pre-receive hook is running and
508 # all it does is process a bunch of refs passed to it on standard input
509 # it's inconceivable that it would ever take as much as an hour to run.
510 if [ -d reflogs ]; then
511 find -L reflogs -maxdepth 1 -type f -mmin +60 -name "tmp_*" -exec rm -f '{}' + || :
514 # Remove any stale object tmp_obj_* files that are more than 3 hours old.
515 # Really these files should only exist very briefly so there shouldn't be any
516 # but things happen that can end up leaving them behind.
517 find -L objects/$octet -maxdepth 1 -type f -mmin +180 -name "tmp_obj_?*" -exec rm -f '{}' + 2>/dev/null || :
519 # Remove any stale pack .keep files that are more than 12 hours old.
520 # We don't do anything to create any permanent pack .keep files, so they must
521 # be remnants from some failed push or something. Removing the .keep will
522 # allow the pack to be properly repacked.
523 find -L objects/pack -maxdepth 1 -type f -mmin +720 -name "pack-$octet20*.keep" -exec rm -f '{}' + || :
525 # Remove any stale tmp_pack_*, tmp_idx_*, tmp_bitmap_*, packtmp-* or .tmp-*-pack* files
526 # that are more than 12 hours old.
527 find -L objects/pack -maxdepth 1 -type f -mmin +720 \( \
528 -name "tmp_pack_?*" -o -name "tmp_idx_?*" -o -name "tmp_bitmap_?*" -o \
529 -name "packtmp-?*" -o -name ".tmp-?*-pack*" \
530 \) -exec rm -f '{}' + || :
532 # Remove any stale incoming-* object quarantine directories that are
533 # more than 12 hours old. These are new with Git >= 2.11.0.
534 find -L objects -maxdepth 1 -type d -name 'incoming-?*' -mmin +720 \
535 -exec rm -rf '{}' + || :
537 # Remove any stale shallow_* files that are more than 12 hours old.
538 # These can be left behind by Git >= 1.8.4.2 and < 2.0.0 when a client
539 # requests a shallow clone. Also discard stale .refs-temp* and
540 # .refs-new* files at the same time.
541 find -L . -maxdepth 1 -type f -mmin +720 \( \
542 -name "shallow_?*" -o -name ".refs-temp*" -o -name ".refs-new*" \
543 \) -exec rm -f '{}' + || :
545 # Remove any stale cmbnpcks-* dirs that are more than 12 hours old.
546 # These can be left behind by abnormal exits (e.g. power failure).
547 find -L . -maxdepth 1 -type d -mmin +720 -name "cmbnpcks-?*" \
548 -exec rm -rf '{}' + || :
550 # Remove any stale *.temp files in the objects area that are more than 12 hours old.
551 # This can be stale sha1.temp, or stale *.pack.temp so we kill all stale *.temp.
552 find -L objects -type f -mmin +720 -name "*.temp" -exec rm -f '{}' + || :
554 # Remove any stale *.lock files in the htmlcache area that might have been left
555 # behind after an abnormal exit during an attempt to update a cached file and
556 # are more than 1 hour old.
557 ! [ -d htmlcache ] || find -L htmlcache -type f -mmin +60 -name "*.lock" -exec rm -f '{}' + || :
559 # Remove any stale git-svn temp files that are more than 12 hours old.
560 # The git-svn process creates temp files with random 10 character names
561 # in the root of $GIT_DIR. Unfortunately they do not have a recognizable
562 # prefix, so we just have to kill any files with a 10-character name. We
563 # do this only for git-svn mirrors. All characters are chosen from
564 # [A-Za-z0-9_] so we can at least check that and fortunately the only
565 # collision is 'FETCH_HEAD' but that shouldn't matter.
566 # There may also be temp files with a Git_ prefix as well.
567 if [ -n "$svn_mirror" ]; then
568 _randchar='[A-Za-z0-9_]'
569 _randchar2="$_randchar$_randchar"
570 _randchar4="$_randchar2$_randchar2"
571 _randchar10="$_randchar4$_randchar4$_randchar2"
572 find -L . -maxdepth 1 -type f -mmin +720 -name "$_randchar10" -exec rm -f '{}' + || :
573 find -L . -maxdepth 1 -type f -mmin +720 -name "Git_*" -exec rm -f '{}' + || :
576 # Remove any stale fast_import_crash_<pid> files that are more than 3 days old.
577 if [ -n "$gfi_mirror" ]; then
578 find -L . -maxdepth 1 -type f -mmin +4320 -name "fast_import_crash_?*" -exec rm -f '{}' + || :
581 # Remove any stale core or *.core or core.* files that are more than 3 days old.
582 find -L . -maxdepth 1 -type f -mmin +4320 \( -name "core" -o -name "*.core" -o -name "core.*" \) \
583 -exec rm -f '{}' + || :
587 ## Garbage Collection Types
589 ## There are two kinds of possible garbage collection (gc) operations:
591 ## 1. A normal, full gc
592 ## 2. A "mini" gc
594 ## If the full garbage collection interval has expired (or gc has never been
595 ## run), then a normal, full gc will take place. Otherwise, a "mini" gc will
596 ## take place if the file .needsgc exists.
598 ## A "mini" gc is similar to "git gc --auto" in that it may not end up actually
599 ## doing anything unless the right conditions are present so it's not a burden
600 ## to run it often. If the file .needsgc exists, a "mini" gc will occur at
601 ## the next opportunity.
603 ## See the docs/technical/gc.txt and docs/technical/gc-mini.txt files for more
604 ## of the gory details of how garbage collection is performed.
606 ## Note, however, that the .nogc file suppresses ALL gc activity (normal or mini).
609 proj="${1%.git}"
610 shift
611 cd "$cfg_reporoot/$proj.git"
612 [ -d objects/pack ] || { rm -f gfi-packs; mkdir -p objects/pack; }
613 mirror_url="$(get_mirror_url)" || :
614 svn_mirror=
615 ! is_svn_mirror_url "$mirror_url" || svn_mirror=1
616 gfi_mirror=
617 if [ -f gfi-packs ] && [ -s gfi-packs ] && is_gfi_mirror_url "$mirror_url"; then
618 gfi_mirror=1
621 # If git config --bool --get girocco.redelta is explicitly false then automatic
622 # redelta when there are less than $var_redelta_threshold objects will be suppressed.
623 # On the other hand, if git config --get girocco.redelta is "always" then, on a full
624 # gc only, for the final repack, deltas will always be recomputed.
625 # This can be set on a per-project basis to avoid unusual pathological gc behavior.
626 # Setting this will hurt efficiency of the affected repository.
627 # Note that fast-import packs ALWAYS get new deltas regardless of this setting.
628 noreusedeltaopt="--no-reuse-delta"
629 [ "$(git config --bool --get girocco.redelta 2>/dev/null || :)" != "false" ] || noreusedeltaopt=
630 alwaysredelta=
631 [ "$(git config --get girocco.redelta 2>/dev/null || :)" != "always" ] || alwaysredelta=1
633 # Extract any -f or -F or --no-reuse-object or --no-reuse-delta options
634 # to be compatible with the old and new gc.sh versions and avoid ugly argument
635 # duplication in process lists at the same time
636 # Any options found will override the "girocco.redelta" setting
637 recompress=
638 idx=$#
639 while [ $idx -gt 0 ]; do
640 idx=$(( $idx - 1 ))
641 opt="$1"
642 shift
643 case "$opt" in
644 -f|--no-reuse-delta)
645 alwaysredelta=1
646 continue
648 -F|--no-reuse-object)
649 alwaysredelta=1
650 recompress=1
651 continue
653 -?*)
656 printf >&2 '%s\n' "bad non-option argument: $opt"
657 echo >&2 "(Did you perhaps intend to use a --xxx=yyy form?)"
658 exit 1
659 esac
660 [ -z "$opt" ] || set -- "$@" "$opt"
661 done
662 if [ -n "$alwaysredelta" ]; then
663 noreusedeltaopt="--no-reuse-delta"
664 [ -z "$recompress" ] || noreusedeltaopt="--no-reuse-object"
667 trap 'e=$?; rm -f .gc_in_progress; if [ $e != 0 ]; then echo "gc failed dir: $PWD" >&2; fi' EXIT
668 trap 'exit 130' INT
669 trap 'exit 143' TERM
671 # date -R is linux-only, POSIX equivalent is '+%a, %d %b %Y %T %z'
672 datefmt='+%a, %d %b %Y %T %z'
674 isminigc=
675 if [ "${force_gc:-0}" = "0" ] && check_interval lastgc $cfg_min_gc_interval; then
676 if [ -e .needsgc ]; then
677 isminigc=1
678 else
679 progress "= [$proj] garbage check skip (last at $(config_get lastgc))"
680 exit 0
683 if [ -e .nogc ]; then
684 progress "x [$proj] garbage check disabled"
685 exit 0
687 if ! [ -e .nofetch ] && [ -e .clone_in_progress ] && ! [ -e .clone_failed ]; then
688 progress "x [$proj] garbage check disabled (clone in progress)"
689 exit 0
691 if [ -z "$isminigc" ] && [ -e .delaygc ] && [ -e .needsgc ]; then
692 # Eligible for a full gc but .delaygc is set so it would be skipped
693 # However .needsgc is also set so transform it into a mini instead
694 isminigc=1
695 progress "~ [$proj] garbage check delayed but checking mini because .needsgc"
698 if [ -n "$isminigc" ]; then
699 # Perform a "mini" gc
700 # Note that .delaygc is ignored here as that's only intended for full gc
701 lock_gc
702 rm -f .allowgc .needsgc
703 rm -f objects/pack/pack-*_[rful].keep
704 remove_crud
705 coalesce_reflogs
706 prune_reflogs
707 compact_reflogs
708 maintain_auto_gc_hack
709 generate_auto_gc_update
710 miniactive=
711 if [ -f .needspack ]; then
712 miniactive=1
713 progress "+ [$proj] mini garbage check ($(date))"
714 make_needs_pack
716 if [ -z "$cfg_delay_gfi_redelta" ] && [ -n "$gfi_mirror" ]; then
717 # $Girocco::Config::delay_gfi_redelta is false, force redeltification now
718 if [ -z "$miniactive" ]; then
719 miniactive=1
720 progress "+ [$proj] mini garbage check ($(date))"
722 repack_gfi_packs
724 if lotsa_loose_objects; then
725 if [ -z "$miniactive" ]; then
726 miniactive=1
727 progress "+ [$proj] mini garbage check ($(date))"
729 pack_loose_objects
731 # If there aren't at least 10 non-keep, non-bitmap, non-bndl packs then
732 # don't actually process them yet
733 lpo="--exclude-no-idx --exclude-keep --exclude-bitmap --exclude-bndl --quiet"
734 packcnt="$(list_packs --count $lpo objects/pack)" || :
735 if [ "${packcnt:-0}" -ge 10 ]; then
736 if [ -z "$miniactive" ]; then
737 miniactive=1
738 progress "+ [$proj] mini garbage check ($(date))"
740 # if we have at least 10 packs go ahead and pack all refs now too
741 git pack-refs --all --prune
742 if [ -n "$gfi_mirror" ]; then
743 repack_gfi_packs
744 packcnt="$(list_packs --count $lpo objects/pack)" || :
746 # if repack_gfi_packs dropped the pack count to < 10 don't combine
747 if [ "${packcnt:-0}" -ge 10 ]; then
748 combine_small_packs
749 combine_small_loose_packs
750 packcnt="$(list_packs --count $lpo objects/pack)" || :
752 # if we still have more than 10 packs trigger a full gc
753 if [ "${packcnt:-0}" -ge 10 ]; then
754 # We shouldn't be in a .delaygc state at this point, but if
755 # we are then nuke it because we really need a full gc now
756 rm -f .delaygc
757 git config --unset gitweb.lastgc
758 rm -f "$lockf"
759 git update-server-info # just in case
760 progress "- [$proj] mini garbage check triggering full gc too many packs ($(date))"
761 exit 0
764 rm -f "$lockf"
765 if [ -n "$miniactive" ]; then
766 git update-server-info
767 progress "- [$proj] mini garbage check ($(date))"
768 else
769 progress "= [$proj] mini garbage check nothing but crud removal to do ($(date))"
771 exit 0
774 # Avoid unnecessary garbage collections:
775 # 1. If lastreceive is set and is older than lastgc
776 # -AND-
777 # 2. We are not a fork (is_empty_alternates_file) -OR- lastparentgc is older than lastgc
779 # If lastgc is NOT set or lastreceive is NOT set we MUST run gc
780 # If we are a fork and lastparentgc is NOT set we MUST run gc
782 # If the repo is dirty after removing any crud we MUST run gc
784 gcstart="$(date "$datefmt")"
785 skipgc=
786 isfork=
787 is_empty_alternates_file objects/info/alternates || isfork=1
788 lastparentgcsecs=
789 [ -z "$isfork" ] || lastparentgcsecs="$(config_get_date_seconds lastparentgc)" || :
790 lastreceivesecs=
791 if lastreceivesecs="$(config_get_date_seconds lastreceive)" &&
792 [ "${force_gc:-0}" = "0" ] &&
793 lastgcsecs="$(config_get_date_seconds lastgc)" &&
794 [ $lastreceivesecs -lt $lastgcsecs ]; then
795 # We've run gc since we last received, so maybe we can skip,
796 # check if not fork or fork and lastparentgc < lastgc
797 if [ -n "$isfork" ]; then
798 if [ -n "$lastparentgcsecs" ] &&
799 [ $lastparentgcsecs -lt $lastgcsecs ]; then
800 # We've run gc since our parent ran gc so we can skip
801 skipgc=1
803 else
804 # We don't have any alternates (we're not a forK) so we can skip
805 skipgc=1
809 # Prevent any other simultaneous gc operations
810 lock_gc
812 # At this point, if .allowgc or .gc_failed exists, it's now crud to be removed
813 rm -f .allowgc .gc_failed
815 # Always get rid of crud
816 remove_crud
818 # Ideally we would do this in post-receive, but that would mean duplicating the
819 # logic so it's available in the chroot jail and that's highly undesirable
820 # Instead, since the first gc will be triggered immediately following the first
821 # push, we do the check here as it's quick and harmless if HEAD is already valid
822 check_and_set_head || :
824 # Always perform reflogs maintenance
825 coalesce_reflogs
826 prune_reflogs
827 compact_reflogs
829 # Always maintain auto gc hack
830 maintain_auto_gc_hack
831 generate_auto_gc_update
833 # Run 'git svn gc' now for svn mirrors
834 if [ -n "$svn_mirror" ]; then
835 git svn gc || :
838 # Skip the actual gc if .delaygc is set
839 if [ -e .delaygc ]; then
840 progress "x [$proj] garbage check delayed (except for crud removal)"
841 rm -f "$lockf"
842 exit 0
845 # Do not skip gc if the repo is dirty
846 if [ -n "$skipgc" ] && ! is_dirty; then
847 progress "= [$proj] garbage check nothing but crud removal to do ($(date))"
848 config_set lastgc "$gcstart"
849 rm -f "$lockf"
850 exit 0
853 bumptime=
854 if [ -n "$isfork" ] && [ -z "$lastparentgcsecs" ]; then
855 # set lastparentgc and then update gcstart to be at least 1 second later
856 config_set lastparentgc "$gcstart"
857 bumptime=1
859 if [ -z "$lastreceivesecs" ]; then
860 # set lastreceive and then update gcstart to be at least 1 second later
861 config_set lastreceive "$gcstart"
862 bumptime=1
864 if [ -n "$bumptime" ]; then
865 sleep 1
866 gcstart="$(date "$datefmt")"
869 progress "+ [$proj] garbage check ($(date))"
871 newdeltas=
872 [ -z "$alwaysredelta" ] || newdeltas="$noreusedeltaopt"
873 if [ -z "$newdeltas" ] && [ -n "$gfi_mirror" ]; then
874 if [ $(list_packs --exclude-no-idx --count objects/pack) -le \
875 $(list_packs --exclude-no-idx --count --quiet --only gfi-packs) ]; then
876 # Don't bother with repack_gfi_packs since everything's being repacked
877 newdeltas="--no-reuse-delta"
880 if [ -z "$newdeltas" ] && [ -n "$noreusedeltaopt" ] &&
881 [ $(list_packs --all --exclude-no-idx --count-objects objects/pack) -le $var_redelta_threshold ]; then
882 # There aren't enough objects to worry about so just redelta to get the best pack
883 newdeltas="--no-reuse-delta"
885 if [ -z "$newdeltas" ]; then
886 # Since we're not going to recompute deltas overall, we need to do the
887 # "mini" maintenance so that we can get more optimal deltas
888 [ -z "$noreusedeltaopt" ] || make_needs_pack
889 repack_gfi_packs
890 force_single_pack_redelta=
891 [ -n "$gfi_mirror" ] || [ -n "$svn_mirror" ] || force_single_pack_redelta=1
892 [ -z "$noreusedeltaopt" ] || combine_small_packs $force_single_pack_redelta
893 [ -z "$noreusedeltaopt" ] || combine_small_loose_packs $force_single_pack_redelta
897 ## Safe Pruning In Forks
899 ## We are about to perform garbage collection. We do NOT use the "git gc" or
900 ## the "git repack" commands directly as they do not provide enough control over
901 ## the fine details. However, we DO maintain a "gc.pid" file during our garbage
902 ## collection so that a simultaneous "git gc" by an administrator will be
903 ## blocked (and similarly we refuse to start garbage collection if we cannot
904 ## create the "gc.pid" file).
906 ## When we say "gc" in the below description we are referring to our "gc.sh"
907 ## script, NOT the "git gc" command.
909 ## If the project we are running garbage collection (gc) on has any forks we
910 ## must be careful not to remove any objects that while no longer referenced by
911 ## this project (the parent) are still referenced by one or more forks (the
912 ## children) otherwise the children will become corrupt and we can't abide
913 ## corrupt children.
915 ## One way to accomplish this is to simply hard-link all currently existing
916 ## loose objects and packs in the parent into all the children that refer to the
917 ## parent (via a line in their objects/info/alternates file) before beginning
918 ## the gc operation and then relying on a subsequent gc in the child to clean up
919 ## any excess objects/packs. We used to use this strategy but it's very
920 ## inefficient because:
922 ## 1. The disk space used by the old pack(s)/object(s) will not be reclaimed
923 ## until all children (and their children, if any) run gc by which time
924 ## it's quite possible the topmost parent will have run gc again and
925 ## hard-linked yet another old pack down to its children (not to mention
926 ## loose objects).
928 ## 2. When using the "-A" option with "git repack", any new objects in the
929 ## parent that are not referenced by children will continually get
930 ## exploded out of the hard-linked pack in the children whenever the
931 ## children run gc.
933 ## 3. To avoid suboptimal and/or unnecessarily many packs being hard-linked
934 ## into child forks, we must run the "mini" gc maintenance before we
935 ## perform the hard-linking into the children which provides yet another
936 ## source of inefficiency.
938 ## While we were still using the "-A" option to "git repack" (that was not
939 ## always the case) to guarantee we can access old ref values for long enough
940 ## to send out a meaningful mail.sh notification, another, more efficient,
941 ## option became available to prevent corruption of child forks that continue
942 ## to refer to objects that are no longer reachable from any ref in the parent.
944 ## The only things that need be copied (or hard-linked) into the child fork(s)
945 ## are those objects that have become unreachable from any ref in the parent.
947 ## When we were using the "git repack -A -d" + "git prune --expire=1.day.ago"
948 ## technique, the only objects that could ever be removed were loose objects
949 ## that "git prune" determined were expired. In that case, loose objects were
950 ## all that need be hard-linked down to child forks in order to avoid
951 ## corruption of any child fork(s).
953 ## The "git repack -A -d" + "git prune --expire=1.day.ago" + hard-linking loose
954 ## objects to child forks technique remains fundamentally sound from the
955 ## perspective of supporting simultaneous gc and push and keeping newly
956 ## unreachable objects around long enough to be sure we can send out meaningful
957 ## ref change notifications and never corrupting any child forks and never
958 ## persisting the lifetime of large old packs containing mostly duplicate or
959 ## unreachable objects as gc percolates through a project's entire fork tree.
961 ## However, that technique suffers from one potential prodigious pitfall.
963 ## Unreachable objects come flying out of their packs to splatter all over the
964 ## objects subdirectories possibly creating a huge, inefficient mess.
966 ## Often this is not an issue. Even with a lot of rebasing going on, usually
967 ## the only objects that will splatter are some commits, trees and the odd blob
968 ## here and there. Not enough to be overly concerned about.
970 ## However, for the reppository that frequently experiences a lot of non-fast-
971 ## forward updates and/or outright ref deletion, the number of objects suddenly
972 ## popping out of their packs at "git repack -A -d" time can be overwhelming.
974 ## To avoid this issue we now use a four phase pack creation strategy.
975 ## This will result in creation of up to four packs (instead of at most one).
977 ## I. A complete pack (with bitmaps if appropriate) gets created including
978 ## only "reachable" objects from all refs/... refs plus HEAD. This will
979 ## also serve as the virtual bundle for the repository.
981 ## II. A pack of recently-became-unreachable objects and friends is created.
982 ## (The "friends" are ref logs, linked working tree HEADs and indicies.)
983 ## Because both the pre-receive and update.sh script record all ref
984 ## changes we can easily choose the cut off point for "recently".
985 ## It is only the fact we maintain those logs in the reflogs subdirectory
986 ## that allows this step to be possible.
988 ## III. If the repository has any forks with a non-zero length alternates file,
989 ## yet another pack of "--keep-unreachable" objects is generated that will
990 ## not actually be kept in the parent, but hard-linked into all the forks.
992 ## IV. Finally, after running "git prune-packed", any remaining loose objects
993 ## are migrated into a pack of their own.
995 ## We then remove any non-.keep packs that existed before we started the
996 ## process being careful to keep any same-pack pushes for the "Push Pack Redux"
997 ## race condition (see docs/technical/gc.txt).
999 ## By using "git pack-objects" directly we are able to accomplish this with
1000 ## very little additional effort.
1002 ## The packs produced by (III) are treated almost like ".keep" packs by child
1003 ## forks in that the objects in them are never repacked into any other
1004 ## "--keep-unreachable" packs (but they can migrate into phase I or II packs)
1005 ## and those phase III packs are then hard-linked into any grandchild forks.
1007 ## This avoids the space explosion that could occur if each fork level ended
1008 ## up duplicating the "--keep-unreachable" pack space by repacking those
1009 ## objects (essentially breaking the hard-link to the single copy of those
1010 ## objects).
1012 ## While it is true that each level of forks could potentially add yet another
1013 ## phase III pack to be hard-linked down to its children, such packs will only
1014 ## include unreachable objects not already in any phase III packs that were
1015 ## received from the parent.
1017 ## The space for the phase III packs will not be reclaimed until the gc
1018 ## finishes percolating through the entire "fork tree" of a project.
1020 ## This is not much different than the "git repack -A -d" situation where
1021 ## all the loose objects are hard-linked down into child forks. In that
1022 ## case forks that actually need any of those objects could gradually reduce
1023 ## the number of objects hard-linked into deeper fork levels.
1025 ## The difference with a phase III "--keep-unreachable" pack is that there
1026 ## cannot be any gradual reduction like that since it would require repacking
1027 ## the pack and breaking the hard-link thereby increasing storage space. The
1028 ## storage will instead always be reclaimed all at once when all of the
1029 ## projects in the "fork tree" complete their gc.
1031 ## However, the belief is that the huge space win by having all the
1032 ## unreachable objects packed up together far eclipses (when many objects are
1033 ## involved, the single-pack version can end up using 1/20th or less of the
1034 ## disk space compared to having them all as loose objects) any brief minor
1035 ## space savings that might occur under the "git repack -A -d" loose object
1036 ## system prior to the gc collection completing for all the projects in the
1037 ## "fork tree".
1041 ## utility functions
1044 make_packs_ugw() {
1045 find -L "$1" -maxdepth 1 -type f ! -perm -ug+w \
1046 -name "pack-$octet20*.pack" -exec chmod ug+w '{}' + || :
1047 } 2>/dev/null
1049 get_index_tree() {
1050 if [ -s "$1" ]; then
1051 GIT_INDEX_FILE="$1"
1052 export GIT_INDEX_FILE
1053 git write-tree 2>/dev/null || :
1054 unset GIT_INDEX_FILE
1058 get_detached_head() {
1059 if [ -s "$1" ] && read -r _head <"$1" 2>/dev/null; then
1060 case "$_head" in $octet20*)
1061 echo "$_head"
1062 esac
1066 # single argument must be a top-level GIT_DIR
1067 # output will be (one per line, zero or more lines) full hash
1068 # values (i.e. 40 or more hex digits) from possible detached head
1069 # "single level" refs (e.g. "FETCH_HEAD" "MERGE_HEAD" etc.) from
1070 # files in the specified directory that have a "suitable" name and
1071 # have a length >= 40 and <= 1000 where EVERY line in a file MUST
1072 # match a 40 digit (or longer) hex string or that file will be ignored.
1073 # In a nod to Git each line first has any tab and anything following truncated.
1074 # NO sorting NOR "uniq"ing NOR "--batch-check"ing is performed on the output.
1075 # Also note that "HEAD" is NOT EXCLUDED and if detached will be output!
1076 get_detached_friends() {
1077 if [ -n "$1" ] && [ -d "$1" ]; then
1078 LC_ALL=C find -H "$1" -maxdepth 1 -name '[A-Za-z]*[A-Za-z0-9]' \
1079 -type f -size +39c -size -1001c -exec awk '
1080 BEGIN {exit}
1081 function process(fn, fnt, hashes, hcnt, fl, hi) {
1082 fnt = fn; sub(/^.*\//, "", fnt)
1083 if (length(fnt) > 31 || fnt !~ /^[A-Za-z][A-Za-z0-9_-]*[A-Za-z0-9]$/) return;
1084 hcnt = 0;
1085 while (getline fl < fn) {
1086 sub(/\t.*$/, "", fl)
1087 if (length(fl) < 40 || fl !~ /^[0-9a-fA-F][0-9a-fA-F]*$/) {hcnt = 0; break;}
1088 hashes[++hcnt] = fl;
1090 close(fn)
1091 for (hi=1;hi<=hcnt;++hi) print tolower(hashes[hi]);
1093 END {for (idx=1;idx<ARGC;++idx) process(ARGV[idx])}
1094 ' '{}' '+' 2>/dev/null || :
1098 # get_worktrees_friends
1099 # single argument is a (possibly relative) path to a "worktrees" subdir
1100 # if omitted it defaults to "worktrees"
1101 # any "friends" found in there are output to stdout
1102 get_worktrees_friends() {
1103 if [ -d "${1:-worktrees}" ]; then
1104 find -L "${1:-worktrees}" -mindepth 2 -maxdepth 2 -name HEAD -type f -print |
1105 while read -r _lwth; do
1106 get_detached_head "$_lwth"
1107 get_detached_friends "${_lwth%HEAD}"
1108 get_index_tree "${_lwth%HEAD}index"
1109 done
1113 # compute_extra_reachables
1114 # create lines suitable for a packed-refs file mentioning all the
1115 # other refs we might like to keep.
1116 # the current directory MUST be set to the repository's --git-dir
1117 # the following are included:
1118 # * refs mentioned in repack/packed-refs.extra (if it exists)
1119 # * refs mentioned in reflogs/... files
1120 # * tree(s) created from index file(s)
1121 # * detached linked working tree heads
1122 # Resulting objects are tested for existence and uniqified then output
1123 # one per line under a refs/z* namespace
1124 compute_extra_reachables() {
1126 if [ -s repack/packed-refs.extra ]; then
1127 LC_ALL=C sed <repack/packed-refs.extra -n \
1128 -e 's/^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p' \
1129 -e 's/^\^\([0-9A-Fa-f][0-9A-Fa-f]*\).*$/\1/p'
1131 digits8='[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
1132 find -L reflogs -mindepth 1 -maxdepth 1 -type f -name "$digits8*" -exec gzip -c -d -f '{}' + |
1133 LC_ALL=C awk '{print $2; print $3}'
1134 get_detached_friends .
1135 ! [ -f index ] || get_index_tree index
1136 get_worktrees_friends
1138 is_git_dir private &&
1139 [ "$(cd objects && pwd -P)" = "$(cd private/objects && pwd -P)" ] &&
1140 [ "$(cd refs && pwd -P)" != "$(cd private/refs && pwd -P)" ]
1141 then
1142 git --git-dir=private show-ref --head --hash 2>/dev/null || :
1143 get_detached_friends private
1144 ! [ -f private/index ] || get_index_tree private/index
1145 get_worktrees_friends private/worktrees
1147 } | LC_ALL=C sort -u |
1148 git cat-file ${var_have_git_260:+--buffer} --batch-check"${var_have_git_185:+=%(objectname)}" |
1149 LC_ALL=C awk '!/missing/ {num++; print $1 " " "refs/" substr("zzzzzzzzzzzz", 1, length(num)) "/" num}'
1153 ## main gc logic
1156 # Everything else is more efficient if we do this first
1157 # The "--prune" option is the default since v1.5.0 but it serves as "documentation" here
1158 git pack-refs --all --prune
1159 [ -e packed-refs ] || >>packed-refs # should never happen...
1161 # If we have a logs directory or a worktrees directory expire the ref logs now
1162 # Note that Git itself does not use either --rewrite or --updateref, so neither do we
1163 ! [ -d logs ] && ! [ -d worktrees ] || eval git reflog expire --all "${quiet:+>/dev/null 2>&1}" || :
1165 make_repack_dir
1166 ! [ -e .gc_failed ] || exit 1
1167 rm -f .gc_in_progress # make sure
1168 touch .gc_in_progress # it's truly fresh
1169 rm -f bundles/* objects/pack/pack-*.bndl
1170 # These only exist for a brief time before the packs loose their _f suffix
1171 # "Push Pack Redux" does not apply to these since they were only ever present with _f
1172 rm -f objects/pack/pack-*_f.keep
1173 # This is perhaps a bit aggressive in that if we're suffering from "Push Pack Redux"
1174 # and somehow we get run again immediately after the run where "Push Pack Redux" happened
1175 # and we have garbage collection forced, there's just the barest, almost negligible,
1176 # possibility that the "Push Pack Redux" ref updates _still_ have not happened and we
1177 # should not be removing _r .keep files. None of the normal Girocco processing can
1178 # cause this. The second run of this script would have to use the force gc option
1179 # for it to even be possible in the first place. What's much more likely is that
1180 # the initial run of this script was somehow interrupted in the middle before it
1181 # could get rid of the _r .keep file itself in which case it's better to get rid of
1182 # it now to avoid keeping something around that would perturb our nice and neat gc
1183 rm -f objects/pack/pack-*_r.keep
1184 # We will add .keep files for _u and _l packs if and when we run phase III
1185 # Otherwise they need to not have any .keep files during phases I and II
1186 rm -f objects/pack/pack-*_[ul].keep
1188 # We need to make sure that any non-Girocco (barely tolerated) Git object creation
1189 # activity will be able to "freshen" the pack containing a pre-existing object
1190 # that's being written. This really should not be necessary as the pre-receive
1191 # hook should make sure this takes place for any incoming pushes.
1192 # However, do it here anyway just in case.
1193 make_packs_ugw objects/pack
1195 # This is only effective with Git v2.3.5 and later and it will only matter when
1196 # we are using one of the "internal_rev_list" modes of pack-objects
1197 # (the combine-packs.sh script never uses any of those modes)
1198 # The "git repack" and "git prune" commands always set this internally themselves
1199 # It makes no difference if there's no repository corruption
1200 GIT_REF_PARANOIA=1 && export GIT_REF_PARANOIA
1202 # All of the options we might want to use with pack-objects were supported
1203 # at some point prior to Git version v1.6.6 which is the minimum version that
1204 # Girocco now requires. Except for one (--use-bitmap-index). Several of them
1205 # are "boiler plate" options we always want to use so we bundle them up here.
1206 pkopt="--delta-base-offset --keep-true-parents --non-empty --all-progress-implied"
1207 # We want to use --include-tag, but before Git v2.10.1 it would leave out
1208 # "middle" tags (e.g. a tag of a tag of a commit would omit the tagged tag)
1209 # See http://repo.or.cz/git.git/b773ddea2cd3b08c for details
1210 # ("pack-objects: walk tag chains for --include-tag", 2016-09-07, v2.10.1)
1211 # This is not a free check as it matches all refs against refs/tags/ then
1212 # peels all the annotated tags and checks for inclusion. The situation in
1213 # which it would add a tag that was not already included by a reachability
1214 # trace that included tag starting points can only occur if a new tag gets
1215 # pushed during gc pointing to something that would have been packed anyway.
1216 # But, it could happen and, really, compared to gc as a whole it's not that
1217 # expensive to perform (provided we do not get an unconnected pack).
1218 [ -z "$var_have_git_2101" ] || pkopt="$pkopt --include-tag"
1219 pkopt="$pkopt ${quiet:---progress} $packopts"
1221 # The git pack-objects command only supports bitmaps if all objects are being
1222 # packed (the "--all" option) and the "--stdout" option is NOT being used.
1223 # Additionally, while packing, if any encountered reachable objects are
1224 # determined to be "not wanted" then no bitmap index will be written anyway.
1225 # While it is theoretically possible that a project with a non-empty alternates
1226 # file ends up packing all objects (because it does not actually use any of the
1227 # objects found in the alternates), it's very unlikely. And, in the unlikely
1228 # event that did occur, clients would see a message about only using one bitmap
1229 # because Git can only use one bitmap at a time and at least one of the
1230 # alternates is bound to have a bitmap. Therefore if we see a non-empty
1231 # alternates file, we disable writing bitmaps which avoids the warning and any
1232 # possibility of a client warning as well. Also if we are running anything
1233 # before Git v2.1.0 (the effective version for repack.writeBitmaps=true) then
1234 # we also always disable bitmap writing.
1235 wbmopt=
1236 [ -z "$var_have_git_210" ] || wbmopt="--write-bitmap-index"
1237 # More recent versions of pack-objects have optimizations when not using the
1238 # --local option. If we do not have any alternates it's a pointless option.
1239 # If we do have alternates we need to skip writing a bitmap and we cannot
1240 # have a bundle since it must contain all objects.
1241 if [ -n "$isfork" ]; then
1242 lclopt="--local"
1243 wbmopt=
1244 makebndl=
1245 else
1246 lclopt=
1247 makebndl=1
1251 ## Phase I
1254 wbmstr=
1255 [ -n "$wbmopt" ] || wbmstr=" (bitmaps disabled)"
1256 progress "~ [$proj] running primary full gc pack-objects$wbmstr ($(date))"
1258 gotforks=
1259 ! has_forks_with_alternates "$proj" || gotforks=1
1261 # To avoid "Push Pack Redux" (see docs/technical/gc.txt), after collecting the
1262 # initial preexisting non-keep pack list, we rename them so that an incoming push
1263 # pack cannot possibly experience a pack name collision. Git does not require
1264 # use of the "default" pack names, simply that the proper extensions are used.
1265 # We rename to insert an "_r" just before the extension to avoid "Push Pack Redux"
1266 # name collisions. Later on we may create an "unreachable" pack for hard-linking
1267 # down into forks and it will have an "_u" inserted just before its extension.
1268 packlist="$(list_packs -C objects/pack --all --exclude-no-idx --exclude-keep --quiet .)" || :
1269 oldpacks=
1270 for oldpack in $packlist; do
1271 oldpack="${oldpack%.pack}"
1272 [ -f "objects/pack/$oldpack.pack" ] || {
1273 echo >&2 "[$proj] unable to list old pack files"
1274 exit 1
1276 case "$oldpack" in pre-auto-gc-[12])
1277 # we never disturb pre-auto-gc-1 or pre-auto-gc-2 packs
1278 continue
1279 esac
1280 oldpackhex="${oldpack#pack-}"
1281 if [ "${oldpackhex#*[!0-9a-fA-F]}" != "$oldpackhex" ]; then
1282 # names not exclusively hexadecimal do not need renaming
1283 case "$oldpack" in
1284 pack-$octet20*_l)
1285 # _l packs are treated like still-unpacked loose objects
1286 continue;;
1287 *_f)
1288 # _f packs can only be left over from a previously interrupted gc;
1289 # they need to be renamed to _r now so they're not confused with
1290 # any freshly generated "final" packs (and we already removed
1291 # any pre-existing *_f.keep files so we're good to go)
1294 oldpacks="${oldpacks:+$oldpacks }$oldpack"
1295 continue;;
1296 esac
1298 rename_pack "objects/pack/$oldpack" "objects/pack/${oldpack%_f}_r" || {
1299 echo >&2 "[$proj] unable to rename old pack files"
1300 exit 1
1302 # If the oldpack has a .keep now it means a "Push Pack Redux" is actually
1303 # in progress at this moment and we need to .keep the renamed pack,
1304 # otherwise no "Push Pack Redux" has started yet or it has already finished.
1305 # In either case we're okay because if it's just finished then all ref
1306 # changes have already been made so we don't need a .keep and we will
1307 # see the ref changes and grab all the objects via a reachability trace.
1308 # If it hasn't started yet that's okay because we're done moving that
1309 # name so a complete pack will appear under the old name that we'll
1310 # leave alone.
1311 if [ -f "objects/pack/$oldpack.keep" ]; then
1312 echo "Push Pack Redux" >"objects/pack/${oldpack%_f}_r.keep"
1313 else
1314 oldpacks="${oldpacks:+$oldpacks }${oldpack%_f}_r"
1316 done
1318 # We wish to keep deltas from our last full pack so if we're not redeltaing
1319 # then make sure the .pack associated with the .bitmap has a newer mod time
1320 # (If there is no .bitmap then touch the pack with the most objects instead.)
1321 if [ -z "$newdeltas" ]; then
1322 bmpack="$(list_packs --exclude-no-bitmap --exclude-no-idx --max-matches 1 objects/pack)"
1323 [ -n "$bmpack" ] || bmpack="$(list_packs --exclude-no-idx --max-matches 1 --object-limit -1 --include-boundary objects/pack)"
1324 if [ -n "$bmpack" ] && [ -f "$bmpack" ] && [ -s "$bmpack" ]; then
1325 sleep 1
1326 touch -c "$bmpack" 2>/dev/null || :
1327 # We must touch .gc_in_progress here to avoid $bmpack looking
1328 # like it's been "freshened" when redundant packs are removed
1329 # It's okay if they have the same mod time, but POSIX does not
1330 # guarantee an ordering for the "touching" that occurs which is
1331 # why this must be a separate command but needs no "sleep 1"
1332 touch .gc_in_progress
1336 # Now we need to make sure that any "freshening" that takes place will actually
1337 # result in a "newer" modification time than the .gc_in_progress file now has
1338 sleep 1
1340 # We run git pack-objects from the repack subdirectory so we can force
1341 # optimized packs to be generated even for repositories that do not have any
1342 # tagged commits
1343 packs="$(git --git-dir=repack pack-objects </dev/null \
1344 $pkopt --all $newdeltas $lclopt ${wbmopt:---honor-pack-keep} "$@" repack/alt/pack/pack)"
1345 v_cnt packcnt $packs
1346 [ $packcnt -eq 1 ] || makebndl=
1349 ## Phase II
1352 progress "~ [$proj] running supplementary gc pack-objects ($(date))"
1354 # Add the "supplementary" refs
1355 compute_extra_reachables >>repack/packed-refs
1357 # Subtract the primary refs
1358 GIT_ALTERNATE_OBJECT_DIRECTORIES="$PWD/repack/alt"
1359 export GIT_ALTERNATE_OBJECT_DIRECTORIES
1361 # For this one we MUST use --local and MUST NOT use --write-bitmap-index
1362 # However, if there is a "logs" subdirectory we need to use --reflog
1363 # We do add it, just in case, if the linked working trees dir is present
1364 # We do not add --indexed-objects as that requires v2.2.0 and it's unclear
1365 # if it properly includes linked working tree index files or not. The
1366 # above compute_extra_reachables has already included all index trees (thereby
1367 # providing proper --indexed-objects support for all Git versions) making the
1368 # option completely unnecessary.
1369 rflopt=
1370 ! [ -d logs ] && ! [ -d worktrees ] || rflopt=--reflog
1371 spacks="$(git --git-dir=repack pack-objects </dev/null \
1372 $pkopt --honor-pack-keep --all $rflopt $newdeltas --local "$@" repack/alt/pack/pack)"
1375 ## Phase III
1378 # There's nothing to do for Phase III unless we have forks that refer to our
1379 # project from their alternates file
1380 hlpacks=
1381 upacks=
1382 if [ -n "$gotforks" ]; then
1384 progress "~ [$proj] running keep-unreachable gc pack-objects for forks ($(date))"
1386 # If we are a fork, any pre-existing _u packs need to have a .keep
1387 # for this phase and be added to the hlpacks list otherwise (we are
1388 # not a fork) pre-existing _u packs are anomalies to be treated like
1389 # regular non-_u packs
1390 if [ -n "$isfork" ]; then
1391 for upack in $(find -L objects/pack -mindepth 1 -maxdepth 1 -name "pack-$octet20*_[ul].pack" -print); do
1392 upack="${upack%.pack}"
1393 [ -e "$upack.keep" ] || echo "unreachable" >"$upack.keep"
1394 case "$upack" in *_l);;*)
1395 hlpacks="${hlpacks:+$hlpacks }${upack#objects/pack/pack-}"
1396 esac
1397 done
1399 # Using either --no-reuse-delta or --no-reuse-object together with the
1400 # --keep-unreachable option is a very, very, very bad idea when good
1401 # packs are the desired outcome. If newdeltas are being generated
1402 # then we pack to a temp name, and use combine-packs.sh to get a better
1403 # pack as the result to avoid making a bad --keep-unreachable pack
1404 pfx=
1405 [ -z "$newdeltas" ] || pfx="ku"
1406 upacks="$(git --git-dir=repack pack-objects </dev/null \
1407 $pkopt --honor-pack-keep --all $rflopt --keep-unreachable --local "$@" repack/alt/pack/${pfx}pack)"
1408 if [ -n "$upacks" ] && [ -n "$newdeltas" ]; then
1409 progress "~ [$proj] rebuilding keep-unreachable pack deltas"
1410 oldupacks="$upacks"
1411 upacks="$(
1412 printf "repack/alt/pack/${pfx}pack-%s.pack\n" $oldupacks |
1413 run_combine_packs --names --weak-naming --non-empty --all-progress-implied ${quiet:---progress} \
1414 $packopts $newdeltas "$@" repack/alt/pack/pack)"
1415 eval rm -f "$(printf \""repack/alt/pack/${pfx}pack-%s.*"\"" " $oldupacks)"
1417 for upack in $upacks; do
1418 rename_pack "repack/alt/pack/pack-$upack" "repack/alt/pack/pack-${upack}_u"
1419 done
1420 rm -f objects/pack/pack-*_[ul].keep
1421 [ -z "$hlpacks" ] && [ -z "$upacks" ] ||
1422 progress "~ [$proj] hard-linking keep-unreachable pack(s) into immediate child forks"
1424 # We have to update the lastparentgc time in the child forks even if they do not get any
1425 # new "unreachable packs" because they need to run gc just in case the parent now has some
1426 # objects that used to only be in the child so they can be removed from the child.
1427 # For example, a "patch" might be developed first in a fork and then later accepted into
1428 # the parent in which case the objects making up the patch in the child fork are now
1429 # redundant (since they're now in the parent as well) and need to be removed from the
1430 # child fork which can only happen if the child fork runs gc.
1431 lastparentgc="$(date "$datefmt")"
1433 # It is enough to copy objects just one level down and get_repo_list
1434 # takes a regular expression (which is automatically prefixed with '^')
1435 # so we can easily match forks exactly one level down from this project
1436 forkdir="$proj"
1437 get_repo_list "$forkdir/[^/:][^/:]*:" |
1438 while read fork; do
1439 # Ignore forks that do not exist or are symbolic links
1440 ! [ -L "$cfg_reporoot/$fork.git" ] && [ -d "$cfg_reporoot/$fork.git" ] ||
1441 continue
1442 # Or have an empty alternates file
1443 ! is_empty_alternates_file "$cfg_reporoot/$fork.git/objects/info/alternates" ||
1444 continue
1445 runupdate=
1446 # Match hlpacks in parent project if any
1447 if [ -n "$hlpacks" ]; then
1448 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1449 eval ln -f "$(printf '"objects/pack/pack-%s.pack" ' $hlpacks)" \
1450 "$(printf '"objects/pack/pack-%s.idx" ' $hlpacks)" \
1451 '"$cfg_reporoot/$fork.git/objects/pack/"'
1452 runupdate=1
1454 # Match upacks in repack/alt area if any
1455 if [ -n "$upacks" ]; then
1456 mkdir -p "$cfg_reporoot/$fork.git/objects/pack"
1457 eval ln -f "$(printf '"repack/alt/pack/pack-%s_u.pack" ' $upacks)" \
1458 "$(printf '"repack/alt/pack/pack-%s_u.idx" ' $upacks)" \
1459 '"$cfg_reporoot/$fork.git/objects/pack/"'
1460 runupdate=1
1462 if ! [ -e "$cfg_reporoot/$fork.git/.needsgc" ]; then
1463 # Trigger a mini gc in the fork if it now has too many packs
1464 packs="$(list_packs --quiet --count --exclude-no-idx --exclude-keep "$cfg_reporoot/$fork.git/objects/pack")" || :
1465 if [ -n "$packs" ] && [ "$packs" -ge 20 ]; then
1466 >"$cfg_reporoot/$fork.git/.needsgc"
1469 [ -z "$runupdate" ] || git --git-dir="$cfg_reporoot/$fork.git" update-server-info
1470 # Update the fork's lastparentgc date (must be more recent than $gcstart)
1471 git --git-dir="$cfg_reporoot/$fork.git" config gitweb.lastparentgc "$lastparentgc"
1472 done
1475 # Now move any primary/supplementary packs back into objects/pack
1476 # then drop any "unfreshened" redundant packs and clear repack/alt
1478 # First make sure the primary pack(s) have the most recent mod time
1479 if [ -n "$packs" ]; then
1480 [ -z "$spacks" ] || sleep 1
1481 printf 'repack/alt/pack/pack-%s.pack\n' $packs | xargs touch -c 2>/dev/null || :
1484 # Move the packs into place but with a _f suffix and a .keep file for now
1485 for pack in $packs $spacks; do
1486 rename_pack "repack/alt/pack/pack-$pack" "objects/pack/pack-${pack}_f"
1487 [ -e "objects/pack/pack-${pack}_f.keep" ] ||
1488 echo "final" >"objects/pack/pack-${pack}_f.keep"
1489 done
1491 # It's possible that one of the $oldpacks had a .bitmap, got renamed (along
1492 # with its .bitmap) and then got "freshened" causing us to not remove it
1493 # However, if $wbmopt is set we most likely now have TWO .bitmap packs!
1494 # This can produce ugly warnings we don't want and possibly get the wrong
1495 # bitmap used since only one .bitmap file can ever be used by Git.
1496 # If this has happened, the .bitmap we want to discard will always have
1497 # an _r suffix so we can just zap any such now since it will leave the pack.
1498 [ -z "$wbmopt" ] || rm -f objects/pack/pack-*_r.bitmap || :
1500 # Remove the redundant packs that have not since been "freshened"
1501 # This does not completely eliminate the race condition window (Girocco's own
1502 # activites -- gc/fetch/receive are immune to the race) but it substantially
1503 # shrinks it down to just the time after the find but before the following rm
1504 >repack/oldpacks
1505 [ -z "$oldpacks" ] ||
1506 printf 'objects/pack/%s.pack\n' $oldpacks |
1507 LC_ALL=C sort >repack/oldpacks
1508 find -L objects/pack -maxdepth 1 -type f -name "pack-$octet20*.pack" -newer .gc_in_progress -print |
1509 LC_ALL=C sort >repack/freshened
1510 deadpacks="$(LC_ALL=C join -v 1 repack/oldpacks repack/freshened | LC_ALL=C sed 's/\.pack$//')"
1511 [ -z "$deadpacks" ] ||
1512 eval echo "$(printf '"%s".* ' $deadpacks)" | xargs rm -f || :
1514 # No need for this anymore
1515 rm -rf repack/alt objects/pack/repack
1516 unset GIT_ALTERNATE_OBJECT_DIRECTORIES
1519 ## Phase IV
1522 progress "~ [$proj] running gc prune-packed"
1524 # We do not want the redundant packs or any new "--keep-unreachable" pack(s) to be
1525 # present while running prune-packed. We try to guarantee that any loose object
1526 # (or any object present in a pack with an _l suffix which was created by mini gc)
1527 # that's unreachable persists for at least one $Girocco::Config::min_gc_interval
1528 # (not withstanding administrator interference to force earlier gc to occur).
1529 # If we were to include the redundant/keep-unreachable pack(s) when running
1530 # prune-packed and a loose unreachable object happened to be duplicated in one
1531 # of them we would end up removing it too soon and void our guarantee.
1532 git prune-packed $quiet
1534 progress "~ [$proj] running loose objects gc pack-objects ($(date))"
1536 # Although Git v2.10.0 and later support a --pack-loose-unreachable option,
1537 # we MUST NOT use it for these reasons:
1538 # 1) We're not interested in expensive "unreachable" at this point, only "loose"
1539 # 2) It produces simply horrid packs about 3.8x times larger than they should be
1540 # 3) We don't require anything more than Git v1.6.6
1541 # The only way we could see any _o pack files at this point is if one got
1542 # "freshened" while we were running gc. If that happens then it gets to live on
1543 # until the next full gc and we need to include it in the loose repack here.
1544 lpacks="$(list_packs --exclude-no-idx --exclude-no-sfx _l --exclude-no-sfx _o --quiet objects/pack |
1545 run_combine_packs --replace --names --loose --weak-naming --non-empty --honor-pack-keep \
1546 --all-progress-implied ${quiet:---progress} $packopts $newdeltas "$@")"
1548 if [ -n "$lpacks" ]; then
1549 # Make sure any primary pack(s) have a more recent mod time than "unreachable" objects packs
1550 if [ -n "$packs" ]; then
1551 sleep 1
1552 printf 'objects/pack/pack-%s_f.pack\n' $packs | xargs touch -c 2>/dev/null || :
1554 # We need to identify these packs later so we don't combine_packs them
1555 for objpack in $lpacks; do
1556 rename_pack "objects/pack/pack-$objpack" "objects/pack/pack-${objpack}_o" || :
1557 done
1560 # Polish up the final packs now
1561 rm -f objects/pack/pack-*_f.keep
1562 for pack in $packs $spacks; do
1563 rename_pack "objects/pack/pack-${pack}_f" "objects/pack/pack-$pack"
1564 done
1566 if [ -n "$lpacks" ]; then
1567 # Finally zap the corresponding loose objects
1568 progress "~ [$proj] running packed loose objects gc prune-packed"
1569 git prune-packed $quiet
1572 ! [ -e .gc_failed ] || exit 1
1573 # These, if they exist, are now meaningless and need to be removed
1574 rm -f gfi-packs .needsgc .needspack .needspackgc
1576 # Make sure this stays up to date
1577 git update-server-info
1579 # We must make loose objects group writable so that they
1580 # can be freshened by other pushers. Technically we need only do this for
1581 # push projects but to enable mirror projects to be more easily converted to
1582 # push projects, we go ahead and do it for all projects.
1583 # By the time we get here we really shouldn't have any of these, but just in case.
1584 { find -L objects/$octet -type f -name "$octet19*" -exec chmod ug+w '{}' + || :; } 2>/dev/null
1586 # darcs mirrors have a xxx.log file that will grow endlessly
1587 # if this is a mirror and the file exists, shorten it to 10000 lines
1588 # also take this opportunity to optimize the darcs repo
1589 if ! [ -e .nofetch ] && [ -n "$cfg_mirror" ]; then
1590 url="$(config_get baseurl)" || :
1591 case "$url" in darcs://* | darcs+http://* | darcs+https://*)
1592 if [ -n "$cfg_mirror_darcs" ]; then
1593 url="${url%/}"
1594 basedarcs="$(basename "${url#darcs*:/}")"
1595 if [ -f "$basedarcs.log" ]; then
1596 tail -n 10000 "$basedarcs.log" >"$basedarcs.log.$$"
1597 mv -f "$basedarcs.log.$$" "$basedarcs.log"
1599 if [ -d "$basedarcs.darcs" ]; then
1601 cd "$basedarcs.darcs"
1602 # without show_progress suppress non-error output
1603 [ "${show_progress:-0}" != "0" ] || exec >/dev/null
1604 # Note that this does not optimize _darcs/inventories/ :(
1605 darcs optimize || :
1609 esac
1612 # Create a matching .bndl header file for the all-in-one pack we just created
1613 # but only if we're not a fork (otherwise the bundle would not be complete)
1614 # and we are running at least Git version 1.7.2 (pack_is_complete always fails otherwise)
1615 if [ -n "$makebndl" ] && [ -n "$var_have_git_172" ]; then
1616 # There should only be one pack in $packs but do some checking...
1617 # The one we just created will have a .idx and will NOT have a .keep
1618 progress "~ [$proj] creating downloadable bundle header"
1619 pkbase=
1620 pkhead=
1621 IFS= read -r curhead <repack/HEAD.orig || :
1623 [ -s "objects/pack/pack-$packs.pack" ] &&
1624 [ -s "objects/pack/pack-$packs.idx" ] &&
1625 ! [ -e "objects/pack/pack-$packs.keep" ] &&
1626 pkhead="$(pack_is_complete "$PWD/objects/pack/pack-$packs.pack" \
1627 "$PWD/repack/packed-refs.orig" "$curhead")"
1628 then
1629 pkbase="objects/pack/pack-$packs"
1631 if [ -n "$pkbase" ] && [ -n "$pkhead" ]; then
1633 symref=
1634 case "$curhead" in "ref: refs/"?*|"ref:refs/"?*|"refs/"?*)
1635 symref="${curhead#ref:}"
1636 symref="${symref# }"
1637 esac
1638 bndlurl=
1639 [ -z "$cfg_httpbundleurl" ] || bndlurl=" url=$cfg_httpbundleurl/$proj.git/clone.bundle"
1640 echo "# v2 git bundle"
1641 LC_ALL=C sed -ne "/^$octet20$hexdig* refs\/[^ $tab]*\$/ p" <repack/packed-refs.orig
1642 if [ -n "$symref" ]; then
1643 printf "$pkhead HEAD\0symref=HEAD:%s%s\n" "$symref" "$bndlurl"
1644 else
1645 if [ -n "$bndlurl" ]; then
1646 printf "$pkhead HEAD\0%s\n" "${bndlurl# }"
1647 else
1648 echo "$pkhead HEAD"
1651 echo ""
1652 } >"$pkbase.bndl"
1653 bndletag="$("$cfg_basedir/bin/rangecgi" --etag -m 1 "$pkbase.bndl" "$pkbase.pack")" || :
1654 bndlsha="$(printf '%s' "$bndletag" | git hash-object --stdin)" || :
1655 if [ -n "$bndletag" ]; then
1656 case "$bndlsha" in $octet20*)
1657 bndlshatrailer="${bndlsha#????????}"
1658 bndlshaprefix="${bndlsha%$bndlshatrailer}"
1659 bndlname="$(TZ=UTC date +%Y%m%d_%H%M%S)-${bndlshaprefix:-0}"
1660 [ -d bundles ] || mkdir bundles
1661 echo "${pkbase#objects/pack/}.bndl" >"bundles/$bndlname"
1662 echo "${pkbase#objects/pack/}.pack" >>"bundles/$bndlname"
1663 ln -s -f -n "$bndlname" bundles/latest
1664 esac
1669 # Record the size of this repo as the sum of its clone packed-refs + *.pack sizes as 1024-byte blocks
1670 eval "reposizek=$(( $(
1671 echo 0 $(du -k repack/packed-refs.orig $(printf 'objects/pack/pack-%s.pack ' $packs) 2>/dev/null |
1672 LC_ALL=C awk '{print $1}') |
1673 LC_ALL=C sed -e 's/ / + /g') ))"
1674 config_set_raw girocco.reposizek "${reposizek:-0}"
1676 # Now we're finally done with this
1677 rm -rf repack
1679 # We didn't used to do anything about rerere or worktrees but we're
1680 # trying to make nice with linked working trees these days :)
1681 # Maybe even non-bare repositories too, but *shush* about those ;)
1682 if [ -n "$var_have_git_250" ] && [ -d worktrees ]; then
1683 # The value "3.months.ago" is hard-coded into gc.c rather than
1684 # having the default be in worktree.c so we must provide it if
1685 # we get nothing out of the gc.worktreePruneExpire config item
1686 # Prior to Git v2.6.0 the config item was gc.pruneworktreesexpire
1687 # however we just always use the newer name no matter what Git version
1688 expiry="$(git config --get gc.worktreePruneExpire 2>/dev/null)" || :
1689 eval git worktree prune --expire '"${expiry:-3.months.ago}"' "${quiet:+>/dev/null 2>&1}" || :
1691 # git rerere does it right and handles its own default/config'd expiration values
1692 ! [ -d rr-cache ] || eval git rerere gc "${quiet:+>/dev/null 2>&1}" || :
1694 # We use $gcstart here to avoid a race where a push occurs during the gc itself
1695 # and the next future gc could be incorrectly skipped if we used the current
1696 # timestamp here instead
1697 config_set lastgc "$gcstart"
1698 rm -f "$lockf"
1700 progress "- [$proj] garbage check ($(date))"