Git gc что это
Перейти к содержимому

Git gc что это

  • автор:

Git gc что это

Changes in the git-gc manual

  1. 2.43.0 11/20/23
  2. 2.42.1 no changes
  3. 2.42.0 08/21/23
  4. 2.41.0 06/01/23
  5. 2.38.1 → 2.40.1 no changes
  6. 2.38.0 10/02/22
  7. 2.37.1 → 2.37.7 no changes
  8. 2.37.0 06/27/22
  9. 2.31.1 → 2.36.6 no changes
  10. 2.31.0 03/15/21
  11. 2.30.1 → 2.30.9 no changes
  12. 2.30.0 12/27/20

Check your version of git by running

NAME

git-gc — Cleanup unnecessary files and optimize the local repository

SYNOPSIS

git gc [--aggressive] [--auto] [--quiet] [--prune= | --no-prune] [--force] [--keep-largest-pack]

DESCRIPTION

Runs a number of housekeeping tasks within the current repository, such as compressing file revisions (to reduce disk space and increase performance), removing unreachable objects which may have been created from prior invocations of git add, packing refs, pruning reflog, rerere metadata or stale working trees. May also update ancillary indexes such as the commit-graph.

When common porcelain operations that create objects are run, they will check whether the repository has grown substantially since the last maintenance, and if so run git gc automatically. See gc.auto below for how to disable this behavior.

Running git gc manually should only be needed when adding objects to a repository without regularly running such porcelain commands, to do a one-off repository optimization, or e.g. to clean up a suboptimal mass-import. See the «PACKFILE OPTIMIZATION» section in git-fast-import[1] for more details on the import case.

OPTIONS

—aggressive

Usually git gc runs very quickly while providing good disk space utilization and performance. This option will cause git gc to more aggressively optimize the repository at the expense of taking much more time. The effects of this optimization are mostly persistent. See the «AGGRESSIVE» section below for details.

With this option, git gc checks whether any housekeeping is required; if not, it exits without performing any work.

See the gc.auto option in the «CONFIGURATION» section below for how this heuristic works.

Once housekeeping is triggered by exceeding the limits of configuration options such as gc.auto and gc.autoPackLimit , all other housekeeping tasks (e.g. rerere, working trees, reflog…​) will be performed as well.

When expiring unreachable objects, pack them separately into a cruft pack instead of storing them as loose objects. —cruft is on by default.

When packing unreachable objects into a cruft pack, limit the size of new cruft packs to be at most bytes. Overrides any value specified via the gc.maxCruftSize configuration. See the —max-cruft-size option of git-repack[1] for more.

Prune loose objects older than date (default is 2 weeks ago, overridable by the config variable gc.pruneExpire ). —prune=now prunes loose objects regardless of their age and increases the risk of corruption if another process is writing to the repository concurrently; see «NOTES» below. —prune is on by default.

Do not prune any loose objects.

Suppress all progress reports.

Force git gc to run even if there may be another git gc instance running on this repository.

All packs except the largest non-cruft pack, any packs marked with a .keep file, and any cruft pack(s) are consolidated into a single pack. When this option is used, gc.bigPackThreshold is ignored.

AGGRESSIVE

When the —aggressive option is supplied, git-repack[1] will be invoked with the -f flag, which in turn will pass —no-reuse-delta to git-pack-objects[1]. This will throw away any existing deltas and re-compute them, at the expense of spending much more time on the repacking.

The effects of this are mostly persistent, e.g. when packs and loose objects are coalesced into one another pack the existing deltas in that pack might get re-used, but there are also various cases where we might pick a sub-optimal delta from a newer pack instead.

Furthermore, supplying —aggressive will tweak the —depth and —window options passed to git-repack[1]. See the gc.aggressiveDepth and gc.aggressiveWindow settings below. By using a larger window size we’re more likely to find more optimal deltas.

It’s probably not worth it to use this option on a given repository without running tailored performance benchmarks on it. It takes a lot more time, and the resulting space/delta optimization may or may not be worth it. Not using this at all is the right trade-off for most users and their repositories.

CONFIGURATION

Everything below this line in this section is selectively included from the git-config[1] documentation. The content is the same as what’s found there:

gc.aggressiveDepth

The depth parameter used in the delta compression algorithm used by git gc —aggressive. This defaults to 50, which is the default for the —depth option when —aggressive isn’t in use.

See the documentation for the —depth option in git-repack[1] for more details.

gc.aggressiveWindow

The window size parameter used in the delta compression algorithm used by git gc —aggressive. This defaults to 250, which is a much more aggressive window size than the default —window of 10.

