Git·30 questions

How to clean a local repository from garbage and unused files?

Answer

During active development, switching between branches, and experimenting with code, a large number of temporary files accumulate in the local repository. These can be compiled artifacts, build environment caches, test results, or files created by third-party programs that did not fall under the ignore rules in the gitignore file. Such garbage clutters the working directory and can interfere with the correct building of the project.

To quickly clean the working directory of all untracked files and folders, the git clean command is used. This utility deletes everything that is not under the control of the version control system. Since this is a destructive action, developers often use the dry-run flag -n to see in advance a list of files that will be permanently deleted.

To confirm the deletion of only untracked files, the combination of flags -f is used. If you need to delete untracked directories as well, the -d flag is added. The full command for a deep clean of the working area looks like git clean -fd. Be extremely careful with this command, as it will be impossible to restore files deleted this way through Git.

In addition to files in the working directory, over time, objects that have lost connection with branches and commits accumulate in the repository, for example, after history resets or deleting old branches. To clean the database of such dangling objects, the garbage collector git gc is used. This command optimizes the Git database, packs files, and removes unused junk, which helps reduce the project folder size on disk.

It is also useful to periodically clean local references to remote branches that have already been deleted on the server by colleagues. For this, the git remote prune origin command is used. It synchronizes the list of remote branches in your local cache, removing outdated pointers and keeping the repository structure up to date and clean.

Was this answer helpful?

More questions in this topic

Related questions from other topics