bashgit-branchgitolitegit

Git get worktree for every branch in seperate folders - Bash


I need to write a bash script that copies our repository branches onto our local linux web server every hour.

We have a git remote repository (gitolite) with branches named "master" "testing" "feature-featurename" "hotfix-number" each one of these branches is supposed to have its worktree copied to /var/www/html/branchname

First of all: How do I get different worktrees copied into different folders? Second: How can I automate this process if the "feature-" and "hotfix-" branches constantly change names?

This has nothing to do with a git hook, this is supposed to be a script running on a different server which is triggered by a cron job.


Solution

  • Horrible few-liner:

    mkdir -p /var/www/html
    git clone --bare user@git-server:/your-repo.git && cd your-repo.git
    
    git for-each-ref --format='%(refname)' refs/heads/ | grep 'branch-pattern' | while read branchRef; do
      branchName=${branchRef#refs/heads/}
      git archive --format=tar --prefix="$branchName/" "$branchRef" | tar -C/var/www/html -x
    done
    

    Let's break it down:

    1. Make sure the target directory exists. Probably not necessary for you.
      mkdir -p /var/www/html

    2. Clone the git repository and enter the directory
      git clone --bare user@git-server:/your-repo.git

    3. List branches. This would be run from a cloned directory. Note that git branch is not used, as that can have surprising outputs when used in scripts.
      git for-each-ref --format='%(refname)' refs/heads/

    4. Filter for the branches you want. In your case the pattern would probably be something like grep -E "(master)|(testing)|(feature-.*)" etc.
      grep 'branch-pattern'

    5. The while statement reads each branch name and assigns it to the branch variable

    6. Create a branchName variable that is the name of the branch excluding the ref prefix. Note that this is bash-specific.
    7. git archive creates a tar archive of the selected branch, prefixing all entries with the branch name. The archive is sent to standard output
      git archive --format=tar --prefix="$branch/" "$branch"

    8. Immediately extract the archive to its target location
      tar -C/var/www/html -x