See the documentation for the —window option in git-repack[1] for more details.

When there are approximately more than this many loose objects in the repository, git gc —auto will pack them. Some Porcelain commands use this command to perform a light-weight garbage collection from time to time. The default value is 6700.

Setting this to 0 disables not only automatic packing based on the number of loose objects, but also any other heuristic git gc —auto will otherwise use to determine if there’s work to do, such as gc.autoPackLimit .

gc.autoPackLimit

When there are more than this many packs that are not marked with *.keep file in the repository, git gc —auto consolidates them into one larger pack. The default value is 50. Setting this to 0 disables it. Setting gc.auto to 0 will also disable this.

See the gc.bigPackThreshold configuration variable below. When in use, it’ll affect how the auto pack limit works.

gc.autoDetach

Make git gc —auto return immediately and run in the background if the system supports it. Default is true.

If non-zero, all non-cruft packs larger than this limit are kept when git gc is run. This is very similar to —keep-largest-pack except that all non-cruft packs that meet the threshold are kept, not just the largest pack. Defaults to zero. Common unit suffixes of k, m, or g are supported.

Note that if the number of kept packs is more than gc.autoPackLimit, this configuration variable is ignored, all packs except the base pack will be repacked. After this the number of packs should go below gc.autoPackLimit and gc.bigPackThreshold should be respected again.

If the amount of memory estimated for git repack to run smoothly is not available and gc.bigPackThreshold is not set, the largest pack will also be excluded (this is the equivalent of running git gc with —keep-largest-pack ).

gc.writeCommitGraph

If true, then gc will rewrite the commit-graph file when git-gc[1] is run. When using git gc —auto the commit-graph will be updated if housekeeping is required. Default is true. See git-commit-graph[1] for details.

If the file gc.log exists, then git gc —auto will print its content and exit with status zero instead of running unless that file is more than gc.logExpiry old. Default is «1.day». See gc.pruneExpire for more ways to specify its value.

Running git pack-refs in a repository renders it unclonable by Git versions prior to 1.5.1.2 over dumb transports such as HTTP. This variable determines whether git gc runs git pack-refs . This can be set to notbare to enable it within all non-bare repos or it can be set to a boolean value. The default is true .

Store unreachable objects in a cruft pack (see git-repack[1]) instead of as loose objects. The default is true .

Limit the size of new cruft packs when repacking. When specified in addition to —max-cruft-size , the command line option takes priority. See the —max-cruft-size option of git-repack[1].

When git gc is run, it will call prune —expire 2.weeks.ago (and repack —cruft —cruft-expiration 2.weeks.ago if using cruft packs via gc.cruftPacks or —cruft ). Override the grace period with this config variable. The value «now» may be used to disable this grace period and always prune unreachable objects immediately, or «never» may be used to suppress pruning. This feature helps prevent corruption when git gc runs concurrently with another process writing to the repository; see the «NOTES» section of git-gc[1].

When git gc is run, it calls git worktree prune —expire 3.months.ago. This config variable can be used to set a different grace period. The value «now» may be used to disable the grace period and prune $GIT_DIR/worktrees immediately, or «never» may be used to suppress pruning.

git reflog expire removes reflog entries older than this time; defaults to 90 days. The value «now» expires all entries immediately, and «never» suppresses expiration altogether. With «» (e.g. «refs/stash») in the middle the setting applies only to the refs that match the .

git reflog expire removes reflog entries older than this time and are not reachable from the current tip; defaults to 30 days. The value «now» expires all entries immediately, and «never» suppresses expiration altogether. With «» (e.g. «refs/stash») in the middle, the setting applies only to the refs that match the .

These types of entries are generally created as a result of using git commit —amend or git rebase and are the commits prior to the amend or rebase occurring. Since these changes are not part of the current project most users will want to expire them sooner, which is why the default is more aggressive than gc.reflogExpire .

gc.recentObjectsHook

When considering whether or not to remove an object (either when generating a cruft pack or storing unreachable objects as loose), use the shell to execute the specified command(s). Interpret their output as object IDs which Git will consider as «recent», regardless of their age. By treating their mtimes as «now», any objects (and their descendants) mentioned in the output will be kept regardless of their true age.

Output must contain exactly one hex object ID per line, and nothing else. Objects which cannot be found in the repository are ignored. Multiple hooks are supported, but all must exit successfully, else the operation (either generating a cruft pack or unpacking unreachable objects) will be halted.

gc.repackFilter

When repacking, use the specified filter to move certain objects into a separate packfile. See the —filter= option of git-repack[1].

