Tagged: linux

Automating Git Branch Cleanup with an Alias: A Practical Guide

Automating Git Branch Cleanup with an Alias: A Practical Guide

Working with Git often involves managing multiple local and remote branches. Over time, remote branches may be deleted, leaving behind obsolete local branches. To simplify the cleanup process, you can create a Git alias that automates this task. In this article, we’ll show you how to set up this alias and discuss its pros and cons.

Creating a Git Alias to Clean Up Local Branches

Here’s the command to create a Git alias named prune-all that automatically cleans up obsolete local branches:

git config --global alias.prune-all '!git fetch --prune && git branch -vv | grep ": gone]" | sed "s/^[[:space:]]*\([^[:space:]]*\).*/\1/" | xargs -r git branch -d'

Once this alias is set up, you can simply run:

git prune-all

This command will:

  1. Update local references and remove deleted remote branches (git fetch --prune).
  2. Identify local branches that no longer have a corresponding remote branch (git branch -vv | grep ": gone]").
  3. Extract the names of these branches (sed).
  4. Delete the local branches (xargs -r git branch -d).

Why Use This Alias?

This alias offers several advantages:

  • Time-saving: No need to manually run multiple commands to clean up local branches.
  • Automation: The process is fully automated, reducing human error.
  • Repository Cleanliness: Keeps your local repository clean and in sync with the remote repository.

Precautions to Take

While this alias is very useful, it’s important to understand its limitations and potential risks:

  • Using git branch -d: The alias uses git branch -d to delete local branches. This means Git will refuse to delete a branch if it contains unmerged commits. This is a safety measure to prevent losing work.
  • Risk of Accidental Deletion: If you use git branch -D (with an uppercase D) instead of -d, branches will be force-deleted, even if they contain unmerged commits. Be cautious if you modify the alias to use -D.
  • Manual Verification: Before running the alias, it may be helpful to check which branches will be deleted by running:
git fetch --prune && git branch -vv | grep ": gone]"

When to Use This Alias?

This alias is particularly useful in the following scenarios:

  • You’re working on a project with many branches and want to keep your local repository clean.
  • You’re collaborating with a team, and remote branches are frequently deleted after merging.
  • You want to automate a repetitive task to save time.

Conclusion

Creating a Git alias to clean up local branches is an excellent way to automate a tedious task and keep your repository tidy. By using git branch -d, you add a layer of safety to avoid losing unmerged work. However, be aware of the risks if you decide to use git branch -D instead.

Feel free to try out this alias and adapt it to your needs. Happy branch management!

Have questions or suggestions? Leave a comment below!

Delete the oldest files from a folder as long as it exceeds a certain size


Samples

Note that you have to launch using “source

  • Delete the oldest files in the current folder (./) as long as it takes up more than 96MB:
    source ./clean_custom.sh --path ./ -l 9600000
  • Delete older files from temporary folder (/tmp/) as long as it takes more than 2GB:
    source ./clean_custom.sh --path /tmp/ -l 2000000000

Script source code

#!/usr/bin/env bash                                                              
PATH_TO_CLEAN=                                                                   
NUMBER_FILES_TO_DELETE_EACH_LOOP=1                                               
SIZE_LIMIT=2000000000                                                            
                                                                                 
# ----------------------------------------------------------------------------   
# usage:                                                                         
usage()                                                                          
{                                                                                
    echo "Clean directory: while size of a dir > limit, oldest files first."
    echo "Usage: ${filename} [-p|--path path] [-s|--max-size size] | [-h]"
    echo "    -p|--path: path to clean"            
    echo "    -l|--limit: max size for the folder (must be > 0)"
    echo "    -h|--help this help"                 
}                                                                                
                                                                                 
# ----------------------------------------------------------------------------   
# handling arguments:                                                            
args=("$@")                                                            
filename=$(basename -- "$0" | sed 's/\(.*\)\..*/\1/')        
while [ "$1" != "" ]; do                                     
    case $1 in                                               
        -p | --path ) shift              
                      # stop if path doesn't exist:
                      if [ ! -d "$1" ]; then
                          echo "Path not found: '$1'"
                          usage
                          return 1
                      fi
                      PATH_TO_CLEAN=$1
                      ;;
        -l | --limit ) shift             
                       SIZE_LIMIT=$(echo $1 | bc)
                       if [ $SIZE_LIMIT -le 0 ]
                       then
                           usage
                           return 1
                       fi
                       ;;
        -h | --help ) usage              
                      return
                      ;;
        * ) usage                        
            return 1 
    esac                                                     
    shift                                                    
done                                                                             
[ -z "$PATH_TO_CLEAN" ] && echo "Path empty" && usage && return 1
echo "Cleanin dir: '$PATH_TO_CLEAN', size limit=$SIZE_LIMIT" 
# ----------------------------------------------------------------------------   
# handling arguments:                                                            
while [ 1 ]                                                                      
do                                                                               
    s=$(du -sb $PATH_TO_CLEAN | cut -f1 | bc)                
    if [ $s -gt $SIZE_LIMIT ]                                
    then                                                     
        find $PATH_TO_CLEAN -type f -printf '%T+ %p\n' | \
            sort -nr | \
            tail -$NUMBER_FILES_TO_DELETE_EACH_LOOP | \
            cut -d' ' -f 2- | \
            xargs -I {} rm -f {}
    else                                                     
        break                            
    fi                                                                                                                                                                                                                                                      
done                                                                             
return 0

Python: compile and run multiple versions without collisions

You have to go find the source code for the Python version that you want.

Example, run an “old” Python 3.6, go here and take the one that we want.

Then get the source code and compile it:

mkdir ~/source ; cd ~/source
wget https://www.python.org/ftp/python/3.6.13/Python-3.6.13.tar.xz
tar xvf Python-3.6.13.tar.xz
cd ~/source/Python-3.6.13
./configure && make
sudo make altinstall

“Et voilà”!

~/source/Python-3.6.13$ python3.6
Python 3.6.13 (default, May 21 2021, 17:12:12) 
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>