When repacking and using a filter, see gc.repackFilter , the specified location will be used to create the packfile containing the filtered out objects. WARNING: The specified location should be accessible, using for example the Git alternates mechanism, otherwise the repo could be considered corrupt by Git as it migh not be able to access the objects in that packfile. See the —filter-to= option of git-repack[1] and the objects/info/alternates section of gitrepository-layout[5].

Records of conflicted merge you resolved earlier are kept for this many days when git rerere gc is run. You can also use more human-readable «1.month.ago», etc. The default is 60 days. See git-rerere[1].

Records of conflicted merge you have not resolved are kept for this many days when git rerere gc is run. You can also use more human-readable «1.month.ago», etc. The default is 15 days. See git-rerere[1].

NOTES

git gc tries very hard not to delete objects that are referenced anywhere in your repository. In particular, it will keep not only objects referenced by your current set of branches and tags, but also objects referenced by the index, remote-tracking branches, reflogs (which may reference commits in branches that were later amended or rewound), and anything else in the refs/* namespace. Note that a note (of the kind created by git notes) attached to an object does not contribute in keeping the object alive. If you are expecting some objects to be deleted and they aren’t, check all of those locations and decide whether it makes sense in your case to remove those references.

On the other hand, when git gc runs concurrently with another process, there is a risk of it deleting an object that the other process is using but hasn’t created a reference to. This may just cause the other process to fail or may corrupt the repository if the other process later adds a reference to the deleted object. Git has two features that significantly mitigate this problem:

  1. Any object with modification time newer than the —prune date is kept, along with everything reachable from it.
  2. Most operations that add an object to the database update the modification time of the object if it is already present so that #1 applies.

However, these features fall short of a complete solution, so users who run commands concurrently have to live with some risk of corruption (which seems to be low in practice).

HOOKS

The git gc —auto command will run the pre-auto-gc hook. See githooks[5] for more information.

A3.11 Приложение C: Команды Git — Администрирование

Если вы администрируете Git репозиторий или вам нужно исправить что-либо, Git предоставляет несколько административных команд вам в помощь.

git gc

Команда git gc запускает сборщик мусора в вашем репозитории, который удаляет ненужные файлы из хранилища объектов и эффективно упаковывает оставшиеся файлы.

Обычно, эта команда выполняется автоматически без вашего участия, но, если пожелаете, можете вызвать её вручную. Мы рассмотрели некоторые примеры её использования в разделе Обслуживание репозитория главы 10.

git fsck

Команда git fsck используется для проверки внутренней базы данных на предмет наличия ошибок и несоответствий.

Мы лишь однажды использовали её в разделе Восстановление данных главы 10 для поиска более недостижимых (dangling) объектов.

git reflog

Команда git reflog просматривает историю изменения голов веток на протяжении вашей работы для поиска коммитов, которые вы могли внезапно потерять, переписывая историю.

В основном, мы рассматривали эту команду в разделе RefLog-сокращения главы 7, где мы показали пример использования этой команды, а также как использовать git log -g для просмотра той же информации, используя git log .

Мы на практике рассмотрели восстановление потерянной ветки в разделе Восстановление данных главы 10.

git filter-branch

Команда git filter-branch используется для переписывания содержимого коммитов по заданному алгоритму, например, для полного удаления файла из истории или для вычленения истории лишь части файлов в проекте для вынесения в отдельный репозиторий.

В разделе Удаление файла из каждого коммита главы 7 мы объяснили механизм работы этой команды и рассказали про использование опций —commit-filter , —subdirectory-filter и —tree-filter .

10.4 Git изнутри — Pack-файлы

Если вы следовали всем инструкциям из примеров предыдущего раздела, то теперь ваш тестовый репозиторий должен содержать 11 объектов: 4 блоба, 3 дерева, 3 коммита и один тег:

$ find .git/objects -type f .git/objects/01/55eb4229851634a0f03eb265b69f5a2d56f341 # tree 2 .git/objects/1a/410efbd13591db07496601ebc7a059dd55cfe9 # commit 3 .git/objects/1f/7a7a472abf3dd9643fd615f6da379c4acb3e3a # test.txt v2 .git/objects/3c/4e9cd789d88d8d89c1073707c3585e41b0e614 # tree 3 .git/objects/83/baae61804e65cc73a7201a7252750c76066a30 # test.txt v1 .git/objects/95/85191f37f7b0fb9444f35a9bf50de191beadc2 # tag .git/objects/ca/c0cab538b970a37ea1e769cbbde608743bc96d # commit 2 .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 # 'test content' .git/objects/d8/329fc1cc938780ffdd9f94e0d364e0ea74f579 # tree 1 .git/objects/fa/49b077972391ad58037050f2a75f74e3671e92 # new.txt .git/objects/fd/f4fc3344e67ab068f836878b6c4951e3b15f3d # commit 1

Git использует zlib для сжатия содержимого этих файлов; к тому же у нас не так много данных, поэтому все эти файлы вместе занимают всего 925 байт. Для того, чтобы продемонстрировать одну интересную особенность Git, добавим файл побольше. Добавим файл repo.rb из библиотеки Grit — он занимает примерно 22 Кб:

$ curl https://raw.githubusercontent.com/mojombo/grit/master/lib/grit/repo.rb > repo.rb $ git checkout master $ git add repo.rb $ git commit -m 'Create repo.rb' [master 484a592] Create repo.rb 3 files changed, 709 insertions(+), 2 deletions(-) delete mode 100644 bak/test.txt create mode 100644 repo.rb rewrite test.txt (100%)

Если посмотреть на полученное дерево, мы увидим значение SHA-1 блоба для файла repo.rb :

$ git cat-file -p master^ 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt 100644 blob 033b4468fa6b2a9547a70d88d1bbe8bf3f9ed0d5 repo.rb 100644 blob e3f094f522629ae358806b17daf78246c27c007b test.txt

Посмотрим, сколько этот объект занимает места на диске, используя git cat-file :

$ git cat-file -s 033b4468fa6b2a9547a70d88d1bbe8bf3f9ed0d5 22044

Теперь немного изменим этот файл и посмотрим на результат:

$ echo '# testing' >> repo.rb $ git commit -am 'Modify repo.rb a bit' [master 2431da6] Modify repo.rb a bit 1 file changed, 1 insertion(+)

Взглянув на дерево, полученное в результате коммита, мы увидим любопытную вещь:

$ git cat-file -p master^ 100644 blob fa49b077972391ad58037050f2a75f74e3671e92 new.txt 100644 blob b042a60ef7dff760008df33cee372b945b6e884e repo.rb 100644 blob e3f094f522629ae358806b17daf78246c27c007b test.txt

Теперь файлу repo.rb соответствует совершенно другой блоб; это означает, что после добавления всего одной единственной строки в конец 400-строчного файла, Git сохранит новый контент в отдельный объект:

$ git cat-file -s b042a60ef7dff760008df33cee372b945b6e884e 22054

Итак, мы имеем два практически одинаковых объекта, занимающих по 22 Кб на диске (в сжатом виде — приблизительно 7 Кб каждый). Было бы здорово, если бы Git сохранял только один объект целиком, а другой как разницу между ним и первым объектом.

Оказывается, Git так и делает. Первоначальный формат для сохранения объектов в Git называется «рыхлым» форматом (loose format). Однако, время от времени Git упаковывает несколько таких объектов в один pack-файл для сохранения места на диске и повышения эффективности. Это происходит, когда «рыхлых» объектов становится слишком много, а также при ручном вызове git gc или отправке изменений на удалённый сервер. Чтобы посмотреть, как происходит упаковка, можно выполнить команду git gc :

$ git gc Counting objects: 18, done. Delta compression using up to 8 threads. Compressing objects: 100% (14/14), done. Writing objects: 100% (18/18), done. Total 18 (delta 3), reused 0 (delta 0)

Если заглянуть в каталог с объектами, то можно обнаружить, что большинство объектов исчезло, зато появились два новых файла:

$ find .git/objects -type f .git/objects/bd/9dbf5aae1a3862dd1526723246b20206e5fc37 .git/objects/d6/70460b4b4aece5915caf5c68d12f560a9fe3e4 .git/objects/info/packs .git/objects/pack/pack-978e03944f5c581011e6998cd0e9e30000905586.idx .git/objects/pack/pack-978e03944f5c581011e6998cd0e9e30000905586.pack

Оставшиеся объекты — это блобы, на которые не указывает ни один коммит; в нашем случае это созданные ранее объекты, содержащие строки «what is up, doc?» и «test content». В силу того, что ни в одном коммите данные файлы не присутствуют, они считаются «висячими» и в pack-файл не включаются.

Остальные файлы — это pack-файл и его индекс. Pack-файл — это файл, в котором теперь находится содержимое всех удалённых объектов. Индекс — это файл, в котором записаны смещения для быстрого доступа к содержимому прежних объектов. Упаковка данных положительно повлияла на общий размер файлов: если до вызова команды gc в сжатом виде они занимали примерно 15 Кб, то pack-файл занимает всего 7 Кб. За счёт упаковки объектов мы только что освободили как минимум половину занимаемого дискового пространства!

Как Git это делает? При упаковке Git ищет похожие по имени и размеру файлы и сохраняет только разницу между соседними версиями. Можно заглянуть в pack-файл чтобы понять, какие действия выполняются при сжатии. Для просмотра содержимого упакованного файла существует служебная команда git verify-pack :

$ git verify-pack -v .git/objects/pack/pack-978e03944f5c581011e6998cd0e9e30000905586.idx 2431da676938450a4d72e260db3bf7b0f587bbc1 commit 223 155 12 69bcdaff5328278ab1c0812ce0e07fa7d26a96d7 commit 214 152 167 80d02664cb23ed55b226516648c7ad5d0a3deb90 commit 214 145 319 43168a18b7613d1281e5560855a83eb8fde3d687 commit 213 146 464 092917823486a802e94d727c820a9024e14a1fc2 commit 214 146 610 702470739ce72005e2edff522fde85d52a65df9b commit 165 118 756 d368d0ac0678cbe6cce505be58126d3526706e54 tag 130 122 874 fe879577cb8cffcdf25441725141e310dd7d239b tree 136 136 996 d8329fc1cc938780ffdd9f94e0d364e0ea74f579 tree 36 46 1132 deef2e1b793907545e50a2ea2ddb5ba6c58c4506 tree 136 136 1178 d982c7cb2c2a972ee391a85da481fc1f9127a01d tree 6 17 1314 1 \ deef2e1b793907545e50a2ea2ddb5ba6c58c4506 3c4e9cd789d88d8d89c1073707c3585e41b0e614 tree 8 19 1331 1 \ deef2e1b793907545e50a2ea2ddb5ba6c58c4506 0155eb4229851634a0f03eb265b69f5a2d56f341 tree 71 76 1350 83baae61804e65cc73a7201a7252750c76066a30 blob 10 19 1426 fa49b077972391ad58037050f2a75f74e3671e92 blob 9 18 1445 b042a60ef7dff760008df33cee372b945b6e884e blob 22054 5799 1463 033b4468fa6b2a9547a70d88d1bbe8bf3f9ed0d5 blob 9 20 7262 1 \ b042a60ef7dff760008df33cee372b945b6e884e 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a blob 10 19 7282 non delta: 15 objects chain length = 1: 3 objects .git/objects/pack/pack-978e03944f5c581011e6998cd0e9e30000905586.pack: ok

Здесь блоб 033b4 , который, как мы помним, был первой версией файла repo.rb , ссылается на блоб b042a , который хранит вторую его версию. Третья колонка в выводе — это размер содержимого объекта в pack-файле; как видите, b042a занимает 22 Кб, а 033b4 — всего 9 байт. Что интересно, вторая версия файла сохраняется «как есть», а первая — в виде дельты: ведь скорее всего вам понадобится быстрый доступ к самым последним версиям файла.

Также здорово, что переупаковку можно выполнять в любое время. Время от времени Git будет выполнять её автоматически, чтобы сэкономить место на диске, но всегда можно инициировать упаковку вручную используя git gc .

Git gc что это

На больших репоозиториях, git зависит от способа сжатия информации истории, чтобы не занимать много дискового пространства или памяти.

Это сжатие не выполнятеся автоматически. Поэтому вы должны иногда выполнять git gc:

$ git gc 

чтобы заново сжать архив. Это может занять длительное время, так что вы возможно предпочтете выполнять git-gc тогда когда не заняты чем то другим.

Обеспечение достоверности

Команда git fsck выполняет некоторое количество проверок целостности репозитория, и составляет отчет если будут найдены какие либо проблемы. Это возможно займет некоторое время. Наиболее общее предупреждение в значительной степени будут о подвешенных объектах:

$ git fsck dangling commit 7281251ddd2a61e38657c827739c57015671a6b3 dangling commit 2706a059f258c6b245f298dc4ff2ccd30ec21a63 dangling commit 13472b7c4b80851a1bc551779171dcb03655e9b5 dangling blob 218761f9d90712d37a9c5e36f406f92202db07eb dangling commit bf093535a34a4d35731aa2bd90fe6b176302f14f dangling commit 8e4bec7f2ddaa268bef999853c25755452100f8e dangling tree d50bb86186bf27b681d25af89d3b5b68382e4085 dangling tree b24c2473f1fd3d91352a624795be026d64c8841f . 

Подвешенные объекты это не проблема. Самое худшее что они могут сделать это просто занять немного дополнительного дискового пространства. Иногда они могут быть вашим последним способом восстановить потерянную работу.

This book is maintained by Scott Chacon, and hosting is donated by GitHub.
Please email me at schacon@gmail.com with patches, suggestions and comments.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *